乐于分享
好东西不私藏

小学生Python进阶:做一个AI聊天助手

小学生Python进阶:做一个AI聊天助手

上节课我们学会了调用 AI 接口,但这只是「一问一答」——AI 每次都不记得之前说了什么。这节课,我们来做一个真正的 AI 聊天助手,让它记住完整的对话历史!

一、什么是多轮对话?

普通单轮对话 vs 多轮对话:

# ❌ 单轮对话(每次都从零开始)
ask("今天天气怎么样?")
ask("明天呢?")          # AI 不知道「明天」是指什么!

# ✅ 多轮对话(记住上下文)
messages = [
    {"role": "user",   "content": "今天天气怎么样?"},
    {"role": "assistant","content": "今天是晴天,25度。"},
    {"role": "user",   "content": "明天呢?"}   # AI 知道「明天」= 明天天气
]
# 这次 AI 能理解「明天」是指天气预报的延续!

二、核心原理:messages 列表

messages 列表就像「聊天记录本」,每轮对话只需要把之前的对话历史都放进去:

from zai import ZhipuAiClient

client = ZhipuAiClient(api_key="你的API Key")

# 第一轮
messages = [
    {"role": "user", "content": "我叫小明,今年10岁"}
]
response = client.chat.completions.create(
    model="glm-4.7-flash",
    messages=messages
)
ai_reply = response.choices[0].message.content
print("AI:", ai_reply)

# 把 AI 回复加入历史,继续第二轮
messages.append({"role": "assistant", "content": ai_reply})
messages.append({"role": "user", "content": "我叫什么名字?"})

response = client.chat.completions.create(
    model="glm-4.7-flash",
    messages=messages     # 把历史也一起发过去
)
print("AI:", response.choices[0].message.content)
AI: 很高兴认识你,小明!10岁正是学习编程的好年纪,加油!

AI: 你叫小明,今年10岁。

三、封装成聊天函数

直接用列表管理太麻烦,我们把它封装成一个好用的 ChatBot 类:

from zai import ZhipuAiClient

class AIChatbot:
    """AI 聊天机器人,可记住对话历史"""

    def __init__(self, api_key, model="glm-4.7-flash", system_prompt=None):
        self.client = ZhipuAiClient(api_key=api_key)
        self.model = model
        self.messages = []
        if system_prompt:
            self.messages.append({"role": "system", "content": system_prompt})

    def chat(self, user_message):
        """发送消息给 AI,返回回复"""
        self.messages.append({"role": "user", "content": user_message})

        response = self.client.chat.completions.create(
            model=self.model,
            messages=self.messages
        )

        ai_reply = response.choices[0].message.content
        self.messages.append({"role": "assistant", "content": ai_reply})
        return ai_reply

    def history(self):
        """查看对话历史"""
        for msg in self.messages:
            role = {"user":"用户","assistant":"AI","system":"系统"}[msg["role"]]
            print(f"{role}: {msg['content'][:50]}{'...' if len(msg['content']) > 50 else ''}")

    def clear(self):
        """清空历史,重新开始"""
        system_msg = self.messages[0] if self.messages and self.messages[0]["role"] == "system" else None
        self.messages = [system_msg] if system_msg else []

四、使用聊天机器人

# 1. 创建机器人(可以设定角色)
bot = AIChatbot(
    api_key="你的API Key",
    system_prompt="你是一个专门教小学生学 Python 的老师,语言生动有趣"
)

# 2. 开始聊天
print(bot.chat("Python 里的列表是什么?"))
print(bot.chat("和字典有什么区别?"))   # AI 能记住之前在聊「列表」!
print(bot.chat("给我一个例子"))           # 继续聊同一个话题
列表就像一个带编号的柜子,比如柜子第1格、第2格……
字典像一本词典,用「名字」找「内容」——比如 {"姓名":"小明","年龄":10}。

用列表的例子:fruits = ["苹果","香蕉","橙子"],可以用 fruits[0] 访问第一个水果!

五、自定义角色(System Prompt)

通过 system_prompt,你可以给 AI 设定不同的「人设」:

# 英语翻译助手
translator = AIChatbot(
    api_key="你的API Key",
    system_prompt="你是一个耐心的英语老师,擅长用简单的方式教小学生学英语"
)
print(translator.chat("苹果用英语怎么说?"))
print(translator.chat("那香蕉呢?"))

# 故事大王
storyteller = AIChatbot(
    api_key="你的API Key",
    system_prompt="你是一个专门给小朋友讲故事的讲故事人"
)
print(storyteller.chat("给我讲一个关于勇敢的小猫的故事"))
print(storyteller.chat("后来呢?"))    # 自动续上故事!

六、完整实战:命令行聊天程序

from zai import ZhipuAiClient

API_KEY = "你的API Key"

def main():
    print("=" * 40)
    print("  🦐 AI 聊天助手(输入 quit 退出)")
    print("=" * 40)

    bot = AIChatbot(
        api_key=API_KEY,
        system_prompt="你是一个友善的 AI 助手,喜欢用简单的语言回答问题"
    )

    while True:
        user_input = input("\n你: ")
        if user_input.lower() in ['quit', 'exit', '退出']:
            print("AI: 再见!有问题随时来找我 😊")
            break
        if user_input.strip() == '':
            continue
        try:
            reply = bot.chat(user_input)
            print(f"AI: {reply}")
        except Exception as e:
            print(f"出错了: {e}")

if __name__ == "__main__":
    main()
运行效果:

========================================
  🦐 AI 聊天助手(输入 quit 退出)
========================================

你: 你好!
AI: 你好!很高兴认识你!有什么我可以帮助你的吗?

你: 我叫小华
AI: 好的,小华!很高兴认识你!

你: 我叫什么名字?
AI: 你叫小华!

你: quit
AI: 再见!有问题随时来找我 😊

七、今天学到了什么?

  1. 多轮对话原理:把对话历史放进 messages 列表,AI 就能记住上下文
  2. ChatBot 类:封装成类,一行代码创建聊天助手
  3. system_prompt:设定 AI 的角色,让它变成翻译官、故事大王、数学老师……
  4. history():查看历史;clear():清空历史重新开始
  5. 实用工具:可以用 AI 做英语翻译、答疑解惑、辅助写作

八、下期预告

学会了聊天助手,下节课我们来做一个 AI 写作工具——输入关键词,AI 自动帮你写文章、写作文、起标题!

敬请期待:《小学生Python进阶:AI写作小助手》

有不明白的地方?欢迎留言告诉我!