Skip to content

Build and run agents you can see, understand and trust.

fix(app): reject unusable saved context ratios (#3357)

ZxlDragonDoctor782bd43f9f61
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.py
index 589267b1f..012358e48 100644
--- a/src/agentscope/agent/_agent.py
+++ b/src/agentscope/agent/_agent.py
@@ -24,7 +24,13 @@ from typing import (
import jsonschema
from pydantic import BaseModel
-from ._config import ContextConfig, ReActConfig, ModelConfig, InjectionConfig
+from ._config import (
+ ContextConfig,
+ ReActConfig,
+ ModelConfig,
+ InjectionConfig,
+ _validate_context_config_ratios,
+)
from ..state import AgentState
from ..state._state import ReplyContext
from ._utils import _ToolCallBatch, Acting, Exit, Reasoning, _resolve_timezone
@@ -256,34 +262,10 @@ class Agent:
If the reserved/buffer ratios don't leave room ahead of the
context compression threshold.
"""
- if (
- self.context_config.reserve_ratio
- >= self.context_config.trigger_ratio
- ):
- raise ValueError(
- "The 'reserve_ratio' of the context config must be smaller "
- "than its 'trigger_ratio', got "
- f"{self.context_config.reserve_ratio} and "
- f"{self.context_config.trigger_ratio}.",
- )
-
- # The buffer is only consumed by the runtime state injection and
- # the compression tool, so it's checked only when one of them is on
- if (
- self.injection_config.inject_runtime_state
- or self.context_config.compression_tool_enabled
- ) and (
- self.context_config.context_buffer_ratio
- >= self.context_config.trigger_ratio
- ):
- raise ValueError(
- "The 'context_buffer_ratio' of the context config must be "
- "smaller than its 'trigger_ratio', so that the context "
- "length is injected and the compression tool takes effect "
- "before the hard compression, got "
- f"{self.context_config.context_buffer_ratio} and "
- f"{self.context_config.trigger_ratio}.",
- )
+ _validate_context_config_ratios(
+ self.context_config,
+ self.injection_config.inject_runtime_state,
+ )
# =======================================================================
# Agent public methods
diff --git a/src/agentscope/agent/_config.py b/src/agentscope/agent/_config.py
index e54f0c422..213a84898 100644
--- a/src/agentscope/agent/_config.py
+++ b/src/agentscope/agent/_config.py
@@ -192,6 +192,35 @@ class ContextConfig(BaseModel):
hint without path information."""
+def _validate_context_config_ratios(
+ context_config: ContextConfig,
+ inject_runtime_state: bool,
+) -> None:
+ """Validate that context compression thresholds leave room to operate."""
+ if context_config.reserve_ratio >= context_config.trigger_ratio:
+ raise ValueError(
+ "The 'reserve_ratio' of the context config must be smaller "
+ "than its 'trigger_ratio', got "
+ f"{context_config.reserve_ratio} and "
+ f"{context_config.trigger_ratio}.",
+ )
+
+ # The buffer is only consumed by runtime-state injection and the
+ # compression tool, so it is checked only when one of them is enabled.
+ if (
+ (inject_runtime_state or context_config.compression_tool_enabled)
+ and context_config.context_buffer_ratio >= context_config.trigger_ratio
+ ):
+ raise ValueError(
+ "The 'context_buffer_ratio' of the context config must be "
+ "smaller than its 'trigger_ratio', so that the context "
+ "length is injected and the compression tool takes effect "
+ "before the hard compression, got "
+ f"{context_config.context_buffer_ratio} and "
+ f"{context_config.trigger_ratio}.",
+ )
+
+
class InjectionConfig(BaseModel):
"""The state injection related configuration in AgentScope."""
diff --git a/src/agentscope/app/_router/_agent.py b/src/agentscope/app/_router/_agent.py
index 3b1580775..30dbad9c2 100644
--- a/src/agentscope/app/_router/_agent.py
+++ b/src/agentscope/app/_router/_agent.py
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import ValidationError
from ...agent import ContextConfig, ReActConfig
+from ...agent._config import _validate_context_config_ratios
from ..._utils._common import _flatten_json_schema
from ..access import ResourceKind
from ..deps import (
@@ -194,17 +195,25 @@ async def create_agent(
Raises:
`HTTPException`: 422 if the request body passes
:class:`CreateAgentRequest` validation but the resulting
- :class:`AgentData` fails its cross-field invariants (e.g.
- ``chat_config.invite_config.invitable=True`` without a
- non-empty ``invite_description``). Symmetrical with
- :func:`update_agent`.
+ :class:`AgentData` fails its cross-field invariants or its
+ context ratios are invalid for the default Agent runtime.
+ Symmetrical with :func:`update_agent`.
"""
try:
data = AgentData.model_validate(body.model_dump(exclude_none=True))
- except ValidationError as exc:
+ # Validate writes only, so old invalid records remain repairable.
+ _validate_context_config_ratios(
+ data.chat_config.context_config,
+ inject_runtime_state=True,
+ )
+ except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
- detail=exc.errors(),
+ detail=(
+ exc.errors(include_context=False)
+ if isinstance(exc, ValidationError)
+ else str(exc)
+ ),
) from exc
record = AgentRecord(user_id=user_id, data=data)
agent_id = await storage.upsert_agent(user_id, record)
@@ -240,7 +249,8 @@ async def update_agent(
Raises:
`HTTPException`: 404 if the agent is not visible to the caller;
- 403 if visible but only readable.
+ 403 if visible but only readable; 422 if the merged settings
+ violate configuration constraints.
"""
owner_id, existing = await access.resolve_for_edit(
user_id,
@@ -268,10 +278,18 @@ async def update_agent(
updated_data = AgentData.model_validate(
{**current_data, **updates},
)
- except ValidationError as exc:
+ _validate_context_config_ratios(
+ updated_data.chat_config.context_config,
+ inject_runtime_state=True,
+ )
+ except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
- detail=exc.errors(),
+ detail=(
+ exc.errors(include_context=False)
+ if isinstance(exc, ValidationError)
+ else str(exc)
+ ),
) from exc
updated_agent = existing.model_copy(
update={"data": updated_data, "updated_at": datetime.now()},
diff --git a/tests/agent_config_grouping_test.py b/tests/agent_config_grouping_test.py
index f0699cbd0..7c58e203b 100644
--- a/tests/agent_config_grouping_test.py
+++ b/tests/agent_config_grouping_test.py
@@ -152,6 +152,136 @@ class AgentConfigGroupingTest(IsolatedAsyncioTestCase):
],
)
+ def test_create_rejects_context_ratios_that_make_agent_unusable(
+ self,
+ ) -> None:
+ """POST rejects settings that Agent construction would reject."""
+ invalid_configs = (
+ {"trigger_ratio": 0.1},
+ {"trigger_ratio": 0.15},
+ {"context_buffer_ratio": 0.8},
+ )
+
+ for context_config in invalid_configs:
+ config = {"context_config": context_config}
+ payloads: tuple[dict[str, Any], ...] = (
+ config,
+ {"chat_config": config},
+ )
+ for payload in payloads:
+ with self.subTest(payload=payload):
+ response = self.client.post(
+ "/agent/",
+ headers=HEADERS,
+ json={"name": "invalid", **payload},
+ )
+ self.assertEqual(response.status_code, 422)
+
+ self.assertEqual(
+ self.client.get("/agent/", headers=HEADERS).json(),
+ {"agents": [], "total": 0},
+ )
+
+ valid = self.client.post(
+ "/agent/",
+ headers=HEADERS,
+ json={"name": "valid-default"},
+ )
+ self.assertEqual(valid.status_code, 201)
+
+ def test_update_rejects_invalid_context_ratio_without_mutating_record(
+ self,
+ ) -> None:
+ """PATCH rejects and does not persist a context ratio violation."""
+ agent_id = self.client.post(
+ "/agent/",
+ headers=HEADERS,
+ json={"name": "valid-agent"},
+ ).json()["agent_id"]
+
+ before = self.client.get("/agent/", headers=HEADERS).json()
+ config = {"context_config": {"trigger_ratio": 0.15}}
+ for payload in (config, {"chat_config": config}):
+ with self.subTest(payload=payload):
+ response = self.client.patch(
+ f"/agent/{agent_id}",
+ headers=HEADERS,
+ json=payload,
+ )
+ self.assertEqual(response.status_code, 422)
+ self.assertEqual(
+ response.json(),
+ {
+ "detail": (
+ "The 'context_buffer_ratio' of the context "
+ "config must be smaller than its "
+ "'trigger_ratio', so that the context length "
+ "is injected and the compression tool takes "
+ "effect before the hard compression, got "
+ "0.2 and 0.15."
+ ),
+ },
+ )
+ saved = self.client.get("/agent/", headers=HEADERS)
+ self.assertEqual(saved.status_code, 200)
+ self.assertEqual(saved.json(), before)
+
+ async def test_invalid_stored_ratios_allow_listing_repair_and_delete(
+ self,
+ ) -> None:
+ """Old invalid ratios remain readable and manageable after upgrade."""
+ record = AgentRecord(user_id="alice", data=AgentData(name="old"))
+ valid_data = record.data.model_dump(mode="json")
+ # Simulate an invalid record persisted by an older app version.
+ record.data.chat_config.context_config.trigger_ratio = 0.15
+ await self.storage.upsert_agent("alice", record)
+ healthy = AgentRecord(user_id="alice", data=AgentData(name="healthy"))
+ await self.storage.upsert_agent("alice", healthy)
+
+ listed = self.client.get("/agent/", headers=HEADERS)
+ self.assertEqual(listed.status_code, 200)
+ self.assertEqual(
+ {
+ **listed.json(),
+ "agents": sorted(
+ listed.json()["agents"],
+ key=lambda a: a["id"],
+ ),
+ },
+ {
+ "agents": sorted(
+ [
+ {**item.model_dump(mode="json"), "editable": True}
+ for item in (record, healthy)
+ ],
+ key=lambda a: a["id"],
+ ),
+ "total": 2,
+ },
+ )
+ repaired = self.client.patch(
+ f"/agent/{record.id}",
+ headers=HEADERS,
+ json={"chat_config": {"context_config": {"trigger_ratio": 0.8}}},
+ )
+ self.assertEqual(repaired.status_code, 200)
+ self.assertEqual(repaired.json()["data"], valid_data)
+ stored = await self.storage.get_agent("alice", record.id)
+ self.assertEqual(stored.data.model_dump(mode="json"), valid_data)
+
+ await self.storage.upsert_agent("alice", record)
+ deleted = self.client.delete(f"/agent/{record.id}", headers=HEADERS)
+ self.assertEqual(deleted.status_code, 204)
+ self.assertEqual(
+ self.client.get("/agent/", headers=HEADERS).json(),
+ {
+ "agents": [
+ {**healthy.model_dump(mode="json"), "editable": True},
+ ],
+ "total": 1,
+ },
+ )
+
def test_update_keeps_untouched_sub_configs(self) -> None:
"""A legacy PATCH replaces its own sub-config and nothing else."""
agent_id = self.client.post(
@@ -251,7 +381,10 @@ class AgentConfigGroupingTest(IsolatedAsyncioTestCase):
headers=HEADERS,
json={
"chat_config": {
- "context_config": {"max_image_num": 7},
+ "context_config": {
+ "max_image_num": 7,
+ "trigger_ratio": 0.15,
+ },
"react_config": {"max_iters": 11},
},
"context_config": {"max_image_num": 3},