Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add provider category to steps model (#2303)
cthomas353bd607df5f
diff --git a/alembic/versions/6c53224a7a58_add_provider_category_to_steps.py b/alembic/versions/6c53224a7a58_add_provider_category_to_steps.pynew file mode 100644index 000000000..891f427f4--- /dev/null+++ b/alembic/versions/6c53224a7a58_add_provider_category_to_steps.py@@ -0,0 +1,31 @@+"""add provider category to steps++Revision ID: 6c53224a7a58+Revises: cc8dc340836d+Create Date: 2025-05-21 10:09:43.761669++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "6c53224a7a58"+down_revision: Union[str, None] = "cc8dc340836d"+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! ###+ op.add_column("steps", sa.Column("provider_category", sa.String(), nullable=True))+ # ### end Alembic commands ###+++def downgrade() -> None:+ # ### commands auto generated by Alembic - please adjust! ###+ op.drop_column("steps", "provider_category")+ # ### end Alembic commands ###diff --git a/letta/agent.py b/letta/agent.pyindex 5c13abf48..85a37d600 100644--- a/letta/agent.py+++ b/letta/agent.py@@ -959,6 +959,7 @@ class Agent(BaseAgent):actor=self.user,agent_id=self.agent_state.id,provider_name=self.agent_state.llm_config.model_endpoint_type,+ provider_category=self.agent_state.llm_config.provider_category or "base",model=self.agent_state.llm_config.model,model_endpoint=self.agent_state.llm_config.model_endpoint,context_window_limit=self.agent_state.llm_config.context_window,diff --git a/letta/agents/letta_agent.py b/letta/agents/letta_agent.pyindex 3ec862b15..3eebbb244 100644--- a/letta/agents/letta_agent.py+++ b/letta/agents/letta_agent.py@@ -554,6 +554,7 @@ class LettaAgent(BaseAgent):actor=self.actor,agent_id=agent_state.id,provider_name=agent_state.llm_config.model_endpoint_type,+ provider_category=agent_state.llm_config.provider_category or "base",model=agent_state.llm_config.model,model_endpoint=agent_state.llm_config.model_endpoint,context_window_limit=agent_state.llm_config.context_window,diff --git a/letta/orm/step.py b/letta/orm/step.pyindex ce7b82442..bd03d935a 100644--- a/letta/orm/step.py+++ b/letta/orm/step.py@@ -35,6 +35,7 @@ class Step(SqlalchemyBase):)agent_id: Mapped[Optional[str]] = mapped_column(None, nullable=True, doc="The name of the model used for this step.")provider_name: Mapped[Optional[str]] = mapped_column(None, nullable=True, doc="The name of the provider used for this step.")+ provider_category: Mapped[Optional[str]] = mapped_column(None, nullable=True, doc="The category of the provider used for this step.")model: Mapped[Optional[str]] = mapped_column(None, nullable=True, doc="The name of the model used for this step.")model_endpoint: Mapped[Optional[str]] = mapped_column(None, nullable=True, doc="The model endpoint url used for this step.")context_window_limit: Mapped[Optional[int]] = mapped_column(diff --git a/letta/schemas/step.py b/letta/schemas/step.pyindex d25d8b684..2e0604d85 100644--- a/letta/schemas/step.py+++ b/letta/schemas/step.py@@ -20,6 +20,7 @@ class Step(StepBase):)agent_id: Optional[str] = Field(None, description="The ID of the agent that performed the step.")provider_name: Optional[str] = Field(None, description="The name of the provider used for this step.")+ provider_category: Optional[str] = Field(None, description="The category of the provider used for this step.")model: Optional[str] = Field(None, description="The name of the model used for this step.")model_endpoint: Optional[str] = Field(None, description="The model endpoint url used for this step.")context_window_limit: Optional[int] = Field(None, description="The context window limit configured for this step.")diff --git a/letta/services/step_manager.py b/letta/services/step_manager.pyindex cdac474ba..8ee052218 100644--- a/letta/services/step_manager.py+++ b/letta/services/step_manager.py@@ -2,6 +2,7 @@ from datetime import datetimefrom typing import List, Literal, Optionalfrom sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import Sessionfrom letta.orm.errors import NoResultFound@@ -58,6 +59,7 @@ class StepManager:actor: PydanticUser,agent_id: str,provider_name: str,+ provider_category: str,model: str,model_endpoint: Optional[str],context_window_limit: int,@@ -72,6 +74,7 @@ class StepManager:"agent_id": agent_id,"provider_id": provider_id,"provider_name": provider_name,+ "provider_category": provider_category,"model": model,"model_endpoint": model_endpoint,"context_window_limit": context_window_limit,@@ -98,6 +101,7 @@ class StepManager:actor: PydanticUser,agent_id: str,provider_name: str,+ provider_category: str,model: str,model_endpoint: Optional[str],context_window_limit: int,@@ -112,6 +116,7 @@ class StepManager:"agent_id": agent_id,"provider_id": provider_id,"provider_name": provider_name,+ "provider_category": provider_category,"model": model,"model_endpoint": model_endpoint,"context_window_limit": context_window_limit,@@ -127,7 +132,7 @@ class StepManager:step_data["id"] = step_idasync with db_registry.async_session() as session:if job_id:- self._verify_job_access(session, job_id, actor, access=["write"])+ await self._verify_job_access_async(session, job_id, actor, access=["write"])new_step = StepModel(**step_data)await new_step.create_async(session)return new_step.to_pydantic()@@ -192,6 +197,35 @@ class StepManager:raise NoResultFound(f"Job with id {job_id} does not exist or user does not have access")return job+ async def _verify_job_access_async(+ self,+ session: AsyncSession,+ job_id: str,+ actor: PydanticUser,+ access: List[Literal["read", "write", "delete"]] = ["read"],+ ) -> JobModel:+ """+ Verify that a job exists and the user has the required access asynchronously.++ Args:+ session: The async database session+ job_id: The ID of the job to verify+ actor: The user making the request++ Returns:+ The job if it exists and the user has access++ Raises:+ NoResultFound: If the job does not exist or user does not have access+ """+ job_query = select(JobModel).where(JobModel.id == job_id)+ job_query = JobModel.apply_access_predicate(job_query, actor, access, AccessType.USER)+ result = await session.execute(job_query)+ job = result.scalar_one_or_none()+ if not job:+ raise NoResultFound(f"Job with id {job_id} does not exist or user does not have access")+ return job+@singletonclass NoopStepManager(StepManager):@@ -207,6 +241,7 @@ class NoopStepManager(StepManager):actor: PydanticUser,agent_id: str,provider_name: str,+ provider_category: str,model: str,model_endpoint: Optional[str],context_window_limit: int,@@ -223,6 +258,7 @@ class NoopStepManager(StepManager):actor: PydanticUser,agent_id: str,provider_name: str,+ provider_category: str,model: str,model_endpoint: Optional[str],context_window_limit: int,@@ -231,4 +267,29 @@ class NoopStepManager(StepManager):job_id: Optional[str] = None,step_id: Optional[str] = None,) -> PydanticStep:- return+ step_data = {+ "origin": None,+ "organization_id": actor.organization_id,+ "agent_id": agent_id,+ "provider_id": provider_id,+ "provider_name": provider_name,+ "provider_category": provider_category,+ "model": model,+ "model_endpoint": model_endpoint,+ "context_window_limit": context_window_limit,+ "completion_tokens": usage.completion_tokens,+ "prompt_tokens": usage.prompt_tokens,+ "total_tokens": usage.total_tokens,+ "job_id": job_id,+ "tags": [],+ "tid": None,+ "trace_id": get_trace_id(), # Get the current trace ID+ }+ if step_id:+ step_data["id"] = step_id+ async with db_registry.async_session() as session:+ if job_id:+ await self._verify_job_access_async(session, job_id, actor, access=["write"])+ new_step = StepModel(**step_data)+ await new_step.create_async(session)+ return new_step.to_pydantic()diff --git a/tests/test_managers.py b/tests/test_managers.pyindex 58deb7483..561cb73ec 100644--- a/tests/test_managers.py+++ b/tests/test_managers.py@@ -4859,15 +4859,17 @@ def test_get_run_messages(server: SyncServer, default_user: PydanticUser, sarah_# ======================================================================================================================-def test_job_usage_stats_add_and_get(server: SyncServer, sarah_agent, default_job, default_user):+async def test_job_usage_stats_add_and_get(server: SyncServer, sarah_agent, default_job, default_user, event_loop):"""Test adding and retrieving job usage statistics."""job_manager = server.job_managerstep_manager = server.step_manager# Add usage statistics- step_manager.log_step(+ await step_manager.log_step_async(agent_id=sarah_agent.id,provider_name="openai",+ provider_category="base",model="gpt-4o-mini",model_endpoint="https://api.openai.com/v1",context_window_limit=8192,@@ -4910,15 +4912,17 @@ def test_job_usage_stats_get_no_stats(server: SyncServer, default_job, default_uassert len(steps) == 0-def test_job_usage_stats_add_multiple(server: SyncServer, sarah_agent, default_job, default_user):+async def test_job_usage_stats_add_multiple(server: SyncServer, sarah_agent, default_job, default_user, event_loop):"""Test adding multiple usage statistics entries for a job."""job_manager = server.job_managerstep_manager = server.step_manager# Add first usage statistics entry- step_manager.log_step(+ await step_manager.log_step_async(agent_id=sarah_agent.id,provider_name="openai",+ provider_category="base",model="gpt-4o-mini",model_endpoint="https://api.openai.com/v1",context_window_limit=8192,@@ -4932,9 +4936,10 @@ def test_job_usage_stats_add_multiple(server: SyncServer, sarah_agent, default_j)# Add second usage statistics entry- step_manager.log_step(+ await step_manager.log_step_async(agent_id=sarah_agent.id,provider_name="openai",+ provider_category="base",model="gpt-4o-mini",model_endpoint="https://api.openai.com/v1",context_window_limit=8192,@@ -4973,14 +4978,16 @@ def test_job_usage_stats_get_nonexistent_job(server: SyncServer, default_user):job_manager.get_job_usage(job_id="nonexistent_job", actor=default_user)-def test_job_usage_stats_add_nonexistent_job(server: SyncServer, sarah_agent, default_user):+async def test_job_usage_stats_add_nonexistent_job(server: SyncServer, sarah_agent, default_user, event_loop):"""Test adding usage statistics for a nonexistent job."""step_manager = server.step_managerwith pytest.raises(NoResultFound):- step_manager.log_step(+ await step_manager.log_step_async(agent_id=sarah_agent.id,provider_name="openai",+ provider_category="base",model="gpt-4o-mini",model_endpoint="https://api.openai.com/v1",context_window_limit=8192,