Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,7 @@ import os
|
|
| 2 |
import json
|
| 3 |
import requests
|
| 4 |
from flask import Flask, request, jsonify
|
| 5 |
-
from datetime import datetime
|
| 6 |
import asyncio
|
| 7 |
|
| 8 |
app = Flask(__name__)
|
|
@@ -52,6 +52,17 @@ BOT_COMMANDS = [
|
|
| 52 |
]
|
| 53 |
DEFAULT_TEMP = 1.5
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
def make_telegram_request(method, data=None):
|
| 56 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
| 57 |
if PHP_PROXY_URL:
|
|
@@ -182,7 +193,6 @@ def parseCommand(userMessage):
|
|
| 182 |
command = command.split('@')[0]
|
| 183 |
return command[1:]
|
| 184 |
|
| 185 |
-
|
| 186 |
async def handlePrivateCommand(chatId, userMessage, fromUserId, isGroupChat):
|
| 187 |
command = parseCommand(userMessage)
|
| 188 |
if userMessage.startswith('/settemp '):
|
|
@@ -237,18 +247,57 @@ async def processAiMessage(chatId, userMessage, fromUserId, message_id):
|
|
| 237 |
|
| 238 |
thinking_message = await sendTelegramMessage(chatId, "正在思考,请等待...", options={'reply_to_message_id': message_id})
|
| 239 |
thinking_message_id = thinking_message.get('result', {}).get('message_id')
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
try:
|
| 242 |
ai_response = requests.post(AI_API_ENDPOINT, headers=AI_API_HEADERS, json={
|
| 243 |
'model': AI_MODEL,
|
| 244 |
'messages': messages,
|
| 245 |
'max_tokens': MAX_TOKENS,
|
| 246 |
'temperature': userTemp,
|
|
|
|
|
|
|
| 247 |
})
|
| 248 |
ai_response.raise_for_status()
|
| 249 |
ai_data = ai_response.json()
|
| 250 |
ai_reply = await handleAiResponse(ai_data, chatId, history)
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
history.append({'role': 'assistant', 'content': ai_reply})
|
| 253 |
chatHistories[chatId] = history
|
| 254 |
|
|
@@ -263,8 +312,11 @@ async def processAiMessage(chatId, userMessage, fromUserId, message_id):
|
|
| 263 |
async def handleAiResponse(ai_data, chatId, history):
|
| 264 |
if ai_data and ai_data.get('choices') and len(ai_data['choices']) > 0:
|
| 265 |
choice = ai_data['choices'][0]
|
| 266 |
-
if choice.get('message')
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
| 268 |
return 'AI 返回了无法识别的格式'
|
| 269 |
|
| 270 |
async def handleCallbackQuery(callbackQuery):
|
|
@@ -318,7 +370,6 @@ async def editTelegramMessage(chatId, message_id, text, options={}):
|
|
| 318 |
except requests.exceptions.RequestException as e:
|
| 319 |
print(f'编辑 Telegram 消息失败: {e}')
|
| 320 |
|
| 321 |
-
|
| 322 |
def getHelpMessage():
|
| 323 |
return f"""
|
| 324 |
可用指令:
|
|
|
|
| 2 |
import json
|
| 3 |
import requests
|
| 4 |
from flask import Flask, request, jsonify
|
| 5 |
+
from datetime import datetime, timezone, timedelta
|
| 6 |
import asyncio
|
| 7 |
|
| 8 |
app = Flask(__name__)
|
|
|
|
| 52 |
]
|
| 53 |
DEFAULT_TEMP = 1.5
|
| 54 |
|
| 55 |
+
def get_current_datetime_utc8():
|
| 56 |
+
utc_plus_8 = timezone(timedelta(hours=8))
|
| 57 |
+
now = datetime.now(utc_plus_8)
|
| 58 |
+
return now.strftime("%Y年%m月%d日 %H时%M分%S秒")
|
| 59 |
+
|
| 60 |
+
TOOL_DEFINITIONS = {
|
| 61 |
+
"get_current_datetime_utc8": {
|
| 62 |
+
"description": "获取当前的日期和时间(UTC+8时区)。",
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
def make_telegram_request(method, data=None):
|
| 67 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
| 68 |
if PHP_PROXY_URL:
|
|
|
|
| 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 '):
|
|
|
|
| 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': 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 |
|
|
|
|
| 312 |
async def handleAiResponse(ai_data, chatId, history):
|
| 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 |
+
if choice['message'].get('content'):
|
| 317 |
+
return choice['message']['content']
|
| 318 |
+
elif choice['message'].get('tool_calls'):
|
| 319 |
+
return {'tool_calls': choice['message']['tool_calls']}
|
| 320 |
return 'AI 返回了无法识别的格式'
|
| 321 |
|
| 322 |
async def handleCallbackQuery(callbackQuery):
|
|
|
|
| 370 |
except requests.exceptions.RequestException as e:
|
| 371 |
print(f'编辑 Telegram 消息失败: {e}')
|
| 372 |
|
|
|
|
| 373 |
def getHelpMessage():
|
| 374 |
return f"""
|
| 375 |
可用指令:
|