Files
2025-12-01 03:42:34 +08:00

130 lines
4.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import requests
import json
import time
from typing import Optional, Dict
# 基础配置
BASE_URL = "http://10.10.10.202:8088/v1"
API_KEY = "app-m7HZNV1aGiheh3wr6wNVHFxX" # 替换为实际的 API-Key
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
def send_chat_message(
query: str,
user: str,
response_mode: str = "streaming",
inputs: Dict = None,
conversation_id: Optional[str] = None
) -> tuple:
"""
发送对话消息到 API(修复scene_description必填问题)
"""
# 构造请求体:强制补充scene_description(必填)
payload = {
"query": query,
# 核心修复:inputs必须包含scene_description字段
"inputs": inputs or {"scene_description": "通用聊天场景"}, # 替换为实际业务场景描述
"response_mode": response_mode,
"user": user,
}
if conversation_id:
payload["conversation_id"] = conversation_id
url = f"{BASE_URL}/chat-messages"
full_response = ""
res_conversation_id = None
try:
if response_mode == "streaming":
response = requests.post(
url,
headers=HEADERS,
json=payload,
stream=True
)
response.raise_for_status()
for line in response.iter_lines():
if line:
line_data = line.decode("utf-8")
if line_data.startswith("data: "):
json_str = line_data[6:]
if json_str == "[DONE]":
break
try:
data = json.loads(json_str)
# 兼容不同的返回字段(优先取content/answer/message
if not res_conversation_id and "conversation_id" in data:
res_conversation_id = data["conversation_id"]
# 适配常见的回复字段名
chunk = ""
if "content" in data:
chunk = data["content"]
elif "answer" in data:
chunk = data["answer"]
elif "message" in data:
chunk = data["message"]
if chunk:
full_response += chunk
print(chunk, end="", flush=True)
except json.JSONDecodeError:
continue
print()
else:
response = requests.post(
url,
headers=HEADERS,
json=payload
)
response.raise_for_status()
data = response.json()
res_conversation_id = data.get("conversation_id")
# 兼容不同返回字段
full_response = data.get("content", data.get("answer", data.get("message", "")))
print("完整回复:", full_response)
return res_conversation_id, full_response
except requests.exceptions.RequestException as e:
print(f"请求错误: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f"错误响应内容: {e.response.text}")
return None, ""
# ------------------- 示例调用 -------------------
if __name__ == "__main__":
# 自定义inputs(必须包含scene_description
custom_inputs = {
"scene_description": "电商客服场景,用户咨询商品售后问题", # 必填!根据实际场景修改
# 可添加其他自定义变量(如果有)
# "product_id": "123456",
# "user_level": "VIP"
}
# 1. 首次对话
print("=== 首次对话 ===")
conv_id, reply = send_chat_message(
query="请问这个商品支持7天无理由退货吗?",
user="user_123456",
response_mode="streaming",
inputs=custom_inputs # 传入包含scene_description的inputs
)
print(f"\n会话ID: {conv_id}")
print(f"最终回复: {reply}\n")
# 2. 续聊(复用conversation_id
if conv_id:
print("=== 续聊 ===")
send_chat_message(
query="退货的运费是由你们承担吗?",
user="user_123456",
response_mode="streaming",
inputs=custom_inputs,
conversation_id=conv_id
)