如何用Python调用Open WebUI创建对话、发消息并获取回复?
解决Open WebUI Python API创建对话、发消息及获取回复问题
问题根源
- 创建对话时未指定模型,导致对话无关联模型,界面显示空白
- 发送消息的接口路径错误,原代码直接POST到对话详情接口而非消息添加接口
- 缺少触发模型生成回复的步骤,仅发送用户消息不会触发模型响应
修正后的完整代码
1. 导入依赖
import requests
2. 创建新对话函数(指定模型)
def create_new_chat(api_url, api_key, model_name): """创建带指定模型的新对话,返回对话ID""" headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' } payload = { 'chat': { 'model': model_name, 'name': 'API创建的对话' # 可选,自定义对话名称 } } response = requests.post(f'{api_url}/chats/new', json=payload, headers=headers) response.raise_for_status() # 主动抛出HTTP错误,便于调试 return response.json()['id']
3. 发送消息并获取模型回复函数
def send_message_and_get_reply(api_url, api_key, chat_id, message, model_name): """发送用户消息,触发模型回复并返回结果""" headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' } # 1. 添加用户消息到对话 message_payload = { 'message': { 'content': message, 'role': 'user' } } msg_response = requests.post(f'{api_url}/chats/{chat_id}/messages', json=message_payload, headers=headers) msg_response.raise_for_status() # 2. 触发模型生成回复 completion_payload = { 'model': model_name, 'stream': False # 若需流式回复可设为True,需对应修改接收逻辑 } comp_response = requests.post(f'{api_url}/chats/{chat_id}/completion', json=completion_payload, headers=headers) comp_response.raise_for_status() # 3. 获取对话中的模型回复 chat_detail = requests.get(f'{api_url}/chats/{chat_id}', headers=headers).json() # 倒序查找最新的assistant角色消息 for msg in reversed(chat_detail['messages']): if msg['role'] == 'assistant': return msg['content'] return "未获取到模型回复"
4. 使用示例
# 配置参数 API_URL = "https://your-openwebui-domain/api/v1" # 替换为你的Open WebUI API地址 API_KEY = "your-api-key" # 替换为你的API密钥 TARGET_MODEL = "gpt-3.5-turbo" # 替换为你要测试的模型名称 # 创建对话 chat_id = create_new_chat(API_URL, API_KEY, TARGET_MODEL) print(f"对话ID: {chat_id}") # 交互测试 user_input = "你好,请介绍下你自己" model_reply = send_message_and_get_reply(API_URL, API_KEY, chat_id, user_input, TARGET_MODEL) print(f"模型回复: {model_reply}")
关键说明
- 更换模型时,只需修改
TARGET_MODEL参数即可,无需改动核心逻辑 - 若需要流式接收回复,可将
stream设为True,并使用response.iter_lines()逐行处理返回内容 - 调用
raise_for_status()可以快速捕获API请求中的HTTP错误,避免静默失败
内容的提问来源于stack exchange,提问作者lelorrain7
相关产品推荐
相关产品推荐

