Update app.py
Browse files
app.py
CHANGED
@@ -5,6 +5,7 @@ from flask import Flask, request, jsonify
|
|
5 |
from datetime import datetime, timezone, timedelta
|
6 |
import asyncio
|
7 |
import re
|
|
|
8 |
|
9 |
app = Flask(__name__)
|
10 |
|
@@ -65,6 +66,44 @@ TOOLS = [
|
|
65 |
"required": []
|
66 |
}
|
67 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
}
|
69 |
]
|
70 |
|
@@ -73,6 +112,31 @@ def get_current_datetime():
|
|
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,41 +351,47 @@ async def handleAiResponse(ai_data, chatId, history, thinking_message_id):
|
|
287 |
if choice.get('message'):
|
288 |
message = choice['message']
|
289 |
if message.get('tool_calls'):
|
290 |
-
tool_call
|
291 |
-
|
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 |
-
|
324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
325 |
elif message.get('content'):
|
326 |
return message['content']
|
327 |
|
|
|
5 |
from datetime import datetime, timezone, timedelta
|
6 |
import asyncio
|
7 |
import re
|
8 |
+
import random
|
9 |
|
10 |
app = Flask(__name__)
|
11 |
|
|
|
66 |
"required": []
|
67 |
}
|
68 |
}
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"type": "function",
|
72 |
+
"function": {
|
73 |
+
"name": "generate_random_number",
|
74 |
+
"description": "生成指定范围内的随机整数",
|
75 |
+
"parameters": {
|
76 |
+
"type": "object",
|
77 |
+
"properties": {
|
78 |
+
"min": {
|
79 |
+
"type": "integer",
|
80 |
+
"description": "随机数的最小值"
|
81 |
+
},
|
82 |
+
"max": {
|
83 |
+
"type": "integer",
|
84 |
+
"description": "随机数的最大值"
|
85 |
+
}
|
86 |
+
},
|
87 |
+
"required": ["min", "max"]
|
88 |
+
}
|
89 |
+
}
|
90 |
+
},
|
91 |
+
{
|
92 |
+
"type": "function",
|
93 |
+
"function": {
|
94 |
+
"name": "search_bing",
|
95 |
+
"description": "使用必应搜索查询",
|
96 |
+
"parameters": {
|
97 |
+
"type": "object",
|
98 |
+
"properties": {
|
99 |
+
"query": {
|
100 |
+
"type": "string",
|
101 |
+
"description": "搜索查询词"
|
102 |
+
}
|
103 |
+
},
|
104 |
+
"required": ["query"]
|
105 |
+
}
|
106 |
+
}
|
107 |
}
|
108 |
]
|
109 |
|
|
|
112 |
local_time = utc_time.astimezone(timezone(timedelta(hours=8)))
|
113 |
return local_time.strftime("%Y-%m-%d %H:%M:%S")
|
114 |
|
115 |
+
def generate_random_number(min, max):
|
116 |
+
return random.randint(min, max)
|
117 |
+
|
118 |
+
def search_bing(query):
|
119 |
+
search_api_url = "https://api.bing.microsoft.com/v7.0/search"
|
120 |
+
bing_api_key = os.environ.get("BING_API_KEY")
|
121 |
+
if not bing_api_key:
|
122 |
+
return "请设置 BING_API_KEY 环境变量"
|
123 |
+
headers = {"Ocp-Apim-Subscription-Key": bing_api_key}
|
124 |
+
params = {"q": query}
|
125 |
+
try:
|
126 |
+
response = requests.get(search_api_url, headers=headers, params=params)
|
127 |
+
response.raise_for_status()
|
128 |
+
search_results = response.json()
|
129 |
+
if search_results and search_results.get("webPages") and search_results.get("webPages").get("value"):
|
130 |
+
results = search_results["webPages"]["value"][:3]
|
131 |
+
formatted_results = []
|
132 |
+
for result in results:
|
133 |
+
formatted_results.append(f"[{result['name']}]({result['url']})")
|
134 |
+
return "\n".join(formatted_results)
|
135 |
+
else:
|
136 |
+
return "没有找到相关结果"
|
137 |
+
except requests.exceptions.RequestException as e:
|
138 |
+
return f"搜索失败: {e}"
|
139 |
+
|
140 |
def make_telegram_request(method, data=None):
|
141 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
142 |
if PHP_PROXY_URL:
|
|
|
351 |
if choice.get('message'):
|
352 |
message = choice['message']
|
353 |
if message.get('tool_calls'):
|
354 |
+
for tool_call in message['tool_calls']:
|
355 |
+
function_name = tool_call['function']['name']
|
356 |
+
arguments = json.loads(tool_call['function']['arguments'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
357 |
|
358 |
+
tool_result = None
|
359 |
+
if function_name == 'get_current_datetime':
|
360 |
+
tool_result = get_current_datetime()
|
361 |
+
elif function_name == 'generate_random_number':
|
362 |
+
tool_result = generate_random_number(arguments.get('min'), arguments.get('max'))
|
363 |
+
elif function_name == 'search_bing':
|
364 |
+
tool_result = search_bing(arguments.get('query'))
|
365 |
+
|
366 |
+
if tool_result is not None:
|
367 |
+
history.append({
|
368 |
+
'tool_call_id': tool_call['id'],
|
369 |
+
'role': 'tool',
|
370 |
+
'name': function_name,
|
371 |
+
'content': str(tool_result),
|
372 |
+
})
|
373 |
+
else:
|
374 |
+
return '工具调用失败'
|
375 |
+
|
376 |
+
messages = [
|
377 |
+
{'role': 'system', 'content': PROMPT_TEMPLATES.get(USER_SETTINGS.get(chatId, {}).get('prompt_index', CURRENT_PROMPT_INDEX), "")},
|
378 |
+
*history
|
379 |
+
]
|
380 |
+
try:
|
381 |
+
ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
|
382 |
+
'model': AI_MODEL,
|
383 |
+
'messages': messages,
|
384 |
+
'max_tokens': MAX_TOKENS,
|
385 |
+
'temperature': USER_SETTINGS.get(chatId, {}).get('temperature', DEFAULT_TEMP),
|
386 |
+
'tools': TOOLS,
|
387 |
+
})
|
388 |
+
ai_response.raise_for_status()
|
389 |
+
ai_data = ai_response.json()
|
390 |
+
return await handleAiResponse(ai_data, chatId, history, thinking_message_id)
|
391 |
+
except requests.exceptions.RequestException as e:
|
392 |
+
print(f'AI API 响应失败: {e}')
|
393 |
+
await editTelegramMessage(chatId, thinking_message_id, 'AI API 响应失败,请稍后再试')
|
394 |
+
return 'AI API 响应失败,请稍后再试'
|
395 |
elif message.get('content'):
|
396 |
return message['content']
|
397 |
|