Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: Implement search files (#2645)
Matthew Zhou8ae9f6369b4f
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.pyindex 41bc5b35b..4cb0af6a8 100644--- a/letta/services/agent_manager.py+++ b/letta/services/agent_manager.py@@ -3,9 +3,8 @@ import osfrom datetime import datetime, timezonefrom typing import Dict, List, Optional, Set, Tuple-import numpy as npimport sqlalchemy as sa-from sqlalchemy import Select, and_, delete, func, insert, literal, or_, select, union_all+from sqlalchemy import delete, func, insert, literal, or_, selectfrom sqlalchemy.dialects.postgresql import insert as pg_insertfrom letta.constants import (@@ -17,10 +16,8 @@ from letta.constants import (BASE_VOICE_SLEEPTIME_CHAT_TOOLS,BASE_VOICE_SLEEPTIME_TOOLS,DATA_SOURCE_ATTACH_ALERT,- MAX_EMBEDDING_DIM,MULTI_AGENT_TOOLS,)-from letta.embeddings import embedding_modelfrom letta.helpers.datetime_helpers import get_utc_timefrom letta.llm_api.llm_client import LLMClientfrom letta.log import get_logger@@ -39,7 +36,6 @@ from letta.orm.errors import NoResultFoundfrom letta.orm.sandbox_config import AgentEnvironmentVariablefrom letta.orm.sandbox_config import AgentEnvironmentVariable as AgentEnvironmentVariableModelfrom letta.orm.sqlalchemy_base import AccessType-from letta.orm.sqlite_functions import adapt_arrayfrom letta.schemas.agent import AgentState as PydanticAgentStatefrom letta.schemas.agent import AgentType, CreateAgent, UpdateAgent, get_prompt_template_for_agent_typefrom letta.schemas.block import DEFAULT_BLOCKS@@ -74,6 +70,9 @@ from letta.services.helpers.agent_manager_helper import (_apply_tag_filter,_process_relationship,_process_relationship_async,+ build_agent_passage_query,+ build_passage_query,+ build_source_passage_query,check_supports_structured_output,compile_system_message,derive_system_message,@@ -85,7 +84,6 @@ from letta.services.message_manager import MessageManagerfrom letta.services.passage_manager import PassageManagerfrom letta.services.source_manager import SourceManagerfrom letta.services.tool_manager import ToolManager-from letta.settings import settingsfrom letta.tracing import trace_methodfrom letta.utils import enforce_types, united_diff@@ -2016,184 +2014,6 @@ class AgentManager:# ======================================================================================================================# Passage Management# ======================================================================================================================- def _build_passage_query(- self,- actor: PydanticUser,- agent_id: Optional[str] = None,- file_id: Optional[str] = None,- query_text: Optional[str] = None,- start_date: Optional[datetime] = None,- end_date: Optional[datetime] = None,- before: Optional[str] = None,- after: Optional[str] = None,- source_id: Optional[str] = None,- embed_query: bool = False,- ascending: bool = True,- embedding_config: Optional[EmbeddingConfig] = None,- agent_only: bool = False,- ) -> Select:- """Helper function to build the base passage query with all filters applied.- Supports both before and after pagination across merged source and agent passages.-- Returns the query before any limit or count operations are applied.- """- embedded_text = None- if embed_query:- assert embedding_config is not None, "embedding_config must be specified for vector search"- assert query_text is not None, "query_text must be specified for vector search"- embedded_text = embedding_model(embedding_config).get_text_embedding(query_text)- embedded_text = np.array(embedded_text)- embedded_text = np.pad(embedded_text, (0, MAX_EMBEDDING_DIM - embedded_text.shape[0]), mode="constant").tolist()-- # Start with base query for source passages- source_passages = None- if not agent_only: # Include source passages- if agent_id is not None:- source_passages = (- select(SourcePassage, literal(None).label("agent_id"))- .join(SourcesAgents, SourcesAgents.source_id == SourcePassage.source_id)- .where(SourcesAgents.agent_id == agent_id)- .where(SourcePassage.organization_id == actor.organization_id)- )- else:- source_passages = select(SourcePassage, literal(None).label("agent_id")).where(- SourcePassage.organization_id == actor.organization_id- )-- if source_id:- source_passages = source_passages.where(SourcePassage.source_id == source_id)- if file_id:- source_passages = source_passages.where(SourcePassage.file_id == file_id)-- # Add agent passages query- agent_passages = None- if agent_id is not None:- agent_passages = (- select(- AgentPassage.id,- AgentPassage.text,- AgentPassage.embedding_config,- AgentPassage.metadata_,- AgentPassage.embedding,- AgentPassage.created_at,- AgentPassage.updated_at,- AgentPassage.is_deleted,- AgentPassage._created_by_id,- AgentPassage._last_updated_by_id,- AgentPassage.organization_id,- literal(None).label("file_id"),- literal(None).label("source_id"),- AgentPassage.agent_id,- )- .where(AgentPassage.agent_id == agent_id)- .where(AgentPassage.organization_id == actor.organization_id)- )-- # Combine queries- if source_passages is not None and agent_passages is not None:- combined_query = union_all(source_passages, agent_passages).cte("combined_passages")- elif agent_passages is not None:- combined_query = agent_passages.cte("combined_passages")- elif source_passages is not None:- combined_query = source_passages.cte("combined_passages")- else:- raise ValueError("No passages found")-- # Build main query from combined CTE- main_query = select(combined_query)-- # Apply filters- if start_date:- main_query = main_query.where(combined_query.c.created_at >= start_date)- if end_date:- main_query = main_query.where(combined_query.c.created_at <= end_date)- if source_id:- main_query = main_query.where(combined_query.c.source_id == source_id)- if file_id:- main_query = main_query.where(combined_query.c.file_id == file_id)-- # Vector search- if embedded_text:- if settings.letta_pg_uri_no_default:- # PostgreSQL with pgvector- main_query = main_query.order_by(combined_query.c.embedding.cosine_distance(embedded_text).asc())- else:- # SQLite with custom vector type- query_embedding_binary = adapt_array(embedded_text)- main_query = main_query.order_by(- func.cosine_distance(combined_query.c.embedding, query_embedding_binary).asc(),- combined_query.c.created_at.asc() if ascending else combined_query.c.created_at.desc(),- combined_query.c.id.asc(),- )- else:- if query_text:- main_query = main_query.where(func.lower(combined_query.c.text).contains(func.lower(query_text)))-- # Handle pagination- if before or after:- # Create reference CTEs- if before:- before_ref = select(combined_query.c.created_at, combined_query.c.id).where(combined_query.c.id == before).cte("before_ref")- if after:- after_ref = select(combined_query.c.created_at, combined_query.c.id).where(combined_query.c.id == after).cte("after_ref")-- if before and after:- # Window-based query (get records between before and after)- main_query = main_query.where(- or_(- combined_query.c.created_at < select(before_ref.c.created_at).scalar_subquery(),- and_(- combined_query.c.created_at == select(before_ref.c.created_at).scalar_subquery(),- combined_query.c.id < select(before_ref.c.id).scalar_subquery(),- ),- )- )- main_query = main_query.where(- or_(- combined_query.c.created_at > select(after_ref.c.created_at).scalar_subquery(),- and_(- combined_query.c.created_at == select(after_ref.c.created_at).scalar_subquery(),- combined_query.c.id > select(after_ref.c.id).scalar_subquery(),- ),- )- )- else:- # Pure pagination (only before or only after)- if before:- main_query = main_query.where(- or_(- combined_query.c.created_at < select(before_ref.c.created_at).scalar_subquery(),- and_(- combined_query.c.created_at == select(before_ref.c.created_at).scalar_subquery(),- combined_query.c.id < select(before_ref.c.id).scalar_subquery(),- ),- )- )- if after:- main_query = main_query.where(- or_(- combined_query.c.created_at > select(after_ref.c.created_at).scalar_subquery(),- and_(- combined_query.c.created_at == select(after_ref.c.created_at).scalar_subquery(),- combined_query.c.id > select(after_ref.c.id).scalar_subquery(),- ),- )- )-- # Add ordering if not already ordered by similarity- if not embed_query:- if ascending:- main_query = main_query.order_by(- combined_query.c.created_at.asc(),- combined_query.c.id.asc(),- )- else:- main_query = main_query.order_by(- combined_query.c.created_at.desc(),- combined_query.c.id.asc(),- )-- return main_query@trace_method@enforce_types@@ -2216,7 +2036,7 @@ class AgentManager:) -> List[PydanticPassage]:"""Lists all passages attached to an agent."""with db_registry.session() as session:- main_query = self._build_passage_query(+ main_query = build_passage_query(actor=actor,agent_id=agent_id,file_id=file_id,@@ -2276,7 +2096,7 @@ class AgentManager:) -> List[PydanticPassage]:"""Lists all passages attached to an agent."""async with db_registry.async_session() as session:- main_query = self._build_passage_query(+ main_query = build_passage_query(actor=actor,agent_id=agent_id,file_id=file_id,@@ -2315,6 +2135,100 @@ class AgentManager:return [p.to_pydantic() for p in passages]+ @trace_method+ @enforce_types+ async def list_source_passages_async(+ self,+ actor: PydanticUser,+ agent_id: Optional[str] = None,+ file_id: Optional[str] = None,+ limit: Optional[int] = 50,+ query_text: Optional[str] = None,+ start_date: Optional[datetime] = None,+ end_date: Optional[datetime] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,+ source_id: Optional[str] = None,+ embed_query: bool = False,+ ascending: bool = True,+ embedding_config: Optional[EmbeddingConfig] = None,+ ) -> List[PydanticPassage]:+ """Lists all passages attached to an agent."""+ async with db_registry.async_session() as session:+ main_query = build_source_passage_query(+ actor=actor,+ agent_id=agent_id,+ file_id=file_id,+ query_text=query_text,+ start_date=start_date,+ end_date=end_date,+ before=before,+ after=after,+ source_id=source_id,+ embed_query=embed_query,+ ascending=ascending,+ embedding_config=embedding_config,+ )++ # Add limit+ if limit:+ main_query = main_query.limit(limit)++ # Execute query+ result = await session.execute(main_query)++ # Get ORM objects directly using scalars()+ passages = result.scalars().all()++ # Convert to Pydantic models+ return [p.to_pydantic() for p in passages]++ @trace_method+ @enforce_types+ async def list_agent_passages_async(+ self,+ actor: PydanticUser,+ agent_id: Optional[str] = None,+ file_id: Optional[str] = None,+ limit: Optional[int] = 50,+ query_text: Optional[str] = None,+ start_date: Optional[datetime] = None,+ end_date: Optional[datetime] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,+ source_id: Optional[str] = None,+ embed_query: bool = False,+ ascending: bool = True,+ embedding_config: Optional[EmbeddingConfig] = None,+ ) -> List[PydanticPassage]:+ """Lists all passages attached to an agent."""+ async with db_registry.async_session() as session:+ main_query = build_agent_passage_query(+ actor=actor,+ agent_id=agent_id,+ query_text=query_text,+ start_date=start_date,+ end_date=end_date,+ before=before,+ after=after,+ embed_query=embed_query,+ ascending=ascending,+ embedding_config=embedding_config,+ )++ # Add limit+ if limit:+ main_query = main_query.limit(limit)++ # Execute query+ result = await session.execute(main_query)++ # Get ORM objects directly using scalars()+ passages = result.scalars().all()++ # Convert to Pydantic models+ return [p.to_pydantic() for p in passages]+@trace_method@enforce_typesdef passage_size(@@ -2335,7 +2249,7 @@ class AgentManager:) -> int:"""Returns the count of passages matching the given criteria."""with db_registry.session() as session:- main_query = self._build_passage_query(+ main_query = build_passage_query(actor=actor,agent_id=agent_id,file_id=file_id,@@ -2373,7 +2287,7 @@ class AgentManager:agent_only: bool = False,) -> int:async with db_registry.async_session() as session:- main_query = self._build_passage_query(+ main_query = build_passage_query(actor=actor,agent_id=agent_id,file_id=file_id,diff --git a/letta/services/helpers/agent_manager_helper.py b/letta/services/helpers/agent_manager_helper.pyindex 7c1429ade..3513a89ba 100644--- a/letta/services/helpers/agent_manager_helper.py+++ b/letta/services/helpers/agent_manager_helper.py@@ -1,25 +1,31 @@import datetimefrom typing import List, Literal, Optional-from sqlalchemy import and_, asc, desc, or_, select+import numpy as np+from sqlalchemy import Select, and_, asc, desc, func, literal, or_, select, union_allfrom sqlalchemy.sql.expression import existsfrom letta import system-from letta.constants import IN_CONTEXT_MEMORY_KEYWORD, STRUCTURED_OUTPUT_MODELS+from letta.constants import IN_CONTEXT_MEMORY_KEYWORD, MAX_EMBEDDING_DIM, STRUCTURED_OUTPUT_MODELS+from letta.embeddings import embedding_modelfrom letta.helpers import ToolRulesSolverfrom letta.helpers.datetime_helpers import get_local_time, get_local_time_fast+from letta.orm import AgentPassage, SourcePassage, SourcesAgentsfrom letta.orm.agent import Agent as AgentModelfrom letta.orm.agents_tags import AgentsTagsfrom letta.orm.errors import NoResultFoundfrom letta.orm.identity import Identity+from letta.orm.sqlite_functions import adapt_arrayfrom letta.prompts import gpt_systemfrom letta.schemas.agent import AgentState, AgentType+from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.enums import MessageRolefrom letta.schemas.letta_message_content import TextContentfrom letta.schemas.memory import Memoryfrom letta.schemas.message import Message, MessageCreatefrom letta.schemas.tool_rule import ToolRulefrom letta.schemas.user import User+from letta.settings import settingsfrom letta.system import get_initial_boot_messages, get_login_event, package_function_responsefrom letta.tracing import trace_method@@ -566,3 +572,367 @@ def _apply_filters(if base_template_id:query = query.where(AgentModel.base_template_id == base_template_id)return query+++def build_passage_query(+ actor: User,+ agent_id: Optional[str] = None,+ file_id: Optional[str] = None,+ query_text: Optional[str] = None,+ start_date: Optional[datetime] = None,+ end_date: Optional[datetime] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,+ source_id: Optional[str] = None,+ embed_query: bool = False,+ ascending: bool = True,+ embedding_config: Optional[EmbeddingConfig] = None,+ agent_only: bool = False,+) -> Select:+ """Helper function to build the base passage query with all filters applied.+ Supports both before and after pagination across merged source and agent passages.++ Returns the query before any limit or count operations are applied.+ """+ embedded_text = None+ if embed_query:+ assert embedding_config is not None, "embedding_config must be specified for vector search"+ assert query_text is not None, "query_text must be specified for vector search"+ embedded_text = embedding_model(embedding_config).get_text_embedding(query_text)+ embedded_text = np.array(embedded_text)+ embedded_text = np.pad(embedded_text, (0, MAX_EMBEDDING_DIM - embedded_text.shape[0]), mode="constant").tolist()++ # Start with base query for source passages+ source_passages = None+ if not agent_only: # Include source passages+ if agent_id is not None:+ source_passages = (+ select(SourcePassage, literal(None).label("agent_id"))+ .join(SourcesAgents, SourcesAgents.source_id == SourcePassage.source_id)+ .where(SourcesAgents.agent_id == agent_id)+ .where(SourcePassage.organization_id == actor.organization_id)+ )+ else:+ source_passages = select(SourcePassage, literal(None).label("agent_id")).where(+ SourcePassage.organization_id == actor.organization_id+ )++ if source_id:+ source_passages = source_passages.where(SourcePassage.source_id == source_id)+ if file_id:+ source_passages = source_passages.where(SourcePassage.file_id == file_id)++ # Add agent passages query+ agent_passages = None+ if agent_id is not None:+ agent_passages = (+ select(+ AgentPassage.id,+ AgentPassage.text,+ AgentPassage.embedding_config,+ AgentPassage.metadata_,+ AgentPassage.embedding,+ AgentPassage.created_at,+ AgentPassage.updated_at,+ AgentPassage.is_deleted,+ AgentPassage._created_by_id,+ AgentPassage._last_updated_by_id,+ AgentPassage.organization_id,+ literal(None).label("file_id"),+ literal(None).label("source_id"),+ AgentPassage.agent_id,+ )+ .where(AgentPassage.agent_id == agent_id)+ .where(AgentPassage.organization_id == actor.organization_id)+ )++ # Combine queries+ if source_passages is not None and agent_passages is not None:+ combined_query = union_all(source_passages, agent_passages).cte("combined_passages")+ elif agent_passages is not None:+ combined_query = agent_passages.cte("combined_passages")+ elif source_passages is not None:+ combined_query = source_passages.cte("combined_passages")+ else:+ raise ValueError("No passages found")++ # Build main query from combined CTE+ main_query = select(combined_query)++ # Apply filters+ if start_date:+ main_query = main_query.where(combined_query.c.created_at >= start_date)+ if end_date:+ main_query = main_query.where(combined_query.c.created_at <= end_date)+ if source_id:+ main_query = main_query.where(combined_query.c.source_id == source_id)+ if file_id:+ main_query = main_query.where(combined_query.c.file_id == file_id)++ # Vector search+ if embedded_text:+ if settings.letta_pg_uri_no_default:+ # PostgreSQL with pgvector+ main_query = main_query.order_by(combined_query.c.embedding.cosine_distance(embedded_text).asc())+ else:+ # SQLite with custom vector type+ query_embedding_binary = adapt_array(embedded_text)+ main_query = main_query.order_by(+ func.cosine_distance(combined_query.c.embedding, query_embedding_binary).asc(),+ combined_query.c.created_at.asc() if ascending else combined_query.c.created_at.desc(),+ combined_query.c.id.asc(),+ )+ else:+ if query_text:+ main_query = main_query.where(func.lower(combined_query.c.text).contains(func.lower(query_text)))++ # Handle pagination+ if before or after:+ # Create reference CTEs+ if before:+ before_ref = select(combined_query.c.created_at, combined_query.c.id).where(combined_query.c.id == before).cte("before_ref")+ if after:+ after_ref = select(combined_query.c.created_at, combined_query.c.id).where(combined_query.c.id == after).cte("after_ref")++ if before and after:+ # Window-based query (get records between before and after)+ main_query = main_query.where(+ or_(+ combined_query.c.created_at < select(before_ref.c.created_at).scalar_subquery(),+ and_(+ combined_query.c.created_at == select(before_ref.c.created_at).scalar_subquery(),+ combined_query.c.id < select(before_ref.c.id).scalar_subquery(),+ ),+ )+ )+ main_query = main_query.where(+ or_(+ combined_query.c.created_at > select(after_ref.c.created_at).scalar_subquery(),+ and_(+ combined_query.c.created_at == select(after_ref.c.created_at).scalar_subquery(),+ combined_query.c.id > select(after_ref.c.id).scalar_subquery(),+ ),+ )+ )+ else:+ # Pure pagination (only before or only after)+ if before:+ main_query = main_query.where(+ or_(+ combined_query.c.created_at < select(before_ref.c.created_at).scalar_subquery(),+ and_(+ combined_query.c.created_at == select(before_ref.c.created_at).scalar_subquery(),+ combined_query.c.id < select(before_ref.c.id).scalar_subquery(),+ ),+ )+ )+ if after:+ main_query = main_query.where(+ or_(+ combined_query.c.created_at > select(after_ref.c.created_at).scalar_subquery(),+ and_(+ combined_query.c.created_at == select(after_ref.c.created_at).scalar_subquery(),+ combined_query.c.id > select(after_ref.c.id).scalar_subquery(),+ ),+ )+ )++ # Add ordering if not already ordered by similarity+ if not embed_query:+ if ascending:+ main_query = main_query.order_by(+ combined_query.c.created_at.asc(),+ combined_query.c.id.asc(),+ )+ else:+ main_query = main_query.order_by(+ combined_query.c.created_at.desc(),+ combined_query.c.id.asc(),+ )++ return main_query+++def build_source_passage_query(+ actor: User,+ agent_id: Optional[str] = None,+ file_id: Optional[str] = None,+ query_text: Optional[str] = None,+ start_date: Optional[datetime] = None,+ end_date: Optional[datetime] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,+ source_id: Optional[str] = None,+ embed_query: bool = False,+ ascending: bool = True,+ embedding_config: Optional[EmbeddingConfig] = None,+) -> Select:+ """Build query for source passages with all filters applied."""++ # Handle embedding for vector search+ embedded_text = None+ if embed_query:+ assert embedding_config is not None, "embedding_config must be specified for vector search"+ assert query_text is not None, "query_text must be specified for vector search"+ embedded_text = embedding_model(embedding_config).get_text_embedding(query_text)+ embedded_text = np.array(embedded_text)+ embedded_text = np.pad(embedded_text, (0, MAX_EMBEDDING_DIM - embedded_text.shape[0]), mode="constant").tolist()++ # Base query for source passages+ query = select(SourcePassage).where(SourcePassage.organization_id == actor.organization_id)++ # If agent_id is specified, join with SourcesAgents to get only passages linked to that agent+ if agent_id is not None:+ query = query.join(SourcesAgents, SourcesAgents.source_id == SourcePassage.source_id)+ query = query.where(SourcesAgents.agent_id == agent_id)++ # Apply filters+ if source_id:+ query = query.where(SourcePassage.source_id == source_id)+ if file_id:+ query = query.where(SourcePassage.file_id == file_id)+ if start_date:+ query = query.where(SourcePassage.created_at >= start_date)+ if end_date:+ query = query.where(SourcePassage.created_at <= end_date)++ # Handle text search or vector search+ if embedded_text:+ if settings.letta_pg_uri_no_default:+ # PostgreSQL with pgvector+ query = query.order_by(SourcePassage.embedding.cosine_distance(embedded_text).asc())+ else:+ # SQLite with custom vector type+ query_embedding_binary = adapt_array(embedded_text)+ query = query.order_by(+ func.cosine_distance(SourcePassage.embedding, query_embedding_binary).asc(),+ SourcePassage.created_at.asc() if ascending else SourcePassage.created_at.desc(),+ SourcePassage.id.asc(),+ )+ else:+ if query_text:+ query = query.where(func.lower(SourcePassage.text).contains(func.lower(query_text)))++ # Handle pagination+ if before or after:+ if before:+ # Get the reference record+ before_subq = select(SourcePassage.created_at, SourcePassage.id).where(SourcePassage.id == before).subquery()+ query = query.where(+ or_(+ SourcePassage.created_at < before_subq.c.created_at,+ and_(+ SourcePassage.created_at == before_subq.c.created_at,+ SourcePassage.id < before_subq.c.id,+ ),+ )+ )++ if after:+ # Get the reference record+ after_subq = select(SourcePassage.created_at, SourcePassage.id).where(SourcePassage.id == after).subquery()+ query = query.where(+ or_(+ SourcePassage.created_at > after_subq.c.created_at,+ and_(+ SourcePassage.created_at == after_subq.c.created_at,+ SourcePassage.id > after_subq.c.id,+ ),+ )+ )++ # Apply ordering if not already ordered by similarity+ if not embed_query:+ if ascending:+ query = query.order_by(SourcePassage.created_at.asc(), SourcePassage.id.asc())+ else:+ query = query.order_by(SourcePassage.created_at.desc(), SourcePassage.id.asc())++ return query+++def build_agent_passage_query(+ actor: User,+ agent_id: str, # Required for agent passages+ query_text: Optional[str] = None,+ start_date: Optional[datetime] = None,+ end_date: Optional[datetime] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,+ embed_query: bool = False,+ ascending: bool = True,+ embedding_config: Optional[EmbeddingConfig] = None,+) -> Select:+ """Build query for agent passages with all filters applied."""++ # Handle embedding for vector search+ embedded_text = None+ if embed_query:+ assert embedding_config is not None, "embedding_config must be specified for vector search"+ assert query_text is not None, "query_text must be specified for vector search"+ embedded_text = embedding_model(embedding_config).get_text_embedding(query_text)+ embedded_text = np.array(embedded_text)+ embedded_text = np.pad(embedded_text, (0, MAX_EMBEDDING_DIM - embedded_text.shape[0]), mode="constant").tolist()++ # Base query for agent passages+ query = select(AgentPassage).where(AgentPassage.agent_id == agent_id, AgentPassage.organization_id == actor.organization_id)++ # Apply filters+ if start_date:+ query = query.where(AgentPassage.created_at >= start_date)+ if end_date:+ query = query.where(AgentPassage.created_at <= end_date)++ # Handle text search or vector search+ if embedded_text:+ if settings.letta_pg_uri_no_default:+ # PostgreSQL with pgvector+ query = query.order_by(AgentPassage.embedding.cosine_distance(embedded_text).asc())+ else:+ # SQLite with custom vector type+ query_embedding_binary = adapt_array(embedded_text)+ query = query.order_by(+ func.cosine_distance(AgentPassage.embedding, query_embedding_binary).asc(),+ AgentPassage.created_at.asc() if ascending else AgentPassage.created_at.desc(),+ AgentPassage.id.asc(),+ )+ else:+ if query_text:+ query = query.where(func.lower(AgentPassage.text).contains(func.lower(query_text)))++ # Handle pagination+ if before or after:+ if before:+ # Get the reference record+ before_subq = select(AgentPassage.created_at, AgentPassage.id).where(AgentPassage.id == before).subquery()+ query = query.where(+ or_(+ AgentPassage.created_at < before_subq.c.created_at,+ and_(+ AgentPassage.created_at == before_subq.c.created_at,+ AgentPassage.id < before_subq.c.id,+ ),+ )+ )++ if after:+ # Get the reference record+ after_subq = select(AgentPassage.created_at, AgentPassage.id).where(AgentPassage.id == after).subquery()+ query = query.where(+ or_(+ AgentPassage.created_at > after_subq.c.created_at,+ and_(+ AgentPassage.created_at == after_subq.c.created_at,+ AgentPassage.id > after_subq.c.id,+ ),+ )+ )++ # Apply ordering if not already ordered by similarity+ if not embed_query:+ if ascending:+ query = query.order_by(AgentPassage.created_at.asc(), AgentPassage.id.asc())+ else:+ query = query.order_by(AgentPassage.created_at.desc(), AgentPassage.id.asc())++ return querydiff --git a/letta/services/tool_executor/files_tool_executor.py b/letta/services/tool_executor/files_tool_executor.pyindex ec3ab6b50..b88a496e4 100644--- a/letta/services/tool_executor/files_tool_executor.py+++ b/letta/services/tool_executor/files_tool_executor.py@@ -125,6 +125,8 @@ class LettaFileToolExecutor(ToolExecutor):"""Stub for grep tool."""raise NotImplementedError- async def search_files(self, agent_state: AgentState, query: str) -> List[Any]:+ # TODO: Make this paginated?+ async def search_files(self, agent_state: AgentState, query: str) -> List[str]:"""Stub for search_files tool."""- raise NotImplementedError+ passages = await self.agent_manager.list_source_passages_async(actor=self.actor, agent_id=agent_state.id, query_text=query)+ return [p.text for p in passages]diff --git a/tests/test_managers.py b/tests/test_managers.pyindex 7ed9eaa55..f861be837 100644--- a/tests/test_managers.py+++ b/tests/test_managers.py@@ -1909,6 +1909,12 @@ async def test_agent_list_passages_basic(server, default_user, sarah_agent, agenall_passages = await server.agent_manager.list_passages_async(actor=default_user, agent_id=sarah_agent.id)assert len(all_passages) == 5 # 3 source + 2 agent passages+ source_passages = await server.agent_manager.list_source_passages_async(actor=default_user, agent_id=sarah_agent.id)+ assert len(source_passages) == 3 # 3 source + 2 agent passages++ agent_passages = await server.agent_manager.list_agent_passages_async(actor=default_user, agent_id=sarah_agent.id)+ assert len(agent_passages) == 2 # 3 source + 2 agent passages+@pytest.mark.asyncioasync def test_agent_list_passages_ordering(server, default_user, sarah_agent, agent_passages_setup, event_loop):diff --git a/tests/test_sources.py b/tests/test_sources.pyindex 9001742f7..ec8fd3cf5 100644--- a/tests/test_sources.py+++ b/tests/test_sources.py@@ -45,6 +45,7 @@ def client() -> LettaSDKClient:def agent_state(client: LettaSDKClient):open_file_tool = client.tools.list(name="open_file")[0]close_file_tool = client.tools.list(name="close_file")[0]+ search_files_tool = client.tools.list(name="search_files")[0]agent_state = client.agents.create(memory_blocks=[@@ -55,7 +56,7 @@ def agent_state(client: LettaSDKClient):],model="openai/gpt-4o-mini",embedding="openai/text-embedding-ada-002",- tool_ids=[open_file_tool.id, close_file_tool.id],+ tool_ids=[open_file_tool.id, close_file_tool.id, search_files_tool.id],)yield agent_state@@ -367,3 +368,95 @@ def test_agent_uses_open_close_file_correctly(client: LettaSDKClient, agent_statassert new_value != old_value, f"Different view ranges should have different content. New: '{new_value}', Old: '{old_value}'"print("✓ File successfully opened with different range - content differs as expected")+++@retry_until_success(max_attempts=5, sleep_time_seconds=2)+def test_agent_uses_search_files_correctly(client: LettaSDKClient, agent_state: AgentState):+ print(f"Starting test with agent ID: {agent_state.id}")++ # Clear existing sources+ existing_sources = client.sources.list()+ print(f"Found {len(existing_sources)} existing sources, clearing...")+ for source in existing_sources:+ print(f" Deleting source: {source.id}")+ client.sources.delete(source_id=source.id)++ # Clear existing jobs+ existing_jobs = client.jobs.list()+ print(f"Found {len(existing_jobs)} existing jobs, clearing...")+ for job in existing_jobs:+ print(f" Deleting job: {job.id}")+ client.jobs.delete(job_id=job.id)++ # Create a new source+ print("Creating new source...")+ source = client.sources.create(name="test_source", embedding="openai/text-embedding-ada-002")+ print(f"Created source with ID: {source.id}")++ sources_list = client.sources.list()+ assert len(sources_list) == 1+ print(f"✓ Verified source creation - found {len(sources_list)} source(s)")++ # Attach source to agent+ print(f"Attaching source {source.id} to agent {agent_state.id}...")+ client.agents.sources.attach(source_id=source.id, agent_id=agent_state.id)+ print("✓ Source attached to agent")++ # Load files into the source+ file_path = "tests/data/long_test.txt"+ print(f"Uploading file: {file_path}")++ # Upload the files+ with open(file_path, "rb") as f:+ job = client.sources.files.upload(source_id=source.id, file=f)++ print(f"File upload job created with ID: {job.id}, initial status: {job.status}")++ # Wait for the jobs to complete+ while job.status != "completed":+ print(f"Waiting for job {job.id} to complete... Current status: {job.status}")+ time.sleep(1)+ job = client.jobs.retrieve(job_id=job.id)++ print(f"✓ Job completed successfully with status: {job.status}")++ # Get uploaded files+ print("Retrieving uploaded files...")+ files = client.sources.files.list(source_id=source.id, limit=1)+ assert len(files) == 1+ assert files[0].source_id == source.id+ file = files[0]+ print(f"✓ Found uploaded file: {file.file_name} (ID: {file.id})")++ # Check that file is opened initially+ print("Checking initial agent state...")+ agent_state = client.agents.retrieve(agent_id=agent_state.id)+ blocks = agent_state.memory.file_blocks+ print(f"Agent has {len(blocks)} file block(s)")+ if blocks:+ initial_content_length = len(blocks[0].value)+ print(f"Initial file content length: {initial_content_length} characters")+ print(f"First 100 chars of content: {blocks[0].value[:100]}...")+ assert initial_content_length > 10, f"Expected file content > 10 chars, got {initial_content_length}"+ print("✓ File appears to be initially loaded")++ # Ask agent to use the search_files tool+ print(f"Requesting agent to search_files")+ search_files_response = client.agents.messages.create(+ agent_id=agent_state.id,+ messages=[+ MessageCreate(role="user", content=f"Use ONLY the search_files tool to search for details regarding the electoral history.")+ ],+ )+ print(f"Search file request sent, got {len(search_files_response.messages)} message(s) in response")+ print(search_files_response.messages)++ # Check that archival_memory_search was called+ tool_calls = [msg for msg in search_files_response.messages if msg.message_type == "tool_call_message"]+ assert len(tool_calls) > 0, "No tool calls found"+ assert any(tc.tool_call.name == "search_files" for tc in tool_calls), "search_files not called"++ # Check it returned successfully+ tool_returns = [msg for msg in search_files_response.messages if msg.message_type == "tool_return_message"]+ assert len(tool_returns) > 0, "No tool returns found"+ assert all(tr.status == "success" for tr in tool_returns), "Tool call failed"