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.

fix: Bug fixes (#2377)

Matthew Zhou7aa824ea38d8
diff --git a/alembic/versions/f895232c144a_backfill_composio_tools.py b/alembic/versions/f895232c144a_backfill_composio_tools.py
new file mode 100644
index 000000000..a1c08c71e
--- /dev/null
+++ b/alembic/versions/f895232c144a_backfill_composio_tools.py
@@ -0,0 +1,51 @@
+"""Backfill composio tools
+
+Revision ID: f895232c144a
+Revises: 25fc99e97839
+Create Date: 2025-01-16 14:21:33.764332
+
+"""
+
+from typing import Sequence, Union
+
+from alembic import op
+from letta.orm.enums import ToolType
+
+# revision identifiers, used by Alembic.
+revision: str = "f895232c144a"
+down_revision: Union[str, None] = "416b9d2db10b"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ # ### commands auto generated by Alembic - please adjust! ###
+ # Define the value for EXTERNAL_COMPOSIO
+ external_composio_value = ToolType.EXTERNAL_COMPOSIO.value
+
+ # Update tool_type to EXTERNAL_COMPOSIO if the tags field includes "composio"
+ # This is super brittle and awful but no other way to do this
+ op.execute(
+ f"""
+ UPDATE tools
+ SET tool_type = '{external_composio_value}'
+ WHERE tags::jsonb @> '["composio"]';
+ """
+ )
+ # ### end Alembic commands ###
+
+
+def downgrade() -> None:
+ # ### commands auto generated by Alembic - please adjust! ###
+ custom_value = ToolType.CUSTOM.value
+
+ # Update tool_type to CUSTOM if the tags field includes "composio"
+ # This is super brittle and awful but no other way to do this
+ op.execute(
+ f"""
+ UPDATE tools
+ SET tool_type = '{custom_value}'
+ WHERE tags::jsonb @> '["composio"]';
+ """
+ )
+ # ### end Alembic commands ###
diff --git a/letta/agent.py b/letta/agent.py
index 978fbda3f..3f416e394 100644
--- a/letta/agent.py
+++ b/letta/agent.py
@@ -13,9 +13,6 @@ from letta.constants import (
LETTA_CORE_TOOL_MODULE_NAME,
LETTA_MULTI_AGENT_TOOL_MODULE_NAME,
LLM_MAX_TOKENS,
- MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST,
- MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC,
- MESSAGE_SUMMARY_WARNING_FRAC,
REQ_HEARTBEAT_MESSAGE,
)
from letta.errors import ContextWindowExceededError
@@ -23,7 +20,7 @@ from letta.functions.ast_parsers import coerce_dict_args_by_annotations, get_fun
from letta.functions.functions import get_function_from_module
from letta.helpers import ToolRulesSolver
from letta.interface import AgentInterface
-from letta.llm_api.helpers import is_context_overflow_error
+from letta.llm_api.helpers import calculate_summarizer_cutoff, get_token_counts_for_messages, is_context_overflow_error
from letta.llm_api.llm_api_tools import create
from letta.local_llm.utils import num_tokens_from_functions, num_tokens_from_messages
from letta.log import get_logger
@@ -52,6 +49,7 @@ from letta.services.passage_manager import PassageManager
from letta.services.provider_manager import ProviderManager
from letta.services.step_manager import StepManager
from letta.services.tool_execution_sandbox import ToolExecutionSandbox
+from letta.settings import summarizer_settings
from letta.streaming_interface import StreamingRefreshCLIInterface
from letta.system import get_heartbeat, get_token_limit_warning, package_function_response, package_summarize_message, package_user_message
from letta.utils import (
@@ -66,6 +64,8 @@ from letta.utils import (
validate_function_response,
)
+logger = get_logger(__name__)
+
class BaseAgent(ABC):
"""
@@ -635,7 +635,7 @@ class Agent(BaseAgent):
self.logger.info(f"Hit max chaining steps, stopping after {counter} steps")
break
# Chain handlers
- elif token_warning:
+ elif token_warning and summarizer_settings.send_memory_warning_message:
assert self.agent_state.created_by_id is not None
next_input_message = Message.dict_to_message(
agent_id=self.agent_state.id,
@@ -686,6 +686,7 @@ class Agent(BaseAgent):
stream: bool = False, # TODO move to config?
step_count: Optional[int] = None,
metadata: Optional[dict] = None,
+ summarize_attempt_count: int = 0,
) -> AgentStepResponse:
"""Runs a single step in the agent loop (generates at most one LLM call)"""
@@ -753,9 +754,9 @@ class Agent(BaseAgent):
LLM_MAX_TOKENS[self.model] if (self.model is not None and self.model in LLM_MAX_TOKENS) else LLM_MAX_TOKENS["DEFAULT"]
)
- if current_total_tokens > MESSAGE_SUMMARY_WARNING_FRAC * int(self.agent_state.llm_config.context_window):
- self.logger.warning(
- f"{CLI_WARNING_PREFIX}last response total_tokens ({current_total_tokens}) > {MESSAGE_SUMMARY_WARNING_FRAC * int(self.agent_state.llm_config.context_window)}"
+ if current_total_tokens > summarizer_settings.memory_warning_threshold * int(self.agent_state.llm_config.context_window):
+ printd(
+ f"{CLI_WARNING_PREFIX}last response total_tokens ({current_total_tokens}) > {summarizer_settings.memory_warning_threshold * int(self.agent_state.llm_config.context_window)}"
)
# Only deliver the alert if we haven't already (this period)
@@ -764,8 +765,8 @@ class Agent(BaseAgent):
self.agent_alerted_about_memory_pressure = True # it's up to the outer loop to handle this
else:
- self.logger.warning(
- f"last response total_tokens ({current_total_tokens}) < {MESSAGE_SUMMARY_WARNING_FRAC * int(self.agent_state.llm_config.context_window)}"
+ printd(
+ f"last response total_tokens ({current_total_tokens}) < {summarizer_settings.memory_warning_threshold * int(self.agent_state.llm_config.context_window)}"
)
# Log step - this must happen before messages are persisted
@@ -807,28 +808,46 @@ class Agent(BaseAgent):
)
except Exception as e:
- self.logger.error(f"step() failed\nmessages = {messages}\nerror = {e}")
+ logger.error(f"step() failed\nmessages = {messages}\nerror = {e}")
# If we got a context alert, try trimming the messages length, then try again
if is_context_overflow_error(e):
- self.logger.warning(
- f"context window exceeded with limit {self.agent_state.llm_config.context_window}, running summarizer to trim messages"
- )
- # A separate API call to run a summarizer
- self.summarize_messages_inplace()
+ in_context_messages = self.agent_manager.get_in_context_messages(agent_id=self.agent_state.id, actor=self.user)
- # Try step again
- return self.inner_step(
- messages=messages,
- first_message=first_message,
- first_message_retry_limit=first_message_retry_limit,
- skip_verify=skip_verify,
- stream=stream,
- metadata=metadata,
- )
+ if summarize_attempt_count <= summarizer_settings.max_summarizer_retries:
+ logger.warning(
+ f"context window exceeded with limit {self.agent_state.llm_config.context_window}, attempting to summarize ({summarize_attempt_count}/{summarizer_settings.max_summarizer_retries}"
+ )
+ # A separate API call to run a summarizer
+ self.summarize_messages_inplace()
+
+ # Try step again
+ return self.inner_step(
+ messages=messages,
+ first_message=first_message,
+ first_message_retry_limit=first_message_retry_limit,
+ skip_verify=skip_verify,
+ stream=stream,
+ metadata=metadata,
+ summarize_attempt_count=summarize_attempt_count + 1,
+ )
+ else:
+ err_msg = f"Ran summarizer {summarize_attempt_count - 1} times for agent id={self.agent_state.id}, but messages are still overflowing the context window."
+ token_counts = (get_token_counts_for_messages(in_context_messages),)
+ logger.error(err_msg)
+ logger.error(f"num_in_context_messages: {len(self.agent_state.message_ids)}")
+ logger.error(f"token_counts: {token_counts}")
+ raise ContextWindowExceededError(
+ err_msg,
+ details={
+ "num_in_context_messages": len(self.agent_state.message_ids),
+ "in_context_messages_text": [m.text for m in in_context_messages],
+ "token_counts": token_counts,
+ },
+ )
else:
- self.logger.error(f"step() failed with an unrecognized exception: '{str(e)}'")
+ logger.error(f"step() failed with an unrecognized exception: '{str(e)}'")
raise e
def step_user_message(self, user_message_str: str, **kwargs) -> AgentStepResponse:
@@ -865,109 +884,54 @@ class Agent(BaseAgent):
return self.inner_step(messages=[user_message], **kwargs)
- def summarize_messages_inplace(self, cutoff=None, preserve_last_N_messages=True, disallow_tool_as_first=True):
+ def summarize_messages_inplace(self):
in_context_messages = self.agent_manager.get_in_context_messages(agent_id=self.agent_state.id, actor=self.user)
in_context_messages_openai = [m.to_openai_dict() for m in in_context_messages]
+ in_context_messages_openai_no_system = in_context_messages_openai[1:]
+ token_counts = get_token_counts_for_messages(in_context_messages)
+ logger.info(f"System message token count={token_counts[0]}")
+ logger.info(f"token_counts_no_system={token_counts[1:]}")
if in_context_messages_openai[0]["role"] != "system":
raise RuntimeError(f"in_context_messages_openai[0] should be system (instead got {in_context_messages_openai[0]})")
- # Start at index 1 (past the system message),
- # and collect messages for summarization until we reach the desired truncation token fraction (eg 50%)
- # Do not allow truncation of the last N messages, since these are needed for in-context examples of function calling
- token_counts = [count_tokens(str(msg)) for msg in in_context_messages_openai]
- message_buffer_token_count = sum(token_counts[1:]) # no system message
- desired_token_count_to_summarize = int(message_buffer_token_count * MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC)
- candidate_messages_to_summarize = in_context_messages_openai[1:]
- token_counts = token_counts[1:]
-
- if preserve_last_N_messages:
- candidate_messages_to_summarize = candidate_messages_to_summarize[:-MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST]
- token_counts = token_counts[:-MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST]
-
- printd(f"MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC={MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC}")
- printd(f"MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST={MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST}")
- printd(f"token_counts={token_counts}")
- printd(f"message_buffer_token_count={message_buffer_token_count}")
- printd(f"desired_token_count_to_summarize={desired_token_count_to_summarize}")
- printd(f"len(candidate_messages_to_summarize)={len(candidate_messages_to_summarize)}")
-
# If at this point there's nothing to summarize, throw an error
- if len(candidate_messages_to_summarize) == 0:
+ if len(in_context_messages_openai_no_system) == 0:
raise ContextWindowExceededError(
"Not enough messages to compress for summarization",
details={
- "num_candidate_messages": len(candidate_messages_to_summarize),
+ "num_candidate_messages": len(in_context_messages_openai_no_system),
"num_total_messages": len(in_context_messages_openai),
- "preserve_N": MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST,
},
)
- # Walk down the message buffer (front-to-back) until we hit the target token count
- tokens_so_far = 0
- cutoff = 0
- for i, msg in enumerate(candidate_messages_to_summarize):
- cutoff = i
- tokens_so_far += token_counts[i]
- if tokens_so_far > desired_token_count_to_summarize:
- break
- # Account for system message
- cutoff += 1
-
- # Try to make an assistant message come after the cutoff
- try:
- printd(f"Selected cutoff {cutoff} was a 'user', shifting one...")
- if in_context_messages_openai[cutoff]["role"] == "user":
- new_cutoff = cutoff + 1
- if in_context_messages_openai[new_cutoff]["role"] == "user":
- printd(f"Shifted cutoff {new_cutoff} is still a 'user', ignoring...")
- cutoff = new_cutoff
- except IndexError:
- pass
-
- # Make sure the cutoff isn't on a 'tool' or 'function'
- if disallow_tool_as_first:
- while in_context_messages_openai[cutoff]["role"] in ["tool", "function"] and cutoff < len(in_context_messages_openai):
- printd(f"Selected cutoff {cutoff} was a 'tool', shifting one...")
- cutoff += 1
-
+ cutoff = calculate_summarizer_cutoff(in_context_messages=in_context_messages, token_counts=token_counts, logger=logger)
message_sequence_to_summarize = in_context_messages[1:cutoff] # do NOT get rid of the system message
- if len(message_sequence_to_summarize) <= 1:
- # This prevents a potential infinite loop of summarizing the same message over and over
- raise ContextWindowExceededError(
- "Not enough messages to compress for summarization after determining cutoff",
- details={
- "num_candidate_messages": len(message_sequence_to_summarize),
- "num_total_messages": len(in_context_messages_openai),
- "preserve_N": MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST,
- },
- )
- else:
- printd(f"Attempting to summarize {len(message_sequence_to_summarize)} messages [1:{cutoff}] of {len(in_context_messages)}")
+ logger.info(f"Attempting to summarize {len(message_sequence_to_summarize)} messages of {len(in_context_messages)}")
# We can't do summarize logic properly if context_window is undefined
if self.agent_state.llm_config.context_window is None:
# Fallback if for some reason context_window is missing, just set to the default
- print(f"{CLI_WARNING_PREFIX}could not find context_window in config, setting to default {LLM_MAX_TOKENS['DEFAULT']}")
- print(f"{self.agent_state}")
+ logger.warning(f"{CLI_WARNING_PREFIX}could not find context_window in config, setting to default {LLM_MAX_TOKENS['DEFAULT']}")
self.agent_state.llm_config.context_window = (
LLM_MAX_TOKENS[self.model] if (self.model is not None and self.model in LLM_MAX_TOKENS) else LLM_MAX_TOKENS["DEFAULT"]
)
summary = summarize_messages(agent_state=self.agent_state, message_sequence_to_summarize=message_sequence_to_summarize)
- printd(f"Got summary: {summary}")
+ logger.info(f"Got summary: {summary}")
# Metadata that's useful for the agent to see
all_time_message_count = self.message_manager.size(agent_id=self.agent_state.id, actor=self.user)
- remaining_message_count = len(in_context_messages_openai[cutoff:])
+ remaining_message_count = 1 + len(in_context_messages) - cutoff # System + remaining
hidden_message_count = all_time_message_count - remaining_message_count
summary_message_count = len(message_sequence_to_summarize)
summary_message = package_summarize_message(summary, summary_message_count, hidden_message_count, all_time_message_count)
- printd(f"Packaged into message: {summary_message}")
+ logger.info(f"Packaged into message: {summary_message}")
prior_len = len(in_context_messages_openai)
- self.agent_state = self.agent_manager.trim_older_in_context_messages(cutoff, agent_id=self.agent_state.id, actor=self.user)
+ self.agent_state = self.agent_manager.trim_all_in_context_messages_except_system(agent_id=self.agent_state.id, actor=self.user)
packed_summary_message = {"role": "user", "content": summary_message}
+ # Prepend the summary
self.agent_state = self.agent_manager.prepend_to_in_context_messages(
messages=[
Message.dict_to_message(
@@ -983,8 +947,12 @@ class Agent(BaseAgent):
# reset alert
self.agent_alerted_about_memory_pressure = False
+ curr_in_context_messages = self.agent_manager.get_in_context_messages(agent_id=self.agent_state.id, actor=self.user)
- printd(f"Ran summarizer, messages length {prior_len} -> {len(in_context_messages_openai)}")
+ logger.info(f"Ran summarizer, messages length {prior_len} -> {len(curr_in_context_messages)}")
+ logger.info(
+ f"Summarizer brought down total token count from {sum(token_counts)} -> {sum(get_token_counts_for_messages(curr_in_context_messages))}"
+ )
def add_function(self, function_name: str) -> str:
# TODO: refactor
diff --git a/letta/client/client.py b/letta/client/client.py
index d2425b8c4..35b0c6f64 100644
--- a/letta/client/client.py
+++ b/letta/client/client.py
@@ -92,19 +92,19 @@ class AbstractClient(object):
):
raise NotImplementedError
- def get_tools_from_agent(self, agent_id: str):
+ def get_tools_from_agent(self, agent_id: str) -> List[Tool]:
raise NotImplementedError
- def add_tool_to_agent(self, agent_id: str, tool_id: str):
+ def attach_tool(self, agent_id: str, tool_id: str) -> AgentState:
raise NotImplementedError
- def remove_tool_from_agent(self, agent_id: str, tool_id: str):
+ def detach_tool(self, agent_id: str, tool_id: str) -> AgentState:
raise NotImplementedError
- def rename_agent(self, agent_id: str, new_name: str):
+ def rename_agent(self, agent_id: str, new_name: str) -> AgentState:
raise NotImplementedError
- def delete_agent(self, agent_id: str):
+ def delete_agent(self, agent_id: str) -> None:
raise NotImplementedError
def get_agent(self, agent_id: str) -> AgentState:
@@ -218,6 +218,18 @@ class AbstractClient(object):
def get_tool_id(self, name: str) -> Optional[str]:
raise NotImplementedError
+ def list_attached_tools(self, agent_id: str) -> List[Tool]:
+ """
+ List all tools attached to an agent.
+
+ Args:
+ agent_id (str): ID of the agent
+
+ Returns:
+ List[Tool]: A list of attached tools
+ """
+ raise NotImplementedError
+
def upsert_base_tools(self) -> List[Tool]:
raise NotImplementedError
@@ -242,10 +254,10 @@ class AbstractClient(object):
def get_source_id(self, source_name: str) -> str:
raise NotImplementedError
- def attach_source_to_agent(self, agent_id: str, source_id: Optional[str] = None, source_name: Optional[str] = None):
+ def attach_source(self, agent_id: str, source_id: Optional[str] = None, source_name: Optional[str] = None) -> AgentState:
raise NotImplementedError
- def detach_source_from_agent(self, agent_id: str, source_id: Optional[str] = None, source_name: Optional[str] = None):
+ def detach_source(self, agent_id: str, source_id: Optional[str] = None, source_name: Optional[str] = None) -> AgentState:
raise NotImplementedError
def list_sources(self) -> List[Source]:
@@ -397,6 +409,26 @@ class AbstractClient(object):
"""
raise NotImplementedError
+ def attach_block(self, agent_id: str, block_id: str) -> AgentState:
+ """
+ Attach a block to an agent.
+
+ Args:
+ agent_id (str): ID of the agent
+ block_id (str): ID of the block to attach
+ """
+ raise NotImplementedError
+
+ def detach_block(self, agent_id: str, block_id: str) -> AgentState:
+ """
+ Detach a block from an agent.
+
+ Args:
+ agent_id (str): ID of the agent
+ block_id (str): ID of the block to detach
+ """
+ raise NotImplementedError
+
class RESTClient(AbstractClient):
"""
@@ -628,7 +660,7 @@ class RESTClient(AbstractClient):
embedding_config: Optional[EmbeddingConfig] = None,
message_ids: Optional[List[str]] = None,
tags: Optional[List[str]] = None,
- ):
+ ) -> AgentState:
"""
Update an existing agent
@@ -678,7 +710,7 @@ class RESTClient(AbstractClient):
raise ValueError(f"Failed to get tools from agents: {response.text}")
return [Tool(**tool) for tool in response.json()]
- def add_tool_to_agent(self, agent_id: str, tool_id: str):
+ def attach_tool(self, agent_id: str, tool_id: str) -> AgentState:
"""
Add tool to an existing agent
@@ -689,12 +721,12 @@ class RESTClient(AbstractClient):
Returns:
agent_state (AgentState): State of the updated agent
"""
- response = requests.patch(f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/add-tool/{tool_id}", headers=self.headers)
+ response = requests.patch(f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/tools/attach/{tool_id}", headers=self.headers)
if response.status_code != 200:
raise ValueError(f"Failed to update agent: {response.text}")
return AgentState(**response.json())
- def remove_tool_from_agent(self, agent_id: str, tool_id: str):
+ def detach_tool(self, agent_id: str, tool_id: str) -> AgentState:
"""
Removes tools from an existing agent
@@ -706,12 +738,12 @@ class RESTClient(AbstractClient):
agent_state (AgentState): State of the updated agent
"""
- response = requests.patch(f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/remove-tool/{tool_id}", headers=self.headers)
+ response = requests.patch(f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/tools/detach/{tool_id}", headers=self.headers)
if response.status_code != 200:
raise ValueError(f"Failed to update agent: {response.text}")
return AgentState(**response.json())
- def rename_agent(self, agent_id: str, new_name: str):
+ def rename_agent(self, agent_id: str, new_name: str) -> AgentState:
"""
Rename an agent
@@ -719,10 +751,12 @@ class RESTClient(AbstractClient):
agent_id (str): ID of the agent
new_name (str): New name for the agent
+ Returns:
+ agent_state (AgentState): State of the updated agent
"""
return self.update_agent(agent_id, name=new_name)
- def delete_agent(self, agent_id: str):
+ def delete_agent(self, agent_id: str) -> None:
"""
Delete an agent
@@ -1433,7 +1467,7 @@ class RESTClient(AbstractClient):
raise ValueError(f"Failed to update source: {response.text}")
return Source(**response.json())
- def attach_source_to_agent(self, source_id: str, agent_id: str):
+ def attach_source(self, source_id: str, agent_id: str) -> AgentState:
"""
Attach a source to an agent
@@ -1443,15 +1477,20 @@ class RESTClient(AbstractClient):
source_name (str): Name of the source
"""
params = {"agent_id": agent_id}
- response = requests.post(f"{self.base_url}/{self.api_prefix}/sources/{source_id}/attach", params=params, headers=self.headers)
+ response = requests.patch(
+ f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/sources/attach/{source_id}", params=params, headers=self.headers
+ )
assert response.status_code == 200, f"Failed to attach source to agent: {response.text}"
+ return AgentState(**response.json())
- def detach_source(self, source_id: str, agent_id: str):
+ def detach_source(self, source_id: str, agent_id: str) -> AgentState:
"""Detach a source from an agent"""
params = {"agent_id": str(agent_id)}
- response = requests.post(f"{self.base_url}/{self.api_prefix}/sources/{source_id}/detach", params=params, headers=self.headers)
+ response = requests.patch(
+ f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/sources/detach/{source_id}", params=params, headers=self.headers
+ )
assert response.status_code == 200, f"Failed to detach source from agent: {response.text}"
- return Source(**response.json())
+ return AgentState(**response.json())
# tools
@@ -1474,6 +1513,21 @@ class RESTClient(AbstractClient):
return None
return tools[0].id
+ def list_attached_tools(self, agent_id: str) -> List[Tool]:
+ """
+ List all tools attached to an agent.
+
+ Args:
+ agent_id (str): ID of the agent
+
+ Returns:
+ List[Tool]: A list of attached tools
+ """
+ response = requests.get(f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/tools", headers=self.headers)
+ if response.status_code != 200:
+ raise ValueError(f"Failed to list attached tools: {response.text}")
+ return [Tool(**tool) for tool in response.json()]
+
def upsert_base_tools(self) -> List[Tool]:
response = requests.post(f"{self.base_url}/{self.api_prefix}/tools/add-base-tools/", headers=self.headers)
if response.status_code != 200:
@@ -1843,66 +1897,36 @@ class RESTClient(AbstractClient):
block = self.get_agent_memory_block(agent_id, current_label)
return self.update_block(block.id, label=new_label)
- # TODO: remove this
- def add_agent_memory_block(self, agent_id: str, create_block: CreateBlock) -> Memory:
- """
- Create and link a memory block to an agent's core memory
-
- Args:
- agent_id (str): The agent ID
- create_block (CreateBlock): The block to create
-
- Returns:
- memory (Memory): The updated memory
- """
- response = requests.post(
- f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/core_memory/blocks",
- headers=self.headers,
- json=create_block.model_dump(),
- )
- if response.status_code != 200:
- raise ValueError(f"Failed to add agent memory block: {response.text}")
- return Memory(**response.json())
-
- def link_agent_memory_block(self, agent_id: str, block_id: str) -> Memory:
+ def attach_block(self, agent_id: str, block_id: str) -> AgentState:
"""
- Link a block to an agent's core memory
+ Attach a block to an agent.
Args:
- agent_id (str): The agent ID
- block_id (str): The block ID
-
- Returns:
- memory (Memory): The updated memory
+ agent_id (str): ID of the agent
+ block_id (str): ID of the block to attach
"""
- params = {"agent_id": agent_id}
response = requests.patch(
- f"{self.base_url}/{self.api_prefix}/blocks/{block_id}/attach",
- params=params,
+ f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/core_memory/blocks/attach/{block_id}",
headers=self.headers,
)
if response.status_code != 200:
- raise ValueError(f"Failed to link agent memory block: {response.text}")
- return Block(**response.json())
+ raise ValueError(f"Failed to attach block to agent: {response.text}")
+ return AgentState(**response.json())
- def remove_agent_memory_block(self, agent_id: str, block_label: str) -> Memory:
+ def detach_block(self, agent_id: str, block_id: str) -> AgentState:
"""
- Unlike a block from the agent's core memory
+ Detach a block from an agent.
Args:
- agent_id (str): The agent ID
- block_label (str): The block label
-
- Returns:
- memory (Memory): The updated memory
+ agent_id (str): ID of the agent
+ block_id (str): ID of the block to detach
"""
- response = requests.delete(
- f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/core_memory/blocks/{block_label}",
- headers=self.headers,
+ response = requests.patch(
+ f"{self.base_url}/{self.api_prefix}/agents/{agent_id}/core_memory/blocks/detach/{block_id}", headers=self.headers
)
if response.status_code != 200:
- raise ValueError(f"Failed to remove agent memory block: {response.text}")
- return Memory(**response.json())
+ raise ValueError(f"Failed to detach block from agent: {response.text}")
+ return AgentState(**response.json())
def list_agent_memory_blocks(self, agent_id: str) -> List[Block]:
"""
@@ -2389,7 +2413,7 @@ class LocalClient(AbstractClient):
Returns:
agent_state (AgentState): State of the updated agent
"""
- # TODO: add the abilitty to reset linked block_ids
+ # TODO: add the ability to reset linked block_ids
self.interface.clear()
agent_state = self.server.agent_manager.update_agent(
agent_id,
@@ -2421,7 +2445,7 @@ class LocalClient(AbstractClient):
self.interface.clear()
return self.server.agent_manager.get_agent_by_id(agent_id=agent_id, actor=self.user).tools
- def add_tool_to_agent(self, agent_id: str, tool_id: str):
+ def attach_tool(self, agent_id: str, tool_id: str) -> AgentState:
"""
Add tool to an existing agent
@@ -2436,7 +2460,7 @@ class LocalClient(AbstractClient):
agent_state = self.server.agent_manager.attach_tool(agent_id=agent_id, tool_id=tool_id, actor=self.user)
return agent_state
- def remove_tool_from_agent(self, agent_id: str, tool_id: str):
+ def detach_tool(self, agent_id: str, tool_id: str) -> AgentState:
"""
Removes tools from an existing agent
@@ -2451,17 +2475,20 @@ class LocalClient(AbstractClient):
agent_state = self.server.agent_manager.detach_tool(agent_id=agent_id, tool_id=tool_id, actor=self.user)
return agent_state
- def rename_agent(self, agent_id: str, new_name: str):
+ def rename_agent(self, agent_id: str, new_name: str) -> AgentState:
"""
Rename an agent
Args:
agent_id (str): ID of the agent
new_name (str): New name for the agent
+
+ Returns:
+ agent_state (AgentState): State of the updated agent
"""
- self.update_agent(agent_id, name=new_name)
+ return self.update_agent(agent_id, name=new_name)
- def delete_agent(self, agent_id: str):
+ def delete_agent(self, agent_id: str) -> None:
"""
Delete an agent
@@ -2874,7 +2901,7 @@ class LocalClient(AbstractClient):
def load_composio_tool(self, action: "ActionType") -> Tool:
tool_create = ToolCreate.from_composio(action_name=action.name)
- return self.server.tool_manager.create_or_update_tool(pydantic_tool=Tool(**tool_create.model_dump()), actor=self.user)
+ return self.server.tool_manager.create_or_update_composio_tool(pydantic_tool=Tool(**tool_create.model_dump()), actor=self.user)
def create_tool(
self,
@@ -3036,6 +3063,18 @@ class LocalClient(AbstractClient):
tool = self.server.tool_manager.get_tool_by_name(tool_name=name, actor=self.user)
return tool.id if tool else None
+ def list_attached_tools(self, agent_id: str) -> List[Tool]:
+ """
+ List all tools attached to an agent.
+
+ Args:
+ agent_id (str): ID of the agent
+
+ Returns:
+ List[Tool]: List of tools attached to the agent
+ """
+ return self.server.agent_manager.list_attached_tools(agent_id=agent_id, actor=self.user)
+
def load_data(self, connector: DataConnector, source_name: str):
"""
Load data into a source
@@ -3069,14 +3108,14 @@ class LocalClient(AbstractClient):
self.server.load_file_to_source(source_id=source_id, file_path=filename, job_id=job.id, actor=self.user)
return job
- def delete_file_from_source(self, source_id: str, file_id: str):
+ def delete_file_from_source(self, source_id: str, file_id: str) -> None:
self.server.source_manager.delete_file(file_id, actor=self.user)
def get_job(self, job_id: str):
return self.server.job_manager.get_job_by_id(job_id=job_id, actor=self.user)
def delete_job(self, job_id: str):
- return self.server.job_manager.delete_job(job_id=job_id, actor=self.user)
+ return self.server.job_manager.delete_job_by_id(job_id=job_id, actor=self.user)
def list_jobs(self):
return self.server.job_manager.list_jobs(actor=self.user)
@@ -3135,7 +3174,7 @@ class LocalClient(AbstractClient):
"""
return self.server.source_manager.get_source_by_name(source_name=source_name, actor=self.user).id
- def attach_source_to_agent(self, agent_id: str, source_id: Optional[str] = None, source_name: Optional[str] = None):
+ def attach_source(self, agent_id: str, source_id: Optional[str] = None, source_name: Optional[str] = None) -> AgentState:
"""
Attach a source to an agent
@@ -3148,9 +3187,9 @@ class LocalClient(AbstractClient):
source = self.server.source_manager.get_source_by_id(source_id=source_id, actor=self.user)
source_id = source.id
- self.server.agent_manager.attach_source(source_id=source_id, agent_id=agent_id, actor=self.user)
+ return self.server.agent_manager.attach_source(source_id=source_id, agent_id=agent_id, actor=self.user)
- def detach_source_from_agent(self, agent_id: str, source_id: Optional[str] = None, source_name: Optional[str] = None):
+ def detach_source(self, agent_id: str, source_id: Optional[str] = None, source_name: Optional[str] = None) -> AgentState:
"""
Detach a source from an agent by removing all `Passage` objects that were loaded from the source from archival memory.
Args:
@@ -3483,51 +3522,7 @@ class LocalClient(AbstractClient):
block = self.get_agent_memory_block(agent_id, current_label)
return self.update_block(block.id, label=new_label)
- # TODO: remove this
- def add_agent_memory_block(self, agent_id: str, create_block: CreateBlock) -> Memory:
- """
- Create and link a memory block to an agent's core memory
-
- Args:
- agent_id (str): The agent ID
- create_block (CreateBlock): The block to create
-
- Returns:
- memory (Memory): The updated memory
- """
- block_req = Block(**create_block.model_dump())
- block = self.server.block_manager.create_or_update_block(actor=self.user, block=block_req)
- # Link the block to the agent
- agent = self.server.agent_manager.attach_block(agent_id=agent_id, block_id=block.id, actor=self.user)
- return agent.memory
-
- def link_agent_memory_block(self, agent_id: str, block_id: str) -> Memory:
- """
- Link a block to an agent's core memory
-
- Args:
- agent_id (str): The agent ID
- block_id (str): The block ID
-
- Returns:
- memory (Memory): The updated memory
- """
- return self.server.agent_manager.attach_block(agent_id=agent_id, block_id=block_id, actor=self.user)
-
- def remove_agent_memory_block(self, agent_id: str, block_label: str) -> Memory:
- """
- Unlike a block from the agent's core memory
-
- Args:
- agent_id (str): The agent ID
- block_label (str): The block label
-
- Returns:
- memory (Memory): The updated memory
- """
- return self.server.agent_manager.detach_block_with_label(agent_id=agent_id, block_label=block_label, actor=self.user)
-
- def list_agent_memory_blocks(self, agent_id: str) -> List[Block]:
+ def get_agent_memory_blocks(self, agent_id: str) -> List[Block]:
"""
Get all the blocks in the agent's core memory
@@ -3608,6 +3603,26 @@ class LocalClient(AbstractClient):
data["label"] = label
return self.server.block_manager.update_block(block_id, actor=self.user, block_update=BlockUpdate(**data))
+ def attach_block(self, agent_id: str, block_id: str) -> AgentState:
+ """
+ Attach a block to an agent.
+
+ Args:
+ agent_id (str): ID of the agent
+ block_id (str): ID of the block to attach
+ """
+ return self.server.agent_manager.attach_block(agent_id=agent_id, block_id=block_id, actor=self.user)
+
+ def detach_block(self, agent_id: str, block_id: str) -> AgentState:
+ """
+ Detach a block from an agent.
+
+ Args:
+ agent_id (str): ID of the agent
+ block_id (str): ID of the block to detach
+ """
+ return self.server.agent_manager.detach_block(agent_id=agent_id, block_id=block_id, actor=self.user)
+
def get_run_messages(
self,
run_id: str,
diff --git a/letta/constants.py b/letta/constants.py
index 0b46202aa..ee062cdac 100644
--- a/letta/constants.py
+++ b/letta/constants.py
@@ -125,8 +125,6 @@ LLM_MAX_TOKENS = {
"gpt-3.5-turbo-16k-0613": 16385, # legacy
"gpt-3.5-turbo-0301": 4096, # legacy
}
-# The amount of tokens before a sytem warning about upcoming truncation is sent to Letta
-MESSAGE_SUMMARY_WARNING_FRAC = 0.75
# The error message that Letta will receive
# MESSAGE_SUMMARY_WARNING_STR = f"Warning: the conversation history will soon reach its maximum length and be trimmed. Make sure to save any important information from the conversation to your memory before it is removed."
# Much longer and more specific variant of the prompt
@@ -138,15 +136,10 @@ MESSAGE_SUMMARY_WARNING_STR = " ".join(
# "Remember to pass request_heartbeat = true if you would like to send a message immediately after.",
]
)
-# The fraction of tokens we truncate down to
-MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC = 0.75
+
# The ackknowledgement message used in the summarize sequence
MESSAGE_SUMMARY_REQUEST_ACK = "Understood, I will respond with a summary of the message (and only the summary, nothing else) once I receive the conversation history. I'm ready."
-# Even when summarizing, we want to keep a handful of recent messages
-# These serve as in-context examples of how to use functions / what user messages look like
-MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST = 3
-
# Maximum length of an error message
MAX_ERROR_MESSAGE_CHAR_LIMIT = 500
diff --git a/letta/functions/helpers.py b/letta/functions/helpers.py
index cbdb50012..6ba9cc39d 100644
--- a/letta/functions/helpers.py
+++ b/letta/functions/helpers.py
@@ -12,12 +12,37 @@ from letta.schemas.letta_response import LettaResponse
from letta.schemas.message import MessageCreate
-def generate_composio_tool_wrapper(action_name: str) -> tuple[str, str]:
- # Instantiate the object
- tool_instantiation_str = f"composio_toolset.get_tools(actions=['{action_name}'])[0]"
+# TODO: This is kind of hacky, as this is used to search up the action later on composio's side
+# TODO: So be very careful changing/removing these pair of functions
+def generate_func_name_from_composio_action(action_name: str) -> str:
+ """
+ Generates the composio function name from the composio action.
+ Args:
+ action_name: The composio action name
+
+ Returns:
+ function name
+ """
+ return action_name.lower()
+
+
+def generate_composio_action_from_func_name(func_name: str) -> str:
+ """
+ Generates the composio action from the composio function name.
+
+ Args:
+ func_name: The composio function name
+
+ Returns:
+ composio action name
+ """
+ return func_name.upper()
+
+
+def generate_composio_tool_wrapper(action_name: str) -> tuple[str, str]:
# Generate func name
- func_name = action_name.lower()
+ func_name = generate_func_name_from_composio_action(action_name)
wrapper_function_str = f"""
def {func_name}(**kwargs):
diff --git a/letta/functions/schema_generator.py b/letta/functions/schema_generator.py
index 1f33d87d6..7c2764ae1 100644
--- a/letta/functions/schema_generator.py
+++ b/letta/functions/schema_generator.py
@@ -2,6 +2,7 @@ import inspect
import warnings
from typing import Any, Dict, List, Optional, Type, Union, get_args, get_origin
+from composio.client.collections import ActionParametersModel
from docstring_parser import parse
from pydantic import BaseModel
@@ -429,3 +430,57 @@ def generate_schema_from_args_schema_v2(
function_call_json["parameters"]["required"].append("request_heartbeat")
return function_call_json
+
+
+def generate_tool_schema_for_composio(
+ parameters_model: ActionParametersModel,
+ name: str,
+ description: str,
+ append_heartbeat: bool = True,
+) -> Dict[str, Any]:
+ properties_json = {}
+ required_fields = parameters_model.required or []
+
+ # Extract properties from the ActionParametersModel
+ for field_name, field_props in parameters_model.properties.items():
+ # Initialize the property structure
+ property_schema = {
+ "type": field_props["type"],
+ "description": field_props.get("description", ""),
+ }
+
+ # Handle optional default values
+ if "default" in field_props:
+ property_schema["default"] = field_props["default"]
+
+ # Handle enumerations
+ if "enum" in field_props:
+ property_schema["enum"] = field_props["enum"]
+
+ # Handle array item types
+ if field_props["type"] == "array" and "items" in field_props:
+ property_schema["items"] = field_props["items"]
+
+ # Add the property to the schema
+ properties_json[field_name] = property_schema
+
+ # Add the optional heartbeat parameter
+ if append_heartbeat:
+ properties_json["request_heartbeat"] = {
+ "type": "boolean",
+ "description": "Request an immediate heartbeat after function execution. Set to `True` if you want to send a follow-up message or run a follow-up function.",
+ }
+ required_fields.append("request_heartbeat")
+
+ # Return the final schema
+ return {
+ "name": name,
+ "description": description,
+ "strict": True,
+ "parameters": {
+ "type": "object",
+ "properties": properties_json,
+ "additionalProperties": False,
+ "required": required_fields,
+ },
+ }
diff --git a/letta/llm_api/helpers.py b/letta/llm_api/helpers.py
index 7c99bbcdb..cdb178b93 100644
--- a/letta/llm_api/helpers.py
+++ b/letta/llm_api/helpers.py
@@ -7,8 +7,10 @@ from typing import Any, List, Union
import requests
from letta.constants import OPENAI_CONTEXT_WINDOW_ERROR_SUBSTRING
+from letta.schemas.message import Message
from letta.schemas.openai.chat_completion_response import ChatCompletionResponse, Choice
-from letta.utils import json_dumps, printd
+from letta.settings import summarizer_settings
+from letta.utils import count_tokens, json_dumps, printd
def _convert_to_structured_output_helper(property: dict) -> dict:
@@ -287,6 +289,54 @@ def unpack_inner_thoughts_from_kwargs(choice: Choice, inner_thoughts_key: str) -
return rewritten_choice
+def calculate_summarizer_cutoff(in_context_messages: List[Message], token_counts: List[int], logger: "logging.Logger") -> int:
+ if len(in_context_messages) != len(token_counts):
+ raise ValueError(
+ f"Given in_context_messages has different length from given token_counts: {len(in_context_messages)} != {len(token_counts)}"
+ )
+
+ in_context_messages_openai = [m.to_openai_dict() for m in in_context_messages]
+
+ if summarizer_settings.evict_all_messages:
+ logger.info("Evicting all messages...")
+ return len(in_context_messages)
+ else:
+ # Start at index 1 (past the system message),
+ # and collect messages for summarization until we reach the desired truncation token fraction (eg 50%)
+ # We do the inverse of `desired_memory_token_pressure` to get what we need to remove
+ desired_token_count_to_summarize = int(sum(token_counts) * (1 - summarizer_settings.desired_memory_token_pressure))
+ logger.info(f"desired_token_count_to_summarize={desired_token_count_to_summarize}")
+
+ tokens_so_far = 0
+ cutoff = 0
+ for i, msg in enumerate(in_context_messages_openai):
+ # Skip system
+ if i == 0:
+ continue
+ cutoff = i
+ tokens_so_far += token_counts[i]
+
+ if msg["role"] not in ["user", "tool", "function"] and tokens_so_far >= desired_token_count_to_summarize:
+ # Break if the role is NOT a user or tool/function and tokens_so_far is enough
+ break
+ elif len(in_context_messages) - cutoff - 1 <= summarizer_settings.keep_last_n_messages:
+ # Also break if we reached the `keep_last_n_messages` threshold
+ # NOTE: This may be on a user, tool, or function in theory
+ logger.warning(
+ f"Breaking summary cutoff early on role={msg['role']} because we hit the `keep_last_n_messages`={summarizer_settings.keep_last_n_messages}"
+ )
+ break
+
+ logger.info(f"Evicting {cutoff}/{len(in_context_messages)} messages...")
+ return cutoff + 1
+
+
+def get_token_counts_for_messages(in_context_messages: List[Message]) -> List[int]:
+ in_context_messages_openai = [m.to_openai_dict() for m in in_context_messages]
+ token_counts = [count_tokens(str(msg)) for msg in in_context_messages_openai]
+ return token_counts
+
+
def is_context_overflow_error(exception: Union[requests.exceptions.RequestException, Exception]) -> bool:
"""Checks if an exception is due to context overflow (based on common OpenAI response messages)"""
from letta.utils import printd
diff --git a/letta/memory.py b/letta/memory.py
index 107990948..b81e5e1da 100644
--- a/letta/memory.py
+++ b/letta/memory.py
@@ -1,12 +1,13 @@
from typing import Callable, Dict, List
-from letta.constants import MESSAGE_SUMMARY_REQUEST_ACK, MESSAGE_SUMMARY_WARNING_FRAC
+from letta.constants import MESSAGE_SUMMARY_REQUEST_ACK
from letta.llm_api.llm_api_tools import create
from letta.prompts.gpt_summarize import SYSTEM as SUMMARY_PROMPT_SYSTEM
from letta.schemas.agent import AgentState
from letta.schemas.enums import MessageRole
from letta.schemas.memory import Memory
from letta.schemas.message import Message
+from letta.settings import summarizer_settings
from letta.utils import count_tokens, printd
@@ -49,8 +50,8 @@ def summarize_messages(
summary_prompt = SUMMARY_PROMPT_SYSTEM
summary_input = _format_summary_history(message_sequence_to_summarize)
summary_input_tkns = count_tokens(summary_input)
- if summary_input_tkns > MESSAGE_SUMMARY_WARNING_FRAC * context_window:
- trunc_ratio = (MESSAGE_SUMMARY_WARNING_FRAC * context_window / summary_input_tkns) * 0.8 # For good measure...
+ if summary_input_tkns > summarizer_settings.memory_warning_threshold * context_window:
+ trunc_ratio = (summarizer_settings.memory_warning_threshold * context_window / summary_input_tkns) * 0.8 # For good measure...
cutoff = int(len(message_sequence_to_summarize) * trunc_ratio)
summary_input = str(
[summarize_messages(agent_state, message_sequence_to_summarize=message_sequence_to_summarize[:cutoff])]
@@ -58,10 +59,11 @@ def summarize_messages(
)
dummy_agent_id = agent_state.id
- message_sequence = []
- message_sequence.append(Message(agent_id=dummy_agent_id, role=MessageRole.system, text=summary_prompt))
- message_sequence.append(Message(agent_id=dummy_agent_id, role=MessageRole.assistant, text=MESSAGE_SUMMARY_REQUEST_ACK))
- message_sequence.append(Message(agent_id=dummy_agent_id, role=MessageRole.user, text=summary_input))
+ message_sequence = [
+ Message(agent_id=dummy_agent_id, role=MessageRole.system, text=summary_prompt),
+ Message(agent_id=dummy_agent_id, role=MessageRole.assistant, text=MESSAGE_SUMMARY_REQUEST_ACK),
+ Message(agent_id=dummy_agent_id, role=MessageRole.user, text=summary_input),
+ ]
# TODO: We need to eventually have a separate LLM config for the summarizer LLM
llm_config_no_inner_thoughts = agent_state.llm_config.model_copy(deep=True)
diff --git a/letta/orm/enums.py b/letta/orm/enums.py
index aa7f800bf..e87d28d23 100644
--- a/letta/orm/enums.py
+++ b/letta/orm/enums.py
@@ -6,6 +6,7 @@ class ToolType(str, Enum):
LETTA_CORE = "letta_core"
LETTA_MEMORY_CORE = "letta_memory_core"
LETTA_MULTI_AGENT_CORE = "letta_multi_agent_core"
+ EXTERNAL_COMPOSIO = "external_composio"
class JobType(str, Enum):
diff --git a/letta/schemas/environment_variables.py b/letta/schemas/environment_variables.py
index 9f482c1c4..bf423e06e 100644
--- a/letta/schemas/environment_variables.py
+++ b/letta/schemas/environment_variables.py
@@ -26,7 +26,7 @@ class EnvironmentVariableUpdateBase(LettaBase):
description: Optional[str] = Field(None, description="An optional description of the environment variable.")
-# Sandbox-Specific Environment Variable
+# Environment Variable
class SandboxEnvironmentVariableBase(EnvironmentVariableBase):
__id_prefix__ = "sandbox-env"
sandbox_config_id: str = Field(..., description="The ID of the sandbox config this environment variable belongs to.")
diff --git a/letta/schemas/tool.py b/letta/schemas/tool.py
index 610685b45..0296f0906 100644
--- a/letta/schemas/tool.py
+++ b/letta/schemas/tool.py
@@ -9,11 +9,14 @@ from letta.constants import (
LETTA_MULTI_AGENT_TOOL_MODULE_NAME,
)
from letta.functions.functions import derive_openai_json_schema, get_json_schema_from_module
-from letta.functions.helpers import generate_composio_tool_wrapper, generate_langchain_tool_wrapper
-from letta.functions.schema_generator import generate_schema_from_args_schema_v2
+from letta.functions.helpers import generate_composio_action_from_func_name, generate_composio_tool_wrapper, generate_langchain_tool_wrapper
+from letta.functions.schema_generator import generate_schema_from_args_schema_v2, generate_tool_schema_for_composio
+from letta.log import get_logger
from letta.orm.enums import ToolType
from letta.schemas.letta_base import LettaBase
+logger = get_logger(__name__)
+
class BaseTool(LettaBase):
__id_prefix__ = "tool"
@@ -52,14 +55,16 @@ class Tool(BaseTool):
last_updated_by_id: Optional[str] = Field(None, description="The id of the user that made this Tool.")
@model_validator(mode="after")
- def populate_missing_fields(self):
+ def refresh_source_code_and_json_schema(self):
"""
- Populate missing fields: name, description, and json_schema.
+ Refresh name, description, source_code, and json_schema.
"""
if self.tool_type == ToolType.CUSTOM:
# If it's a custom tool, we need to ensure source_code is present
if not self.source_code:
- raise ValueError(f"Custom tool with id={self.id} is missing source_code field.")
+ error_msg = f"Custom tool with id={self.id} is missing source_code field."
+ logger.error(error_msg)
+ raise ValueError(error_msg)
# Always derive json_schema for freshest possible json_schema
# TODO: Instead of checking the tag, we should having `COMPOSIO` as a specific ToolType
@@ -72,6 +77,24 @@ class Tool(BaseTool):
elif self.tool_type in {ToolType.LETTA_MULTI_AGENT_CORE}:
# If it's letta multi-agent tool, we also generate the json_schema on the fly here
self.json_schema = get_json_schema_from_module(module_name=LETTA_MULTI_AGENT_TOOL_MODULE_NAME, function_name=self.name)
+ elif self.tool_type == ToolType.EXTERNAL_COMPOSIO:
+ # If it is a composio tool, we generate both the source code and json schema on the fly here
+ # TODO: This is brittle, need to think long term about how to improve this
+ try:
+ composio_action = generate_composio_action_from_func_name(self.name)
+ tool_create = ToolCreate.from_composio(composio_action)
+ self.source_code = tool_create.source_code
+ self.json_schema = tool_create.json_schema
+ self.description = tool_create.description
+ self.tags = tool_create.tags
+ except Exception as e:
+ logger.error(f"Encountered exception while attempting to refresh source_code and json_schema for composio_tool: {e}")
+
+ # At this point, we need to validate that at least json_schema is populated
+ if not self.json_schema:
+ error_msg = f"Tool with id={self.id} name={self.name} tool_type={self.tool_type} is missing a json_schema."
+ logger.error(error_msg)
+ raise ValueError(error_msg)
# Derive name from the JSON schema if not provided
if not self.name:
@@ -100,7 +123,7 @@ class ToolCreate(LettaBase):
return_char_limit: int = Field(FUNCTION_RETURN_CHAR_LIMIT, description="The maximum number of characters in the response.")
@classmethod
- def from_composio(cls, action_name: str, api_key: Optional[str] = None) -> "ToolCreate":
+ def from_composio(cls, action_name: str) -> "ToolCreate":
"""
Class method to create an instance of Letta-compatible Composio Tool.
Check https://docs.composio.dev/introduction/intro/overview to look at options for from_composio
@@ -115,24 +138,21 @@ class ToolCreate(LettaBase):
from composio import LogLevel
from composio_langchain import ComposioToolSet
- if api_key:
- # Pass in an external API key
- composio_toolset = ComposioToolSet(logging_level=LogLevel.ERROR, api_key=api_key)
- else:
- # Use environmental variable
- composio_toolset = ComposioToolSet(logging_level=LogLevel.ERROR)
- composio_tools = composio_toolset.get_tools(actions=[action_name])
+ composio_toolset = ComposioToolSet(logging_level=LogLevel.ERROR)
+ composio_action_schemas = composio_toolset.get_action_schemas(actions=[action_name], check_connected_accounts=False)
- assert len(composio_tools) > 0, "User supplied parameters do not match any Composio tools"
- assert len(composio_tools) == 1, f"User supplied parameters match too many Composio tools; {len(composio_tools)} > 1"
+ assert len(composio_action_schemas) > 0, "User supplied parameters do not match any Composio tools"
+ assert (
+ len(composio_action_schemas) == 1
+ ), f"User supplied parameters match too many Composio tools; {len(composio_action_schemas)} > 1"
- composio_tool = composio_tools[0]
+ composio_action_schema = composio_action_schemas[0]
- description = composio_tool.description
+ description = composio_action_schema.description
source_type = "python"
tags = [COMPOSIO_TOOL_TAG_NAME]
wrapper_func_name, wrapper_function_str = generate_composio_tool_wrapper(action_name)
- json_schema = generate_schema_from_args_schema_v2(composio_tool.args_schema, name=wrapper_func_name, description=description)
+ json_schema = generate_tool_schema_for_composio(composio_action_schema.parameters, name=wrapper_func_name, description=description)
return cls(
name=wrapper_func_name,
@@ -175,31 +195,6 @@ class ToolCreate(LettaBase):
json_schema=json_schema,
)
- @classmethod
- def load_default_langchain_tools(cls) -> List["ToolCreate"]:
- # For now, we only support wikipedia tool
- from langchain_community.tools import WikipediaQueryRun
- from langchain_community.utilities import WikipediaAPIWrapper
-
- wikipedia_tool = ToolCreate.from_langchain(
- WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper()), {"langchain_community.utilities": "WikipediaAPIWrapper"}
- )
-
- return [wikipedia_tool]
-
- @classmethod
- def load_default_composio_tools(cls) -> List["ToolCreate"]:
- pass
-
- # TODO: Disable composio tools for now
- # TODO: Naming is causing issues
- # calculator = ToolCreate.from_composio(action_name=Action.MATHEMATICAL_CALCULATOR.name)
- # serp_news = ToolCreate.from_composio(action_name=Action.SERPAPI_NEWS_SEARCH.name)
- # serp_google_search = ToolCreate.from_composio(action_name=Action.SERPAPI_SEARCH.name)
- # serp_google_maps = ToolCreate.from_composio(action_name=Action.SERPAPI_GOOGLE_MAPS_SEARCH.name)
-
- return []
-
class ToolUpdate(LettaBase):
description: Optional[str] = Field(None, description="The description of the tool.")
diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.py
index 1e255b539..dcc3ca716 100644
--- a/letta/server/rest_api/routers/v1/agents.py
+++ b/letta/server/rest_api/routers/v1/agents.py
@@ -126,43 +126,63 @@ def get_tools_from_agent(
):
"""Get tools from an existing agent"""
actor = server.user_manager.get_user_or_default(user_id=user_id)
- return server.agent_manager.get_agent_by_id(agent_id=agent_id, actor=actor).tools
+ return server.agent_manager.list_attached_tools(agent_id=agent_id, actor=actor)
[email protected]("/{agent_id}/add-tool/{tool_id}", response_model=AgentState, operation_id="add_tool_to_agent")
-def add_tool_to_agent(
[email protected]("/{agent_id}/tools/attach/{tool_id}", response_model=AgentState, operation_id="attach_tool_to_agent")
+def attach_tool(
agent_id: str,
tool_id: str,
server: "SyncServer" = Depends(get_letta_server),
- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
+ user_id: Optional[str] = Header(None, alias="user_id"),
):
- """Add tools to an existing agent"""
+ """
+ Attach a tool to an agent.
+ """
actor = server.user_manager.get_user_or_default(user_id=user_id)
return server.agent_manager.attach_tool(agent_id=agent_id, tool_id=tool_id, actor=actor)
[email protected]("/{agent_id}/remove-tool/{tool_id}", response_model=AgentState, operation_id="remove_tool_from_agent")
-def remove_tool_from_agent(
[email protected]("/{agent_id}/tools/detach/{tool_id}", response_model=AgentState, operation_id="detach_tool_from_agent")
+def detach_tool(
agent_id: str,
tool_id: str,
server: "SyncServer" = Depends(get_letta_server),
- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
+ user_id: Optional[str] = Header(None, alias="user_id"),
):
- """Add tools to an existing agent"""
+ """
+ Detach a tool from an agent.
+ """
actor = server.user_manager.get_user_or_default(user_id=user_id)
return server.agent_manager.detach_tool(agent_id=agent_id, tool_id=tool_id, actor=actor)
[email protected]("/{agent_id}/reset-messages", response_model=AgentState, operation_id="reset_messages")
-def reset_messages(
[email protected]("/{agent_id}/sources/attach/{source_id}", response_model=AgentState, operation_id="attach_source_to_agent")
+def attach_source(
agent_id: str,
- add_default_initial_messages: bool = Query(default=False, description="If true, adds the default initial messages after resetting."),
+ source_id: str,
server: "SyncServer" = Depends(get_letta_server),
- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
+ user_id: Optional[str] = Header(None, alias="user_id"),
):
- """Resets the messages for an agent"""
+ """
+ Attach a source to an agent.
+ """
actor = server.user_manager.get_user_or_default(user_id=user_id)
- return server.agent_manager.reset_messages(agent_id=agent_id, actor=actor, add_default_initial_messages=add_default_initial_messages)
+ return server.agent_manager.attach_source(agent_id=agent_id, source_id=source_id, actor=actor)
+
+
[email protected]("/{agent_id}/sources/detach/{source_id}", response_model=AgentState, operation_id="detach_source_from_agent")
+def detach_source(
+ agent_id: str,
+ source_id: str,
+ server: "SyncServer" = Depends(get_letta_server),
+ user_id: Optional[str] = Header(None, alias="user_id"),
+):
+ """
+ Detach a source from an agent.
+ """
+ actor = server.user_manager.get_user_or_default(user_id=user_id)
+ return server.agent_manager.detach_source(agent_id=agent_id, source_id=source_id, actor=actor)
@router.get("/{agent_id}", response_model=AgentState, operation_id="get_agent")
@@ -263,69 +283,54 @@ def list_agent_memory_blocks(
raise HTTPException(status_code=404, detail=str(e))
[email protected]("/{agent_id}/core_memory/blocks", response_model=Memory, operation_id="add_agent_memory_block")
-def add_agent_memory_block(
[email protected]("/{agent_id}/core_memory/blocks/{block_label}", response_model=Block, operation_id="update_agent_memory_block_by_label")
+def update_agent_memory_block(
agent_id: str,
- create_block: CreateBlock = Body(...),
+ block_label: str,
+ block_update: BlockUpdate = Body(...),
server: "SyncServer" = Depends(get_letta_server),
user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
):
"""
- Creates a memory block and links it to the agent.
+ Updates a memory block of an agent.
"""
actor = server.user_manager.get_user_or_default(user_id=user_id)
- # Copied from POST /blocks
- # TODO: Should have block_manager accept only CreateBlock
- # TODO: This will be possible once we move ID creation to the ORM
- block_req = Block(**create_block.model_dump())
- block = server.block_manager.create_or_update_block(actor=actor, block=block_req)
+ block = server.agent_manager.get_block_with_label(agent_id=agent_id, block_label=block_label, actor=actor)
+ block = server.block_manager.update_block(block.id, block_update=block_update, actor=actor)
- # Link the block to the agent
- agent = server.agent_manager.attach_block(agent_id=agent_id, block_id=block.id, actor=actor)
- return agent.memory
+ # This should also trigger a system prompt change in the agent
+ server.agent_manager.rebuild_system_prompt(agent_id=agent_id, actor=actor, force=True, update_timestamp=False)
+
+ return block
[email protected]("/{agent_id}/core_memory/blocks/{block_label}", response_model=Memory, operation_id="remove_agent_memory_block_by_label")
-def remove_agent_memory_block(
[email protected]("/{agent_id}/core_memory/blocks/attach/{block_id}", response_model=AgentState, operation_id="attach_block_to_agent")
+def attach_block(
agent_id: str,
- # TODO should this be block_id, or the label?
- # I think label is OK since it's user-friendly + guaranteed to be unique within a Memory object
- block_label: str,
+ block_id: str,
server: "SyncServer" = Depends(get_letta_server),
- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
+ user_id: Optional[str] = Header(None, alias="user_id"),
):
"""
- Removes a memory block from an agent by unlnking it. If the block is not linked to any other agent, it is deleted.
+ Attach a block to an agent.
"""
actor = server.user_manager.get_user_or_default(user_id=user_id)
+ return server.agent_manager.attach_block(agent_id=agent_id, block_id=block_id, actor=actor)
- # Unlink the block from the agent
- agent = server.agent_manager.detach_block_with_label(agent_id=agent_id, block_label=block_label, actor=actor)
- return agent.memory
-
-
[email protected]("/{agent_id}/core_memory/blocks/{block_label}", response_model=Block, operation_id="update_agent_memory_block_by_label")
-def update_agent_memory_block(
[email protected]("/{agent_id}/core_memory/blocks/detach/{block_id}", response_model=AgentState, operation_id="detach_block_from_agent")
+def detach_block(
agent_id: str,
- block_label: str,
- block_update: BlockUpdate = Body(...),
+ block_id: str,
server: "SyncServer" = Depends(get_letta_server),
- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
+ user_id: Optional[str] = Header(None, alias="user_id"),
):
"""
- Removes a memory block from an agent by unlnking it. If the block is not linked to any other agent, it is deleted.
+ Detach a block from an agent.
"""
actor = server.user_manager.get_user_or_default(user_id=user_id)
-
- block = server.agent_manager.get_block_with_label(agent_id=agent_id, block_label=block_label, actor=actor)
- block = server.block_manager.update_block(block.id, block_update=block_update, actor=actor)
-
- # This should also trigger a system prompt change in the agent
- server.agent_manager.rebuild_system_prompt(agent_id=agent_id, actor=actor, force=True, update_timestamp=False)
-
- return block
+ return server.agent_manager.detach_block(agent_id=agent_id, block_id=block_id, actor=actor)
@router.get("/{agent_id}/archival_memory", response_model=List[Passage], operation_id="list_agent_archival_memory")
@@ -613,3 +618,15 @@ async def send_message_async(
)
return run
+
+
[email protected]("/{agent_id}/reset-messages", response_model=AgentState, operation_id="reset_messages")
+def reset_messages(
+ agent_id: str,
+ add_default_initial_messages: bool = Query(default=False, description="If true, adds the default initial messages after resetting."),
+ server: "SyncServer" = Depends(get_letta_server),
+ user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
+):
+ """Resets the messages for an agent"""
+ actor = server.user_manager.get_user_or_default(user_id=user_id)
+ return server.agent_manager.reset_messages(agent_id=agent_id, actor=actor, add_default_initial_messages=add_default_initial_messages)
diff --git a/letta/server/rest_api/routers/v1/blocks.py b/letta/server/rest_api/routers/v1/blocks.py
index d92132334..ba9e1aef5 100644
--- a/letta/server/rest_api/routers/v1/blocks.py
+++ b/letta/server/rest_api/routers/v1/blocks.py
@@ -1,6 +1,6 @@
from typing import TYPE_CHECKING, List, Optional
-from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query, Response
+from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query
from letta.orm.errors import NoResultFound
from letta.schemas.block import Block, BlockUpdate, CreateBlock
@@ -73,41 +73,3 @@ def get_block(
return block
except NoResultFound:
raise HTTPException(status_code=404, detail="Block not found")
-
-
[email protected]("/{block_id}/attach", response_model=None, status_code=204, operation_id="link_agent_memory_block")
-def link_agent_memory_block(
- block_id: str,
- agent_id: str = Query(..., description="The unique identifier of the agent to attach the source to."),
- server: "SyncServer" = Depends(get_letta_server),
- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
-):
- """
- Link a memory block to an agent.
- """
- actor = server.user_manager.get_user_or_default(user_id=user_id)
-
- try:
- server.agent_manager.attach_block(agent_id=agent_id, block_id=block_id, actor=actor)
- return Response(status_code=204)
- except NoResultFound as e:
- raise HTTPException(status_code=404, detail=str(e))
-
-
[email protected]("/{block_id}/detach", response_model=None, status_code=204, operation_id="unlink_agent_memory_block")
-def unlink_agent_memory_block(
- block_id: str,
- agent_id: str = Query(..., description="The unique identifier of the agent to attach the source to."),
- server: "SyncServer" = Depends(get_letta_server),
- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
-):
- """
- Unlink a memory block from an agent
- """
- actor = server.user_manager.get_user_or_default(user_id=user_id)
-
- try:
- server.agent_manager.detach_block(agent_id=agent_id, block_id=block_id, actor=actor)
- return Response(status_code=204)
- except NoResultFound as e:
- raise HTTPException(status_code=404, detail=str(e))
diff --git a/letta/server/rest_api/routers/v1/sources.py b/letta/server/rest_api/routers/v1/sources.py
index 59b933cfc..0d7213598 100644
--- a/letta/server/rest_api/routers/v1/sources.py
+++ b/letta/server/rest_api/routers/v1/sources.py
@@ -111,36 +111,6 @@ def delete_source(
server.delete_source(source_id=source_id, actor=actor)
[email protected]("/{source_id}/attach", response_model=Source, operation_id="attach_agent_to_source")
-def attach_source_to_agent(
- source_id: str,
- agent_id: str = Query(..., description="The unique identifier of the agent to attach the source to."),
- server: "SyncServer" = Depends(get_letta_server),
- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
-):
- """
- Attach a data source to an existing agent.
- """
- actor = server.user_manager.get_user_or_default(user_id=user_id)
- server.agent_manager.attach_source(source_id=source_id, agent_id=agent_id, actor=actor)
- return server.source_manager.get_source_by_id(source_id=source_id, actor=actor)
-
-
[email protected]("/{source_id}/detach", response_model=Source, operation_id="detach_agent_from_source")
-def detach_source_from_agent(
- source_id: str,
- agent_id: str = Query(..., description="The unique identifier of the agent to detach the source from."),
- server: "SyncServer" = Depends(get_letta_server),
- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
-) -> None:
- """
- Detach a data source from an existing agent.
- """
- actor = server.user_manager.get_user_or_default(user_id=user_id)
- server.agent_manager.detach_source(agent_id=agent_id, source_id=source_id, actor=actor)
- return server.source_manager.get_source_by_id(source_id=source_id, actor=actor)
-
-
@router.post("/{source_id}/upload", response_model=Job, operation_id="upload_file_to_source")
def upload_file_to_source(
file: UploadFile,
diff --git a/letta/server/rest_api/routers/v1/tools.py b/letta/server/rest_api/routers/v1/tools.py
index 4fee8e48e..6a2310ae2 100644
--- a/letta/server/rest_api/routers/v1/tools.py
+++ b/letta/server/rest_api/routers/v1/tools.py
@@ -220,11 +220,10 @@ def add_composio_tool(
Add a new Composio tool by action name (Composio refers to each tool as an `Action`)
"""
actor = server.user_manager.get_user_or_default(user_id=user_id)
- composio_api_key = get_composio_key(server, actor=actor)
try:
- tool_create = ToolCreate.from_composio(action_name=composio_action_name, api_key=composio_api_key)
- return server.tool_manager.create_or_update_tool(pydantic_tool=Tool(**tool_create.model_dump()), actor=actor)
+ tool_create = ToolCreate.from_composio(action_name=composio_action_name)
+ return server.tool_manager.create_or_update_composio_tool(pydantic_tool=Tool(**tool_create.model_dump()), actor=actor)
except EnumStringNotFound as e:
raise HTTPException(
status_code=400, # Bad Request
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index a7dd45077..41e29b786 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -25,6 +25,7 @@ from letta.schemas.message import Message as PydanticMessage
from letta.schemas.message import MessageCreate
from letta.schemas.passage import Passage as PydanticPassage
from letta.schemas.source import Source as PydanticSource
+from letta.schemas.tool import Tool as PydanticTool
from letta.schemas.tool_rule import ToolRule as PydanticToolRule
from letta.schemas.user import User as PydanticUser
from letta.services.block_manager import BlockManager
@@ -464,6 +465,12 @@ class AgentManager:
new_messages = [message_ids[0]] + message_ids[num:] # 0 is system message
return self.set_in_context_messages(agent_id=agent_id, message_ids=new_messages, actor=actor)
+ @enforce_types
+ def trim_all_in_context_messages_except_system(self, agent_id: str, actor: PydanticUser) -> PydanticAgentState:
+ message_ids = self.get_agent_by_id(agent_id=agent_id, actor=actor).message_ids
+ new_messages = [message_ids[0]] # 0 is system message
+ return self.set_in_context_messages(agent_id=agent_id, message_ids=new_messages, actor=actor)
+
@enforce_types
def prepend_to_in_context_messages(self, messages: List[PydanticMessage], agent_id: str, actor: PydanticUser) -> PydanticAgentState:
message_ids = self.get_agent_by_id(agent_id=agent_id, actor=actor).message_ids
@@ -531,7 +538,7 @@ class AgentManager:
# Source Management
# ======================================================================================================================
@enforce_types
- def attach_source(self, agent_id: str, source_id: str, actor: PydanticUser) -> None:
+ def attach_source(self, agent_id: str, source_id: str, actor: PydanticUser) -> PydanticAgentState:
"""
Attaches a source to an agent.
@@ -561,6 +568,7 @@ class AgentManager:
# Commit the changes
agent.update(session, actor=actor)
+ return agent.to_pydantic()
@enforce_types
def list_attached_sources(self, agent_id: str, actor: PydanticUser) -> List[PydanticSource]:
@@ -582,7 +590,7 @@ class AgentManager:
return [source.to_pydantic() for source in agent.sources]
@enforce_types
- def detach_source(self, agent_id: str, source_id: str, actor: PydanticUser) -> None:
+ def detach_source(self, agent_id: str, source_id: str, actor: PydanticUser) -> PydanticAgentState:
"""
Detaches a source from an agent.
@@ -596,10 +604,17 @@ class AgentManager:
agent = AgentModel.read(db_session=session, identifier=agent_id, actor=actor)
# Remove the source from the relationship
- agent.sources = [s for s in agent.sources if s.id != source_id]
+ remaining_sources = [s for s in agent.sources if s.id != source_id]
+
+ if len(remaining_sources) == len(agent.sources): # Source ID was not in the relationship
+ logger.warning(f"Attempted to remove unattached source id={source_id} from agent id={agent_id} by actor={actor}")
+
+ # Update the sources relationship
+ agent.sources = remaining_sources
# Commit the changes
agent.update(session, actor=actor)
+ return agent.to_pydantic()
# ======================================================================================================================
# Block management
@@ -1005,6 +1020,22 @@ class AgentManager:
agent.update(session, actor=actor)
return agent.to_pydantic()
+ @enforce_types
+ def list_attached_tools(self, agent_id: str, actor: PydanticUser) -> List[PydanticTool]:
+ """
+ List all tools attached to an agent.
+
+ Args:
+ agent_id: ID of the agent to list tools for.
+ actor: User performing the action.
+
+ Returns:
+ List[PydanticTool]: List of tools attached to the agent.
+ """
+ with self.session_maker() as session:
+ agent = AgentModel.read(db_session=session, identifier=agent_id, actor=actor)
+ return [tool.to_pydantic() for tool in agent.tools]
+
# ======================================================================================================================
# Tag Management
# ======================================================================================================================
diff --git a/letta/services/tool_manager.py b/letta/services/tool_manager.py
index d21923291..3a66aaa3c 100644
--- a/letta/services/tool_manager.py
+++ b/letta/services/tool_manager.py
@@ -53,6 +53,11 @@ class ToolManager:
return tool
+ @enforce_types
+ def create_or_update_composio_tool(self, pydantic_tool: PydanticTool, actor: PydanticUser) -> PydanticTool:
+ pydantic_tool.tool_type = ToolType.EXTERNAL_COMPOSIO
+ return self.create_or_update_tool(pydantic_tool, actor)
+
@enforce_types
def create_tool(self, pydantic_tool: PydanticTool, actor: PydanticUser) -> PydanticTool:
"""Create a new tool based on the ToolCreate schema."""
diff --git a/letta/settings.py b/letta/settings.py
index da3e429fb..1c5f5bfe6 100644
--- a/letta/settings.py
+++ b/letta/settings.py
@@ -18,6 +18,34 @@ class ToolSettings(BaseSettings):
local_sandbox_dir: Optional[str] = None
+class SummarizerSettings(BaseSettings):
+ model_config = SettingsConfigDict(env_prefix="letta_summarizer_", extra="ignore")
+
+ # Controls if we should evict all messages
+ # TODO: Can refactor this into an enum if we have a bunch of different kinds of summarizers
+ evict_all_messages: bool = False
+
+ # The maximum number of retries for the summarizer
+ # If we reach this cutoff, it probably means that the summarizer is not compressing down the in-context messages any further
+ # And we throw a fatal error
+ max_summarizer_retries: int = 3
+
+ # When to warn the model that a summarize command will happen soon
+ # The amount of tokens before a system warning about upcoming truncation is sent to Letta
+ memory_warning_threshold: float = 0.75
+
+ # Whether to send the system memory warning message
+ send_memory_warning_message: bool = False
+
+ # The desired memory pressure to summarize down to
+ desired_memory_token_pressure: float = 0.3
+
+ # The number of messages at the end to keep
+ # Even when summarizing, we may want to keep a handful of recent messages
+ # These serve as in-context examples of how to use functions / what user messages look like
+ keep_last_n_messages: int = 0
+
+
class ModelSettings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
@@ -147,3 +175,4 @@ settings = Settings(_env_parse_none_str="None")
test_settings = TestSettings()
model_settings = ModelSettings()
tool_settings = ToolSettings()
+summarizer_settings = SummarizerSettings()
diff --git a/letta/system.py b/letta/system.py
index d903bf1fe..9c795704c 100644
--- a/letta/system.py
+++ b/letta/system.py
@@ -161,10 +161,10 @@ def package_system_message(system_message, message_type="system_alert", time=Non
return json.dumps(packaged_message)
-def package_summarize_message(summary, summary_length, hidden_message_count, total_message_count, timestamp=None):
+def package_summarize_message(summary, summary_message_count, hidden_message_count, total_message_count, timestamp=None):
context_message = (
f"Note: prior messages ({hidden_message_count} of {total_message_count} total messages) have been hidden from view due to conversation memory constraints.\n"
- + f"The following is a summary of the previous {summary_length} messages:\n {summary}"
+ + f"The following is a summary of the previous {summary_message_count} messages:\n {summary}"
)
formatted_time = get_local_time() if timestamp is None else timestamp
diff --git a/poetry.lock b/poetry.lock
index 9e35498f2..c8213cb9f 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -416,10 +416,6 @@ files = [
{file = "Brotli-1.1.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:a37b8f0391212d29b3a91a799c8e4a2855e0576911cdfb2515487e30e322253d"},
{file = "Brotli-1.1.0-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:e84799f09591700a4154154cab9787452925578841a94321d5ee8fb9a9a328f0"},
{file = "Brotli-1.1.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:f66b5337fa213f1da0d9000bc8dc0cb5b896b726eefd9c6046f699b169c41b9e"},
- {file = "Brotli-1.1.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5dab0844f2cf82be357a0eb11a9087f70c5430b2c241493fc122bb6f2bb0917c"},
- {file = "Brotli-1.1.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e4fe605b917c70283db7dfe5ada75e04561479075761a0b3866c081d035b01c1"},
- {file = "Brotli-1.1.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:1e9a65b5736232e7a7f91ff3d02277f11d339bf34099a56cdab6a8b3410a02b2"},
- {file = "Brotli-1.1.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:58d4b711689366d4a03ac7957ab8c28890415e267f9b6589969e74b6e42225ec"},
{file = "Brotli-1.1.0-cp310-cp310-win32.whl", hash = "sha256:be36e3d172dc816333f33520154d708a2657ea63762ec16b62ece02ab5e4daf2"},
{file = "Brotli-1.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:0c6244521dda65ea562d5a69b9a26120769b7a9fb3db2fe9545935ed6735b128"},
{file = "Brotli-1.1.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a3daabb76a78f829cafc365531c972016e4aa8d5b4bf60660ad8ecee19df7ccc"},
@@ -432,14 +428,8 @@ files = [
{file = "Brotli-1.1.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:19c116e796420b0cee3da1ccec3b764ed2952ccfcc298b55a10e5610ad7885f9"},
{file = "Brotli-1.1.0-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:510b5b1bfbe20e1a7b3baf5fed9e9451873559a976c1a78eebaa3b86c57b4265"},
{file = "Brotli-1.1.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:a1fd8a29719ccce974d523580987b7f8229aeace506952fa9ce1d53a033873c8"},
- {file = "Brotli-1.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c247dd99d39e0338a604f8c2b3bc7061d5c2e9e2ac7ba9cc1be5a69cb6cd832f"},
- {file = "Brotli-1.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1b2c248cd517c222d89e74669a4adfa5577e06ab68771a529060cf5a156e9757"},
- {file = "Brotli-1.1.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:2a24c50840d89ded6c9a8fdc7b6ed3692ed4e86f1c4a4a938e1e92def92933e0"},
- {file = "Brotli-1.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f31859074d57b4639318523d6ffdca586ace54271a73ad23ad021acd807eb14b"},
{file = "Brotli-1.1.0-cp311-cp311-win32.whl", hash = "sha256:39da8adedf6942d76dc3e46653e52df937a3c4d6d18fdc94a7c29d263b1f5b50"},
{file = "Brotli-1.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:aac0411d20e345dc0920bdec5548e438e999ff68d77564d5e9463a7ca9d3e7b1"},
- {file = "Brotli-1.1.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:32d95b80260d79926f5fab3c41701dbb818fde1c9da590e77e571eefd14abe28"},
- {file = "Brotli-1.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b760c65308ff1e462f65d69c12e4ae085cff3b332d894637f6273a12a482d09f"},
{file = "Brotli-1.1.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:316cc9b17edf613ac76b1f1f305d2a748f1b976b033b049a6ecdfd5612c70409"},
{file = "Brotli-1.1.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:caf9ee9a5775f3111642d33b86237b05808dafcd6268faa492250e9b78046eb2"},
{file = "Brotli-1.1.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:70051525001750221daa10907c77830bc889cb6d865cc0b813d9db7fefc21451"},
@@ -450,24 +440,8 @@ files = [
{file = "Brotli-1.1.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:4093c631e96fdd49e0377a9c167bfd75b6d0bad2ace734c6eb20b348bc3ea180"},
{file = "Brotli-1.1.0-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:7e4c4629ddad63006efa0ef968c8e4751c5868ff0b1c5c40f76524e894c50248"},
{file = "Brotli-1.1.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:861bf317735688269936f755fa136a99d1ed526883859f86e41a5d43c61d8966"},
- {file = "Brotli-1.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:87a3044c3a35055527ac75e419dfa9f4f3667a1e887ee80360589eb8c90aabb9"},
- {file = "Brotli-1.1.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:c5529b34c1c9d937168297f2c1fde7ebe9ebdd5e121297ff9c043bdb2ae3d6fb"},
- {file = "Brotli-1.1.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:ca63e1890ede90b2e4454f9a65135a4d387a4585ff8282bb72964fab893f2111"},
- {file = "Brotli-1.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e79e6520141d792237c70bcd7a3b122d00f2613769ae0cb61c52e89fd3443839"},
{file = "Brotli-1.1.0-cp312-cp312-win32.whl", hash = "sha256:5f4d5ea15c9382135076d2fb28dde923352fe02951e66935a9efaac8f10e81b0"},
{file = "Brotli-1.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:906bc3a79de8c4ae5b86d3d75a8b77e44404b0f4261714306e3ad248d8ab0951"},
- {file = "Brotli-1.1.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8bf32b98b75c13ec7cf774164172683d6e7891088f6316e54425fde1efc276d5"},
- {file = "Brotli-1.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7bc37c4d6b87fb1017ea28c9508b36bbcb0c3d18b4260fcdf08b200c74a6aee8"},
- {file = "Brotli-1.1.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c0ef38c7a7014ffac184db9e04debe495d317cc9c6fb10071f7fefd93100a4f"},
- {file = "Brotli-1.1.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:91d7cc2a76b5567591d12c01f019dd7afce6ba8cba6571187e21e2fc418ae648"},
- {file = "Brotli-1.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a93dde851926f4f2678e704fadeb39e16c35d8baebd5252c9fd94ce8ce68c4a0"},
- {file = "Brotli-1.1.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f0db75f47be8b8abc8d9e31bc7aad0547ca26f24a54e6fd10231d623f183d089"},
- {file = "Brotli-1.1.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6967ced6730aed543b8673008b5a391c3b1076d834ca438bbd70635c73775368"},
- {file = "Brotli-1.1.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:7eedaa5d036d9336c95915035fb57422054014ebdeb6f3b42eac809928e40d0c"},
- {file = "Brotli-1.1.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:d487f5432bf35b60ed625d7e1b448e2dc855422e87469e3f450aa5552b0eb284"},
- {file = "Brotli-1.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:832436e59afb93e1836081a20f324cb185836c617659b07b129141a8426973c7"},
- {file = "Brotli-1.1.0-cp313-cp313-win32.whl", hash = "sha256:43395e90523f9c23a3d5bdf004733246fba087f2948f87ab28015f12359ca6a0"},
- {file = "Brotli-1.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:9011560a466d2eb3f5a6e4929cf4a09be405c64154e12df0dd72713f6500e32b"},
{file = "Brotli-1.1.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:a090ca607cbb6a34b0391776f0cb48062081f5f60ddcce5d11838e67a01928d1"},
{file = "Brotli-1.1.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2de9d02f5bda03d27ede52e8cfe7b865b066fa49258cbab568720aa5be80a47d"},
{file = "Brotli-1.1.0-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2333e30a5e00fe0fe55903c8832e08ee9c3b1382aacf4db26664a16528d51b4b"},
@@ -477,10 +451,6 @@ files = [
{file = "Brotli-1.1.0-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:fd5f17ff8f14003595ab414e45fce13d073e0762394f957182e69035c9f3d7c2"},
{file = "Brotli-1.1.0-cp36-cp36m-musllinux_1_1_ppc64le.whl", hash = "sha256:069a121ac97412d1fe506da790b3e69f52254b9df4eb665cd42460c837193354"},
{file = "Brotli-1.1.0-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:e93dfc1a1165e385cc8239fab7c036fb2cd8093728cbd85097b284d7b99249a2"},
- {file = "Brotli-1.1.0-cp36-cp36m-musllinux_1_2_aarch64.whl", hash = "sha256:aea440a510e14e818e67bfc4027880e2fb500c2ccb20ab21c7a7c8b5b4703d75"},
- {file = "Brotli-1.1.0-cp36-cp36m-musllinux_1_2_i686.whl", hash = "sha256:6974f52a02321b36847cd19d1b8e381bf39939c21efd6ee2fc13a28b0d99348c"},
- {file = "Brotli-1.1.0-cp36-cp36m-musllinux_1_2_ppc64le.whl", hash = "sha256:a7e53012d2853a07a4a79c00643832161a910674a893d296c9f1259859a289d2"},
- {file = "Brotli-1.1.0-cp36-cp36m-musllinux_1_2_x86_64.whl", hash = "sha256:d7702622a8b40c49bffb46e1e3ba2e81268d5c04a34f460978c6b5517a34dd52"},
{file = "Brotli-1.1.0-cp36-cp36m-win32.whl", hash = "sha256:a599669fd7c47233438a56936988a2478685e74854088ef5293802123b5b2460"},
{file = "Brotli-1.1.0-cp36-cp36m-win_amd64.whl", hash = "sha256:d143fd47fad1db3d7c27a1b1d66162e855b5d50a89666af46e1679c496e8e579"},
{file = "Brotli-1.1.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:11d00ed0a83fa22d29bc6b64ef636c4552ebafcef57154b4ddd132f5638fbd1c"},
@@ -492,10 +462,6 @@ files = [
{file = "Brotli-1.1.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:919e32f147ae93a09fe064d77d5ebf4e35502a8df75c29fb05788528e330fe74"},
{file = "Brotli-1.1.0-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:23032ae55523cc7bccb4f6a0bf368cd25ad9bcdcc1990b64a647e7bbcce9cb5b"},
{file = "Brotli-1.1.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:224e57f6eac61cc449f498cc5f0e1725ba2071a3d4f48d5d9dffba42db196438"},
- {file = "Brotli-1.1.0-cp37-cp37m-musllinux_1_2_aarch64.whl", hash = "sha256:cb1dac1770878ade83f2ccdf7d25e494f05c9165f5246b46a621cc849341dc01"},
- {file = "Brotli-1.1.0-cp37-cp37m-musllinux_1_2_i686.whl", hash = "sha256:3ee8a80d67a4334482d9712b8e83ca6b1d9bc7e351931252ebef5d8f7335a547"},
- {file = "Brotli-1.1.0-cp37-cp37m-musllinux_1_2_ppc64le.whl", hash = "sha256:5e55da2c8724191e5b557f8e18943b1b4839b8efc3ef60d65985bcf6f587dd38"},
- {file = "Brotli-1.1.0-cp37-cp37m-musllinux_1_2_x86_64.whl", hash = "sha256:d342778ef319e1026af243ed0a07c97acf3bad33b9f29e7ae6a1f68fd083e90c"},
{file = "Brotli-1.1.0-cp37-cp37m-win32.whl", hash = "sha256:587ca6d3cef6e4e868102672d3bd9dc9698c309ba56d41c2b9c85bbb903cdb95"},
{file = "Brotli-1.1.0-cp37-cp37m-win_amd64.whl", hash = "sha256:2954c1c23f81c2eaf0b0717d9380bd348578a94161a65b3a2afc62c86467dd68"},
{file = "Brotli-1.1.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:efa8b278894b14d6da122a72fefcebc28445f2d3f880ac59d46c90f4c13be9a3"},
@@ -508,10 +474,6 @@ files = [
{file = "Brotli-1.1.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:1ab4fbee0b2d9098c74f3057b2bc055a8bd92ccf02f65944a241b4349229185a"},
{file = "Brotli-1.1.0-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:141bd4d93984070e097521ed07e2575b46f817d08f9fa42b16b9b5f27b5ac088"},
{file = "Brotli-1.1.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:fce1473f3ccc4187f75b4690cfc922628aed4d3dd013d047f95a9b3919a86596"},
- {file = "Brotli-1.1.0-cp38-cp38-musllinux_1_2_aarch64.whl", hash = "sha256:d2b35ca2c7f81d173d2fadc2f4f31e88cc5f7a39ae5b6db5513cf3383b0e0ec7"},
- {file = "Brotli-1.1.0-cp38-cp38-musllinux_1_2_i686.whl", hash = "sha256:af6fa6817889314555aede9a919612b23739395ce767fe7fcbea9a80bf140fe5"},
- {file = "Brotli-1.1.0-cp38-cp38-musllinux_1_2_ppc64le.whl", hash = "sha256:2feb1d960f760a575dbc5ab3b1c00504b24caaf6986e2dc2b01c09c87866a943"},
- {file = "Brotli-1.1.0-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:4410f84b33374409552ac9b6903507cdb31cd30d2501fc5ca13d18f73548444a"},
{file = "Brotli-1.1.0-cp38-cp38-win32.whl", hash = "sha256:db85ecf4e609a48f4b29055f1e144231b90edc90af7481aa731ba2d059226b1b"},
{file = "Brotli-1.1.0-cp38-cp38-win_amd64.whl", hash = "sha256:3d7954194c36e304e1523f55d7042c59dc53ec20dd4e9ea9d151f1b62b4415c0"},
{file = "Brotli-1.1.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:5fb2ce4b8045c78ebbc7b8f3c15062e435d47e7393cc57c25115cfd49883747a"},
@@ -524,10 +486,6 @@ files = [
{file = "Brotli-1.1.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:949f3b7c29912693cee0afcf09acd6ebc04c57af949d9bf77d6101ebb61e388c"},
{file = "Brotli-1.1.0-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:89f4988c7203739d48c6f806f1e87a1d96e0806d44f0fba61dba81392c9e474d"},
{file = "Brotli-1.1.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:de6551e370ef19f8de1807d0a9aa2cdfdce2e85ce88b122fe9f6b2b076837e59"},
- {file = "Brotli-1.1.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:0737ddb3068957cf1b054899b0883830bb1fec522ec76b1098f9b6e0f02d9419"},
- {file = "Brotli-1.1.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:4f3607b129417e111e30637af1b56f24f7a49e64763253bbc275c75fa887d4b2"},
- {file = "Brotli-1.1.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:6c6e0c425f22c1c719c42670d561ad682f7bfeeef918edea971a79ac5252437f"},
- {file = "Brotli-1.1.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:494994f807ba0b92092a163a0a283961369a65f6cbe01e8891132b7a320e61eb"},
{file = "Brotli-1.1.0-cp39-cp39-win32.whl", hash = "sha256:f0d8a7a6b5983c2496e364b969f0e526647a06b075d034f3297dc66f3b360c64"},
{file = "Brotli-1.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:cdad5b9014d83ca68c25d2e9444e28e967ef16e80f6b436918c700c117a85467"},
{file = "Brotli-1.1.0.tar.gz", hash = "sha256:81de08ac11bcb85841e440c13611c00b67d3bf82698314928d0b676362546724"},
@@ -859,6 +817,7 @@ files = [
{file = "cryptography-44.0.0-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:761817a3377ef15ac23cd7834715081791d4ec77f9297ee694ca1ee9c2c7e5eb"},
{file = "cryptography-44.0.0-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:3c672a53c0fb4725a29c303be906d3c1fa99c32f58abe008a82705f9ee96f40b"},
{file = "cryptography-44.0.0-cp37-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:4ac4c9f37eba52cb6fbeaf5b59c152ea976726b865bd4cf87883a7e7006cc543"},
+ {file = "cryptography-44.0.0-cp37-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:60eb32934076fa07e4316b7b2742fa52cbb190b42c2df2863dbc4230a0a9b385"},
{file = "cryptography-44.0.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:ed3534eb1090483c96178fcb0f8893719d96d5274dfde98aa6add34614e97c8e"},
{file = "cryptography-44.0.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f3f6fdfa89ee2d9d496e2c087cebef9d4fcbb0ad63c40e821b39f74bf48d9c5e"},
{file = "cryptography-44.0.0-cp37-abi3-win32.whl", hash = "sha256:eb33480f1bad5b78233b0ad3e1b0be21e8ef1da745d8d2aecbb20671658b9053"},
@@ -869,6 +828,7 @@ files = [
{file = "cryptography-44.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c5eb858beed7835e5ad1faba59e865109f3e52b3783b9ac21e7e47dc5554e289"},
{file = "cryptography-44.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f53c2c87e0fb4b0c00fa9571082a057e37690a8f12233306161c8f4b819960b7"},
{file = "cryptography-44.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:9e6fc8a08e116fb7c7dd1f040074c9d7b51d74a8ea40d4df2fc7aa08b76b9e6c"},
+ {file = "cryptography-44.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9abcc2e083cbe8dde89124a47e5e53ec38751f0d7dfd36801008f316a127d7ba"},
{file = "cryptography-44.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:d2436114e46b36d00f8b72ff57e598978b37399d2786fd39793c36c6d5cb1c64"},
{file = "cryptography-44.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a01956ddfa0a6790d594f5b34fc1bfa6098aca434696a03cfdbe469b8ed79285"},
{file = "cryptography-44.0.0-cp39-abi3-win32.whl", hash = "sha256:eca27345e1214d1b9f9490d200f9db5a874479be914199194e746c893788d417"},
@@ -2019,7 +1979,7 @@ files = [
name = "iniconfig"
version = "2.0.0"
description = "brain-dead simple config-ini parsing"
-optional = true
+optional = false
python-versions = ">=3.7"
files = [
{file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"},
@@ -3739,7 +3699,7 @@ type = ["mypy (>=1.11.2)"]
name = "pluggy"
version = "1.5.0"
description = "plugin and hook calling mechanisms for python"
-optional = true
+optional = false
python-versions = ">=3.8"
files = [
{file = "pluggy-1.5.0-py3-none-any.whl", hash = "sha256:44e1ad92c8ca002de6377e165f3e0f1be63266ab4d554740532335b9d75ea669"},
@@ -3972,7 +3932,6 @@ files = [
{file = "psycopg2-2.9.10-cp311-cp311-win_amd64.whl", hash = "sha256:0435034157049f6846e95103bd8f5a668788dd913a7c30162ca9503fdf542cb4"},
{file = "psycopg2-2.9.10-cp312-cp312-win32.whl", hash = "sha256:65a63d7ab0e067e2cdb3cf266de39663203d38d6a8ed97f5ca0cb315c73fe067"},
{file = "psycopg2-2.9.10-cp312-cp312-win_amd64.whl", hash = "sha256:4a579d6243da40a7b3182e0430493dbd55950c493d8c68f4eec0b302f6bbf20e"},
- {file = "psycopg2-2.9.10-cp313-cp313-win_amd64.whl", hash = "sha256:91fd603a2155da8d0cfcdbf8ab24a2d54bca72795b90d2a3ed2b6da8d979dee2"},
{file = "psycopg2-2.9.10-cp39-cp39-win32.whl", hash = "sha256:9d5b3b94b79a844a986d029eee38998232451119ad653aea42bb9220a8c5066b"},
{file = "psycopg2-2.9.10-cp39-cp39-win_amd64.whl", hash = "sha256:88138c8dedcbfa96408023ea2b0c369eda40fe5d75002c0964c78f46f11fa442"},
{file = "psycopg2-2.9.10.tar.gz", hash = "sha256:12ec0b40b0273f95296233e8750441339298e6a572f7039da5b260e3c8b60e11"},
@@ -4032,7 +3991,6 @@ files = [
{file = "psycopg2_binary-2.9.10-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:bb89f0a835bcfc1d42ccd5f41f04870c1b936d8507c6df12b7737febc40f0909"},
{file = "psycopg2_binary-2.9.10-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:f0c2d907a1e102526dd2986df638343388b94c33860ff3bbe1384130828714b1"},
{file = "psycopg2_binary-2.9.10-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f8157bed2f51db683f31306aa497311b560f2265998122abe1dce6428bd86567"},
- {file = "psycopg2_binary-2.9.10-cp313-cp313-win_amd64.whl", hash = "sha256:27422aa5f11fbcd9b18da48373eb67081243662f9b46e6fd07c3eb46e4535142"},
{file = "psycopg2_binary-2.9.10-cp38-cp38-macosx_12_0_x86_64.whl", hash = "sha256:eb09aa7f9cecb45027683bb55aebaaf45a0df8bf6de68801a6afdc7947bb09d4"},
{file = "psycopg2_binary-2.9.10-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b73d6d7f0ccdad7bc43e6d34273f70d587ef62f824d7261c4ae9b8b1b6af90e8"},
{file = "psycopg2_binary-2.9.10-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ce5ab4bf46a211a8e924d307c1b1fcda82368586a19d0a24f8ae166f5c784864"},
@@ -4421,7 +4379,7 @@ websocket-client = "!=0.49"
name = "pytest"
version = "8.3.4"
description = "pytest: simple powerful testing with Python"
-optional = true
+optional = false
python-versions = ">=3.8"
files = [
{file = "pytest-8.3.4-py3-none-any.whl", hash = "sha256:50e16d954148559c9a74109af1eaf0c945ba2d8f30f0a3d3335edde19788b6f6"},
@@ -4457,6 +4415,23 @@ pytest = ">=7.0.0,<9"
docs = ["sphinx (>=5.3)", "sphinx-rtd-theme (>=1.0)"]
testing = ["coverage (>=6.2)", "hypothesis (>=5.7.1)"]
+[[package]]
+name = "pytest-mock"
+version = "3.14.0"
+description = "Thin-wrapper around the mock package for easier use with pytest"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "pytest-mock-3.14.0.tar.gz", hash = "sha256:2719255a1efeceadbc056d6bf3df3d1c5015530fb40cf347c0f9afac88410bd0"},
+ {file = "pytest_mock-3.14.0-py3-none-any.whl", hash = "sha256:0b72c38033392a5f4621342fe11e9219ac11ec9d375f8e2a0c164539e0d70f6f"},
+]
+
+[package.dependencies]
+pytest = ">=6.2.5"
+
+[package.extras]
+dev = ["pre-commit", "pytest-asyncio", "tox"]
+
[[package]]
name = "pytest-order"
version = "1.3.0"
@@ -6311,4 +6286,4 @@ tests = ["wikipedia"]
[metadata]
lock-version = "2.0"
python-versions = "<3.14,>=3.10"
-content-hash = "01a1e7dc94ef2d8d3a61f1bbc28a1b3237d2dc8f14fe0561ade5d58175cddd42"
+content-hash = "effb82094dcdc8c73c1c3e4277a7d3012f33ff7d8b4cf114f90b55df7f663587"
diff --git a/pyproject.toml b/pyproject.toml
index fe520cd18..51229c774 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,5 +1,6 @@
[tool.poetry]
name = "letta"
+
version = "0.6.13"
packages = [
{include = "letta"},
@@ -80,6 +81,7 @@ anthropic = "^0.43.0"
letta_client = "^0.1.16"
colorama = "^0.4.6"
+
[tool.poetry.extras]
postgres = ["pgvector", "pg8000", "psycopg2-binary", "psycopg2"]
dev = ["pytest", "pytest-asyncio", "pexpect", "black", "pre-commit", "datasets", "pyright", "pytest-order", "autoflake", "isort", "locust"]
@@ -95,6 +97,7 @@ bedrock = ["boto3"]
black = "^24.4.2"
ipykernel = "^6.29.5"
ipdb = "^0.13.13"
+pytest-mock = "^3.14.0"
[tool.black]
line-length = 140
diff --git a/tests/integration_test_summarizer.py b/tests/integration_test_summarizer.py
index b4de0043b..07b0e90a2 100644
--- a/tests/integration_test_summarizer.py
+++ b/tests/integration_test_summarizer.py
@@ -1,6 +1,7 @@
import json
import os
import uuid
+from datetime import datetime
from typing import List
import pytest
@@ -8,9 +9,13 @@ import pytest
from letta import create_client
from letta.agent import Agent
from letta.client.client import LocalClient
+from letta.errors import ContextWindowExceededError
+from letta.llm_api.helpers import calculate_summarizer_cutoff
from letta.schemas.embedding_config import EmbeddingConfig
+from letta.schemas.enums import MessageRole
from letta.schemas.llm_config import LLMConfig
from letta.schemas.message import Message
+from letta.settings import summarizer_settings
from letta.streaming_interface import StreamingRefreshCLIInterface
from tests.helpers.endpoints_helper import EMBEDDING_CONFIG_PATH
from tests.helpers.utils import cleanup
@@ -44,6 +49,101 @@ def agent_state(client):
client.delete_agent(agent_state.id)
+# Sample data setup
+def generate_message(role: str, text: str = None, tool_calls: List = None) -> Message:
+ """Helper to generate a Message object."""
+ return Message(
+ id="message-" + str(uuid.uuid4()),
+ role=MessageRole(role),
+ text=text or f"{role} message text",
+ created_at=datetime.utcnow(),
+ tool_calls=tool_calls or [],
+ )
+
+
+def test_cutoff_calculation(mocker):
+ """Test basic scenarios where the function calculates the cutoff correctly."""
+ # Arrange
+ logger = mocker.Mock() # Mock logger
+ messages = [
+ generate_message("system"),
+ generate_message("user"),
+ generate_message("assistant"),
+ generate_message("user"),
+ generate_message("assistant"),
+ ]
+ mocker.patch("letta.settings.summarizer_settings.desired_memory_token_pressure", 0.5)
+ mocker.patch("letta.settings.summarizer_settings.evict_all_messages", False)
+
+ # Basic tests
+ token_counts = [4, 2, 8, 2, 2]
+ cutoff = calculate_summarizer_cutoff(messages, token_counts, logger)
+ assert cutoff == 3
+ assert messages[cutoff - 1].role == MessageRole.assistant
+
+ token_counts = [4, 2, 2, 2, 2]
+ cutoff = calculate_summarizer_cutoff(messages, token_counts, logger)
+ assert cutoff == 5
+ assert messages[cutoff - 1].role == MessageRole.assistant
+
+ token_counts = [2, 2, 3, 2, 2]
+ cutoff = calculate_summarizer_cutoff(messages, token_counts, logger)
+ assert cutoff == 3
+ assert messages[cutoff - 1].role == MessageRole.assistant
+
+ # Evict all messages
+ # Should give the end of the token_counts, even though it is not necessary (can just evict up to the 100)
+ mocker.patch("letta.settings.summarizer_settings.evict_all_messages", True)
+ token_counts = [1, 1, 100, 1, 1]
+ cutoff = calculate_summarizer_cutoff(messages, token_counts, logger)
+ assert cutoff == 5
+ assert messages[cutoff - 1].role == MessageRole.assistant
+
+ # Don't evict all messages with same token_counts, cutoff now should be at the 100
+ # Should give the end of the token_counts, even though it is not necessary (can just evict up to the 100)
+ mocker.patch("letta.settings.summarizer_settings.evict_all_messages", False)
+ cutoff = calculate_summarizer_cutoff(messages, token_counts, logger)
+ assert cutoff == 3
+ assert messages[cutoff - 1].role == MessageRole.assistant
+
+ # Set `keep_last_n_messages`
+ mocker.patch("letta.settings.summarizer_settings.keep_last_n_messages", 3)
+ token_counts = [4, 2, 2, 2, 2]
+ cutoff = calculate_summarizer_cutoff(messages, token_counts, logger)
+ assert cutoff == 2
+ assert messages[cutoff - 1].role == MessageRole.user
+
+
+def test_summarize_many_messages_basic(client, mock_e2b_api_key_none):
+ small_context_llm_config = LLMConfig.default_config("gpt-4o-mini")
+ small_context_llm_config.context_window = 3000
+ small_agent_state = client.create_agent(
+ name="small_context_agent",
+ llm_config=small_context_llm_config,
+ )
+ for _ in range(10):
+ client.user_message(
+ agent_id=small_agent_state.id,
+ message="hi " * 60,
+ )
+ client.delete_agent(small_agent_state.id)
+
+
+def test_summarize_large_message_does_not_loop_infinitely(client, mock_e2b_api_key_none):
+ small_context_llm_config = LLMConfig.default_config("gpt-4o-mini")
+ small_context_llm_config.context_window = 2000
+ small_agent_state = client.create_agent(
+ name="super_small_context_agent",
+ llm_config=small_context_llm_config,
+ )
+ with pytest.raises(ContextWindowExceededError, match=f"Ran summarizer {summarizer_settings.max_summarizer_retries}"):
+ client.user_message(
+ agent_id=small_agent_state.id,
+ message="hi " * 1000,
+ )
+ client.delete_agent(small_agent_state.id)
+
+
def test_summarize_messages_inplace(client, agent_state, mock_e2b_api_key_none):
"""Test summarization via sending the summarize CLI command or via a direct call to the agent object"""
# First send a few messages (5)
@@ -134,7 +234,7 @@ def test_auto_summarize(client, mock_e2b_api_key_none):
# "gemini-pro.json", TODO: Gemini is broken
],
)
-def test_summarizer(config_filename):
+def test_summarizer(config_filename, client, agent_state):
namespace = uuid.NAMESPACE_DNS
agent_name = str(uuid.uuid5(namespace, f"integration-test-summarizer-{config_filename}"))
@@ -175,6 +275,6 @@ def test_summarizer(config_filename):
)
# Invoke a summarize
- letta_agent.summarize_messages_inplace(preserve_last_N_messages=False)
+ letta_agent.summarize_messages_inplace()
in_context_messages = client.get_in_context_messages(agent_state.id)
assert SUMMARY_KEY_PHRASE in in_context_messages[1].text, f"Test failed for config: {config_filename}"
diff --git a/tests/integration_test_tool_execution_sandbox.py b/tests/integration_test_tool_execution_sandbox.py
index 041c25cc9..8a6e5d9d0 100644
--- a/tests/integration_test_tool_execution_sandbox.py
+++ b/tests/integration_test_tool_execution_sandbox.py
@@ -183,7 +183,15 @@ def list_tool(test_user):
def composio_github_star_tool(test_user):
tool_manager = ToolManager()
tool_create = ToolCreate.from_composio(action_name="GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER")
- tool = tool_manager.create_or_update_tool(pydantic_tool=Tool(**tool_create.model_dump()), actor=test_user)
+ tool = tool_manager.create_or_update_composio_tool(pydantic_tool=Tool(**tool_create.model_dump()), actor=test_user)
+ yield tool
+
+
+def composio_gmail_get_profile_tool(test_user):
+ tool_manager = ToolManager()
+ tool_create = ToolCreate.from_composio(action_name="GMAIL_GET_PROFILE")
+ tool = tool_manager.create_or_update_composio_tool(pydantic_tool=Tool(**tool_create.model_dump()), actor=test_user)
yield tool
diff --git a/tests/test_client.py b/tests/test_client.py
index e1dbd8647..9dbc14684 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -13,7 +13,6 @@ from sqlalchemy import delete
from letta import LocalClient, RESTClient, create_client
from letta.orm import SandboxConfig, SandboxEnvironmentVariable
from letta.schemas.agent import AgentState
-from letta.schemas.block import CreateBlock
from letta.schemas.embedding_config import EmbeddingConfig
from letta.schemas.enums import MessageRole
from letta.schemas.job import JobStatus
@@ -113,46 +112,6 @@ def clear_tables():
session.commit()
-def test_shared_blocks(mock_e2b_api_key_none, client: Union[LocalClient, RESTClient]):
- # _reset_config()
-
- # create a block
- block = client.create_block(label="human", value="username: sarah")
-
- # create agents with shared block
- from letta.schemas.block import Block
- from letta.schemas.memory import BasicBlockMemory
-
- # persona1_block = client.create_block(label="persona", value="you are agent 1")
- # persona2_block = client.create_block(label="persona", value="you are agent 2")
- # create agents
- agent_state1 = client.create_agent(
- name="agent1", memory=BasicBlockMemory([Block(label="persona", value="you are agent 1")]), block_ids=[block.id]
- )
- agent_state2 = client.create_agent(
- name="agent2", memory=BasicBlockMemory([Block(label="persona", value="you are agent 2")]), block_ids=[block.id]
- )
-
- ## attach shared block to both agents
- # client.link_agent_memory_block(agent_state1.id, block.id)
- # client.link_agent_memory_block(agent_state2.id, block.id)
-
- # update memory
- client.user_message(agent_id=agent_state1.id, message="my name is actually charles")
-
- # check agent 2 memory
- assert "charles" in client.get_block(block.id).value.lower(), f"Shared block update failed {client.get_block(block.id).value}"
-
- client.user_message(agent_id=agent_state2.id, message="whats my name?")
- assert (
- "charles" in client.get_core_memory(agent_state2.id).get_block("human").value.lower()
- ), f"Shared block update failed {client.get_core_memory(agent_state2.id).get_block('human').value}"
-
- # cleanup
- client.delete_agent(agent_state1.id)
- client.delete_agent(agent_state2.id)
-
-
def test_sandbox_config_and_env_var_basic(client: Union[LocalClient, RESTClient]):
"""
Test sandbox config and environment variable functions for both LocalClient and RESTClient.
@@ -204,6 +163,11 @@ def test_sandbox_config_and_env_var_basic(client: Union[LocalClient, RESTClient]
client.delete_sandbox_config(sandbox_config_id=sandbox_config.id)
+# --------------------------------------------------------------------------------------------------------------------
+# Agent tags
+# --------------------------------------------------------------------------------------------------------------------
+
+
def test_add_and_manage_tags_for_agent(client: Union[LocalClient, RESTClient]):
"""
Comprehensive happy path test for adding, retrieving, and managing tags on an agent.
@@ -306,6 +270,49 @@ def test_agent_tags(client: Union[LocalClient, RESTClient]):
client.delete_agent(agent3.id)
+# --------------------------------------------------------------------------------------------------------------------
+# Agent memory blocks
+# --------------------------------------------------------------------------------------------------------------------
+def test_shared_blocks(mock_e2b_api_key_none, client: Union[LocalClient, RESTClient]):
+ # _reset_config()
+
+ # create a block
+ block = client.create_block(label="human", value="username: sarah")
+
+ # create agents with shared block
+ from letta.schemas.block import Block
+ from letta.schemas.memory import BasicBlockMemory
+
+ # persona1_block = client.create_block(label="persona", value="you are agent 1")
+ # persona2_block = client.create_block(label="persona", value="you are agent 2")
+ # create agents
+ agent_state1 = client.create_agent(
+ name="agent1", memory=BasicBlockMemory([Block(label="persona", value="you are agent 1")]), block_ids=[block.id]
+ )
+ agent_state2 = client.create_agent(
+ name="agent2", memory=BasicBlockMemory([Block(label="persona", value="you are agent 2")]), block_ids=[block.id]
+ )
+
+ ## attach shared block to both agents
+ # client.link_agent_memory_block(agent_state1.id, block.id)
+ # client.link_agent_memory_block(agent_state2.id, block.id)
+
+ # update memory
+ client.user_message(agent_id=agent_state1.id, message="my name is actually charles")
+
+ # check agent 2 memory
+ assert "charles" in client.get_block(block.id).value.lower(), f"Shared block update failed {client.get_block(block.id).value}"
+
+ client.user_message(agent_id=agent_state2.id, message="whats my name?")
+ assert (
+ "charles" in client.get_core_memory(agent_state2.id).get_block("human").value.lower()
+ ), f"Shared block update failed {client.get_core_memory(agent_state2.id).get_block('human').value}"
+
+ # cleanup
+ client.delete_agent(agent_state1.id)
+ client.delete_agent(agent_state2.id)
+
+
def test_update_agent_memory_label(client: Union[LocalClient, RESTClient], agent: AgentState):
"""Test that we can update the label of a block in an agent's memory"""
@@ -326,38 +333,32 @@ def test_update_agent_memory_label(client: Union[LocalClient, RESTClient], agent
client.delete_agent(agent.id)
-def test_add_remove_agent_memory_block(client: Union[LocalClient, RESTClient], agent: AgentState):
+def test_attach_detach_agent_memory_block(client: Union[LocalClient, RESTClient], agent: AgentState):
"""Test that we can add and remove a block from an agent's memory"""
- agent = client.create_agent(name=create_random_username())
-
- try:
- current_labels = agent.memory.list_block_labels()
- example_new_label = "example_new_label"
- example_new_value = "example value"
- assert example_new_label not in current_labels
-
- # Link a new memory block
- client.add_agent_memory_block(
- agent_id=agent.id,
- create_block=CreateBlock(
- label=example_new_label,
- value=example_new_value,
- limit=1000,
- ),
- )
-
- updated_agent = client.get_agent(agent_id=agent.id)
- assert example_new_label in updated_agent.memory.list_block_labels()
-
- # Now unlink the block
- client.remove_agent_memory_block(agent_id=agent.id, block_label=example_new_label)
-
- updated_agent = client.get_agent(agent_id=agent.id)
- assert example_new_label not in updated_agent.memory.list_block_labels()
+ current_labels = agent.memory.list_block_labels()
+ example_new_label = current_labels[0] + "_v2"
+ example_new_value = "example value"
+ assert example_new_label not in current_labels
+
+ # Link a new memory block
+ block = client.create_block(
+ label=example_new_label,
+ value=example_new_value,
+ limit=1000,
+ )
+ updated_agent = client.attach_block(
+ agent_id=agent.id,
+ block_id=block.id,
+ )
+ assert example_new_label in updated_agent.memory.list_block_labels()
- finally:
- client.delete_agent(agent.id)
+ # Now unlink the block
+ updated_agent = client.detach_block(
+ agent_id=agent.id,
+ block_id=block.id,
+ )
+ assert example_new_label not in updated_agent.memory.list_block_labels()
# def test_core_memory_token_limits(client: Union[LocalClient, RESTClient], agent: AgentState):
@@ -413,24 +414,9 @@ def test_update_agent_memory_limit(client: Union[LocalClient, RESTClient]):
client.delete_agent(agent.id)
-def test_messages(client: Union[LocalClient, RESTClient], agent: AgentState):
- # _reset_config()
-
- send_message_response = client.send_message(agent_id=agent.id, message="Test message", role="user")
- assert send_message_response, "Sending message failed"
-
- messages_response = client.get_messages(agent_id=agent.id, limit=1)
- assert len(messages_response) > 0, "Retrieving messages failed"
-
-
-def test_send_system_message(client: Union[LocalClient, RESTClient], agent: AgentState):
- """Important unit test since the Letta API exposes sending system messages, but some backends don't natively support it (eg Anthropic)"""
- send_system_message_response = client.send_message(
- agent_id=agent.id, message="Event occurred: The user just logged off.", role="system"
- )
- assert send_system_message_response, "Sending message failed"
-
-
+# --------------------------------------------------------------------------------------------------------------------
+# Agent Tools
+# --------------------------------------------------------------------------------------------------------------------
def test_function_return_limit(client: Union[LocalClient, RESTClient]):
"""Test to see if the function return limit works"""
@@ -503,6 +489,70 @@ def test_function_always_error(client: Union[LocalClient, RESTClient]):
client.delete_agent(agent_id=agent.id)
+def test_attach_detach_agent_tool(client: Union[LocalClient, RESTClient], agent: AgentState):
+ """Test that we can attach and detach a tool from an agent"""
+
+ try:
+ # Create a tool
+ def example_tool(x: int) -> int:
+ """
+ This is an example tool.
+
+ Parameters:
+ x (int): The input value.
+
+ Returns:
+ int: The output value.
+ """
+ return x * 2
+
+ tool = client.create_or_update_tool(func=example_tool, name="test_tool")
+
+ # Initially tool should not be attached
+ initial_tools = client.list_attached_tools(agent_id=agent.id)
+ assert tool.id not in [t.id for t in initial_tools]
+
+ # Attach tool
+ new_agent_state = client.attach_tool(agent_id=agent.id, tool_id=tool.id)
+ assert tool.id in [t.id for t in new_agent_state.tools]
+
+ # Verify tool is attached
+ updated_tools = client.list_attached_tools(agent_id=agent.id)
+ assert tool.id in [t.id for t in updated_tools]
+
+ # Detach tool
+ new_agent_state = client.detach_tool(agent_id=agent.id, tool_id=tool.id)
+ assert tool.id not in [t.id for t in new_agent_state.tools]
+
+ # Verify tool is detached
+ final_tools = client.list_attached_tools(agent_id=agent.id)
+ assert tool.id not in [t.id for t in final_tools]
+
+ finally:
+ client.delete_tool(tool.id)
+
+
+# --------------------------------------------------------------------------------------------------------------------
+# AgentMessages
+# --------------------------------------------------------------------------------------------------------------------
+def test_messages(client: Union[LocalClient, RESTClient], agent: AgentState):
+ # _reset_config()
+
+ send_message_response = client.send_message(agent_id=agent.id, message="Test message", role="user")
+ assert send_message_response, "Sending message failed"
+
+ messages_response = client.get_messages(agent_id=agent.id, limit=1)
+ assert len(messages_response) > 0, "Retrieving messages failed"
+
+
+def test_send_system_message(client: Union[LocalClient, RESTClient], agent: AgentState):
+ """Important unit test since the Letta API exposes sending system messages, but some backends don't natively support it (eg Anthropic)"""
+ send_system_message_response = client.send_message(
+ agent_id=agent.id, message="Event occurred: The user just logged off.", role="system"
+ )
+ assert send_system_message_response, "Sending message failed"
+
+
@pytest.mark.asyncio
async def test_send_message_parallel(client: Union[LocalClient, RESTClient], agent: AgentState, request):
"""
@@ -580,9 +630,9 @@ def test_send_message_async(client: Union[LocalClient, RESTClient], agent: Agent
assert usage.total_tokens == usage.completion_tokens + usage.prompt_tokens
-# ==========================================
-# TESTS FOR AGENT LISTING
-# ==========================================
+# ----------------------------------------------------------------------------------------------------
+# Agent listing
+# ----------------------------------------------------------------------------------------------------
def test_agent_listing(client: Union[LocalClient, RESTClient], agent, search_agent_one, search_agent_two):
@@ -678,3 +728,33 @@ def test_agent_creation(client: Union[LocalClient, RESTClient]):
assert all(tool.id in tool_ids for tool in agent_tools)
client.delete_agent(agent_id=agent.id)
+
+
+# --------------------------------------------------------------------------------------------------------------------
+# Agent sources
+# --------------------------------------------------------------------------------------------------------------------
+def test_attach_detach_agent_source(client: Union[LocalClient, RESTClient], agent: AgentState):
+ """Test that we can attach and detach a source from an agent"""
+
+ # Create a source
+ source = client.create_source(
+ name="test_source",
+ )
+ initial_sources = client.list_attached_sources(agent_id=agent.id)
+ assert source.id not in [s.id for s in initial_sources]
+
+ # Attach source
+ client.attach_source(agent_id=agent.id, source_id=source.id)
+
+ # Verify source is attached
+ final_sources = client.list_attached_sources(agent_id=agent.id)
+ assert source.id in [s.id for s in final_sources]
+
+ # Detach source
+ client.detach_source(agent_id=agent.id, source_id=source.id)
+
+ # Verify source is detached
+ final_sources = client.list_attached_sources(agent_id=agent.id)
+ assert source.id not in [s.id for s in final_sources]
+
+ client.delete_source(source.id)
diff --git a/tests/test_client_legacy.py b/tests/test_client_legacy.py
index a7675c682..882c4e7e6 100644
--- a/tests/test_client_legacy.py
+++ b/tests/test_client_legacy.py
@@ -205,9 +205,9 @@ def test_archival_memory(mock_e2b_api_key_none, client: Union[LocalClient, RESTC
passages = client.get_archival_memory(agent.id)
assert passage.text in [p.text for p in passages], f"Missing passage {passage.text} in {passages}"
- # get archival memory summary
- archival_summary = client.get_archival_memory_summary(agent.id)
- assert archival_summary.size == 1, f"Archival memory summary size is {archival_summary.size}"
+ # # get archival memory summary
+ # archival_summary = client.get_agent_archival_memory_summary(agent.id)
+ # assert archival_summary.size == 1, f"Archival memory summary size is {archival_summary.size}"
# delete archival memory
client.delete_archival_memory(agent.id, passage.id)
@@ -500,7 +500,7 @@ def test_sources(client: Union[LocalClient, RESTClient], agent: AgentState):
assert len(archival_memories) == 0
# attach a source
- client.attach_source_to_agent(source_id=source.id, agent_id=agent.id)
+ client.attach_source(source_id=source.id, agent_id=agent.id)
# list attached sources
attached_sources = client.list_attached_sources(agent_id=agent.id)
@@ -521,8 +521,7 @@ def test_sources(client: Union[LocalClient, RESTClient], agent: AgentState):
# detach the source
assert len(client.get_archival_memory(agent_id=agent.id)) > 0, "No archival memory"
- deleted_source = client.detach_source(source_id=source.id, agent_id=agent.id)
- assert deleted_source.id == source.id
+ client.detach_source(source_id=source.id, agent_id=agent.id)
archival_memories = client.get_archival_memory(agent_id=agent.id)
assert len(archival_memories) == 0, f"Failed to detach source: {len(archival_memories)}"
assert source.id not in [s.id for s in client.list_attached_sources(agent.id)]
diff --git a/tests/test_local_client.py b/tests/test_local_client.py
index da5e533c5..f3d6945ef 100644
--- a/tests/test_local_client.py
+++ b/tests/test_local_client.py
@@ -141,7 +141,7 @@ def test_agent_add_remove_tools(client: LocalClient, agent):
curr_num_tools = len(agent_state.tools)
# add both tools to agent in steps
- agent_state = client.add_tool_to_agent(agent_id=agent_state.id, tool_id=github_tool.id)
+ agent_state = client.attach_tool(agent_id=agent_state.id, tool_id=github_tool.id)
# confirm that both tools are in the agent state
# we could access it like agent_state.tools, but will use the client function instead
@@ -153,7 +153,7 @@ def test_agent_add_remove_tools(client: LocalClient, agent):
assert github_tool.name in curr_tool_names
# remove only the github tool
- agent_state = client.remove_tool_from_agent(agent_id=agent_state.id, tool_id=github_tool.id)
+ agent_state = client.detach_tool(agent_id=agent_state.id, tool_id=github_tool.id)
# confirm that only one tool left
curr_tools = client.get_tools_from_agent(agent_state.id)
diff --git a/tests/test_managers.py b/tests/test_managers.py
index 44d54ef18..988547873 100644
--- a/tests/test_managers.py
+++ b/tests/test_managers.py
@@ -56,7 +56,7 @@ from letta.schemas.sandbox_config import E2BSandboxConfig, LocalSandboxConfig, S
from letta.schemas.source import Source as PydanticSource
from letta.schemas.source import SourceUpdate
from letta.schemas.tool import Tool as PydanticTool
-from letta.schemas.tool import ToolUpdate
+from letta.schemas.tool import ToolCreate, ToolUpdate
from letta.schemas.tool_rule import InitToolRule
from letta.schemas.usage import LettaUsageStatistics
from letta.schemas.user import User as PydanticUser
@@ -196,6 +196,13 @@ def print_tool(server: SyncServer, default_user, default_organization):
yield tool
+def composio_github_star_tool(server, default_user):
+ tool_create = ToolCreate.from_composio(action_name="GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER")
+ tool = server.tool_manager.create_or_update_composio_tool(pydantic_tool=PydanticTool(**tool_create.model_dump()), actor=default_user)
+ yield tool
+
+
@pytest.fixture
def default_job(server: SyncServer, default_user):
"""Fixture to create and return a default job."""
@@ -1549,6 +1556,14 @@ def test_create_tool(server: SyncServer, print_tool, default_user, default_organ
# Assertions to ensure the created tool matches the expected values
assert print_tool.created_by_id == default_user.id
assert print_tool.organization_id == default_organization.id
+ assert print_tool.tool_type == ToolType.CUSTOM
+
+
+def test_create_composio_tool(server: SyncServer, composio_github_star_tool, default_user, default_organization):
+ # Assertions to ensure the created tool matches the expected values
+ assert composio_github_star_tool.created_by_id == default_user.id
+ assert composio_github_star_tool.organization_id == default_organization.id
+ assert composio_github_star_tool.tool_type == ToolType.EXTERNAL_COMPOSIO
@pytest.mark.skipif(USING_SQLITE, reason="Test not applicable when using SQLite.")
diff --git a/tests/test_tool_schema_parsing.py b/tests/test_tool_schema_parsing.py
index fd35be5f2..627302ed5 100644
--- a/tests/test_tool_schema_parsing.py
+++ b/tests/test_tool_schema_parsing.py
@@ -136,7 +136,7 @@ def _openai_payload(model: str, schema: dict, structured_output: bool):
"parallel_tool_calls": False,
}
- print("Request:\n", json.dumps(data, indent=2))
+ print("Request:\n", json.dumps(data, indent=2), "\n\n")
try:
make_post_request(url, headers, data)
@@ -187,28 +187,21 @@ def test_composio_tool_schema_generation(openai_model: str, structured_output: b
if not os.getenv("COMPOSIO_API_KEY"):
pytest.skip("COMPOSIO_API_KEY not set")
- try:
- import composio
- except ImportError:
- pytest.skip("Composio not installed")
-
for action_name in [
+ "GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER", # Simple
"CAL_GET_AVAILABLE_SLOTS_INFO", # has an array arg, needs to be converted properly
+ "SALESFORCE_RETRIEVE_LEAD_DETAILS_BY_ID_WITH_CONDITIONAL_SUPPORT", # has an array arg, needs to be converted properly
]:
- try:
- tool_create = ToolCreate.from_composio(action_name=action_name)
- except composio.exceptions.ComposioSDKError:
- # e.g. "composio.exceptions.ComposioSDKError: No connected account found for app `CAL`; Run `composio add cal` to fix this"
- pytest.skip(f"Composio account not configured to use action_name {action_name}")
-
- print(tool_create)
+ tool_create = ToolCreate.from_composio(action_name=action_name)
assert tool_create.json_schema
schema = tool_create.json_schema
+ print(f"The schema for {action_name}: {json.dumps(schema, indent=4)}\n\n")
try:
_openai_payload(openai_model, schema, structured_output)
- print(f"Successfully called OpenAI using schema {schema} generated from {action_name}")
+ print(f"Successfully called OpenAI using schema {schema} generated from {action_name}\n\n")
except:
- print(f"Failed to call OpenAI using schema {schema} generated from {action_name}")
+ print(f"Failed to call OpenAI using schema {schema} generated from {action_name}\n\n")
+
raise
diff --git a/tests/test_v1_routes.py b/tests/test_v1_routes.py
index 0dbb2bdb0..6bea63967 100644
--- a/tests/test_v1_routes.py
+++ b/tests/test_v1_routes.py
@@ -296,7 +296,7 @@ def test_add_composio_tool(client, mock_sync_server, add_integers_tool):
)
# Mock server behavior
- mock_sync_server.tool_manager.create_or_update_tool.return_value = add_integers_tool
+ mock_sync_server.tool_manager.create_or_update_composio_tool.return_value = add_integers_tool
# Perform the request
response = client.post(f"/v1/tools/composio/{add_integers_tool.name}", headers={"user_id": "test_user"})
@@ -304,10 +304,10 @@ def test_add_composio_tool(client, mock_sync_server, add_integers_tool):
# Assertions
assert response.status_code == 200
assert response.json()["id"] == add_integers_tool.id
- mock_sync_server.tool_manager.create_or_update_tool.assert_called_once()
+ mock_sync_server.tool_manager.create_or_update_composio_tool.assert_called_once()
# Verify the mocked from_composio method was called
- mock_from_composio.assert_called_once_with(action_name=add_integers_tool.name, api_key="mock_composio_api_key")
+ mock_from_composio.assert_called_once_with(action_name=add_integers_tool.name)
# ======================================================================================================================