fix(client): honor named agent model profiles (#8509)

* fix(client): honor named agent model profiles

* fix(client): fall back from retired saved model profiles
This commit is contained in:
ZephyrWang 2026-11-23 20:38:14 +08:00 committed by GitHub
parent 7076409781
commit e212596a02
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 91 additions and 2 deletions

View File

@ -34,7 +34,7 @@ from langchain.agents.middleware import AgentMiddleware
from langchain_core.messages import AIMessage, AIMessageChunk, HumanMessage, SystemMessage, ToolMessage
from langchain_core.runnables import RunnableConfig
from deerflow.agents.lead_agent.agent import _authorize_model_name, build_middlewares
from deerflow.agents.lead_agent.agent import _authorize_model_name, _resolve_model_name, build_middlewares
from deerflow.agents.lead_agent.prompt import apply_prompt_template, get_enabled_skills_for_config, has_bash_tool
from deerflow.agents.middlewares.tool_declarations import layer_one_outcome, narrow_declared_tools, verify_declared_tool_view
from deerflow.agents.thread_state import get_thread_state_schema, normalize_middleware_state_schemas
@ -402,6 +402,12 @@ class DeerFlowClient:
thinking_enabled = cfg.get("thinking_enabled", True)
model_name = cfg.get("model_name")
if model_name is None:
model_name = getattr(agent_config, "model", None)
if model_name is not None:
model_name = _resolve_model_name(model_name, app_config=self._app_config)
agent_model_settings = getattr(agent_config, "model_settings", None)
agent_model_overrides = agent_model_settings.model_dump(exclude_none=True) if agent_model_settings else None
# Phase 3: enforce model:use authorization on the embedded/library path
# too, mirroring the Gateway runtime path in ``_make_lead_agent`` so the
# role-scoped model policy cannot be bypassed by constructing the agent
@ -546,7 +552,7 @@ class DeerFlowClient:
# 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": create_chat_model(name=model_name, thinking_enabled=thinking_enabled, attach_tracing=False, model_overrides=agent_model_overrides),
"tools": final_tools,
"middleware": bound_middlewares,
"system_prompt": apply_prompt_template(

View File

@ -1581,6 +1581,82 @@ class TestClientMcpSelection:
class TestEnsureAgent:
@pytest.mark.parametrize(
("selection", "saved_model"),
[
("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"),
],
)
def test_named_agent_model_profile_reaches_provider(self, client, tmp_path, monkeypatch, selection, saved_model):
import httpx
from deerflow.config.app_config import AppConfig
from deerflow.config.sandbox_config import SandboxConfig
paths = Paths(tmp_path)
monkeypatch.setattr("deerflow.config.paths._paths", paths)
agent_dir = paths.user_agent_dir("test-user", "researcher")
agent_dir.mkdir(parents=True)
(agent_dir / "config.yaml").write_text(
f"name: researcher\nmodel: {json.dumps(saved_model)}\nmodel_settings:\n temperature: 0.7\n max_tokens: 32\n",
encoding="utf-8",
)
requests = []
def respond(request):
requests.append(json.loads(request.content))
chunk = {"id": "chatcmpl-profile", "choices": [{"index": 0, "delta": {"content": "Done"}, "finish_reason": "stop"}]}
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n")
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}
for name in ("global-default", "agent-model", "explicit-model")
],
tools=[],
sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"),
)
app_config.tool_search.enabled = False
monkeypatch.setattr("deerflow.config.app_config._app_config", app_config)
monkeypatch.setattr("deerflow.config.app_config._app_config_is_custom", True)
client._app_config = app_config
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 {}
# Keep saved configuration, the real graph, model factory and SDK;
# isolate prompt/middleware work unrelated to model selection.
with (
patch("deerflow.client.build_middlewares", return_value=[]),
patch("deerflow.client.apply_prompt_template", return_value="Answer briefly."),
patch("deerflow.client.get_enabled_skills_for_config", return_value=[]),
patch.object(ExtensionsConfig, "from_file", return_value=ExtensionsConfig()),
patch("deerflow.runtime.checkpointer.get_checkpointer", return_value=None),
):
if selection.startswith("invalid-"):
with pytest.raises(ValueError, match="unknown-explicit"):
client.chat("Hello", thread_id="model-profile", user_id="test-user", **overrides)
assert requests == []
return
assert client.chat("Hello", thread_id="model-profile", user_id="test-user", **overrides) == "Done"
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"
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)
@pytest.mark.parametrize(
("groups", "expected"),
[(None, {"read_file", "write_file"}), ([], set()), (["file:read"], {"read_file"})],

View File

@ -39,6 +39,13 @@ managed-subagent writes and requires `subagents:write` from an admin token owner
## Embedded Python Client
For a named agent, `DeerFlowClient` uses the saved `model` before the global
default. An explicit constructor or per-call `model_name` takes precedence.
An empty or removed saved model falls back to the global default, matching the Gateway.
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.
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
their ampersands unchanged. Encoded payloads include a note to decode exactly