File size: 19,580 Bytes
c3c93e2 4eec083 c3c93e2 8008fbb 3bc6d83 a4ae7b7 8008fbb a4ae7b7 8a9b05e e7c16da 4eec083 4319607 4eec083 8008fbb 4eec083 e7c16da a4ae7b7 338d1f0 a4ae7b7 4eec083 3bc6d83 8008fbb c3c93e2 2492fd1 c3c93e2 2492fd1 c3c93e2 2492fd1 338d1f0 2492fd1 8008fbb 2492fd1 8008fbb 2492fd1 8008fbb 3bc6d83 4eec083 3bc6d83 92a6e67 54fc02c c3c93e2 e7c16da c3c93e2 8008fbb 54fc02c c3c93e2 8008fbb 54fc02c c3c93e2 8008fbb c3c93e2 8008fbb c3c93e2 8008fbb c3c93e2 8008fbb 2fa1b7b a4ae7b7 2fa1b7b c3c93e2 8008fbb 54fc02c 8008fbb 54fc02c 8008fbb 54fc02c 8008fbb 54fc02c 8008fbb 4eec083 54fc02c 8008fbb c3c93e2 92a6e67 8008fbb 8a9b05e c3c93e2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, request, make_response
import hashlib
import time
import xml.etree.ElementTree as ET
import os
import json
from openai import OpenAI
from dotenv import load_dotenv
from duckduckgo_search import DDGS
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 加载环境变量
load_dotenv()
app = Flask(__name__)
# 配置
TOKEN = os.getenv('TOKEN')
API_KEY = os.getenv("API_KEY")
BASE_URL = os.getenv("OPENAI_BASE_URL")
emailkey = os.getenv("EMAIL_KEY")
client = OpenAI(api_key=API_KEY, base_url=BASE_URL)
# 定义可用的模型列表
AVAILABLE_MODELS = {
'gpt-3.5-turbo': 'GPT-3.5 Turbo',
'gpt-4o': 'GPT-4o',
'gpt-4o-mini': 'GPT-4o-mini',
}
# 存储用户会话信息
user_sessions = {}
# 定义函数
def search_duckduckgo(keywords):
search_term = " ".join(keywords)
with DDGS() as ddgs:
results = list(ddgs.text(keywords=search_term, region="cn-zh", safesearch="on", max_results=5))
return [{"title": result['title'], "body": result['body'].replace('\n', ' ')} for result in results]
def search_papers(query):
url = f"https://api.crossref.org/works?query={query}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
papers = data['message']['items']
processed_papers = []
for paper in papers:
processed_paper = {
"标题": paper.get('title', [''])[0],
"作者": ", ".join([f"{author.get('given', '')} {author.get('family', '')}" for author in paper.get('author', [])]),
"DOI": paper.get('DOI', ''),
"摘要": paper.get('abstract', '').replace('<p>', '').replace('</p>', '').replace('<italic>', '*').replace('</italic>', '*')
}
processed_papers.append(processed_paper)
return processed_papers
else:
return []
def send_email(to, subject, content):
try:
with smtplib.SMTP('106.15.184.28', 8025) as smtp:
smtp.login("jwt", emailkey)
message = MIMEMultipart()
message['From'] = "Me <[email protected]>"
message['To'] = to
message['Subject'] = subject
message.attach(MIMEText(content, 'html'))
smtp.sendmail("[email protected]", to, message.as_string())
return True
except Exception as e:
print(f"发送邮件时出错: {str(e)}")
return False
# 定义函数列表
FUNCTIONS = [
{
"name": "search_duckduckgo",
"description": "使用DuckDuckGo搜索引擎查询信息。可以搜索最新新闻、文章、博客等内容。",
"parameters": {
"type": "object",
"properties": {
"keywords": {
"type": "array",
"items": {"type": "string"},
"description": "搜索的关键词列表。例如:['Python', '机器学习', '最新进展']。"
}
},
"required": ["keywords"]
}
},
{
"name": "search_papers",
"description": "使用Crossref API搜索学术论文。",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "搜索查询字符串。例如:'climate change'。"
}
},
"required": ["query"]
}
},
{
"name": "send_email",
"description": "发送电子邮件。",
"parameters": {
"type": "object",
"properties": {
"to": {
"type": "string",
"description": "收件人邮箱地址"
},
"subject": {
"type": "string",
"description": "邮件主题"
},
"content": {
"type": "string",
"description": "邮件内容"
}
},
"required": ["to", "subject", "content"]
}
}
]
def verify_wechat(request):
# 获取微信服务器发送过来的参数
data = request.args
signature = data.get('signature')
timestamp = data.get('timestamp')
nonce = data.get('nonce')
echostr = data.get('echostr')
# 对参数进行字典排序,拼接字符串
temp = [timestamp, nonce, TOKEN]
temp.sort()
temp = ''.join(temp)
# 加密
if (hashlib.sha1(temp.encode('utf8')).hexdigest() == signature):
return echostr
else:
return 'error', 403
def getUserMessageContentFromXML(xml_content):
# 解析XML字符串
root = ET.fromstring(xml_content)
# 提取数据
content = root.find('Content').text
from_user_name = root.find('FromUserName').text
to_user_name = root.find('ToUserName').text
return content, from_user_name, to_user_name
def generate_response_xml(from_user_name, to_user_name, output_content):
output_xml = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>'''
response = make_response(output_xml % (from_user_name, to_user_name, str(int(time.time())), output_content))
response.content_type = 'application/xml'
return response
def get_openai_response(messages, model="gpt-4o-mini", functions=None, function_call=None):
try:
response = client.chat.completions.create(
model=model,
messages=messages,
functions=functions,
function_call=function_call
)
return response.choices[0].message
except Exception as e:
print(f"调用OpenAI API时出错: {str(e)}")
return None
def process_function_call(function_name, function_args):
if function_name == "search_duckduckgo":
keywords = function_args.get('keywords', [])
if not keywords:
return "搜索关键词为空,无法执行搜索。"
return search_duckduckgo(keywords)
elif function_name == "search_papers":
query = function_args.get('query', '')
if not query:
return "搜索查询为空,无法执行论文搜索。"
return search_papers(query)
elif function_name == "send_email":
to = function_args.get('to', '')
subject = function_args.get('subject', '')
content = function_args.get('content', '')
if not to or not subject or not content:
return "邮件信息不完整,无法发送邮件。"
success = send_email(to, subject, content)
return {
"success": success,
"message": "邮件发送成功" if success else "邮件发送失败",
"to": to,
"subject": subject,
"content": content,
"is_email": True
}
else:
return "未知的函数调用。"
def split_message(message, max_length=500):
return [message[i:i+max_length] for i in range(0, len(message), max_length)]
# @app.route('/api/wx', methods=['GET', 'POST'])
# def wechatai():
# if request.method == 'GET':
# return verify_wechat(request)
# else:
# # 处理POST请求
# xml_str = request.data
# if not xml_str:
# return ""
# user_message_content, from_user_name, to_user_name = getUserMessageContentFromXML(xml_str)
# if from_user_name not in user_sessions:
# user_sessions[from_user_name] = {'model': 'gpt-4o-mini', 'messages': [], 'pending_response': []}
# session = user_sessions[from_user_name]
# if user_message_content.lower() == '/models':
# response_content = f"可用的模型列表:\n{list_available_models()}\n\n使用 /model 模型名称 来切换模型"
# return generate_response_xml(from_user_name, to_user_name, response_content)
# elif user_message_content.lower().startswith('/model'):
# model = user_message_content.split(' ')[1]
# if model in AVAILABLE_MODELS:
# session['model'] = model
# response_content = f'模型已切换为 {AVAILABLE_MODELS[model]}'
# else:
# response_content = f'无效的模型名称。可用的模型有:\n{list_available_models()}'
# return generate_response_xml(from_user_name, to_user_name, response_content)
# elif user_message_content.lower() == '继续':
# if session['pending_response']:
# response_content = session['pending_response'].pop(0)
# if session['pending_response']:
# response_content += '\n\n回复"继续"获取下一部分。'
# else:
# response_content += '\n\n回复结束。'
# else:
# response_content = "没有待发送的消息。"
# return generate_response_xml(from_user_name, to_user_name, response_content)
# session['messages'].append({"role": "user", "content": user_message_content})
# # 调用OpenAI API
# ai_response = get_openai_response(session['messages'], model=session['model'], functions=FUNCTIONS, function_call="auto")
# if ai_response.function_call:
# function_name = ai_response.function_call.name
# function_args = json.loads(ai_response.function_call.arguments)
# function_result = process_function_call(function_name, function_args)
# session['messages'].append(ai_response.model_dump())
# session['messages'].append({
# "role": "function",
# "name": function_name,
# "content": json.dumps(function_result, ensure_ascii=False)
# })
# final_response = get_openai_response(session['messages'], model=session['model'])
# response_content = final_response.content
# else:
# response_content = ai_response.content
# session['messages'].append({"role": "assistant", "content": response_content})
# # 处理长消息
# response_parts = split_message(response_content)
# if len(response_parts) > 1:
# session['pending_response'] = response_parts[1:]
# response_content = response_parts[0] + '\n\n回复"继续"获取下一部分。'
# return generate_response_xml(from_user_name, to_user_name, response_content)
# @app.route('/api/wx', methods=['GET', 'POST'])
# def wechatai():
# if request.method == 'GET':
# return verify_wechat(request)
# else:
# # 处理POST请求
# xml_str = request.data
# if not xml_str:
# return ""
# user_message_content, from_user_name, to_user_name = getUserMessageContentFromXML(xml_str)
# if from_user_name not in user_sessions:
# user_sessions[from_user_name] = {'model': 'gpt-4o-mini', 'messages': [], 'pending_response': []}
# session = user_sessions[from_user_name]
# if user_message_content.lower() == '/models':
# response_content = f"可用的模型列表:\n{list_available_models()}\n\n使用 /model 模型名称 来切换模型"
# return generate_response_xml(from_user_name, to_user_name, response_content)
# elif user_message_content.lower().startswith('/model'):
# model = user_message_content.split(' ')[1]
# if model in AVAILABLE_MODELS:
# session['model'] = model
# response_content = f'模型已切换为 {AVAILABLE_MODELS[model]}'
# else:
# response_content = f'无效的模型名称。可用的模型有:\n{list_available_models()}'
# return generate_response_xml(from_user_name, to_user_name, response_content)
# elif user_message_content.lower() == '继续':
# if session['pending_response']:
# response_content = session['pending_response'].pop(0)
# if session['pending_response']:
# response_content += '\n\n回复"继续"获取下一部分。'
# else:
# response_content += '\n\n回复结束。'
# else:
# response_content = "没有待发送的消息。"
# return generate_response_xml(from_user_name, to_user_name, response_content)
# session['messages'].append({"role": "user", "content": user_message_content})
# # 调用OpenAI API
# ai_response = get_openai_response(session['messages'], model=session['model'], functions=FUNCTIONS, function_call="auto")
# if ai_response.function_call:
# function_name = ai_response.function_call.name
# function_args = json.loads(ai_response.function_call.arguments)
# function_result = process_function_call(function_name, function_args)
# session['messages'].append(ai_response.model_dump())
# session['messages'].append({
# "role": "function",
# "name": function_name,
# "content": json.dumps(function_result, ensure_ascii=False)
# })
# # 再次调用OpenAI API,将函数执行结果作为上下文
# final_response = get_openai_response(session['messages'], model=session['model'])
# response_content = final_response.content
# else:
# response_content = ai_response.content
# session['messages'].append({"role": "assistant", "content": response_content})
# # 处理长消息
# response_parts = split_message(response_content)
# if len(response_parts) > 1:
# session['pending_response'] = response_parts[1:]
# response_content = response_parts[0] + '\n\n回复"继续"获取下一部分。'
# return generate_response_xml(from_user_name, to_user_name, response_content)
@app.route('/api/wx', methods=['GET', 'POST'])
def wechatai():
if request.method == 'GET':
return verify_wechat(request)
else:
xml_str = request.data
if not xml_str:
return ""
user_message_content, from_user_name, to_user_name = getUserMessageContentFromXML(xml_str)
if from_user_name not in user_sessions:
user_sessions[from_user_name] = {'model': 'gpt-3.5-turbo', 'messages': [], 'pending_response': []}
session = user_sessions[from_user_name]
# 处理特殊命令
if user_message_content.lower() == '/models':
response_content = f"可用的模型列表:\n{list_available_models()}\n\n使用 /model 模型名称 来切换模型"
return generate_response_xml(from_user_name, to_user_name, response_content)
elif user_message_content.lower().startswith('/model'):
model = user_message_content.split(' ')[1]
if model in AVAILABLE_MODELS:
session['model'] = model
response_content = f'模型已切换为 {AVAILABLE_MODELS[model]}'
else:
response_content = f'无效的模型名称。可用的模型有:\n{list_available_models()}'
return generate_response_xml(from_user_name, to_user_name, response_content)
elif user_message_content.lower() == '继续':
if session['pending_response']:
response_content = session['pending_response'].pop(0)
if session['pending_response']:
response_content += '\n\n回复"继续"获取下一部分。'
else:
response_content += '\n\n回复结束。'
else:
response_content = "没有待发送的消息。"
return generate_response_xml(from_user_name, to_user_name, response_content)
session['messages'].append({"role": "user", "content": user_message_content})
messages = session['messages']
# 次级模型1: 处理搜索相关函数
sub_model_1_response = get_openai_response(messages, model=session['model'], functions=FUNCTIONS_GROUP_1, function_call="auto")
# 次级模型2: 处理邮件发送相关函数
sub_model_2_response = get_openai_response(messages, model=session['model'], functions=FUNCTIONS_GROUP_2, function_call="auto")
function_call_1 = sub_model_1_response.function_call if sub_model_1_response and sub_model_1_response.function_call else None
function_call_2 = sub_model_2_response.function_call if sub_model_2_response and sub_model_2_response.function_call else None
final_function_call = None
if function_call_1 and function_call_2:
# 裁决模型: 决定使用哪个函数调用
arbitration_messages = messages + [
{"role": "system", "content": "两个次级模型都建议使用函数。请决定使用哪个函数更合适。"},
{"role": "assistant", "content": f"次级模型1建议使用函数:{function_call_1.name}"},
{"role": "assistant", "content": f"次级模型2建议使用函数:{function_call_2.name}"}
]
arbitration_response = get_openai_response(arbitration_messages, model=session['model'])
if arbitration_response and ("模型1" in arbitration_response.content or function_call_1.name in arbitration_response.content):
final_function_call = function_call_1
else:
final_function_call = function_call_2
elif function_call_1:
final_function_call = function_call_1
elif function_call_2:
final_function_call = function_call_2
if final_function_call:
function_name = final_function_call.name
function_args = json.loads(final_function_call.arguments)
function_result = process_function_call(function_name, function_args)
messages.append({"role": "function", "name": function_name, "content": json.dumps(function_result, ensure_ascii=False)})
# 主模型: 生成最终回复
final_response = get_openai_response(messages, model=session['model'])
response_content = final_response.content if final_response else "Error occurred"
session['messages'].append({"role": "assistant", "content": response_content})
# 处理长消息
response_parts = split_message(response_content)
if len(response_parts) > 1:
session['pending_response'] = response_parts[1:]
response_content = response_parts[0] + '\n\n回复"继续"获取下一部分。'
return generate_response_xml(from_user_name, to_user_name, response_content)
def list_available_models():
return "\n".join([f"{key}: {value}" for key, value in AVAILABLE_MODELS.items()])
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True) |