-
Notifications
You must be signed in to change notification settings - Fork 0
Stream reasoning #175
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Stream reasoning #175
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
f728baa
Add agent_stream endpoint
jmsevin 0d007a7
Fix typing issues
jmsevin a75bd24
Fix linter issues
jmsevin 8eef762
Fix test coverage
jmsevin 35570fd
Upgrade qdrant_client to 1.18
jmsevin e0cb403
Remove vectors from tool response
jmsevin 6dba99c
Stream the agent answer content and send processing steps
jmsevin 4188a12
Update AgentResponse model
jmsevin 5ffec23
Update streaming metadata
jmsevin ca0f307
Tests and bugfixes
jmsevin a88cf74
Fix lint issue
jmsevin 7ae4a0d
Remove Summarization Middleware
jmsevin c0ddd6c
Update requirements
jmsevin 1f3d0b5
Remove Git comments
jmsevin 50db994
Fix PR Copilot comments
jmsevin 17b435e
Fix poetry issue
jmsevin c168f58
Fix PR Copilot comments
jmsevin 1179e5a
Fix PR Copilot issue
jmsevin 2b6117f
Fix PR Copilot comments
jmsevin 138c715
Update .env.example
jmsevin cab0c1c
Apply suggestions from code review
jmsevin b0d6045
Refactoring serialization
jmsevin 27c27b1
Fix defaut docs value
jmsevin be6aeec
Fix tests
jmsevin 46997b5
Apply typing suggestion
jmsevin 1316551
Update src/app/api/api_v1/endpoints/chat.py
jmsevin a9e5b55
Factorize code to isolate utils
jmsevin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,203 @@ | ||
| import json | ||
| import uuid | ||
| from typing import Any, AsyncGenerator, cast | ||
| from uuid import UUID | ||
|
|
||
| import psycopg | ||
| from fastapi import BackgroundTasks | ||
| from fastapi.encoders import jsonable_encoder | ||
| from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver | ||
| from psycopg.rows import AsyncRowFactory, DictRow | ||
|
|
||
| from src.app.models import chat as models | ||
| from src.app.search.services.search import SearchService | ||
| from src.app.utils.logger import logger as utils_logger | ||
|
|
||
| logger = utils_logger(__name__) | ||
|
|
||
|
|
||
| def _format_sse_event(data: str) -> str: | ||
| lines = data.splitlines() | ||
| return "".join(f"data: {line}\n" for line in lines) + "\n" | ||
|
|
||
|
|
||
| async def _sse_wrap(stream: Any) -> AsyncGenerator[str, None]: | ||
| async for chunk in stream: | ||
| if isinstance(chunk, str): | ||
| data = chunk | ||
| elif isinstance(chunk, bytes): | ||
| data = chunk.decode("utf-8", errors="replace") | ||
| else: | ||
| data = json.dumps(jsonable_encoder(chunk)) | ||
| yield _format_sse_event(data) | ||
|
|
||
|
|
||
| def _resolve_thread_id(thread_id: UUID | None) -> UUID: | ||
| if thread_id: | ||
| return thread_id | ||
|
|
||
| logger.info("No thread_id provided. Generating new thread_id.") | ||
| return uuid.uuid4() | ||
|
|
||
|
|
||
| def _update_agent_stream_state( | ||
| chunk: dict[str, Any], | ||
| current_final_content: str, | ||
| current_docs: Any, | ||
| ) -> tuple[str, Any]: | ||
| status = chunk.get("status") | ||
| docs = current_docs | ||
| final_content = current_final_content | ||
|
|
||
| if status == "processing" and chunk.get("docs"): | ||
| docs = chunk["docs"] | ||
| elif status == "streaming": | ||
| final_content += cast(str, chunk.get("content", "")) | ||
| elif status == "stop": | ||
| stop_content = cast(str, chunk.get("content", "")) | ||
| if stop_content: | ||
| final_content = stop_content | ||
|
|
||
| return final_content, docs | ||
|
|
||
|
|
||
| def _serialize_agent_stream_chunk(chunk: dict[str, Any]) -> str: | ||
| payload = { | ||
| "content": chunk.get("content"), | ||
| "status": chunk.get("status"), | ||
| "step": chunk.get("step"), | ||
| "label": chunk.get("label"), | ||
| "docs": chunk.get("docs"), | ||
| } | ||
|
|
||
| return json.dumps(jsonable_encoder(payload)) | ||
|
|
||
|
|
||
| async def _stream_agent_with_memory( | ||
| *, | ||
| db_uri: str, | ||
| async_dict_row_factory: AsyncRowFactory[DictRow], | ||
| chatfactory: Any, | ||
| body: models.AgentContext, | ||
| sp: SearchService, | ||
| background_tasks: BackgroundTasks, | ||
| thread_id: UUID, | ||
| ) -> AsyncGenerator[dict[str, Any], None]: | ||
| async with await psycopg.AsyncConnection[DictRow].connect( | ||
| db_uri, | ||
| autocommit=True, | ||
| prepare_threshold=0, | ||
| row_factory=async_dict_row_factory, | ||
| ) as conn: | ||
| await conn.execute("SET SEARCH_PATH to agent_related") | ||
| await conn.commit() | ||
|
|
||
| memory = AsyncPostgresSaver(conn) | ||
| stream = await chatfactory.agent_message( | ||
| query=body.query, | ||
| memory=memory, | ||
| thread_id=thread_id, | ||
| corpora=body.corpora, | ||
| sdg_filter=body.sdg_filter, | ||
| sp=sp, | ||
| background_tasks=background_tasks, | ||
| streamed_ans=True, | ||
| ) | ||
|
|
||
| async for chunk in stream: | ||
| yield chunk | ||
|
|
||
|
|
||
| def _build_final_stream_payload( | ||
| *, | ||
| final_content: str, | ||
| docs: Any, | ||
| thread_id: UUID, | ||
| ) -> dict[str, Any]: | ||
| return { | ||
| "content": final_content, | ||
| "status": "stop", | ||
| "docs": docs, | ||
| "thread_id": thread_id, | ||
| } | ||
|
|
||
|
|
||
| async def _register_stream_chat_data( | ||
| *, | ||
| data_collection: Any, | ||
| session_id: UUID | None, | ||
| user_query: str, | ||
| conversation_id: UUID, | ||
| answer_content: str, | ||
| sources: Any, | ||
| ) -> Any: | ||
| _, message_id = await data_collection.register_chat_data( | ||
| session_id=session_id, | ||
| user_query=user_query, | ||
| conversation_id=conversation_id, | ||
| answer_content=answer_content, | ||
| sources=sources, | ||
| ) | ||
| return message_id | ||
|
|
||
|
|
||
| async def _stream_agent_response( | ||
| *, | ||
| db_uri: str, | ||
| async_dict_row_factory: AsyncRowFactory[DictRow], | ||
| body: models.AgentContext, | ||
| chatfactory: Any, | ||
| sp: SearchService, | ||
| background_tasks: BackgroundTasks, | ||
| data_collection: Any, | ||
| session_id: UUID | None, | ||
| thread_id: UUID, | ||
| ) -> AsyncGenerator[str, None]: | ||
| final_content = "" | ||
| docs = [] | ||
| has_streamed_content = False | ||
|
|
||
| stream = _stream_agent_with_memory( | ||
| db_uri=db_uri, | ||
| async_dict_row_factory=async_dict_row_factory, | ||
| chatfactory=chatfactory, | ||
| body=body, | ||
| sp=sp, | ||
| background_tasks=background_tasks, | ||
| thread_id=thread_id, | ||
| ) | ||
|
|
||
| async for chunk in stream: | ||
| final_content, docs = _update_agent_stream_state(chunk, final_content, docs) | ||
| if chunk.get("status") == "streaming" and chunk.get("content"): | ||
| has_streamed_content = True | ||
| if chunk.get("status") == "stop": | ||
| continue | ||
| try: | ||
| yield _format_sse_event(_serialize_agent_stream_chunk(chunk)) | ||
| except Exception as e: | ||
| logger.error("Error while yielding chunk: %s", e) | ||
|
|
||
| final_payload = _build_final_stream_payload( | ||
| final_content=final_content, | ||
| docs=docs, | ||
| thread_id=thread_id, | ||
| ) | ||
|
|
||
| if has_streamed_content: | ||
| final_payload = {**final_payload, "content": ""} | ||
|
|
||
| try: | ||
| message_id = await _register_stream_chat_data( | ||
| data_collection=data_collection, | ||
| session_id=session_id, | ||
| user_query=cast(str, body.query), | ||
| conversation_id=thread_id, | ||
| answer_content=final_content, | ||
| sources=docs, | ||
| ) | ||
| final_payload = {**final_payload, "message_id": message_id} | ||
| except Exception as e: | ||
| logger.error("Error while registering chat data: %s", e) | ||
|
|
||
| yield _format_sse_event(json.dumps(jsonable_encoder(final_payload))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.