llm_tasks.py
13.4 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"""LLM 异步调用 Celery 任务 — 消费队列 → 调适配器 → 写结果 → 更新状态"""
import asyncio
import logging
from datetime import datetime
from typing import Optional
from celery import Task
from sqlalchemy import select
from app.celery_app import celery_app
from app.core.config import settings
from app.core.database import async_session_factory
from app.models.async_task import AsyncTask
from app.models.call_record import CallRecord
from app.models.account import ModelAccountConfig
from app.models.provider import ModelProvider
from app.services import prompt_renderer, account_matcher
from app.services.adapter import AdapterError
from app.services.adapter_service import invoke_model as adapter_invoke
logger = logging.getLogger(__name__)
MAX_RETRIES = settings.CELERY_MAX_RETRIES
STUCK_TIMEOUT_SECONDS = 600 # 10 分钟无更新则认为卡住
async def _mark_task_failed(async_task_id: str, error: str):
"""将异步任务标记为失败(用于 Celery 重试耗尽后的最终回调)"""
async with async_session_factory() as db:
result = await db.execute(
select(AsyncTask).where(AsyncTask.id == async_task_id)
)
task = result.scalar_one_or_none()
if not task or task.status in ("success", "cancelled"):
return
task.status = "failed"
task.error_message = error
task.progress = 100
task.completed_at = datetime.now()
# 同步更新 call_record
call_result = await db.execute(
select(CallRecord).where(CallRecord.id == task.call_record_id)
)
call_record = call_result.scalar_one_or_none()
if call_record and call_record.status not in ("success", "failed"):
call_record.status = "failed"
if not call_record.response_body:
call_record.response_body = {"error": error}
await db.commit()
logger.info(f"任务最终标记为失败: task_id={async_task_id}")
class LLMCallTask(Task):
"""LLM 调用任务的 Celery Task 基类 — 自动重试 + 重试耗尽后更新 DB"""
autoretry_for = (Exception,)
max_retries = MAX_RETRIES
retry_backoff = True
retry_backoff_max = 300 # 最大退避间隔 5 分钟
retry_jitter = True
def on_failure(self, exc, task_id, args, kwargs, einfo):
"""Celery 重试全部耗尽后调用 — 将 DB 状态标记为 failed
此时 Celery 不会再重试,这是最终回调。
"""
async_task_id = args[0] if args else None
if not async_task_id:
logger.error(f"on_failure 无法获取 async_task_id: task_id={task_id}")
return
try:
asyncio.run(_mark_task_failed(async_task_id, str(exc)))
except Exception as e:
logger.error(f"on_failure 更新 DB 失败: task_id={async_task_id}, error={e}")
async def _process_call(async_task_id: str) -> dict:
"""核心处理逻辑(异步)"""
async with async_session_factory() as db:
# 1. 加载异步任务
result = await db.execute(
select(AsyncTask).where(AsyncTask.id == async_task_id)
)
task = result.scalar_one_or_none()
if not task:
raise ValueError(f"异步任务不存在: {async_task_id}")
# 检查是否已被取消
if task.status == "cancelled":
logger.info(f"任务已被取消,跳过: {async_task_id}")
return {"status": "cancelled", "task_id": async_task_id}
# 标记为 processing
task.status = "processing"
task.progress = 10
await db.flush()
# 2. 加载调用记录
call_result = await db.execute(
select(CallRecord).where(CallRecord.id == task.call_record_id)
)
call_record = call_result.scalar_one_or_none()
if not call_record:
raise ValueError(f"调用记录不存在: {task.call_record_id}")
# 3. 加载账号信息
account_result = await db.execute(
select(ModelAccountConfig).where(ModelAccountConfig.id == call_record.account_id)
)
account = account_result.scalar_one_or_none()
if not account:
raise ValueError(f"账号不存在: {call_record.account_id}")
provider_result = await db.execute(
select(ModelProvider).where(ModelProvider.id == account.provider_id)
)
provider = provider_result.scalar_one_or_none()
if not provider:
raise ValueError(f"供应商不存在: {account.provider_id}")
# 4. 调用适配器引擎(复用 adapter_invoke,system_prompt 单独传参)
task.progress = 30
await db.flush()
start_time = datetime.now()
# 从 request_body 中提取参数
request_body = call_record.request_body or {}
messages = request_body.get("messages", [])
system_prompt = request_body.get("system_prompt")
try:
llm_response = await adapter_invoke(
db=db,
account_id=account.id,
model_name=call_record.model_name,
messages=messages,
system_prompt=system_prompt,
)
except AdapterError as e:
logger.error(f"适配器调用失败: task_id={async_task_id}, error={e}, status_code={e.status_code}")
# 4xx 客户端错误(如参数错误、角色无效)— 重试也无法成功,直接标记失败
if 400 <= e.status_code < 500:
call_record.status = "failed"
call_record.response_body = {"error": str(e)}
task.status = "failed"
task.error_message = str(e)
task.progress = 100
task.completed_at = datetime.now()
await db.commit()
logger.info(f"客户端错误,任务直接标记为失败: task_id={async_task_id}, status_code={e.status_code}")
return {"status": "failed", "task_id": async_task_id, "error": str(e)}
# 5xx/网络错误 — 让 Celery 自动重试
raise
except Exception as e:
logger.error(f"适配器调用失败: task_id={async_task_id}, error={e}")
# 其他异常 — 让 Celery 自动重试
# 重试耗尽后由 LLMCallTask.on_failure 回调标记为 failed
raise
# 5. 更新调用记录
duration_ms = int((datetime.now() - start_time).total_seconds() * 1000)
if llm_response.success:
call_record.status = "success"
# 处理 content:剥离 markdown 标记后解析为 Python 对象,存 DB
stripped = prompt_renderer.strip_markdown_code_block(llm_response.content)
parsed = prompt_renderer.parse_json_response(llm_response.content)
# response_body 统一存放处理后的内容,结构固定为 {"content": ...}
call_record.response_body = {
"content": parsed,
}
# 额外保留 raw_response,但不影响 response_content 提取
if llm_response.raw_response:
call_record.response_body["_raw"] = llm_response.raw_response
else:
call_record.status = "failed"
call_record.response_body = {"error": llm_response.error_message}
call_record.prompt_tokens = llm_response.prompt_tokens
call_record.completion_tokens = llm_response.completion_tokens
call_record.total_tokens = llm_response.total_tokens
call_record.duration_ms = duration_ms
# 6. 更新任务状态
task.status = "success" if llm_response.success else "failed"
task.progress = 100
task.completed_at = datetime.now()
task.result = llm_response.raw_response
await db.flush()
await db.commit()
logger.info(
f"异步任务处理完成: task_id={async_task_id}, "
f"status={task.status}, tokens={llm_response.total_tokens}, "
f"duration={duration_ms}ms"
)
return {
"status": task.status,
"task_id": async_task_id,
"call_record_id": call_record.id,
"total_tokens": llm_response.total_tokens,
"duration_ms": duration_ms,
}
# 每个 Celery prefork 子进程独立持有的事件循环(进程隔离,无需加锁)
_process_loop: asyncio.AbstractEventLoop | None = None
def _run_async(coro):
"""在进程持久化的事件循环中运行协程,避免 ``asyncio.run()`` 每次建新循环导致连接跨循环复用。"""
global _process_loop
if _process_loop is None or _process_loop.is_closed():
_process_loop = asyncio.new_event_loop()
asyncio.set_event_loop(_process_loop)
return _process_loop.run_until_complete(coro)
@celery_app.task(
bind=True,
base=LLMCallTask,
name="app.tasks.llm_tasks.process_async_llm_call",
)
def process_async_llm_call(self, async_task_id: str) -> dict:
"""处理异步 LLM 调用
Celery 任务入口。从数据库加载任务配置 → 调用 F-09 适配引擎 →
写入结果 → 更新 F-04 状态。
Args:
async_task_id: AsyncTask 表的 id
"""
logger.info(f"开始处理异步任务: async_task_id={async_task_id}")
try:
result = _run_async(_process_call(async_task_id))
logger.info(f"异步任务处理成功: {result}")
return result
except Exception as exc:
logger.error(f"异步任务处理失败: async_task_id={async_task_id}, error={exc}")
raise self.retry(exc=exc)
async def _rescan_stuck() -> list[dict]:
"""扫描并重新提交卡住的任务
扫描条件:
- "processing" 超过 STUCK_TIMEOUT_SECONDS(10 分钟)未更新 → 卡住
- "pending" 超过 5 分钟未被 Worker 消费 → 可能丢失在队列中
"""
async with async_session_factory() as db:
now = datetime.now()
re_queued = []
# 1. 扫描 stuck processing 任务
timeout_dt = datetime.fromtimestamp(now.timestamp() - STUCK_TIMEOUT_SECONDS)
result = await db.execute(
select(AsyncTask).where(
AsyncTask.status == "processing",
AsyncTask.updated_at < timeout_dt,
)
)
stuck_tasks = result.scalars().all()
for task in stuck_tasks:
logger.warning(f"发现卡住任务(processing超时),重新提交: task_id={task.id}")
task.status = "pending"
task.progress = 0
await db.flush()
process_async_llm_call.delay(task.id)
re_queued.append({
"task_id": task.id,
"call_record_id": task.call_record_id,
})
# 2. 扫描 stale pending 任务(提交后 5 分钟仍未被消费)
pending_timeout_dt = datetime.fromtimestamp(now.timestamp() - 300)
result = await db.execute(
select(AsyncTask).where(
AsyncTask.status == "pending",
AsyncTask.celery_task_id != "",
AsyncTask.updated_at < pending_timeout_dt,
)
)
stale_tasks = result.scalars().all()
for task in stale_tasks:
logger.warning(f"发现队列丢失任务(pending超时),重新提交: task_id={task.id}")
task.progress = 0
await db.flush()
process_async_llm_call.delay(task.id)
re_queued.append({
"task_id": task.id,
"call_record_id": task.call_record_id,
})
if re_queued:
logger.info(f"重新提交卡住/丢失任务: count={len(re_queued)}")
else:
logger.debug("未发现卡住或丢失任务")
await db.commit()
return re_queued
@celery_app.task(
name="app.tasks.llm_tasks.rescan_stuck_tasks",
)
def rescan_stuck_tasks() -> list[dict]:
"""扫描卡住的任务并重新提交(Celery Beat 定时触发)"""
logger.info("开始扫描卡住任务...")
try:
result = _run_async(_rescan_stuck())
return result
except Exception as e:
logger.error(f"扫描卡住任务失败: {e}")
return []
@celery_app.task(
name="app.tasks.llm_tasks.archive_expired_logs",
)
def archive_expired_logs() -> dict:
"""归档超期日志文件(Celery Beat 定时触发)"""
logger.info("开始归档超期日志...")
try:
from app.services.log_storage_service import archive_expired_logs as _do_archive
archived = _do_archive()
logger.info(f"日志归档完成: archived_count={archived}")
return {"archived_count": archived}
except Exception as e:
logger.error(f"日志归档失败: {e}")
return {"archived_count": 0, "error": str(e)}
@celery_app.task(
name="app.tasks.llm_tasks.aggregate_call_stats",
)
def aggregate_call_stats() -> dict:
"""每小时聚合:计算上一小时调用统计数据(Celery Beat 定时触发)"""
logger.info("开始每小时聚合统计...")
try:
from app.services.statistics_service import aggregate_hourly
async def _run():
async with async_session_factory() as db:
await aggregate_hourly(db)
await db.commit()
_run_async(_run())
logger.info("每小时聚合统计完成")
return {"status": "ok", "agg_type": "hourly"}
except Exception as e:
logger.error(f"每小时聚合统计失败: {e}")
return {"status": "error", "error": str(e)}