ChatCompletions API를 사용하여 응답 생성

완료됨

OpenAI ChatCompletions API는 일반적으로 생성 AI 모델 및 플랫폼에서 사용됩니다. 응답 API는 새 프로젝트 개발에 권장되지만 ChatCompletions API가 플랫폼 간 호환성의 코드 유지 관리에 유용한 시나리오가 발생할 수 있습니다.

프롬프트 제출

ChatCompletions API는 JSON 형식의 메시지 개체 컬렉션을 사용하여 프롬프트를 캡슐화합니다.

completion = openai_client.chat.completions.create(
    model="gpt-4o",  # Your model deployment name
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "When was Microsoft founded?"}
    ]
)

print(completion.choices[0].message.content)

대화형 컨텍스트 유지

응답 API와 달리 ChatCompletins API는 상태 저장 응답 추적 기능을 제공하지 않습니다. 대화형 컨텍스트를 유지하려면 이전 프롬프트 및 응답을 수동으로 추적하는 코드를 작성해야 합니다.

# Initial messages
conversation_messages=[
    {
        "role": "system",
        "content": "You are a helpful AI assistant that answers questions and provides information."
    }
]

# Add the first user message
conversation_messages.append(
    {"role": "user",
    "content": "When was Microsoft founded?"}
)

# Get a completion
completion = openai_client.chat.completions.create(
    model="gpt-4o",
    messages=conversation_messages
)
assistant_message = completion.choices[0].message.content
print("Assistant:", assistant_text)

# Append the response to the conversation
conversation_messages.append(
    {"role": "assistant", "content": assistant_text}
)

# Add the next user message
conversation_messages.append(
    {"role": "user",
    "content": "Who founded it?"}
)

# Get a completion
completion = openai_client.chat.completions.create(
    model="gpt-4o",
    messages=conversation_messages
)
assistant_message = completion.choices[0].message.content
print("Assistant:", assistant_text)

# and so on...

실제 애플리케이션에서 대화는 루프에서 구현될 가능성이 높습니다. 이런 식으로:

# Initial messages
conversation_messages=[
    {
        "role": "system",
        "content": "You are a helpful AI assistant that answers questions and provides information."
    }
]

# Loop until the user wants to quit
print("Assistant: Enter a prompt (or type 'quit' to exit)")
while True:
    input_text = input('\nYou: ')
    if input_text.lower() == "quit":
        print("Assistant: Goodbye!")
        break

    # Add the user message
    conversation_messages.append(
        {"role": "user",
        "content": input_text}
    )

    # Get a completion
    completion = openai_client.chat.completions.create(
        model="gpt-4o",
        messages=conversation_messages
    )
    assistant_message = completion.choices[0].message.content
    print("\nAssistant:", assistant_message)
    
    # Append the response to the conversation
    conversation_messages.append(
        {"role": "assistant", "content": assistant_message}
    )

이 예제의 출력은 다음과 유사합니다.

Assistant: Enter a prompt (or type 'quit' to exit)

You: When was Microsoft founded?

Assistant: Microsoft was founded on April 4, 1975 in Albuquerque, New Mexico, USA.

You: Who founded it?

Assistant: Microsoft was founded by Bill Gates and Paul Allen.

You: quit

Assistant: Goodbye!

각 새 사용자 프롬프트 및 완료가 대화에 추가되고 전체 대화 기록이 각 턴에 제출됩니다.

응답 API만큼 완벽하게 기능하지는 않지만, ChatCompletions API는 생성 AI 모델 에코시스템에서 잘 설정되므로 잘 알고 있으면 유용합니다.