fix(client): use the effective model output budget for write_file (#8545)

* chore: initialize SDK write_file budget fix draft

* fix(client): use the effective model output budget for write_file

* test(client): update authorization tool stubs

---------

Co-authored-by: Leeminjing <247553113+Leeminjing@users.noreply.github.com>
This commit is contained in:
Lee minjing 2026-11-24 10:28:03 +08:00 committed by GitHub
parent f81d1633a4
commit fa20a53fa5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 59 additions and 29 deletions

View File

@ -31,6 +31,7 @@ from typing import Any, Literal
from langchain.agents import create_agent
from langchain.agents.middleware import AgentMiddleware
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import AIMessage, AIMessageChunk, HumanMessage, SystemMessage, ToolMessage
from langchain_core.runnables import RunnableConfig
@ -476,7 +477,12 @@ class DeerFlowClient:
)
max_total_subagents = effective_total_subagents_per_run(cfg.get("max_total_subagents"), self._app_config)
tools = self._get_tools(model_name=model_name, subagent_enabled=subagent_enabled, mcp_plugins=mcp_plugins, groups=tool_groups)
# attach_tracing=False because ``stream()`` injects tracing
# callbacks at the graph invocation root so a single embedded run
# produces one trace with correct session_id / user_id propagation.
# Attaching them again on the model would emit duplicate spans.
chat_model = create_chat_model(name=model_name, thinking_enabled=thinking_enabled, attach_tracing=False, model_overrides=agent_model_overrides)
tools = self._get_tools(model_name=model_name, subagent_enabled=subagent_enabled, mcp_plugins=mcp_plugins, groups=tool_groups, chat_model=chat_model)
# Add framework-provided tools before authorization so Layer 1 sees
# every capability that can become model-visible.
@ -548,11 +554,7 @@ class DeerFlowClient:
verify_declared_tool_view(bound_middlewares, authorized_names=declared_authorized)
kwargs: dict[str, Any] = {
# attach_tracing=False because ``stream()`` injects tracing
# callbacks at the graph invocation root so a single embedded run
# produces one trace with correct session_id / user_id propagation.
# Attaching them again on the model would emit duplicate spans.
"model": create_chat_model(name=model_name, thinking_enabled=thinking_enabled, attach_tracing=False, model_overrides=agent_model_overrides),
"model": chat_model,
"tools": final_tools,
"middleware": bound_middlewares,
"system_prompt": apply_prompt_template(
@ -586,11 +588,11 @@ class DeerFlowClient:
logger.info("Agent created: agent_name=%s, model=%s, thinking=%s", self._agent_name, model_name, thinking_enabled)
@staticmethod
def _get_tools(*, model_name: str | None, subagent_enabled: bool, mcp_plugins: list[str] | None = None, groups: list[str] | None = None):
def _get_tools(*, model_name: str | None, subagent_enabled: bool, chat_model: BaseChatModel, mcp_plugins: list[str] | None = None, groups: list[str] | None = None):
"""Lazy import to avoid circular dependency at module level."""
from deerflow.tools import get_available_tools
return get_available_tools(model_name=model_name, subagent_enabled=subagent_enabled, mcp_plugins=mcp_plugins, groups=groups)
return get_available_tools(model_name=model_name, subagent_enabled=subagent_enabled, mcp_plugins=mcp_plugins, groups=groups, chat_model=chat_model)
@staticmethod
def _serialize_tool_calls(tool_calls) -> list[dict]:

View File

@ -1582,21 +1582,23 @@ class TestClientMcpSelection:
class TestEnsureAgent:
@pytest.mark.parametrize(
("selection", "saved_model"),
("selection", "saved_model", "when_thinking_disabled"),
[
("agent", "agent-model"),
("constructor", "agent-model"),
("request", "agent-model"),
("global", "agent-model"),
("agent", ""),
("agent", "retired-profile"),
("constructor", "retired-profile"),
("request", "retired-profile"),
("invalid-constructor", "agent-model"),
("invalid-request", "agent-model"),
("agent", "agent-model", None),
("constructor", "agent-model", None),
("request", "agent-model", None),
("global", "agent-model", None),
("agent", "", None),
("agent", "retired-profile", None),
("constructor", "retired-profile", None),
("request", "retired-profile", None),
("invalid-constructor", "agent-model", None),
("invalid-request", "agent-model", None),
pytest.param("agent", "agent-model", {"max_tokens": 16}, id="thinking-disabled-lower-budget"),
pytest.param("agent", "agent-model", {"max_tokens": None}, id="thinking-disabled-uncapped"),
],
)
def test_named_agent_model_profile_reaches_provider(self, client, tmp_path, monkeypatch, selection, saved_model):
def test_named_agent_model_profile_reaches_provider(self, client, tmp_path, monkeypatch, selection, saved_model, when_thinking_disabled):
import httpx
from deerflow.config.app_config import AppConfig
@ -1620,10 +1622,21 @@ class TestEnsureAgent:
with httpx.Client(transport=httpx.MockTransport(respond)) as transport:
app_config = AppConfig(
models=[
{"name": name, "use": "langchain_openai:ChatOpenAI", "model": name, "api_key": "offline-placeholder", "http_client": transport, "use_responses_api": False, "temperature": 0.2, "max_tokens": 64}
{
"name": name,
"use": "langchain_openai:ChatOpenAI",
"model": name,
"api_key": "offline-placeholder",
"http_client": transport,
"use_responses_api": False,
"temperature": 0.2,
"max_tokens": 64,
"supports_thinking": True,
"when_thinking_disabled": when_thinking_disabled,
}
for name in ("global-default", "agent-model", "explicit-model")
],
tools=[],
tools=[{"name": "write_file", "group": "file:write", "use": "deerflow.sandbox.tools:write_file_tool"}],
sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"),
)
app_config.tool_search.enabled = False
@ -1633,6 +1646,8 @@ class TestEnsureAgent:
client._agent_name = None if selection == "global" else "researcher"
client._model_name = "explicit-model" if selection == "constructor" else "unknown-explicit" if selection == "invalid-constructor" else None
overrides = {"model_name": "explicit-model"} if selection == "request" else {"model_name": "unknown-explicit"} if selection == "invalid-request" else {}
if when_thinking_disabled is not None:
overrides["thinking_enabled"] = False
# Keep saved configuration, the real graph, model factory and SDK;
# isolate prompt/middleware work unrelated to model selection.
with (
@ -1651,11 +1666,22 @@ class TestEnsureAgent:
assert client.chat("Again", thread_id="model-profile", user_id="test-user", **overrides) == "Done"
expected_model = "explicit-model" if selection in {"constructor", "request"} else "global-default" if selection == "global" or saved_model in {"", "retired-profile"} else "agent-model"
expected_max_tokens = 64 if selection == "global" else 32
if when_thinking_disabled is not None:
expected_max_tokens = when_thinking_disabled["max_tokens"]
assert len(requests) == 2
for request in requests:
assert request["model"] == expected_model
assert request["temperature"] == (0.2 if selection == "global" else 0.7)
assert request["max_completion_tokens"] == (64 if selection == "global" else 32)
write_file = next(tool["function"] for tool in request["tools"] if tool["function"]["name"] == "write_file")
budget_notes = [line for line in write_file["description"].splitlines() if line.startswith("PER-RESPONSE BUDGET:")]
if expected_max_tokens is None:
assert "max_completion_tokens" not in request
assert not budget_notes
else:
assert request["max_completion_tokens"] == expected_max_tokens
assert len(budget_notes) == 1
assert budget_notes[0].startswith(f"PER-RESPONSE BUDGET: your output limit is {expected_max_tokens} tokens")
@pytest.mark.parametrize(
("groups", "expected"),

View File

@ -791,7 +791,7 @@ def _stub_client_assembly(monkeypatch) -> dict[str, str]:
)
monkeypatch.setattr("deerflow.client.create_agent", lambda **kwargs: object())
monkeypatch.setattr("deerflow.client.build_middlewares", lambda *args, **kwargs: [])
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **_: [])
monkeypatch.setattr("deerflow.client.get_enabled_skills_for_config", lambda app_config, **kw: []) # noqa: ARG005
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",

View File

@ -539,7 +539,7 @@ def test_client_ensure_agent_filters_skills_by_authorization(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", _capture_build_middlewares)
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **_: [])
monkeypatch.setattr("deerflow.client.get_enabled_skills_for_config", lambda app_config, **kw: [])
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
@ -592,7 +592,7 @@ def test_client_ensure_agent_noop_when_authorization_disabled(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", _capture_build_middlewares)
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **_: [])
monkeypatch.setattr("deerflow.client.get_enabled_skills_for_config", lambda app_config, **kw: [])
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
@ -884,7 +884,7 @@ def test_client_wires_skill_authorization_into_middleware(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", _capture_build_middlewares)
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **_: [])
monkeypatch.setattr("deerflow.client.get_enabled_skills_for_config", lambda app_config, **kw: [])
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
@ -969,7 +969,7 @@ def test_client_filter_candidates_reuse_catalog_loader(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", lambda *a, **kw: [])
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **_: [])
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
lambda skills, *, enabled, container_base_path, skill_authorization=None: SimpleNamespace(describe_skill_tool=None, skill_names=frozenset()),
@ -1151,7 +1151,7 @@ def test_client_skill_surface_uses_one_effective_user(monkeypatch):
monkeypatch.setattr("deerflow.client.create_chat_model", lambda **kw: object())
monkeypatch.setattr("deerflow.client.create_agent", lambda **kw: object())
monkeypatch.setattr("deerflow.client.build_middlewares", lambda *a, **kw: [])
monkeypatch.setattr("deerflow.client.DeerFlowClient._get_tools", staticmethod(lambda *, model_name, subagent_enabled, mcp_plugins=None, groups=None: [])) # noqa: ARG005
monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **_: [])
monkeypatch.setattr(
"deerflow.client.build_skill_search_setup",
lambda skills, *, enabled, container_base_path, skill_authorization=None: SimpleNamespace(describe_skill_tool=None, skill_names=frozenset()),

View File

@ -45,6 +45,8 @@ An empty or removed saved model falls back to the global default, matching the G
The agent's `model_settings` sampling overrides apply to the selected model,
as they do through the Gateway. Call `client.reset_agent()` after editing the
saved model configuration.
The [`write_file` budget hint](sandbox.md#sandbox--file-system) reflects the
effective model's output token limit after agent and thinking-mode overrides.
User messages are framed as untrusted input. Reserved XML-like tags are escaped
for model context only when present; tag-free URLs and shell commands retain