Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat(core): support forking the default (agent-direct) conversation (#10263)
Sarah Woodersa22a57c2b7f9
diff --git a/fern/openapi.json b/fern/openapi.jsonindex c5fc687c0..bd5870861 100644--- a/fern/openapi.json+++ b/fern/openapi.json@@ -9028,7 +9028,7 @@"post": {"tags": ["conversations"],"summary": "Fork Conversation",- "description": "Fork an existing conversation.\n\nCreates a new conversation that shares the same in-context messages as the source\nconversation, but with a newly compiled system message reflecting the latest memory\nblock values. The forked conversation belongs to the same agent as the source.",+ "description": "Fork an existing conversation.\n\nCreates a new conversation that shares the same in-context messages as the source\nconversation, but with a newly compiled system message reflecting the latest memory\nblock values. The forked conversation belongs to the same agent as the source.\n\n**Agent-direct mode**: Pass conversation_id=\"default\" with agent_id query parameter\nto fork the agent's default (agent-direct) message history into a new conversation.\n\n**Deprecated**: Passing an agent ID as conversation_id still works but will be removed.","operationId": "fork_conversation","parameters": [{@@ -9037,14 +9037,36 @@"required": true,"schema": {"type": "string",- "minLength": 41,- "maxLength": 41,- "pattern": "^conv-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",- "description": "The ID of the conv in the format 'conv-<uuid4>'",- "examples": ["conv-123e4567-e89b-42d3-8456-426614174000"],+ "minLength": 1,+ "maxLength": 42,+ "pattern": "^(default|conv-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|agent-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$",+ "description": "The conversation identifier. Can be a conversation ID ('conv-<uuid4>'), 'default' for agent-direct mode (with agent_id parameter), or an agent ID ('agent-<uuid4>') for backwards compatibility (deprecated).",+ "examples": [+ "default",+ "conv-123e4567-e89b-42d3-8456-426614174000",+ "agent-123e4567-e89b-42d3-8456-426614174000"+ ],"title": "Conversation Id"},- "description": "The ID of the conv in the format 'conv-<uuid4>'"+ "description": "The conversation identifier. Can be a conversation ID ('conv-<uuid4>'), 'default' for agent-direct mode (with agent_id parameter), or an agent ID ('agent-<uuid4>') for backwards compatibility (deprecated)."+ },+ {+ "name": "agent_id",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Agent ID for agent-direct mode with 'default' conversation",+ "title": "Agent Id"+ },+ "description": "Agent ID for agent-direct mode with 'default' conversation"}],"responses": {diff --git a/letta/server/rest_api/routers/v1/conversations.py b/letta/server/rest_api/routers/v1/conversations.pyindex 9bbdec35c..98ec0b320 100644--- a/letta/server/rest_api/routers/v1/conversations.py+++ b/letta/server/rest_api/routers/v1/conversations.py@@ -121,7 +121,8 @@ async def update_conversation(@router.post("/{conversation_id}/fork", response_model=Conversation, operation_id="fork_conversation")async def fork_conversation(- conversation_id: ConversationId,+ conversation_id: ConversationIdOrDefault,+ agent_id: Optional[str] = Query(None, description="Agent ID for agent-direct mode with 'default' conversation"),server: SyncServer = Depends(get_letta_server),headers: HeaderParams = Depends(get_headers),):@@ -131,8 +132,29 @@ async def fork_conversation(Creates a new conversation that shares the same in-context messages as the sourceconversation, but with a newly compiled system message reflecting the latest memoryblock values. The forked conversation belongs to the same agent as the source.++ **Agent-direct mode**: Pass conversation_id="default" with agent_id query parameter+ to fork the agent's default (agent-direct) message history into a new conversation.++ **Deprecated**: Passing an agent ID as conversation_id still works but will be removed."""actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)++ # Agent-direct mode: conversation_id="default" + agent_id param (preferred)+ # OR conversation_id="agent-*" (backwards compat, deprecated)+ resolved_agent_id = None+ if conversation_id == "default" and agent_id:+ resolved_agent_id = agent_id+ elif conversation_id.startswith("agent-"):+ resolved_agent_id = conversation_id++ if resolved_agent_id:+ return await conversation_manager.fork_default_conversation(+ agent_id=resolved_agent_id,+ actor=actor,+ server=server,+ )+return await conversation_manager.fork_conversation(conversation_id=conversation_id,actor=actor,diff --git a/letta/services/conversation_manager.py b/letta/services/conversation_manager.pyindex 7fde324aa..c2288822c 100644--- a/letta/services/conversation_manager.py+++ b/letta/services/conversation_manager.py@@ -1,7 +1,7 @@from typing import TYPE_CHECKING, Dict, List, Optionalif TYPE_CHECKING:- pass+ from letta.server.server import SyncServer# Import AgentState outside TYPE_CHECKING for @enforce_types decoratorfrom sqlalchemy import and_, asc, delete, desc, func, nulls_last, or_, select, update@@ -171,6 +171,53 @@ class ConversationManager:return pydantic_conversation+ @trace_method+ async def fork_default_conversation(+ self,+ agent_id: str,+ actor: PydanticUser,+ server: "SyncServer",+ ) -> PydanticConversation:+ """Fork the agent's default (agent-direct) message history into a new conversation.++ Reads the agent's message_ids, creates a new Conversation record, links all+ non-system messages, and compiles a fresh system message for the fork.+ """+ agent = await server.agent_manager.get_agent_by_id_async(agent_id, actor)+ source_message_ids = agent.message_ids or []++ # Skip the system message (always position 0); the fork gets its own.+ message_ids_to_copy = source_message_ids[1:] if source_message_ids else []++ async with db_registry.async_session() as session:+ new_conversation = ConversationModel(+ agent_id=agent_id,+ summary=None,+ organization_id=actor.organization_id,+ )+ await new_conversation.create_async(session, actor=actor, no_commit=True)++ await self._add_messages_to_conversation_with_session(+ session=session,+ conversation_id=new_conversation.id,+ agent_id=agent_id,+ message_ids=message_ids_to_copy,+ actor=actor,+ starting_position=1,+ )++ await session.commit()+ await session.refresh(new_conversation)+ pydantic_conversation = new_conversation.to_pydantic()++ await self.compile_and_save_system_message_for_conversation(+ conversation_id=pydantic_conversation.id,+ agent_id=agent_id,+ actor=actor,+ )++ return pydantic_conversation+@trace_methodasync def compile_and_save_system_message_for_conversation(self,@@ -536,12 +583,9 @@ class ConversationManager:# shared with any other active (non-deleted) conversation.# With conversation forking, messages can be referenced by multiple# conversations via the conversation_messages junction table.- other_conv_ref = (- select(ConversationMessageModel.message_id)- .where(- ConversationMessageModel.conversation_id != conversation_id,- ConversationMessageModel.is_deleted == False,- )+ other_conv_ref = select(ConversationMessageModel.message_id).where(+ ConversationMessageModel.conversation_id != conversation_id,+ ConversationMessageModel.is_deleted == False,)await session.execute(update(MessageModel)diff --git a/tests/integration_test_conversations_sdk.py b/tests/integration_test_conversations_sdk.pyindex aacefb1de..42b4bfe47 100644--- a/tests/integration_test_conversations_sdk.py+++ b/tests/integration_test_conversations_sdk.py@@ -1152,6 +1152,69 @@ class TestConversationsSDK:combined_response = " ".join(c for c in assistant_contents if isinstance(c, str))assert "blue" in combined_response.lower(), f"Expected 'blue' in assistant response, got: {combined_response}"+ def test_fork_default_conversation_via_rest(self, client: Letta, agent, server_url: str):+ """Fork the default (agent-direct) conversation via REST and verify message sharing."""+ # Send a message to the default conversation (agent-direct mode)+ requests.post(+ f"{server_url}/v1/conversations/default/messages",+ json={+ "agent_id": agent.id,+ "messages": [{"role": "user", "content": "my favorite animal is a penguin"}],+ "streaming": False,+ },+ )++ # Fork the default conversation using the new pattern+ fork_response = requests.post(+ f"{server_url}/v1/conversations/default/fork",+ params={"agent_id": agent.id},+ )+ assert fork_response.status_code == 200, f"Fork request failed: {fork_response.text}"+ forked_conversation = fork_response.json()+ forked_id = forked_conversation["id"]+ assert forked_id.startswith("conv-"), f"Expected conversation ID, got: {forked_id}"++ # Verify the forked conversation remembers the context+ fork_reply_response = requests.post(+ f"{server_url}/v1/conversations/{forked_id}/messages",+ json={+ "messages": [{"role": "user", "content": "what is my favorite animal?"}],+ "streaming": False,+ },+ )+ assert fork_reply_response.status_code == 200, f"Fork reply failed: {fork_reply_response.text}"+ fork_reply_data = fork_reply_response.json()++ fork_reply_text = " ".join(+ m.get("content", "")+ for m in fork_reply_data.get("messages", [])+ if m.get("message_type") == "assistant_message" and isinstance(m.get("content"), str)+ )+ assert "penguin" in fork_reply_text.lower(), f"Expected forked conversation to remember penguin, got: {fork_reply_text}"++ # Verify message IDs are shared (non-system messages)+ default_messages_response = requests.get(+ f"{server_url}/v1/conversations/default/messages",+ params={"agent_id": agent.id, "order": "asc"},+ )+ assert default_messages_response.status_code == 200+ default_messages = default_messages_response.json()++ forked_messages = list(client.conversations.messages.list(conversation_id=forked_id, order="asc"))++ default_message_ids = [m["id"] for m in default_messages]+ forked_message_ids = [m.id for m in forked_messages]++ # System messages should differ+ assert default_message_ids[0] != forked_message_ids[0], "System messages should be different"++ # Non-system messages from default should be in the fork+ default_non_system_ids = default_message_ids[1:]+ forked_after_system_ids = forked_message_ids[1:]+ assert default_non_system_ids == forked_after_system_ids[: len(default_non_system_ids)], (+ f"Non-system messages should match. Default: {default_non_system_ids}, Fork: {forked_after_system_ids}"+ )+class TestConversationDelete:"""Tests for the conversation delete endpoint."""