Update app.py
Browse files
app.py
CHANGED
@@ -4,6 +4,7 @@ import requests
|
|
4 |
from flask import Flask, request, jsonify
|
5 |
from datetime import datetime, timezone, timedelta
|
6 |
import asyncio
|
|
|
7 |
|
8 |
app = Flask(__name__)
|
9 |
|
@@ -52,16 +53,28 @@ BOT_COMMANDS = [
|
|
52 |
]
|
53 |
DEFAULT_TEMP = 1.5
|
54 |
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
63 |
}
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
def make_telegram_request(method, data=None):
|
67 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
@@ -193,6 +206,7 @@ def parseCommand(userMessage):
|
|
193 |
command = command.split('@')[0]
|
194 |
return command[1:]
|
195 |
|
|
|
196 |
async def handlePrivateCommand(chatId, userMessage, fromUserId, isGroupChat):
|
197 |
command = parseCommand(userMessage)
|
198 |
if userMessage.startswith('/settemp '):
|
@@ -244,60 +258,22 @@ async def processAiMessage(chatId, userMessage, fromUserId, message_id):
|
|
244 |
{'role': 'system', 'content': currentPrompt},
|
245 |
*history
|
246 |
]
|
247 |
-
|
248 |
thinking_message = await sendTelegramMessage(chatId, "正在思考,请等待...", options={'reply_to_message_id': message_id})
|
249 |
thinking_message_id = thinking_message.get('result', {}).get('message_id')
|
250 |
-
|
251 |
-
tools = [
|
252 |
-
{
|
253 |
-
"type": "function",
|
254 |
-
"function": {
|
255 |
-
"name": "get_current_datetime_utc8",
|
256 |
-
"description": "获取当前的日期和时间(UTC+8时区)。",
|
257 |
-
}
|
258 |
-
}
|
259 |
-
]
|
260 |
-
|
261 |
try:
|
262 |
ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
|
263 |
'model': AI_MODEL,
|
264 |
'messages': messages,
|
265 |
'max_tokens': MAX_TOKENS,
|
266 |
'temperature': userTemp,
|
267 |
-
'tools':
|
268 |
-
'tool_choice': 'auto',
|
269 |
})
|
270 |
ai_response.raise_for_status()
|
271 |
ai_data = ai_response.json()
|
272 |
-
ai_reply = await handleAiResponse(ai_data, chatId, history)
|
273 |
-
|
274 |
-
if isinstance(ai_reply, dict) and ai_reply.get('tool_calls'):
|
275 |
-
tool_calls = ai_reply['tool_calls']
|
276 |
-
for tool_call in tool_calls:
|
277 |
-
tool_call_id = tool_call.get('id')
|
278 |
-
function_name = tool_call['function']['name']
|
279 |
-
|
280 |
-
if function_name == 'get_current_datetime_utc8':
|
281 |
-
tool_result = get_current_datetime_utc8()
|
282 |
-
|
283 |
-
messages.append({
|
284 |
-
'tool_call_id': tool_call_id,
|
285 |
-
'role': 'tool',
|
286 |
-
'name': function_name,
|
287 |
-
'content': tool_result
|
288 |
-
})
|
289 |
-
|
290 |
-
ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
|
291 |
-
'model': AI_MODEL,
|
292 |
-
'messages': messages,
|
293 |
-
'max_tokens': MAX_TOKENS,
|
294 |
-
'temperature': userTemp,
|
295 |
-
})
|
296 |
-
ai_response.raise_for_status()
|
297 |
-
ai_data = ai_response.json()
|
298 |
-
ai_reply = await handleAiResponse(ai_data, chatId, history)
|
299 |
-
break
|
300 |
-
|
301 |
history.append({'role': 'assistant', 'content': ai_reply})
|
302 |
chatHistories[chatId] = history
|
303 |
|
@@ -309,16 +285,54 @@ async def processAiMessage(chatId, userMessage, fromUserId, message_id):
|
|
309 |
print(f'处理消息时发生错误: {error}')
|
310 |
await editTelegramMessage(chatId, thinking_message_id, '处理消息时发生错误,请稍后再试')
|
311 |
|
312 |
-
|
|
|
313 |
if ai_data and ai_data.get('choices') and len(ai_data['choices']) > 0:
|
314 |
choice = ai_data['choices'][0]
|
315 |
if choice.get('message'):
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
320 |
return 'AI 返回了无法识别的格式'
|
321 |
|
|
|
322 |
async def handleCallbackQuery(callbackQuery):
|
323 |
chatId = callbackQuery['message']['chat']['id']
|
324 |
data = callbackQuery['data']
|
@@ -370,6 +384,7 @@ async def editTelegramMessage(chatId, message_id, text, options={}):
|
|
370 |
except requests.exceptions.RequestException as e:
|
371 |
print(f'编辑 Telegram 消息失败: {e}')
|
372 |
|
|
|
373 |
def getHelpMessage():
|
374 |
return f"""
|
375 |
可用指令:
|
|
|
4 |
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 |
|
|
|
53 |
]
|
54 |
DEFAULT_TEMP = 1.5
|
55 |
|
56 |
+
# 工具定义
|
57 |
+
TOOLS = [
|
58 |
+
{
|
59 |
+
"type": "function",
|
60 |
+
"function": {
|
61 |
+
"name": "get_current_datetime",
|
62 |
+
"description": "获取当前的日期和时间,并返回UTC+8时区的时间。",
|
63 |
+
"parameters": {
|
64 |
+
"type": "object",
|
65 |
+
"properties": {},
|
66 |
+
"required": []
|
67 |
+
}
|
68 |
+
}
|
69 |
}
|
70 |
+
]
|
71 |
+
|
72 |
+
def get_current_datetime():
|
73 |
+
"""获取当前的日期和时间,并返回UTC+8时区的时间。"""
|
74 |
+
utc_time = datetime.now(timezone.utc)
|
75 |
+
local_time = utc_time.astimezone(timezone(timedelta(hours=8)))
|
76 |
+
return local_time.strftime("%Y-%m-%d %H:%M:%S")
|
77 |
+
|
78 |
|
79 |
def make_telegram_request(method, data=None):
|
80 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
|
|
206 |
command = command.split('@')[0]
|
207 |
return command[1:]
|
208 |
|
209 |
+
|
210 |
async def handlePrivateCommand(chatId, userMessage, fromUserId, isGroupChat):
|
211 |
command = parseCommand(userMessage)
|
212 |
if userMessage.startswith('/settemp '):
|
|
|
258 |
{'role': 'system', 'content': currentPrompt},
|
259 |
*history
|
260 |
]
|
261 |
+
|
262 |
thinking_message = await sendTelegramMessage(chatId, "正在思考,请等待...", options={'reply_to_message_id': message_id})
|
263 |
thinking_message_id = thinking_message.get('result', {}).get('message_id')
|
264 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
265 |
try:
|
266 |
ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
|
267 |
'model': AI_MODEL,
|
268 |
'messages': messages,
|
269 |
'max_tokens': MAX_TOKENS,
|
270 |
'temperature': userTemp,
|
271 |
+
'tools': TOOLS,
|
|
|
272 |
})
|
273 |
ai_response.raise_for_status()
|
274 |
ai_data = ai_response.json()
|
275 |
+
ai_reply = await handleAiResponse(ai_data, chatId, history, thinking_message_id)
|
276 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
277 |
history.append({'role': 'assistant', 'content': ai_reply})
|
278 |
chatHistories[chatId] = history
|
279 |
|
|
|
285 |
print(f'处理消息时发生错误: {error}')
|
286 |
await editTelegramMessage(chatId, thinking_message_id, '处理消息时发生错误,请稍后再试')
|
287 |
|
288 |
+
|
289 |
+
async def handleAiResponse(ai_data, chatId, history, thinking_message_id):
|
290 |
if ai_data and ai_data.get('choices') and len(ai_data['choices']) > 0:
|
291 |
choice = ai_data['choices'][0]
|
292 |
if choice.get('message'):
|
293 |
+
message = choice['message']
|
294 |
+
if message.get('tool_calls'):
|
295 |
+
tool_call = message['tool_calls'][0]
|
296 |
+
function_name = tool_call['function']['name']
|
297 |
+
|
298 |
+
if function_name == 'get_current_datetime':
|
299 |
+
current_datetime = get_current_datetime()
|
300 |
+
history.append({
|
301 |
+
'tool_call_id': tool_call['id'],
|
302 |
+
'role': 'tool',
|
303 |
+
'name': function_name,
|
304 |
+
'content': current_datetime,
|
305 |
+
})
|
306 |
+
messages = [
|
307 |
+
{'role': 'system', 'content': PROMPT_TEMPLATES.get(USER_SETTINGS.get(chatId, {}).get('prompt_index', CURRENT_PROMPT_INDEX), "")},
|
308 |
+
*history
|
309 |
+
]
|
310 |
+
|
311 |
+
try:
|
312 |
+
ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
|
313 |
+
'model': AI_MODEL,
|
314 |
+
'messages': messages,
|
315 |
+
'max_tokens': MAX_TOKENS,
|
316 |
+
'temperature': USER_SETTINGS.get(chatId, {}).get('temperature', DEFAULT_TEMP),
|
317 |
+
'tools': TOOLS,
|
318 |
+
})
|
319 |
+
ai_response.raise_for_status()
|
320 |
+
ai_data = ai_response.json()
|
321 |
+
return await handleAiResponse(ai_data, chatId, history, thinking_message_id)
|
322 |
+
except requests.exceptions.RequestException as e:
|
323 |
+
print(f'AI API 响应失败: {e}')
|
324 |
+
await editTelegramMessage(chatId, thinking_message_id, 'AI API 响应失败,请稍后再试')
|
325 |
+
return 'AI API 响应失败,请稍后再试'
|
326 |
+
|
327 |
+
|
328 |
+
else:
|
329 |
+
return '不支持的工具调用'
|
330 |
+
elif message.get('content'):
|
331 |
+
return message['content']
|
332 |
+
|
333 |
return 'AI 返回了无法识别的格式'
|
334 |
|
335 |
+
|
336 |
async def handleCallbackQuery(callbackQuery):
|
337 |
chatId = callbackQuery['message']['chat']['id']
|
338 |
data = callbackQuery['data']
|
|
|
384 |
except requests.exceptions.RequestException as e:
|
385 |
print(f'编辑 Telegram 消息失败: {e}')
|
386 |
|
387 |
+
|
388 |
def getHelpMessage():
|
389 |
return f"""
|
390 |
可用指令:
|