构建用于编码的推理聊天机器人
现在把所学内容整合起来,构建一个用于代码辅助的推理聊天机器人!
我们提供了两条用户消息:第一条请求为特定任务编写 Python 代码,第二条是跟进消息,要求使用特定的库来实现。
V4-Pro 默认进行推理,因此您只需循环处理对话,并将正确的字段追加到历史记录中。
本练习是课程的一部分
在 Python 中使用 DeepSeek
练习说明
- 循环遍历用户问题。
- 将每个用户问题
q发送给deepseek-ai/DeepSeek-V4-Pro模型。 - 将助手的最终答案(
.content,而非推理过程)追加到messages,以保持对话历史精简。
交互式实操练习
通过完成这段示例代码来试试这个练习。
client = OpenAI(api_key="", base_url="https://api.together.xyz/v1")
messages = []
user_msgs = ["Write some Python code to generate a list of numbers from 1-10.", "Update the code to use the NumPy library."]
# Loop over the user questions
for q in ____:
print("User: ", q)
user_dict = {"role": "user", "content": q}
messages.append(user_dict)
# Create the API request — V4-Pro reasons by default
response = client.chat.completions.create(
model="deepseek-ai/____",
messages=____,
max_tokens=500
)
# Append only the final answer to the conversation history
assistant_dict = {"role": "assistant", "content": response.choices[0].message.____}
messages.append(assistant_dict)
print("Assistant: ", response.choices[0].message.content, "\n")