Skip to content

The agent that grows with you

fix(plugins): complete task-routed LLM integration

Magnus Hedemark79c11aea7ae6
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 99da9ee2f79..c04c99215b5 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -3149,6 +3149,17 @@ def _set_relay_auxiliary_route(
context["api_mode"] = str(api_mode or "chat_completions")
+def _record_route_info(
+ route_info: Optional[Dict[str, str]],
+ provider: Optional[str],
+ model: Optional[str],
+) -> None:
+ """Expose the concrete route selected for one auxiliary call."""
+ if route_info is not None:
+ route_info["provider"] = provider or "auto"
+ route_info["model"] = model or "default"
+
+
def _relay_auxiliary_metadata(
*,
provider: str | None = None,
@@ -4809,7 +4820,10 @@ def _fallback_entry_timeout(task: Optional[str], fb_label: str) -> Optional[floa
def _fallback_provider_from_label(label: str) -> str:
"""Recover the provider identifier from a fallback display label."""
- match = re.match(r"(?:fallback_chain\[\d+\]|main-agent)\(([^)]+)\)$", label or "")
+ match = re.match(
+ r"(?:fallback_chain\[\d+\]|fallback_providers\[\d+\]|main-agent)\(([^)]+)\)$",
+ label or "",
+ )
return match.group(1).strip() if match else str(label or "").strip()
@@ -8881,6 +8895,7 @@ def call_llm(
api_mode: str = None,
stream: bool = False,
stream_options: dict = None,
+ route_info: Optional[Dict[str, str]] = None,
) -> Any:
"""Run an auxiliary LLM request, applying the configured task limit."""
semaphore = _acquire_sync_aux_semaphore(task)
@@ -8905,6 +8920,7 @@ def call_llm(
api_mode=api_mode,
stream=stream,
stream_options=stream_options,
+ route_info=route_info,
)
if stream and semaphore is not None:
stream_semaphore = semaphore
@@ -8950,6 +8966,7 @@ def _call_llm_impl(
api_mode: str = None,
stream: bool = False,
stream_options: dict = None,
+ route_info: Optional[Dict[str, str]] = None,
) -> Any:
"""Centralized synchronous LLM call.
@@ -9088,6 +9105,9 @@ def _call_llm_impl(
final_model,
resolved_api_mode,
)
+ _record_route_info(
+ route_info, _fallback_provider_from_label(request_provider), final_model
+ )
# Log what we're about to do — makes auxiliary operations visible
_base_info = str(getattr(client, "base_url", resolved_base_url) or "")
@@ -9607,6 +9627,9 @@ def _call_llm_impl(
failed_model=_chain_failed_model)
if fb_client is not None:
+ _record_route_info(
+ route_info, _fallback_provider_from_label(fb_label), fb_model
+ )
fb_resp = _call_fallback_candidate_sync(
fb_client, fb_model, fb_label,
task=task, messages=messages,
@@ -9622,6 +9645,9 @@ def _call_llm_impl(
fb_client, fb_model, fb_label = _try_payment_fallback(
resolved_provider, task, reason="stale fallback credential")
if fb_client is not None:
+ _record_route_info(
+ route_info, _fallback_provider_from_label(fb_label), fb_model
+ )
fb_resp = _call_fallback_candidate_sync(
fb_client, fb_model, fb_label,
task=task, messages=messages,
@@ -9725,6 +9751,7 @@ async def async_call_llm(
timeout: float = None,
extra_body: dict = None,
reasoning_config: Optional[dict] = None,
+ route_info: Optional[Dict[str, str]] = None,
) -> Any:
"""Run an asynchronous auxiliary LLM request under the configured limit."""
semaphore = _acquire_async_aux_semaphore(task)
@@ -9745,6 +9772,7 @@ async def async_call_llm(
timeout=timeout,
extra_body=extra_body,
reasoning_config=reasoning_config,
+ route_info=route_info,
)
finally:
if semaphore is not None:
@@ -9766,6 +9794,7 @@ async def _async_call_llm_impl(
timeout: float = None,
extra_body: dict = None,
reasoning_config: Optional[dict] = None,
+ route_info: Optional[Dict[str, str]] = None,
) -> Any:
"""Centralized asynchronous LLM call.
@@ -9862,6 +9891,9 @@ async def _async_call_llm_impl(
final_model,
resolved_api_mode,
)
+ _record_route_info(
+ route_info, _fallback_provider_from_label(request_provider), final_model
+ )
# Pass the client's actual base_url (not just resolved_base_url) so
# endpoint-specific temperature overrides can distinguish
@@ -10263,6 +10295,11 @@ async def _async_call_llm_impl(
async_fb, async_fb_model = _to_async_client(
fb_client, fb_model or "", is_vision=(task == "vision")
)
+ _record_route_info(
+ route_info,
+ _fallback_provider_from_label(fb_label),
+ async_fb_model or fb_model,
+ )
fb_resp = await _call_fallback_candidate_async(
async_fb, async_fb_model or fb_model, fb_label,
task=task, messages=messages,
@@ -10280,6 +10317,11 @@ async def _async_call_llm_impl(
async_fb, async_fb_model = _to_async_client(
fb_client, fb_model or "", is_vision=(task == "vision")
)
+ _record_route_info(
+ route_info,
+ _fallback_provider_from_label(fb_label),
+ async_fb_model or fb_model,
+ )
fb_resp = await _call_fallback_candidate_async(
async_fb, async_fb_model or fb_model, fb_label,
task=task, messages=messages,
diff --git a/agent/plugin_llm.py b/agent/plugin_llm.py
index 6086636aec2..e0cc8ccca58 100644
--- a/agent/plugin_llm.py
+++ b/agent/plugin_llm.py
@@ -656,6 +656,7 @@ def _resolve_attribution(
provider_override: Optional[str],
model_override: Optional[str],
response: Any,
+ route_info: Optional[Dict[str, str]] = None,
) -> tuple[str, str]:
"""Decide what to record as ``result.provider`` / ``result.model``.
@@ -664,20 +665,24 @@ def _resolve_attribution(
1. Explicit overrides win — if the plugin asked for ``provider="x"``
or ``model="y"``, that's what we record (it's what the call
actually targeted).
- 2. Otherwise we ask the host for the current main provider/model
- via :func:`_read_main_provider` / :func:`_read_main_model`, since
- those are what ``call_llm`` resolves to when ``provider=None``
- and ``model=None`` are passed through. They reflect runtime
- overrides set by ``set_runtime_main()``.
- 3. ``response.model`` (if present) overrides the recorded model
+ 2. ``response.model`` (if present) overrides the recorded model
string. Providers post-resolution often return a slightly
different model id than the request (e.g. ``gpt-4o`` →
``gpt-4o-2024-08-06``); the plugin's audit log should reflect
what actually ran.
- 4. If everything above is empty, fall back to ``"auto"`` /
+ 3. The route selected by ``auxiliary_client`` supplies the provider/model
+ when no override or response model is available.
+ 4. Otherwise the current main provider/model is used.
+ 5. If everything above is empty, fall back to ``"auto"`` /
``"default"`` so the result object has non-empty strings.
"""
- if provider_override:
+ route_info = route_info or {}
+ route_provider = route_info.get("provider")
+ route_model = route_info.get("model")
+
+ if route_provider:
+ provider = route_provider
+ elif provider_override:
provider = provider_override
else:
try:
@@ -689,6 +694,8 @@ def _resolve_attribution(
response_model = getattr(response, "model", None)
if isinstance(response_model, str) and response_model.strip():
model = response_model.strip()
+ elif route_model:
+ model = route_model
elif model_override:
model = model_override
else:
@@ -938,7 +945,7 @@ class PluginLlm:
)
text = _extract_text(response)
usage = _extract_usage(response)
- return PluginLlmCompleteResult(
+ result = PluginLlmCompleteResult(
text=text,
provider=real_provider,
model=real_model,
@@ -951,6 +958,13 @@ class PluginLlm:
"task": eff_task or "",
},
)
+ logger.info(
+ "plugin_llm.acomplete plugin=%s provider=%s model=%s task=%s "
+ "purpose=%s tokens=%d",
+ self._plugin_id, real_provider, real_model, eff_task or "",
+ purpose or "", usage.total_tokens,
+ )
+ return result
async def acomplete_structured(
self,
@@ -1011,7 +1025,7 @@ class PluginLlm:
parsed, content_type = _parse_structured_text(
text=text, json_mode=json_mode, json_schema=json_schema
)
- return PluginLlmStructuredResult(
+ result = PluginLlmStructuredResult(
text=text,
provider=real_provider,
model=real_model,
@@ -1027,6 +1041,13 @@ class PluginLlm:
"task": eff_task or "",
},
)
+ logger.info(
+ "plugin_llm.acomplete_structured plugin=%s provider=%s model=%s "
+ "task=%s purpose=%s content_type=%s tokens=%d",
+ self._plugin_id, real_provider, real_model, eff_task or "",
+ purpose or "", content_type, usage.total_tokens,
+ )
+ return result
# -- internals ---------------------------------------------------------
@@ -1088,6 +1109,7 @@ class PluginLlm:
merged_extra = dict(extra_body or {})
if profile_override:
merged_extra.setdefault("metadata", {})["auth_profile"] = profile_override
+ route_info: Optional[Dict[str, str]] = {} if task else None
response = call_llm(
task=task,
provider=provider_override,
@@ -1097,11 +1119,13 @@ class PluginLlm:
max_tokens=max_tokens,
timeout=timeout,
extra_body=merged_extra or None,
+ route_info=route_info,
)
provider, model = _resolve_attribution(
provider_override=provider_override,
model_override=model_override,
response=response,
+ route_info=route_info,
)
return provider, model, response
@@ -1134,6 +1158,7 @@ class PluginLlm:
merged_extra = dict(extra_body or {})
if profile_override:
merged_extra.setdefault("metadata", {})["auth_profile"] = profile_override
+ route_info: Optional[Dict[str, str]] = {} if task else None
response = await async_call_llm(
task=task,
provider=provider_override,
@@ -1143,11 +1168,13 @@ class PluginLlm:
max_tokens=max_tokens,
timeout=timeout,
extra_body=merged_extra or None,
+ route_info=route_info,
)
provider, model = _resolve_attribution(
provider_override=provider_override,
model_override=model_override,
response=response,
+ route_info=route_info,
)
return provider, model, response
diff --git a/tests/agent/test_plugin_llm_task_routing.py b/tests/agent/test_plugin_llm_task_routing.py
index 3757c6e94e1..a4682d04634 100644
--- a/tests/agent/test_plugin_llm_task_routing.py
+++ b/tests/agent/test_plugin_llm_task_routing.py
@@ -23,6 +23,7 @@ from agent.plugin_llm import (
PluginLlmTrustError,
PluginLlmTextInput,
_check_task,
+ _resolve_attribution,
_resolve_task_ownership,
_TrustPolicy,
make_plugin_llm_for_test,
@@ -239,6 +240,19 @@ class TestRouting:
# The caller must never run for a rejected task — no wrong-model call.
assert captured == {}
+ def test_unknown_task_raises_before_invoking_caller(self, monkeypatch):
+ _set_registry(monkeypatch, [])
+ _set_builtins(monkeypatch, [])
+ captured: Dict[str, Any] = {}
+ llm = make_plugin_llm_for_test(
+ plugin_id="my-plugin",
+ policy=_policy(),
+ sync_caller=_capturing_caller(captured),
+ )
+ with pytest.raises(PluginLlmTrustError):
+ llm.complete([{"role": "user", "content": "hi"}], task="unknown")
+ assert captured == {}
+
def test_structured_routes_task(self, monkeypatch):
_set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])
_set_builtins(monkeypatch, [])
@@ -290,25 +304,81 @@ class TestRouting:
assert captured["task"] == "classifier"
assert result.audit["task"] == "classifier"
+ def test_async_variants_log_exact_route(self, monkeypatch, caplog):
+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])
+ _set_builtins(monkeypatch, [])
+ llm = make_plugin_llm_for_test(
+ plugin_id="my-plugin",
+ policy=_policy(),
+ async_caller=_async_capturing_caller({}),
+ )
+
+ with caplog.at_level(logging.INFO, logger="agent.plugin_llm"):
+ asyncio.run(
+ llm.acomplete(
+ [{"role": "user", "content": "hi"}],
+ task="classifier",
+ purpose="plain",
+ )
+ )
+ asyncio.run(
+ llm.acomplete_structured(
+ instructions="classify",
+ input=[PluginLlmTextInput(text="payload")],
+ task="classifier",
+ purpose="structured",
+ )
+ )
+
+ messages = [record.getMessage() for record in caplog.records]
+ assert any(
+ "plugin_llm.acomplete plugin=my-plugin provider=aux-provider "
+ "model=aux-model task=classifier purpose=plain tokens=8" in message
+ for message in messages
+ )
+ assert any(
+ "plugin_llm.acomplete_structured plugin=my-plugin provider=aux-provider "
+ "model=aux-model task=classifier purpose=structured "
+ "content_type=text tokens=8" in message
+ for message in messages
+ )
+
+
+def test_successful_fallback_route_beats_requested_route_for_attribution():
+ provider, model = _resolve_attribution(
+ provider_override="primary-provider",
+ model_override="primary-model",
+ response=_fake_response(),
+ route_info={"provider": "fallback-provider", "model": "fallback-model"},
+ )
+ assert (provider, model) == ("fallback-provider", "fallback-model")
+
class TestForwardsToCallLlm:
"""Cover the production ``_invoke_*`` path (no injected caller), which is
where the previously-hardcoded ``task=None`` is replaced by the routed
key. The injected-caller tests above bypass this line."""
- def test_sync_forwards_task_to_call_llm(self, monkeypatch):
+ def test_sync_task_uses_auxiliary_attribution_and_log(self, monkeypatch, caplog):
_set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])
_set_builtins(monkeypatch, [])
seen: Dict[str, Any] = {}
def fake_call_llm(**kwargs: Any):
seen.update(kwargs)
+ kwargs["route_info"].update(provider="aux-provider", model="aux-model")
return _fake_response()
monkeypatch.setattr("agent.auxiliary_client.call_llm", fake_call_llm)
llm = make_plugin_llm_for_test(plugin_id="my-plugin", policy=_policy())
- llm.complete([{"role": "user", "content": "hi"}], task="classifier")
+ with caplog.at_level(logging.INFO, logger="agent.plugin_llm"):
+ result = llm.complete([{"role": "user", "content": "hi"}], task="classifier")
assert seen["task"] == "classifier"
+ assert (result.provider, result.model) == ("aux-provider", "aux-model")
+ assert any(
+ "provider=aux-provider model=aux-model task=classifier" in record.getMessage()
+ for record in caplog.records
+ )
def test_sync_default_forwards_task_none(self, monkeypatch):
_set_registry(monkeypatch, [])
@@ -324,21 +394,23 @@ class TestForwardsToCallLlm:
llm.complete([{"role": "user", "content": "hi"}])
assert seen["task"] is None
- def test_async_forwards_task_to_async_call_llm(self, monkeypatch):
+ def test_async_task_uses_auxiliary_attribution(self, monkeypatch):
_set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])
_set_builtins(monkeypatch, [])
seen: Dict[str, Any] = {}
async def fake_async_call_llm(**kwargs: Any):
seen.update(kwargs)
+ kwargs["route_info"].update(provider="aux-provider", model="aux-model")
return _fake_response()
monkeypatch.setattr("agent.auxiliary_client.async_call_llm", fake_async_call_llm)
llm = make_plugin_llm_for_test(plugin_id="my-plugin", policy=_policy())
- asyncio.run(
+ result = asyncio.run(
llm.acomplete([{"role": "user", "content": "hi"}], task="classifier")
)
assert seen["task"] == "classifier"
+ assert (result.provider, result.model) == ("aux-provider", "aux-model")
# ---------------------------------------------------------------------------
@@ -397,3 +469,191 @@ class TestOwnershipIntegration:
_check_task(
_policy(plugin_id="other"), plugin_id="other", requested_task="classifier"
)
+
+ def test_auto_task_reports_configured_fallback_provider_and_model(self, tmp_path, monkeypatch):
+ from agent import auxiliary_client as auxiliary_mod
+ from hermes_cli import config as config_mod
+
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text(
+ """
+auxiliary:
+ classifier:
+ provider: auto
+ fallback_chain:
+ - provider: fallback-provider
+ model: fallback-model
+""",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setattr(config_mod, "_LOAD_CONFIG_CACHE", {})
+ monkeypatch.setattr(config_mod, "_RAW_CONFIG_CACHE", {})
+
+ manager = self._make_manager()
+ ctx = self._register(manager, name="my-plugin", key="my-plugin", task_key="classifier")
+ monkeypatch.setattr("hermes_cli.plugins._ensure_plugins_discovered", lambda: manager)
+ _set_builtins(monkeypatch, [])
+ monkeypatch.setattr("agent.auxiliary_client._read_main_provider", lambda: "")
+ monkeypatch.setattr("agent.auxiliary_client._read_main_model", lambda: "")
+
+ captured: Dict[str, Any] = {}
+ client = SimpleNamespace(
+ chat=SimpleNamespace(
+ completions=SimpleNamespace(create=lambda **_kwargs: _fake_response())
+ )
+ )
+
+ real_provider_client = auxiliary_mod.resolve_provider_client
+
+ def fake_provider_client(provider, model, _async_mode=False, **kwargs):
+ if provider == "auto":
+ return real_provider_client(provider, model, _async_mode, **kwargs)
+ captured.update(provider=provider, model=model, **kwargs)
+ return client, model
+
+ monkeypatch.setattr(
+ "agent.auxiliary_client.resolve_provider_client", fake_provider_client
+ )
+
+ result = ctx.llm.complete(
+ [{"role": "user", "content": "hi"}], task="classifier"
+ )
+
+ assert (captured["provider"], captured["model"]) == (
+ "fallback-provider", "fallback-model"
+ )
+ assert (result.provider, result.model) == (
+ "fallback-provider", "fallback-model"
+ )
+
+ def test_async_auto_resolution_preserves_route_provider(self, monkeypatch):
+ from agent import auxiliary_client
+
+ sync_client = SimpleNamespace()
+ async_client = SimpleNamespace()
+ monkeypatch.setattr(
+ auxiliary_client,
+ "_resolve_auto_route",
+ lambda **_kwargs: (sync_client, "fallback-model", "fallback-provider"),
+ )
+ monkeypatch.setattr(
+ auxiliary_client,
+ "_to_async_client",
+ lambda _client, model, **_kwargs: (async_client, model),
+ )
+
+ resolved_client, model = auxiliary_client.resolve_provider_client(
+ "auto", async_mode=True, task="classifier"
+ )
+
+ assert resolved_client is async_client
+ assert auxiliary_client._effective_provider_for_client(
+ resolved_client, "auto"
+ ) == "fallback-provider"
+ assert model == "fallback-model"
+
+ def test_sync_fallback_reports_the_successful_route(self, tmp_path, monkeypatch):
+ from hermes_cli import config as config_mod
+
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text(
+ """
+auxiliary:
+ classifier:
+ provider: primary-provider
+ model: primary-model
+ fallback_chain:
+ - provider: fallback-provider
+ model: fallback-model
+""",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setattr(config_mod, "_LOAD_CONFIG_CACHE", {})
+ monkeypatch.setattr(config_mod, "_RAW_CONFIG_CACHE", {})
+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])
+ _set_builtins(monkeypatch, [])
+
+ def fail(**_kwargs):
+ raise ConnectionError("connection refused")
+
+ failed_client = SimpleNamespace(
+ chat=SimpleNamespace(completions=SimpleNamespace(create=fail))
+ )
+ fallback_client = SimpleNamespace(
+ chat=SimpleNamespace(completions=SimpleNamespace(create=lambda **_kwargs: _fake_response()))
+ )
+ monkeypatch.setattr(
+ "agent.auxiliary_client._get_cached_client",
+ lambda provider, model, **_kwargs: (failed_client, model),
+ )
+ monkeypatch.setattr(
+ "agent.auxiliary_client.resolve_provider_client",
+ lambda provider, model, **_kwargs: (fallback_client, model),
+ )
+ monkeypatch.setattr("agent.auxiliary_client._transient_retry_count", lambda: 0)
+
+ result = make_plugin_llm_for_test(
+ plugin_id="my-plugin", policy=_policy()
+ ).complete([{"role": "user", "content": "hi"}], task="classifier")
+
+ assert (result.provider, result.model) == ("fallback-provider", "fallback-model")
+
+ def test_async_fallback_reports_the_successful_route(self, tmp_path, monkeypatch):
+ from hermes_cli import config as config_mod
+
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text(
+ """
+auxiliary:
+ classifier:
+ provider: primary-provider
+ model: primary-model
+ fallback_chain:
+ - provider: fallback-provider
+ model: fallback-model
+""",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setattr(config_mod, "_LOAD_CONFIG_CACHE", {})
+ monkeypatch.setattr(config_mod, "_RAW_CONFIG_CACHE", {})
+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])
+ _set_builtins(monkeypatch, [])
+
+ async def fail(**_kwargs):
+ raise ConnectionError("connection refused")
+
+ async def succeed(**_kwargs):
+ return _fake_response()
+
+ failed_client = SimpleNamespace(
+ chat=SimpleNamespace(completions=SimpleNamespace(create=fail))
+ )
+ fallback_client = SimpleNamespace(
+ chat=SimpleNamespace(completions=SimpleNamespace(create=succeed))
+ )
+ monkeypatch.setattr(
+ "agent.auxiliary_client._get_cached_client",
+ lambda provider, model, **_kwargs: (failed_client, model),
+ )
+ monkeypatch.setattr(
+ "agent.auxiliary_client.resolve_provider_client",
+ lambda provider, model, **_kwargs: (fallback_client, model),
+ )
+ monkeypatch.setattr(
+ "agent.auxiliary_client._to_async_client",
+ lambda client, model, **_kwargs: (client, model),
+ )
+
+ result = asyncio.run(
+ make_plugin_llm_for_test(plugin_id="my-plugin", policy=_policy()).acomplete(
+ [{"role": "user", "content": "hi"}], task="classifier"
+ )
+ )
+
+ assert (result.provider, result.model) == ("fallback-provider", "fallback-model")
diff --git a/website/docs/developer-guide/plugin-llm-access.md b/website/docs/developer-guide/plugin-llm-access.md
index 0d7959f519d..f6eeee09cdf 100644
--- a/website/docs/developer-guide/plugin-llm-access.md
+++ b/website/docs/developer-guide/plugin-llm-access.md
@@ -223,6 +223,7 @@ result = ctx.llm.complete(
agent_id=None, # optional, gated
profile=None, # optional, gated — explicit auth-profile name
purpose="optional-audit-string",
+ task=None, # optional — a plugin-registered auxiliary slot
)
# → PluginLlmCompleteResult(text, provider, model, agent_id, usage, audit)
```
@@ -260,6 +261,7 @@ result = ctx.llm.complete_structured(
agent_id=None,
profile=None,
purpose=None,
+ task=None, # optional — a plugin-registered auxiliary slot
)
# → PluginLlmStructuredResult(text, provider, model, agent_id,
# usage, parsed, content_type, audit)
@@ -279,14 +281,49 @@ against your schema if `jsonschema` is installed.
### Async
```python
-result = await ctx.llm.acomplete(messages=...)
-result = await ctx.llm.acomplete_structured(instructions=..., input=...)
+result = await ctx.llm.acomplete(messages=..., task="classifier")
+result = await ctx.llm.acomplete_structured(
+ instructions=..., input=..., task="classifier"
+)
```
Same arguments and result types as their sync counterparts. Use
these from gateway adapters, async hooks, or any plugin code
already running on an asyncio loop.
+### Task-routed auxiliary calls
+
+Pass `task=` to any of the four call shapes when a plugin needs its
+own configured auxiliary route. Register that task during plugin setup;
+plugin defaults apply until the operator overrides its provider and model
+in `auxiliary.<task>`:
+
+```python
+def register(ctx):
+ ctx.register_auxiliary_task(
+ "classifier", display_name="Classifier", description="Classify input."
+ )
+
+
+result = ctx.llm.complete(messages=[...], task="classifier")
+result = ctx.llm.complete_structured(instructions=..., input=..., task="classifier")
+```
+
+```yaml
+auxiliary:
+ classifier:
+ provider: openrouter
+ model: vendor/model-id
+```
+
+Plugins may supply provider/model registration defaults for their own
+tasks. Operator configuration in `auxiliary.<task>` overrides those
+defaults and controls the deployment choice. A plugin can only use a task
+it registered itself; unknown or foreign task names fail before provider
+invocation. `allow_task_override: true` is an explicit operator grant for
+using Hermes built-in auxiliary tasks; it does not permit another plugin's
+tasks. Omit `task=` (or use `"auto"`) to keep the active main provider/model.
+
### Result attributes
```python
@@ -324,6 +361,8 @@ config block, a plugin can:
…and that's it. `provider=`, `model=`, `agent_id=`, and `profile=`
arguments raise `PluginLlmTrustError` until the operator opts in.
+Likewise, `task=` can use only the plugin's registered auxiliary task
+unless the operator grants `allow_task_override` for a built-in task.
**Most plugins never need this section.** A plugin that just calls
`ctx.llm.complete(messages=...)` with no overrides runs against
@@ -378,6 +417,7 @@ path-derived key for nested plugins (`image_gen/openai`,
| ↳ allowlist | — | `allowed_models: [...]` |
| `agent_id=` | denied | `allow_agent_id_override: true` |
| `profile=` | denied | `allow_profile_override: true` |
+| built-in `task=` | denied | `allow_task_override: true` |
Each override is independently gated. Granting `allow_model_override`
does **not** also grant `allow_provider_override` — a plugin trusted
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/plugin-llm-access.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/plugin-llm-access.md
index 75c65f7ec3c..e628617a059 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/plugin-llm-access.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/plugin-llm-access.md
@@ -193,6 +193,7 @@ result = ctx.llm.complete(
agent_id=None, # 可选,受门控
profile=None, # 可选,受门控——显式指定认证 profile 名称
purpose="optional-audit-string",
+ task=None, # 可选——plugin 注册的辅助槽位
)
# → PluginLlmCompleteResult(text, provider, model, agent_id, usage, audit)
```
@@ -223,6 +224,7 @@ result = ctx.llm.complete_structured(
agent_id=None,
profile=None,
purpose=None,
+ task=None, # 可选——plugin 注册的辅助槽位
)
# → PluginLlmStructuredResult(text, provider, model, agent_id,
# usage, parsed, content_type, audit)
@@ -236,12 +238,38 @@ result = ctx.llm.complete_structured(
### 异步
```python
-result = await ctx.llm.acomplete(messages=...)
-result = await ctx.llm.acomplete_structured(instructions=..., input=...)
+result = await ctx.llm.acomplete(messages=..., task="classifier")
+result = await ctx.llm.acomplete_structured(
+ instructions=..., input=..., task="classifier"
+)
```
参数和结果类型与对应的同步版本相同。在 gateway 适配器、异步 hook 或任何已运行在 asyncio 事件循环上的 plugin 代码中使用。
+### 通过任务路由的辅助调用
+
+当 plugin 需要使用自己配置的辅助路由时,可在四种调用形态中的任意一种传入 `task=`。在 plugin 初始化期间注册该任务;在运营人员通过 `auxiliary.<task>` 覆盖 provider 和模型之前,将使用 plugin 提供的默认值:
+
+```python
+def register(ctx):
+ ctx.register_auxiliary_task(
+ "classifier", display_name="Classifier", description="Classify input."
+ )
+
+
+result = ctx.llm.complete(messages=[...], task="classifier")
+result = ctx.llm.complete_structured(instructions=..., input=..., task="classifier")
+```
+
+```yaml
+auxiliary:
+ classifier:
+ provider: openrouter
+ model: vendor/model-id
+```
+
+Plugin 可以为自己注册的任务提供 provider/模型注册默认值。运营人员在 `auxiliary.<task>` 中的配置会覆盖这些默认值,并控制部署选择。Plugin 只能使用自己注册的任务;未知或属于其他 plugin 的任务名会在调用 provider 前失败。`allow_task_override: true` 是运营人员显式授予的权限,用于使用 Hermes 内置辅助任务;它不允许使用其他 plugin 的任务。省略 `task=`(或使用 `"auto"`)会继续使用当前主 provider/模型。
+
### 结果属性
```python
@@ -271,6 +299,7 @@ class PluginLlmStructuredResult(PluginLlmCompleteResult):
* 设置请求塑形参数(`temperature`、`max_tokens`、`timeout`、`system_prompt`、`purpose`、`messages`、`instructions`、`input`、`json_schema`),
……仅此而已。`provider=`、`model=`、`agent_id=` 和 `profile=` 参数在运营人员授权前均会抛出 `PluginLlmTrustError`。
+同样,`task=` 只能使用该 plugin 已注册的辅助任务,除非运营人员授予 `allow_task_override` 以使用内置任务。
**大多数 plugin 永远不需要此部分。** 仅调用 `ctx.llm.complete(messages=...)` 且不带任何覆盖的 plugin,会针对用户当前激活的内容运行,零配置即可工作。以下配置块仅在 plugin 明确需要固定到与用户不同的模型或 provider 时才有意义。
@@ -319,6 +348,7 @@ Plugin id 对于扁平 plugin 是 manifest 中的 `name:` 字段,对于嵌套
| ↳ 允许列表 | — | `allowed_models: [...]` |
| `agent_id=` | 拒绝 | `allow_agent_id_override: true` |
| `profile=` | 拒绝 | `allow_profile_override: true` |
+| 内置 `task=` | 拒绝 | `allow_task_override: true` |
每项覆盖独立门控。授予 `allow_model_override` **不会**同时授予 `allow_provider_override`——被信任可选择模型的 plugin,在未获得 provider 门控授权前仍固定在用户当前激活的 provider 上。
@@ -368,4 +398,4 @@ Plugin id 对于扁平 plugin 是 manifest 中的 `name:` 字段,对于嵌套
* [`plugin-llm-example`](https://github.com/NousResearch/hermes-example-plugins/tree/main/plugin-llm-example) — 带图像输入的同步结构化提取
* [`plugin-llm-async-example`](https://github.com/NousResearch/hermes-example-plugins/tree/main/plugin-llm-async-example) — 使用 `asyncio.gather()` 的异步示例
* 辅助客户端(底层引擎):参见
- [Provider 运行时](/developer-guide/provider-runtime)。
\ No newline at end of file
+ [Provider 运行时](/developer-guide/provider-runtime)。