使用 ChatCompletions API 產生回應
OpenAI ChatCompletions API 廣泛應用於生成式 AI 模型與平台。 雖然 Responses 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 模型生態系中已相當成熟,熟悉它會很有幫助。