-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai_service.py
More file actions
78 lines (72 loc) · 2.78 KB
/
ai_service.py
File metadata and controls
78 lines (72 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import base64
import logging
from openai import AsyncOpenAI
from config import KIMI_CODE_API_KEY, KIMI_CODE_BASE_URL, KIMI_CODE_MODEL, DEEPSEEK_API_KEY
from prompts import build_system_prompt
client = AsyncOpenAI(
api_key=KIMI_CODE_API_KEY,
base_url=KIMI_CODE_BASE_URL,
timeout=60.0,
max_retries=1
)
ds_client = AsyncOpenAI(
api_key=DEEPSEEK_API_KEY,
base_url="https://api.deepseek.com",
timeout=60.0,
max_retries=1
)
async def generate_response(user_text: str) -> str:
# Primary: DeepSeek Reasoner (stable, fast, thinking mode)
try:
response = await ds_client.chat.completions.create(
model="deepseek-reasoner",
messages=[
{"role": "system", "content": build_system_prompt()},
{"role": "user", "content": user_text}
]
)
return response.choices[0].message.content.strip()
except Exception as e:
logging.warning(f"DeepSeek API Failed: {e}. Falling back to Kimi K2.5...")
# Fallback: Kimi K2.5
try:
response = await client.chat.completions.create(
model=KIMI_CODE_MODEL,
messages=[
{"role": "system", "content": build_system_prompt()},
{"role": "user", "content": user_text}
]
)
return response.choices[0].message.content.strip()
except Exception as e:
logging.error(f"Kimi Fallback also failed: {e}")
return "Извините, у меня небольшие неполадки со связью (оба сервера перегружены). Нажмите кнопку оплаты или попробуйте позже."
async def analyze_slip(image_bytes: bytes) -> bool:
try:
base64_image = base64.b64encode(image_bytes).decode('utf-8')
response = await client.chat.completions.create(
model=KIMI_CODE_MODEL,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Analyze this Thai bank slip. Does it show a successful transfer of exactly 3000 THB? Answer strictly YES or NO."
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
]
)
answer = response.choices[0].message.content.strip().upper()
return "YES" in answer
except Exception as e:
error_msg = str(e) or repr(e)
logging.error(f"Kimi Vision API Error: {error_msg}")
return False