Update app.py
Browse files
app.py
CHANGED
@@ -5,7 +5,6 @@ from flask import Flask, request, jsonify
|
|
5 |
from datetime import datetime, timezone, timedelta
|
6 |
import asyncio
|
7 |
import re
|
8 |
-
import random
|
9 |
|
10 |
app = Flask(__name__)
|
11 |
|
@@ -14,7 +13,6 @@ AI_API_ENDPOINT = os.environ.get('AI_API_ENDPOINT')
|
|
14 |
AI_API_KEY = os.environ.get('AI_API_KEY')
|
15 |
AI_MODEL = os.environ.get('AI_MODEL')
|
16 |
PHP_PROXY_URL = os.environ.get('PHP_PROXY_URL')
|
17 |
-
SEARXNG_URL = os.environ.get('SEARXNG_URL', 'https://sousuo.emoe.top') # 默认值是你的 URL
|
18 |
|
19 |
if not all([TELEGRAM_BOT_TOKEN, AI_API_ENDPOINT, AI_API_KEY, AI_MODEL]):
|
20 |
raise ValueError("请设置所有必要的环境变量")
|
@@ -67,44 +65,6 @@ TOOLS = [
|
|
67 |
"required": []
|
68 |
}
|
69 |
}
|
70 |
-
},
|
71 |
-
{
|
72 |
-
"type": "function",
|
73 |
-
"function": {
|
74 |
-
"name": "generate_random_number",
|
75 |
-
"description": "生成指定范围内的随机整数",
|
76 |
-
"parameters": {
|
77 |
-
"type": "object",
|
78 |
-
"properties": {
|
79 |
-
"min": {
|
80 |
-
"type": "integer",
|
81 |
-
"description": "随机数的最小值"
|
82 |
-
},
|
83 |
-
"max": {
|
84 |
-
"type": "integer",
|
85 |
-
"description": "随机数的最大值"
|
86 |
-
}
|
87 |
-
},
|
88 |
-
"required": ["min", "max"]
|
89 |
-
}
|
90 |
-
}
|
91 |
-
},
|
92 |
-
{
|
93 |
-
"type": "function",
|
94 |
-
"function": {
|
95 |
-
"name": "search_searxng",
|
96 |
-
"description": "使用SearXNG搜索查询",
|
97 |
-
"parameters": {
|
98 |
-
"type": "object",
|
99 |
-
"properties": {
|
100 |
-
"query": {
|
101 |
-
"type": "string",
|
102 |
-
"description": "搜索查询词"
|
103 |
-
}
|
104 |
-
},
|
105 |
-
"required": ["query"]
|
106 |
-
}
|
107 |
-
}
|
108 |
}
|
109 |
]
|
110 |
|
@@ -113,28 +73,6 @@ def get_current_datetime():
|
|
113 |
local_time = utc_time.astimezone(timezone(timedelta(hours=8)))
|
114 |
return local_time.strftime("%Y-%m-%d %H:%M:%S")
|
115 |
|
116 |
-
def generate_random_number(min, max):
|
117 |
-
return random.randint(min, max)
|
118 |
-
|
119 |
-
def search_searxng(query):
|
120 |
-
search_url = f"{SEARXNG_URL}/search"
|
121 |
-
params = {"q": query, "format": "json"}
|
122 |
-
try:
|
123 |
-
response = requests.get(search_url, params=params)
|
124 |
-
response.raise_for_status()
|
125 |
-
search_results = response.json()
|
126 |
-
if search_results and search_results.get("results"):
|
127 |
-
results = search_results["results"][:3]
|
128 |
-
formatted_results = []
|
129 |
-
for result in results:
|
130 |
-
formatted_results.append(f"[{result['title']}]({result['url']})")
|
131 |
-
return "\n".join(formatted_results)
|
132 |
-
else:
|
133 |
-
return "没有找到相关结果"
|
134 |
-
except requests.exceptions.RequestException as e:
|
135 |
-
return f"搜索失败: {e}"
|
136 |
-
|
137 |
-
|
138 |
def make_telegram_request(method, data=None):
|
139 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
140 |
if PHP_PROXY_URL:
|
@@ -349,47 +287,41 @@ async def handleAiResponse(ai_data, chatId, history, thinking_message_id):
|
|
349 |
if choice.get('message'):
|
350 |
message = choice['message']
|
351 |
if message.get('tool_calls'):
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
tool_result = search_searxng(arguments.get('query'))
|
363 |
-
|
364 |
-
if tool_result is not None:
|
365 |
-
history.append({
|
366 |
-
'tool_call_id': tool_call['id'],
|
367 |
-
'role': 'tool',
|
368 |
-
'name': function_name,
|
369 |
-
'content': str(tool_result),
|
370 |
-
})
|
371 |
-
else:
|
372 |
-
return '工具调用失败'
|
373 |
-
|
374 |
-
messages = [
|
375 |
-
{'role': 'system', 'content': PROMPT_TEMPLATES.get(USER_SETTINGS.get(chatId, {}).get('prompt_index', CURRENT_PROMPT_INDEX), "")},
|
376 |
-
*history
|
377 |
-
]
|
378 |
-
try:
|
379 |
-
ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
|
380 |
-
'model': AI_MODEL,
|
381 |
-
'messages': messages,
|
382 |
-
'max_tokens': MAX_TOKENS,
|
383 |
-
'temperature': USER_SETTINGS.get(chatId, {}).get('temperature', DEFAULT_TEMP),
|
384 |
-
'tools': TOOLS,
|
385 |
})
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
393 |
elif message.get('content'):
|
394 |
return message['content']
|
395 |
|
|
|
5 |
from datetime import datetime, timezone, timedelta
|
6 |
import asyncio
|
7 |
import re
|
|
|
8 |
|
9 |
app = Flask(__name__)
|
10 |
|
|
|
13 |
AI_API_KEY = os.environ.get('AI_API_KEY')
|
14 |
AI_MODEL = os.environ.get('AI_MODEL')
|
15 |
PHP_PROXY_URL = os.environ.get('PHP_PROXY_URL')
|
|
|
16 |
|
17 |
if not all([TELEGRAM_BOT_TOKEN, AI_API_ENDPOINT, AI_API_KEY, AI_MODEL]):
|
18 |
raise ValueError("请设置所有必要的环境变量")
|
|
|
65 |
"required": []
|
66 |
}
|
67 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
}
|
69 |
]
|
70 |
|
|
|
73 |
local_time = utc_time.astimezone(timezone(timedelta(hours=8)))
|
74 |
return local_time.strftime("%Y-%m-%d %H:%M:%S")
|
75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
def make_telegram_request(method, data=None):
|
77 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
78 |
if PHP_PROXY_URL:
|
|
|
287 |
if choice.get('message'):
|
288 |
message = choice['message']
|
289 |
if message.get('tool_calls'):
|
290 |
+
tool_call = message['tool_calls'][0]
|
291 |
+
function_name = tool_call['function']['name']
|
292 |
+
|
293 |
+
if function_name == 'get_current_datetime':
|
294 |
+
current_datetime = get_current_datetime()
|
295 |
+
history.append({
|
296 |
+
'tool_call_id': tool_call['id'],
|
297 |
+
'role': 'tool',
|
298 |
+
'name': function_name,
|
299 |
+
'content': current_datetime,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
300 |
})
|
301 |
+
messages = [
|
302 |
+
{'role': 'system', 'content': PROMPT_TEMPLATES.get(USER_SETTINGS.get(chatId, {}).get('prompt_index', CURRENT_PROMPT_INDEX), "")},
|
303 |
+
*history
|
304 |
+
]
|
305 |
+
|
306 |
+
try:
|
307 |
+
ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
|
308 |
+
'model': AI_MODEL,
|
309 |
+
'messages': messages,
|
310 |
+
'max_tokens': MAX_TOKENS,
|
311 |
+
'temperature': USER_SETTINGS.get(chatId, {}).get('temperature', DEFAULT_TEMP),
|
312 |
+
'tools': TOOLS,
|
313 |
+
})
|
314 |
+
ai_response.raise_for_status()
|
315 |
+
ai_data = ai_response.json()
|
316 |
+
return await handleAiResponse(ai_data, chatId, history, thinking_message_id)
|
317 |
+
except requests.exceptions.RequestException as e:
|
318 |
+
print(f'AI API 响应失败: {e}')
|
319 |
+
await editTelegramMessage(chatId, thinking_message_id, 'AI API 响应失败,请稍后再试')
|
320 |
+
return 'AI API 响应失败,请稍后再试'
|
321 |
+
|
322 |
+
|
323 |
+
else:
|
324 |
+
return '不支持的工具调用'
|
325 |
elif message.get('content'):
|
326 |
return message['content']
|
327 |
|