Repository navigation
LCORE-4760: Add v3 conversation facade and persistence mapping #3291
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
Open
asimurka
wants to merge
1
commit into
lightspeed-core:main
Choose a base branch
from
asimurka:v3-conversation-facade-mapping
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+700
−2
Open
Changes from all commits
Commits
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
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
163 changes: 163 additions & 0 deletions
163
src/conversations/display_history/persistence/facade/conversation.py
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,163 @@ | ||
| """Read and mutate display-history conversations for the v3 Conversations API.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from conversations.display_history.access import ( | ||
| check_conversation_access, | ||
| get_user_conversation, | ||
| ) | ||
| from conversations.display_history.agentic.models.conversation import ( | ||
| Conversation, | ||
| ConversationMetadata, | ||
| ) | ||
| from conversations.display_history.errors import ConversationAccessDeniedError | ||
| from conversations.display_history.persistence.mapping.conversation import ( | ||
| map_conversation, | ||
| map_conversation_metadata, | ||
| ) | ||
| from conversations.display_history.persistence.repository.agentic_turn import ( | ||
| list_agentic_turns_for_conversation, | ||
| ) | ||
| from conversations.display_history.persistence.repository.conversation import ( | ||
| delete_conversation as delete_conversation_row, | ||
| ) | ||
| from conversations.display_history.persistence.repository.conversation import ( | ||
| list_conversations as list_conversation_rows, | ||
| ) | ||
| from conversations.display_history.persistence.repository.conversation import ( | ||
| list_conversations_for_user, | ||
| update_conversation_topic_summary, | ||
| ) | ||
| from conversations.display_history.persistence.repository.turn import ( | ||
| list_turns_for_conversation, | ||
| ) | ||
| from log import get_logger | ||
| from utils.suid import normalize_conversation_id | ||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
|
|
||
| def list_conversations( | ||
| user_id: str, | ||
| others_allowed: bool, | ||
| ) -> list[ConversationMetadata]: | ||
| """List conversations visible to the caller. | ||
|
|
||
| Args: | ||
| user_id: Authenticated user. | ||
| others_allowed: When true, include other users' conversations. | ||
|
|
||
| Returns: | ||
| Conversation metadata without chat history. | ||
|
|
||
| """ | ||
| rows = ( | ||
| list_conversation_rows() | ||
| if others_allowed | ||
| else list_conversations_for_user(user_id) | ||
| ) | ||
| logger.info("Listed %s conversations for user %s", len(rows), user_id) | ||
| return [map_conversation_metadata(row) for row in rows] | ||
|
|
||
|
|
||
| def get_conversation( | ||
| conversation_id: str, | ||
| user_id: str, | ||
| others_allowed: bool, | ||
| ) -> Conversation: | ||
| """Load one conversation with chat history. | ||
|
|
||
| Args: | ||
| conversation_id: Conversation id; client prefix is optional. | ||
| user_id: Authenticated user. | ||
| others_allowed: When true, allow reading other users' conversations. | ||
|
|
||
| Returns: | ||
| Full conversation for the v3 API. | ||
|
|
||
| Raises: | ||
| ConversationAccessDeniedError: Caller may not read this conversation. | ||
| ConversationNotFoundError: Conversation does not exist. | ||
| DisplayHistoryDatabaseError: Database operation failed. | ||
|
|
||
| """ | ||
| normalized = normalize_conversation_id(conversation_id) | ||
| row = get_user_conversation(normalized, user_id, others_allowed) | ||
| conversation = map_conversation( | ||
| row, | ||
| list_turns_for_conversation(normalized), | ||
| list_agentic_turns_for_conversation(normalized), | ||
| ) | ||
| logger.info( | ||
| "Loaded conversation %s for user %s with %s turns", | ||
| normalized, | ||
| user_id, | ||
| len(conversation.chat_history), | ||
| ) | ||
| return conversation | ||
|
|
||
|
|
||
| def delete_conversation( | ||
| conversation_id: str, | ||
| user_id: str, | ||
| others_allowed: bool, | ||
| ) -> bool: | ||
| """Delete a conversation when the caller is allowed. | ||
|
|
||
| Missing conversations return false rather than an access error so the | ||
| HTTP layer can match v2 delete semantics. | ||
|
|
||
| Args: | ||
| conversation_id: Conversation id; client prefix is optional. | ||
| user_id: Authenticated user. | ||
| others_allowed: When true, allow deleting other users' conversations. | ||
|
|
||
| Returns: | ||
| True when a row was removed. | ||
|
|
||
| Raises: | ||
| ConversationAccessDeniedError: Caller may not delete this conversation. | ||
| DisplayHistoryDatabaseError: Database operation failed. | ||
|
|
||
| """ | ||
| normalized = normalize_conversation_id(conversation_id) | ||
| if not check_conversation_access(normalized, user_id, others_allowed): | ||
| raise ConversationAccessDeniedError(normalized, user_id) | ||
| deleted = delete_conversation_row(normalized) | ||
| logger.info( | ||
| "Deleted conversation %s for user %s: %s", | ||
| normalized, | ||
| user_id, | ||
| deleted, | ||
| ) | ||
| return deleted | ||
|
|
||
|
|
||
| def update_conversation_topic( | ||
| conversation_id: str, | ||
| user_id: str, | ||
| others_allowed: bool, | ||
| topic_summary: str, | ||
| ) -> None: | ||
| """Update the conversation topic summary. | ||
|
|
||
| Args: | ||
| conversation_id: Conversation id; client prefix is optional. | ||
| user_id: Authenticated user. | ||
| others_allowed: When true, allow updating other users' conversations. | ||
| topic_summary: New topic summary text. | ||
|
|
||
| Raises: | ||
| ConversationAccessDeniedError: Caller may not update this conversation. | ||
| ConversationNotFoundError: Conversation does not exist. | ||
| DisplayHistoryDatabaseError: Database operation failed. | ||
|
|
||
| """ | ||
| normalized = normalize_conversation_id(conversation_id) | ||
| get_user_conversation(normalized, user_id, others_allowed) | ||
| update_conversation_topic_summary(normalized, topic_summary) | ||
| logger.info( | ||
| "Updated topic summary for conversation %s for user %s", | ||
| normalized, | ||
| user_id, | ||
| ) | ||
13 changes: 13 additions & 0 deletions
13
src/conversations/display_history/persistence/mapping/README.md
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,13 @@ | ||
| # List of source files stored in `src/conversations/display_history/persistence/mapping` directory | ||
|
|
||
| ## [__init__.py](__init__.py) | ||
|
|
||
| Map display-history database rows onto v3 API models. | ||
|
|
||
| ## [agent_turn.py](agent_turn.py) | ||
|
|
||
| Map turn envelopes and agentic rows onto ``AgentTurn``. | ||
|
|
||
| ## [conversation.py](conversation.py) | ||
|
|
||
| Map conversation rows onto the v3 conversation envelope. |
17 changes: 17 additions & 0 deletions
17
src/conversations/display_history/persistence/mapping/__init__.py
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,17 @@ | ||
| """Map display-history database rows onto v3 API models.""" | ||
|
|
||
| from conversations.display_history.persistence.mapping.agent_turn import ( | ||
| map_agent_turn, | ||
| map_chat_history, | ||
| ) | ||
| from conversations.display_history.persistence.mapping.conversation import ( | ||
| map_conversation, | ||
| map_conversation_metadata, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "map_agent_turn", | ||
| "map_chat_history", | ||
| "map_conversation", | ||
| "map_conversation_metadata", | ||
| ] |
62 changes: 62 additions & 0 deletions
62
src/conversations/display_history/persistence/mapping/agent_turn.py
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,62 @@ | ||
| """Map stored turn rows onto the public agent-turn contract.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from conversations.display_history.agentic.models.agent_turn import AgentTurn | ||
| from conversations.display_history.persistence.models import UserAgenticTurn, UserTurn | ||
|
|
||
|
|
||
| def map_agent_turn(turn: UserTurn, agentic_turn: UserAgenticTurn) -> AgentTurn: | ||
| """Join a turn envelope and agentic row into a public agent turn. | ||
|
|
||
| Args: | ||
| turn: Turn envelope (provider, model, timestamps, run id). | ||
| agentic_turn: Agentic display row for the same turn number. | ||
|
|
||
| Returns: | ||
| Public agent turn for the conversation timeline. | ||
|
|
||
| """ | ||
| return AgentTurn.model_validate( | ||
| { | ||
| "id": turn.response_id, | ||
| "status": agentic_turn.status, | ||
| "agent": agentic_turn.agent, | ||
| "provider": turn.provider, | ||
| "model": turn.model, | ||
| "started_at": turn.started_at, | ||
| "completed_at": turn.completed_at, | ||
| "context_status": agentic_turn.context_status, | ||
| "usage": { | ||
| "input_tokens": agentic_turn.input_tokens, | ||
| "output_tokens": agentic_turn.output_tokens, | ||
| }, | ||
| "referenced_documents": agentic_turn.referenced_documents, | ||
| "input": agentic_turn.input_items, | ||
| "output": agentic_turn.output_items, | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def map_chat_history( | ||
| turns: list[UserTurn], | ||
| agentic_turns: list[UserAgenticTurn], | ||
| ) -> list[AgentTurn]: | ||
| """Build ordered chat history by matching turn number. | ||
|
|
||
| Args: | ||
| turns: Turn envelopes for the conversation. | ||
| agentic_turns: Agentic rows for the same conversation. | ||
|
|
||
| Returns: | ||
| Public agent turns in turn-number order. | ||
|
|
||
| """ | ||
| agentic_by_number = {row.turn_number: row for row in agentic_turns} | ||
| history: list[AgentTurn] = [] | ||
| for turn in turns: | ||
| agentic = agentic_by_number.get(turn.turn_number) | ||
| if agentic is None or not turn.response_id: | ||
| continue | ||
| history.append(map_agent_turn(turn, agentic)) | ||
| return history |
63 changes: 63 additions & 0 deletions
63
src/conversations/display_history/persistence/mapping/conversation.py
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,63 @@ | ||
| """Map stored conversation rows onto the v3 conversation envelope.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from conversations.display_history.agentic.models.conversation import ( | ||
| Conversation, | ||
| ConversationMetadata, | ||
| ) | ||
| from conversations.display_history.persistence.mapping.agent_turn import ( | ||
| map_chat_history, | ||
| ) | ||
| from conversations.display_history.persistence.models import ( | ||
| UserAgenticTurn, | ||
| UserConversation, | ||
| UserTurn, | ||
| ) | ||
|
|
||
|
|
||
| def map_conversation_metadata(row: UserConversation) -> ConversationMetadata: | ||
| """Map a conversation row to list/get metadata. | ||
|
|
||
| Args: | ||
| row: Stored conversation row. | ||
|
|
||
| Returns: | ||
| Metadata without chat history. | ||
|
|
||
| """ | ||
| return ConversationMetadata.model_validate( | ||
| { | ||
| "conversation_id": row.id, | ||
| "created_at": row.created_at, | ||
| "last_turn_at": row.last_message_at, | ||
| "turn_count": row.message_count, | ||
| "last_used_model": row.last_used_model, | ||
| "last_used_provider": row.last_used_provider, | ||
| "topic_summary": row.topic_summary or None, | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def map_conversation( | ||
| row: UserConversation, | ||
| turns: list[UserTurn], | ||
| agentic_turns: list[UserAgenticTurn], | ||
| ) -> Conversation: | ||
| """Map stored rows to a full v3 conversation. | ||
|
|
||
| Args: | ||
| row: Stored conversation row. | ||
| turns: Turn envelopes for the conversation. | ||
| agentic_turns: Agentic rows for the same conversation. | ||
|
|
||
| Returns: | ||
| Conversation including chat history. | ||
|
|
||
| """ | ||
| return Conversation.model_validate( | ||
| { | ||
| **map_conversation_metadata(row).model_dump(), | ||
| "chat_history": map_chat_history(turns, agentic_turns), | ||
| } | ||
| ) |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: lightspeed-core/lightspeed-stack
Length of output: 7978
Script executed:
Repository: lightspeed-core/lightspeed-stack
Length of output: 11216
Script executed:
Repository: lightspeed-core/lightspeed-stack
Length of output: 4345
Script executed:
Repository: lightspeed-core/lightspeed-stack
Length of output: 9723
Delete the conversation's turn and agentic-turn rows explicitly on SQLite.
The declared
ON DELETE CASCADEconstraints onuser_turnanduser_agentic_turndo not block deletion, so no foreign-key error occurs. The cascade runs only when the database enforces foreign keys. The SQLite engine does not enable them, sodelete_conversationremoves only theuser_conversationrow. Itsuser_turnanduser_agentic_turnrows remain, including stored input and output items. PostgreSQL enforces the cascade, so this affects SQLite deployments only.Require
delete_conversationto remove the conversation'suser_agentic_turnanduser_turnrows in the same transaction, on every backend. Do not rely on the database cascade alone.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Valid. Will be fixed in a separate PR as it is related to repository, not fasade.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#3297