feat(api): Synchronize history and summary from DB in chat stream

This commit is contained in:
Yunxiao Xu
2026-02-15 04:11:42 -08:00
parent 398aad4280
commit 5b9d644fe5
2 changed files with 95 additions and 4 deletions

View File

@@ -7,10 +7,12 @@ from ea_chatbot.api.utils import convert_to_json_compatible
from ea_chatbot.graph.workflow import app
from ea_chatbot.graph.checkpoint import get_checkpointer
from ea_chatbot.history.models import User as UserDB, Conversation
from ea_chatbot.history.utils import map_db_messages_to_langchain
from ea_chatbot.api.schemas import ChatRequest
import io
import base64
from langchain_core.runnables.config import RunnableConfig
from langchain_core.messages import BaseMessage
router = APIRouter(prefix="/chat", tags=["agent"])
@@ -18,14 +20,15 @@ async def stream_agent_events(
message: str,
thread_id: str,
user_id: str,
summary: str
summary: str,
messages: List[BaseMessage] = []
) -> AsyncGenerator[str, None]:
"""
Generator that invokes the LangGraph agent and yields SSE formatted events.
Persists assistant responses and plots to the database.
"""
initial_state = {
"messages": [],
"messages": messages,
"question": message,
"summary": summary,
"analysis": None,
@@ -149,8 +152,16 @@ async def chat_stream(
raise HTTPException(status_code=404, detail="Conversation not found")
if conv.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized to access this conversation")
# Load existing summary from DB if not provided in request
db_summary = conv.summary or ""
# Save user message immediately
# Load last 10 messages for context (BEFORE saving the current user message)
# This ensures we don't include the current message twice if the graph reduces it.
db_messages = history_manager.get_messages_by_window(request.thread_id, window_size=10)
lc_messages = map_db_messages_to_langchain(db_messages)
# Save user message immediately to DB
history_manager.add_message(request.thread_id, "user", request.message)
return StreamingResponse(
@@ -158,7 +169,8 @@ async def chat_stream(
request.message,
request.thread_id,
current_user.id,
request.summary or ""
db_summary,
lc_messages
),
media_type="text/event-stream"
)