Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add conversation recompile endpoint (#9848)
github-actions[bot]ca1b1c6e7690
diff --git a/fern/openapi.json b/fern/openapi.jsonindex 245ed7a5b..4f3f0d786 100644--- a/fern/openapi.json+++ b/fern/openapi.json@@ -9415,6 +9415,87 @@}}},+ "/v1/conversations/{conversation_id}/recompile": {+ "post": {+ "tags": ["conversations"],+ "summary": "Recompile Conversation",+ "description": "Manually trigger system prompt recompilation for a conversation.",+ "operationId": "recompile_conversation",+ "parameters": [+ {+ "name": "conversation_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "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 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": "dry_run",+ "in": "query",+ "required": false,+ "schema": {+ "type": "boolean",+ "description": "If True, do not persist changes; still returns the compiled system prompt.",+ "default": false,+ "title": "Dry Run"+ },+ "description": "If True, do not persist changes; still returns the compiled system prompt."+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/letta__server__rest_api__routers__v1__conversations__CompactionRequest"+ },+ {+ "type": "null"+ }+ ],+ "title": "Request"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "type": "string",+ "title": "Response Recompile Conversation"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/v1/conversations/{conversation_id}/compact": {"post": {"tags": ["conversations"],diff --git a/letta/server/rest_api/routers/v1/conversations.py b/letta/server/rest_api/routers/v1/conversations.pyindex e94bdc0fb..ad154c0a3 100644--- a/letta/server/rest_api/routers/v1/conversations.py+++ b/letta/server/rest_api/routers/v1/conversations.py@@ -1,5 +1,6 @@from datetime import timedeltafrom typing import Annotated, List, Literal, Optional+from uuid import uuid4from fastapi import APIRouter, Body, Depends, HTTPException, Query, status@@ -713,6 +714,91 @@ class CompactionResponse(BaseModel):num_messages_after: int+ "/{conversation_id}/recompile",+ response_model=str,+ operation_id="recompile_conversation",+)+async def recompile_conversation(+ conversation_id: ConversationIdOrDefault,+ request: Optional[CompactionRequest] = Body(default=None),+ server: SyncServer = Depends(get_letta_server),+ headers: HeaderParams = Depends(get_headers),+ dry_run: bool = Query(+ False,+ description="If True, do not persist changes; still returns the compiled system prompt.",+ ),+):+ """Manually trigger system prompt recompilation for a conversation."""+ actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)++ resolved_agent_id = None+ if conversation_id == "default" and request and request.agent_id:+ resolved_agent_id = request.agent_id+ elif conversation_id.startswith("agent-"):+ resolved_agent_id = conversation_id++ if resolved_agent_id:+ _, system_message, _, _ = await server.agent_manager.rebuild_system_prompt_async(+ agent_id=resolved_agent_id,+ actor=actor,+ force=True,+ update_timestamp=True,+ dry_run=dry_run,+ )++ if system_message is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No system message found for agent '{resolved_agent_id}'")++ return system_message.to_openai_dict().get("content", "")++ conversation = await conversation_manager.get_conversation_by_id(+ conversation_id=conversation_id,+ actor=actor,+ )++ _, system_message, _, _ = await server.agent_manager.rebuild_system_prompt_async(+ agent_id=conversation.agent_id,+ actor=actor,+ force=True,+ update_timestamp=True,+ dry_run=True,+ )++ if system_message is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No system message found for conversation '{conversation_id}'")++ compiled_content = system_message.to_openai_dict().get("content", "")++ if not dry_run:+ in_context_messages = await conversation_manager.get_messages_for_conversation(+ conversation_id=conversation_id,+ actor=actor,+ )+ if not in_context_messages:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="No in-context messages found for this conversation.",+ )++ existing_system_message = in_context_messages[0]+ if existing_system_message.role != "system":+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Conversation does not have a system message in the first position.",+ )++ temp_message = existing_system_message.model_copy(update={"text": compiled_content})+ await server.message_manager.update_message_by_id_async(+ message_id=existing_system_message.id,+ message_update=temp_message,+ actor=actor,+ project_id=conversation.project_id,+ )++ return compiled_content++@router.post("/{conversation_id}/compact", response_model=CompactionResponse, operation_id="compact_conversation")async def compact_conversation(conversation_id: ConversationIdOrDefault,diff --git a/tests/integration_test_conversations_sdk.py b/tests/integration_test_conversations_sdk.pyindex 5c38d725d..4d384d81b 100644--- a/tests/integration_test_conversations_sdk.py+++ b/tests/integration_test_conversations_sdk.py@@ -949,6 +949,116 @@ class TestConversationDelete:assert response.status_code == 404, "Updating deleted conversation should return 404"+class TestConversationRecompile:+ """Tests for the conversation recompile endpoint."""++ def test_recompile_conversation_updates_existing_conversation_system_message(self, client: Letta, server_url: str):+ unique_marker = f"RECOMPILE_MARKER_{uuid.uuid4().hex[:8]}"++ agent = client.agents.create(+ name=f"test_conv_recompile_{uuid.uuid4().hex[:8]}",+ model="openai/gpt-4o-mini",+ embedding="openai/text-embedding-3-small",+ memory_blocks=[+ {"label": "human", "value": "The user is a test user."},+ {"label": "persona", "value": "You are a helpful assistant."},+ ],+ )++ try:+ conversation = client.conversations.create(agent_id=agent.id)+ list(+ client.conversations.messages.create(+ conversation_id=conversation.id,+ messages=[{"role": "user", "content": "Hello, just a quick test."}],+ )+ )++ original_messages = client.conversations.messages.list(conversation_id=conversation.id, order="asc")+ assert original_messages[0].message_type == "system_message"+ assert unique_marker not in original_messages[0].content++ client.agents.blocks.update(+ agent_id=agent.id,+ block_label="human",+ value=f"The user is a test user. {unique_marker}",+ )++ before_recompile_messages = client.conversations.messages.list(conversation_id=conversation.id, order="asc")+ assert unique_marker not in before_recompile_messages[0].content++ response = requests.post(f"{server_url}/v1/conversations/{conversation.id}/recompile")+ assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.text}"+ assert unique_marker in response.json()++ after_recompile_messages = client.conversations.messages.list(conversation_id=conversation.id, order="asc")+ assert unique_marker in after_recompile_messages[0].content++ finally:+ client.agents.delete(agent_id=agent.id)++ def test_recompile_conversation_dry_run_does_not_persist(self, client: Letta, server_url: str):+ unique_marker = f"DRY_RUN_MARKER_{uuid.uuid4().hex[:8]}"++ agent = client.agents.create(+ name=f"test_conv_recompile_dry_run_{uuid.uuid4().hex[:8]}",+ model="openai/gpt-4o-mini",+ embedding="openai/text-embedding-3-small",+ memory_blocks=[+ {"label": "human", "value": "The user is a test user."},+ {"label": "persona", "value": "You are a helpful assistant."},+ ],+ )++ try:+ conversation = client.conversations.create(agent_id=agent.id)+ client.agents.blocks.update(+ agent_id=agent.id,+ block_label="human",+ value=f"The user is a test user. {unique_marker}",+ )++ response = requests.post(f"{server_url}/v1/conversations/{conversation.id}/recompile", params={"dry_run": "true"})+ assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.text}"+ assert unique_marker in response.json()++ messages = client.conversations.messages.list(conversation_id=conversation.id, order="asc")+ assert unique_marker not in messages[0].content++ finally:+ client.agents.delete(agent_id=agent.id)++ def test_recompile_conversation_agent_direct_mode(self, client: Letta, server_url: str):+ unique_marker = f"AGENT_DIRECT_MARKER_{uuid.uuid4().hex[:8]}"++ agent = client.agents.create(+ name=f"test_conv_recompile_default_{uuid.uuid4().hex[:8]}",+ model="openai/gpt-4o-mini",+ embedding="openai/text-embedding-3-small",+ memory_blocks=[+ {"label": "human", "value": "The user is a test user."},+ {"label": "persona", "value": "You are a helpful assistant."},+ ],+ )++ try:+ client.agents.blocks.update(+ agent_id=agent.id,+ block_label="human",+ value=f"The user is a test user. {unique_marker}",+ )++ response = requests.post(+ f"{server_url}/v1/conversations/default/recompile",+ json={"agent_id": agent.id},+ )+ assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.text}"+ assert unique_marker in response.json()++ finally:+ client.agents.delete(agent_id=agent.id)++class TestConversationCompact:"""Tests for the conversation compact (summarization) endpoint."""