Advisor
Give an executor model a way to consult a separate advisor model before it answers or commits to a decision.
While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.
flowchart TB
accTitle: Advisor: let the model consult a second model
accDescr: The executor model consults the advisor tool of the Advisor capability and gets an answer. On the local fallback, for any other pairing, an advisor agent run with its own instructions and no access to your tools prompts the advisor model and gets an answer. On the native path, for the same provider, Anthropic or OpenRouter, the provider runs AdvisorTool in the model request.
executor(["executor model"])
advisor["Advisor()<br/>advisor tool"]:::capability
run["advisor agent run<br/>own instructions,<br/>no access to your tools"]:::capability
advmodel(["advisor model"])
native["AdvisorTool<br/>the provider runs it<br/>in the model request"]:::external
executor <-->|"consultation, answer"| advisor
advisor -->|"local fallback:<br/>any other pairing"| run
run <-->|"prompt, answer"| advmodel
advisor -->|"native: same provider,<br/>Anthropic or OpenRouter"| native
classDef capability stroke:#E520E9,stroke-width:2px
classDef external stroke:#0E9C86,stroke-width:2px
Pass the advisor model as the first argument. The model can be any model name or model instance accepted by Pydantic AI:
from pydantic_ai import Agent
from pydantic_ai_harness import Advisor
agent = Agent(
'openai:gpt-6.1-sol',
capabilities=[
Advisor(
'anthropic:claude-opus-5-5',
max_uses=1,
max_tokens=4096,
)
],
)
result = agent.run_sync(
'Design a zero-downtime database migration. Consult the advisor before choosing a plan.'
)
print(result.output)
The executor decides when to consult. Ask it explicitly in the user prompt or the agent’s instructions when a consultation is required.
Set output_type to the output specification you would pass to a Pydantic AI Agent, such as a Pydantic model, a scalar type, or NativeOutput(...). It defaults to str. The advisor model must support the selected output mode.
Provider-native advisor tools do not accept an output schema. A non-default output_type therefore consults locally; combining it with local=False raises ValueError.
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai_harness.advisor import Advisor
class Decision(BaseModel):
proceed: bool
risk_score: float
agent = Agent(
'openai:gpt-6.1-sol',
capabilities=[Advisor('anthropic:claude-opus-5-5', output_type=Decision)],
)
The executor receives the validated object as the tool result. Once max_uses is used up, the tool returns a plain-text limit message instead.
Advisor exposes one logical tool through two execution paths, using Pydantic AI’s native-or-local tool selection:
- Native: when the executor and advisor are both on a compatible Anthropic provider, or both use OpenRouter, Pydantic AI’s provider-native
AdvisorToolruns the consultation. - Local fallback: every other pairing gets an
advisorfunction tool. Calling it runs a separate Pydantic AI agent with the configured advisor model.
By default, native selection is conservative. The capability only reuses an explicit provider-qualified model name when the executor and advisor share a provider, so it does not guess how an Anthropic model ID maps to an OpenRouter catalog slug. For example:
from pydantic_ai_harness import Advisor
# Native for an Anthropic executor; local for OpenAI, Google, and other executors.
anthropic_advisor = Advisor('anthropic:claude-opus-5-5')
# Native for an OpenRouter executor.
openrouter_advisor = Advisor('openrouter:anthropic/claude-opus-4.8')
By default, a Model instance runs locally and keeps its own provider, client, credentials, base URL, and instrumentation. A model name is resolved only when a consultation runs locally, so a native consultation uses the executor provider’s configuration. Native use also requires the executor model’s profile to support the advisor tool; otherwise the capability falls back to local.
| Option | Default | Behavior |
|---|---|---|
model | required | Advisor model name or Model instance. |
native | True | The provider-native advisor. False disables it; an AdvisorTool instance or a function returning one replaces the one built from these options, which then don’t apply to it. |
local | True | The local fallback. True builds the advisor tool; False disables it; a Tool or function replaces it and, like the built tool, is left out of requests where the native advisor applies. A replacement keeps its own tool name. It can’t be combined with output_type, forward_history=True, or, on OpenRouter, max_uses, which only the built tool applies; otherwise max_uses, max_tokens and caching still shape the native advisor. |
output_type | str | Local advisor output specification. Non-default values require local execution. |
max_uses | None | Maximum consultations in one executor model request. An int must be at least 1; a callable returns the limit for each request. |
max_tokens | None | Maximum output tokens for each consultation. Must be at least 1024. |
caching | None | Native-only prompt-cache TTL: '5m' or '1h'. Supported by Anthropic; OpenRouter and the local fallback have no equivalent control. |
forward_history | False | Forward completed executor message history to local consultations. |
id | 'advisor' | Capability and toolset ID. Advisors that share it merge into one. |
defer_loading | False | Make Advisor an on-demand capability: its tools stay hidden until the model loads it by id. |
description | None | Catalog entry the model reads to decide whether to load an on-demand Advisor. |
Pass local=False when the consultation must stay inside the executor provider, or native=False when the configured advisor provider must receive a separate request, the same switches as the other native-or-local capabilities. With the built native advisor, local=False requires an anthropic:<model> or openrouter:<model> string and an executor on that same provider; a native= replacement carries its own model. A provider subclass that only changes its name, such as an AnthropicProvider subclass named claude-code, counts as the provider it extends. It does not fall back when the executor lacks support.
The earlier mode option still works until pydantic-ai-harness 1.0, with a HarnessDeprecationWarning: mode='native' is local=False, mode='local' is native=False, and mode='auto' is the default.
max_uses has the same per-request scope as Anthropic’s native tool and resets on the next request. On the local path, a call counts once its arguments validate, even if the consultation then fails. Parallel calls cannot exceed the cap. Without max_uses, the run’s usage limits bound local consultations within one request.
A callable max_uses takes the RunContext and returns the limit for each executor request, so a budget shared by several runs can live in deps, as in max_uses=lambda ctx: 5 - ctx.deps.consulted. The native tool is sent with that limit. The local tool reads it once per request, when the tool is prepared. Below 1, the native tool is omitted from the request, and the local tool stays visible and returns its limit message. A callable is Python-only, like output_type, and should be cheap and deterministic, since it runs for each request and, under durable execution, in workflow code.
OpenRouter’s native tool ignores max_uses and applies its own fixed per-request limit. By default, setting max_uses with an OpenRouter advisor therefore selects the local fallback. With local=False and the built native advisor, it raises ValueError.
forward_history does not affect native-versus-local selection. The current response, including partial text and unresolved tool calls, is not forwarded, so the consultation prompt still needs to contain the complete current question.
String model configurations can be loaded from YAML or JSON agent specs by passing Advisor in custom_capability_types. Runtime Model instances and custom output specifications remain Python-only.
The context depends on the execution path:
| Path | Advisor context |
|---|---|
| Anthropic native | The provider supplies the full transcript, including system instructions, tool definitions, earlier turns and results, and executor text produced so far. |
| OpenRouter native | The executor supplies a consultation prompt. Pydantic AI configures forward_transcript=false. |
| Local fallback | The executor supplies a consultation prompt through the advisor function tool. With forward_history=True, the advisor also receives completed executor message history. |
The local advisor has its own instructions and no access to the executor’s dependencies, tools, or toolsets. For portable behavior, tell the executor to put the question and all relevant evidence in its consultation prompt; the local tool description asks for this too.
Local consultations go to the advisor model’s provider. With forward_history=True, that request also carries the executor’s earlier messages as structured message history, including any system_prompt parts, its tool calls, and their results. Native consultations stay with the executor’s provider.
Local advisor requests share the parent run’s RunUsage and UsageLimits, so their requests and tokens count toward the agent tree’s normal limits. With count_tokens_before_request=True, an advisor model that implements count_tokens has the consultation checked before it is sent. If the advisor model can’t count tokens, such as an openai-codex: or openai-chatgpt: model, the consultation runs without the up-front count and the token and cost limits are checked against the advisor’s response instead.
A local advisor run is filed under the parent run’s conversation_id, so its requests and spans group with the conversation it advises.
Native providers report advisor usage according to their own protocol. Anthropic records advisor-specific values in RequestUsage.details, while OpenRouter exposes aggregate server-tool counts in response provider details.
Invalid option combinations fail when Advisor is constructed, or when merging two advisors produces one. Executor and provider compatibility is validated when a run prepares its model request. Anthropic reports native advisor errors as tool results so the executor can continue. If a local advisor produces invalid model behavior, the executor receives a normal tool retry, matching Pydantic AI’s other subagent-backed tools. Local model resolution, authentication, provider, request, and usage-limit errors otherwise propagate and can stop the run. When a local call exceeds max_uses, the tool returns a bounded message telling the executor to continue without more advice.
Advisor emits no spans of its own. With Pydantic AI instrumentation enabled globally, for example through logfire.instrument_pydantic_ai(), a local consultation appears as an agent run named advisor; per-agent instrument= on the executor does not reach that run. A native consultation is part of the executor’s model request.
The advisor tool is visible from the start unless defer_loading=True makes Advisor an on-demand capability. With local=False, a request where the max_uses callable returns less than 1 has no advisor tool.
The built tool is named advisor; a local= replacement keeps its own name. The id, and the toolset ID, default to 'advisor'. Keep the id stable once deployed: loading and history replay key on it.
Two Advisor capabilities with the same id merge into one:
- An option left at
None(max_uses,max_tokens,caching) takes the other instance’s value. - Two list
output_types are combined. - Every other option takes the later instance’s value.
nativeandlocalboth default toTrue, so a laterAdvisorleft at its defaults restores the built native advisor and local tool. - A merge that leaves an OpenRouter
Advisorwithlocal=False, the built native advisor, and amax_usesignoresmax_useswith aUserWarning, since no singleAdvisoraccepts that combination.
During streaming, the executor stream pauses while an advisor consultation runs and resumes when the completed advice is available. The local fallback does not splice the advisor model’s token deltas into the executor stream.
Native advice is compatible with durable execution because it remains part of the executor model request. Local execution cannot yet preserve the same semantics across every durable backend. Temporal and Prefect can checkpoint the returned advice, but changes to the activity-local or task-local RunUsage do not merge back into the outer run. DBOS checkpoints each local consultation, so workflow replay reuses the recorded advice.
Under Temporal and Prefect, pass local=False with a supported provider. Local execution there, including the default fallback, is unsupported. Advisor cannot detect durable runs, because Pydantic AI does not yet expose a public durable-context contract, so it does not reject local execution in them.
Bases: NativeOrLocalTool[AgentDepsT]
Let an agent consult another model through a provider-native tool or local fallback.
By default, Advisor uses Pydantic AI’s native AdvisorTool when an explicit
provider-qualified model name matches a compatible Anthropic or OpenRouter
executor. On every other model, it exposes an advisor function tool backed
by a separate Pydantic AI agent. Pass local=False to require the native
advisor, or native=False to always consult locally.
from pydantic_ai import Agent
from pydantic_ai_harness.advisor import Advisor
agent = Agent(
'openai:gpt-5.4',
capabilities=[Advisor('anthropic:claude-opus-4-8')],
)
The capability id, 'advisor' by default.
Two Advisor capabilities with the same id resolve to one via
combine. With different ids, their
built tools conflict, since both are named advisor.
Type: str | None Default: 'advisor'
The model to consult.
Accepts the same model names and model instances as Agent. A model
instance is consulted locally so its provider configuration is preserved;
only an explicit 'anthropic:<model>' or 'openrouter:<model>' name can
select the native advisor.
Type: ModelSelection Default: model
Output specification for local consultations, defaulting to text.
Provider-native advisors return text, so a non-default specification
consults locally and cannot be combined with local=False. Successful
consultations return the validated output directly to the executor.
Type: OutputSpec[object] Default: output_type
Maximum consultations in one executor model request.
The limit resets on the next executor request. A callable is called with the run context for each request and returns that request’s limit, for example what is left of a budget shared by several runs. Below 1, the native advisor is omitted and the local tool returns its limit message. OpenRouter’s native advisor does not honor this option, so setting it consults locally there.
Type: int | Callable[[RunContext[AgentDepsT]], int] | None Default: max_uses
Maximum output tokens for each advisor consultation.
Values below 1024 are rejected so the setting remains valid on every native and local execution path.
Type: int | None Default: max_tokens
Prompt-cache TTL for the advisor’s transcript. Native-only; ignored by local tools.
Supported by: Anthropic.
Type: Literal[‘5m’, ‘1h’] | None Default: caching
Whether local consultations receive the executor’s completed message history.
Local-only: native execution keeps the provider’s transcript behavior unchanged.
Type: bool Default: forward_history
Deprecated: read the native and local declarations instead.
'native' when the local fallback is disabled, 'local' when the native advisor is, and
'auto' otherwise.
Type: _Mode
def __init__(
model: ModelSelection,
*,
native: AdvisorTool | Callable[[RunContext[AgentDepsT]], Awaitable[AdvisorTool | None] | AdvisorTool | None] | bool = True,
local: Tool[AgentDepsT] | Callable[..., Any] | bool | None = True,
output_type: OutputSpec[object] = str,
max_uses: int | Callable[[RunContext[AgentDepsT]], int] | None = None,
max_tokens: int | None = None,
caching: Literal['5m', '1h'] | None = None,
forward_history: bool = False,
id: str | None = None,
defer_loading: bool = False,
description: str | None = None,
mode: _Mode | None = None,
) -> None
Create an advisor capability.
The model to consult.
native : AdvisorTool | Callable[[RunContext[AgentDepsT]], Awaitable[AdvisorTool | None] | AdvisorTool | None] | bool Default: True
The provider-native advisor: True builds it from the fields, False disables
it, and an AdvisorTool or a function returning one replaces it. A replacement
carries its own configuration, so max_uses, max_tokens and caching don’t
apply to it, and a later default Advisor in a merge restores the built one.
The local fallback: True (the default) or None builds the advisor tool from
the fields, False disables it, and a Tool or function replaces it. Like the built
tool, a replacement is left out of requests where the native advisor applies, and it
keeps its own tool name. output_type and forward_history apply only to the
built tool, so they are rejected with a replacement, as is max_uses on OpenRouter,
where it would leave only the unlimited replacement. Otherwise max_uses,
max_tokens and caching still shape the native advisor. None is stored as
True, so that, as with the earlier mode='auto', a later default Advisor in a
merge restores the built local fallback, replacing an earlier False or replacement
tool.
output_type : OutputSpec[object] Default: str
Output specification for local consultations.
max_uses : int | Callable[[RunContext[AgentDepsT]], int] | None Default: None
Maximum consultations in one executor model request.
Maximum output tokens for each consultation.
Prompt-cache TTL for the native advisor’s transcript.
forward_history : bool Default: False
Whether local consultations receive the executor’s message history.
The capability id. Defaults to the class-level id: 'advisor', or a subclass’s own.
defer_loading : bool Default: False
Whether to make this an on-demand capability, whose tools the model loads by id.
The capability description.
mode : _Mode | None Default: None
Deprecated: use native and local. Combined with a non-default native or
local, it raises UserError; a default value is overridden by mode.
@classmethod
def from_spec(
cls,
model: KnownModelName | str,
*,
native: bool = True,
local: bool = True,
max_uses: int | None = None,
max_tokens: int | None = None,
caching: Literal['5m', '1h'] | None = None,
forward_history: bool = False,
id: str | None = None,
defer_loading: bool = False,
description: str | None = None,
mode: _Mode | None = None,
**kwargs: Any,
) -> Advisor[Any]
Build from an agent spec, covering the fields a spec can express.
Every JSON-expressible parameter is named because that signature is what core reads to
generate the spec’s JSON schema. A spec names the model by string and can only switch the
native and local halves on or off. output_type has no JSON form, so it is passed through
**kwargs, which the schema omits. mode is deprecated, as on the constructor.
Advisor[Any]
def __post_init__() -> None
Validate the declared configuration, then resolve native and local.
Runs on construction and again on every merged or per-run copy, so a merge can’t reach a combination no constructor accepts.
@classmethod
def combine(
cls,
capabilities: Sequence[AbstractCapability[AgentDepsT]],
) -> AbstractCapability[AgentDepsT]
Merge like any native-or-local capability, keeping one combination that used to merge.
No single Advisor accepts the built native advisor with local=False and max_uses on
OpenRouter, but merging used to send the native tool without max_uses. That merge keeps
working, with a warning, so an agent composed from two packaged advisors keeps building.
AbstractCapability[AgentDepsT]
@async
def for_run(ctx: RunContext[AgentDepsT]) -> Self
Return a fresh capability with local usage isolated to this run.
The advisor tool counts consultations on the capability it was built from, so the copy
builds its own.
@async
def after_model_request(
ctx: RunContext[AgentDepsT],
*,
request_context: ModelRequestContext,
response: ModelResponse,
) -> ModelResponse
Reset the local consultation allowance for each executor response.