orchestration.py
5.12 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
"""LLM 调用编排 API 路由"""
import json
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.schemas.orchestration import (
OrchestrateSyncRequest,
OrchestrateAsyncRequest,
BatchQueryRequest,
)
from app.services import orchestration_service
from app.services import adapter_service
from app.services.adapter import LLMRequest, LLMResponse, AdapterError, create_adapter
from app.services.adapter.base import Message
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/calls/orchestrate", tags=["调用编排"])
class StreamCallRequest(BaseModel):
model_name: str = Field(..., description="模型名称", max_length=100)
messages: list[dict] = Field(default_factory=list, description="消息列表")
system_prompt: Optional[str] = Field(None, description="系统提示词")
temperature: Optional[float] = Field(None, ge=0, le=2, description="Temperature 参数")
max_tokens: Optional[int] = Field(None, ge=1, le=32768, description="Max Tokens 参数")
thinking_enabled: Optional[bool] = Field(None, description="是否启用思考模式(None 则使用账号配置)")
model_config = {"protected_namespaces": ()}
@router.post("/sync")
async def sync_call(data: OrchestrateSyncRequest, db: AsyncSession = Depends(get_db)):
"""同步调用 LLM"""
try:
result = await orchestration_service.orchestrate_sync(db, data)
return result
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.error(f"同步调用异常: {e}")
raise HTTPException(status_code=500, detail="内部错误")
@router.post("/async", status_code=202)
async def async_call(data: OrchestrateAsyncRequest, db: AsyncSession = Depends(get_db)):
"""异步调用 LLM(创建任务后立即返回)"""
try:
result = await orchestration_service.orchestrate_async(db, data)
return result
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.error(f"异步调用异常: {e}")
raise HTTPException(status_code=500, detail="内部错误")
@router.get("/async")
async def get_async_result(task_id: str = Query(..., description="异步任务 ID"), db: AsyncSession = Depends(get_db)):
"""查询异步调用结果"""
result = await orchestration_service.get_async_result(db, task_id)
if not result:
raise HTTPException(status_code=404, detail="任务不存在")
return result
@router.post("/async/batch")
async def batch_query(data: BatchQueryRequest, db: AsyncSession = Depends(get_db)):
"""批量查询异步结果"""
results = await orchestration_service.batch_query_tasks(db, data.task_ids)
return {"results": results}
@router.post("/stream")
async def stream_call(data: StreamCallRequest, db: AsyncSession = Depends(get_db)):
"""流式调用 LLM(SSE 逐 token 返回)"""
try:
# 在请求上下文中解析账号和适配器
account = await orchestration_service._match_account(db, data.model_name)
if not account:
raise HTTPException(status_code=404, detail=f"模型 {data.model_name} 无可用账号")
# 构建 LLMRequest
request = LLMRequest(
model=data.model_name,
messages=[Message(**m) for m in data.messages] if data.messages else [],
system_prompt=data.system_prompt,
temperature=data.temperature,
max_tokens=data.max_tokens,
)
async def event_stream():
try:
async for chunk in adapter_service.invoke_model_stream(
db=db,
account_id=account["id"],
model_name=data.model_name,
messages=data.messages,
system_prompt=data.system_prompt,
temperature=data.temperature,
max_tokens=data.max_tokens,
thinking_enabled=data.thinking_enabled,
):
# chunk 为结构化 dict: {"type": "reasoning", "content": "..."}
# 或 {"type": "content", "content": "..."}
yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
yield "data: [DONE]\n\n"
except Exception as e:
logger.error(f"流式调用异常: {e}")
yield f"data: {json.dumps({'error': str(e)}, ensure_ascii=False)}\n\n"
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
except HTTPException:
raise
except Exception as e:
logger.error(f"流式调用初始化异常: {e}")
raise HTTPException(status_code=500, detail="内部错误")