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.

chore: bump version 0.7.23 (#2656)

cthomas23ac226172dc
diff --git a/letta/__init__.py b/letta/__init__.py
index dcbda419e..cd4956d28 100644
--- a/letta/__init__.py
+++ b/letta/__init__.py
@@ -1,4 +1,4 @@
-__version__ = "0.7.22"
+__version__ = "0.7.23"
# import clients
from letta.client.client import RESTClient
diff --git a/letta/llm_api/google_ai_client.py b/letta/llm_api/google_ai_client.py
index 47671398c..f1d8e091e 100644
--- a/letta/llm_api/google_ai_client.py
+++ b/letta/llm_api/google_ai_client.py
@@ -7,7 +7,10 @@ from letta.errors import ErrorCode, LLMAuthenticationError, LLMError
from letta.llm_api.google_constants import GOOGLE_MODEL_FOR_API_KEY_CHECK
from letta.llm_api.google_vertex_client import GoogleVertexClient
from letta.log import get_logger
+from letta.schemas.llm_config import LLMConfig
+from letta.schemas.message import Message as PydanticMessage
from letta.settings import model_settings
+from letta.tracing import trace_method
logger = get_logger(__name__)
@@ -17,6 +20,18 @@ class GoogleAIClient(GoogleVertexClient):
def _get_client(self):
return genai.Client(api_key=model_settings.gemini_api_key)
+ @trace_method
+ def build_request_data(
+ self,
+ messages: List[PydanticMessage],
+ llm_config: LLMConfig,
+ tools: List[dict],
+ force_tool_call: Optional[str] = None,
+ ) -> dict:
+ request = super().build_request_data(messages, llm_config, tools, force_tool_call)
+ del request["config"]["thinking_config"]
+ return request
+
def get_gemini_endpoint_and_headers(
base_url: str, model: Optional[str], api_key: str, key_in_header: bool = True, generate_content: bool = False
diff --git a/letta/llm_api/google_vertex_client.py b/letta/llm_api/google_vertex_client.py
index e8215813f..afc80ebde 100644
--- a/letta/llm_api/google_vertex_client.py
+++ b/letta/llm_api/google_vertex_client.py
@@ -244,11 +244,10 @@ class GoogleVertexClient(LLMClientBase):
# Add thinking_config
# If enable_reasoner is False, set thinking_budget to 0
# Otherwise, use the value from max_reasoning_tokens
- if llm_config.enable_reasoner:
- thinking_config = ThinkingConfig(
- thinking_budget=llm_config.max_reasoning_tokens,
- )
- request_data["config"]["thinking_config"] = thinking_config.model_dump()
+ thinking_config = ThinkingConfig(
+ thinking_budget=llm_config.max_reasoning_tokens if llm_config.enable_reasoner else 0,
+ )
+ request_data["config"]["thinking_config"] = thinking_config.model_dump()
return request_data
diff --git a/letta/schemas/providers.py b/letta/schemas/providers.py
index 9f17737a4..86f919eb1 100644
--- a/letta/schemas/providers.py
+++ b/letta/schemas/providers.py
@@ -54,7 +54,7 @@ class Provider(ProviderBase):
return []
async def list_embedding_models_async(self) -> List[EmbeddingConfig]:
- return []
+ return self.list_embedding_models()
def get_model_context_window(self, model_name: str) -> Optional[int]:
raise NotImplementedError
diff --git a/letta/server/db.py b/letta/server/db.py
index 38b9b33b9..32f93a03f 100644
--- a/letta/server/db.py
+++ b/letta/server/db.py
@@ -17,8 +17,6 @@ from letta.tracing import trace_method
logger = get_logger(__name__)
-logger = get_logger(__name__)
-
def print_sqlite_schema_error():
"""Print a formatted error message for SQLite schema issues"""
diff --git a/letta/server/rest_api/routers/v1/blocks.py b/letta/server/rest_api/routers/v1/blocks.py
index bf669f432..d31fd8557 100644
--- a/letta/server/rest_api/routers/v1/blocks.py
+++ b/letta/server/rest_api/routers/v1/blocks.py
@@ -50,47 +50,46 @@ def count_blocks(
@router.post("/", response_model=Block, operation_id="create_block")
-def create_block(
+async def create_block(
create_block: CreateBlock = Body(...),
server: SyncServer = Depends(get_letta_server),
actor_id: Optional[str] = Header(None, alias="user_id"),
):
- actor = server.user_manager.get_user_or_default(user_id=actor_id)
+ actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)
block = Block(**create_block.model_dump())
- return server.block_manager.create_or_update_block(actor=actor, block=block)
+ return await server.block_manager.create_or_update_block_async(actor=actor, block=block)
@router.patch("/{block_id}", response_model=Block, operation_id="modify_block")
-def modify_block(
+async def modify_block(
block_id: str,
block_update: BlockUpdate = Body(...),
server: SyncServer = Depends(get_letta_server),
actor_id: Optional[str] = Header(None, alias="user_id"),
):
- actor = server.user_manager.get_user_or_default(user_id=actor_id)
- return server.block_manager.update_block(block_id=block_id, block_update=block_update, actor=actor)
+ actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)
+ return await server.block_manager.update_block_async(block_id=block_id, block_update=block_update, actor=actor)
@router.delete("/{block_id}", response_model=Block, operation_id="delete_block")
-def delete_block(
+async def delete_block(
block_id: str,
server: SyncServer = Depends(get_letta_server),
actor_id: Optional[str] = Header(None, alias="user_id"),
):
- actor = server.user_manager.get_user_or_default(user_id=actor_id)
- return server.block_manager.delete_block(block_id=block_id, actor=actor)
+ actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)
+ return await server.block_manager.delete_block_async(block_id=block_id, actor=actor)
@router.get("/{block_id}", response_model=Block, operation_id="retrieve_block")
-def retrieve_block(
+async def retrieve_block(
block_id: str,
server: SyncServer = Depends(get_letta_server),
actor_id: Optional[str] = Header(None, alias="user_id"),
):
- print("call get block", block_id)
- actor = server.user_manager.get_user_or_default(user_id=actor_id)
+ actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)
try:
- block = server.block_manager.get_block_by_id(block_id=block_id, actor=actor)
+ block = await server.block_manager.get_block_by_id_async(block_id=block_id, actor=actor)
if block is None:
raise HTTPException(status_code=404, detail="Block not found")
return block
diff --git a/letta/server/rest_api/routers/v1/sources.py b/letta/server/rest_api/routers/v1/sources.py
index 478b6278a..24ebe9d67 100644
--- a/letta/server/rest_api/routers/v1/sources.py
+++ b/letta/server/rest_api/routers/v1/sources.py
@@ -78,17 +78,6 @@ async def list_sources(
return await server.source_manager.list_sources(actor=actor)
[email protected]("/count", response_model=int, operation_id="count_sources")
-def count_sources(
- server: "SyncServer" = Depends(get_letta_server),
- actor_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present
-):
- """
- Count all data sources created by a user.
- """
- return server.source_manager.size(actor=server.user_manager.get_user_or_default(user_id=actor_id))
-
-
@router.post("/", response_model=Source, operation_id="create_source")
async def create_source(
source_create: SourceCreate,
diff --git a/letta/server/server.py b/letta/server/server.py
index 45cdc882a..80001a025 100644
--- a/letta/server/server.py
+++ b/letta/server/server.py
@@ -741,6 +741,13 @@ class SyncServer(Server):
self._llm_config_cache[key] = self.get_llm_config_from_handle(actor=actor, **kwargs)
return self._llm_config_cache[key]
+ @trace_method
+ async def get_cached_llm_config_async(self, actor: User, **kwargs):
+ key = make_key(**kwargs)
+ if key not in self._llm_config_cache:
+ self._llm_config_cache[key] = await self.get_llm_config_from_handle_async(actor=actor, **kwargs)
+ return self._llm_config_cache[key]
+
@trace_method
def get_cached_embedding_config(self, actor: User, **kwargs):
key = make_key(**kwargs)
@@ -748,6 +755,13 @@ class SyncServer(Server):
self._embedding_config_cache[key] = self.get_embedding_config_from_handle(actor=actor, **kwargs)
return self._embedding_config_cache[key]
+ @trace_method
+ async def get_cached_embedding_config_async(self, actor: User, **kwargs):
+ key = make_key(**kwargs)
+ if key not in self._embedding_config_cache:
+ self._embedding_config_cache[key] = await self.get_embedding_config_from_handle_async(actor=actor, **kwargs)
+ return self._embedding_config_cache[key]
+
@trace_method
def create_agent(
self,
@@ -815,7 +829,7 @@ class SyncServer(Server):
"enable_reasoner": request.enable_reasoner,
}
log_event(name="start get_cached_llm_config", attributes=config_params)
- request.llm_config = self.get_cached_llm_config(actor=actor, **config_params)
+ request.llm_config = await self.get_cached_llm_config_async(actor=actor, **config_params)
log_event(name="end get_cached_llm_config", attributes=config_params)
if request.embedding_config is None:
@@ -826,7 +840,7 @@ class SyncServer(Server):
"embedding_chunk_size": request.embedding_chunk_size or constants.DEFAULT_EMBEDDING_CHUNK_SIZE,
}
log_event(name="start get_cached_embedding_config", attributes=embedding_config_params)
- request.embedding_config = self.get_cached_embedding_config(actor=actor, **embedding_config_params)
+ request.embedding_config = await self.get_cached_embedding_config_async(actor=actor, **embedding_config_params)
log_event(name="end get_cached_embedding_config", attributes=embedding_config_params)
log_event(name="start create_agent db")
@@ -877,10 +891,10 @@ class SyncServer(Server):
actor: User,
) -> AgentState:
if request.model is not None:
- request.llm_config = self.get_llm_config_from_handle(handle=request.model, actor=actor)
+ request.llm_config = await self.get_llm_config_from_handle_async(handle=request.model, actor=actor)
if request.embedding is not None:
- request.embedding_config = self.get_embedding_config_from_handle(handle=request.embedding, actor=actor)
+ request.embedding_config = await self.get_embedding_config_from_handle_async(handle=request.embedding, actor=actor)
if request.enable_sleeptime:
agent = self.agent_manager.get_agent_by_id(agent_id=agent_id, actor=actor)
@@ -1568,6 +1582,61 @@ class SyncServer(Server):
return llm_config
+ @trace_method
+ async def get_llm_config_from_handle_async(
+ self,
+ actor: User,
+ handle: str,
+ context_window_limit: Optional[int] = None,
+ max_tokens: Optional[int] = None,
+ max_reasoning_tokens: Optional[int] = None,
+ enable_reasoner: Optional[bool] = None,
+ ) -> LLMConfig:
+ try:
+ provider_name, model_name = handle.split("/", 1)
+ provider = await self.get_provider_from_name_async(provider_name, actor)
+
+ all_llm_configs = await provider.list_llm_models_async()
+ llm_configs = [config for config in all_llm_configs if config.handle == handle]
+ if not llm_configs:
+ llm_configs = [config for config in all_llm_configs if config.model == model_name]
+ if not llm_configs:
+ available_handles = [config.handle for config in all_llm_configs]
+ raise HandleNotFoundError(handle, available_handles)
+ except ValueError as e:
+ llm_configs = [config for config in self.get_local_llm_configs() if config.handle == handle]
+ if not llm_configs:
+ llm_configs = [config for config in self.get_local_llm_configs() if config.model == model_name]
+ if not llm_configs:
+ raise e
+
+ if len(llm_configs) == 1:
+ llm_config = llm_configs[0]
+ elif len(llm_configs) > 1:
+ raise ValueError(f"Multiple LLM models with name {model_name} supported by {provider_name}")
+ else:
+ llm_config = llm_configs[0]
+
+ if context_window_limit is not None:
+ if context_window_limit > llm_config.context_window:
+ raise ValueError(f"Context window limit ({context_window_limit}) is greater than maximum of ({llm_config.context_window})")
+ llm_config.context_window = context_window_limit
+ else:
+ llm_config.context_window = min(llm_config.context_window, model_settings.global_max_context_window_limit)
+
+ if max_tokens is not None:
+ llm_config.max_tokens = max_tokens
+ if max_reasoning_tokens is not None:
+ if not max_tokens or max_reasoning_tokens > max_tokens:
+ raise ValueError(f"Max reasoning tokens ({max_reasoning_tokens}) must be less than max tokens ({max_tokens})")
+ llm_config.max_reasoning_tokens = max_reasoning_tokens
+ if enable_reasoner is not None:
+ llm_config.enable_reasoner = enable_reasoner
+ if enable_reasoner and llm_config.model_endpoint_type == "anthropic":
+ llm_config.put_inner_thoughts_in_kwargs = False
+
+ return llm_config
+
@trace_method
def get_embedding_config_from_handle(
self, actor: User, handle: str, embedding_chunk_size: int = constants.DEFAULT_EMBEDDING_CHUNK_SIZE
@@ -1597,6 +1666,36 @@ class SyncServer(Server):
return embedding_config
+ @trace_method
+ async def get_embedding_config_from_handle_async(
+ self, actor: User, handle: str, embedding_chunk_size: int = constants.DEFAULT_EMBEDDING_CHUNK_SIZE
+ ) -> EmbeddingConfig:
+ try:
+ provider_name, model_name = handle.split("/", 1)
+ provider = await self.get_provider_from_name_async(provider_name, actor)
+
+ all_embedding_configs = await provider.list_embedding_models_async()
+ embedding_configs = [config for config in all_embedding_configs if config.handle == handle]
+ if not embedding_configs:
+ raise ValueError(f"Embedding model {model_name} is not supported by {provider_name}")
+ except ValueError as e:
+ # search local configs
+ embedding_configs = [config for config in self.get_local_embedding_configs() if config.handle == handle]
+ if not embedding_configs:
+ raise e
+
+ if len(embedding_configs) == 1:
+ embedding_config = embedding_configs[0]
+ elif len(embedding_configs) > 1:
+ raise ValueError(f"Multiple embedding models with name {model_name} supported by {provider_name}")
+ else:
+ embedding_config = embedding_configs[0]
+
+ if embedding_chunk_size:
+ embedding_config.embedding_chunk_size = embedding_chunk_size
+
+ return embedding_config
+
def get_provider_from_name(self, provider_name: str, actor: User) -> Provider:
providers = [provider for provider in self.get_enabled_providers(actor) if provider.name == provider_name]
if not providers:
@@ -1608,6 +1707,18 @@ class SyncServer(Server):
return provider
+ async def get_provider_from_name_async(self, provider_name: str, actor: User) -> Provider:
+ all_providers = await self.get_enabled_providers_async(actor)
+ providers = [provider for provider in all_providers if provider.name == provider_name]
+ if not providers:
+ raise ValueError(f"Provider {provider_name} is not supported")
+ elif len(providers) > 1:
+ raise ValueError(f"Multiple providers with name {provider_name} supported")
+ else:
+ provider = providers[0]
+
+ return provider
+
def get_local_llm_configs(self):
llm_models = []
try:
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index fcdf39430..d44354191 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -1023,34 +1023,6 @@ class AgentManager:
return await asyncio.gather(*[agent.to_pydantic_async(include_relationships=include_relationships) for agent in agents])
@trace_method
- @enforce_types
- async def get_agent_by_id_async(
- self,
- agent_id: str,
- actor: PydanticUser,
- include_relationships: Optional[List[str]] = None,
- ) -> PydanticAgentState:
- """Fetch an agent by its ID."""
- async with db_registry.async_session() as session:
- agent = await AgentModel.read_async(db_session=session, identifier=agent_id, actor=actor)
- return await agent.to_pydantic_async(include_relationships=include_relationships)
-
- @enforce_types
- async def get_agents_by_ids_async(
- self,
- agent_ids: list[str],
- actor: PydanticUser,
- include_relationships: Optional[List[str]] = None,
- ) -> list[PydanticAgentState]:
- """Fetch a list of agents by their IDs."""
- async with db_registry.async_session() as session:
- agents = await AgentModel.read_multiple_async(
- db_session=session,
- identifiers=agent_ids,
- actor=actor,
- )
- return await asyncio.gather(*[agent.to_pydantic_async(include_relationships=include_relationships) for agent in agents])
-
@enforce_types
def get_agent_by_name(self, agent_name: str, actor: PydanticUser) -> PydanticAgentState:
"""Fetch an agent by its ID."""
@@ -1321,11 +1293,6 @@ class AgentManager:
return await self.message_manager.get_messages_by_ids_async(message_ids=agent.message_ids, actor=actor)
@trace_method
- @enforce_types
- async def get_in_context_messages_async(self, agent_id: str, actor: PydanticUser) -> List[PydanticMessage]:
- agent = await self.get_agent_by_id_async(agent_id=agent_id, include_relationships=[], actor=actor)
- return await self.message_manager.get_messages_by_ids_async(message_ids=agent.message_ids, actor=actor)
-
@enforce_types
def get_system_message(self, agent_id: str, actor: PydanticUser) -> PydanticMessage:
message_ids = self.get_agent_by_id(agent_id=agent_id, actor=actor).message_ids
@@ -1475,73 +1442,6 @@ class AgentManager:
return agent_state
@trace_method
- @enforce_types
- async def rebuild_system_prompt_async(
- self, agent_id: str, actor: PydanticUser, force=False, update_timestamp=True
- ) -> PydanticAgentState:
- """Rebuilds the system message with the latest memory object and any shared memory block updates
-
- Updates to core memory blocks should trigger a "rebuild", which itself will create a new message object
-
- Updates to the memory header should *not* trigger a rebuild, since that will simply flood recall storage with excess messages
- """
- agent_state = await self.get_agent_by_id_async(agent_id=agent_id, include_relationships=["memory"], actor=actor)
-
- curr_system_message = await self.get_system_message_async(
- agent_id=agent_id, actor=actor
- ) # this is the system + memory bank, not just the system prompt
- curr_system_message_openai = curr_system_message.to_openai_dict()
-
- # note: we only update the system prompt if the core memory is changed
- # this means that the archival/recall memory statistics may be someout out of date
- curr_memory_str = agent_state.memory.compile()
- if curr_memory_str in curr_system_message_openai["content"] and not force:
- # NOTE: could this cause issues if a block is removed? (substring match would still work)
- logger.debug(
- f"Memory hasn't changed for agent id={agent_id} and actor=({actor.id}, {actor.name}), skipping system prompt rebuild"
- )
- return agent_state
-
- # If the memory didn't update, we probably don't want to update the timestamp inside
- # For example, if we're doing a system prompt swap, this should probably be False
- if update_timestamp:
- memory_edit_timestamp = get_utc_time()
- else:
- # NOTE: a bit of a hack - we pull the timestamp from the message created_by
- memory_edit_timestamp = curr_system_message.created_at
-
- num_messages = await self.message_manager.size_async(actor=actor, agent_id=agent_id)
- num_archival_memories = await self.passage_manager.size_async(actor=actor, agent_id=agent_id)
-
- # update memory (TODO: potentially update recall/archival stats separately)
- new_system_message_str = compile_system_message(
- system_prompt=agent_state.system,
- in_context_memory=agent_state.memory,
- in_context_memory_last_edit=memory_edit_timestamp,
- recent_passages=self.list_passages(actor=actor, agent_id=agent_id, ascending=False, limit=10),
- previous_message_count=num_messages,
- archival_memory_size=num_archival_memories,
- )
-
- diff = united_diff(curr_system_message_openai["content"], new_system_message_str)
- if len(diff) > 0: # there was a diff
- logger.debug(f"Rebuilding system with new memory...\nDiff:\n{diff}")
-
- # Swap the system message out (only if there is a diff)
- message = PydanticMessage.dict_to_message(
- agent_id=agent_id,
- model=agent_state.llm_config.model,
- openai_message_dict={"role": "system", "content": new_system_message_str},
- )
- message = await self.message_manager.update_message_by_id_async(
- message_id=curr_system_message.id,
- message_update=MessageUpdate(**message.model_dump()),
- actor=actor,
- )
- return await self.set_in_context_messages_async(agent_id=agent_id, message_ids=agent_state.message_ids, actor=actor)
- else:
- return agent_state
-
@enforce_types
def set_in_context_messages(self, agent_id: str, message_ids: List[str], actor: PydanticUser) -> PydanticAgentState:
return self.update_agent(agent_id=agent_id, agent_update=UpdateAgent(message_ids=message_ids), actor=actor)
@@ -1552,10 +1452,6 @@ class AgentManager:
return await self.update_agent_async(agent_id=agent_id, agent_update=UpdateAgent(message_ids=message_ids), actor=actor)
@trace_method
- @enforce_types
- async def set_in_context_messages_async(self, agent_id: str, message_ids: List[str], actor: PydanticUser) -> PydanticAgentState:
- return await self.update_agent_async(agent_id=agent_id, agent_update=UpdateAgent(message_ids=message_ids), actor=actor)
-
@enforce_types
def trim_older_in_context_messages(self, num: int, agent_id: str, actor: PydanticUser) -> PydanticAgentState:
message_ids = self.get_agent_by_id(agent_id=agent_id, actor=actor).message_ids
@@ -1786,25 +1682,6 @@ class AgentManager:
return [source.to_pydantic() for source in agent.sources]
@trace_method
- @enforce_types
- async def list_attached_sources_async(self, agent_id: str, actor: PydanticUser) -> List[PydanticSource]:
- """
- Lists all sources attached to an agent.
-
- Args:
- agent_id: ID of the agent to list sources for
- actor: User performing the action
-
- Returns:
- List[str]: List of source IDs attached to the agent
- """
- async with db_registry.async_session() as session:
- # Verify agent exists and user has permission to access it
- agent = await AgentModel.read_async(db_session=session, identifier=agent_id, actor=actor)
-
- # Use the lazy-loaded relationship to get sources
- return [source.to_pydantic() for source in agent.sources]
-
@enforce_types
def detach_source(self, agent_id: str, source_id: str, actor: PydanticUser) -> PydanticAgentState:
"""
@@ -1896,33 +1773,6 @@ class AgentManager:
return block.to_pydantic()
@trace_method
- @enforce_types
- async def modify_block_by_label_async(
- self,
- agent_id: str,
- block_label: str,
- block_update: BlockUpdate,
- actor: PydanticUser,
- ) -> PydanticBlock:
- """Gets a block attached to an agent by its label."""
- async with db_registry.async_session() as session:
- block = None
- agent = await AgentModel.read_async(db_session=session, identifier=agent_id, actor=actor)
- for block in agent.core_memory:
- if block.label == block_label:
- block = block
- break
- if not block:
- raise NoResultFound(f"No block with label '{block_label}' found for agent '{agent_id}'")
-
- update_data = block_update.model_dump(to_orm=True, exclude_unset=True, exclude_none=True)
-
- for key, value in update_data.items():
- setattr(block, key, value)
-
- await block.update_async(session, actor=actor)
- return block.to_pydantic()
-
@enforce_types
def update_block_with_label(
self,
@@ -2337,65 +2187,6 @@ class AgentManager:
return [p.to_pydantic() for p in passages]
@trace_method
- @enforce_types
- async def list_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,
- agent_only: bool = False,
- ) -> List[PydanticPassage]:
- """Lists all passages attached to an agent."""
- async with db_registry.async_session() as session:
- main_query = self._build_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,
- agent_only=agent_only,
- )
-
- # Add limit
- if limit:
- main_query = main_query.limit(limit)
-
- # Execute query
- result = await session.execute(main_query)
-
- passages = []
- for row in result:
- data = dict(row._mapping)
- if data["agent_id"] is not None:
- # This is an AgentPassage - remove source fields
- data.pop("source_id", None)
- data.pop("file_id", None)
- passage = AgentPassage(**data)
- else:
- # This is a SourcePassage - remove agent field
- data.pop("agent_id", None)
- passage = SourcePassage(**data)
- passages.append(passage)
-
- return [p.to_pydantic() for p in passages]
-
@enforce_types
def passage_size(
self,
diff --git a/letta/services/block_manager.py b/letta/services/block_manager.py
index 0795ed7fe..fd46e86a7 100644
--- a/letta/services/block_manager.py
+++ b/letta/services/block_manager.py
@@ -38,6 +38,21 @@ class BlockManager:
block.create(session, actor=actor)
return block.to_pydantic()
+ @trace_method
+ @enforce_types
+ async def create_or_update_block_async(self, block: PydanticBlock, actor: PydanticUser) -> PydanticBlock:
+ """Create a new block based on the Block schema."""
+ db_block = await self.get_block_by_id_async(block.id, actor)
+ if db_block:
+ update_data = BlockUpdate(**block.model_dump(to_orm=True, exclude_none=True))
+ return await self.update_block_async(block.id, update_data, actor)
+ else:
+ async with db_registry.async_session() as session:
+ data = block.model_dump(to_orm=True, exclude_none=True)
+ block = BlockModel(**data, organization_id=actor.organization_id)
+ await block.create_async(session, actor=actor)
+ return block.to_pydantic()
+
@trace_method
@enforce_types
def batch_create_blocks(self, blocks: List[PydanticBlock], actor: PydanticUser) -> List[PydanticBlock]:
@@ -78,6 +93,22 @@ class BlockManager:
block.update(db_session=session, actor=actor)
return block.to_pydantic()
+ @trace_method
+ @enforce_types
+ async def update_block_async(self, block_id: str, block_update: BlockUpdate, actor: PydanticUser) -> PydanticBlock:
+ """Update a block by its ID with the given BlockUpdate object."""
+ # Safety check for block
+
+ async with db_registry.async_session() as session:
+ block = await BlockModel.read_async(db_session=session, identifier=block_id, actor=actor)
+ update_data = block_update.model_dump(to_orm=True, exclude_unset=True, exclude_none=True)
+
+ for key, value in update_data.items():
+ setattr(block, key, value)
+
+ await block.update_async(db_session=session, actor=actor)
+ return block.to_pydantic()
+
@trace_method
@enforce_types
def delete_block(self, block_id: str, actor: PydanticUser) -> PydanticBlock:
@@ -87,6 +118,15 @@ class BlockManager:
block.hard_delete(db_session=session, actor=actor)
return block.to_pydantic()
+ @trace_method
+ @enforce_types
+ async def delete_block_async(self, block_id: str, actor: PydanticUser) -> PydanticBlock:
+ """Delete a block by its ID."""
+ async with db_registry.async_session() as session:
+ block = await BlockModel.read_async(db_session=session, identifier=block_id, actor=actor)
+ await block.hard_delete_async(db_session=session, actor=actor)
+ return block.to_pydantic()
+
@trace_method
@enforce_types
async def get_blocks_async(
@@ -161,6 +201,17 @@ class BlockManager:
except NoResultFound:
return None
+ @trace_method
+ @enforce_types
+ async def get_block_by_id_async(self, block_id: str, actor: Optional[PydanticUser] = None) -> Optional[PydanticBlock]:
+ """Retrieve a block by its name."""
+ async with db_registry.async_session() as session:
+ try:
+ block = await BlockModel.read_async(db_session=session, identifier=block_id, actor=actor)
+ return block.to_pydantic()
+ except NoResultFound:
+ return None
+
@trace_method
@enforce_types
async def get_all_blocks_by_ids_async(self, block_ids: List[str], actor: Optional[PydanticUser] = None) -> List[PydanticBlock]:
diff --git a/pyproject.toml b/pyproject.toml
index 2400bdf84..194d5b783 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "letta"
-version = "0.7.22"
+version = "0.7.23"
packages = [
{include = "letta"},
]