代码如下,这是基于之前帖子里发的直接改的,来个大佬帮忙看一下
import requests
定义headers,使用提供的KEY
headers = {
‘accept’: ‘application/json’,
‘AUTHORIZATION’: ‘application-98d838cbd407975270f40fc9cfc2666e’ # 使用提供的api key
}
基础URL
BASE_URL = ‘http://localhost:8080/chat/api’
直接使用提供的profile id(已正确设置)
PROFILE_ID = ‘01984f42-2c25-77f2-a8b3-178787aa485a’
获取 chat id
def get_chat_id(profile_id):
# 使用传入的profile_id参数构建URL
chat_open_url = f’{BASE_URL}/{profile_id}/chat/open’
try:
response = requests.get(chat_open_url, headers=headers)
print(f"获取chat响应状态码: {response.status_code}“)
print(f"获取chat响应内容: {response.text}”)
if response.status_code == 200:
return response.json()['data']
else:
print(f"获取chat id失败,状态码: {response.status_code}")
return None
except Exception as e:
print(f"获取chat id时发生错误: {str(e)}")
return None
发送聊天消息
def send_chat_message(chat_id, payload):
# 使用预设的PROFILE_ID构建URL,与定义的常量保持一致
chat_message_url = f’{BASE_URL}/{PROFILE_ID}/chat_message/{chat_id}’
try:
response = requests.post(chat_message_url, headers=headers, json=payload)
print(f"发送消息响应状态码: {response.status_code}“)
print(f"发送消息响应内容: {response.text}”)
if response.status_code == 200:
return response.json()
else:
print(f"发送消息失败,状态码: {response.status_code}")
return None
except Exception as e:
print(f"发送消息时发生错误: {str(e)}")
return None
主函数
def main(message, re_chat=False, stream=False):
# 直接使用预设的profile id
profile_id = PROFILE_ID
print(f"使用提供的profile id: {profile_id}")
chat_id = get_chat_id(profile_id)
if chat_id:
print("获取chat id成功:", chat_id)
chat_message_payload = {
"message": message,
"re_chat": re_chat,
"stream": stream
}
response = send_chat_message(chat_id, chat_message_payload)
if response:
print("消息发送成功")
content = response['data']['content']
return content
else:
print("获取chat id失败")
return None
if name == “main”:
message = “你好”
r = main(message, re_chat=False, stream=False)
print(“返回结果:”, r)
报错:发送消息失败,状态码: 401,响应: {“code”: 1002, “message”: “\u8eab\u4efd\u9a8c\u8bc1\u4fe1\u606f\u4e0d\u6b63\u786e\uff01\u975e\u6cd5\u7528\u6237”, “data”: null}
AI回复: None