Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: support forking conversations with shared messages (#10234)
github-actions[bot]566fa8561ed7
diff --git a/fern/openapi.json b/fern/openapi.jsonindex 99ed93506..e9d0f8436 100644--- a/fern/openapi.json+++ b/fern/openapi.json@@ -7944,8 +7944,9 @@"patch": {"tags": ["agents"],"summary": "Modify Message",- "description": "Update the details of a message associated with an agent.",+ "description": "Update the details of a message associated with an agent.\n\n**Deprecated**: Messages are now considered immutable since they can be shared across\nmultiple conversations via forking. This endpoint will be removed in a future version.","operationId": "modify_message",+ "deprecated": true,"parameters": [{"name": "agent_id",@@ -9023,6 +9024,53 @@}}},+ "/v1/conversations/{conversation_id}/fork": {+ "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.",+ "operationId": "fork_conversation",+ "parameters": [+ {+ "name": "conversation_id",+ "in": "path",+ "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"],+ "title": "Conversation Id"+ },+ "description": "The ID of the conv in the format 'conv-<uuid4>'"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Conversation"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/v1/conversations/{conversation_id}/messages": {"get": {"tags": ["conversations"],diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.pyindex d76f3013a..dd2e19d52 100644--- a/letta/server/rest_api/routers/v1/agents.py+++ b/letta/server/rest_api/routers/v1/agents.py@@ -1622,7 +1622,7 @@ async def list_messages()[email protected]("/{agent_id}/messages/{message_id}", response_model=LettaMessageUnion, operation_id="modify_message")[email protected]("/{agent_id}/messages/{message_id}", response_model=LettaMessageUnion, operation_id="modify_message", deprecated=True)async def modify_message(agent_id: AgentId, # backwards compatible. Consider removing for v1message_id: MessageId,@@ -1632,11 +1632,13 @@ async def modify_message():"""Update the details of a message associated with an agent.++ **Deprecated**: Messages are now considered immutable since they can be shared across+ multiple conversations via forking. This endpoint will be removed in a future version."""- # TODO: support modifying tool calls/returns- actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)- return await server.message_manager.update_message_by_letta_message_async(- message_id=message_id, letta_message_update=request, actor=actor+ raise HTTPException(+ status_code=status.HTTP_405_METHOD_NOT_ALLOWED,+ detail="Message editing is no longer supported. Messages are immutable as they may be shared across multiple conversations via forking.",)diff --git a/letta/server/rest_api/routers/v1/conversations.py b/letta/server/rest_api/routers/v1/conversations.pyindex 1622c5c4d..9bbdec35c 100644--- a/letta/server/rest_api/routers/v1/conversations.py+++ b/letta/server/rest_api/routers/v1/conversations.py@@ -119,6 +119,26 @@ async def update_conversation()[email protected]("/{conversation_id}/fork", response_model=Conversation, operation_id="fork_conversation")+async def fork_conversation(+ conversation_id: ConversationId,+ server: SyncServer = Depends(get_letta_server),+ headers: HeaderParams = Depends(get_headers),+):+ """+ Fork an existing conversation.++ Creates a new conversation that shares the same in-context messages as the source+ conversation, but with a newly compiled system message reflecting the latest memory+ block values. The forked conversation belongs to the same agent as the source.+ """+ actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)+ return await conversation_manager.fork_conversation(+ conversation_id=conversation_id,+ actor=actor,+ )++@router.delete("/{conversation_id}", response_model=None, operation_id="delete_conversation")async def delete_conversation(conversation_id: ConversationId,diff --git a/letta/services/conversation_manager.py b/letta/services/conversation_manager.pyindex b0aae27bb..7fde324aa 100644--- a/letta/services/conversation_manager.py+++ b/letta/services/conversation_manager.py@@ -100,6 +100,77 @@ class ConversationManager:return pydantic_conversation+ @enforce_types+ @trace_method+ async def fork_conversation(+ self,+ conversation_id: str,+ actor: PydanticUser,+ ) -> PydanticConversation:+ """Fork an existing conversation, creating a new conversation with shared messages.++ The forked conversation gets:+ - A new Conversation record (same agent_id as the source)+ - A NEW system message compiled from the latest block values+ - The same in-context Message objects as the source (shared, not copied)++ Args:+ conversation_id: The ID of the conversation to fork+ actor: The user performing the action++ Returns:+ The newly created forked conversation+ """+ async with db_registry.async_session() as session:+ source_conversation = await ConversationModel.read_async(+ db_session=session,+ identifier=conversation_id,+ actor=actor,+ check_is_deleted=True,+ )+ agent_id = source_conversation.agent_id++ new_conversation = ConversationModel(+ agent_id=agent_id,+ summary=None,+ organization_id=actor.organization_id,+ model=source_conversation.model,+ model_settings=source_conversation.model_settings,+ )+ await new_conversation.create_async(session, actor=actor, no_commit=True)++ source_message_ids = await self._get_message_ids_for_conversation_with_session(+ session=session,+ conversation_id=conversation_id,+ actor=actor,+ )++ # 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 []++ 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()++ # Compile and persist a NEW system message for the forked conversation+ # This captures the latest memory block state+ 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,@@ -461,12 +532,23 @@ class ConversationManager:.values({ConversationMessageModel.is_deleted: True}))- # Bulk soft-delete messages that belong to this real conversation.+ # Soft-delete messages that belong to this conversation AND are not+ # 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,+ )+ )await session.execute(update(MessageModel).where(MessageModel.conversation_id == conversation_id).where(MessageModel.organization_id == actor.organization_id).where(MessageModel.is_deleted == False)+ .where(~MessageModel.id.in_(other_conv_ref)).values({MessageModel.is_deleted: True}))@@ -484,6 +566,25 @@ class ConversationManager:# ==================== Message Management Methods ====================+ async def _get_message_ids_for_conversation_with_session(+ self,+ session,+ conversation_id: str,+ actor: PydanticUser,+ ) -> List[str]:+ query = (+ select(ConversationMessageModel.message_id)+ .where(+ ConversationMessageModel.conversation_id == conversation_id,+ ConversationMessageModel.organization_id == actor.organization_id,+ ConversationMessageModel.in_context == True,+ ConversationMessageModel.is_deleted == False,+ )+ .order_by(ConversationMessageModel.position)+ )+ result = await session.execute(query)+ return list(result.scalars().all())+@enforce_types@trace_methodasync def get_message_ids_for_conversation(@@ -498,18 +599,11 @@ class ConversationManager:Only returns messages that are currently in_context."""async with db_registry.async_session() as session:- query = (- select(ConversationMessageModel.message_id)- .where(- ConversationMessageModel.conversation_id == conversation_id,- ConversationMessageModel.organization_id == actor.organization_id,- ConversationMessageModel.in_context == True,- ConversationMessageModel.is_deleted == False,- )- .order_by(ConversationMessageModel.position)+ return await self._get_message_ids_for_conversation_with_session(+ session=session,+ conversation_id=conversation_id,+ actor=actor,)- result = await session.execute(query)- return list(result.scalars().all())@enforce_types@trace_method@@ -542,6 +636,40 @@ class ConversationManager:result = await session.execute(query)return [msg.to_pydantic() for msg in result.scalars().all()]+ async def _add_messages_to_conversation_with_session(+ self,+ session,+ conversation_id: str,+ agent_id: str,+ message_ids: List[str],+ actor: PydanticUser,+ starting_position: Optional[int] = None,+ ) -> None:+ if not message_ids:+ return++ if starting_position is None:+ query = select(func.coalesce(func.max(ConversationMessageModel.position), -1)).where(+ ConversationMessageModel.conversation_id == conversation_id,+ ConversationMessageModel.organization_id == actor.organization_id,+ )+ result = await session.execute(query)+ max_position = result.scalar()+ if max_position is None:+ max_position = -1+ starting_position = max_position + 1++ for i, message_id in enumerate(message_ids):+ conv_msg = ConversationMessageModel(+ conversation_id=conversation_id,+ agent_id=agent_id,+ message_id=message_id,+ position=starting_position + i,+ in_context=True,+ organization_id=actor.organization_id,+ )+ session.add(conv_msg)+@enforce_types@trace_methodasync def add_messages_to_conversation(@@ -564,35 +692,15 @@ class ConversationManager:actor: The user performing the actionstarting_position: Optional starting position (defaults to next available)"""- if not message_ids:- return-async with db_registry.async_session() as session:- # Get starting position if not provided- if starting_position is None:- query = select(func.coalesce(func.max(ConversationMessageModel.position), -1)).where(- ConversationMessageModel.conversation_id == conversation_id,- ConversationMessageModel.organization_id == actor.organization_id,- )- result = await session.execute(query)- max_position = result.scalar()- # Use explicit None check instead of `or` to handle position=0 correctly- if max_position is None:- max_position = -1- starting_position = max_position + 1-- # Create ConversationMessage entries- for i, message_id in enumerate(message_ids):- conv_msg = ConversationMessageModel(- conversation_id=conversation_id,- agent_id=agent_id,- message_id=message_id,- position=starting_position + i,- in_context=True,- organization_id=actor.organization_id,- )- session.add(conv_msg)-+ await self._add_messages_to_conversation_with_session(+ session=session,+ conversation_id=conversation_id,+ agent_id=agent_id,+ message_ids=message_ids,+ actor=actor,+ starting_position=starting_position,+ )await session.commit()@enforce_typesdiff --git a/tests/integration_test_conversations_sdk.py b/tests/integration_test_conversations_sdk.pyindex 939f690fb..aacefb1de 100644--- a/tests/integration_test_conversations_sdk.py+++ b/tests/integration_test_conversations_sdk.py@@ -369,6 +369,56 @@ class TestConversationsSDK:conv2_system_id = conv2_messages[0].idassert conv1_system_id != conv2_system_id, "System messages should have different IDs for different conversations"+ def test_fork_conversation_via_rest_shares_non_system_message_ids(self, client: Letta, agent, server_url: str):+ """Fork via REST and verify memory continuity plus shared non-system message IDs in-order."""+ source = client.conversations.create(agent_id=agent.id)++ list(+ client.conversations.messages.create(+ conversation_id=source.id,+ messages=[{"role": "user", "content": "my favorite color is red"}],+ )+ )++ fork_response = requests.post(f"{server_url}/v1/conversations/{source.id}/fork")+ assert fork_response.status_code == 200, f"Fork request failed: {fork_response.text}"+ forked_conversation = fork_response.json()+ forked_id = forked_conversation["id"]++ fork_reply_stream = list(+ client.conversations.messages.create(+ conversation_id=forked_id,+ messages=[{"role": "user", "content": "whats my favorite color?"}],+ )+ )++ fork_reply_text = " ".join(+ m.content+ for m in fork_reply_stream+ if hasattr(m, "message_type") and m.message_type == "assistant_message" and isinstance(getattr(m, "content", None), str)+ )+ assert "red" in fork_reply_text.lower(), f"Expected forked conversation to remember red, got: {fork_reply_text}"++ source_messages = list(client.conversations.messages.list(conversation_id=source.id, order="asc"))+ forked_messages = list(client.conversations.messages.list(conversation_id=forked_id, order="asc"))++ source_message_ids = [m.id for m in source_messages]+ forked_message_ids = [m.id for m in forked_messages]++ # System messages should differ across source and fork.+ assert source_message_ids[0] != forked_message_ids[0]++ # All non-system source messages should be reused in-order in the fork.+ source_non_system_ids = source_message_ids[1:]+ forked_after_system_ids = forked_message_ids[1:]+ assert source_non_system_ids == forked_after_system_ids[: len(source_non_system_ids)]+ assert set(source_non_system_ids).issubset(set(forked_message_ids))++ def test_fork_conversation_via_rest_not_found(self, client: Letta, agent, server_url: str):+ """Forking a non-existent conversation should return not found/validation error."""+ response = requests.post(f"{server_url}/v1/conversations/conv-nonexistent-00000000/fork")+ assert response.status_code in (404, 422), f"Expected 404/422, got {response.status_code}: {response.text}"+def test_conversation_messages_pagination(self, client: Letta, agent):"""Test pagination when listing conversation messages."""# Create a conversationdiff --git a/tests/managers/test_conversation_manager.py b/tests/managers/test_conversation_manager.pyindex 93e65dcf2..719b2e32a 100644--- a/tests/managers/test_conversation_manager.py+++ b/tests/managers/test_conversation_manager.py@@ -1493,3 +1493,341 @@ async def test_update_conversation_schema_model_validation():# Invalid format should raisewith pytest.raises(LettaInvalidArgumentError):UpdateConversation(model="no-slash")+++# ======================================================================================================================+# Fork Conversation Tests+# ======================================================================================================================+++async def test_fork_conversation_basic(conversation_manager, server: SyncServer, sarah_agent, default_user):+ """Test basic conversation forking creates a new conversation with shared messages."""+ from letta.schemas.letta_message_content import TextContent+ from letta.schemas.message import Message as PydanticMessage++ # Create source conversation+ source = await conversation_manager.create_conversation(+ agent_id=sarah_agent.id,+ conversation_create=CreateConversation(summary="Source conversation"),+ actor=default_user,+ )++ # Add some user messages to the source conversation+ pydantic_messages = [+ PydanticMessage(+ agent_id=sarah_agent.id,+ role="user",+ content=[TextContent(text=f"Message {i}")],+ )+ for i in range(3)+ ]+ messages = await server.message_manager.create_many_messages_async(+ pydantic_messages,+ actor=default_user,+ )+ await conversation_manager.add_messages_to_conversation(+ conversation_id=source.id,+ agent_id=sarah_agent.id,+ message_ids=[m.id for m in messages],+ actor=default_user,+ )++ # Fork the conversation+ forked = await conversation_manager.fork_conversation(+ conversation_id=source.id,+ actor=default_user,+ )++ # Verify the fork has a different ID+ assert forked.id != source.id+ assert forked.id.startswith("conv-")+ assert forked.agent_id == sarah_agent.id++ # Get messages from both conversations+ source_msg_ids = await conversation_manager.get_message_ids_for_conversation(+ conversation_id=source.id,+ actor=default_user,+ )+ forked_msg_ids = await conversation_manager.get_message_ids_for_conversation(+ conversation_id=forked.id,+ actor=default_user,+ )++ # Both should have system message + 3 user messages = 4 messages+ assert len(source_msg_ids) == 4 # system + 3 user+ assert len(forked_msg_ids) == 4 # new system + 3 shared user++ # The user messages should be SHARED (same message IDs)+ source_user_msgs = source_msg_ids[1:] # skip system message+ forked_user_msgs = forked_msg_ids[1:] # skip system message+ assert source_user_msgs == forked_user_msgs++ # The system messages should be DIFFERENT+ assert source_msg_ids[0] != forked_msg_ids[0]+++async def test_fork_conversation_new_system_message(conversation_manager, server: SyncServer, sarah_agent, default_user):+ """Test that a forked conversation gets a newly compiled system message."""+ # Create source conversation+ source = await conversation_manager.create_conversation(+ agent_id=sarah_agent.id,+ conversation_create=CreateConversation(summary="Source"),+ actor=default_user,+ )++ # Fork the conversation+ forked = await conversation_manager.fork_conversation(+ conversation_id=source.id,+ actor=default_user,+ )++ # Get the system messages from both conversations+ source_msgs = await conversation_manager.get_messages_for_conversation(+ conversation_id=source.id,+ actor=default_user,+ )+ forked_msgs = await conversation_manager.get_messages_for_conversation(+ conversation_id=forked.id,+ actor=default_user,+ )++ # Both should have at least the system message+ assert len(source_msgs) >= 1+ assert len(forked_msgs) >= 1++ # First message in both should be system role+ assert source_msgs[0].role == "system"+ assert forked_msgs[0].role == "system"++ # System message IDs should be different (fork gets its own)+ assert source_msgs[0].id != forked_msgs[0].id+++async def test_fork_conversation_preserves_model_settings(conversation_manager, server: SyncServer, sarah_agent, default_user):+ """Test that forking preserves model and model_settings from the source."""+ from letta.schemas.model import OpenAIModelSettings++ source = await conversation_manager.create_conversation(+ agent_id=sarah_agent.id,+ conversation_create=CreateConversation(+ summary="Source with model",+ model="openai/gpt-4o",+ model_settings=OpenAIModelSettings(temperature=0.5),+ ),+ actor=default_user,+ )++ forked = await conversation_manager.fork_conversation(+ conversation_id=source.id,+ actor=default_user,+ )++ # Retrieve the forked conversation to verify model settings+ retrieved = await conversation_manager.get_conversation_by_id(+ conversation_id=forked.id,+ actor=default_user,+ )++ assert retrieved.model == "openai/gpt-4o"+ assert retrieved.model_settings is not None+ assert retrieved.model_settings.temperature == 0.5+++async def test_fork_conversation_not_found(conversation_manager, server: SyncServer, default_user):+ """Test that forking a non-existent conversation raises an error."""+ from letta.orm.errors import NoResultFound++ with pytest.raises(NoResultFound):+ await conversation_manager.fork_conversation(+ conversation_id="conv-nonexistent",+ actor=default_user,+ )+++async def test_fork_conversation_shared_messages_survive_source_delete(+ conversation_manager, server: SyncServer, sarah_agent, default_user+):+ """Test that deleting the source conversation does not delete messages shared with forks."""+ from letta.schemas.letta_message_content import TextContent+ from letta.schemas.message import Message as PydanticMessage++ # Create source conversation with messages+ source = await conversation_manager.create_conversation(+ agent_id=sarah_agent.id,+ conversation_create=CreateConversation(summary="Source"),+ actor=default_user,+ )++ user_msg = PydanticMessage(+ agent_id=sarah_agent.id,+ role="user",+ content=[TextContent(text="Shared message")],+ conversation_id=source.id,+ )+ created = await server.message_manager.create_many_messages_async([user_msg], actor=default_user)+ shared_msg_id = created[0].id++ await conversation_manager.add_messages_to_conversation(+ conversation_id=source.id,+ agent_id=sarah_agent.id,+ message_ids=[shared_msg_id],+ actor=default_user,+ )++ # Fork the conversation+ forked = await conversation_manager.fork_conversation(+ conversation_id=source.id,+ actor=default_user,+ )++ # Delete the source conversation+ await conversation_manager.delete_conversation(+ conversation_id=source.id,+ actor=default_user,+ )++ # The shared message should still be accessible since the fork references it+ still_visible = await server.message_manager.get_message_by_id_async(shared_msg_id, actor=default_user)+ assert still_visible is not None++ # The fork should still have its messages+ forked_msg_ids = await conversation_manager.get_message_ids_for_conversation(+ conversation_id=forked.id,+ actor=default_user,+ )+ assert shared_msg_id in forked_msg_ids+++async def test_fork_conversation_delete_fork_preserves_source(+ conversation_manager, server: SyncServer, sarah_agent, default_user+):+ """Test that deleting a forked conversation does not affect the source."""+ from letta.schemas.letta_message_content import TextContent+ from letta.schemas.message import Message as PydanticMessage++ # Create source conversation with messages+ source = await conversation_manager.create_conversation(+ agent_id=sarah_agent.id,+ conversation_create=CreateConversation(summary="Source"),+ actor=default_user,+ )++ user_msg = PydanticMessage(+ agent_id=sarah_agent.id,+ role="user",+ content=[TextContent(text="Shared message")],+ conversation_id=source.id,+ )+ created = await server.message_manager.create_many_messages_async([user_msg], actor=default_user)+ shared_msg_id = created[0].id++ await conversation_manager.add_messages_to_conversation(+ conversation_id=source.id,+ agent_id=sarah_agent.id,+ message_ids=[shared_msg_id],+ actor=default_user,+ )++ # Fork and then delete the fork+ forked = await conversation_manager.fork_conversation(+ conversation_id=source.id,+ actor=default_user,+ )++ await conversation_manager.delete_conversation(+ conversation_id=forked.id,+ actor=default_user,+ )++ # Source messages should be unaffected+ source_msg_ids = await conversation_manager.get_message_ids_for_conversation(+ conversation_id=source.id,+ actor=default_user,+ )+ assert shared_msg_id in source_msg_ids++ # Shared message should still be visible+ still_visible = await server.message_manager.get_message_by_id_async(shared_msg_id, actor=default_user)+ assert still_visible is not None+++async def test_fork_empty_conversation(conversation_manager, server: SyncServer, sarah_agent, default_user):+ """Test forking a conversation that only has a system message."""+ source = await conversation_manager.create_conversation(+ agent_id=sarah_agent.id,+ conversation_create=CreateConversation(summary="Empty source"),+ actor=default_user,+ )++ forked = await conversation_manager.fork_conversation(+ conversation_id=source.id,+ actor=default_user,+ )++ # Forked conversation should have only its own system message+ forked_msg_ids = await conversation_manager.get_message_ids_for_conversation(+ conversation_id=forked.id,+ actor=default_user,+ )+ assert len(forked_msg_ids) == 1 # Just the new system message+++async def test_fork_conversation_messages_appear_in_list(conversation_manager, server: SyncServer, sarah_agent, default_user):+ """Test that shared messages appear when listing forked conversation messages."""+ from letta.schemas.letta_message_content import TextContent+ from letta.schemas.message import Message as PydanticMessage++ # Create source conversation with messages+ source = await conversation_manager.create_conversation(+ agent_id=sarah_agent.id,+ conversation_create=CreateConversation(summary="Source"),+ actor=default_user,+ )++ pydantic_messages = [+ PydanticMessage(+ agent_id=sarah_agent.id,+ role="user",+ content=[TextContent(text="Hello from source!")],+ ),+ PydanticMessage(+ agent_id=sarah_agent.id,+ role="assistant",+ content=[TextContent(text="Hi there!")],+ ),+ ]+ messages = await server.message_manager.create_many_messages_async(pydantic_messages, actor=default_user)++ await conversation_manager.add_messages_to_conversation(+ conversation_id=source.id,+ agent_id=sarah_agent.id,+ message_ids=[m.id for m in messages],+ actor=default_user,+ )++ # Fork the conversation+ forked = await conversation_manager.fork_conversation(+ conversation_id=source.id,+ actor=default_user,+ )++ # List messages in the forked conversation+ letta_messages = await conversation_manager.list_conversation_messages(+ conversation_id=forked.id,+ actor=default_user,+ )++ # Should have system + user + assistant = 3 messages+ assert len(letta_messages) == 3+ message_types = [m.message_type for m in letta_messages]+ assert "system_message" in message_types+ assert "user_message" in message_types+ assert "assistant_message" in message_types