2026-07-26 07:25:24 +08:00
|
|
|
"""FastGPT client and chat backend dependency injection."""
|
2026-01-08 16:22:25 +08:00
|
|
|
from contextlib import asynccontextmanager
|
|
|
|
|
from fastapi import FastAPI
|
|
|
|
|
from fastgpt_client import AsyncChatClient
|
2026-07-26 07:25:24 +08:00
|
|
|
from ..backends.chat import ChatBackend
|
|
|
|
|
from ..backends.fastgpt import FastGPTBackend
|
2026-01-08 16:22:25 +08:00
|
|
|
from .config import Config
|
|
|
|
|
|
2026-07-28 08:41:34 +08:00
|
|
|
|
2026-01-08 16:22:25 +08:00
|
|
|
_fastgpt_client: AsyncChatClient | None = None
|
2026-07-26 07:25:24 +08:00
|
|
|
_chat_backend: ChatBackend | None = None
|
2026-01-08 16:22:25 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@asynccontextmanager
|
|
|
|
|
async def lifespan(app: FastAPI):
|
|
|
|
|
"""Manage FastGPT client lifecycle."""
|
2026-07-26 07:25:24 +08:00
|
|
|
global _chat_backend, _fastgpt_client
|
2026-01-08 16:22:25 +08:00
|
|
|
Config.validate()
|
2026-07-28 08:41:34 +08:00
|
|
|
|
2026-01-08 16:22:25 +08:00
|
|
|
_fastgpt_client = AsyncChatClient(
|
|
|
|
|
api_key=Config.FASTGPT_API_KEY,
|
|
|
|
|
base_url=Config.FASTGPT_BASE_URL,
|
|
|
|
|
timeout=60.0,
|
|
|
|
|
max_retries=3,
|
|
|
|
|
retry_delay=1.0,
|
|
|
|
|
enable_logging=Config.DEBUG,
|
|
|
|
|
)
|
|
|
|
|
await _fastgpt_client.__aenter__()
|
2026-07-26 07:25:24 +08:00
|
|
|
_chat_backend = FastGPTBackend(_fastgpt_client)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
yield
|
|
|
|
|
finally:
|
|
|
|
|
_chat_backend = None
|
|
|
|
|
if _fastgpt_client:
|
|
|
|
|
await _fastgpt_client.__aexit__(None, None, None)
|
|
|
|
|
_fastgpt_client = None
|
2026-01-08 16:22:25 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_fastgpt_client() -> AsyncChatClient:
|
2026-07-28 10:38:01 +08:00
|
|
|
"""Get the initialized FastGPT client."""
|
2026-01-08 16:22:25 +08:00
|
|
|
if _fastgpt_client is None:
|
|
|
|
|
raise RuntimeError("FastGPT client not initialized")
|
|
|
|
|
return _fastgpt_client
|
2026-07-26 07:25:24 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_chat_backend() -> ChatBackend:
|
|
|
|
|
"""Get the backend-neutral chat service."""
|
|
|
|
|
if _chat_backend is None:
|
|
|
|
|
raise RuntimeError("Chat backend not initialized")
|
|
|
|
|
return _chat_backend
|