Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add tools used filtering to internal runs [LET-5415] (#5557)
Christina Tong12185c860173
diff --git a/fern/openapi.json b/fern/openapi.jsonindex e3874fa55..7685855cb 100644--- a/fern/openapi.json+++ b/fern/openapi.json@@ -8997,6 +8997,56 @@},"description": "Filter runs by template family (base_template_id)."},+ {+ "name": "step_count",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "description": "Filter runs by step count. Must be provided with step_count_operator.",+ "title": "Step Count"+ },+ "description": "Filter runs by step count. Must be provided with step_count_operator."+ },+ {+ "name": "step_count_operator",+ "in": "query",+ "required": false,+ "schema": {+ "$ref": "#/components/schemas/ComparisonOperator",+ "description": "Operator for step_count filter: 'eq' for equals, 'gte' for greater than or equal, 'lte' for less than or equal.",+ "default": "eq"+ },+ "description": "Operator for step_count filter: 'eq' for equals, 'gte' for greater than or equal, 'lte' for less than or equal."+ },+ {+ "name": "tools_used",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ],+ "description": "Filter runs that used any of the specified tools.",+ "title": "Tools Used"+ },+ "description": "Filter runs that used any of the specified tools."+ },{"name": "before","in": "query",@@ -26373,6 +26423,12 @@"required": ["code"],"title": "CodeInput"},+ "ComparisonOperator": {+ "type": "string",+ "enum": ["eq", "gte", "lte"],+ "title": "ComparisonOperator",+ "description": "Comparison operators for filtering numeric values"+ },"CompletionTokensDetails": {"properties": {"accepted_prediction_tokens": {diff --git a/letta/server/rest_api/routers/v1/internal_runs.py b/letta/server/rest_api/routers/v1/internal_runs.pyindex bd303c8c4..fa603d238 100644--- a/letta/server/rest_api/routers/v1/internal_runs.py+++ b/letta/server/rest_api/routers/v1/internal_runs.py@@ -2,7 +2,7 @@ from typing import List, Literal, Optionalfrom fastapi import APIRouter, Depends, Query-from letta.schemas.enums import RunStatus+from letta.schemas.enums import ComparisonOperator, RunStatusfrom letta.schemas.letta_stop_reason import StopReasonTypefrom letta.schemas.run import Runfrom letta.server.rest_api.dependencies import HeaderParams, get_headers, get_letta_server@@ -39,6 +39,12 @@ async def list_runs(background: Optional[bool] = Query(None, description="If True, filters for runs that were created in background mode."),stop_reason: Optional[StopReasonType] = Query(None, description="Filter runs by stop reason."),template_family: Optional[str] = Query(None, description="Filter runs by template family (base_template_id)."),+ step_count: Optional[int] = Query(None, description="Filter runs by step count. Must be provided with step_count_operator."),+ step_count_operator: ComparisonOperator = Query(+ ComparisonOperator.EQ,+ description="Operator for step_count filter: 'eq' for equals, 'gte' for greater than or equal, 'lte' for less than or equal.",+ ),+ tools_used: Optional[List[str]] = Query(None, description="Filter runs that used any of the specified tools."),before: Optional[str] = Query(None, description="Run ID cursor for pagination. Returns runs that come before this run ID in the specified sort order"),@@ -94,5 +100,8 @@ async def list_runs(stop_reason=stop_reason,background=background,template_family=template_family,+ step_count=step_count,+ step_count_operator=step_count_operator,+ tools_used=tools_used,)return runsdiff --git a/letta/services/run_manager.py b/letta/services/run_manager.pyindex 8a2b3a4be..d3d70d9e9 100644--- a/letta/services/run_manager.py+++ b/letta/services/run_manager.py@@ -3,8 +3,6 @@ from pickletools import pyunicodefrom typing import List, Literal, Optionalfrom httpx import AsyncClient-from sqlalchemy import select-from sqlalchemy.orm import Sessionfrom letta.helpers.datetime_helpers import get_utc_timefrom letta.log import get_logger@@ -111,10 +109,11 @@ class RunManager:template_family: Optional[str] = None,step_count: Optional[int] = None,step_count_operator: ComparisonOperator = ComparisonOperator.EQ,+ tools_used: Optional[List[str]] = None,) -> List[PydanticRun]:"""List runs with filtering options."""async with db_registry.async_session() as session:- from sqlalchemy import select+ from sqlalchemy import or_, selectquery = select(RunModel).filter(RunModel.organization_id == actor.organization_id)@@ -140,17 +139,28 @@ class RunManager:if template_family:query = query.filter(RunModel.base_template_id == template_family)- # Filter by step_count - join with run_metrics- if step_count is not None:+ # Filter by step_count and/or tools_used - join with run_metrics+ if step_count is not None or tools_used:query = query.join(RunMetricsModel, RunModel.id == RunMetricsModel.id)# Filter by step_count with the specified operator- if step_count_operator == ComparisonOperator.EQ:- query = query.filter(RunMetricsModel.num_steps == step_count)- elif step_count_operator == ComparisonOperator.GTE:- query = query.filter(RunMetricsModel.num_steps >= step_count)- elif step_count_operator == ComparisonOperator.LTE:- query = query.filter(RunMetricsModel.num_steps <= step_count)+ if step_count is not None:+ if step_count_operator == ComparisonOperator.EQ:+ query = query.filter(RunMetricsModel.num_steps == step_count)+ elif step_count_operator == ComparisonOperator.GTE:+ query = query.filter(RunMetricsModel.num_steps >= step_count)+ elif step_count_operator == ComparisonOperator.LTE:+ query = query.filter(RunMetricsModel.num_steps <= step_count)++ # Filter by tools used ids+ if tools_used:+ from sqlalchemy import String, cast as sa_cast, type_coerce+ from sqlalchemy.dialects.postgresql import ARRAY, JSONB++ # Use ?| operator to check if any tool_id exists in the array (OR logic)+ jsonb_tools = sa_cast(RunMetricsModel.tools_used, JSONB)+ tools_array = type_coerce(tools_used, ARRAY(String))+ query = query.filter(jsonb_tools.op("?|")(tools_array))# Apply paginationfrom letta.services.helpers.run_manager_helper import _apply_pagination_async@@ -234,7 +244,8 @@ class RunManager:from letta.services.tool_manager import ToolManagertool_manager = ToolManager()- tool_id = await tool_manager.get_tool_id_by_name_async(tool_call.function.name, actor)+ tool_name = tool_call.function.name+ tool_id = await tool_manager.get_tool_id_by_name_async(tool_name, actor)if tool_id:tools_used.add(tool_id)diff --git a/tests/managers/test_run_manager.py b/tests/managers/test_run_manager.pyindex 2c2b17a53..e61de6ccf 100644--- a/tests/managers/test_run_manager.py+++ b/tests/managers/test_run_manager.py@@ -382,6 +382,96 @@ async def test_list_runs_by_stop_reason(server: SyncServer, sarah_agent, defaultassert runs[0].id == run.id+async def test_list_runs_by_tools_used(server: SyncServer, sarah_agent, default_user):+ """Test listing runs filtered by tools used."""+ # Seed tools first+ from letta.services.tool_manager import ToolManager++ tool_manager = ToolManager()+ await tool_manager.upsert_base_tools_async(default_user)++ web_search_tool_id = await tool_manager.get_tool_id_by_name_async("web_search", default_user)+ run_code_tool_id = await tool_manager.get_tool_id_by_name_async("run_code", default_user)++ if not web_search_tool_id or not run_code_tool_id:+ pytest.skip("Required tools (web_search, run_code) are not available in the database")++ # Create run with web_search tool+ run_web = await server.run_manager.create_run(+ pydantic_run=PydanticRun(agent_id=sarah_agent.id),+ actor=default_user,+ )+ await server.message_manager.create_many_messages_async(+ [+ PydanticMessage(+ agent_id=sarah_agent.id,+ role=MessageRole.assistant,+ content=[TextContent(text="Using web search")],+ tool_calls=[+ OpenAIToolCall(+ id="call_web",+ type="function",+ function=OpenAIFunction(name="web_search", arguments="{}"),+ )+ ],+ run_id=run_web.id,+ )+ ],+ actor=default_user,+ )++ # Create run with run_code tool+ run_code = await server.run_manager.create_run(+ pydantic_run=PydanticRun(agent_id=sarah_agent.id),+ actor=default_user,+ )+ await server.message_manager.create_many_messages_async(+ [+ PydanticMessage(+ agent_id=sarah_agent.id,+ role=MessageRole.assistant,+ content=[TextContent(text="Using run code")],+ tool_calls=[+ OpenAIToolCall(+ id="call_code",+ type="function",+ function=OpenAIFunction(name="run_code", arguments="{}"),+ )+ ],+ run_id=run_code.id,+ )+ ],+ actor=default_user,+ )++ # Complete runs to populate tools_used+ await server.run_manager.update_run_by_id_async(+ run_web.id, RunUpdate(status=RunStatus.completed, stop_reason=StopReasonType.end_turn), actor=default_user+ )+ await server.run_manager.update_run_by_id_async(+ run_code.id, RunUpdate(status=RunStatus.completed, stop_reason=StopReasonType.end_turn), actor=default_user+ )++ # Test filtering by single tool+ runs_web = await server.run_manager.list_runs(+ actor=default_user,+ agent_id=sarah_agent.id,+ tools_used=[web_search_tool_id],+ )+ assert len(runs_web) == 1+ assert runs_web[0].id == run_web.id++ # Test filtering by multiple tools+ runs_multi = await server.run_manager.list_runs(+ actor=default_user,+ agent_id=sarah_agent.id,+ tools_used=[web_search_tool_id, run_code_tool_id],+ )+ assert len(runs_multi) == 2+ assert {r.id for r in runs_multi} == {run_web.id, run_code.id}++@pytest.mark.asyncioasync def test_list_runs_by_step_count(server: SyncServer, sarah_agent, default_user):"""Test listing runs filtered by step count."""