用Python从零搭建一个AI聊天机器人
AI · python · 技术

用Python从零搭建一个AI聊天机器人

用Python从零搭建AI聊天机器人

不需要框架,200行Python代码搭建一个完整的AI聊天机器人。

准备工作

pip install openai  # 兼容OpenAI格式的API

最简版本

from openai import OpenAI

client = OpenAI(
    api_key="your-api-key",
    base_url="https://api.deepseek.com/v1"  # 用DeepSeek更便宜
)

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {"role": "system", "content": "你是一个友好的助手"},
        {"role": "user", "content": "你好"}
    ]
)
print(response.choices[0].message.content)

加上多轮对话

class ChatBot:
    def __init__(self, system_prompt="你是一个友好的助手"):
        self.client = OpenAI(api_key="your-key", base_url="https://api.deepseek.com/v1")
        self.history = [{"role": "system", "content": system_prompt}]

    def chat(self, user_input):
        self.history.append({"role": "user", "content": user_input})
        response = self.client.chat.completions.create(
            model="deepseek-chat",
            messages=self.history,
            temperature=0.7
        )
        reply = response.choices[0].message.content
        self.history.append({"role": "assistant", "content": reply})
        return reply

    def reset(self):
        system = self.history[0]
        self.history = [system]

bot = ChatBot("你是一个Python编程助手")
print(bot.chat("怎么读取文件?"))
print(bot.chat("能给个例子吗?"))  # 它记得上文

加上流式输出

def chat_stream(self, user_input):
    self.history.append({"role": "user", "content": user_input})
    stream = self.client.chat.completions.create(
        model="deepseek-chat",
        messages=self.history,
        stream=True
    )
    full_reply = ""
    for chunk in stream:
        if chunk.choices[0].delta.content:
            text = chunk.choices[0].delta.content
            print(text, end="", flush=True)
            full_reply += text
    print()
    self.history.append({"role": "assistant", "content": full_reply})

加上命令行界面

def main():
    bot = ChatBot("你是一个技术博客助手,帮助用户解决编程问题")
    print("AI助手已启动(输入quit退出,reset重置)")
    while True:
        user_input = input("\n你: ").strip()
        if user_input.lower() == "quit":
            break
        if user_input.lower() == "reset":
            bot.reset()
            print("对话已重置")
            continue
        print("\nAI: ", end="")
        bot.chat_stream(user_input)

if __name__ == "__main__":
    main()

进阶方向

  1. 加Web界面:用Gradio或Streamlit
  2. 加RAG:接入向量数据库
  3. 加工具调用:Function Calling
  4. 加记忆持久化:存到数据库
  5. 加多用户支持:FastAPI + WebSocket

200行代码就能跑起来一个能用的AI聊天机器人。AI开发的门槛比想象的低。