mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2026-11-01 01:24:45 +03:00
feat: refactor ChatSessionManager to be application-specific and integrate httpx2 for websocket transport
This commit is contained in:
+1
-1
@@ -100,7 +100,7 @@ async def chat_websocket(websocket: WebSocket) -> None:
|
||||
await websocket.accept()
|
||||
|
||||
agent: ChatAgent = websocket.app.chat_agent
|
||||
session_manager: ChatSessionManager = ChatSessionManager()
|
||||
session_manager: ChatSessionManager = websocket.app.state.chat_sessions
|
||||
session = await session_manager.create()
|
||||
|
||||
await websocket.send_json(Connected(session_id=session.id).model_dump(mode="json"))
|
||||
|
||||
+3
-4
@@ -22,6 +22,7 @@ from app.middleware.profiler import ProfilingMiddleware
|
||||
from app.redis import get_redis
|
||||
from app.services.auth import AuthBearer
|
||||
from app.services.chat_agent import build_chat_agent
|
||||
from app.services.chat_session import ChatSessionManager
|
||||
from app.services.scheduler import scheduler_lifespan
|
||||
|
||||
templates = Jinja2Templates(directory=Path(__file__).parent.parent / "templates")
|
||||
@@ -32,11 +33,9 @@ async def lifespan(app: FastAPI):
|
||||
app.logger = get_logger()
|
||||
app.redis = await get_redis()
|
||||
global_settings.postgres_url.unicode_string()
|
||||
# Chat service: initialize the pluggable model-client adapter. The session
|
||||
# manager is now a singleton and will be auto-instantiated on first access.
|
||||
# See app/services/chat_agent.py to swap the local stub for a real model
|
||||
# client (OpenAI, Ollama, etc.).
|
||||
# Initialize the chat agent and per-application session registry.
|
||||
app.chat_agent = build_chat_agent(global_settings.chat)
|
||||
app.state.chat_sessions = ChatSessionManager()
|
||||
try:
|
||||
# app.postgres_pool = await asyncpg.create_pool(
|
||||
# dsn=postgres_dsn,
|
||||
|
||||
@@ -13,7 +13,6 @@ from uuid import UUID, uuid4
|
||||
import attrs
|
||||
|
||||
from app.schemas.chat import ChatMessage
|
||||
from app.utils.singleton import SingletonMetaNoArgs
|
||||
|
||||
|
||||
@attrs.define(slots=True)
|
||||
@@ -28,11 +27,11 @@ class ChatSession:
|
||||
return list(self.messages)
|
||||
|
||||
|
||||
class ChatSessionManager(metaclass=SingletonMetaNoArgs):
|
||||
class ChatSessionManager:
|
||||
"""Tracks active chat sessions keyed by their opaque session id.
|
||||
|
||||
Implemented as a singleton to ensure exactly one instance per application,
|
||||
maintaining a consistent registry of all active websocket chat sessions.
|
||||
Each application lifespan owns its own manager, maintaining a consistent
|
||||
registry of active websocket chat sessions for that application.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
|
||||
Reference in New Issue
Block a user