더북(TheBook)

ch01_chat_openai.py

from openai import OpenAI

client = OpenAI(
    api_key = "API_Key_입력"
)

# ➊ 대화 내역을 저장할 리스트 선언
message_history = []

# ➋ 대화 시작
while True:
    user_input = input("사용자: ")
    # ➌ 사용자의 질문을 리스트에 추가
    message_history.append({"role": "user", "content": user_input})
    # ➍ API 요청 및 응답 
    chat_completion = client.chat.completions.create(
        messages = message_history,
        model = "gpt-4o",
    )
    # ➎ 챗봇의 응답을 리스트에 추가
    assistant_response = chat_completion.choices[0].message.content
    message_history.append({"role": "assistant", "content": assistant_response})
    # ➏ 응답 결과 출력
    print(f"챗봇: {assistant_response}")
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.