import requests
class ChatAPI:
def __init__(self, api_key):
self.api_key = api_key
self.users_history = {} # 用于存储每个用户的对话历史
def _build_payload(self, query, user_id, conversation_id):
# 包装 API 请求体
return {
"inputs": {}, # 可扩展变量输入
"query": query,
"response_mode": "blocking", # 使用阻塞模式
"conversation_id": conversation_id, # 继续之前的对话
"user": user_id
}
def _send_request(self, payload):
url = "http://app.dify.glwsq.cn/v1/chat-messages"
headers = {
"Authorization": f"Bearer {self.api_key}"
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def _update_conversation_id(self, response, user_id):
# 更新会话 ID 和历史记录
conversation_id = response.get('conversation_id', "")
# 确保每个用户有独立的历史记录
if user_id not in self.users_history:
self.users_history[user_id] = {'history': [], 'conversation_id': conversation_id}
# 如果历史记录超过 5 条,则移除最旧的一条
user_data = self.users_history[user_id]
if len(user_data['history']) >= 5:
user_data['history'].pop(0) # 限制最多5条历史记录
user_data['history'].append(response)
user_data['conversation_id'] = conversation_id
def chat(self, user_input, user_id):
# 获取用户的历史记录和会话 ID
if user_id not in self.users_history:
self.users_history[user_id] = {'history': [], 'conversation_id': ""}
conversation_id = self.users_history[user_id]['conversation_id']
payload = self._build_payload(user_input, user_id, conversation_id)
response = self._send_request(payload)
# 更新会话 ID 和历史记录
self._update_conversation_id(response, user_id)
# 提取并返回回答
answer = response.get('answer', '没有收到有效的回答')
return answer
# 使用示例
if __name__ == "__main__":
api_key = "app-xxxx" # 需要替换为实际的 API 密钥
chat_api = ChatAPI(api_key)
user_id = "user123" # 需要替换为实际的用户标识
# 发送对话请求
while True:
user_input = input("请输入您的问题: ")
if user_input.lower() == 'exit':
break
answer = chat_api.chat(user_input, user_id)
print(f"AI 回复: {answer}")
dify 中的机器人放到python中运行
暂无评论,快来抢沙发

