开始使用免费开始使用

创建一个 AI 聊天机器人

为完成您的 POC,您将把消息历史与一个 for 循环集成,这样就能向模型连续发送多次提示,并将每次响应依次存入消息历史中。

本练习是课程的一部分

使用 OpenAI API

查看课程

练习说明

  • 遍历用户消息(user_msgs)。
  • 在每次迭代中为用户消息创建一个字典,并将其追加到 messages
  • 在一次聊天请求中将 messages 发送给模型。
  • 将助手消息的字典追加到 messages

交互式实操练习

通过完成这段示例代码来试试这个练习。

client = OpenAI(api_key="")

messages = [{"role": "system", "content": "You are a helpful math tutor that speaks concisely."}]
user_msgs = ["Explain what pi is.", "Summarize this in two bullet points."]

# Loop over the user questions
for q in ____:
    print("User: ", q)
    
    # Create a dictionary for the user message from q and append to messages
    user_dict = {"role": ____, "content": ____}
    messages.append(____)
    
    # Create the API request
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        ____,
        max_completion_tokens=100
    )
    
    # Append the assistant's message to messages
    assistant_dict = {"role": "assistant", "content": response.choices[0].message.content}
    messages.append(____)
    print("Assistant: ", response.choices[0].message.content, "\n")
编辑并运行代码