Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add pending approval field on agent state (#8361)
cthomas9b359418d079
diff --git a/fern/openapi.json b/fern/openapi.jsonindex 152275dcd..ac17d496c 100644--- a/fern/openapi.json+++ b/fern/openapi.json@@ -453,6 +453,7 @@"agent.blocks","agent.identities","agent.managed_group",+ "agent.pending_approval","agent.secrets","agent.sources","agent.tags",@@ -4189,6 +4190,7 @@"agent.blocks","agent.identities","agent.managed_group",+ "agent.pending_approval","agent.secrets","agent.sources","agent.tags",@@ -4874,6 +4876,7 @@"agent.blocks","agent.identities","agent.managed_group",+ "agent.pending_approval","agent.secrets","agent.sources","agent.tags",@@ -10401,6 +10404,7 @@"agent.blocks","agent.identities","agent.managed_group",+ "agent.pending_approval","agent.secrets","agent.sources","agent.tags",@@ -13321,6 +13325,7 @@"agent.blocks","agent.identities","agent.managed_group",+ "agent.pending_approval","agent.secrets","agent.sources","agent.tags",@@ -23764,6 +23769,17 @@"description": "The identities associated with this agent.","default": []},+ "pending_approval": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ApprovalRequestMessage"+ },+ {+ "type": "null"+ }+ ],+ "description": "The latest approval request message pending for this agent, if any."+ },"message_buffer_autoclear": {"type": "boolean","title": "Message Buffer Autoclear",diff --git a/letta/orm/agent.py b/letta/orm/agent.pyindex 747cc1466..8527ca208 100644--- a/letta/orm/agent.py+++ b/letta/orm/agent.py@@ -1,15 +1,16 @@import asyncioimport uuidfrom datetime import datetime-from typing import TYPE_CHECKING, List, Optional, Set+from typing import TYPE_CHECKING, Any, List, Optional, Set-from sqlalchemy import JSON, Boolean, DateTime, Index, Integer, String+from sqlalchemy import JSON, Boolean, DateTime, Index, Integer, String, selectfrom sqlalchemy.ext.asyncio import AsyncAttrsfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom letta.orm.block import Blockfrom letta.orm.custom_columns import CompactionSettingsColumn, EmbeddingConfigColumn, LLMConfigColumn, ResponseFormatColumn, ToolRulesColumnfrom letta.orm.identity import Identity+from letta.orm.message import Message as MessageModelfrom letta.orm.mixins import OrganizationMixin, ProjectMixin, TemplateEntityMixin, TemplateMixinfrom letta.orm.organization import Organizationfrom letta.orm.sqlalchemy_base import SqlalchemyBase@@ -308,6 +309,25 @@ class Agent(SqlalchemyBase, OrganizationMixin, ProjectMixin, TemplateEntityMixinreturn self.__pydantic_model__(**state)+ async def _get_pending_approval_async(self) -> Optional[Any]:+ if self.message_ids and len(self.message_ids) > 0:+ from letta.server.db import db_registry++ async with db_registry.async_session() as session:+ latest_message_id = self.message_ids[-1]+ result = await session.execute(select(MessageModel).where(MessageModel.id == latest_message_id))+ latest_message = result.scalar_one_or_none()++ if (+ latest_message+ and latest_message.role == "approval"+ and latest_message.tool_calls is not None+ and len(latest_message.tool_calls) > 0+ ):+ pydantic_message = latest_message.to_pydantic()+ return pydantic_message._convert_approval_request_message()+ return None+async def to_pydantic_async(self,include_relationships: Optional[Set[str]] = None,@@ -379,6 +399,7 @@ class Agent(SqlalchemyBase, OrganizationMixin, ProjectMixin, TemplateEntityMixin"managed_group": None,"tool_exec_environment_variables": [],"secrets": [],+ "pending_approval": None,}# Initialize include_relationships to an empty set if it's None@@ -422,9 +443,20 @@ class Agent(SqlalchemyBase, OrganizationMixin, ProjectMixin, TemplateEntityMixinfile_agents = (self.awaitable_attrs.file_agents if "memory" in include_relationships or "agent.blocks" in include_set else empty_list_async())-- (tags, tools, sources, memory, identities, multi_agent_group, tool_exec_environment_variables, file_agents) = await asyncio.gather(- tags, tools, sources, memory, identities, multi_agent_group, tool_exec_environment_variables, file_agents+ pending_approval = self._get_pending_approval_async() if "agent.pending_approval" in include_set else none_async()++ (+ tags,+ tools,+ sources,+ memory,+ identities,+ multi_agent_group,+ tool_exec_environment_variables,+ file_agents,+ pending_approval,+ ) = await asyncio.gather(+ tags, tools, sources, memory, identities, multi_agent_group, tool_exec_environment_variables, file_agents, pending_approval)state["tags"] = [t.tag for t in tags]@@ -466,6 +498,7 @@ class Agent(SqlalchemyBase, OrganizationMixin, ProjectMixin, TemplateEntityMixinenv_vars_pydantic.append(AgentEnvironmentVariable.model_validate(data))state["tool_exec_environment_variables"] = env_vars_pydanticstate["secrets"] = env_vars_pydantic+ state["pending_approval"] = pending_approvalstate["model"] = self.llm_config.handle if self.llm_config else Nonestate["model_settings"] = self.llm_config._to_model_settings() if self.llm_config else Nonestate["embedding"] = self.embedding_config.handle if self.embedding_config else Nonediff --git a/letta/schemas/agent.py b/letta/schemas/agent.pyindex b6a22ea84..64cb313b8 100644--- a/letta/schemas/agent.py+++ b/letta/schemas/agent.py@@ -14,6 +14,7 @@ from letta.schemas.file import FileStatusfrom letta.schemas.group import Groupfrom letta.schemas.identity import Identityfrom letta.schemas.letta_base import OrmMetadataBase+from letta.schemas.letta_message import ApprovalRequestMessagefrom letta.schemas.letta_stop_reason import StopReasonTypefrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.memory import Memory@@ -51,6 +52,7 @@ AgentRelationships = Literal["agent.blocks","agent.identities","agent.managed_group",+ "agent.pending_approval","agent.secrets","agent.sources","agent.tags",@@ -125,6 +127,9 @@ class AgentState(OrmMetadataBase, validate_assignment=True):[], description="Deprecated: Use `identities` field instead. The ids of the identities associated with this agent.", deprecated=True)identities: List[Identity] = Field([], description="The identities associated with this agent.")+ pending_approval: Optional[ApprovalRequestMessage] = Field(+ None, description="The latest approval request message pending for this agent, if any."+ )# An advanced configuration that makes it so this agent does not remember any previous messagesmessage_buffer_autoclear: bool = Field(diff --git a/tests/integration_test_human_in_the_loop.py b/tests/integration_test_human_in_the_loop.pyindex 87365d296..73584629f 100644--- a/tests/integration_test_human_in_the_loop.py+++ b/tests/integration_test_human_in_the_loop.py@@ -274,8 +274,21 @@ def test_invoke_approval_request(client.get(f"/v1/agents/{agent.id}/context", cast_to=dict[str, Any])+ # Test pending_approval relationship field+ agent_with_pending = client.agents.retrieve(agent_id=agent.id, include=["agent.pending_approval"])+ assert agent_with_pending.pending_approval is not None+ # Client SDK returns it as a dict, so use dict access+ assert agent_with_pending.pending_approval["tool_call"]["name"] == "get_secret_code_tool"+ assert len(agent_with_pending.pending_approval["tool_calls"]) > 0+ assert agent_with_pending.pending_approval["tool_calls"][0]["name"] == "get_secret_code_tool"+ assert agent_with_pending.pending_approval["tool_calls"][0]["tool_call_id"] == response.messages[-1].tool_call.tool_call_id+approve_tool_call(client, agent.id, response.messages[-1].tool_call.tool_call_id)+ # After approval, pending_approval should be None (latest message is no longer approval request)+ agent_after_approval = client.agents.retrieve(agent_id=agent.id, include=["agent.pending_approval"])+ assert agent_after_approval.pending_approval is None+def test_invoke_approval_request_stream(client: Letta,diff --git a/tests/managers/test_agent_manager.py b/tests/managers/test_agent_manager.pyindex c374a7649..72bcd2fe2 100644--- a/tests/managers/test_agent_manager.py+++ b/tests/managers/test_agent_manager.py@@ -1571,6 +1571,7 @@ async def test_agent_state_schema_unchanged(server: SyncServer):from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.environment_variables import AgentEnvironmentVariablefrom letta.schemas.group import Group+ from letta.schemas.letta_message import ApprovalRequestMessagefrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.memory import Memoryfrom letta.schemas.model import ModelSettingsUnion@@ -1620,6 +1621,7 @@ async def test_agent_state_schema_unchanged(server: SyncServer):"entity_id": (str, type(None)),"identity_ids": list,"identities": list,+ "pending_approval": (ApprovalRequestMessage, type(None)),# Advanced configuration"message_buffer_autoclear": bool,"enable_sleeptime": (bool, type(None)),