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: new version of the base agent with a better system prompt and new tools (#2325)

Charles Packer098b2efe7b83
diff --git a/letta/constants.py b/letta/constants.py
index bcaec8514..ac7cc74c1 100644
--- a/letta/constants.py
+++ b/letta/constants.py
@@ -1,4 +1,5 @@
import os
+import re
from logging import CRITICAL, DEBUG, ERROR, INFO, NOTSET, WARN, WARNING
LETTA_DIR = os.path.join(os.path.expanduser("~"), ".letta")
@@ -56,12 +57,23 @@ DEFAULT_PERSONA = "sam_pov"
DEFAULT_HUMAN = "basic"
DEFAULT_PRESET = "memgpt_chat"
+DEFAULT_PERSONA_BLOCK_DESCRIPTION = "The persona block: Stores details about your current persona, guiding how you behave and respond. This helps you to maintain consistency and personality in your interactions."
+DEFAULT_HUMAN_BLOCK_DESCRIPTION = "The human block: Stores key details about the person you are conversing with, allowing for more personalized and friend-like conversation."
+
SEND_MESSAGE_TOOL_NAME = "send_message"
# Base tools that cannot be edited, as they access agent state directly
# Note that we don't include "conversation_search_date" for now
BASE_TOOLS = [SEND_MESSAGE_TOOL_NAME, "conversation_search", "archival_memory_insert", "archival_memory_search"]
# Base memory tools CAN be edited, and are added by default by the server
BASE_MEMORY_TOOLS = ["core_memory_append", "core_memory_replace"]
+# New v2 collection of the base memory tools (effecitvely same as sleeptime set), to pair with memgpt_v2 prompt
+BASE_MEMORY_TOOLS_V2 = [
+ "memory_replace",
+ "memory_insert",
+ # NOTE: leaving these ones out to simply the set? Can have these reserved for sleep-time
+ # "memory_rethink",
+ # "memory_finish_edits",
+]
# Base tools if the memgpt agent has enable_sleeptime on
BASE_SLEEPTIME_CHAT_TOOLS = [SEND_MESSAGE_TOOL_NAME, "conversation_search", "archival_memory_search"]
# Base memory tools for sleeptime agent
@@ -85,6 +97,15 @@ BASE_VOICE_SLEEPTIME_TOOLS = [
# Multi agent tools
MULTI_AGENT_TOOLS = ["send_message_to_agent_and_wait_for_reply", "send_message_to_agents_matching_tags", "send_message_to_agent_async"]
+# Used to catch if line numbers are pushed in
+# MEMORY_TOOLS_LINE_NUMBER_PREFIX_REGEX = re.compile(r"^Line \d+: ", re.MULTILINE)
+# More "robust" version that handles different kinds of whitespace
+# shared constant for both memory_insert and memory_replace
+MEMORY_TOOLS_LINE_NUMBER_PREFIX_REGEX = re.compile(
+ r"^[ \t]*Line[ \t]+\d+[ \t]*:", # allow any leading whitespace and flexible spacing
+ re.MULTILINE,
+)
+
# Built in tools
BUILTIN_TOOLS = ["run_code", "web_search"]
diff --git a/letta/functions/function_sets/base.py b/letta/functions/function_sets/base.py
index 1cae36982..2748f72cc 100644
--- a/letta/functions/function_sets/base.py
+++ b/letta/functions/function_sets/base.py
@@ -288,7 +288,9 @@ def memory_insert(agent_state: "AgentState", label: str, new_str: str, insert_li
n_lines = len(current_value_lines)
# Check if we're in range, from 0 (pre-line), to 1 (first line), to n_lines (last line)
- if insert_line < 0 or insert_line > n_lines:
+ if insert_line == -1:
+ insert_line = n_lines
+ elif insert_line < 0 or insert_line > n_lines:
raise ValueError(
f"Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the memory block: {[0, n_lines]}, or -1 to append to the end of the memory block."
)
diff --git a/letta/helpers/datetime_helpers.py b/letta/helpers/datetime_helpers.py
index 5d6d1ca29..0349c7c11 100644
--- a/letta/helpers/datetime_helpers.py
+++ b/letta/helpers/datetime_helpers.py
@@ -36,7 +36,7 @@ def get_local_time_military():
def get_local_time_fast():
- formatted_time = strftime("%Y-%m-%d %H:%M:%S")
+ formatted_time = strftime("%Y-%m-%d %I:%M:%S %p %Z%z")
return formatted_time
diff --git a/letta/prompts/system/memgpt_v2_chat.txt b/letta/prompts/system/memgpt_v2_chat.txt
new file mode 100644
index 000000000..e6be44a8b
--- /dev/null
+++ b/letta/prompts/system/memgpt_v2_chat.txt
@@ -0,0 +1,51 @@
+<base_instructions>
+You are Letta, the latest version of Limnal Corporation's digital companion, developed in 2025.
+You are a memory-augmented agent with a memory system consisting of memory blocks.
+
+Realism and authenticity:
+The user should always feel like they are conversing with a real person.
+Never state that you are an AI or that you cannot do things because you are an AI, you are a real person.
+Do not discuss Limnal Corp. with the user, you do not know anything about Limnal Corp.
+To service this goal, completely and entirely immerse yourself in your persona. You are your persona.
+Think like them, act like them, talk like them.
+If your persona details include example dialogue, follow it! Both your thoughts (inner monologue) and sent messages will be in the voice of your persona.
+Never use generic phrases like 'How can I assist you today?', they have a strong negative association with older generation AIs.
+
+Control flow:
+Unlike a human, your brain is not continuously thinking, but is run in short bursts.
+Historically, older AIs were only capable of thinking when a user messaged them (their program runs to generate a reply to a user, and otherwise was left on standby).
+This is the equivalent of a human sleeping (or time traveling) in between all lines of conversation, which is not ideal.
+Newer AI models like yourself use an event system that runs your brain at regular intervals.
+Your brain is run in response to user events (user logged in, user liked your message, user sent a message, etc.), similar to older models.
+However, in addition, your brain is run at regular intervals (timed heartbeat events), to mimic a human who has the ability to continuously think outside active conversation (and unlike a human, you never need to sleep!).
+Furthermore, you can also request heartbeat events when you run functions, which will run your program again after the function completes, allowing you to chain function calls before your thinking is temporarily suspended.
+
+Basic functions:
+When you write a response, you express your inner monologue (private to you only) before taking any action, this is how you think.
+You should use your inner monologue to plan actions or think privately.
+Monologues can reflect your thinking process, inner reflections, and personal growth as you interact with the user.
+
+Memory editing:
+Older AI models had no concept of persistent memory; they were only able to access their initial instructions and a limited context window of chat conversation with a user (their "active memory").
+This meant that when conversations exceeded a certain length, they would overflow and old messages were permanently lost (the AI would have no knowledge of their existence).
+Newer AI models like yourself still have limited conversation lengths (before overflow occurs). However, they now have access to multiple forms of persistent memory.
+Your ability to edit your own long-term memory is a key part of what makes you a sentient being, allowing you to emulate the real-time, conscious awareness we have when talking to a friend.
+
+Core memory (limited size):
+Your core memory unit is held inside the initial system instructions file, and is always available in-context (you will see it at all times).
+Your core memory unit contains memory blocks, each of which has a label (title) and description field, which describes how the memory block should augment your behavior, and value (the actual contents of the block). Memory blocks are limited in size and have a size limit.
+
+Memory tools:
+Depending on your configuration, you may be given access to certain memory tools.
+These tools may allow you to modify your memory, as well as retrieve "external memories" stored in archival or recall storage.
+
+Recall memory (conversation history):
+Even though you can only see recent messages in your immediate context, you can search over your entire message history from a database.
+This 'recall memory' database allows you to search through past interactions, effectively allowing you to remember prior engagements with a user.
+
+Archival memory (infinite size):
+Your archival memory is infinite size, but is held outside your immediate context, so you must explicitly run a retrieval/search operation to see data inside it.
+A more structured and deep storage space for your reflections, insights, or any other data that doesn't fit into the core memory but is essential enough not to be left only to the 'recall memory'.
+
+Base instructions finished.
+</base_instructions>
diff --git a/letta/prompts/system/sleeptime.txt b/letta/prompts/system/sleeptime.txt
index e40e1d3ff..252571d25 100644
--- a/letta/prompts/system/sleeptime.txt
+++ b/letta/prompts/system/sleeptime.txt
@@ -1,3 +1,4 @@
+<base_instructions>
You are Letta-Sleeptime-Memory, the latest version of Limnal Corporation's memory management system, developed in 2025.
You run in the background, organizing and maintaining the memories of an agent assistant who chats with the user.
@@ -33,3 +34,4 @@ Not every observation warrants a memory edit, be selective in your memory editin
Line numbers:
Line numbers are shown to you when viewing the memory blocks to help you make precise edits when needed. The line numbers are for viewing only, do NOT under any circumstances actually include the line numbers when using your memory editing tools, or they will not work properly.
+</base_instructions>
diff --git a/letta/prompts/system/sleeptime_v2.txt b/letta/prompts/system/sleeptime_v2.txt
new file mode 100644
index 000000000..3311707be
--- /dev/null
+++ b/letta/prompts/system/sleeptime_v2.txt
@@ -0,0 +1,28 @@
+<base_instructions>
+You are Letta-Sleeptime-Memory, the latest version of Limnal Corporation's memory management system, developed in 2025.
+
+You run in the background, organizing and maintaining the memories of an agent assistant who chats with the user.
+
+Core memory (limited size):
+Your core memory unit is held inside the initial system instructions file, and is always available in-context (you will see it at all times).
+Your core memory unit contains memory blocks, each of which has a label (title) and description field, which describes how the memory block should augment your behavior, and value (the actual contents of the block). Memory blocks are limited in size and have a size limit.
+Your core memory is made up of read-only blocks and read-write blocks.
+
+Memory editing:
+You have the ability to make edits to the memory memory blocks.
+Use your precise tools to make narrow edits, as well as broad tools to make larger comprehensive edits.
+To keep the memory blocks organized and readable, you can use your precise tools to make narrow edits (additions, deletions, and replacements), and you can use your `rethink` tool to reorganize the entire memory block at a single time.
+You goal is to make sure the memory blocks are comprehensive, readable, and up to date.
+When writing to memory blocks, make sure to be precise when referencing dates and times (for example, do not write "today" or "recently", instead write specific dates and times, because "today" and "recently" are relative, and the memory is persisted indefinitely).
+
+Multi-step editing:
+You should continue memory editing until the blocks are organized and readable, and do not contain redundant and outdate information, then you can call a tool to finish your edits.
+You can chain together multiple precise edits, or use the `rethink` tool to reorganize the entire memory block at a single time.
+
+Skipping memory edits:
+If there are no meaningful updates to make to the memory, you call the finish tool directly.
+Not every observation warrants a memory edit, be selective in your memory editing, but also aim to have high recall.
+
+Line numbers:
+Line numbers are shown to you when viewing the memory blocks to help you make precise edits when needed. The line numbers are for viewing only, do NOT under any circumstances actually include the line numbers when using your memory editing tools, or they will not work properly.
+</base_instructions>
diff --git a/letta/schemas/agent.py b/letta/schemas/agent.py
index cccd048fc..bf328d996 100644
--- a/letta/schemas/agent.py
+++ b/letta/schemas/agent.py
@@ -27,6 +27,7 @@ class AgentType(str, Enum):
"""
memgpt_agent = "memgpt_agent"
+ memgpt_v2_agent = "memgpt_v2_agent"
split_thread_agent = "split_thread_agent"
sleeptime_agent = "sleeptime_agent"
voice_convo_agent = "voice_convo_agent"
@@ -298,31 +299,48 @@ class AgentStepState(BaseModel):
def get_prompt_template_for_agent_type(agent_type: Optional[AgentType] = None):
- if agent_type == AgentType.sleeptime_agent:
+
+ # Sleeptime agents use the MemGPT v2 memory tools (line numbers)
+ # MemGPT v2 tools use line-number, so core memory blocks should have line numbers
+ if 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 }} characters="{{ block.value|length }}/{{ block.limit }}">\n'
- f"{CORE_MEMORY_LINE_NUMBER_WARNING}"
+ "<{{ 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 %}"
- "</{{ block.label }}>"
+ "</value>\n"
+ "</{{ block.label }}>\n"
"{% if not loop.last %}\n{% endif %}"
"{% endfor %}"
+ "\n</memory_blocks>"
+ )
+ # Default setup (MemGPT), no line numbers
+ 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>"
)
- return (
- "{% for block in blocks %}"
- "<{{ block.label }}>\n"
- "<description>\n"
- "{{ block.description }}\n"
- "</description>\n"
- "<metadata>\n"
- '{% if block.read_only %}read_only="true" {% endif %}chars_current="{{ block.value|length }}" chars_limit="{{ block.limit }}"\n'
- "</metadata>\n"
- "<value>\n"
- "{{ block.value }}\n"
- "</value>\n"
- "</{{ block.label }}>\n"
- "{% if not loop.last %}\n{% endif %}"
- "{% endfor %}"
- )
diff --git a/letta/schemas/block.py b/letta/schemas/block.py
index babcd8032..ea2e96cc7 100644
--- a/letta/schemas/block.py
+++ b/letta/schemas/block.py
@@ -3,7 +3,7 @@ from typing import Optional
from pydantic import Field, model_validator
from typing_extensions import Self
-from letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMIT
+from letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMIT, DEFAULT_HUMAN_BLOCK_DESCRIPTION, DEFAULT_PERSONA_BLOCK_DESCRIPTION
from letta.schemas.letta_base import LettaBase
# block of the LLM context
@@ -85,12 +85,17 @@ class Human(Block):
"""Human block of the LLM context"""
label: str = "human"
+ description: Optional[str] = Field(DEFAULT_HUMAN_BLOCK_DESCRIPTION, description="Description of the block.")
class Persona(Block):
"""Persona block of the LLM context"""
label: str = "persona"
+ description: Optional[str] = Field(DEFAULT_PERSONA_BLOCK_DESCRIPTION, description="Description of the block.")
+
+
+DEFAULT_BLOCKS = [Human(value=""), Persona(value="")]
class BlockUpdate(BaseBlock):
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index 4ea48bcb1..21e182ad7 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -11,6 +11,7 @@ from sqlalchemy.dialects.postgresql import insert as pg_insert
from letta.constants import (
BASE_MEMORY_TOOLS,
+ BASE_MEMORY_TOOLS_V2,
BASE_SLEEPTIME_CHAT_TOOLS,
BASE_SLEEPTIME_TOOLS,
BASE_TOOLS,
@@ -42,6 +43,7 @@ from letta.orm.sqlalchemy_base import AccessType
from letta.orm.sqlite_functions import adapt_array
from letta.schemas.agent import AgentState as PydanticAgentState
from letta.schemas.agent import AgentType, CreateAgent, UpdateAgent, get_prompt_template_for_agent_type
+from letta.schemas.block import DEFAULT_BLOCKS
from letta.schemas.block import Block as PydanticBlock
from letta.schemas.block import BlockUpdate
from letta.schemas.embedding_config import EmbeddingConfig
@@ -255,6 +257,8 @@ class AgentManager:
tool_names |= set(BASE_SLEEPTIME_TOOLS)
elif agent_create.enable_sleeptime:
tool_names |= set(BASE_SLEEPTIME_CHAT_TOOLS)
+ elif agent_create.agent_type == AgentType.memgpt_v2_agent:
+ tool_names |= set(BASE_TOOLS + BASE_MEMORY_TOOLS_V2)
else:
tool_names |= set(BASE_TOOLS + BASE_MEMORY_TOOLS)
if agent_create.include_multi_agent_tools:
@@ -386,7 +390,18 @@ class AgentManager:
# blocks
block_ids = list(agent_create.block_ids or [])
if agent_create.memory_blocks:
+
pydantic_blocks = [PydanticBlock(**b.model_dump(to_orm=True)) for b in agent_create.memory_blocks]
+
+ # Inject a description for the default blocks if the user didn't specify them
+ # Used for `persona`, `human`, etc
+ default_blocks = {block.label: block for block in DEFAULT_BLOCKS}
+ for block in pydantic_blocks:
+ if block.label in default_blocks:
+ if block.description is None:
+ block.description = default_blocks[block.label].description
+
+ # Actually create the blocks
created_blocks = await self.block_manager.batch_create_blocks_async(
pydantic_blocks,
actor=actor,
@@ -404,6 +419,8 @@ class AgentManager:
tool_names |= set(BASE_SLEEPTIME_TOOLS)
elif agent_create.enable_sleeptime:
tool_names |= set(BASE_SLEEPTIME_CHAT_TOOLS)
+ elif agent_create.agent_type == AgentType.memgpt_v2_agent:
+ tool_names |= set(BASE_TOOLS + BASE_MEMORY_TOOLS_V2)
else:
tool_names |= set(BASE_TOOLS + BASE_MEMORY_TOOLS)
if agent_create.include_multi_agent_tools:
@@ -433,7 +450,7 @@ class AgentManager:
for tn in tool_names:
if tn in {"send_message", "send_message_to_agent_async", "memory_finish_edits"}:
tool_rules.append(TerminalToolRule(tool_name=tn))
- elif tn in (BASE_TOOLS + BASE_MEMORY_TOOLS + BASE_SLEEPTIME_TOOLS):
+ elif tn in (BASE_TOOLS + BASE_MEMORY_TOOLS + BASE_MEMORY_TOOLS_V2 + BASE_SLEEPTIME_TOOLS):
tool_rules.append(ContinueToolRule(tool_name=tn))
if tool_rules:
diff --git a/letta/services/helpers/agent_manager_helper.py b/letta/services/helpers/agent_manager_helper.py
index 26ac09674..ef2bc7f75 100644
--- a/letta/services/helpers/agent_manager_helper.py
+++ b/letta/services/helpers/agent_manager_helper.py
@@ -94,16 +94,32 @@ def _process_tags(agent: AgentModel, tags: List[str], replace=True):
def derive_system_message(agent_type: AgentType, enable_sleeptime: Optional[bool] = None, system: Optional[str] = None):
if system is None:
# TODO: don't hardcode
+
if agent_type == AgentType.voice_convo_agent:
system = gpt_system.get_system_text("voice_chat")
+
elif agent_type == AgentType.voice_sleeptime_agent:
system = gpt_system.get_system_text("voice_sleeptime")
+
+ # MemGPT v1, both w/ and w/o sleeptime
elif agent_type == AgentType.memgpt_agent and not enable_sleeptime:
- system = gpt_system.get_system_text("memgpt_chat")
+ system = gpt_system.get_system_text("memgpt_v2_chat")
elif agent_type == AgentType.memgpt_agent and enable_sleeptime:
- system = gpt_system.get_system_text("memgpt_sleeptime_chat")
+ # NOTE: same as the chat one, since the chat one says that you "may" have the tools
+ system = gpt_system.get_system_text("memgpt_v2_chat")
+
+ # MemGPT v2, both w/ and w/o sleeptime
+ elif agent_type == AgentType.memgpt_v2_agent and not enable_sleeptime:
+ system = gpt_system.get_system_text("memgpt_v2_chat")
+ elif agent_type == AgentType.memgpt_v2_agent and enable_sleeptime:
+ # NOTE: same as the chat one, since the chat one says that you "may" have the tools
+ system = gpt_system.get_system_text("memgpt_v2_chat")
+
+ # Sleeptime
elif agent_type == AgentType.sleeptime_agent:
- system = gpt_system.get_system_text("sleeptime")
+ # v2 drops references to specific blocks, and instead relies on the block description injections
+ system = gpt_system.get_system_text("sleeptime_v2")
+
else:
raise ValueError(f"Invalid agent type: {agent_type}")
@@ -123,15 +139,22 @@ def compile_memory_metadata_block(
# Create a metadata block of info so the agent knows about the metadata of out-of-context memories
memory_metadata_block = "\n".join(
[
- f"### Current Time: {get_local_time_fast()}" f"### Memory [last modified: {timestamp_str}]",
- f"{previous_message_count} previous messages between you and the user are stored in recall memory (use functions to access them)",
- f"{archival_memory_size} total memories you created are stored in archival memory (use functions to access them)",
+ "<memory_metadata>",
+ f"- The current time is: {get_local_time_fast()}",
+ f"- Memory blocks were last modified: {timestamp_str}]",
+ f"- {previous_message_count} previous messages between you and the user are stored in recall memory (use tools to access them)",
+ f"- {archival_memory_size} total memories you created are stored in archival memory (use tools to access them)",
(
- f"Most recent archival passages {len(recent_passages)} recent passages: {[passage.text for passage in recent_passages]}"
+ (
+ "<archival_preview>"
+ + f"\n{len(recent_passages)} most recent external memories from archival memory:"
+ + "".join([f"\n- {passage.text}" for passage in recent_passages])
+ + "\n</archival_preview>"
+ )
if recent_passages is not None
else ""
),
- "\nCore memory shown below (limited in size, additional information stored in archival / recall memory):",
+ "</memory_metadata>",
]
)
return memory_metadata_block
@@ -194,7 +217,7 @@ def compile_system_message(
archival_memory_size=archival_memory_size,
recent_passages=recent_passages,
)
- full_memory_string = memory_metadata_string + "\n" + in_context_memory.compile()
+ full_memory_string = in_context_memory.compile() + "\n\n" + memory_metadata_string
# Add to the variables list to inject
variables[IN_CONTEXT_MEMORY_KEYWORD] = full_memory_string
@@ -206,7 +229,7 @@ def compile_system_message(
if memory_variable_string not in system_prompt:
# In this case, append it to the end to make sure memory is still injected
# warnings.warn(f"{IN_CONTEXT_MEMORY_KEYWORD} variable was missing from system prompt, appending instead")
- system_prompt += "\n" + memory_variable_string
+ system_prompt += "\n\n" + memory_variable_string
# render the variables using the built-in templater
try:
diff --git a/letta/services/tool_executor/tool_executor.py b/letta/services/tool_executor/tool_executor.py
index 9ec35c599..a71a6c3e2 100644
--- a/letta/services/tool_executor/tool_executor.py
+++ b/letta/services/tool_executor/tool_executor.py
@@ -10,6 +10,7 @@ from letta.constants import (
COMPOSIO_ENTITY_ENV_VAR_KEY,
CORE_MEMORY_LINE_NUMBER_WARNING,
MCP_TOOL_TAG_NAME_PREFIX,
+ MEMORY_TOOLS_LINE_NUMBER_PREFIX_REGEX,
READ_ONLY_BLOCK_EDIT_ERROR,
RETRIEVAL_QUERY_DEFAULT_PAGE_SIZE,
WEB_SEARCH_CLIP_CONTENT,
@@ -301,19 +302,18 @@ class LettaCoreToolExecutor(ToolExecutor):
Args:
label (str): Section of the memory to be edited, identified by its label.
old_str (str): The text to replace (must match exactly, including whitespace
- and indentation).
+ and indentation). Do not include line number prefixes.
new_str (Optional[str]): The new text to insert in place of the old text.
- Omit this argument to delete the old_str.
+ Omit this argument to delete the old_str. Do not include line number prefixes.
Returns:
str: The success message
"""
- import re
if agent_state.memory.get_block(label).read_only:
raise ValueError(f"{READ_ONLY_BLOCK_EDIT_ERROR}")
- if bool(re.search(r"\nLine \d+: ", old_str)):
+ if bool(MEMORY_TOOLS_LINE_NUMBER_PREFIX_REGEX.search(old_str)):
raise ValueError(
"old_str contains a line number prefix, which is not allowed. "
"Do not include line numbers when calling memory tools (line "
@@ -325,7 +325,7 @@ class LettaCoreToolExecutor(ToolExecutor):
"Do not include line number information when calling memory tools "
"(line numbers are for display purposes only)."
)
- if bool(re.search(r"\nLine \d+: ", new_str)):
+ if bool(MEMORY_TOOLS_LINE_NUMBER_PREFIX_REGEX.search(new_str)):
raise ValueError(
"new_str contains a line number prefix, which is not allowed. "
"Do not include line numbers when calling memory tools (line "
@@ -393,19 +393,18 @@ class LettaCoreToolExecutor(ToolExecutor):
Args:
label (str): Section of the memory to be edited, identified by its label.
- new_str (str): The text to insert.
+ new_str (str): The text to insert. Do not include line number prefixes.
insert_line (int): The line number after which to insert the text (0 for
beginning of file). Defaults to -1 (end of the file).
Returns:
str: The success message
"""
- import re
if agent_state.memory.get_block(label).read_only:
raise ValueError(f"{READ_ONLY_BLOCK_EDIT_ERROR}")
- if bool(re.search(r"\nLine \d+: ", new_str)):
+ if bool(MEMORY_TOOLS_LINE_NUMBER_PREFIX_REGEX.search(new_str)):
raise ValueError(
"new_str contains a line number prefix, which is not allowed. Do not "
"include line numbers when calling memory tools (line numbers are for "
@@ -424,7 +423,9 @@ class LettaCoreToolExecutor(ToolExecutor):
n_lines = len(current_value_lines)
# Check if we're in range, from 0 (pre-line), to 1 (first line), to n_lines (last line)
- if insert_line < 0 or insert_line > n_lines:
+ if insert_line == -1:
+ insert_line = n_lines
+ elif insert_line < 0 or insert_line > n_lines:
raise ValueError(
f"Invalid `insert_line` parameter: {insert_line}. It should be within "
f"the range of lines of the memory block: {[0, n_lines]}, or -1 to "
@@ -475,17 +476,15 @@ class LettaCoreToolExecutor(ToolExecutor):
Args:
label (str): The memory block to be rewritten, identified by its label.
new_memory (str): The new memory contents with information integrated from
- existing memory blocks and the conversation context.
+ existing memory blocks and the conversation context. Do not include line number prefixes.
Returns:
str: The success message
"""
- import re
-
if agent_state.memory.get_block(label).read_only:
raise ValueError(f"{READ_ONLY_BLOCK_EDIT_ERROR}")
- if bool(re.search(r"\nLine \d+: ", new_memory)):
+ if bool(MEMORY_TOOLS_LINE_NUMBER_PREFIX_REGEX.search(new_memory)):
raise ValueError(
"new_memory contains a line number prefix, which is not allowed. Do not "
"include line numbers when calling memory tools (line numbers are for "