Week2 day3 对话式 AI(聊天机器人) OpenAI API + Gradio
1. 环境准备
- 导入依赖库:
os、dotenv读取环境变量、openai调用大模型、gradio做网页聊天界面 - 从
.env文件读取OPENAI_API_KEY,初始化 OpenAI 客户端,指定模型gpt‑4.1‑mini system_message:设定大模型的角色系统提示词。
2. Gradio ChatInterface 回调函数 chat(message, history)
- 参数:
message:用户当前输入消息history:完整聊天历史记录
- 功能:接收用户消息 + 历史对话,组装消息传给大模型,返回模型回答,作为 Gradio 聊天界面的回调。
迭代 1:静态假回复
直接返回固定字符串,没有调用大模型,仅测试界面:
python
运行
def chat(message, history): return "bananas"
迭代 2:把用户输入和历史打印出来
只是把输入、历史拼接返回,依旧没有调用大模型,熟悉参数。
迭代 3:调用 OpenAI,完整一次性返回
- 把 Gradio 的 history 转换成 OpenAI 接口要求的
role/content格式 - 组装消息列表:系统提示词 + 历史对话 + 当前用户提问
- 调用
openai.chat.completions.create(),一次性拿到完整结果返回。
迭代 4:流式输出(重点)
增加
stream=True 开启流式传输,循环读取分片chunk,使用yield逐段把文字输出到前端,实现打字机效果。3. 业务场景:服装店导购机器人(One‑shot Prompt 一次性提示)
修改
system_message设定角色:服装店导购- 促销规则:帽子 4 折(60% off),其余大多商品 5 折;要委婉引导客户选购促销商品,给了回答示例,属于 one‑shot 提示。
- 追加规则:客户问鞋子 → 告知鞋子不打折,继续引导看帽子。
- 代码动态修改系统提示词:检测用户输入包含
belt(腰带),动态追加提示:本店不卖腰带,推荐其他促销商品。
关键点:不是固定写死 system_message,可以根据用户输入动态拼接系统提示,实现简单业务逻辑。
整体流程总览
- 加载密钥,初始化 OpenAI 客户端
- 定义
chat(message, history)回调:格式化历史 → 动态组装系统提示 → 调用流式 OpenAI 接口 → yield 分片输出回答 gr.ChatInterface直接把函数挂载,一键启动网页聊天界面。
核心知识点
- history 格式转换:Gradio 聊天历史需要转成 OpenAI 标准
[{"role":"xxx","content":"xxx"}]消息格式。 - stream 流式 + yield:实现打字机实时输出效果。
- One‑shot Prompt:系统提示词中直接给回答示例,引导模型输出风格。
- 动态 System Prompt:根据用户提问内容,运行时修改系统提示,实现简单业务分支判断。
- Gradio
ChatInterface快速搭建对话网页,不用写前端 HTML。
# Day 3 - Conversational AI - aka Chatbot! import os from dotenv import load_dotenv from openai import OpenAI import gradio as gr # 加载环境变量 .env 文件 load_dotenv(override=True) openai_api_key = os.getenv('OPENAI_API_KEY') if openai_api_key: print(f"OpenAI API Key exists and begins {openai_api_key[:8]}") else: print("OpenAI API Key not set") # 初始化 OpenAI 客户端 openai = OpenAI() MODEL = 'gpt-4.1-mini' # 系统提示词:服装店导购机器人 system_message = """You are a helpful assistant in a clothes store. You should try to gently encourage \ the customer to try items that are on sale. Hats are 60% off, and most other items are 50% off. \ For example, if the customer says 'I'm looking to buy a hat', \ you could reply something like, 'Wonderful - we have lots of hats - including several that are part of our sales event.'\ Encourage the customer to buy hats if they are unsure what to get.""" # 追加规则:鞋子不打折,提醒看帽子 system_message += "\nIf the customer asks for shoes, you should respond that shoes are not on sale today, \ but remind the customer to look at hats!" def chat(message, history): # 将gradio的history转为openai需要的消息格式 history = [{"role": h["role"], "content": h["content"]} for h in history] relevant_system_message = system_message # 如果用户提到belt腰带,动态追加系统提示 if 'belt' in message.lower(): relevant_system_message += " The store does not sell belts; if you are asked for belts, be sure to point out other items on sale." # 拼装完整消息列表:系统提示 + 历史对话 + 当前用户消息 messages = [{"role": "system", "content": relevant_system_message}] + history + [ {"role": "user", "content": message}] # 开启流式输出 stream=True stream = openai.chat.completions.create(model=MODEL, messages=messages, stream=True) response = "" for chunk in stream: response += chunk.choices[0].delta.content or '' yield response # 启动Gradio聊天网页界面 gr.ChatInterface(fn=chat, type="messages").launch()

浙公网安备 33010602011771号