Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

feat: Remove jinja2 (#2971)

Matthew Zhou3c2911e9ae3d
diff --git a/letta/agent.py b/letta/agent.py
index f1d1f3d03..0a0394285 100644
--- a/letta/agent.py
+++ b/letta/agent.py
@@ -42,7 +42,7 @@ from letta.memory import summarize_messages
from letta.orm import User
from letta.otel.tracing import log_event, trace_method
from letta.prompts.prompt_generator import PromptGenerator
-from letta.schemas.agent import AgentState, AgentStepResponse, UpdateAgent, get_prompt_template_for_agent_type
+from letta.schemas.agent import AgentState, AgentStepResponse, UpdateAgent
from letta.schemas.block import BlockUpdate
from letta.schemas.embedding_config import EmbeddingConfig
from letta.schemas.enums import MessageRole, ProviderType, StepStatus, ToolType
@@ -221,7 +221,7 @@ class Agent(BaseAgent):
self.agent_state.memory = Memory(
blocks=[self.block_manager.get_block_by_id(block.id, actor=self.user) for block in self.agent_state.memory.get_blocks()],
file_blocks=self.agent_state.memory.file_blocks,
- prompt_template=get_prompt_template_for_agent_type(self.agent_state.agent_type),
+ agent_type=self.agent_state.agent_type,
)
# NOTE: don't do this since re-buildin the memory is handled at the start of the step
@@ -880,7 +880,7 @@ class Agent(BaseAgent):
current_persisted_memory = Memory(
blocks=[self.block_manager.get_block_by_id(block.id, actor=self.user) for block in self.agent_state.memory.get_blocks()],
file_blocks=self.agent_state.memory.file_blocks,
- prompt_template=get_prompt_template_for_agent_type(self.agent_state.agent_type),
+ agent_type=self.agent_state.agent_type,
) # read blocks from DB
self.update_memory_if_changed(current_persisted_memory)
diff --git a/letta/agents/agent_loop.py b/letta/agents/agent_loop.py
index 881044a06..507dc4d17 100644
--- a/letta/agents/agent_loop.py
+++ b/letta/agents/agent_loop.py
@@ -3,7 +3,8 @@ from typing import TYPE_CHECKING
from letta.agents.base_agent_v2 import BaseAgentV2
from letta.agents.letta_agent_v2 import LettaAgentV2
from letta.groups.sleeptime_multi_agent_v3 import SleeptimeMultiAgentV3
-from letta.schemas.agent import AgentState, AgentType
+from letta.schemas.agent import AgentState
+from letta.schemas.enums import AgentType
if TYPE_CHECKING:
from letta.orm import User
diff --git a/letta/agents/base_agent.py b/letta/agents/base_agent.py
index 99715e0b2..271e4502e 100644
--- a/letta/agents/base_agent.py
+++ b/letta/agents/base_agent.py
@@ -139,7 +139,7 @@ class BaseAgent(ABC):
curr_dynamic_section = extract_dynamic_section(curr_system_message_text)
# generate just the memory string with current state for comparison
- curr_memory_str = await agent_state.memory.compile_in_thread_async(
+ curr_memory_str = agent_state.memory.compile(
tool_usage_rules=tool_constraint_block, sources=agent_state.sources, max_files_open=agent_state.max_files_open
)
new_dynamic_section = extract_dynamic_section(curr_memory_str)
diff --git a/letta/agents/letta_agent_v2.py b/letta/agents/letta_agent_v2.py
index b8814d5c4..5093059e6 100644
--- a/letta/agents/letta_agent_v2.py
+++ b/letta/agents/letta_agent_v2.py
@@ -29,8 +29,8 @@ from letta.local_llm.constants import INNER_THOUGHTS_KWARG
from letta.log import get_logger
from letta.otel.tracing import log_event, trace_method, tracer
from letta.prompts.prompt_generator import PromptGenerator
-from letta.schemas.agent import AgentState, AgentType, UpdateAgent
-from letta.schemas.enums import JobStatus, MessageRole, MessageStreamStatus, StepStatus
+from letta.schemas.agent import AgentState, UpdateAgent
+from letta.schemas.enums import AgentType, JobStatus, MessageRole, MessageStreamStatus, StepStatus
from letta.schemas.letta_message import LettaMessage, MessageType
from letta.schemas.letta_message_content import OmittedReasoningContent, ReasoningContent, RedactedReasoningContent, TextContent
from letta.schemas.letta_response import LettaResponse
@@ -679,7 +679,7 @@ class LettaAgentV2(BaseAgentV2):
curr_dynamic_section = extract_dynamic_section(curr_system_message_text)
# generate just the memory string with current state for comparison
- curr_memory_str = await agent_state.memory.compile_in_thread_async(
+ curr_memory_str = agent_state.memory.compile(
tool_usage_rules=tool_constraint_block, sources=agent_state.sources, max_files_open=agent_state.max_files_open
)
new_dynamic_section = extract_dynamic_section(curr_memory_str)
diff --git a/letta/agents/voice_agent.py b/letta/agents/voice_agent.py
index e3c20acfe..f320986eb 100644
--- a/letta/agents/voice_agent.py
+++ b/letta/agents/voice_agent.py
@@ -14,8 +14,8 @@ from letta.helpers.tool_execution_helper import add_pre_execution_message, enabl
from letta.interfaces.openai_chat_completions_streaming_interface import OpenAIChatCompletionsStreamingInterface
from letta.log import get_logger
from letta.prompts.prompt_generator import PromptGenerator
-from letta.schemas.agent import AgentState, AgentType
-from letta.schemas.enums import MessageRole, ToolType
+from letta.schemas.agent import AgentState
+from letta.schemas.enums import AgentType, MessageRole, ToolType
from letta.schemas.letta_response import LettaResponse
from letta.schemas.message import Message, MessageCreate
from letta.schemas.openai.chat_completion_request import (
diff --git a/letta/orm/agent.py b/letta/orm/agent.py
index 49c459824..7587bca5e 100644
--- a/letta/orm/agent.py
+++ b/letta/orm/agent.py
@@ -13,8 +13,9 @@ from letta.orm.identity import Identity
from letta.orm.mixins import OrganizationMixin, ProjectMixin, TemplateEntityMixin, TemplateMixin
from letta.orm.organization import Organization
from letta.orm.sqlalchemy_base import SqlalchemyBase
-from letta.schemas.agent import AgentState as PydanticAgentState, AgentType, get_prompt_template_for_agent_type
+from letta.schemas.agent import AgentState as PydanticAgentState
from letta.schemas.embedding_config import EmbeddingConfig
+from letta.schemas.enums import AgentType
from letta.schemas.llm_config import LLMConfig
from letta.schemas.memory import Memory
from letta.schemas.response_format import ResponseFormatUnion
@@ -249,7 +250,7 @@ class Agent(SqlalchemyBase, OrganizationMixin, ProjectMixin, TemplateEntityMixin
if (block := b.to_pydantic_block(per_file_view_window_char_limit=self._get_per_file_view_window_char_limit()))
is not None
],
- prompt_template=get_prompt_template_for_agent_type(self.agent_type),
+ agent_type=self.agent_type,
),
"identity_ids": lambda: [i.id for i in self.identities],
"multi_agent_group": lambda: self.multi_agent_group,
@@ -366,7 +367,7 @@ class Agent(SqlalchemyBase, OrganizationMixin, ProjectMixin, TemplateEntityMixin
for b in file_agents
if (block := b.to_pydantic_block(per_file_view_window_char_limit=self._get_per_file_view_window_char_limit())) is not None
],
- prompt_template=get_prompt_template_for_agent_type(self.agent_type),
+ agent_type=self.agent_type,
)
state["identity_ids"] = [i.id for i in identities]
state["multi_agent_group"] = multi_agent_group
diff --git a/letta/prompts/prompt_generator.py b/letta/prompts/prompt_generator.py
index 4930ff26f..8c2623ae5 100644
--- a/letta/prompts/prompt_generator.py
+++ b/letta/prompts/prompt_generator.py
@@ -94,7 +94,7 @@ class PromptGenerator:
timezone: str,
user_defined_variables: Optional[dict] = None,
append_icm_if_missing: bool = True,
- template_format: Literal["f-string", "mustache", "jinja2"] = "f-string",
+ template_format: Literal["f-string", "mustache"] = "f-string",
previous_message_count: int = 0,
archival_memory_size: int = 0,
archive_tags: Optional[List[str]] = None,
@@ -150,7 +150,7 @@ class PromptGenerator:
raise ValueError(f"Failed to format system prompt - {str(e)}. System prompt value:\n{system_prompt}")
else:
- # TODO support for mustache and jinja2
+ # TODO support for mustache
raise NotImplementedError(template_format)
return formatted_prompt
@@ -164,7 +164,7 @@ class PromptGenerator:
timezone: str,
user_defined_variables: Optional[dict] = None,
append_icm_if_missing: bool = True,
- template_format: Literal["f-string", "mustache", "jinja2"] = "f-string",
+ template_format: Literal["f-string", "mustache"] = "f-string",
previous_message_count: int = 0,
archival_memory_size: int = 0,
tool_rules_solver: Optional[ToolRulesSolver] = None,
@@ -181,7 +181,7 @@ class PromptGenerator:
else:
pass
- memory_with_sources = await in_context_memory.compile_in_thread_async(
+ memory_with_sources = in_context_memory.compile(
tool_usage_rules=tool_constraint_block, sources=sources, max_files_open=max_files_open
)
diff --git a/letta/schemas/agent.py b/letta/schemas/agent.py
index 5ca237237..f16e72528 100644
--- a/letta/schemas/agent.py
+++ b/letta/schemas/agent.py
@@ -1,5 +1,4 @@
from datetime import datetime
-from enum import Enum
from typing import Dict, List, Optional
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
@@ -7,6 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
from letta.constants import CORE_MEMORY_LINE_NUMBER_WARNING, DEFAULT_EMBEDDING_CHUNK_SIZE
from letta.schemas.block import CreateBlock
from letta.schemas.embedding_config import EmbeddingConfig
+from letta.schemas.enums import AgentType
from letta.schemas.environment_variables import AgentEnvironmentVariable
from letta.schemas.file import FileStatus
from letta.schemas.group import Group
@@ -22,21 +22,6 @@ from letta.schemas.tool_rule import ToolRule
from letta.utils import calculate_file_defaults_based_on_context_window, create_random_username
-class AgentType(str, Enum):
- """
- Enum to represent the type of agent.
- """
-
- memgpt_agent = "memgpt_agent" # the OG set of memgpt tools
- memgpt_v2_agent = "memgpt_v2_agent" # memgpt style tools, but refreshed
- react_agent = "react_agent" # basic react agent, no memory tools
- workflow_agent = "workflow_agent" # workflow with auto-clearing message buffer
- split_thread_agent = "split_thread_agent"
- sleeptime_agent = "sleeptime_agent"
- voice_convo_agent = "voice_convo_agent"
- voice_sleeptime_agent = "voice_sleeptime_agent"
-
-
class AgentState(OrmMetadataBase, validate_assignment=True):
"""
Representation of an agent's state. This is the state of the agent at a given time, and is persisted in the DB backend. The state has all the information needed to recreate a persisted agent.
@@ -383,196 +368,5 @@ class AgentStepResponse(BaseModel):
def get_prompt_template_for_agent_type(agent_type: Optional[AgentType] = None):
- # Workflow agents and ReAct agents don't use memory blocks
- # However, they still allow files to be injected into the context
- if agent_type == AgentType.react_agent or agent_type == AgentType.workflow_agent:
- return (
- "{% if sources %}"
- "<directories>\n"
- "{% if max_files_open %}"
- "<file_limits>\n"
- "- current_files_open={{ file_blocks|selectattr('value')|list|length }}\n"
- "- max_files_open={{ max_files_open }}\n"
- "</file_limits>\n"
- "{% endif %}"
- "{% for source in sources %}"
- f'<directory name="{{{{ source.name }}}}">\n'
- "{% if source.description %}"
- "<description>{{ source.description }}</description>\n"
- "{% endif %}"
- "{% if source.instructions %}"
- "<instructions>{{ source.instructions }}</instructions>\n"
- "{% endif %}"
- "{% if file_blocks %}"
- "{% for block in file_blocks %}"
- "{% if block.source_id and block.source_id == source.id %}"
- f"<file status=\"{{{{ '{FileStatus.open.value}' if block.value else '{FileStatus.closed.value}' }}}}\">\n"
- "<{{ block.label }}>\n"
- "<description>\n"
- "{{ block.description }}\n"
- "</description>\n"
- "<metadata>"
- "{% if block.read_only %}\n- read_only=true{% endif %}\n"
- "- chars_current={{ block.value|length }}\n"
- "- chars_limit={{ block.limit }}\n"
- "</metadata>\n"
- "<value>\n"
- "{{ block.value }}\n"
- "</value>\n"
- "</file>\n"
- "{% endif %}"
- "{% endfor %}"
- "{% endif %}"
- "</directory>\n"
- "{% endfor %}"
- "</directories>"
- "{% endif %}"
- )
-
- # Sleeptime agents use the MemGPT v2 memory tools (line numbers)
- # MemGPT v2 tools use line-number, so core memory blocks should have line numbers
- elif agent_type == AgentType.sleeptime_agent or agent_type == AgentType.memgpt_v2_agent:
- return (
- "<memory_blocks>\nThe following memory blocks are currently engaged in your core memory unit:\n\n"
- "{% for block in blocks %}"
- "<{{ block.label }}>\n"
- "<description>\n"
- "{{ block.description }}\n"
- "</description>\n"
- "<metadata>"
- "{% if block.read_only %}\n- read_only=true{% endif %}\n"
- "- chars_current={{ block.value|length }}\n"
- "- chars_limit={{ block.limit }}\n"
- "</metadata>\n"
- "<value>\n"
- f"{CORE_MEMORY_LINE_NUMBER_WARNING}\n"
- "{% for line in block.value.split('\\n') %}"
- "Line {{ loop.index }}: {{ line }}\n"
- "{% endfor %}"
- "</value>\n"
- "</{{ block.label }}>\n"
- "{% if not loop.last %}\n{% endif %}"
- "{% endfor %}"
- "\n</memory_blocks>"
- "\n\n{% if tool_usage_rules %}"
- "<tool_usage_rules>\n"
- "{{ tool_usage_rules.description }}\n\n"
- "{{ tool_usage_rules.value }}\n"
- "</tool_usage_rules>"
- "{% endif %}"
- "\n\n{% if sources %}"
- "<directories>\n"
- "{% if max_files_open %}"
- "<file_limits>\n"
- "- current_files_open={{ file_blocks|selectattr('value')|list|length }}\n"
- "- max_files_open={{ max_files_open }}\n"
- "</file_limits>\n"
- "{% endif %}"
- "{% for source in sources %}"
- f'<directory name="{{{{ source.name }}}}">\n'
- "{% if source.description %}"
- "<description>{{ source.description }}</description>\n"
- "{% endif %}"
- "{% if source.instructions %}"
- "<instructions>{{ source.instructions }}</instructions>\n"
- "{% endif %}"
- "{% if file_blocks %}"
- "{% for block in file_blocks %}"
- "{% if block.source_id and block.source_id == source.id %}"
- f"<file status=\"{{{{ '{FileStatus.open.value}' if block.value else '{FileStatus.closed.value}' }}}}\" name=\"{{{{ block.label }}}}\">\n"
- "{% if block.description %}"
- "<description>\n"
- "{{ block.description }}\n"
- "</description>\n"
- "{% endif %}"
- "<metadata>"
- "{% if block.read_only %}\n- read_only=true{% endif %}\n"
- "- chars_current={{ block.value|length }}\n"
- "- chars_limit={{ block.limit }}\n"
- "</metadata>\n"
- "{% if block.value %}"
- "<value>\n"
- "{{ block.value }}\n"
- "</value>\n"
- "{% endif %}"
- "</file>\n"
- "{% endif %}"
- "{% endfor %}"
- "{% endif %}"
- "</directory>\n"
- "{% endfor %}"
- "</directories>"
- "{% endif %}"
- )
-
- # All other agent types use memory blocks
- else:
- return (
- "<memory_blocks>\nThe following memory blocks are currently engaged in your core memory unit:\n\n"
- "{% for block in blocks %}"
- "<{{ block.label }}>\n"
- "<description>\n"
- "{{ block.description }}\n"
- "</description>\n"
- "<metadata>"
- "{% if block.read_only %}\n- read_only=true{% endif %}\n"
- "- chars_current={{ block.value|length }}\n"
- "- chars_limit={{ block.limit }}\n"
- "</metadata>\n"
- "<value>\n"
- "{{ block.value }}\n"
- "</value>\n"
- "</{{ block.label }}>\n"
- "{% if not loop.last %}\n{% endif %}"
- "{% endfor %}"
- "\n</memory_blocks>"
- "\n\n{% if tool_usage_rules %}"
- "<tool_usage_rules>\n"
- "{{ tool_usage_rules.description }}\n\n"
- "{{ tool_usage_rules.value }}\n"
- "</tool_usage_rules>"
- "{% endif %}"
- "\n\n{% if sources %}"
- "<directories>\n"
- "{% if max_files_open %}"
- "<file_limits>\n"
- "- current_files_open={{ file_blocks|selectattr('value')|list|length }}\n"
- "- max_files_open={{ max_files_open }}\n"
- "</file_limits>\n"
- "{% endif %}"
- "{% for source in sources %}"
- f'<directory name="{{{{ source.name }}}}">\n'
- "{% if source.description %}"
- "<description>{{ source.description }}</description>\n"
- "{% endif %}"
- "{% if source.instructions %}"
- "<instructions>{{ source.instructions }}</instructions>\n"
- "{% endif %}"
- "{% if file_blocks %}"
- "{% for block in file_blocks %}"
- "{% if block.source_id and block.source_id == source.id %}"
- f"<file status=\"{{{{ '{FileStatus.open.value}' if block.value else '{FileStatus.closed.value}' }}}}\" name=\"{{{{ block.label }}}}\">\n"
- "{% if block.description %}"
- "<description>\n"
- "{{ block.description }}\n"
- "</description>\n"
- "{% endif %}"
- "<metadata>"
- "{% if block.read_only %}\n- read_only=true{% endif %}\n"
- "- chars_current={{ block.value|length }}\n"
- "- chars_limit={{ block.limit }}\n"
- "</metadata>\n"
- "{% if block.value %}"
- "<value>\n"
- "{{ block.value }}\n"
- "</value>\n"
- "{% endif %}"
- "</file>\n"
- "{% endif %}"
- "{% endfor %}"
- "{% endif %}"
- "</directory>\n"
- "{% endfor %}"
- "</directories>"
- "{% endif %}"
- )
+ """Deprecated. Templates are not used anymore; fast renderer handles formatting."""
+ return ""
diff --git a/letta/schemas/enums.py b/letta/schemas/enums.py
index 65afde6e0..cbf50c895 100644
--- a/letta/schemas/enums.py
+++ b/letta/schemas/enums.py
@@ -21,6 +21,21 @@ class ProviderType(str, Enum):
xai = "xai"
+class AgentType(str, Enum):
+ """
+ Enum to represent the type of agent.
+ """
+
+ memgpt_agent = "memgpt_agent" # the OG set of memgpt tools
+ memgpt_v2_agent = "memgpt_v2_agent" # memgpt style tools, but refreshed
+ react_agent = "react_agent" # basic react agent, no memory tools
+ workflow_agent = "workflow_agent" # workflow with auto-clearing message buffer
+ split_thread_agent = "split_thread_agent"
+ sleeptime_agent = "sleeptime_agent"
+ voice_convo_agent = "voice_convo_agent"
+ voice_sleeptime_agent = "voice_sleeptime_agent"
+
+
class ProviderCategory(str, Enum):
base = "base"
byok = "byok"
diff --git a/letta/schemas/memory.py b/letta/schemas/memory.py
index bd7908a8d..934ced641 100644
--- a/letta/schemas/memory.py
+++ b/letta/schemas/memory.py
@@ -1,20 +1,17 @@
import asyncio
import logging
from datetime import datetime
-from typing import TYPE_CHECKING, List, Optional
-
-from jinja2 import Template, TemplateSyntaxError
-from pydantic import BaseModel, Field, field_validator
-
-# Forward referencing to avoid circular import with Agent -> Memory -> Agent
-if TYPE_CHECKING:
- pass
+from io import StringIO
+from typing import TYPE_CHECKING, List, Optional, Union
from openai.types.beta.function_tool import FunctionTool as OpenAITool
+from pydantic import BaseModel, Field, field_validator
-from letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMIT
+from letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMIT, CORE_MEMORY_LINE_NUMBER_WARNING
from letta.otel.tracing import trace_method
from letta.schemas.block import Block, FileBlock
+from letta.schemas.enums import AgentType
+from letta.schemas.file import FileStatus
from letta.schemas.message import Message
@@ -23,12 +20,9 @@ class ContextWindowOverview(BaseModel):
Overview of the context window, including the number of messages and tokens.
"""
- # top-level information
context_window_size_max: int = Field(..., description="The maximum amount of tokens the context window can hold.")
context_window_size_current: int = Field(..., description="The current number of tokens in the context window.")
- # context window breakdown (in messages)
- # (technically not in the context window, but useful to know)
num_messages: int = Field(..., description="The number of messages in the context window.")
num_archival_memory: int = Field(..., description="The number of messages in the archival memory.")
num_recall_memory: int = Field(..., description="The number of messages in the recall memory.")
@@ -39,9 +33,6 @@ class ContextWindowOverview(BaseModel):
..., description="The metadata summary of the external memory sources (archival + recall metadata)."
)
- # context window breakdown (in tokens)
- # this should all add up to context_window_size_current
-
num_tokens_system: int = Field(..., description="The number of tokens in the system prompt.")
system_prompt: str = Field(..., description="The content of the system prompt.")
@@ -55,8 +46,6 @@ class ContextWindowOverview(BaseModel):
functions_definitions: Optional[List[OpenAITool]] = Field(..., description="The content of the functions definitions.")
num_tokens_messages: int = Field(..., description="The number of tokens in the messages list.")
- # TODO make list of messages?
- # messages: List[dict] = Field(..., description="The messages in the context window.")
messages: List[Message] = Field(..., description="The messages in the context window.")
@@ -67,7 +56,7 @@ class Memory(BaseModel, validate_assignment=True):
"""
- # Memory.block contains the list of memory blocks in the core memory
+ agent_type: Optional[Union["AgentType", str]] = Field(None, description="Agent type controlling prompt rendering.")
blocks: List[Block] = Field(..., description="Memory blocks contained in the agent's in-context memory")
file_blocks: List[FileBlock] = Field(
default_factory=list, description="Special blocks representing the agent's in-context memory of an attached file"
@@ -97,111 +86,238 @@ class Memory(BaseModel, validate_assignment=True):
return unique_blocks
- # Memory.template is a Jinja2 template for compiling memory module into a prompt string.
- prompt_template: str = Field(
- default="{% for block in blocks %}"
- "<{{ block.label }}>\n"
- "<metadata>"
- 'read_only="{{ block.read_only}}" chars_current="{{ block.value|length }}" chars_limit="{{ block.limit }}"'
- "</metadata>"
- "<value>"
- "{{ block.value }}\n"
- "</value>"
- "</{{ block.label }}>\n"
- "{% if not loop.last %}\n{% endif %}"
- "{% endfor %}",
- description="Jinja2 template for compiling memory blocks into a prompt string",
- )
+ prompt_template: str = Field(default="", description="Deprecated. Ignored for performance.")
def get_prompt_template(self) -> str:
- """Return the current Jinja2 template string."""
+ """Return the stored (deprecated) prompt template string."""
return str(self.prompt_template)
@trace_method
def set_prompt_template(self, prompt_template: str):
- """
- Set a new Jinja2 template string.
- Validates the template syntax and compatibility with current memory structure.
- """
- try:
- # Validate Jinja2 syntax
- Template(prompt_template)
-
- # Validate compatibility with current memory structure
- Template(prompt_template).render(blocks=self.blocks, file_blocks=self.file_blocks, sources=[], max_files_open=None)
-
- # If we get here, the template is valid and compatible
- self.prompt_template = prompt_template
- except TemplateSyntaxError as e:
- raise ValueError(f"Invalid Jinja2 template syntax: {str(e)}")
- except Exception as e:
- raise ValueError(f"Prompt template is not compatible with current memory structure: {str(e)}")
+ """Deprecated. Stores the provided string but is not used for rendering."""
+ self.prompt_template = prompt_template
@trace_method
async def set_prompt_template_async(self, prompt_template: str):
- """
- Async version of set_prompt_template that doesn't block the event loop.
- """
- try:
- # Validate Jinja2 syntax with async enabled
- Template(prompt_template)
-
- # Validate compatibility with current memory structure - use async rendering
- template = Template(prompt_template)
- await asyncio.to_thread(template.render, blocks=self.blocks, file_blocks=self.file_blocks, sources=[], max_files_open=None)
-
- # If we get here, the template is valid and compatible
- self.prompt_template = prompt_template
- except TemplateSyntaxError as e:
- raise ValueError(f"Invalid Jinja2 template syntax: {str(e)}")
- except Exception as e:
- raise ValueError(f"Prompt template is not compatible with current memory structure: {str(e)}")
+ """Deprecated. Async setter that stores the string but does not validate or use it."""
+ self.prompt_template = prompt_template
@trace_method
+ def _render_memory_blocks_standard(self, s: StringIO):
+ if len(self.blocks) == 0:
+ # s.write("<memory_blocks></memory_blocks>") # TODO: consider empty tags
+ s.write("")
+ return
+
+ s.write("<memory_blocks>\nThe following memory blocks are currently engaged in your core memory unit:\n\n")
+ for idx, block in enumerate(self.blocks):
+ label = block.label or "block"
+ value = block.value or ""
+ desc = block.description or ""
+ chars_current = len(value)
+ limit = block.limit if block.limit is not None else 0
+
+ s.write(f"<{label}>\n")
+ s.write("<description>\n")
+ s.write(f"{desc}\n")
+ s.write("</description>\n")
+ s.write("<metadata>")
+ if getattr(block, "read_only", False):
+ s.write("\n- read_only=true")
+ s.write(f"\n- chars_current={chars_current}")
+ s.write(f"\n- chars_limit={limit}\n")
+ s.write("</metadata>\n")
+ s.write("<value>\n")
+ s.write(f"{value}\n")
+ s.write("</value>\n")
+ s.write(f"</{label}>\n")
+ if idx != len(self.blocks) - 1:
+ s.write("\n")
+ s.write("\n</memory_blocks>")
+
+ def _render_memory_blocks_line_numbered(self, s: StringIO):
+ s.write("<memory_blocks>\nThe following memory blocks are currently engaged in your core memory unit:\n\n")
+ for idx, block in enumerate(self.blocks):
+ label = block.label or "block"
+ value = block.value or ""
+ desc = block.description or ""
+ limit = block.limit if block.limit is not None else 0
+
+ s.write(f"<{label}>\n")
+ s.write("<description>\n")
+ s.write(f"{desc}\n")
+ s.write("</description>\n")
+ s.write("<metadata>")
+ if getattr(block, "read_only", False):
+ s.write("\n- read_only=true")
+ s.write(f"\n- chars_current={len(value)}")
+ s.write(f"\n- chars_limit={limit}\n")
+ s.write("</metadata>\n")
+ s.write("<value>\n")
+ s.write(f"{CORE_MEMORY_LINE_NUMBER_WARNING}\n")
+ if value:
+ for i, line in enumerate(value.split("\n"), start=1):
+ s.write(f"Line {i}: {line}\n")
+ s.write("</value>\n")
+ s.write(f"</{label}>\n")
+ if idx != len(self.blocks) - 1:
+ s.write("\n")
+ s.write("\n</memory_blocks>")
+
+ def _render_directories_common(self, s: StringIO, sources, max_files_open):
+ s.write("\n\n<directories>\n")
+ if max_files_open is not None:
+ current_open = sum(1 for b in self.file_blocks if getattr(b, "value", None))
+ s.write("<file_limits>\n")
+ s.write(f"- current_files_open={current_open}\n")
+ s.write(f"- max_files_open={max_files_open}\n")
+ s.write("</file_limits>\n")
+
+ for source in sources:
+ source_name = getattr(source, "name", "")
+ source_desc = getattr(source, "description", None)
+ source_instr = getattr(source, "instructions", None)
+ source_id = getattr(source, "id", None)
+
+ s.write(f'<directory name="{source_name}">\n')
+ if source_desc:
+ s.write(f"<description>{source_desc}</description>\n")
+ if source_instr:
+ s.write(f"<instructions>{source_instr}</instructions>\n")
+
+ if self.file_blocks:
+ for fb in self.file_blocks:
+ if source_id is not None and getattr(fb, "source_id", None) == source_id:
+ status = FileStatus.open.value if getattr(fb, "value", None) else FileStatus.closed.value
+ label = fb.label or "file"
+ desc = fb.description or ""
+ chars_current = len(fb.value or "")
+ limit = fb.limit if fb.limit is not None else 0
+
+ s.write(f'<file status="{status}" name="{label}">\n')
+ if desc:
+ s.write("<description>\n")
+ s.write(f"{desc}\n")
+ s.write("</description>\n")
+ s.write("<metadata>")
+ if getattr(fb, "read_only", False):
+ s.write("\n- read_only=true")
+ s.write(f"\n- chars_current={chars_current}\n")
+ s.write(f"- chars_limit={limit}\n")
+ s.write("</metadata>\n")
+ if getattr(fb, "value", None):
+ s.write("<value>\n")
+ s.write(f"{fb.value}\n")
+ s.write("</value>\n")
+ s.write("</file>\n")
+
+ s.write("</directory>\n")
+ s.write("</directories>")
+
+ def _render_directories_react(self, s: StringIO, sources, max_files_open):
+ s.write("\n\n<directories>\n")
+ if max_files_open is not None:
+ current_open = sum(1 for b in self.file_blocks if getattr(b, "value", None))
+ s.write("<file_limits>\n")
+ s.write(f"- current_files_open={current_open}\n")
+ s.write(f"- max_files_open={max_files_open}\n")
+ s.write("</file_limits>\n")
+
+ for source in sources:
+ source_name = getattr(source, "name", "")
+ source_desc = getattr(source, "description", None)
+ source_instr = getattr(source, "instructions", None)
+ source_id = getattr(source, "id", None)
+
+ s.write(f'<directory name="{source_name}">\n')
+ if source_desc:
+ s.write(f"<description>{source_desc}</description>\n")
+ if source_instr:
+ s.write(f"<instructions>{source_instr}</instructions>\n")
+
+ if self.file_blocks:
+ for fb in self.file_blocks:
+ if source_id is not None and getattr(fb, "source_id", None) == source_id:
+ status = FileStatus.open.value if getattr(fb, "value", None) else FileStatus.closed.value
+ label = fb.label or "file"
+ desc = fb.description or ""
+ chars_current = len(fb.value or "")
+ limit = fb.limit if fb.limit is not None else 0
+
+ s.write(f'<file status="{status}">\n')
+ s.write(f"<{label}>\n")
+ s.write("<description>\n")
+ s.write(f"{desc}\n")
+ s.write("</description>\n")
+ s.write("<metadata>")
+ if getattr(fb, "read_only", False):
+ s.write("\n- read_only=true")
+ s.write(f"\n- chars_current={chars_current}\n")
+ s.write(f"- chars_limit={limit}\n")
+ s.write("</metadata>\n")
+ s.write("<value>\n")
+ s.write(f"{fb.value or ''}\n")
+ s.write("</value>\n")
+ s.write(f"</{label}>\n")
+ s.write("</file>\n")
+
+ s.write("</directory>\n")
+ s.write("</directories>")
+
def compile(self, tool_usage_rules=None, sources=None, max_files_open=None) -> str:
- """Generate a string representation of the memory in-context using the Jinja2 template"""
- try:
- template = Template(self.prompt_template)
- return template.render(
- blocks=self.blocks,
- file_blocks=self.file_blocks,
- tool_usage_rules=tool_usage_rules,
- sources=sources,
- max_files_open=max_files_open,
- )
- except TemplateSyntaxError as e:
- raise ValueError(f"Invalid Jinja2 template syntax: {str(e)}")
- except Exception as e:
- raise ValueError(f"Prompt template is not compatible with current memory structure: {str(e)}")
+ """Efficiently render memory, tool rules, and sources into a prompt string."""
+ s = StringIO()
+
+ raw_type = self.agent_type.value if hasattr(self.agent_type, "value") else (self.agent_type or "")
+ norm_type = raw_type.lower()
+ is_react = norm_type in ("react_agent", "workflow_agent")
+ is_line_numbered = norm_type in ("sleeptime_agent", "memgpt_v2_agent")
+
+ # Memory blocks (not for react/workflow). Always include wrapper for preview/tests.
+ if not is_react:
+ if is_line_numbered:
+ self._render_memory_blocks_line_numbered(s)
+ else:
+ self._render_memory_blocks_standard(s)
+
+ if tool_usage_rules is not None:
+ desc = getattr(tool_usage_rules, "description", None) or ""
+ val = getattr(tool_usage_rules, "value", None) or ""
+ s.write("\n\n<tool_usage_rules>\n")
+ s.write(f"{desc}\n\n")
+ s.write(f"{val}\n")
+ s.write("</tool_usage_rules>")
+
+ if sources:
+ if is_react:
+ self._render_directories_react(s, sources, max_files_open)
+ else:
+ self._render_directories_common(s, sources, max_files_open)
+
+ return s.getvalue()
@trace_method
async def compile_async(self, tool_usage_rules=None, sources=None, max_files_open=None) -> str:
- """Async version of compile that doesn't block the event loop"""
- try:
- template = Template(self.prompt_template, enable_async=True)
- return await template.render_async(
- blocks=self.blocks,
- file_blocks=self.file_blocks,
- tool_usage_rules=tool_usage_rules,
- sources=sources,
- max_files_open=max_files_open,
- )
- except TemplateSyntaxError as e:
- raise ValueError(f"Invalid Jinja2 template syntax: {str(e)}")
- except Exception as e:
- raise ValueError(f"Prompt template is not compatible with current memory structure: {str(e)}")
+ """Async version that offloads to a thread for CPU-bound string building."""
+ return await asyncio.to_thread(
+ self.compile,
+ tool_usage_rules=tool_usage_rules,
+ sources=sources,
+ max_files_open=max_files_open,
+ )
@trace_method
async def compile_in_thread_async(self, tool_usage_rules=None, sources=None, max_files_open=None) -> str:
- """Compile the memory in a thread"""
- return await asyncio.to_thread(self.compile, tool_usage_rules=tool_usage_rules, sources=sources, max_files_open=max_files_open)
+ """Deprecated: use compile() instead."""
+ import warnings
+
+ warnings.warn("compile_in_thread_async is deprecated; use compile()", DeprecationWarning, stacklevel=2)
+ return self.compile(tool_usage_rules=tool_usage_rules, sources=sources, max_files_open=max_files_open)
def list_block_labels(self) -> List[str]:
"""Return a list of the block names held inside the memory object"""
- # return list(self.memory.keys())
return [block.label for block in self.blocks]
- # TODO: these should actually be label, not name
def get_block(self, label: str) -> Block:
"""Correct way to index into the memory.memory field, returns a Block"""
keys = []
@@ -213,7 +329,6 @@ class Memory(BaseModel, validate_assignment=True):
def get_blocks(self) -> List[Block]:
"""Return a list of the blocks held inside the memory object"""
- # return list(self.memory.values())
return self.blocks
def set_block(self, block: Block):
@@ -236,7 +351,6 @@ class Memory(BaseModel, validate_assignment=True):
raise ValueError(f"Block with label {label} does not exist")
-# TODO: ideally this is refactored into ChatMemory and the subclasses are given more specific names.
class BasicBlockMemory(Memory):
"""
BasicBlockMemory is a basic implemention of the Memory class, which takes in a list of blocks and links them to the memory object. These are editable by the agent via the core memory functions.
@@ -308,7 +422,6 @@ class ChatMemory(BasicBlockMemory):
human (str): The starter value for the human block.
limit (int): The character limit for each block.
"""
- # TODO: Should these be CreateBlocks?
super().__init__(blocks=[Block(value=persona, limit=limit, label="persona"), Block(value=human, limit=limit, label="human")])
diff --git a/letta/schemas/tool_rule.py b/letta/schemas/tool_rule.py
index 6056f3b4c..211ed9253 100644
--- a/letta/schemas/tool_rule.py
+++ b/letta/schemas/tool_rule.py
@@ -2,7 +2,6 @@ import json
import logging
from typing import Annotated, Any, Dict, List, Literal, Optional, Set, Union
-from jinja2 import Template
from pydantic import Field, field_validator
from letta.schemas.enums import ToolRuleType
@@ -17,7 +16,7 @@ class BaseToolRule(LettaBase):
type: ToolRuleType = Field(..., description="The type of the message.")
prompt_template: Optional[str] = Field(
None,
- description="Optional Jinja2 template for generating agent prompt about this tool rule. Template can use variables like 'tool_name' and rule-specific attributes.",
+ description="Optional template string (ignored). Rendering uses fast built-in formatting for performance.",
)
def __hash__(self):
@@ -34,22 +33,8 @@ class BaseToolRule(LettaBase):
raise NotImplementedError
def render_prompt(self) -> str | None:
- """Render the prompt template with this rule's attributes."""
- if not self.prompt_template:
- return None
-
- try:
- template = Template(self.prompt_template)
- return template.render(**self.model_dump())
- except Exception as e:
- logger.warning(
- "Failed to render prompt template for tool rule '%s' (type: %s). Template: '%s'. Error: %s",
- self.tool_name,
- self.type,
- self.prompt_template,
- e,
- )
- return None
+ """Default implementation returns None. Subclasses provide optimized strings."""
+ return None
class ChildToolRule(BaseToolRule):
@@ -60,8 +45,8 @@ class ChildToolRule(BaseToolRule):
type: Literal[ToolRuleType.constrain_child_tools] = ToolRuleType.constrain_child_tools
children: List[str] = Field(..., description="The children tools that can be invoked.")
prompt_template: Optional[str] = Field(
- default="<tool_rule>\nAfter using {{ tool_name }}, you must use one of these tools: {{ children | join(', ') }}\n</tool_rule>",
- description="Optional Jinja2 template for generating agent prompt about this tool rule.",
+ default=None,
+ description="Optional template string (ignored).",
)
def __hash__(self):
@@ -78,6 +63,10 @@ class ChildToolRule(BaseToolRule):
last_tool = tool_call_history[-1] if tool_call_history else None
return set(self.children) if last_tool == self.tool_name else available_tools
+ def render_prompt(self) -> str | None:
+ children_str = ", ".join(self.children)
+ return f"<tool_rule>\nAfter using {self.tool_name}, you must use one of these tools: {children_str}\n</tool_rule>"
+
class ParentToolRule(BaseToolRule):
"""
@@ -86,10 +75,7 @@ class ParentToolRule(BaseToolRule):
type: Literal[ToolRuleType.parent_last_tool] = ToolRuleType.parent_last_tool
children: List[str] = Field(..., description="The children tools that can be invoked.")
- prompt_template: Optional[str] = Field(
- default="<tool_rule>\n{{ children | join(', ') }} can only be used after {{ tool_name }}\n</tool_rule>",
- description="Optional Jinja2 template for generating agent prompt about this tool rule.",
- )
+ prompt_template: Optional[str] = Field(default=None, description="Optional template string (ignored).")
def __hash__(self):
"""Hash including children list (sorted for consistency)."""
@@ -105,6 +91,10 @@ class ParentToolRule(BaseToolRule):
last_tool = tool_call_history[-1] if tool_call_history else None
return set(self.children) if last_tool == self.tool_name else available_tools - set(self.children)
+ def render_prompt(self) -> str | None:
+ children_str = ", ".join(self.children)
+ return f"<tool_rule>\n{children_str} can only be used after {self.tool_name}\n</tool_rule>"
+
class ConditionalToolRule(BaseToolRule):
"""
@@ -115,10 +105,7 @@ class ConditionalToolRule(BaseToolRule):
default_child: Optional[str] = Field(None, description="The default child tool to be called. If None, any tool can be called.")
child_output_mapping: Dict[Any, str] = Field(..., description="The output case to check for mapping")
require_output_mapping: bool = Field(default=False, description="Whether to throw an error when output doesn't match any case")
- prompt_template: Optional[str] = Field(
- default="<tool_rule>\n{{ tool_name }} will determine which tool to use next based on its output\n</tool_rule>",
- description="Optional Jinja2 template for generating agent prompt about this tool rule.",
- )
+ prompt_template: Optional[str] = Field(default=None, description="Optional template string (ignored).")
def __hash__(self):
"""Hash including all configuration fields."""
@@ -165,6 +152,9 @@ class ConditionalToolRule(BaseToolRule):
return {self.default_child} if self.default_child else available_tools
+ def render_prompt(self) -> str | None:
+ return f"<tool_rule>\n{self.tool_name} will determine which tool to use next based on its output\n</tool_rule>"
+
@field_validator("child_output_mapping")
@classmethod
def validate_child_output_mapping(cls, v):
@@ -205,10 +195,10 @@ class TerminalToolRule(BaseToolRule):
"""
type: Literal[ToolRuleType.exit_loop] = ToolRuleType.exit_loop
- prompt_template: Optional[str] = Field(
- default="<tool_rule>\n{{ tool_name }} ends your response (yields control) when called\n</tool_rule>",
- description="Optional Jinja2 template for generating agent prompt about this tool rule.",
- )
+ prompt_template: Optional[str] = Field(default=None, description="Optional template string (ignored).")
+
+ def render_prompt(self) -> str | None:
+ return f"<tool_rule>\n{self.tool_name} ends your response (yields control) when called\n</tool_rule>"
class ContinueToolRule(BaseToolRule):
@@ -217,10 +207,10 @@ class ContinueToolRule(BaseToolRule):
"""
type: Literal[ToolRuleType.continue_loop] = ToolRuleType.continue_loop
- prompt_template: Optional[str] = Field(
- default="<tool_rule>\n{{ tool_name }} requires continuing your response when called\n</tool_rule>",
- description="Optional Jinja2 template for generating agent prompt about this tool rule.",
- )
+ prompt_template: Optional[str] = Field(default=None, description="Optional template string (ignored).")
+
+ def render_prompt(self) -> str | None:
+ return f"<tool_rule>\n{self.tool_name} requires continuing your response when called\n</tool_rule>"
class RequiredBeforeExitToolRule(BaseToolRule):
@@ -229,15 +219,15 @@ class RequiredBeforeExitToolRule(BaseToolRule):
"""
type: Literal[ToolRuleType.required_before_exit] = ToolRuleType.required_before_exit
- prompt_template: Optional[str] = Field(
- default="<tool_rule>{{ tool_name }} must be called before ending the conversation</tool_rule>",
- description="Optional Jinja2 template for generating agent prompt about this tool rule.",
- )
+ prompt_template: Optional[str] = Field(default=None, description="Optional template string (ignored).")
def get_valid_tools(self, tool_call_history: List[str], available_tools: Set[str], last_function_response: Optional[str]) -> Set[str]:
"""Returns all available tools - the logic for preventing exit is handled elsewhere."""
return available_tools
+ def render_prompt(self) -> str | None:
+ return f"<tool_rule>{self.tool_name} must be called before ending the conversation</tool_rule>"
+
class MaxCountPerStepToolRule(BaseToolRule):
"""
@@ -246,10 +236,7 @@ class MaxCountPerStepToolRule(BaseToolRule):
type: Literal[ToolRuleType.max_count_per_step] = ToolRuleType.max_count_per_step
max_count_limit: int = Field(..., description="The max limit for the total number of times this tool can be invoked in a single step.")
- prompt_template: Optional[str] = Field(
- default="<tool_rule>\n{{ tool_name }}: at most {{ max_count_limit }} use(s) per response\n</tool_rule>",
- description="Optional Jinja2 template for generating agent prompt about this tool rule.",
- )
+ prompt_template: Optional[str] = Field(default=None, description="Optional template string (ignored).")
def __hash__(self):
"""Hash including max_count_limit."""
@@ -271,6 +258,9 @@ class MaxCountPerStepToolRule(BaseToolRule):
return available_tools
+ def render_prompt(self) -> str | None:
+ return f"<tool_rule>\n{self.tool_name}: at most {self.max_count_limit} use(s) per response\n</tool_rule>"
+
class RequiresApprovalToolRule(BaseToolRule):
"""
diff --git a/letta/server/server.py b/letta/server/server.py
index 390b18747..fbee101d6 100644
--- a/letta/server/server.py
+++ b/letta/server/server.py
@@ -38,12 +38,12 @@ from letta.log import get_logger
from letta.orm.errors import NoResultFound
from letta.otel.tracing import log_event, trace_method
from letta.prompts.gpt_system import get_system_text
-from letta.schemas.agent import AgentState, AgentType, CreateAgent, UpdateAgent
+from letta.schemas.agent import AgentState, CreateAgent, UpdateAgent
from letta.schemas.block import Block, BlockUpdate, CreateBlock
from letta.schemas.embedding_config import EmbeddingConfig
# openai schemas
-from letta.schemas.enums import JobStatus, MessageStreamStatus, ProviderCategory, ProviderType, SandboxType, ToolSourceType
+from letta.schemas.enums import AgentType, JobStatus, MessageStreamStatus, ProviderCategory, ProviderType, SandboxType, ToolSourceType
from letta.schemas.environment_variables import SandboxEnvironmentVariableCreate
from letta.schemas.group import GroupCreate, ManagerType, SleeptimeManager, VoiceSleeptimeManager
from letta.schemas.job import Job, JobUpdate
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index e063477c7..7369be752 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -50,15 +50,13 @@ from letta.otel.tracing import trace_method
from letta.prompts.prompt_generator import PromptGenerator
from letta.schemas.agent import (
AgentState as PydanticAgentState,
- AgentType,
CreateAgent,
InternalTemplateAgentCreate,
UpdateAgent,
- get_prompt_template_for_agent_type,
)
from letta.schemas.block import DEFAULT_BLOCKS, Block as PydanticBlock, BlockUpdate
from letta.schemas.embedding_config import EmbeddingConfig
-from letta.schemas.enums import ProviderType, TagMatchMode, ToolType, VectorDBProvider
+from letta.schemas.enums import AgentType, ProviderType, TagMatchMode, ToolType, VectorDBProvider
from letta.schemas.file import FileMetadata as PydanticFileMetadata
from letta.schemas.group import Group as PydanticGroup, ManagerType
from letta.schemas.llm_config import LLMConfig
@@ -1794,7 +1792,7 @@ class AgentManager:
# note: we only update the system prompt if the core memory is changed
# this means that the archival/recall memory statistics may be someout out of date
- curr_memory_str = await agent_state.memory.compile_in_thread_async(
+ curr_memory_str = agent_state.memory.compile(
sources=agent_state.sources,
tool_usage_rules=tool_rules_solver.compile_tool_rule_prompts(),
max_files_open=agent_state.max_files_open,
@@ -1984,7 +1982,7 @@ class AgentManager:
agent_state = await self.get_agent_by_id_async(agent_id=agent_id, actor=actor, include_relationships=["memory", "sources"])
system_message = await self.message_manager.get_message_by_id_async(message_id=agent_state.message_ids[0], actor=actor)
temp_tool_rules_solver = ToolRulesSolver(agent_state.tool_rules)
- new_memory_str = await new_memory.compile_in_thread_async(
+ new_memory_str = new_memory.compile(
sources=agent_state.sources,
tool_usage_rules=temp_tool_rules_solver.compile_tool_rule_prompts(),
max_files_open=agent_state.max_files_open,
@@ -2008,7 +2006,7 @@ class AgentManager:
agent_state.memory = Memory(
blocks=blocks,
file_blocks=agent_state.memory.file_blocks,
- prompt_template=get_prompt_template_for_agent_type(agent_state.agent_type),
+ agent_type=agent_state.agent_type,
)
# NOTE: don't do this since re-buildin the memory is handled at the start of the step
diff --git a/letta/services/helpers/agent_manager_helper.py b/letta/services/helpers/agent_manager_helper.py
index f09981087..fffe6ccd8 100644
--- a/letta/services/helpers/agent_manager_helper.py
+++ b/letta/services/helpers/agent_manager_helper.py
@@ -32,9 +32,9 @@ from letta.orm.sources_agents import SourcesAgents
from letta.otel.tracing import trace_method
from letta.prompts import gpt_system
from letta.prompts.prompt_generator import PromptGenerator
-from letta.schemas.agent import AgentState, AgentType
+from letta.schemas.agent import AgentState
from letta.schemas.embedding_config import EmbeddingConfig
-from letta.schemas.enums import MessageRole
+from letta.schemas.enums import AgentType, MessageRole
from letta.schemas.letta_message_content import TextContent
from letta.schemas.memory import Memory
from letta.schemas.message import Message, MessageCreate
@@ -245,7 +245,7 @@ def compile_system_message(
timezone: str,
user_defined_variables: Optional[dict] = None,
append_icm_if_missing: bool = True,
- template_format: Literal["f-string", "mustache", "jinja2"] = "f-string",
+ template_format: Literal["f-string", "mustache"] = "f-string",
previous_message_count: int = 0,
archival_memory_size: int | None = 0,
tool_rules_solver: Optional[ToolRulesSolver] = None,
@@ -311,7 +311,7 @@ def compile_system_message(
raise ValueError(f"Failed to format system prompt - {str(e)}. System prompt value:\n{system_prompt}")
else:
- # TODO support for mustache and jinja2
+ # TODO support for mustache
raise NotImplementedError(template_format)
return formatted_prompt
diff --git a/letta/services/summarizer/summarizer.py b/letta/services/summarizer/summarizer.py
index 48a320ac7..58bea6b07 100644
--- a/letta/services/summarizer/summarizer.py
+++ b/letta/services/summarizer/summarizer.py
@@ -19,7 +19,6 @@ from letta.services.agent_manager import AgentManager
from letta.services.message_manager import MessageManager
from letta.services.summarizer.enums import SummarizationMode
from letta.system import package_summarize_message_no_counts
-from letta.templates.template_helper import render_template
from letta.utils import safe_create_task
logger = get_logger(__name__)
@@ -280,8 +279,7 @@ class Summarizer:
formatted_evicted_messages = [f"{i}. {msg}" for (i, msg) in enumerate(formatted_evicted_messages)]
formatted_in_context_messages = [f"{i + offset}. {msg}" for (i, msg) in enumerate(formatted_in_context_messages)]
- summary_request_text = render_template(
- "summary_request_text.j2",
+ summary_request_text = build_summary_request_text(
retain_count=retain_count,
evicted_messages=formatted_evicted_messages,
in_context_messages=formatted_in_context_messages,
@@ -304,6 +302,30 @@ def simple_formatter(messages: List[Message], include_system: bool = False) -> s
return "\n".join(json.dumps(msg) for msg in parsed_messages)
+def build_summary_request_text(retain_count: int, evicted_messages: List[str], in_context_messages: List[str]) -> str:
+ parts: List[str] = []
+ if retain_count == 0:
+ parts.append(
+ "You’re a memory-recall helper for an AI that is about to forget all prior messages. Scan the conversation history and write crisp notes that capture any important facts or insights about the conversation history."
+ )
+ else:
+ parts.append(
+ f"You’re a memory-recall helper for an AI that can only keep the last {retain_count} messages. Scan the conversation history, focusing on messages about to drop out of that window, and write crisp notes that capture any important facts or insights about the human so they aren’t lost."
+ )
+
+ if evicted_messages:
+ parts.append("\n(Older) Evicted Messages:")
+ for item in evicted_messages:
+ parts.append(f" {item}")
+
+ if retain_count > 0 and in_context_messages:
+ parts.append("\n(Newer) In-Context Messages:")
+ for item in in_context_messages:
+ parts.append(f" {item}")
+
+ return "\n".join(parts) + "\n"
+
+
def simple_message_wrapper(openai_msg: dict) -> Message:
"""Extremely simple way to map from role/content to Message object w/ throwaway dummy fields"""
diff --git a/letta/services/tool_executor/sandbox_tool_executor.py b/letta/services/tool_executor/sandbox_tool_executor.py
index 1d1050214..525aabc50 100644
--- a/letta/services/tool_executor/sandbox_tool_executor.py
+++ b/letta/services/tool_executor/sandbox_tool_executor.py
@@ -36,7 +36,7 @@ class SandboxToolExecutor(ToolExecutor):
) -> ToolExecutionResult:
# Store original memory state
if agent_state:
- orig_memory_str = await agent_state.memory.compile_in_thread_async()
+ orig_memory_str = agent_state.memory.compile()
else:
orig_memory_str = None
@@ -89,7 +89,7 @@ class SandboxToolExecutor(ToolExecutor):
# Verify memory integrity
if agent_state:
- new_memory_str = await agent_state.memory.compile_in_thread_async()
+ new_memory_str = agent_state.memory.compile()
assert orig_memory_str == new_memory_str, "Memory should not be modified in a sandbox tool"
# Update agent memory if needed
diff --git a/letta/services/tool_sandbox/base.py b/letta/services/tool_sandbox/base.py
index 62ea0a144..e504cdfee 100644
--- a/letta/services/tool_sandbox/base.py
+++ b/letta/services/tool_sandbox/base.py
@@ -13,7 +13,6 @@ from letta.services.helpers.tool_execution_helper import add_imports_and_pydanti
from letta.services.helpers.tool_parser_helper import convert_param_to_str_value, parse_function_arguments
from letta.services.sandbox_config_manager import SandboxConfigManager
from letta.services.tool_manager import ToolManager
-from letta.templates.template_helper import render_template
from letta.types import JsonDict, JsonValue
@@ -79,11 +78,8 @@ class AsyncToolSandboxBase(ABC):
async def generate_execution_script(self, agent_state: Optional[AgentState], wrap_print_with_markers: bool = False) -> str:
"""
Generate code to run inside of execution sandbox. Serialize the agent state and arguments, call the tool,
- then base64-encode/pickle the result. Runs a jinja2 template constructing the python file.
+ then base64-encode/pickle the result. Constructs the python file.
"""
- # Select the appropriate template based on whether the function is async
- TEMPLATE_NAME = "sandbox_code_file_async.py.j2" if self.is_async_function else "sandbox_code_file.py.j2"
-
future_import = False
schema_code = None
@@ -106,11 +102,10 @@ class AsyncToolSandboxBase(ABC):
agent_state_pickle = pickle.dumps(agent_state) if self.inject_agent_state else None
- return render_template(
- TEMPLATE_NAME,
+ code = self._render_sandbox_code(
future_import=future_import,
inject_agent_state=self.inject_agent_state,
- schema_imports=schema_code,
+ schema_imports=schema_code or "",
agent_state_pickle=agent_state_pickle,
tool_args=tool_args,
tool_source_code=self.tool.source_code,
@@ -120,6 +115,138 @@ class AsyncToolSandboxBase(ABC):
start_marker=self.LOCAL_SANDBOX_RESULT_START_MARKER,
use_top_level_await=self.use_top_level_await(),
)
+ return code
+
+ def _render_sandbox_code(
+ self,
+ *,
+ future_import: bool,
+ inject_agent_state: bool,
+ schema_imports: str,
+ agent_state_pickle: bytes | None,
+ tool_args: str,
+ tool_source_code: str,
+ local_sandbox_result_var_name: str,
+ invoke_function_call: str,
+ wrap_print_with_markers: bool,
+ start_marker: bytes,
+ use_top_level_await: bool,
+ ) -> str:
+ lines: list[str] = []
+ if future_import:
+ lines.append("from __future__ import annotations")
+ lines.extend(
+ [
+ "from typing import *",
+ "import pickle",
+ "import sys",
+ "import base64",
+ "import struct",
+ "import hashlib",
+ ]
+ )
+ if self.is_async_function:
+ lines.append("import asyncio")
+
+ if inject_agent_state:
+ lines.extend(["import letta", "from letta import *"]) # noqa: F401
+
+ if schema_imports:
+ lines.append(schema_imports.rstrip())
+
+ if agent_state_pickle is not None:
+ lines.append(f"agent_state = pickle.loads({repr(agent_state_pickle)})")
+ else:
+ lines.append("agent_state = None")
+
+ if tool_args:
+ lines.append(tool_args.rstrip())
+
+ if tool_source_code:
+ lines.append(tool_source_code.rstrip())
+
+ if not self.is_async_function:
+ # sync variant
+ lines.append(f"_function_result = {invoke_function_call}")
+ lines.extend(
+ [
+ "try:",
+ " from pydantic import BaseModel, ConfigDict",
+ " from typing import Any",
+ "",
+ " class _TempResultWrapper(BaseModel):",
+ " model_config = ConfigDict(arbitrary_types_allowed=True)",
+ " result: Any",
+ "",
+ " _wrapped = _TempResultWrapper(result=_function_result)",
+ " _serialized_result = _wrapped.model_dump()['result']",
+ "except ImportError:",
+ ' print("Pydantic not available in sandbox environment, falling back to string conversion")',
+ " _serialized_result = str(_function_result)",
+ "except Exception as e:",
+ ' print(f"Failed to serialize result with Pydantic wrapper: {e}")',
+ " _serialized_result = str(_function_result)",
+ "",
+ f"{local_sandbox_result_var_name} = {{",
+ ' "results": _serialized_result,',
+ ' "agent_state": agent_state',
+ "}",
+ f"{local_sandbox_result_var_name}_pkl = pickle.dumps({local_sandbox_result_var_name})",
+ ]
+ )
+ else:
+ # async variant
+ lines.extend(
+ [
+ "async def _async_wrapper():",
+ f" _function_result = await {invoke_function_call}",
+ " try:",
+ " from pydantic import BaseModel, ConfigDict",
+ " from typing import Any",
+ "",
+ " class _TempResultWrapper(BaseModel):",
+ " model_config = ConfigDict(arbitrary_types_allowed=True)",
+ " result: Any",
+ "",
+ " _wrapped = _TempResultWrapper(result=_function_result)",
+ " _serialized_result = _wrapped.model_dump()['result']",
+ " except ImportError:",
+ ' print("Pydantic not available in sandbox environment, falling back to string conversion")',
+ " _serialized_result = str(_function_result)",
+ " except Exception as e:",
+ ' print(f"Failed to serialize result with Pydantic wrapper: {e}")',
+ " _serialized_result = str(_function_result)",
+ "",
+ " return {",
+ ' "results": _serialized_result,',
+ ' "agent_state": agent_state',
+ " }",
+ ]
+ )
+ if use_top_level_await:
+ lines.append(f"{local_sandbox_result_var_name} = await _async_wrapper()")
+ else:
+ lines.append(f"{local_sandbox_result_var_name} = asyncio.run(_async_wrapper())")
+ lines.append(f"{local_sandbox_result_var_name}_pkl = pickle.dumps({local_sandbox_result_var_name})")
+
+ if wrap_print_with_markers:
+ lines.extend(
+ [
+ f"data_checksum = hashlib.md5({local_sandbox_result_var_name}_pkl).hexdigest().encode('ascii')",
+ f"{local_sandbox_result_var_name}_msg = (",
+ f" {repr(start_marker)} +",
+ f" struct.pack('>I', len({local_sandbox_result_var_name}_pkl)) +",
+ " data_checksum +",
+ f" {local_sandbox_result_var_name}_pkl",
+ ")",
+ f"sys.stdout.buffer.write({local_sandbox_result_var_name}_msg)",
+ "sys.stdout.buffer.flush()",
+ ]
+ )
+ else:
+ lines.append(f"base64.b64encode({local_sandbox_result_var_name}_pkl).decode('utf-8')")
+
+ return "\n".join(lines) + "\n"
def initialize_param(self, name: str, raw_value: JsonValue) -> str:
"""
diff --git a/letta/settings.py b/letta/settings.py
index e76afa4ac..c6dd93fc3 100644
--- a/letta/settings.py
+++ b/letta/settings.py
@@ -42,8 +42,8 @@ class ToolSettings(BaseSettings):
def sandbox_type(self) -> SandboxType:
if self.e2b_api_key:
return SandboxType.E2B
- elif self.modal_token_id and self.modal_token_secret:
- return SandboxType.MODAL
+ # elif self.modal_token_id and self.modal_token_secret:
+ # return SandboxType.MODAL
else:
return SandboxType.LOCAL
diff --git a/letta/templates/template_helper.py b/letta/templates/template_helper.py
deleted file mode 100644
index af4463fc0..000000000
--- a/letta/templates/template_helper.py
+++ /dev/null
@@ -1,53 +0,0 @@
-import asyncio
-import os
-
-from jinja2 import Environment, FileSystemLoader, StrictUndefined, Template
-
-from letta.otel.tracing import trace_method
-
-TEMPLATE_DIR = os.path.dirname(__file__)
-
-# Synchronous environment (for backward compatibility)
-jinja_env = Environment(
- loader=FileSystemLoader(TEMPLATE_DIR),
- undefined=StrictUndefined,
- trim_blocks=True,
- lstrip_blocks=True,
-)
-
-# Async-enabled environment
-jinja_async_env = Environment(
- loader=FileSystemLoader(TEMPLATE_DIR),
- undefined=StrictUndefined,
- trim_blocks=True,
- lstrip_blocks=True,
- enable_async=True, # Enable async support
-)
-
-
-@trace_method
-def render_template(template_name: str, **kwargs):
- """Synchronous template rendering function (kept for backward compatibility)"""
- template = jinja_env.get_template(template_name)
- return template.render(**kwargs)
-
-
-@trace_method
-async def render_template_async(template_name: str, **kwargs):
- """Asynchronous template rendering function that doesn't block the event loop"""
- template = jinja_async_env.get_template(template_name)
- return await template.render_async(**kwargs)
-
-
-@trace_method
-async def render_template_in_thread(template_name: str, **kwargs):
- """Asynchronously render a template from a string"""
- template = jinja_env.get_template(template_name)
- return await asyncio.to_thread(template.render, **kwargs)
-
-
-@trace_method
-async def render_string_async(template_string: str, **kwargs):
- """Asynchronously render a template from a string"""
- template = Template(template_string, enable_async=True)
- return await template.render_async(**kwargs)
diff --git a/pyproject.toml b/pyproject.toml
index 87548008c..6709c743c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -32,7 +32,6 @@ dependencies = [
"pydantic-settings>=2.2.1",
"httpx-sse>=0.4.0",
"nltk>=3.8.1",
- "jinja2>=3.1.5",
"composio-core>=0.7.7",
"alembic>=1.13.3",
"pyhumps>=3.8.0",
diff --git a/tests/integration_test_voice_agent.py b/tests/integration_test_voice_agent.py
index 4026a07d8..9e88f367b 100644
--- a/tests/integration_test_voice_agent.py
+++ b/tests/integration_test_voice_agent.py
@@ -11,10 +11,10 @@ from letta.agents.voice_sleeptime_agent import VoiceSleeptimeAgent
from letta.config import LettaConfig
from letta.constants import DEFAULT_MAX_MESSAGE_BUFFER_LENGTH, DEFAULT_MIN_MESSAGE_BUFFER_LENGTH
from letta.orm.errors import NoResultFound
-from letta.schemas.agent import AgentType, CreateAgent
+from letta.schemas.agent import CreateAgent
from letta.schemas.block import CreateBlock
from letta.schemas.embedding_config import EmbeddingConfig
-from letta.schemas.enums import MessageRole, MessageStreamStatus
+from letta.schemas.enums import AgentType, MessageRole, MessageStreamStatus
from letta.schemas.group import GroupUpdate, ManagerType, VoiceSleeptimeManagerUpdate
from letta.schemas.letta_message import AssistantMessage, ReasoningMessage, ToolCallMessage
from letta.schemas.letta_message_content import TextContent
diff --git a/tests/test_memory.py b/tests/test_memory.py
index c4675b94c..0da6e7f4b 100644
--- a/tests/test_memory.py
+++ b/tests/test_memory.py
@@ -1,58 +1,196 @@
+from types import SimpleNamespace
+
import pytest
-# Import the classes here, assuming the above definitions are in a module named memory_module
+from letta.constants import CORE_MEMORY_LINE_NUMBER_WARNING
+from letta.schemas.block import Block, FileBlock
+from letta.schemas.enums import AgentType
from letta.schemas.memory import ChatMemory, Memory
+def make_source(id_: str, name: str, description: str | None = None, instructions: str | None = None):
+ return SimpleNamespace(id=id_, name=name, description=description, instructions=instructions)
+
+
@pytest.fixture
-def sample_memory():
+def chat_memory():
return ChatMemory(persona="Chat Agent", human="User")
-def test_create_chat_memory():
- """Test creating an instance of ChatMemory"""
- chat_memory = ChatMemory(persona="Chat Agent", human="User")
+def test_chat_memory_init_and_utils(chat_memory: Memory):
assert chat_memory.get_block("persona").value == "Chat Agent"
assert chat_memory.get_block("human").value == "User"
+ assert set(chat_memory.list_block_labels()) == {"persona", "human"}
-def test_memory_limit_validation(sample_memory: Memory):
- """Test exceeding memory limit"""
+def test_memory_limit_validation(chat_memory: Memory):
with pytest.raises(ValueError):
ChatMemory(persona="x " * 50000, human="y " * 50000)
-
with pytest.raises(ValueError):
- sample_memory.get_block("persona").value = "x " * 50000
-
+ chat_memory.get_block("persona").value = "x " * 50000
-def test_memory_jinja2_set_template(sample_memory: Memory):
- """Test setting the template for the memory"""
- example_template = sample_memory.get_prompt_template()
+def test_get_block_not_found(chat_memory: Memory):
+ with pytest.raises(KeyError):
+ chat_memory.get_block("missing")
- # Try setting a valid template
- sample_memory.set_prompt_template(prompt_template=example_template)
- # Try setting an invalid template (bad jinja2)
- template_bad_jinja = (
- "{% for section, module in mammoth.items() %}"
- '<{{ section }} characters="{{ module.value|length }}/{{ module.limit }}">\n'
- "{{ module.value }}\n"
- "</{{ section }}>"
- "{% if not loop.last %}\n{% endif %}"
- "{% endfor %" # Missing closing curly brace
- )
+def test_update_block_value_type_error(chat_memory: Memory):
with pytest.raises(ValueError):
- sample_memory.set_prompt_template(prompt_template=template_bad_jinja)
-
- # Try setting an invalid template (not compatible with memory structure)
- template_bad_memory_structure = (
- "{% for section, module in mammoth.items() %}"
- '<{{ section }} characters="{{ module.value|length }}/{{ module.limit }}">\n'
- "{{ module.value }}\n"
- "</{{ section }}>"
- "{% if not loop.last %}\n{% endif %}"
- "{% endfor %}"
+ chat_memory.update_block_value("persona", 123) # type: ignore[arg-type]
+
+
+def test_update_block_value_success(chat_memory: Memory):
+ chat_memory.update_block_value("human", "Hi")
+ assert chat_memory.get_block("human").value == "Hi"
+
+
+def test_compile_standard_blocks_metadata_and_values():
+ m = Memory(
+ agent_type=AgentType.memgpt_agent,
+ blocks=[
+ Block(label="persona", value="I am P", limit=100, read_only=True),
+ Block(label="human", value="Hello", limit=100),
+ ],
)
- with pytest.raises(ValueError):
- sample_memory.set_prompt_template(prompt_template=template_bad_memory_structure)
+ out = m.compile()
+ assert "<memory_blocks>" in out
+ assert "<persona>" in out and "</persona>" in out
+ assert "<human>" in out and "</human>" in out
+ assert "- read_only=true" in out
+ assert "- chars_current=6" in out # len("Hello")
+
+
+def test_compile_line_numbered_blocks_sleeptime():
+ m = Memory(agent_type=AgentType.sleeptime_agent, blocks=[Block(label="notes", value="line1\nline2", limit=100)])
+ out = m.compile()
+ assert "<memory_blocks>" in out
+ assert CORE_MEMORY_LINE_NUMBER_WARNING in out
+ assert "Line 1: line1" in out and "Line 2: line2" in out
+
+
+def test_compile_line_numbered_blocks_memgpt_v2():
+ m = Memory(agent_type=AgentType.memgpt_v2_agent, blocks=[Block(label="notes", value="a\nb", limit=100)])
+ out = m.compile()
+ assert "Line 1: a" in out and "Line 2: b" in out
+
+
+def test_compile_empty_returns_empty_string():
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[])
+ assert m.compile() == ""
+
+
+def test_tool_usage_rules_inclusion_and_order():
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[Block(label="a", value="b", limit=100)])
+ rules = Block(label="tool_usage_rules", value="RVAL", description="RDESCR", limit=100)
+ out = m.compile(tool_usage_rules=rules)
+ assert "<tool_usage_rules>" in out
+ assert "RDESCR" in out and "RVAL" in out
+ assert out.index("</memory_blocks>") < out.index("<tool_usage_rules>")
+
+
+def test_directories_common_includes_files_and_metadata():
+ src = make_source("src1", "project", "Sdesc", "Sinst")
+ fb = FileBlock(label="fileA", value="data", limit=100, file_id="f1", source_id="src1", is_open=True, read_only=True)
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[Block(label="x", value="y", limit=10)], file_blocks=[fb])
+ out = m.compile(sources=[src], max_files_open=3)
+ assert "<directories>" in out and "</directories>" in out
+ assert "<file_limits>" in out
+ assert "- current_files_open=1" in out and "- max_files_open=3" in out
+ assert "<description>Sdesc</description>" in out
+ assert "<instructions>Sinst</instructions>" in out
+ assert 'name="fileA"' in out
+ assert "- read_only=true" in out
+ assert "<value>\ndata\n</value>" in out
+
+
+def test_directories_common_omits_empty_value():
+ src = make_source("src1", "project")
+ fb = FileBlock(label="fileA", value="", limit=100, file_id="f1", source_id="src1", is_open=True)
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[], file_blocks=[fb])
+ out = m.compile(sources=[src])
+ assert "<directories>" in out
+ assert "<value>" not in out # omitted for empty value in common path
+
+
+def test_directories_react_nested_label_and_status_counts():
+ src = make_source("src1", "project")
+ fb1 = FileBlock(label="fileA", value="content", limit=100, file_id="f1", source_id="src1", is_open=True)
+ fb2 = FileBlock(label="fileB", value="", limit=100, file_id="f2", source_id="src1", is_open=True)
+ m = Memory(agent_type=AgentType.react_agent, blocks=[Block(label="ignore", value="zz", limit=5)], file_blocks=[fb1, fb2])
+ out = m.compile(sources=[src], max_files_open=5)
+ assert "<memory_blocks>" not in out
+ assert "<directories>" in out
+ assert '<file status="open">' in out
+ assert '<file status="closed">' in out
+ assert "<fileA>" in out and "</fileA>" in out
+ assert "- current_files_open=1" in out
+
+
+def test_directories_file_limits_absent_when_none():
+ src = make_source("src1", "project")
+ fb = FileBlock(label="fileA", value="x", limit=100, file_id="f1", source_id="src1", is_open=True)
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[], file_blocks=[fb])
+ out = m.compile(sources=[src], max_files_open=None)
+ assert "<directories>" in out
+ assert "<file_limits>" not in out
+
+
+def test_agent_type_as_string_equivalent_behavior():
+ src = make_source("src1", "project")
+ m = Memory(agent_type="workflow_agent", blocks=[])
+ out = m.compile(sources=[src])
+ assert "<directories>" in out
+ assert "<memory_blocks>" not in out
+
+
+def test_file_blocks_duplicates_pruned_and_warning(caplog):
+ caplog.clear()
+ src = make_source("s", "n")
+ fb1 = FileBlock(label="dup", value="a", limit=100, file_id="f1", source_id="s", is_open=True)
+ fb2 = FileBlock(label="dup", value="b", limit=100, file_id="f2", source_id="s", is_open=True)
+ with caplog.at_level("WARNING", logger="letta.schemas.memory"):
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[], file_blocks=[fb1, fb2])
+ out = m.compile(sources=[src])
+ assert caplog.records
+ assert any("Duplicate block labels found" in r.message for r in caplog.records)
+ assert out.count('name="dup"') == 1
+
+
+async def test_compile_async_matches_sync():
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[Block(label="a", value="b", limit=10)])
+ assert await m.compile_async() == m.compile()
+
+
+def test_prompt_template_deprecated_noop():
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[])
+ m.set_prompt_template("foo")
+ assert m.get_prompt_template() == "foo"
+
+
+def test_sources_without_descriptions_or_instructions():
+ src = make_source("src1", "project", None, None)
+ fb = FileBlock(label="fileA", value="data", limit=100, file_id="f1", source_id="src1", is_open=True)
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[], file_blocks=[fb])
+ out = m.compile(sources=[src])
+ assert "<description>" not in out or "<description></description>" not in out
+ assert "<instructions>" not in out
+
+
+def test_read_only_metadata_in_file_and_block():
+ src = make_source("src1", "project")
+ fb = FileBlock(label="fileA", value="data", limit=100, file_id="f1", source_id="src1", is_open=True, read_only=True)
+ m = Memory(agent_type=AgentType.memgpt_agent, blocks=[Block(label="x", value="y", limit=10, read_only=True)], file_blocks=[fb])
+ out = m.compile(sources=[src])
+ assert out.count("- read_only=true") >= 2
+
+
+def test_current_files_open_counts_truthy_only():
+ src = make_source("src1", "project")
+ fb1 = FileBlock(label="fileA", value="data", limit=100, file_id="f1", source_id="src1", is_open=True)
+ fb2 = FileBlock(label="fileB", value="", limit=100, file_id="f2", source_id="src1", is_open=False)
+ fb3 = FileBlock(label="fileC", value="", limit=100, file_id="f3", source_id="src1", is_open=False)
+ m = Memory(agent_type=AgentType.react_agent, blocks=[], file_blocks=[fb1, fb2, fb3])
+ out = m.compile(sources=[src], max_files_open=10)
+ assert "- current_files_open=1" in out
diff --git a/uv.lock b/uv.lock
index 5d23bcaeb..833420148 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2433,7 +2433,6 @@ dependencies = [
{ name = "html2text" },
{ name = "httpx" },
{ name = "httpx-sse" },
- { name = "jinja2" },
{ name = "letta-client" },
{ name = "llama-index" },
{ name = "llama-index-embeddings-openai" },
@@ -2593,7 +2592,6 @@ requires-dist = [
{ name = "httpx-sse", specifier = ">=0.4.0" },
{ name = "ipdb", marker = "extra == 'dev'", specifier = ">=0.13.13" },
{ name = "ipykernel", marker = "extra == 'dev'", specifier = ">=6.29.5" },
- { name = "jinja2", specifier = ">=3.1.5" },
{ name = "langchain", marker = "extra == 'desktop'", specifier = ">=0.3.7" },
{ name = "langchain", marker = "extra == 'external-tools'", specifier = ">=0.3.7" },
{ name = "langchain-community", marker = "extra == 'desktop'", specifier = ">=0.3.7" },