feat: 公司支持多模型提供商与会话消歧选型

This commit is contained in:
2026-09-20 16:35:06 +08:00
parent d7e4a987c1
commit 9350323ff2
30 changed files with 1031 additions and 448 deletions
+11 -3
View File
@@ -14,17 +14,22 @@ logger = logging.getLogger(__name__)
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
"""GET /api/internal/agent/llm-runtime?companyId=&model=(Agent Bearer)。"""
"""GET /api/internal/agent/llm-runtime?companyId=&providerId=&model=。"""
def __init__(self, settings: Settings) -> None:
self._settings = settings
async def fetch(
self, company_id: int, model: str | None = None
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None:
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
params: dict[str, str | int] = {"companyId": company_id}
if provider_id is not None:
params["providerId"] = provider_id
if model:
params["model"] = model
try:
@@ -37,10 +42,12 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
data = body.get("data") if isinstance(body, dict) else None
if not isinstance(data, dict):
return None
pid = data.get("providerId")
return LlmRuntimeConfig(
base_url=str(data.get("baseUrl") or "").rstrip("/"),
api_key=str(data.get("apiKey") or ""),
model=str(data.get("model") or ""),
provider_id=int(pid) if pid is not None else provider_id,
extra_headers={
str(k): str(v)
for k, v in (data.get("extraHeaders") or {}).items()
@@ -49,8 +56,9 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
)
except Exception:
logger.exception(
"拉取 Server LLM runtime 失败 company_id=%s model=%s",
"拉取 Server LLM runtime 失败 company_id=%s provider_id=%s model=%s",
company_id,
provider_id,
model,
)
return None
@@ -27,6 +27,15 @@ def _dt(v: Any) -> datetime:
return datetime.utcnow()
def _optional_int(v: Any) -> int | None:
if v is None:
return None
try:
return int(v)
except (TypeError, ValueError):
return None
class MongoSessionRepository(SessionRepository):
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._col = db.agent_sessions
@@ -39,6 +48,7 @@ class MongoSessionRepository(SessionRepository):
"title": session.title,
"status": session.status.value,
"summary": session.summary,
"llm_provider_id": session.llm_provider_id,
"llm_model": session.llm_model,
"created_at": session.created_at,
"updated_at": session.updated_at,
@@ -80,6 +90,7 @@ class MongoSessionRepository(SessionRepository):
"title": session.title,
"status": session.status.value,
"summary": session.summary,
"llm_provider_id": session.llm_provider_id,
"llm_model": session.llm_model,
"updated_at": session.updated_at,
"last_message_at": session.last_message_at,
@@ -97,6 +108,7 @@ class MongoSessionRepository(SessionRepository):
title=doc.get("title") or "新对话",
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
summary=doc.get("summary"),
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
llm_model=doc.get("llm_model"),
created_at=_dt(doc.get("created_at")),
updated_at=_dt(doc.get("updated_at")),
@@ -1,4 +1,4 @@
"""Redis 缓存租户 LLM 运行时配置(按公司+模型)。"""
"""Redis 缓存租户 LLM 运行时配置(按公司+提供商+模型)。"""
from __future__ import annotations
@@ -16,18 +16,23 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
self._r = client
@staticmethod
def _key(company_id: int, model: str | None) -> str:
def _key(company_id: int, provider_id: int | None, model: str | None) -> str:
if provider_id is not None and model:
return f"agent:llm:rt:{company_id}:{provider_id}:{model}"
if model:
return f"agent:llm:rt:{company_id}:{model}"
return f"agent:llm:rt:{company_id}"
async def get(
self, company_id: int, model: str | None = None
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None:
raw = await self._r.get(self._key(company_id, model))
if not raw and model:
# 兼容旧缓存键(仅 companyId)
raw = await self._r.get(self._key(company_id, None))
raw = await self._r.get(self._key(company_id, provider_id, model))
if not raw and provider_id is not None and model:
# 兼容旧键 companyId:model
raw = await self._r.get(self._key(company_id, None, model))
if not raw:
return None
data = json.loads(raw)
@@ -35,11 +40,14 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
base_url=data["base_url"],
api_key=data["api_key"],
model=data["model"],
provider_id=_optional_int(data.get("provider_id")) or provider_id,
extra_headers=data.get("extra_headers") or {},
context_window=_optional_int(data.get("context_window")),
)
if model and cfg.model and cfg.model != model:
return None
if provider_id is not None and cfg.provider_id is not None and cfg.provider_id != provider_id:
return None
return cfg
async def set(
@@ -47,10 +55,9 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
model: str | None = None,
) -> None:
key_model = model or config.model
payload = {
"provider_id": config.provider_id,
"base_url": config.base_url,
"api_key": config.api_key,
"model": config.model,
@@ -58,15 +65,12 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
"context_window": config.context_window,
}
await self._r.set(
self._key(company_id, key_model),
self._key(company_id, config.provider_id, config.model),
json.dumps(payload),
ex=ttl_seconds,
)
async def delete(self, company_id: int, model: str | None = None) -> None:
if model:
await self._r.delete(self._key(company_id, model))
return
async def delete(self, company_id: int) -> None:
keys = await self._r.keys(f"agent:llm:rt:{company_id}*")
if keys:
await self._r.delete(*keys)