Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,229 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import requests
|
| 4 |
-
import smtplib
|
| 5 |
-
from email.mime.text import MIMEText
|
| 6 |
-
from email.mime.multipart import MIMEMultipart
|
| 7 |
-
from flask import Flask, request, jsonify, send_from_directory
|
| 8 |
-
from openai import OpenAI
|
| 9 |
-
from duckduckgo_search import DDGS
|
| 10 |
-
|
| 11 |
-
app = Flask(__name__)
|
| 12 |
-
API_KEY = os.getenv("OPENAI_API_KEY")
|
| 13 |
-
BASE_URL = os.getenv("OPENAI_BASE_URL")
|
| 14 |
-
emailkey = os.getenv("EMAIL_KEY")
|
| 15 |
-
client = OpenAI(api_key=API_KEY, base_url=BASE_URL)
|
| 16 |
-
|
| 17 |
-
FUNCTIONS = [
|
| 18 |
-
{
|
| 19 |
-
"name": "search_duckduckgo",
|
| 20 |
-
"description": "使用DuckDuckGo搜索引擎查询信息。可以搜索最新新闻、文章、博客等内容。",
|
| 21 |
-
"parameters": {
|
| 22 |
-
"type": "object",
|
| 23 |
-
"properties": {
|
| 24 |
-
"keywords": {
|
| 25 |
-
"type": "array",
|
| 26 |
-
"items": {"type": "string"},
|
| 27 |
-
"description": "搜索的关键词列表。例如:['Python', '机器学习', '最新进展']。"
|
| 28 |
-
}
|
| 29 |
-
},
|
| 30 |
-
"required": ["keywords"]
|
| 31 |
-
}
|
| 32 |
-
},
|
| 33 |
-
{
|
| 34 |
-
"name": "search_papers",
|
| 35 |
-
"description": "使用Crossref API搜索学术论文。",
|
| 36 |
-
"parameters": {
|
| 37 |
-
"type": "object",
|
| 38 |
-
"properties": {
|
| 39 |
-
"query": {
|
| 40 |
-
"type": "string",
|
| 41 |
-
"description": "搜索查询字符串。例如:'climate change'。"
|
| 42 |
-
}
|
| 43 |
-
},
|
| 44 |
-
"required": ["query"]
|
| 45 |
-
}
|
| 46 |
-
},
|
| 47 |
-
{
|
| 48 |
-
"name": "send_email",
|
| 49 |
-
"description": "发送电子邮件。",
|
| 50 |
-
"parameters": {
|
| 51 |
-
"type": "object",
|
| 52 |
-
"properties": {
|
| 53 |
-
"to": {
|
| 54 |
-
"type": "string",
|
| 55 |
-
"description": "收件人邮箱地址"
|
| 56 |
-
},
|
| 57 |
-
"subject": {
|
| 58 |
-
"type": "string",
|
| 59 |
-
"description": "邮件主题"
|
| 60 |
-
},
|
| 61 |
-
"content": {
|
| 62 |
-
"type": "string",
|
| 63 |
-
"description": "邮件内容"
|
| 64 |
-
}
|
| 65 |
-
},
|
| 66 |
-
"required": ["to", "subject", "content"]
|
| 67 |
-
}
|
| 68 |
-
}
|
| 69 |
-
]
|
| 70 |
-
|
| 71 |
-
def search_duckduckgo(keywords):
|
| 72 |
-
search_term = " ".join(keywords)
|
| 73 |
-
with DDGS() as ddgs:
|
| 74 |
-
return list(ddgs.text(keywords=search_term, region="cn-zh", safesearch="on", max_results=5))
|
| 75 |
-
|
| 76 |
-
def search_papers(query):
|
| 77 |
-
url = f"https://api.crossref.org/works?query={query}"
|
| 78 |
-
response = requests.get(url)
|
| 79 |
-
if response.status_code == 200:
|
| 80 |
-
data = response.json()
|
| 81 |
-
papers = data['message']['items']
|
| 82 |
-
processed_papers = []
|
| 83 |
-
for paper in papers:
|
| 84 |
-
processed_paper = {
|
| 85 |
-
"标题": paper.get('title', [''])[0],
|
| 86 |
-
"作者": ", ".join([f"{author.get('given', '')} {author.get('family', '')}" for author in paper.get('author', [])]),
|
| 87 |
-
"DOI": paper.get('DOI', ''),
|
| 88 |
-
"ISBN": ", ".join(paper.get('ISBN', [])),
|
| 89 |
-
"摘要": paper.get('abstract', '').replace('<p>', '').replace('</p>', '').replace('<italic>', '').replace('</italic>', '')
|
| 90 |
-
}
|
| 91 |
-
processed_papers.append(processed_paper)
|
| 92 |
-
return processed_papers
|
| 93 |
-
else:
|
| 94 |
-
return []
|
| 95 |
-
|
| 96 |
-
def send_email(to, subject, content):
|
| 97 |
-
try:
|
| 98 |
-
with smtplib.SMTP('106.15.184.28', 8025) as smtp:
|
| 99 |
-
smtp.login("jwt", emailkey)
|
| 100 |
-
message = MIMEMultipart()
|
| 101 |
-
message['From'] = "Me <aixiao@aixiao.xyz>"
|
| 102 |
-
message['To'] = to
|
| 103 |
-
message['Subject'] = subject
|
| 104 |
-
message.attach(MIMEText(content, 'html'))
|
| 105 |
-
smtp.sendmail("aixiao@aixiao.xyz", to, message.as_string())
|
| 106 |
-
return True
|
| 107 |
-
except Exception as e:
|
| 108 |
-
print(f"发送邮件时出错: {str(e)}")
|
| 109 |
-
return False
|
| 110 |
-
|
| 111 |
-
def get_openai_response(messages, model="gpt-4o-mini", functions=None, function_call=None):
|
| 112 |
-
try:
|
| 113 |
-
response = client.chat.completions.create(
|
| 114 |
-
model=model,
|
| 115 |
-
messages=messages,
|
| 116 |
-
functions=functions,
|
| 117 |
-
function_call=function_call
|
| 118 |
-
)
|
| 119 |
-
return response.choices[0].message
|
| 120 |
-
except Exception as e:
|
| 121 |
-
print(f"调用OpenAI API时出错: {str(e)}")
|
| 122 |
-
return None
|
| 123 |
-
|
| 124 |
-
def process_function_call(response_message):
|
| 125 |
-
function_name = response_message.function_call.name
|
| 126 |
-
function_args = json.loads(response_message.function_call.arguments)
|
| 127 |
-
if function_name == "search_duckduckgo":
|
| 128 |
-
keywords = function_args.get('keywords', [])
|
| 129 |
-
if not keywords:
|
| 130 |
-
return None
|
| 131 |
-
return search_duckduckgo(keywords)
|
| 132 |
-
elif function_name == "search_papers":
|
| 133 |
-
query = function_args.get('query', '')
|
| 134 |
-
if not query:
|
| 135 |
-
return None
|
| 136 |
-
return search_papers(query)
|
| 137 |
-
elif function_name == "send_email":
|
| 138 |
-
to = function_args.get('to', '')
|
| 139 |
-
subject = function_args.get('subject', '')
|
| 140 |
-
content = function_args.get('content', '')
|
| 141 |
-
if not to or not subject or not content:
|
| 142 |
-
return None
|
| 143 |
-
success = send_email(to, subject, content)
|
| 144 |
-
return {
|
| 145 |
-
"success": success,
|
| 146 |
-
"to": to,
|
| 147 |
-
"subject": subject,
|
| 148 |
-
"content": content
|
| 149 |
-
}
|
| 150 |
-
else:
|
| 151 |
-
return None
|
| 152 |
-
|
| 153 |
-
@app.route('/')
|
| 154 |
-
def index():
|
| 155 |
-
return send_from_directory('.', 'index.html')
|
| 156 |
-
|
| 157 |
-
@app.route('/chat', methods=['POST'])
|
| 158 |
-
def chat():
|
| 159 |
-
data = request.json
|
| 160 |
-
question = data['question']
|
| 161 |
-
history = data.get('history', [])
|
| 162 |
-
messages = history + [{"role": "user", "content": question}]
|
| 163 |
-
|
| 164 |
-
status_log = []
|
| 165 |
-
|
| 166 |
-
# First model: Decide whether to use search or send email
|
| 167 |
-
status_log.append("次模型:正在判断是否需要进行搜索或发送邮件")
|
| 168 |
-
decision_response = get_openai_response(messages, model="gpt-4o-mini", functions=FUNCTIONS, function_call="auto")
|
| 169 |
-
|
| 170 |
-
search_results = None
|
| 171 |
-
email_result = None
|
| 172 |
-
if decision_response and decision_response.function_call:
|
| 173 |
-
function_name = decision_response.function_call.name
|
| 174 |
-
status_log.append(f"次模型:判断需要{function_name}")
|
| 175 |
-
status_log.append(f"正在进行{function_name}")
|
| 176 |
-
result = process_function_call(decision_response)
|
| 177 |
-
if result:
|
| 178 |
-
if function_name == "search_papers":
|
| 179 |
-
search_results = result[:10]
|
| 180 |
-
elif function_name == "search_duckduckgo":
|
| 181 |
-
search_results = result
|
| 182 |
-
elif function_name == "send_email":
|
| 183 |
-
email_result = result
|
| 184 |
-
status_log.append(f"{function_name}完成")
|
| 185 |
-
else:
|
| 186 |
-
status_log.append("次模型:判断不需要进行搜索或发送邮件")
|
| 187 |
-
|
| 188 |
-
# Generate response based on the action taken
|
| 189 |
-
if email_result:
|
| 190 |
-
response = f"邮件{'已成功' if email_result['success'] else '未能成功'}发送到 {email_result['to']}。\n\n主题:{email_result['subject']}\n\n内容:\n{email_result['content']}"
|
| 191 |
-
elif search_results:
|
| 192 |
-
# Second model: Generate final response with search results
|
| 193 |
-
status_log.append("主模型:正在生成回答")
|
| 194 |
-
messages.append({
|
| 195 |
-
"role": "assistant",
|
| 196 |
-
"content": decision_response.content if decision_response.content else f"I need to {function_name}."
|
| 197 |
-
})
|
| 198 |
-
messages.append({
|
| 199 |
-
"role": "function",
|
| 200 |
-
"name": function_name,
|
| 201 |
-
"content": json.dumps(search_results, ensure_ascii=False)
|
| 202 |
-
})
|
| 203 |
-
final_response = get_openai_response(messages, model="gpt-4o-mini")
|
| 204 |
-
response = final_response.content if final_response else "Error occurred"
|
| 205 |
-
status_log.append("主模型:回答生成完成")
|
| 206 |
-
else:
|
| 207 |
-
# Second model: Generate final response without search results
|
| 208 |
-
status_log.append("主模型:正在生成回答")
|
| 209 |
-
final_response = get_openai_response(messages, model="gpt-4o-mini")
|
| 210 |
-
response = final_response.content if final_response else "Error occurred"
|
| 211 |
-
status_log.append("主模型:回答生成完成")
|
| 212 |
-
|
| 213 |
-
return jsonify({
|
| 214 |
-
"response": response,
|
| 215 |
-
"search_used": bool(search_results),
|
| 216 |
-
"search_results": search_results,
|
| 217 |
-
"email_sent": email_result['success'] if email_result else False,
|
| 218 |
-
"status_log": status_log
|
| 219 |
-
})
|
| 220 |
-
|
| 221 |
-
@app.route('/settings', methods=['POST'])
|
| 222 |
-
def update_settings():
|
| 223 |
-
data = request.json
|
| 224 |
-
max_history = data.get('max_history', 10)
|
| 225 |
-
# 在这里可以添加其他设置项
|
| 226 |
-
return jsonify({"status": "success", "max_history": max_history})
|
| 227 |
-
|
| 228 |
-
if __name__ == '__main__':
|
| 229 |
-
app.run(host='0.0.0.0', port=7860, debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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