Menu
CoddyTech

带记忆的聊天

本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 20 课,共 22 课。

challenge icon

挑战

中等

构建一个能记住对话内容的聊天循环。每一行输入都是用户说的一句话,直到输入行为 quit 为止。

  1. 维护一个 messages 列表。对于每一行,将其作为用户轮次追加,并传入 system=SYSTEM、model="claude-opus-5-5" 和 max_tokens=200 发送整个列表。
  2. 打印 Echo: 和回复文本(通过类型查找文本块),然后将该回复作为助手轮次追加到 messages 中,以便下一次调用带上它。
  3. 当输入行为 quit 时,停止运行而不调用模型,并打印 Turns: <number of replies>,然后打印 Input tokens: <total>:即每次调用的 usage.input_tokens 的总和。

输入 token 数在每一轮都会增加,因为每次调用都会再次发送整个历史记录:这就是长对话的成本所在。替代库对陈述句没有什么可说的,因此它会回答 I'm not sure about that.;而真实模型会礼貌地回复。例如,对于以下输入:

My city is Oslo.
What is my city?
quit

程序将输出:

Echo: I'm not sure about that.
Echo: Your city is Oslo.
Turns: 2
Input tokens: 77

亲手试试

import coddy_ai as anthropic  # 在生产环境中:import anthropic

client = anthropic.Anthropic()

SYSTEM = "You are Echo, a friendly assistant. Answer in one sentence."

# 在下方编写你的代码

在代码中调用模型中的所有课

自己练习: Python 在线编译器