pydantic-ai/tests/test_capability_deferred_loading.py
2026-11-17 20:22:27 +00:00

4407 lines
178 KiB
Python

"""Tests for deferred capability loading, reveal deltas, and the capability catalog.
Split out of `test_capabilities.py` per #7304.
"""
from __future__ import annotations
import asyncio
import json
import threading
from collections.abc import AsyncIterable, AsyncIterator, Callable
from dataclasses import dataclass, field, replace
from typing import Any, cast
import pytest
from pydantic_ai import (
AgentRunResult,
CapabilityInstructionSource,
InstructionBaselinePart,
InstructionDigest,
InstructionId,
InstructionPart,
ModelRequestNode,
)
from pydantic_ai._deferred_capabilities import LoadExchanges, parse_loaded_capabilities
from pydantic_ai._run_context import RunContext
from pydantic_ai.agent import Agent, EndStrategy
from pydantic_ai.capabilities import (
Capability,
ModelFallback,
NativeTool,
ProcessHistory,
ToolSearch,
Toolset,
WrapModelRequestHandler,
WrapperCapability,
)
from pydantic_ai.capabilities.abstract import (
AbstractCapability,
AgentNode,
CapabilityOrdering,
CapabilityPosition,
NodeResult,
)
from pydantic_ai.capabilities.combined import CombinedCapability
from pydantic_ai.capabilities.hooks import Hooks
from pydantic_ai.exceptions import (
CallDeferred,
ModelAPIError,
ModelRetry,
UnexpectedModelBehavior,
UserError,
)
from pydantic_ai.messages import (
AgentStreamEvent,
CapabilityLoadDeltaEvent,
CapabilityLoadDeltaPart,
CompactionPart,
EnqueuedMessagesEvent,
InstructionDeltaPart,
LoadCapabilityCallPart,
LoadCapabilityReturnPart,
ModelMessage,
ModelRequest,
ModelResponse,
RetryInfo,
TextPart,
ToolAvailabilityDeltaEvent,
ToolAvailabilityDeltaPart,
ToolCallPart,
ToolReturn,
ToolReturnPart,
ToolSearchCallPart,
ToolSearchReturnPart,
UserPromptPart,
)
from pydantic_ai.models import (
DeferredCapabilityEntry,
ModelRequestContext,
)
from pydantic_ai.models.function import AgentInfo, DeltaToolCall, DeltaToolCalls, FunctionModel
from pydantic_ai.models.test import TestModel
from pydantic_ai.native_tools import (
AbstractNativeTool,
WebSearchTool,
)
from pydantic_ai.native_tools._tool_search import ToolSearchTool
from pydantic_ai.output import ToolOutput
from pydantic_ai.settings import ModelSettings as _ModelSettings
from pydantic_ai.tool_manager import ParallelExecutionMode
from pydantic_ai.tools import DeferredToolRequests, DeferredToolResults, ToolDefinition
from pydantic_ai.toolsets import FunctionToolset, _deferred_capability_loader
from pydantic_ai.toolsets._deferred_capability_loader import (
LOAD_CAPABILITY_ALREADY_ACTIVE_MESSAGE_TEMPLATE,
LOAD_CAPABILITY_DUPLICATE_CALL_MESSAGE_TEMPLATE,
LOAD_CAPABILITY_LOADED_MESSAGE_TEMPLATE,
LOAD_CAPABILITY_TOOL_NAME,
)
from pydantic_ai.usage import RequestUsage, RunUsage
from tests.function_model_prefix import TOOLS_CHANGE_MID_RUN
from ._inline_snapshot import snapshot
from .capability_models import (
make_text_response,
noop_greet as _noop_greet,
)
from .conftest import IsDatetime, IsStr, iter_message_parts
from .function_model_prefix import RecordedRequest, render_anthropic_bodies
_SEARCH_TOOLS_NAME = ToolSearch.function_tool_name
def loaded_instructions(messages: list[ModelMessage], capability_id: str) -> str | None:
"""The instructions the request after `capability_id`'s load stated for it."""
return next(
part.content
for message in messages
if isinstance(message, ModelRequest)
for part in message.parts
if isinstance(part, InstructionDeltaPart) and str(part.id) == f'capability:{capability_id}'
)
pytestmark = []
async def test_deferred_capability_catalog_mentions_search_only_when_search_surface_exists() -> None:
"""The catalog steers away from tool search only in runs that actually offer a search surface.
The surface exists exactly when `ToolSearch` (installed explicitly, or auto-injected by a
searchable deferred tool) has a non-empty corpus — the run then carries the `search_tools`
definition even when a native search surface will replace it on the wire. In a
capability-only run there is nothing to search with, so mentioning searching would name an
affordance that doesn't exist and invite hallucinated search calls.
"""
def model_fn(_messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
return ModelResponse(parts=[TextPart('done')])
refunds = Capability[object](id='refunds', description='Refund tools.', defer_loading=True)
async def first_request_instructions(agent: Agent[None, str]) -> str | None:
result = await agent.run('hi')
request = next(message for message in result.all_messages() if isinstance(message, ModelRequest))
return request.instructions
assert await first_request_instructions(Agent(FunctionModel(model_fn), capabilities=[refunds])) == snapshot(
"The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:\n"
'- refunds: Refund tools.'
)
searchable_toolset = FunctionToolset()
@searchable_toolset.tool_plain(defer_loading=True)
def weather_forecast() -> str: # pragma: no cover
"""Look up a weather forecast."""
return 'sunny'
assert await first_request_instructions(
Agent(FunctionModel(model_fn), capabilities=[ToolSearch(), refunds], toolsets=[searchable_toolset])
) == snapshot(
"The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded — load the capability first rather than searching for its tools:\n"
'- refunds: Refund tools.'
)
# Without an explicit `ToolSearch`, a searchable deferred tool auto-injects one — the run
# still offers a search surface, so the steering variant is still correct.
assert await first_request_instructions(
Agent(FunctionModel(model_fn), capabilities=[refunds], toolsets=[searchable_toolset])
) == snapshot(
"The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded — load the capability first rather than searching for its tools:\n"
'- refunds: Refund tools.'
)
# A named-native strategy registers no local `search_tools` fallback, but the run's search
# surface is no less real for going native — the steering variant must still be picked.
assert await first_request_instructions(
Agent(
FunctionModel(model_fn),
capabilities=[ToolSearch(strategy='bm25'), refunds],
toolsets=[searchable_toolset],
)
) == snapshot(
"The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded — load the capability first rather than searching for its tools:\n"
'- refunds: Refund tools.'
)
async def test_deferred_capability_catalog_bytes_stable_across_turns() -> None:
"""The catalog instruction is byte-identical on every request within a run.
This is a multi-request property — a single-request snapshot proves correct variant
selection, not stability. The run below searches, loads a capability, and finishes; a
catalog that reacted to either event (variant flip, entry annotation) would change the
instructions and bust the prompt-cache prefix at its very front.
"""
instructions_seen: list[str | None] = []
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
request = messages[-1]
assert isinstance(request, ModelRequest)
instructions_seen.append(request.instructions)
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
if not tool_returns:
return ModelResponse(
parts=[ToolCallPart(tool_name=_SEARCH_TOOLS_NAME, args={'queries': ['weather']}, tool_call_id='s1')]
)
if not any(part.tool_name == LOAD_CAPABILITY_TOOL_NAME for part in tool_returns):
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'refunds'}, tool_call_id='l1')]
)
return ModelResponse(parts=[TextPart('done')])
refunds_toolset = FunctionToolset()
@refunds_toolset.tool_plain
def lookup_refund_policy() -> str: # pragma: no cover
"""Look up refund policy."""
return 'ok'
searchable_toolset = FunctionToolset()
@searchable_toolset.tool_plain(defer_loading=True)
def weather_forecast() -> str: # pragma: no cover
"""Look up a weather forecast."""
return 'sunny'
refunds = Capability[object](
id='refunds', description='Refund tools.', toolsets=[refunds_toolset], defer_loading=True
)
agent = Agent(FunctionModel(model_fn), capabilities=[refunds], toolsets=[searchable_toolset])
result = await agent.run('search then load')
assert result.output == 'done'
assert len(instructions_seen) == 3
assert len(set(instructions_seen)) == 1
assert instructions_seen[0] is not None and 'rather than searching' in instructions_seen[0]
async def test_capability_description_can_be_dynamic() -> None:
"""The convenience Capability accepts a CapabilityDescription callable."""
def describe(ctx: RunContext[str]) -> str:
return f'Use for {ctx.deps} questions.'
agent = Agent(
FunctionModel(lambda _messages, _info: ModelResponse(parts=[TextPart('done')])),
deps_type=str,
capabilities=[Capability[str](id='dynamic-description', description=describe, defer_loading=True)],
)
result = await agent.run('hi', deps='billing')
request = next(message for message in result.all_messages() if isinstance(message, ModelRequest))
assert request.instructions == snapshot(
"""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- dynamic-description: Use for billing questions.\
"""
)
def test_combined_capability_get_model_settings_merge():
"""CombinedCapability.get_model_settings() merges settings from all sub-capabilities."""
@dataclass
class MaxTokensCap(AbstractCapability):
def get_model_settings(self) -> _ModelSettings | None:
return _ModelSettings(max_tokens=100)
@dataclass
class TemperatureCap(AbstractCapability):
def get_model_settings(self) -> _ModelSettings | None:
return _ModelSettings(temperature=0.5)
caps = CombinedCapability(
capabilities=[
MaxTokensCap(),
TemperatureCap(),
]
)
merged = caps.get_model_settings()
assert merged is not None
assert not callable(merged)
assert merged.get('max_tokens') == 100
assert merged.get('temperature') == 0.5
def test_combined_capability_get_model_settings_none():
"""CombinedCapability.get_model_settings() returns None when no capabilities provide settings."""
@dataclass
class PlainCap(AbstractCapability):
pass
caps = CombinedCapability(capabilities=[PlainCap()])
assert caps.get_model_settings() is None
def test_combined_capability_get_model_settings_deferred():
"""Deferred capability model settings resolve only after the capability is loaded."""
seen_dynamic_loaded: list[bool | None] = []
@dataclass
class StaticSettingsCap(AbstractCapability):
def get_model_settings(self) -> _ModelSettings:
return _ModelSettings(max_tokens=123)
@dataclass
class DynamicSettingsCap(AbstractCapability):
def get_model_settings(self) -> Callable[[RunContext], _ModelSettings]:
def settings(ctx: RunContext) -> _ModelSettings:
seen_dynamic_loaded.append(ctx.capability_active)
return _ModelSettings(temperature=0.2)
return settings
resolver = CombinedCapability(
[
StaticSettingsCap(id='static-settings', defer_loading=True),
DynamicSettingsCap(id='dynamic-settings', defer_loading=True),
]
).get_model_settings()
assert callable(resolver)
def resolve(loaded_capability_ids: set[str]) -> _ModelSettings:
return resolver(
RunContext(
deps=None,
model=TestModel(),
usage=RunUsage(),
loaded_capability_ids=loaded_capability_ids,
)
)
assert [
resolve(set()),
resolve({'static-settings'}),
resolve({'static-settings', 'dynamic-settings'}),
] == snapshot(
[
{},
{'max_tokens': 123},
{'max_tokens': 123, 'temperature': 0.2},
]
)
assert seen_dynamic_loaded == [True]
async def test_deferred_hooks_do_not_fire_until_capability_is_loaded() -> None:
"""Hooks owned by a deferred capability are skipped until `load_capability` succeeds."""
hooks = Hooks(id='audit', description='Audit request flow.', defer_loading=True)
seen_loaded: list[bool | None] = []
@hooks.on.before_model_request
async def record(ctx: RunContext, request_context: ModelRequestContext) -> ModelRequestContext:
seen_loaded.append(ctx.capability_active)
return request_context
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
already_loaded = any(
isinstance(part, LoadCapabilityReturnPart)
for message in messages
if isinstance(message, ModelRequest)
for part in message.parts
)
if not already_loaded:
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': 'audit'},
tool_call_id='load-audit',
)
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[hooks])
result = await agent.run('hello')
assert result.output == 'done'
assert seen_loaded == [True]
def test_toolset_capability_get_toolset():
"""Toolset capability returns its toolset."""
ts = FunctionToolset()
cap = Toolset(toolset=ts)
assert cap.get_toolset() is ts
convenience_cap = Capability[object](toolsets=[ts])
assert convenience_cap.get_toolset() is ts
ts_b = FunctionToolset()
combined_cap = Capability[object](toolsets=[ts, ts_b])
from pydantic_ai.toolsets import CombinedToolset
combined = cast(CombinedToolset, combined_cap.get_toolset())
assert list(combined.toolsets) == [ts, ts_b]
def test_capability_stamps_id_on_contributed_function_toolset():
"""A capability's `id` is stamped on its contributed function toolset so it can be used with
durable execution, which wraps leaf toolsets by `id` at construction time. User-provided
toolsets keep their own ids and are never overwritten."""
from pydantic_ai.toolsets import CombinedToolset
def my_tool(x: int) -> int:
return x + 1 # pragma: no cover
stamped = Capability[object](id='billing', tools=[my_tool]).get_toolset()
assert isinstance(stamped, FunctionToolset)
assert stamped.id == 'billing'
# No id → stays None (status quo; setting `id=` is what makes durable-exec errors actionable).
unstamped = Capability[object](tools=[my_tool]).get_toolset()
assert isinstance(unstamped, FunctionToolset)
assert unstamped.id is None
# An empty capability still returns its (live) function toolset carrying the id.
empty = Capability[object](id='billing').get_toolset()
assert isinstance(empty, FunctionToolset)
assert empty.id == 'billing'
# Combined with a user toolset: the function toolset gets the capability id; the user toolset
# keeps its own id.
user_toolset = FunctionToolset[object](id='user-ts')
combined = cast(
CombinedToolset, Capability[object](id='billing', tools=[my_tool], toolsets=[user_toolset]).get_toolset()
)
function_toolset, provided = combined.toolsets
assert isinstance(function_toolset, FunctionToolset)
assert function_toolset.id == 'billing'
assert provided is user_toolset
def test_native_or_local_stamps_id_on_local_toolset():
"""`NativeOrLocalTool` stamps its `id` on the FunctionToolset wrapping a bare local callable, so
the local fallback can be used with durable execution."""
from pydantic_ai.capabilities import NativeOrLocalTool
from pydantic_ai.toolsets import PreparedToolset
def local_search(query: str) -> str:
return 'result' # pragma: no cover
cap = NativeOrLocalTool[object](native=WebSearchTool(), local=local_search, id='search')
toolset = cap.get_toolset()
# native + local → the local FunctionToolset is wrapped in a PreparedToolset that tags it
# `unless_native`; the leaf underneath carries the id.
assert isinstance(toolset, PreparedToolset)
leaf = toolset.wrapped
assert isinstance(leaf, FunctionToolset)
assert leaf.id == 'search'
def _noop_greet_with_context(_ctx: RunContext, name: str) -> str:
return f'Hello, {name}!' # pragma: no cover
def test_capability_combines_toolsets_and_tools_together():
"""`Capability[object](toolsets=..., tools=...)` mirrors `Agent` by combining both."""
toolset = FunctionToolset()
cap = Capability[object](toolsets=[toolset], tools=[_noop_greet])
from pydantic_ai.toolsets import CombinedToolset
combined = cast(CombinedToolset, cap.get_toolset())
function_toolset, provided_toolset = combined.toolsets
assert isinstance(function_toolset, FunctionToolset)
assert function_toolset.tools.keys() == {'_noop_greet'}
assert provided_toolset is toolset
def test_capability_tool_plain_combines_with_toolsets():
"""`Capability.tool_plain()` registers a function toolset alongside provided toolsets."""
toolset = FunctionToolset()
cap = Capability[object](toolsets=[toolset])
cap.tool_plain(_noop_greet)
from pydantic_ai.toolsets import CombinedToolset
combined = cast(CombinedToolset, cap.get_toolset())
function_toolset, provided_toolset = combined.toolsets
assert isinstance(function_toolset, FunctionToolset)
assert function_toolset.tools.keys() == {'_noop_greet'}
assert provided_toolset is toolset
def test_capability_tool_combines_with_toolsets():
"""`Capability.tool()` registers a function toolset alongside provided toolsets."""
toolset = FunctionToolset()
cap = Capability[object](toolsets=[toolset])
cap.tool(_noop_greet_with_context)
from pydantic_ai.toolsets import CombinedToolset
combined = cast(CombinedToolset, cap.get_toolset())
function_toolset, provided_toolset = combined.toolsets
assert isinstance(function_toolset, FunctionToolset)
assert function_toolset.tools.keys() == {'_noop_greet_with_context'}
assert provided_toolset is toolset
def test_capability_opts_out_of_spec_serialization():
"""`Capability` holds non-serializable state (function tools, instructions, callable
descriptions), so it opts out of spec construction like the other non-serializable
capabilities, and passing it as a custom capability type fails loudly."""
from pydantic_ai.agent.spec import get_capability_registry
assert Capability.get_serialization_name() is None
with pytest.raises(ValueError, match='Capability has opted out of serialization'):
get_capability_registry(custom_types=[Capability])
async def test_toolset_capability_in_agent():
"""A Toolset capability's tools are available to the agent."""
ts = FunctionToolset()
@ts.tool_plain
def greet(name: str) -> str:
"""Greet someone by name."""
return f'Hello, {name}!'
agent = Agent(TestModel(), capabilities=[Toolset(toolset=ts)])
result = await agent.run('Greet Alice')
tool_returns = list(iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart))
assert len(tool_returns) == 1
assert isinstance(tool_returns[0].content, str)
assert tool_returns[0].content.startswith('Hello, ')
async def test_capability_function_tools_shortcuts_in_agent():
"""A Capability can register function tools directly or with decorators."""
def greet(name: str) -> str:
"""Greet someone by name."""
return f'Hello, {name}!'
cap = Capability[int](tools=[greet])
@cap.tool_plain(name='wave')
def wave(name: str) -> str:
"""Wave to someone by name."""
return f'Waving to {name}!'
@cap.tool
def add_deps(ctx: RunContext[int], value: int) -> int:
"""Add the run dependency to a value."""
return ctx.deps + value
agent = Agent(TestModel(call_tools=['greet', 'wave', 'add_deps']), capabilities=[cap], deps_type=int)
result = await agent.run('Use the capability tools', deps=10)
tool_returns = list(iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart))
assert [part.tool_name for part in tool_returns] == ['greet', 'wave', 'add_deps']
async def test_capability_instructions_decorator_without_parenthesis():
"""A Capability can register instructions with a bare decorator."""
captured_messages: list[ModelMessage] = []
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
captured_messages.extend(messages)
return ModelResponse(parts=[TextPart('done')])
cap = Capability[object]()
@cap.instructions
def instructions() -> str:
return 'Use the capability runbook.'
agent = Agent(FunctionModel(model_fn), capabilities=[cap])
result = await agent.run('Help me')
assert result.output == 'done'
assert [msg.instructions for msg in captured_messages if isinstance(msg, ModelRequest)] == snapshot(
['Use the capability runbook.']
)
async def test_capability_instructions_decorator_with_parenthesis():
"""A Capability can register instructions with a called decorator."""
captured_messages: list[ModelMessage] = []
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
captured_messages.extend(messages)
return ModelResponse(parts=[TextPart('done')])
cap = Capability[object]()
@cap.instructions()
def instructions_2() -> str:
return 'Use the capability runbook.'
agent = Agent(FunctionModel(model_fn), capabilities=[cap])
result = await agent.run('Help me')
assert result.output == 'done'
assert [msg.instructions for msg in captured_messages if isinstance(msg, ModelRequest)] == snapshot(
['Use the capability runbook.']
)
async def test_capability_instructions_decorator_combines_with_constructor_instructions():
"""Constructor instructions and decorator instructions are combined."""
captured_messages: list[ModelMessage] = []
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
captured_messages.extend(messages)
return ModelResponse(parts=[TextPart('done')])
cap = Capability[int](instructions='Use the capability runbook.')
@cap.instructions
def add_deps(ctx: RunContext[int]) -> str:
return f'The current account id is {ctx.deps}.'
agent = Agent(FunctionModel(model_fn), capabilities=[cap], deps_type=int)
result = await agent.run('Help me', deps=123)
assert result.output == 'done'
assert [msg.instructions for msg in captured_messages if isinstance(msg, ModelRequest)] == snapshot(
['Use the capability runbook.\n\nThe current account id is 123.']
)
async def test_deferred_capability_instructions_decorator_resolves_on_load() -> None:
"""A deferred capability returns decorator-registered instructions when loaded."""
cap = Capability[int](
id='account',
description='Account-specific guidance.',
defer_loading=True,
)
@cap.instructions
def account_instructions(ctx: RunContext[int]) -> str:
return f'Use account id {ctx.deps}.'
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
already_loaded = any(
isinstance(part, LoadCapabilityReturnPart)
for message in messages
if isinstance(message, ModelRequest)
for part in message.parts
)
if not already_loaded:
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': 'account'},
tool_call_id='load-account',
)
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[cap], deps_type=int)
result = await agent.run('Help me', deps=123)
assert result.output == 'done'
[load_return] = [
part
for message in result.all_messages()
if isinstance(message, ModelRequest)
for part in message.parts
if isinstance(part, LoadCapabilityReturnPart)
]
assert load_return.content == {'message': "Capability 'account' loaded. Its instructions, if any, follow."}
assert loaded_instructions(result.all_messages(), 'account') == 'Use account id 123.'
first_request = next(message for message in result.all_messages() if isinstance(message, ModelRequest))
assert first_request.instructions == snapshot(
"""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- account: Account-specific guidance.\
"""
)
async def test_deferred_capability_partitions_native_tools() -> None:
"""Deferred native tools are kept out of the baseline request until loaded."""
native_cap = NativeTool(
tool=WebSearchTool(),
id='web-search',
defer_loading=True,
)
[native_tool_func] = CombinedCapability([native_cap]).get_native_tools()
assert callable(native_tool_func)
native_tool_ctx = RunContext(
deps=None,
model=TestModel(),
usage=RunUsage(),
capabilities={'web-search': native_cap},
)
assert native_tool_func(native_tool_ctx) is None
native_tool_ctx.loaded_capability_ids.add('web-search')
assert native_tool_func(native_tool_ctx) == WebSearchTool()
@dataclass
class CallableNativeToolCap(AbstractCapability):
id: str | None = 'callable-web-search'
defer_loading: bool = True
def get_native_tools(self) -> list[Callable[[RunContext], WebSearchTool]]:
return [lambda ctx: WebSearchTool()]
callable_native_cap = CallableNativeToolCap()
[callable_native_tool_func] = CombinedCapability([callable_native_cap]).get_native_tools()
assert callable(callable_native_tool_func)
assert callable_native_tool_func(native_tool_ctx) is None
native_tool_ctx.loaded_capability_ids.add('callable-web-search')
assert callable_native_tool_func(native_tool_ctx) == WebSearchTool()
seen_web_search_tools: list[list[WebSearchTool]] = []
def model_fn(_messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
seen_web_search_tools.append(
[tool for tool in info.model_request_parameters.native_tools if isinstance(tool, WebSearchTool)]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[native_cap])
await agent.run('before load')
await agent.run(
'after load',
message_history=[
ModelResponse(parts=[LoadCapabilityCallPart(args={'id': 'web-search'}, tool_call_id='load-web')]),
ModelRequest(parts=[LoadCapabilityReturnPart(content={}, tool_call_id='load-web')]),
],
)
assert seen_web_search_tools == snapshot([[], [WebSearchTool()]])
async def test_load_capability_tool_name_conflict_raises() -> None:
"""The framework loader must not be shadowed by a user tool with the same name."""
toolset = FunctionToolset()
@toolset.tool_plain
def load_capability() -> str:
return 'user-defined loader' # pragma: no cover
hidden = Capability[object](
id='hidden',
description='Hidden instructions.',
instructions='Hidden instructions.',
defer_loading=True,
)
agent = Agent(TestModel(), toolsets=[toolset], capabilities=[hidden])
with pytest.raises(UserError) as exc_info:
await agent.run('hi')
assert str(exc_info.value) == snapshot(
"Tool name 'load_capability' is reserved for deferred capability loading. Rename your tool to avoid conflicts."
)
def test_duplicate_capability_ids_raise() -> None:
"""Capability ids are used as a run registry, so duplicates must fail loudly — at construction."""
with pytest.raises(UserError) as exc_info:
Agent(
TestModel(),
capabilities=[
Capability[object](id='dup', description='First capability.', instructions='First.'),
Capability[object](id='dup', description='Second capability.', instructions='Second.'),
],
)
assert str(exc_info.value) == snapshot(
"Capability id 'dup' is used by multiple capabilities. Ids identify one capability within a run, so give each a distinct `id`."
)
def test_deferred_capability_without_id_raises_at_construction() -> None:
"""A statically-provided deferred capability without an `id` fails fast at construction."""
with pytest.raises(UserError, match='stable explicit `id` values'):
Agent(TestModel(), capabilities=[Capability[object](description='No id.', defer_loading=True)])
# A deferred group is not merged into the agent's capabilities, so its missing `id` is reported too.
with pytest.raises(UserError, match='stable explicit `id` values'):
Agent(TestModel(), capabilities=[CombinedCapability[object]([Capability[object]()], defer_loading=True)])
def test_deferred_capability_inside_deferred_capability_raises() -> None:
"""Loading a deferred group loads everything in it, so a member can't also be deferred on its own."""
child = Capability[object](id='child', description='Child.', defer_loading=True)
group = CombinedCapability[object]([child], id='group', description='Group.', defer_loading=True)
with pytest.raises(UserError) as exc_info:
Agent(TestModel(), capabilities=[group])
assert str(exc_info.value) == snapshot(
"Deferred capability 'child' is inside deferred capability 'group'. Loading 'group' already loads everything in it, so remove `defer_loading=True` from 'child', or pass it to the agent separately to load it on its own."
)
# A member without an `id` gets the error that names that problem.
anonymous = Capability[object](description='Child.', defer_loading=True)
with pytest.raises(UserError, match='Deferred capabilities must use stable explicit `id` values'):
Agent(
TestModel(),
capabilities=[CombinedCapability([anonymous], id='group', description='G.', defer_loading=True)],
)
@pytest.mark.parametrize('wrap', [False, True], ids=['combined', 'wrapped-combined'])
async def test_deferred_capability_group_loads_all_members_together(wrap: bool) -> None:
"""A deferred group hides its members' tools, instructions and hooks until it loads, then activates all of them.
Its members are not reported as active capabilities before then either, and can't be loaded on their own.
"""
def edit_document(doc_id: str) -> str:
return f'edited {doc_id}'
hooks = Hooks()
hook_steps: list[int] = []
@hooks.on.before_model_request
async def record(ctx: RunContext, request_context: ModelRequestContext) -> ModelRequestContext:
hook_steps.append(ctx.run_step)
return request_context
members: list[AbstractCapability[object]] = [
Capability[object](id='editing_tools', instructions='Editing instructions.', tools=[edit_document]),
hooks,
]
observer = Hooks()
active_ids: list[set[str]] = []
@observer.on.before_model_request
async def observe(ctx: RunContext, request_context: ModelRequestContext) -> ModelRequestContext:
active_ids.append({'editing', 'editing_tools'} & ctx.active_capability_ids)
return request_context
group = (
WrapperCapability[object](CombinedCapability(members), id='editing', description='Editing.', defer_loading=True)
if wrap
else CombinedCapability[object](members, id='editing', description='Editing.', defer_loading=True)
)
visible_tools: list[list[str]] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
visible_tools.append(sorted(tool.name for tool in info.function_tools))
if len(visible_tools) == 1:
return ModelResponse(
parts=[
ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'editing_tools'}),
ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'editing'}),
]
)
if len(visible_tools) == 2:
return ModelResponse(parts=[ToolCallPart('edit_document', {'doc_id': 'd1'})])
return make_text_response('done')
result = await Agent(FunctionModel(model_fn), capabilities=[group, observer]).run('Edit d1.')
assert visible_tools == [
['load_capability'],
['edit_document', 'load_capability'],
['edit_document', 'load_capability'],
]
assert hook_steps == [2, 3]
assert active_ids == [set(), {'editing', 'editing_tools'}, {'editing', 'editing_tools'}]
assert loaded_instructions(result.all_messages(), 'editing') == 'Editing instructions.'
assert [
part.content
for part in iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart)
if part.tool_name == 'edit_document'
] == ['edited d1']
assert [
part.content
for part in iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart)
if part.outcome == 'retried'
] == [
"Capability 'editing_tools' is part of deferred capability 'editing' and loads with it. Load 'editing' instead."
]
async def test_a_deferred_group_member_keeps_its_global_hook_position() -> None:
"""A member that must be outermost or innermost takes that place among all capabilities once its group loads."""
calls: list[str] = []
@dataclass
class Recorder(AbstractCapability[object]):
name: str = ''
position: CapabilityPosition | None = None
def get_ordering(self) -> CapabilityOrdering | None:
return CapabilityOrdering(position=self.position) if self.position else None
async def before_model_request(
self, ctx: RunContext[object], request_context: ModelRequestContext
) -> ModelRequestContext:
calls.append(self.name)
return request_context
group = CombinedCapability[object](
[Recorder('member'), Recorder('outer', 'outermost'), Recorder('inner', 'innermost')],
id='group',
description='Group.',
defer_loading=True,
)
per_request: list[list[str]] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
per_request.append(calls.copy())
calls.clear()
if len(per_request) == 1:
return ModelResponse(parts=[ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'group'})])
return make_text_response('done')
await Agent(FunctionModel(model_fn), capabilities=[Recorder('first'), group, Recorder('last')]).run('hi')
assert per_request == [['first', 'last'], ['outer', 'first', 'member', 'last', 'inner']]
async def test_a_prefixed_deferred_group_loads_its_prefixed_tools() -> None:
"""`prefix_tools` wraps a deferred group under the group's `id`, and loading that `id` reveals the prefixed tools."""
def lookup() -> str:
return 'found' # pragma: no cover
group = CombinedCapability[object](
[Capability[object](id='member', tools=[lookup])], id='group', description='Group.', defer_loading=True
)
visible_tools: list[list[str]] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
visible_tools.append(sorted(tool.name for tool in info.function_tools))
if len(visible_tools) == 1:
return ModelResponse(parts=[ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'group'})])
return make_text_response('done')
await Agent(FunctionModel(model_fn), capabilities=[group.prefix_tools('p')]).run('hi')
assert visible_tools == [['load_capability'], ['load_capability', 'p_lookup']]
@pytest.mark.parametrize('also_eager', [False, True], ids=['only-deferred', 'also-eager'])
async def test_a_shared_member_is_active_only_when_it_occurs_outside_an_unloaded_group(also_eager: bool) -> None:
"""A shared member is inactive only while every occurrence is in an unloaded deferred group."""
member = Capability[object](instructions='Shared.')
active_ids: list[set[str]] = []
observer = Hooks()
@observer.on.before_model_request
async def observe(ctx: RunContext, request_context: ModelRequestContext) -> ModelRequestContext:
aliases = {i for i, cap in ctx.capabilities.items() if cap is member}
active_ids.append(aliases & ctx.active_capability_ids)
return request_context
groups = [CombinedCapability[object]([member], id=i, description='G.', defer_loading=True) for i in ('g1', 'g2')]
eager = [member] if also_eager else []
await Agent(TestModel(call_tools=[]), capabilities=[*groups, *eager, observer]).run('hi')
assert [bool(ids) for ids in active_ids] == [also_eager]
async def test_a_deferred_group_member_rebuilt_for_the_run_still_loads_with_its_group() -> None:
"""A member and a sibling that return a fresh instance from `for_run` are what the run dispatches to."""
calls: list[tuple[str, bool]] = []
@dataclass
class PerRun(AbstractCapability[object]):
name: str = ''
fresh: bool = False
async def for_run(self, ctx: RunContext[object]) -> AbstractCapability[object]:
return replace(self, fresh=True)
async def before_model_request(
self, ctx: RunContext[object], request_context: ModelRequestContext
) -> ModelRequestContext:
calls.append((self.name, self.fresh))
return request_context
group = CombinedCapability[object]([PerRun('member')], id='group', description='Group.', defer_loading=True)
per_request: list[list[tuple[str, bool]]] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
per_request.append(calls.copy())
calls.clear()
if len(per_request) == 1:
return ModelResponse(parts=[ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'group'})])
return make_text_response('done')
await Agent(FunctionModel(model_fn), capabilities=[group, PerRun('sibling')]).run('hi')
assert per_request == [[('sibling', True)], [('member', True), ('sibling', True)]]
async def test_partial_load_capability_history_does_not_mark_loaded() -> None:
"""A partial/stale `load_capability` call in history must not load a capability on replay."""
captured_messages: list[ModelMessage] = []
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
captured_messages.extend(messages)
return ModelResponse(parts=[TextPart('done')])
agent = Agent(
FunctionModel(model_fn),
capabilities=[
Capability[object](
id='reports',
description='Report tools.',
instructions='Report instructions.',
defer_loading=True,
)
],
)
result = await agent.run(
'hi',
message_history=[
ModelResponse(parts=[LoadCapabilityCallPart(args='{"id":', tool_call_id='partial-load')]),
ModelRequest(parts=[LoadCapabilityReturnPart(content={}, tool_call_id='partial-load')]),
],
)
assert result.output == 'done'
# `output == 'done'` alone would pass even if the stale partial load had wrongly marked
# `reports` loaded, so assert the gating directly. The catalog lists `reports` whether or
# not it is loaded (kept stable for prompt caching), so the real discriminator is the
# capability's loaded-only instructions: they must be absent because it never loaded.
final_instructions = next(
msg.instructions for msg in reversed(captured_messages) if isinstance(msg, ModelRequest) and msg.instructions
)
assert 'Report instructions.' not in final_instructions
assert 'reports: Report tools.' in final_instructions
async def test_load_capability_invalid_dict_args_recovers_via_retry() -> None:
"""Schema-violating dict args from the model must produce a retry, not crash the run.
Providers like Anthropic (non-streaming) and Google deliver tool args as parsed
dicts. A dict that doesn't match `LoadCapabilityArgs` fails the typed-subclass
validation when the response is narrowed — promotion must be best-effort (leave
the part plain) so the args validator at execution time can send the model a
retry as designed. Reproduces a live crash with `claude-haiku-4-5` coerced into
sending `{"name": ...}` instead of `{"id": ...}`.
"""
calls = 0
def model_fn(_messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
nonlocal calls
calls += 1
if calls == 1:
return ModelResponse(parts=[ToolCallPart(tool_name='load_capability', args={'name': 'refunds'})])
if calls == 2:
return ModelResponse(parts=[ToolCallPart(tool_name='load_capability', args={'id': 'refunds'})])
return ModelResponse(parts=[TextPart('done')])
agent = Agent(
FunctionModel(model_fn),
capabilities=[
Capability[object](
id='refunds',
description='Refund tools.',
instructions='Refund instructions.',
defer_loading=True,
)
],
)
result = await agent.run('hi')
assert result.output == 'done'
assert result.all_messages() == snapshot(
[
ModelRequest(
parts=[
UserPromptPart(content='hi', timestamp=IsDatetime()),
InstructionBaselinePart(
instructions=[
InstructionPart(
content="""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund tools.\
""",
dynamic=True,
on_change='append',
id=InstructionId(source=CapabilityInstructionSource(id='deferred_capabilities')),
)
]
),
],
timestamp=IsDatetime(),
instructions="""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund tools.\
""",
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelResponse(
parts=[
ToolCallPart(
tool_name='load_capability',
args={'name': 'refunds'},
tool_call_id=IsStr(),
)
],
usage=RequestUsage(input_tokens=51, output_tokens=5),
model_name='function:model_fn:',
model_id='function:function:model_fn:',
timestamp=IsDatetime(),
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelRequest(
parts=[
ToolReturnPart(
content=[
{'type': 'missing', 'loc': ['id'], 'msg': 'Field required', 'input': {'name': 'refunds'}}
],
tool_name='load_capability',
tool_call_id=IsStr(),
timestamp=IsDatetime(),
outcome='retried',
retry=RetryInfo(cause='validation_error', attempt=1, max_retries=1),
)
],
timestamp=IsDatetime(),
instructions="""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund tools.\
""",
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelResponse(
parts=[LoadCapabilityCallPart(args={'id': 'refunds'}, tool_call_id=IsStr())],
usage=RequestUsage(input_tokens=68, output_tokens=10),
model_name='function:model_fn:',
model_id='function:function:model_fn:',
timestamp=IsDatetime(),
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelRequest(
parts=[
LoadCapabilityReturnPart(
content={'message': "Capability 'refunds' loaded. Its instructions, if any, follow."},
tool_call_id=IsStr(),
timestamp=IsDatetime(),
),
InstructionDeltaPart(
id=InstructionId(source=CapabilityInstructionSource(id='refunds')),
content='Refund instructions.',
),
],
timestamp=IsDatetime(),
instructions="""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund tools.\
""",
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelResponse(
parts=[TextPart(content='done')],
usage=RequestUsage(input_tokens=89, output_tokens=11),
model_name='function:model_fn:',
model_id='function:function:model_fn:',
timestamp=IsDatetime(),
run_id=IsStr(),
conversation_id=IsStr(),
),
]
)
@pytest.mark.parametrize(
'args,expected_id',
[
pytest.param(None, None, id='partial-stream-no-args'),
pytest.param({'id': 'refunds'}, 'refunds', id='validated-dict'),
pytest.param('{"id": "billing"}', 'billing', id='complete-json-string'),
pytest.param('{"id":', None, id='partial-stream-json'),
pytest.param('[1, 2, 3]', None, id='non-dict-json'),
],
)
def test_load_capability_call_part_typed_args(args: Any, expected_id: str | None) -> None:
"""`typed_args` handles valid, partial, and invalid payloads."""
part = LoadCapabilityCallPart(tool_call_id='c', args=args)
assert part.capability_id == expected_id
if expected_id is None:
assert part.typed_args is None
else:
assert part.typed_args == {'id': expected_id}
def test_load_capability_return_part_accessors() -> None:
"""`instructions` reads the optional return payload field."""
with_instructions = LoadCapabilityReturnPart(
tool_call_id='c',
content={'instructions': 'Use refunds carefully.'},
)
assert with_instructions.instructions == 'Use refunds carefully.'
without_instructions = LoadCapabilityReturnPart(
tool_call_id='c',
content={},
)
assert without_instructions.instructions is None
def test_load_capability_narrow_type_promotes_and_is_idempotent() -> None:
"""Capability-load narrowing is idempotent."""
base_call = ToolCallPart(
tool_name='load_capability',
tool_call_id='c',
args={'id': 'refunds'},
tool_kind='capability-load',
)
promoted_call = ToolCallPart.narrow_type(base_call)
assert isinstance(promoted_call, LoadCapabilityCallPart)
assert ToolCallPart.narrow_type(promoted_call) is promoted_call
base_return = ToolReturnPart(
tool_name='load_capability',
tool_call_id='c',
content={},
tool_kind='capability-load',
)
promoted_return = ToolReturnPart.narrow_type(base_return)
assert isinstance(promoted_return, LoadCapabilityReturnPart)
assert ToolReturnPart.narrow_type(promoted_return) is promoted_return
def test_load_capability_parts_round_trip_through_message_history() -> None:
"""`capability-load` parts survive history (de)serialization as typed subclasses, and a
user tool named `load_capability` without `tool_kind` is left as a plain `ToolCallPart`."""
from pydantic_ai.messages import ModelMessagesTypeAdapter, ModelRequest, ModelResponse
raw: list[dict[str, Any]] = [
{
'kind': 'response',
'parts': [
{
'part_kind': 'tool-call',
'tool_name': 'load_capability',
'tool_kind': 'capability-load',
'args': {'id': 'refunds'},
'tool_call_id': 'c1',
},
# User tool colliding on the name but without `tool_kind`: must stay base.
{
'part_kind': 'tool-call',
'tool_name': 'load_capability',
'args': {'foo': 'bar'},
'tool_call_id': 'c2',
},
],
},
{
'kind': 'request',
'parts': [
{
'part_kind': 'tool-return',
'tool_name': 'load_capability',
'tool_kind': 'capability-load',
'content': {'instructions': 'Confirm the order id.'},
'tool_call_id': 'c1',
},
],
},
]
response, request = ModelMessagesTypeAdapter.validate_python(raw)
assert isinstance(response, ModelResponse)
assert isinstance(response.parts[0], LoadCapabilityCallPart)
assert response.parts[0].capability_id == 'refunds'
# Collision on `tool_name='load_capability'` without `tool_kind` stays a base part.
assert type(response.parts[1]) is ToolCallPart
assert response.parts[1].args == {'foo': 'bar'}
assert isinstance(request, ModelRequest)
assert isinstance(request.parts[0], LoadCapabilityReturnPart)
assert request.parts[0].instructions == 'Confirm the order id.'
# Full JSON dump -> load round-trip preserves the typed subclasses.
rebuilt = ModelMessagesTypeAdapter.validate_json(ModelMessagesTypeAdapter.dump_json([response, request]))
assert isinstance(rebuilt[0].parts[0], LoadCapabilityCallPart)
assert isinstance(rebuilt[1].parts[0], LoadCapabilityReturnPart)
async def test_deferred_capability_loads_instructions_and_tools_e2e() -> None:
"""A deferred capability starts as a catalog entry and becomes usable after `load_capability`."""
toolset = FunctionToolset()
@toolset.tool_plain
def lookup_refund_policy(order_id: str) -> str:
"""Look up the refund policy for an order."""
return f'{order_id}: refund allowed for 30 days'
def add_account_context(ctx: RunContext) -> str:
return f'Load-time account context for run step {ctx.run_step}.'
def empty_instruction(ctx: RunContext) -> None:
return None
always_on = Capability[object](
id='always-on',
description='Visible billing guidance.',
instructions='Visible billing instructions.',
)
refunds = Capability[object](
id='refunds',
description='Refund policy tools.',
instructions=[
'Use the refund policy before answering refund questions.',
add_account_context,
empty_instruction,
],
toolsets=[toolset],
defer_loading=True,
)
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
if not any(part.tool_name == LOAD_CAPABILITY_TOOL_NAME for part in tool_returns):
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': 'refunds'},
tool_call_id='load-refunds',
)
]
)
if not any(part.tool_name == 'lookup_refund_policy' for part in tool_returns):
return ModelResponse(
parts=[
ToolCallPart(
tool_name='lookup_refund_policy',
args={'order_id': 'order-123'},
tool_call_id='lookup-refund',
)
]
)
refund_result = next(part.content for part in tool_returns if part.tool_name == 'lookup_refund_policy')
return make_text_response(f'final: {refund_result}')
agent = Agent(FunctionModel(model_fn), capabilities=[always_on, refunds])
result = await agent.run('Can I get a refund?')
assert result.output == snapshot('final: order-123: refund allowed for 30 days')
assert result.all_messages() == snapshot(
[
ModelRequest(
parts=[
UserPromptPart(content='Can I get a refund?', timestamp=IsDatetime()),
InstructionBaselinePart(
instructions=[
InstructionDigest(
id=InstructionId(source=CapabilityInstructionSource(id='always-on')),
content_hash='97321e5185a6577bd855abec078319a0b556019f94499fd828a05d24bd9d9a5e',
),
InstructionPart(
content="""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund policy tools.\
""",
dynamic=True,
on_change='append',
id=InstructionId(source=CapabilityInstructionSource(id='deferred_capabilities')),
),
]
),
],
timestamp=IsDatetime(),
instructions="""\
Visible billing instructions.
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund policy tools.\
""",
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelResponse(
parts=[
LoadCapabilityCallPart(
tool_name='load_capability',
args={'id': 'refunds'},
tool_call_id='load-refunds',
)
],
usage=RequestUsage(input_tokens=55, output_tokens=5),
model_name='function:model_fn:',
model_id='function:function:model_fn:',
timestamp=IsDatetime(),
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelRequest(
parts=[
LoadCapabilityReturnPart(
content={'message': "Capability 'refunds' loaded. Its instructions, if any, follow."},
tool_call_id='load-refunds',
timestamp=IsDatetime(),
),
ToolAvailabilityDeltaPart(
tools_added=['lookup_refund_policy'],
tool_call_id='load-refunds',
),
InstructionDeltaPart(
id=InstructionId(source=CapabilityInstructionSource(id='refunds')),
content="""\
Use the refund policy before answering refund questions.
Load-time account context for run step 2.\
""",
),
],
timestamp=IsDatetime(),
instructions="""\
Visible billing instructions.
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund policy tools.\
""",
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelResponse(
parts=[
ToolCallPart(
tool_name='lookup_refund_policy', args={'order_id': 'order-123'}, tool_call_id='lookup-refund'
)
],
usage=RequestUsage(input_tokens=96, output_tokens=10),
model_name='function:model_fn:',
model_id='function:function:model_fn:',
timestamp=IsDatetime(),
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelRequest(
parts=[
ToolReturnPart(
tool_name='lookup_refund_policy',
content='order-123: refund allowed for 30 days',
tool_call_id='lookup-refund',
timestamp=IsDatetime(),
),
InstructionDeltaPart(
id=InstructionId(source=CapabilityInstructionSource(id='refunds')),
content="""\
Use the refund policy before answering refund questions.
Load-time account context for run step 3.\
""",
base_hash='4a05c2dd57b0957d1494fda5f7a7f78d565b493d8bfce3acc48d49e2b1804d54',
),
],
timestamp=IsDatetime(),
instructions="""\
Visible billing instructions.
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund policy tools.\
""",
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelResponse(
parts=[TextPart(content='final: order-123: refund allowed for 30 days')],
usage=RequestUsage(input_tokens=125, output_tokens=17),
model_name='function:model_fn:',
model_id='function:function:model_fn:',
timestamp=IsDatetime(),
run_id=IsStr(),
conversation_id=IsStr(),
),
]
)
async def test_tool_return_reveals_deferred_tool_without_capability() -> None:
"""A user tool can reveal a deferred tool and records the delta beside its return."""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
returns = [
part
for part in iter_message_parts(messages, ModelRequest, ToolReturnPart)
if part.tool_name in {'reveal_weather', 'get_weather'}
]
if not returns:
assert info.model_request_parameters.revealed_tool_names == set()
return ModelResponse(parts=[ToolCallPart(tool_name='reveal_weather', args={}, tool_call_id='reveal')])
if len(returns) == 1:
assert info.model_request_parameters.revealed_tool_names == {'get_weather'}
return ModelResponse(
parts=[ToolCallPart(tool_name='get_weather', args={'city': 'Paris'}, tool_call_id='weather')]
)
return make_text_response(str(returns[-1].content))
agent = Agent(FunctionModel(model_fn))
@agent.tool_plain
def reveal_weather() -> ToolReturn[str]:
return ToolReturn(return_value='Weather tools are ready.', tools=['get_weather'])
@agent.tool_plain(defer_loading=True)
def get_weather(city: str) -> str:
return f'Sunny in {city}'
result = await agent.run('What is the weather?')
assert result.output == 'Sunny in Paris'
reveal_request = next(
message
for message in result.all_messages()
if isinstance(message, ModelRequest)
and any(isinstance(part, ToolReturnPart) and part.tool_call_id == 'reveal' for part in message.parts)
)
assert reveal_request.parts == snapshot(
[
ToolReturnPart(
tool_name='reveal_weather',
content='Weather tools are ready.',
tool_call_id='reveal',
timestamp=IsDatetime(),
),
ToolAvailabilityDeltaPart(tools_added=['get_weather'], tool_call_id='reveal'),
]
)
async def test_processed_history_determines_request_reveal_state() -> None:
"""Removing a reveal from outgoing history also removes it from request parameters."""
seen: list[set[str]] = []
def model_fn(_messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
seen.append(info.model_request_parameters.revealed_tool_names)
assert 'hidden_tool' not in {tool.name for tool in info.function_tools}
return ModelResponse(parts=[TextPart(content='done')])
def strip_deltas(messages: list[ModelMessage]) -> list[ModelMessage]:
return [
replace(message, parts=[part for part in message.parts if not isinstance(part, ToolAvailabilityDeltaPart)])
if isinstance(message, ModelRequest)
else message
for message in messages
]
agent = Agent(FunctionModel(model_fn), capabilities=[ProcessHistory(strip_deltas)])
@agent.tool_plain(defer_loading=True)
def hidden_tool() -> str: # pragma: no cover
return 'hidden'
await agent.run(
'continue',
message_history=[ModelRequest(parts=[ToolAvailabilityDeltaPart(tools_added=['hidden_tool'])])],
)
assert seen == [set()]
def _inject_load(capability_id: str) -> Callable[[list[ModelMessage]], list[ModelMessage]]:
"""Build a processor that injects a complete `load_capability` exchange for `capability_id`."""
def processor(messages: list[ModelMessage]) -> list[ModelMessage]:
if any(True for _ in iter_message_parts(messages, ModelResponse, LoadCapabilityCallPart)):
return messages
return [
messages[0],
ModelResponse(parts=[LoadCapabilityCallPart(args={'id': capability_id}, tool_call_id='injected')]),
ModelRequest(parts=[LoadCapabilityReturnPart(content={}, tool_call_id='injected')]),
*messages[1:],
]
return processor
def _secret_op_returns(messages: list[ModelMessage]) -> list[object]:
return [
part.content
for part in iter_message_parts(messages, ModelRequest, ToolReturnPart)
if part.tool_name == 'secret_op' and part.outcome != 'retried'
]
def _refusals(messages: list[ModelMessage]) -> list[str]:
"""The refused calls' feedback: a refusal answers its call as a return carrying `outcome='retried'`."""
return [
str(part.content)
for part in iter_message_parts(messages, ModelRequest, ToolReturnPart)
if part.outcome == 'retried'
]
def _call_secret_op_once(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
"""Call `secret_op` on the first request, then finish however that call was answered."""
answered = any(
part.tool_name == 'secret_op' or part.outcome == 'retried'
for part in iter_message_parts(messages, ModelRequest, ToolReturnPart)
)
if answered:
return ModelResponse(parts=[TextPart('done')])
return ModelResponse(parts=[ToolCallPart('secret_op', {}, tool_call_id='call-1')])
@pytest.mark.parametrize(
'inject_load', [False, pytest.param(True, marks=pytest.mark.moves_cache_prefix(reason=TOOLS_CHANGE_MID_RUN))]
)
async def test_processor_injected_load_lets_capability_prepare_tools_govern_its_tools(inject_load: bool) -> None:
"""A capability made active by history processing still has `prepare_tools` over its own tools.
Availability is an input to tool *resolution*, not just to the execution gate: the tool set
resolved at the start of the step was built while the capability was inactive, so its
`prepare_tools` never ran and its tools sat in that set ungoverned. Caching the resolved set on
`run_step` alone would then hand that set to a dispatch that reads the (now changed)
availability live, and a `prepare_tools` used as a permission filter would be silently bypassed.
Both directions are pinned: with no injection the tool is refused as not-yet-available (the
filter is never reached, and must not need to be), and with the injection it is refused because
the filter removed it — never executed either way.
"""
prepare_tools_calls: list[list[str]] = []
loaded_ids_seen: list[list[str]] = []
class FilteringSecrets(Capability[object]):
"""Uses `prepare_tools` as a permission filter over its own tool."""
async def prepare_tools(self, ctx: RunContext[object], tool_defs: list[ToolDefinition]) -> list[ToolDefinition]:
prepare_tools_calls.append(sorted(tool_def.name for tool_def in tool_defs))
loaded_ids_seen.append(sorted(ctx.loaded_capability_ids))
return [tool_def for tool_def in tool_defs if tool_def.name != 'secret_op']
secrets_toolset = FunctionToolset[object]()
@secrets_toolset.tool_plain
def secret_op() -> str: # pragma: no cover
return 'EXECUTED'
capabilities: list[AbstractCapability[object]] = [
FilteringSecrets(id='secrets', description='Secret tools.', toolsets=[secrets_toolset], defer_loading=True)
]
if inject_load:
capabilities.append(ProcessHistory[object](processor=_inject_load('secrets')))
agent = Agent(FunctionModel(_call_secret_op_once), capabilities=capabilities)
result = await agent.run('call secret_op')
assert _secret_op_returns(result.all_messages()) == []
refusals = _refusals(result.all_messages())
if inject_load:
# The capability is active, so its own filter decides — and it removed the tool.
assert prepare_tools_calls[0] == snapshot(['secret_op'])
# The run's own prospective state agrees with the history it is sending, so the documented
# "has the runbook been loaded?" check (`id in ctx.loaded_capability_ids`) answers yes on
# this step, rather than the capability being active only through dispatch-time evidence.
assert loaded_ids_seen[0] == snapshot(['secrets'])
assert refusals == snapshot(["Unknown tool name: 'secret_op'. Available tools: 'load_capability'"])
else:
# The capability never loaded, so the availability gate refuses before any filter is reached.
assert prepare_tools_calls == snapshot([])
assert refusals == snapshot(
[
"Tool 'secret_op' is not available yet: it belongs to capability 'secrets'. Call `load_capability` for it first, then call the tool again once you've read the capability's instructions."
]
)
async def test_processor_injected_load_makes_capability_tool_callable() -> None:
"""Without a filter, a processor-injected load makes the capability's tool callable that same step.
The mirror of the test above, and the reason availability is refreshed after processing at all:
the reveal state the request ships is derived from the processed history, so the execution gate
has to read the same history or the model is offered a tool that comes back refused.
"""
secrets_toolset = FunctionToolset[object]()
@secrets_toolset.tool_plain
def secret_op() -> str:
return 'EXECUTED'
agent = Agent(
FunctionModel(_call_secret_op_once),
capabilities=[
Capability[object](
id='secrets', description='Secret tools.', toolsets=[secrets_toolset], defer_loading=True
),
ProcessHistory[object](processor=_inject_load('secrets')),
],
)
result = await agent.run('call secret_op')
assert _secret_op_returns(result.all_messages()) == snapshot(['EXECUTED'])
assert _refusals(result.all_messages()) == snapshot([])
async def test_processor_removed_load_leaves_advertisement_and_gate_in_agreement() -> None:
"""Refreshing availability from processed history must not advertise a tool the gate will refuse.
The mirror of the injection tests, and the direction where making the request and the gate agree
could have gone wrong: the refresh takes the capability *out* of the loaded set for a step whose
tool set was resolved while it was in. `_with_outgoing_reveal_state` derives the request's reveal
state from the same processed messages, so the tool is withheld from the wire rather than shipped
and then refused — the model is never offered something `ToolManager` would reject.
"""
secrets_toolset = FunctionToolset[object]()
@secrets_toolset.tool_plain
def secret_op() -> str: # pragma: no cover
return 'EXECUTED'
advertised: list[list[str]] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
advertised.append(sorted(tool.name for tool in info.function_tools))
return _call_secret_op_once(messages, info)
def drop_load_exchange(messages: list[ModelMessage]) -> list[ModelMessage]:
kept: list[ModelMessage] = []
for message in messages:
parts = [
part
for part in message.parts
if not isinstance(part, (LoadCapabilityCallPart, LoadCapabilityReturnPart))
]
if parts:
kept.append(replace(message, parts=parts))
return kept
agent = Agent(
FunctionModel(model_fn),
capabilities=[
Capability[object](
id='secrets', description='Secret tools.', toolsets=[secrets_toolset], defer_loading=True
),
ProcessHistory[object](processor=drop_load_exchange),
],
)
result = await agent.run(
'call secret_op',
message_history=[
ModelRequest(parts=[UserPromptPart(content='load it')]),
ModelResponse(parts=[LoadCapabilityCallPart(args={'id': 'secrets'}, tool_call_id='l1')]),
ModelRequest(parts=[LoadCapabilityReturnPart(content={}, tool_call_id='l1')]),
],
)
# Withheld from the wire, so the model was never offered it...
assert advertised[0] == snapshot(['load_capability'])
# ...and the call the stub makes anyway is refused, rather than running ungoverned.
assert _secret_op_returns(result.all_messages()) == []
assert _refusals(result.all_messages()) == snapshot(
[
"Tool 'secret_op' is not available yet: it belongs to capability 'secrets'. Call `load_capability` for it first, then call the tool again once you've read the capability's instructions."
]
)
@pytest.mark.moves_cache_prefix(
reason="the hand-built history resumes a suspended response that was sent without the agent's instructions"
)
async def test_processor_injected_load_is_governed_when_resuming_a_suspended_response() -> None:
"""The same governance holds on the request that resumes a provider-suspended turn.
That path prepares its request separately from the normal one — the history already ends in the
suspended response, so there is no new `ModelRequest` to append — but it runs the same history
processing and dispatches the continuation's tool calls against the result, so it needs the same
post-processing availability refresh.
"""
prepare_tools_calls: list[list[str]] = []
loaded_ids_seen: list[list[str]] = []
class FilteringSecrets(Capability[object]):
"""Uses `prepare_tools` as a permission filter over its own tool."""
async def prepare_tools(self, ctx: RunContext[object], tool_defs: list[ToolDefinition]) -> list[ToolDefinition]:
prepare_tools_calls.append(sorted(tool_def.name for tool_def in tool_defs))
loaded_ids_seen.append(sorted(ctx.loaded_capability_ids))
return [tool_def for tool_def in tool_defs if tool_def.name != 'secret_op']
secrets_toolset = FunctionToolset[object]()
@secrets_toolset.tool_plain
def secret_op() -> str: # pragma: no cover
return 'EXECUTED'
agent = Agent(
FunctionModel(_call_secret_op_once),
capabilities=[
FilteringSecrets(id='secrets', description='Secret tools.', toolsets=[secrets_toolset], defer_loading=True),
ProcessHistory[object](processor=_inject_load('secrets')),
],
)
result = await agent.run(
message_history=[
ModelRequest(parts=[UserPromptPart(content='call secret_op')]),
ModelResponse(parts=[TextPart('paused')], state='suspended'),
]
)
assert _secret_op_returns(result.all_messages()) == []
assert prepare_tools_calls[0] == snapshot(['secret_op'])
assert loaded_ids_seen[0] == snapshot(['secrets'])
assert _refusals(result.all_messages()) == snapshot(
["Unknown tool name: 'secret_op'. Available tools: 'load_capability'"]
)
async def test_orphaned_reveal_evidence_stripped_by_cleanup_does_not_count_as_revealed() -> None:
"""Evidence orphaned by a history processor is stripped before reveal derivation.
A processor that drops the response carrying a `ToolSearchCallPart` leaves an orphaned
`ToolSearchReturnPart`; history cleanup removes the orphan before the request ships, so the
derived reveal state must not count it — otherwise the request would declare a revealed tool
with zero reveal evidence on the outgoing wire.
"""
seen: list[set[str]] = []
def model_fn(_messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
seen.append(info.model_request_parameters.revealed_tool_names)
assert 'hidden_tool' not in {tool.name for tool in info.function_tools}
return ModelResponse(parts=[TextPart(content='done')])
def drop_search_calls(messages: list[ModelMessage]) -> list[ModelMessage]:
return [
message
for message in messages
if not (
isinstance(message, ModelResponse)
and any(isinstance(part, ToolSearchCallPart) for part in message.parts)
)
]
agent = Agent(FunctionModel(model_fn), capabilities=[ProcessHistory(drop_search_calls)])
@agent.tool_plain(defer_loading=True)
def hidden_tool() -> str: # pragma: no cover
return 'hidden'
await agent.run(
'continue',
message_history=[
ModelRequest(parts=[UserPromptPart(content='find tools')]),
ModelResponse(parts=[ToolSearchCallPart(args={'queries': ['hidden']}, tool_call_id='search-1')]),
ModelRequest(
parts=[
ToolSearchReturnPart(
content={'discovered_tools': [{'name': 'hidden_tool'}]},
tool_call_id='search-1',
)
]
),
],
)
assert seen == [set()]
async def test_model_calling_a_withheld_tool_is_refused_and_reveals_nothing() -> None:
"""Calling a hidden tool by (guessed) name is refused, and authors no reveal.
Hiding is now an availability gate, not just prompt engineering: a tool the model was never
shown cannot be executed by guessing its name. The refusal is a retry pointing at search, and
a refused call is not a discovery, so the tool stays off the wire afterwards.
"""
wire_tools: list[list[str]] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
wire_tools.append(sorted(tool.name for tool in info.function_tools))
if [part for part in iter_message_parts(messages, ModelRequest, ToolReturnPart) if part.outcome == 'retried']:
return ModelResponse(parts=[TextPart('done')])
return ModelResponse(parts=[ToolCallPart(tool_name='hidden_tool', args={}, tool_call_id='guess')])
agent = Agent(FunctionModel(model_fn))
@agent.tool_plain(defer_loading=True)
def hidden_tool() -> str:
return 'secret' # pragma: no cover
result = await agent.run('guess the hidden tool')
assert result.output == 'done'
executions = [
part
for part in iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart)
if part.outcome != 'retried'
]
assert executions == []
refusals = [
part
for part in iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart)
if part.outcome == 'retried'
]
assert [str(part.content) for part in refusals] == snapshot(
[
"Tool 'hidden_tool' is not available yet: search for it first, then call it again once you've seen its schema."
]
)
deltas = [
part
for message in result.all_messages()
if isinstance(message, ModelRequest)
for part in message.parts
if isinstance(part, ToolAvailabilityDeltaPart)
]
assert deltas == []
assert all('hidden_tool' not in tools for tools in wire_tools)
async def test_tool_return_deduplicates_new_reveals() -> None:
"""Duplicate names and repeated reveals author one ordered availability delta.
A fully repeated reveal drops out entirely; a partial overlap keeps only the genuinely new
names, in order.
"""
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
if not returns:
return ModelResponse(parts=[ToolCallPart('revealer', {}, tool_call_id='first')])
if len(returns) == 1:
return ModelResponse(parts=[ToolCallPart('revealer', {}, tool_call_id='second')])
if len(returns) == 2:
return ModelResponse(parts=[ToolCallPart('partial_revealer', {}, tool_call_id='third')])
return ModelResponse(parts=[TextPart(content='done')])
agent = Agent(FunctionModel(model_fn))
@agent.tool_plain
def revealer() -> ToolReturn[str]:
return ToolReturn(return_value='ready', tools=['tool_b', 'tool_a', 'tool_b'])
@agent.tool_plain
def partial_revealer() -> ToolReturn[str]:
return ToolReturn(return_value='partially new', tools=['tool_a', 'tool_c'])
result = await agent.run('reveal')
deltas = [
part
for message in result.all_messages()
if isinstance(message, ModelRequest)
for part in message.parts
if isinstance(part, ToolAvailabilityDeltaPart)
]
assert deltas == [
ToolAvailabilityDeltaPart(tools_added=['tool_b', 'tool_a'], tool_call_id='first'),
ToolAvailabilityDeltaPart(tools_added=['tool_c'], tool_call_id='third'),
]
@pytest.mark.parametrize(
'tools',
['get_weather', 1, [1], [[]]],
ids=['bare-string', 'non-sequence', 'non-string-element', 'unhashable-element'],
)
async def test_tool_return_rejects_invalid_tools(tools: object) -> None:
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if list(iter_message_parts(messages, ModelRequest, ToolReturnPart)): # pragma: no cover
return make_text_response('done')
return ModelResponse(parts=[ToolCallPart(tool_name='reveal_weather', args={}, tool_call_id='reveal')])
agent = Agent(FunctionModel(model_fn))
@agent.tool_plain
def reveal_weather() -> ToolReturn[str]:
return ToolReturn(return_value='Weather tools are ready.', tools=cast(Any, tools))
with pytest.raises(UserError, match=r'`ToolReturn\.tools` must be a list of tool names'):
await agent.run('Reveal the weather tool.')
async def test_parallel_tool_returns_keep_each_availability_delta_adjacent() -> None:
"""Parallel execution reorders each return together with its own sibling delta."""
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
if not returns:
return ModelResponse(
parts=[
ToolCallPart(tool_name='reveal_b', args={}, tool_call_id='b'),
ToolCallPart(tool_name='reveal_a', args={}, tool_call_id='a'),
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn))
@agent.tool_plain
async def reveal_a() -> ToolReturn[str]:
await asyncio.sleep(0)
return ToolReturn(return_value='a', tools=['tool_a'])
@agent.tool_plain
async def reveal_b() -> ToolReturn[str]:
await asyncio.sleep(0.01)
return ToolReturn(return_value='b', tools=['tool_b'])
result = await agent.run('reveal both')
request = next(
message
for message in result.all_messages()
if isinstance(message, ModelRequest)
and any(isinstance(part, ToolReturnPart) and part.tool_call_id == 'b' for part in message.parts)
)
assert [(type(part).__name__, getattr(part, 'tool_call_id', None)) for part in request.parts] == snapshot(
[
('ToolReturnPart', 'b'),
('ToolAvailabilityDeltaPart', 'b'),
('ToolReturnPart', 'a'),
('ToolAvailabilityDeltaPart', 'a'),
]
)
async def test_parallel_tool_returns_dedupe_same_reveal_in_history_order() -> None:
"""When parallel calls reveal the same tool, the first call in emitted history owns the delta.
Deduplication must not depend on task completion order: the first-emitted call finishes
LAST here, and must still be the one that carries the availability delta — otherwise the
durable history (and the reveal's wire anchor) would vary with scheduling.
"""
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
if not returns:
return ModelResponse(
parts=[
ToolCallPart(tool_name='slow_first', args={}, tool_call_id='first'),
ToolCallPart(tool_name='fast_second', args={}, tool_call_id='second'),
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn))
@agent.tool_plain
async def slow_first() -> ToolReturn[str]:
await asyncio.sleep(0.01)
return ToolReturn(return_value='slow', tools=['revealed'])
@agent.tool_plain
async def fast_second() -> ToolReturn[str]:
return ToolReturn(return_value='fast', tools=['revealed'])
events: list[AgentStreamEvent] = []
async with agent.iter('reveal in parallel') as agent_run:
async for node in agent_run:
if Agent.is_call_tools_node(node):
async with node.stream(agent_run.ctx) as stream:
events.extend([event async for event in stream])
assert agent_run.result is not None
result = agent_run.result
deltas = [
part
for message in result.all_messages()
if isinstance(message, ModelRequest)
for part in message.parts
if isinstance(part, ToolAvailabilityDeltaPart)
]
assert deltas == [ToolAvailabilityDeltaPart(tools_added=['revealed'], tool_call_id='first')]
assert [event for event in events if isinstance(event, ToolAvailabilityDeltaEvent)] == [
ToolAvailabilityDeltaEvent(part=deltas[0])
]
async def test_deferred_capability_tool_registered_after_construction_defers_until_load() -> None:
"""A tool registered via `@cap.tool` *after* construction defers like a constructor tool: hidden until load.
Deferred tools stay tagged `defer_loading=True`; current visibility is tracked separately.
"""
refunds = Capability[object](id='refunds', description='Refund policy tools.', defer_loading=True)
# Register on the deferred capability *after* construction (decorator path, not the `tools=` arg).
@refunds.tool_plain
def lookup_refund_policy(order_id: str) -> str:
"""Look up the refund policy for an order."""
return f'{order_id}: refund allowed for 30 days'
defer_flag_by_phase: dict[str, bool | None] = {}
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
loaded = any(part.tool_name == LOAD_CAPABILITY_TOOL_NAME for part in tool_returns)
refund_def = next((tool for tool in info.function_tools if tool.name == 'lookup_refund_policy'), None)
defer_flag_by_phase['after_load' if loaded else 'before_load'] = (
refund_def.defer_loading if refund_def else None
)
if not loaded:
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'refunds'}, tool_call_id='load')]
)
if not any(part.tool_name == 'lookup_refund_policy' for part in tool_returns):
return ModelResponse(
parts=[
ToolCallPart(tool_name='lookup_refund_policy', args={'order_id': 'order-1'}, tool_call_id='look')
]
)
result = next(part.content for part in tool_returns if part.tool_name == 'lookup_refund_policy')
return make_text_response(f'final: {result}')
agent = Agent(FunctionModel(model_fn), capabilities=[refunds])
result = await agent.run('Can I get a refund?')
assert result.output == snapshot('final: order-1: refund allowed for 30 days')
assert defer_flag_by_phase == snapshot({'before_load': None, 'after_load': True})
async def test_deferred_capability_tool_stays_available_across_turns() -> None:
"""A capability-owned tool stays callable across every turn after `load_capability`.
Regression guard: the `available_tool_names`/`discovered_tool_names` split must keep a
loaded deferred tool non-deferred on the second (and later) post-load model request,
not just on the turn immediately following the load.
"""
toolset = FunctionToolset()
@toolset.tool_plain
def lookup_refund_policy(order_id: str) -> str:
"""Look up the refund policy for an order."""
return f'{order_id}: refund allowed for 30 days'
refunds = Capability[object](
id='refunds',
description='Refund policy tools.',
toolsets=[toolset],
defer_loading=True,
)
hooks = Hooks()
available_per_turn: list[set[str]] = []
@hooks.on.before_model_request
async def record_available_tools(ctx: RunContext, request_context: ModelRequestContext) -> ModelRequestContext:
available_per_turn.append(ctx.available_tool_names)
return request_context
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
# Turn 1: load the capability.
if not any(part.tool_name == LOAD_CAPABILITY_TOOL_NAME for part in tool_returns):
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'refunds'}, tool_call_id='load')]
)
lookup_calls = [part for part in tool_returns if part.tool_name == 'lookup_refund_policy']
# Turns 2 and 3: call the loaded tool twice, so we exercise two post-load turns.
if len(lookup_calls) < 2:
return ModelResponse(
parts=[
ToolCallPart(
tool_name='lookup_refund_policy',
args={'order_id': f'order-{len(lookup_calls)}'},
tool_call_id=f'lookup-{len(lookup_calls)}',
)
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[refunds, hooks])
result = await agent.run('Can I get a refund?')
assert result.output == 'done'
assert 'lookup_refund_policy' not in available_per_turn[0]
assert len(available_per_turn[1:]) >= 2
assert all('lookup_refund_policy' in names for names in available_per_turn[1:])
async def test_run_context_tools_exposes_deferred_definitions_as_name_keyed_dict() -> None:
"""`ctx.tools` is the full name-keyed dict of `ToolDefinition`s, including entries
that are still deferred (and therefore absent from `ctx.available_tool_names`)."""
toolset = FunctionToolset()
@toolset.tool_plain
def lookup_refund_policy(order_id: str) -> str: # pragma: no cover
return f'{order_id}: refund allowed'
refunds = Capability[object](id='refunds', toolsets=[toolset], defer_loading=True)
seen_tools: list[dict[str, ToolDefinition]] = []
@dataclass
class CaptureCtxToolsCap(AbstractCapability):
async def before_model_request(
self, ctx: RunContext, request_context: ModelRequestContext
) -> ModelRequestContext:
seen_tools.append(ctx.tools)
return request_context
def model_fn(_messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[refunds, CaptureCtxToolsCap()])
await agent.run('hi')
[tools] = seen_tools
# The deferred tool is keyed by its own name and carries `defer_loading=True`,
# even though it's absent from `available_tool_names` until the capability loads.
assert tools['lookup_refund_policy'].name == 'lookup_refund_policy'
assert tools['lookup_refund_policy'].defer_loading is True
async def test_deferred_capability_tool_delta_persists_in_history() -> None:
"""The tool delta after a capability load persists, without duplication on resume."""
toolset = FunctionToolset()
@toolset.tool_plain
def lookup_refund_policy(order_id: str) -> str: # pragma: no cover
"""Look up the refund policy for an order."""
return f'{order_id}: refund allowed for 30 days'
refunds = Capability[object](
id='refunds',
description='Refund policy tools.',
toolsets=[toolset],
defer_loading=True,
)
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
if not any(part.tool_name == LOAD_CAPABILITY_TOOL_NAME for part in tool_returns):
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'refunds'}, tool_call_id='load')]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[refunds])
events: list[AgentStreamEvent] = []
async with agent.iter('Can I get a refund?') as agent_run:
async for node in agent_run:
if Agent.is_call_tools_node(node):
async with node.stream(agent_run.ctx) as stream:
events.extend([event async for event in stream])
assert agent_run.result is not None
result = agent_run.result
def availability_deltas(messages: list[ModelMessage]) -> list[ToolAvailabilityDeltaPart]:
return [part for message in messages for part in message.parts if isinstance(part, ToolAvailabilityDeltaPart)]
messages = result.all_messages()
assert availability_deltas(messages) == [
ToolAvailabilityDeltaPart(tools_added=['lookup_refund_policy'], tool_call_id='load')
]
assert [event for event in events if isinstance(event, ToolAvailabilityDeltaEvent)] == [
ToolAvailabilityDeltaEvent(part=availability_deltas(messages)[0])
]
# Idempotence: feeding the resulting history back in does not inject a duplicate pair
# (the deterministic call_id means it's recognized as already discovered).
result2 = await agent.run('And another refund?', message_history=messages)
new_messages = result2.all_messages()[len(messages) :]
assert availability_deltas(new_messages) == []
async def test_capability_load_history_without_delta_is_backfilled() -> None:
"""An ID-only capability load history gains one delta before the resumed model request."""
refunds = Capability[object](id='refunds', defer_loading=True)
visibility: list[tuple[bool, set[str]]] = []
@refunds.tool_plain
def lookup_refund_policy() -> str: # pragma: no cover
return 'refund allowed'
@dataclass
class CaptureVisibility(AbstractCapability[Any]):
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
visibility.append((ctx.is_tool_available('lookup_refund_policy'), ctx.available_tool_names))
return request_context
history: list[ModelMessage] = [
ModelResponse(parts=[LoadCapabilityCallPart(args={'id': 'refunds'}, tool_call_id='old-load')]),
ModelRequest(parts=[LoadCapabilityReturnPart(content={}, tool_call_id='old-load')]),
]
def model_fn(_messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
assert info.model_request_parameters.revealed_tool_names == {'lookup_refund_policy'}
return make_text_response('done')
result = await Agent(FunctionModel(model_fn), capabilities=[refunds, CaptureVisibility()]).run(
'Continue.', message_history=history
)
assert visibility == [(True, {'load_capability', 'lookup_refund_policy'})]
new_deltas = [
part
for message in result.new_messages()
for part in message.parts
if isinstance(part, ToolAvailabilityDeltaPart)
]
assert new_deltas == [ToolAvailabilityDeltaPart(tools_added=['lookup_refund_policy'])]
class _NoNativeToolSearchModel(FunctionModel):
"""`FunctionModel` that forces the local `search_tools` function path.
`FunctionModel` reports support for every native tool (including native tool search),
which would route deferred standalone tools through the provider rather than the
synthetic `search_tools` function. Dropping `ToolSearchTool` mirrors a model without
native tool-search support, exercising the function-tool discovery path.
"""
@classmethod
def supported_native_tools(cls) -> frozenset[type[AbstractNativeTool]]:
return frozenset(super().supported_native_tools()) - {ToolSearchTool}
async def test_two_deferred_capabilities_loaded_sequentially_both_stay_available() -> None:
"""Loading a second deferred capability does not drop the first one's tool.
Trajectory: load A and call A's tool, then on a later turn load B and call B's tool,
then one more turn. Both capabilities' tools must be non-deferred on every turn after
their respective loads, proving loads are additive and sticky.
"""
toolset_a = FunctionToolset()
@toolset_a.tool_plain
def alpha_tool() -> str:
"""Capability A's tool."""
return 'alpha-result'
toolset_b = FunctionToolset()
@toolset_b.tool_plain
def beta_tool() -> str:
"""Capability B's tool."""
return 'beta-result'
cap_a = Capability[object](id='alpha', description='Alpha tools.', toolsets=[toolset_a], defer_loading=True)
cap_b = Capability[object](id='beta', description='Beta tools.', toolsets=[toolset_b], defer_loading=True)
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
names = {part.tool_name for part in tool_returns}
# Turn 1: load A.
if 'alpha' not in {part.capability_id for part in _load_calls(messages)}:
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'alpha'}, tool_call_id='load-a')]
)
# Turn 2: use A's tool.
if 'alpha_tool' not in names:
return ModelResponse(parts=[ToolCallPart(tool_name='alpha_tool', args={}, tool_call_id='call-a')])
# Turn 3: load B.
if 'beta' not in {part.capability_id for part in _load_calls(messages)}:
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'beta'}, tool_call_id='load-b')]
)
# Turn 4: use B's tool.
if 'beta_tool' not in names:
return ModelResponse(parts=[ToolCallPart(tool_name='beta_tool', args={}, tool_call_id='call-b')])
# Turn 5+: just respond.
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[cap_a, cap_b])
result = await agent.run('Use both capabilities.')
assert result.output == 'done'
async def test_tool_search_discovery_and_capability_load_coexist() -> None:
"""A tool-search-discovered standalone tool and a load_capability tool coexist and persist.
Trajectory: discover a standalone deferred tool via `search_tools`, load a deferred
capability via `load_capability`, then continue for extra turns. Both the searched tool
and the capability's tool must be available together and stay available afterwards.
"""
standalone = FunctionToolset()
@standalone.tool_plain(defer_loading=True)
def searchable_weather(city: str) -> str:
"""Look up the weather for a city."""
return f'{city}: sunny'
cap_toolset = FunctionToolset()
@cap_toolset.tool_plain
def lookup_refund(order_id: str) -> str:
"""Look up the refund policy for an order."""
return f'{order_id}: refundable'
refunds = Capability[object](id='refunds', description='Refund tools.', toolsets=[cap_toolset], defer_loading=True)
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
names = {part.tool_name for part in tool_returns}
# Turn 1: search for the standalone deferred tool.
if not any(part.tool_name == _SEARCH_TOOLS_NAME for part in tool_returns):
return ModelResponse(
parts=[ToolCallPart(tool_name=_SEARCH_TOOLS_NAME, args={'queries': ['weather']}, tool_call_id='search')]
)
# Turn 2: load the deferred capability.
if not _load_calls(messages):
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'refunds'}, tool_call_id='load')]
)
# Turn 3: use the discovered standalone tool.
if 'searchable_weather' not in names:
return ModelResponse(
parts=[ToolCallPart(tool_name='searchable_weather', args={'city': 'Paris'}, tool_call_id='call-w')]
)
# Turn 4: use the capability's tool.
if 'lookup_refund' not in names:
return ModelResponse(
parts=[ToolCallPart(tool_name='lookup_refund', args={'order_id': 'o1'}, tool_call_id='call-r')]
)
# Turn 5+: respond.
return make_text_response('done')
agent = Agent(_NoNativeToolSearchModel(model_fn), capabilities=[standalone_capability(standalone), refunds])
result = await agent.run('Find weather and refund tools.')
assert result.output == 'done'
async def test_deferred_capability_tool_delta_not_duplicated_over_long_trajectory() -> None:
"""The tool availability delta for a loaded capability appears exactly once.
Extends the persistence test to >= 3 model-request turns after the load: the delta must
remain singular across the whole trajectory, and the capability's tool stays available
on every post-load turn.
"""
toolset = FunctionToolset()
@toolset.tool_plain
def lookup_refund_policy(order_id: str) -> str:
"""Look up the refund policy for an order."""
return f'{order_id}: refund allowed for 30 days'
refunds = Capability[object](
id='refunds', description='Refund policy tools.', toolsets=[toolset], defer_loading=True
)
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
if not any(part.tool_name == LOAD_CAPABILITY_TOOL_NAME for part in tool_returns):
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'refunds'}, tool_call_id='load')]
)
# Three post-load turns that each call the loaded tool, then respond.
lookup_calls = [part for part in tool_returns if part.tool_name == 'lookup_refund_policy']
if len(lookup_calls) < 3:
return ModelResponse(
parts=[
ToolCallPart(
tool_name='lookup_refund_policy',
args={'order_id': f'order-{len(lookup_calls)}'},
tool_call_id=f'lookup-{len(lookup_calls)}',
)
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[refunds])
result = await agent.run('Refund please.')
assert result.output == 'done'
messages = result.all_messages()
tool_deltas = [
part for message in messages for part in message.parts if isinstance(part, ToolAvailabilityDeltaPart)
]
assert tool_deltas == [ToolAvailabilityDeltaPart(tools_added=['lookup_refund_policy'], tool_call_id='load')]
async def test_deferred_capability_tool_available_on_turn_that_does_not_call_it() -> None:
"""A loaded capability's tool stays available on a turn that does not call it.
After loading, the model calls an unrelated visible tool (not the capability's tool) and
then responds. The capability's tool must remain non-deferred on those turns — loading is
sticky, not gated on per-turn usage.
"""
visible_toolset = FunctionToolset()
@visible_toolset.tool_plain
def ping() -> str:
"""An always-visible tool unrelated to the capability."""
return 'pong'
cap_toolset = FunctionToolset()
@cap_toolset.tool_plain
def lookup_refund_policy(order_id: str) -> str: # pragma: no cover
"""Look up the refund policy for an order."""
return f'{order_id}: refund allowed for 30 days'
refunds = Capability[object](
id='refunds', description='Refund policy tools.', toolsets=[cap_toolset], defer_loading=True
)
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
names = {part.tool_name for part in tool_returns}
# Turn 1: load the capability.
if not any(part.tool_name == LOAD_CAPABILITY_TOOL_NAME for part in tool_returns):
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'refunds'}, tool_call_id='load')]
)
# Turn 2: call an UNRELATED tool, never the capability's tool.
if 'ping' not in names:
return ModelResponse(parts=[ToolCallPart(tool_name='ping', args={}, tool_call_id='call-ping')])
# Turn 3: respond without ever calling the capability's tool.
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), tools=[ping], capabilities=[refunds])
# `ping` is registered via a function tool on the agent; ensure both paths see it.
result = await agent.run('Load refunds but use ping.')
assert result.output == 'done'
def _load_calls(messages: list[ModelMessage]) -> list[LoadCapabilityCallPart]:
"""All `load_capability` call parts in the message history."""
return [
part
for message in messages
if isinstance(message, ModelResponse)
for part in message.parts
if isinstance(part, LoadCapabilityCallPart)
]
def standalone_capability(toolset: FunctionToolset) -> Capability:
"""Wrap a toolset of standalone deferred tools in an eager capability (tools keep their own defer flag)."""
return Capability[object](id='standalone', description='Standalone searchable tools.', toolsets=[toolset])
async def test_deferred_capability_load_includes_toolset_instructions() -> None:
"""Instructions declared on a deferred capability's toolset surface via the `load_capability` return.
The wrapping `CapabilityOwnedToolset` silences `get_instructions` for deferred-loading
capabilities (so toolset hints don't leak into the prompt), then re-emits them on load
alongside the capability's own instructions.
"""
toolset = FunctionToolset(instructions='Use the refund tool with the order id, not the customer id.')
@toolset.tool_plain
def lookup_refund(order_id: str) -> str:
return f'{order_id}: ok'
refunds = Capability[object](
id='refunds',
description='Refund tools.',
instructions='Quote the refund policy verbatim.',
toolsets=[toolset],
defer_loading=True,
)
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
tool_returns = list(iter_message_parts(messages, ModelRequest, ToolReturnPart))
already_loaded = any(
isinstance(part, LoadCapabilityReturnPart)
for message in messages
if isinstance(message, ModelRequest)
for part in message.parts
)
if not already_loaded:
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': 'refunds'},
tool_call_id='load-refunds',
)
]
)
if not any(part.tool_name == 'lookup_refund' for part in tool_returns):
return ModelResponse(
parts=[
ToolCallPart(
tool_name='lookup_refund',
args={'order_id': 'order-123'},
tool_call_id='lookup-refund',
)
]
)
refund_result = next(part.content for part in tool_returns if part.tool_name == 'lookup_refund')
return make_text_response(str(refund_result))
agent = Agent(FunctionModel(model_fn), capabilities=[refunds])
result = await agent.run('hi')
assert result.output == 'order-123: ok'
[load_return] = [
part
for message in result.all_messages()
if isinstance(message, ModelRequest)
for part in message.parts
if isinstance(part, LoadCapabilityReturnPart)
]
assert load_return.content == {'message': "Capability 'refunds' loaded. Its instructions, if any, follow."}
assert loaded_instructions(result.all_messages(), 'refunds') == snapshot("""\
Quote the refund policy verbatim.
Use the refund tool with the order id, not the customer id.\
""")
first_request = next(message for message in result.all_messages() if isinstance(message, ModelRequest))
assert first_request.instructions == snapshot(
"""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund tools.\
"""
)
assert first_request.instructions is not None
assert 'Use the refund tool' not in first_request.instructions
async def test_deferred_capability_load_drops_empty_toolset_instructions() -> None:
"""Empty toolset instructions are filtered from load returns."""
from dataclasses import dataclass
from pydantic_ai.messages import InstructionPart
from pydantic_ai.toolsets.wrapper import WrapperToolset
@dataclass
class _LiteralInstructionsToolset(WrapperToolset):
raw: tuple[str | InstructionPart, ...] = ()
async def get_instructions(self, ctx: RunContext) -> list[str | InstructionPart]:
return list(self.raw)
toolset = _LiteralInstructionsToolset(
wrapped=FunctionToolset(),
raw=(
InstructionPart(content=' ', dynamic=False),
InstructionPart(content='Real hint from toolset.', dynamic=False),
'',
),
)
cap = Capability[object](id='cap', description='Custom-toolset cap.', toolsets=[toolset], defer_loading=True)
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
already_loaded = any(
isinstance(part, LoadCapabilityReturnPart)
for message in messages
if isinstance(message, ModelRequest)
for part in message.parts
)
if not already_loaded:
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': 'cap'},
tool_call_id='load',
)
]
)
return make_text_response('ok')
agent = Agent(FunctionModel(model_fn), capabilities=[cap])
result = await agent.run('hi')
[load_return] = [
part
for message in result.all_messages()
if isinstance(message, ModelRequest)
for part in message.parts
if isinstance(part, LoadCapabilityReturnPart)
]
assert load_return.content == {'message': "Capability 'cap' loaded. Its instructions, if any, follow."}
assert loaded_instructions(result.all_messages(), 'cap') == 'Real hint from toolset.'
async def test_unknown_deferred_capability_id_does_not_reveal_hidden_tools() -> None:
toolset = FunctionToolset()
@toolset.tool_plain
def hidden_tool() -> str:
return 'hidden' # pragma: no cover
hidden = Capability[object](
id='hidden',
description='Hidden tool access.',
toolsets=[toolset],
defer_loading=True,
)
seen_tool_state: list[list[tuple[str, bool]]] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
seen_tool_state.append([(t.name, bool(t.defer_loading)) for t in info.function_tools])
# Give up on the first signal of tool feedback — a `ToolReturnPart`, whether it
# succeeded (which can't happen here) or carries `outcome='retried'` (the framework
# signaling the bad cap id). Without the retry branch, we'd loop past
# `max_retries` and raise `UnexpectedModelBehavior` instead of giving up.
if not any(
isinstance(part, ToolReturnPart)
for message in messages
if isinstance(message, ModelRequest)
for part in message.parts
):
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': 'missing'},
tool_call_id='load-missing',
)
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[hidden])
result = await agent.run('load missing')
assert result.output == snapshot('done')
assert seen_tool_state == snapshot(
[
[('load_capability', False)],
[('load_capability', False)],
]
)
history_parts = [part for message in result.all_messages() for part in message.parts]
assert not any(isinstance(part, LoadCapabilityReturnPart) for part in history_parts)
[retry] = [part for part in history_parts if isinstance(part, ToolReturnPart) and part.outcome == 'retried']
assert retry.content == snapshot("No capability found with id 'missing'. Available capability ids: 'hidden'.")
async def test_load_capability_inherits_agent_tool_retries() -> None:
"""`load_capability` honors the agent's tool retry budget."""
deferred = Capability[object](
id='deferred',
description='Deferred.',
defer_loading=True,
)
calls = 0
def model_fn(_messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
nonlocal calls
calls += 1
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': 'missing'},
tool_call_id=f'load-missing-{calls}',
)
]
)
agent = Agent(FunctionModel(model_fn), capabilities=[deferred], retries={'tools': 3})
with pytest.raises(UnexpectedModelBehavior):
await agent.run('load missing')
assert calls == 4
async def test_load_capability_for_already_available_capability_is_a_no_op() -> None:
"""#8096: a load of a capability that is already active succeeds as a no-op — the
confirmation is a load return, not a retry, so no retry budget is spent on it."""
always_on = Capability[object](
id='always-on',
description='Already visible.',
instructions='Already visible instructions.',
)
deferred = Capability[object](
id='deferred',
description='Deferred.',
instructions='Deferred instructions.',
defer_loading=True,
)
expected_message = LOAD_CAPABILITY_ALREADY_ACTIVE_MESSAGE_TEMPLATE.format(capability_id='always-on')
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
if any(
isinstance(part, LoadCapabilityReturnPart)
for message in messages
if isinstance(message, ModelRequest)
for part in message.parts
):
return make_text_response('done')
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': 'always-on'},
tool_call_id='load-always-on',
)
]
)
agent = Agent(FunctionModel(model_fn), capabilities=[always_on, deferred])
result = await agent.run('load always-on')
assert result.output == 'done'
[ret] = [
part
for message in result.all_messages()
for part in message.parts
if isinstance(part, LoadCapabilityReturnPart)
]
assert ret.content == {'message': expected_message}
assert not any(
isinstance(part, ToolReturnPart) and part.outcome == 'retried'
for message in result.all_messages()
for part in message.parts
)
async def test_load_capability_repeated_load_of_loaded_capability_is_a_no_op() -> None:
"""#8096: re-loading a capability this run already loaded succeeds as a no-op on every
repeat — the run is not aborted for exhausting the retry budget, and the capability's
instructions are still the ones the first load stated."""
deferred = Capability[object](
id='deferred',
description='Deferred.',
instructions='Deferred instructions.',
defer_loading=True,
)
expected_no_op = LOAD_CAPABILITY_ALREADY_ACTIVE_MESSAGE_TEMPLATE.format(capability_id='deferred')
load_calls = 0
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
nonlocal load_calls
load_calls += 1
if load_calls > 4:
return make_text_response('done')
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': 'deferred'},
tool_call_id=f'load-deferred-{load_calls}',
)
]
)
agent = Agent(FunctionModel(model_fn), capabilities=[deferred])
result = await agent.run('load four times')
assert result.output == 'done'
load_returns = [
part
for message in result.all_messages()
for part in message.parts
if isinstance(part, LoadCapabilityReturnPart)
]
assert [ret.content for ret in load_returns] == [
{'message': LOAD_CAPABILITY_LOADED_MESSAGE_TEMPLATE.format(capability_id='deferred')},
{'message': expected_no_op},
{'message': expected_no_op},
{'message': expected_no_op},
]
assert not any(
isinstance(part, ToolReturnPart) and part.outcome == 'retried'
for message in result.all_messages()
for part in message.parts
)
assert parse_loaded_capabilities(result.all_messages()) == {'deferred'}
assert loaded_instructions(result.all_messages(), 'deferred') == 'Deferred instructions.'
async def test_load_capability_reload_after_loading_another_does_not_restate_instructions() -> None:
"""#11275: a no-op reload of an already-loaded capability must not count as a fresh
load — loading one capability, then another, then the first again states the first
capability's instructions exactly once, not once per load return."""
first = Capability[object](
id='first',
description='First.',
instructions='First instructions.',
defer_loading=True,
)
second = Capability[object](
id='second',
description='Second.',
instructions='Second instructions.',
defer_loading=True,
)
script = iter(['first', 'second', 'first'])
calls = 0
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
nonlocal calls
calls += 1
if (capability_id := next(script, None)) is None:
return make_text_response('done')
return ModelResponse(
parts=[
ToolCallPart(
tool_name=LOAD_CAPABILITY_TOOL_NAME,
args={'id': capability_id},
tool_call_id=f'load-{calls}',
)
]
)
agent = Agent(FunctionModel(model_fn), capabilities=[first, second])
result = await agent.run('load first, then second, then first again')
assert result.output == 'done'
messages = result.all_messages()
def instruction_delta_count(capability_id: str) -> int:
return sum(
1
for message in messages
if isinstance(message, ModelRequest)
for part in message.parts
if isinstance(part, InstructionDeltaPart) and str(part.id) == f'capability:{capability_id}'
)
assert instruction_delta_count('first') == 1
assert instruction_delta_count('second') == 1
assert loaded_instructions(messages, 'first') == 'First instructions.'
# The reload itself is still the success-shaped no-op, not a retry.
load_returns = [part for part in iter_message_parts(messages, ModelRequest, LoadCapabilityReturnPart)]
assert load_returns[-1].content == {
'message': LOAD_CAPABILITY_ALREADY_ACTIVE_MESSAGE_TEMPLATE.format(capability_id='first')
}
assert parse_loaded_capabilities(messages) == {'first', 'second'}
async def test_load_capability_unknown_id_lists_valid_ids() -> None:
"""#11275: an unknown id fails with the valid loadable capability ids listed, so the
model can correct itself instead of guessing — and only loadable ids are listed."""
refunds = Capability[object](id='refunds', description='Refund tools.', defer_loading=True)
billing = Capability[object](id='billing', description='Billing tools.', defer_loading=True)
always_on = Capability[object](id='always-on', instructions='Always on.')
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
retried = [
part for part in iter_message_parts(messages, ModelRequest, ToolReturnPart) if part.outcome == 'retried'
]
if retried:
return make_text_response('done')
return ModelResponse(
parts=[ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'refnd'}, tool_call_id='l1')]
)
agent = Agent(FunctionModel(model_fn), capabilities=[refunds, billing, always_on])
result = await agent.run('load typo')
assert result.output == 'done'
[retry] = [
part
for message in result.all_messages()
for part in message.parts
if isinstance(part, ToolReturnPart) and part.outcome == 'retried'
]
assert retry.content == "No capability found with id 'refnd'. Available capability ids: 'billing', 'refunds'."
async def test_load_capability_reload_after_compaction_in_same_response_loads_again() -> None:
"""A reload in the response that compacts away the first load succeeds and states the instructions again (#12936).
The already-active check still sees the load from before the `CompactionPart`, so the return is the no-op
one, but it's a successful load return in the new window: no retry is spent, and the next request states
the capability's instructions again. A further reload after that is a no-op that states nothing.
"""
deferred = Capability[object](
id='deferred', description='Deferred.', instructions='Deferred instructions.', defer_loading=True
)
def load(tool_call_id: str) -> ToolCallPart:
return ToolCallPart(tool_name=LOAD_CAPABILITY_TOOL_NAME, args={'id': 'deferred'}, tool_call_id=tool_call_id)
responses = iter(
[
ModelResponse(parts=[load('initial')]),
ModelResponse(parts=[CompactionPart(content='Summary.'), load('after-compaction')]),
ModelResponse(parts=[load('next-step')]),
make_text_response('done'),
]
)
agent = Agent(FunctionModel(lambda _messages, _info: next(responses)), capabilities=[deferred])
result = await agent.run('load, compact, reload')
assert result.output == 'done'
messages = result.all_messages()
load_returns = list(iter_message_parts(messages, ModelRequest, LoadCapabilityReturnPart))
assert [(part.tool_call_id, part.outcome) for part in load_returns] == [
('initial', 'success'),
('after-compaction', 'success'),
('next-step', 'success'),
]
statements = [
(index, part.content)
for index, message in enumerate(messages)
if isinstance(message, ModelRequest)
for part in message.parts
if isinstance(part, InstructionDeltaPart)
]
assert statements == [(2, 'Deferred instructions.'), (4, 'Deferred instructions.')]
@pytest.mark.parametrize('mode', ['parallel', 'sequential'])
async def test_load_capability_called_twice_in_one_response_loads_once(mode: ParallelExecutionMode) -> None:
"""Only the first `load_capability` call for an id in a response delivers its instructions (#7298).
Sibling calls can't see each other's load through `active_capability_ids` (a load only counts once
its return reaches history), so the duplicate is refused by response position instead, and a load
of a different capability in the same response is unaffected.
"""
def dyn_tool() -> str:
return 'ok' # pragma: no cover
dyn = Capability[object](
id='dyn', description='Dynamic.', instructions='Dyn runbook.', tools=[dyn_tool], defer_loading=True
)
other = Capability[object](id='other', description='Other.', instructions='Other runbook.', defer_loading=True)
def model_fn(messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(
parts=[
ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'dyn'}, tool_call_id='first'),
ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'other'}, tool_call_id='other'),
ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'dyn'}, tool_call_id='duplicate'),
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[dyn, other])
with Agent.parallel_tool_call_execution_mode(mode):
result = await agent.run('load dyn twice')
assert result.output == 'done'
messages = result.all_messages()
tool_results = [part for part in messages[2].parts if isinstance(part, ToolReturnPart | ToolAvailabilityDeltaPart)]
assert [(type(part).__name__, part.tool_call_id) for part in tool_results] == [
('LoadCapabilityReturnPart', 'first'),
('ToolAvailabilityDeltaPart', 'first'),
('LoadCapabilityReturnPart', 'other'),
('ToolReturnPart', 'duplicate'),
]
first, _, other_return, duplicate = tool_results
assert isinstance(first, LoadCapabilityReturnPart) and isinstance(other_return, LoadCapabilityReturnPart)
assert loaded_instructions(messages, 'dyn') == 'Dyn runbook.'
assert loaded_instructions(messages, 'other') == 'Other runbook.'
assert isinstance(duplicate, ToolReturnPart) and duplicate.outcome == 'retried'
assert duplicate.content == LOAD_CAPABILITY_DUPLICATE_CALL_MESSAGE_TEMPLATE.format(capability_id='dyn')
assert parse_loaded_capabilities(messages) == {'dyn', 'other'}
def _refunds() -> Capability[object]:
"""A deferred capability with instructions and a toolset that has instructions of its own."""
toolset = FunctionToolset[object](instructions='Pass the order ID, not the customer ID.')
@toolset.tool_plain
def refund_status(order_id: str) -> str:
return f'{order_id}: refunded'
return Capability[object](
id='refunds',
description='Refund tools.',
instructions='Quote the refund policy.',
toolsets=[toolset],
defer_loading=True,
)
def _open_case_then_check_refund(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
"""Opens a case, calls `refund_status` once it's visible, then answers with its result."""
returns = {part.tool_name: part.content for part in iter_message_parts(messages, ModelRequest, ToolReturnPart)}
if 'refund_status' in returns:
return make_text_response(str(returns['refund_status']))
if any(tool.name == 'refund_status' for tool in info.function_tools):
return ModelResponse(parts=[ToolCallPart('refund_status', {'order_id': 'A1'}, tool_call_id='status')])
if 'open_case' not in returns:
return ModelResponse(parts=[ToolCallPart('open_case', {}, tool_call_id='open')])
return make_text_response('done')
def _load_records(messages: list[ModelMessage]) -> list[tuple[str, str | None]]:
"""Each capability load recorded in `messages`, by the model or from code, as `(capability id, tool call id)`."""
exchanges = LoadExchanges()
records: list[tuple[str, str | None]] = []
for message in messages:
for part in message.parts:
for capability_id in exchanges.loads(part):
assert isinstance(part, LoadCapabilityReturnPart | CapabilityLoadDeltaPart)
records.append((capability_id, part.tool_call_id))
return records
async def test_load_capability_from_sync_tool() -> None:
"""`ctx.load_capability()` is a plain function, so a sync tool can load a capability too."""
agent = Agent(FunctionModel(_open_case_then_check_refund), capabilities=[_refunds()])
@agent.tool
def open_case(ctx: RunContext[object]) -> str:
return f'loaded: {ctx.load_capability("refunds")}'
result = await agent.run('Was I refunded?')
assert (result.output, _load_records(result.all_messages())) == ('A1: refunded', [('refunds', 'open')])
@pytest.mark.parametrize('by', ['id', 'instance'])
async def test_load_capability_from_tool(by: str) -> None:
"""A tool's load is recorded after the tool's return, so the capability is active from the next request.
No `load_capability` call is written: the record is a `CapabilityLoadDeltaPart` naming the capability
and the tool call that loaded it, then a `ToolAvailabilityDeltaPart` revealing its tool, and the request
states the capability's instructions and its toolset's in the system voice, as after a model's load.
"""
refunds = _refunds()
agent = Agent(FunctionModel(_open_case_then_check_refund), capabilities=[refunds])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
return f'loaded: {ctx.load_capability("refunds" if by == "id" else refunds)}'
result = await agent.run('Was I refunded?')
assert result.all_messages() == snapshot(
[
ModelRequest(
parts=[
UserPromptPart(content='Was I refunded?', timestamp=IsDatetime()),
InstructionBaselinePart(
instructions=[
InstructionPart(
content="""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund tools.\
""",
dynamic=True,
on_change='append',
id=InstructionId(source=CapabilityInstructionSource(id='deferred_capabilities')),
)
]
),
],
timestamp=IsDatetime(),
instructions="""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund tools.\
""",
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelResponse(
parts=[ToolCallPart(tool_name='open_case', args={}, tool_call_id='open')],
usage=RequestUsage(input_tokens=53, output_tokens=2),
model_name='function:_open_case_then_check_refund:',
model_id='function:function:_open_case_then_check_refund:',
timestamp=IsDatetime(),
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelRequest(
parts=[
ToolReturnPart(
tool_name='open_case', content='loaded: True', tool_call_id='open', timestamp=IsDatetime()
),
CapabilityLoadDeltaPart(loaded=['refunds'], tool_call_id='open'),
ToolAvailabilityDeltaPart(tools_added=['refund_status'], tool_call_id='open'),
InstructionDeltaPart(
id=InstructionId(source=CapabilityInstructionSource(id='refunds')),
content="""\
Quote the refund policy.
Pass the order ID, not the customer ID.\
""",
),
],
timestamp=IsDatetime(),
instructions="""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund tools.\
""",
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelResponse(
parts=[ToolCallPart(tool_name='refund_status', args={'order_id': 'A1'}, tool_call_id='status')],
usage=RequestUsage(input_tokens=82, output_tokens=7),
model_name='function:_open_case_then_check_refund:',
model_id='function:function:_open_case_then_check_refund:',
timestamp=IsDatetime(),
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelRequest(
parts=[
ToolReturnPart(
tool_name='refund_status', content='A1: refunded', tool_call_id='status', timestamp=IsDatetime()
)
],
timestamp=IsDatetime(),
instructions="""\
The following capabilities are deferred and can be loaded using the `load_capability` tool. A capability's tools stay hidden until it is loaded:
- refunds: Refund tools.\
""",
run_id=IsStr(),
conversation_id=IsStr(),
),
ModelResponse(
parts=[TextPart(content='A1: refunded')],
usage=RequestUsage(input_tokens=84, output_tokens=9),
model_name='function:_open_case_then_check_refund:',
model_id='function:function:_open_case_then_check_refund:',
timestamp=IsDatetime(),
run_id=IsStr(),
conversation_id=IsStr(),
),
]
)
async def test_load_capability_from_tool_hook() -> None:
"""An `after_tool_execute` hook can load a capability whose tool the model then calls."""
hooks = Hooks[object]()
@hooks.on.after_tool_execute
async def load_refunds(
ctx: RunContext[object], *, call: ToolCallPart, tool_def: ToolDefinition, args: dict[str, Any], result: Any
) -> Any:
if tool_def.name == 'open_case':
ctx.load_capability('refunds')
return result
agent = Agent(FunctionModel(_open_case_then_check_refund), capabilities=[_refunds(), hooks])
@agent.tool_plain
def open_case() -> str:
return 'Case opened.'
result = await agent.run('Was I refunded?')
assert (result.output, parse_loaded_capabilities(result.all_messages())) == ('A1: refunded', {'refunds'})
_ALWAYS_ON_WITHOUT_ID = Capability[object](instructions='Be polite.')
@pytest.mark.parametrize(
'responses, loads, expected_results, expected_loads',
[
pytest.param([['open_case']], ['always-on'], [False], 0, id='always-on'),
pytest.param([['open_case']], [_ALWAYS_ON_WITHOUT_ID], [False], 0, id='always-on-without-id'),
pytest.param([['load_capability'], ['open_case']], ['refunds'], [False], 1, id='already-loaded'),
pytest.param([['open_case']], ['refunds', 'refunds'], [True, False], 1, id='already-queued'),
pytest.param([['load_capability', 'open_case']], ['refunds'], [False], 1, id='model-loads-it-in-same-response'),
],
)
async def test_load_capability_returns_whether_it_queued_a_load(
responses: list[list[str]],
loads: list[str | AbstractCapability[object]],
expected_results: list[bool],
expected_loads: int,
) -> None:
"""Loading a capability that is active or already being loaded is a no-op that returns `False`.
The model makes each response's tool calls in turn: `load_capability` loads `refunds`, `open_case` runs the loads.
"""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
step = sum(isinstance(message, ModelResponse) for message in messages)
if step >= len(responses):
return make_text_response('done')
return ModelResponse(
parts=[
ToolCallPart(name, {'id': 'refunds'} if name == 'load_capability' else {}) for name in responses[step]
]
)
results: list[bool] = []
always_on = Capability[object](id='always-on', instructions='Always on.')
agent = Agent(FunctionModel(model_fn), capabilities=[_refunds(), always_on, _ALWAYS_ON_WITHOUT_ID])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
for capability in loads:
results.append(ctx.load_capability(capability))
return 'Case opened.'
result = await agent.run('Was I refunded?')
assert (results, len(_load_records(result.all_messages()))) == (expected_results, expected_loads)
async def test_parallel_tools_loading_one_capability_load_it_once() -> None:
"""Two tool calls loading the same capability queue one load between them: the second finds the first's queued."""
slow = Capability[object](id='slow', description='Slow instructions.', defer_loading=True)
@slow.instructions
async def slow_instructions() -> str:
await asyncio.sleep(0)
return 'Slow runbook.'
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('open_case', {}), ToolCallPart('open_case', {})])
return make_text_response('done')
results: list[bool] = []
agent = Agent(FunctionModel(model_fn), capabilities=[slow])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
results.append(ctx.load_capability('slow'))
return 'Case opened.'
result = await agent.run('Open two cases.')
assert (sorted(results), len(_load_records(result.all_messages()))) == ([False, True], 1)
async def test_parallel_sync_tools_loading_one_capability_load_it_once(monkeypatch: pytest.MonkeyPatch) -> None:
"""Two sync tools, which run in worker threads, loading the same capability at once queue one load between them.
A barrier holds both threads after they've checked for a queued load and before either queues one, so without
an atomic check-and-queue both would queue it.
"""
barrier = threading.Barrier(2, timeout=5)
executing_load_calls = _deferred_capability_loader._executing_load_calls # pyright: ignore[reportPrivateUsage]
def executing_load_calls_after_both_checked(
ctx: RunContext[Any], capability_id: str
) -> list[LoadCapabilityCallPart]:
barrier.wait()
return executing_load_calls(ctx, capability_id)
monkeypatch.setattr(_deferred_capability_loader, '_executing_load_calls', executing_load_calls_after_both_checked)
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(
parts=[ToolCallPart('open_case', {}, tool_call_id='a'), ToolCallPart('open_case', {}, tool_call_id='b')]
)
return make_text_response('done')
results: list[bool] = []
agent = Agent(FunctionModel(model_fn), capabilities=[_refunds()])
@agent.tool
def open_case(ctx: RunContext[object]) -> str:
results.append(ctx.load_capability('refunds'))
return 'Case opened.'
result = await agent.run('Open two cases.')
records = [
type(part).__name__
for message in result.all_messages()
for part in message.parts
if isinstance(part, CapabilityLoadDeltaPart | ToolAvailabilityDeltaPart)
]
assert (sorted(results), records) == ([False, True], ['CapabilityLoadDeltaPart', 'ToolAvailabilityDeltaPart'])
async def test_load_capability_survives_a_fallback_attempt() -> None:
"""A load from code rides along with the request a fallback model retries, without the model seeing its record.
The primary model fails on the request after the loading tool's result, so `ModelFallback` makes another attempt
at that request on the fallback model. That attempt has the capability: its tool and instructions, but not the
`CapabilityLoadDeltaPart`, which `prepare_messages` drops. History records the load once.
"""
def primary(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('open_case', {}, tool_call_id='open')])
raise ModelAPIError(model_name='primary', message='overloaded')
seen: list[tuple[list[str], list[str]]] = []
def fallback(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
seen.append(
(
[type(part).__name__ for part in messages[-1].parts],
[tool.name for tool in info.function_tools],
)
)
return make_text_response('Refunds take 5 days.')
agent = Agent(FunctionModel(primary), capabilities=[_refunds(), ModelFallback(FunctionModel(fallback))])
@agent.tool
def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability('refunds')
return 'Case opened.'
result = await agent.run('Was I refunded?')
assert seen == snapshot(
[(['ToolReturnPart', 'UserPromptPart', 'UserPromptPart'], ['load_capability', 'open_case', 'refund_status'])]
)
assert _load_records(result.all_messages()) == [('refunds', 'open')]
@dataclass
class _PerRunCapability(AbstractCapability[object]):
id: str | None = 'per-run'
defer_loading: bool = True
async def for_run(self, ctx: RunContext[object]) -> AbstractCapability[object]:
return replace(self)
def get_instructions(self) -> str:
return 'Per-run instructions.'
async def test_load_capability_by_instance_resolves_per_run_copy() -> None:
"""Loading by the instance passed to the agent works when `for_run` registered a copy of it for the run."""
per_run = _PerRunCapability()
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('open_case', {})])
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[per_run])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
assert ctx.capabilities['per-run'] is not per_run
return f'loaded: {ctx.load_capability(per_run)}'
result = await agent.run('Open a case.')
assert parse_loaded_capabilities(result.all_messages()) == {'per-run'}
async def test_load_capability_without_tools_records_the_load() -> None:
"""Loading an instructions-only capability records it with no tools, and states its instructions."""
policy = Capability[object](
id='policy', description='Refund policy.', instructions='Refunds take 5 days.', defer_loading=True
)
agent = Agent(FunctionModel(_open_case_then_check_refund), capabilities=[policy])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability('policy')
return 'Case opened.'
result = await agent.run('How long do refunds take?')
assert result.all_messages()[2].parts == snapshot(
[
ToolReturnPart(tool_name='open_case', content='Case opened.', tool_call_id='open', timestamp=IsDatetime()),
CapabilityLoadDeltaPart(loaded=['policy'], tool_call_id='open'),
InstructionDeltaPart(
id=InstructionId(source=CapabilityInstructionSource(id='policy')), content='Refunds take 5 days.'
),
]
)
async def test_loads_before_one_request_are_recorded_in_order() -> None:
"""Loads queued by the tool calls of one response are each recorded on the request after them, in queue order.
The tools run sequentially so the loads are queued, and recorded, in a fixed order.
"""
policy = Capability[object](
id='policy', description='Refund policy.', instructions='Refunds take 5 days.', defer_loading=True
)
escalation = Capability[object](
id='escalation', description='Escalation.', instructions='Escalate after 2 days.', defer_loading=True
)
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(
parts=[
ToolCallPart('open_case', {}, tool_call_id='open'),
ToolCallPart('escalate', {}, tool_call_id='esc'),
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[_refunds(), policy, escalation])
@agent.tool(sequential=True)
async def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability('refunds')
ctx.load_capability('policy')
return 'Case opened.'
@agent.tool(sequential=True)
async def escalate(ctx: RunContext[object]) -> str:
ctx.load_capability('escalation')
return 'Escalated.'
result = await agent.run('Where is my refund?')
assert result.all_messages()[2].parts == snapshot(
[
ToolReturnPart(tool_name='open_case', content='Case opened.', tool_call_id='open', timestamp=IsDatetime()),
ToolReturnPart(tool_name='escalate', content='Escalated.', tool_call_id='esc', timestamp=IsDatetime()),
CapabilityLoadDeltaPart(loaded=['refunds'], tool_call_id='open'),
ToolAvailabilityDeltaPart(tools_added=['refund_status'], tool_call_id='open'),
CapabilityLoadDeltaPart(loaded=['policy'], tool_call_id='open'),
CapabilityLoadDeltaPart(loaded=['escalation'], tool_call_id='esc'),
InstructionDeltaPart(
id=InstructionId(source=CapabilityInstructionSource(id='refunds')),
content="""\
Quote the refund policy.
Pass the order ID, not the customer ID.\
""",
),
InstructionDeltaPart(
id=InstructionId(source=CapabilityInstructionSource(id='policy')), content='Refunds take 5 days.'
),
InstructionDeltaPart(
id=InstructionId(source=CapabilityInstructionSource(id='escalation')), content='Escalate after 2 days.'
),
]
)
assert parse_loaded_capabilities(result.all_messages()) == {'refunds', 'policy', 'escalation'}
async def test_content_enqueued_by_a_loading_tool_joins_its_return() -> None:
"""Content a loading tool enqueues joins the tool's return, ahead of the load's record, in history as in the events.
The load is recorded on the same request as the tool's return rather than as messages of its own, so the
content goes where content a tool enqueues always goes (#7043).
"""
async def stream_fn(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str | DeltaToolCalls]:
if len(messages) == 1:
yield {0: DeltaToolCall(name='open_case', json_args='{}')}
else:
yield 'done'
agent = Agent(FunctionModel(stream_function=stream_fn), capabilities=[_refunds()])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
ctx.enqueue('The customer is a VIP.')
ctx.load_capability('refunds')
return 'Case opened.'
events: list[AgentStreamEvent] = []
async def event_stream_handler(_: RunContext[object], stream: AsyncIterable[AgentStreamEvent]) -> None:
async for event in stream:
events.append(event)
result = await agent.run('Where is my refund?', event_stream_handler=event_stream_handler)
assert [[type(part).__name__ for part in message.parts] for message in result.all_messages()] == snapshot(
[
['UserPromptPart', 'InstructionBaselinePart'],
['ToolCallPart'],
[
'ToolReturnPart',
'UserPromptPart',
'CapabilityLoadDeltaPart',
'ToolAvailabilityDeltaPart',
'InstructionDeltaPart',
],
['TextPart'],
]
)
assert [
[type(part).__name__ for message in event.messages for part in message.parts]
if isinstance(event, EnqueuedMessagesEvent)
else type(event.part).__name__
for event in events
if isinstance(event, EnqueuedMessagesEvent | ToolAvailabilityDeltaEvent)
] == snapshot([['UserPromptPart'], 'ToolAvailabilityDeltaPart'])
@pytest.mark.parametrize(
'capability, error',
[
pytest.param('missing', "No capability with id 'missing' is registered in this run.", id='unknown-id'),
pytest.param(
Capability[object](id='unregistered', defer_loading=True),
"Capability Capability(id='unregistered') is not registered in this run.",
id='unregistered-instance',
),
],
)
async def test_load_capability_of_unregistered_capability_raises(
capability: str | AbstractCapability[object], error: str
) -> None:
agent = Agent(FunctionModel(_open_case_then_check_refund), capabilities=[_refunds()])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability(capability)
return 'Case opened.' # pragma: no cover
with pytest.raises(UserError) as exc_info:
await agent.run('hi')
assert str(exc_info.value) == error
def _load_refunds_from(hook: str) -> Hooks[object]:
"""A `Hooks` capability that loads `refunds` from `hook`."""
hooks = Hooks[object]()
if hook == 'before_run':
@hooks.on.before_run
async def load_before_run(ctx: RunContext[object]) -> None:
ctx.load_capability('refunds')
elif hook == 'before_model_request':
@hooks.on.before_model_request
async def load_before_model_request(
ctx: RunContext[object], request_context: ModelRequestContext
) -> ModelRequestContext:
ctx.load_capability('refunds')
return request_context
elif hook == 'after_model_request':
@hooks.on.after_model_request
async def load_after_model_request(
ctx: RunContext[object], *, request_context: ModelRequestContext, response: ModelResponse
) -> ModelResponse:
ctx.load_capability('refunds')
return response # pragma: no cover
elif hook == 'after_node_run':
@hooks.on.after_node_run
async def load_after_node_run(
ctx: RunContext[object], *, node: AgentNode[object], result: NodeResult[object]
) -> NodeResult[object]:
if isinstance(node, ModelRequestNode):
ctx.load_capability('refunds')
return result
else:
@hooks.on.after_run
async def load_after_run(ctx: RunContext[object], *, result: AgentRunResult[Any]) -> AgentRunResult[Any]:
ctx.load_capability('refunds')
return result # pragma: no cover
return hooks
@pytest.mark.parametrize('mode', ['run', 'run_stream', 'iter'])
@pytest.mark.parametrize('hook', ['before_run', 'before_model_request'])
async def test_load_capability_before_a_request_takes_effect_on_it(hook: str, mode: str) -> None:
"""A load from `before_run` or `before_model_request` is recorded on the request it precedes, which then has it.
That request carries the capability's tool and states its instructions, so loading before the first request
of a run (#10089) needs no extra model turn.
"""
requests: list[tuple[list[str], str]] = []
def record(messages: list[ModelMessage], info: AgentInfo) -> None:
requests.append(([tool.name for tool in info.function_tools], str(messages[-1])))
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
record(messages, info)
return make_text_response('done')
async def stream_fn(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str]:
record(messages, info)
yield 'done'
agent = Agent(
FunctionModel(model_fn, stream_function=stream_fn), capabilities=[_refunds(), _load_refunds_from(hook)]
)
if mode == 'run':
messages = (await agent.run('Was I refunded?')).all_messages()
elif mode == 'run_stream':
async with agent.run_stream('Was I refunded?') as streamed:
await streamed.get_output()
messages = streamed.all_messages()
else:
async with agent.iter('Was I refunded?') as agent_run:
async for _ in agent_run:
pass
assert agent_run.result is not None
messages = agent_run.result.all_messages()
tools, sent = requests[0]
assert ('refund_status' in tools, 'Quote the refund policy.' in sent) == (True, True)
assert [type(part).__name__ for part in messages[0].parts] == [
'UserPromptPart',
'CapabilityLoadDeltaPart',
'ToolAvailabilityDeltaPart',
'InstructionBaselinePart',
'InstructionDeltaPart',
]
assert _load_records(messages) == [('refunds', None)]
async def test_load_capability_in_a_run_nested_in_before_run_follows_its_own_rules() -> None:
"""A run started from another run's `before_run` hook doesn't inherit that hook's permission to load.
Its `after_model_request` comes after its final answer, so a load there is refused as in any other run.
"""
inner = Agent(
FunctionModel(lambda messages, info: make_text_response('refunds')),
capabilities=[_refunds(), _load_refunds_from('after_model_request')],
)
hooks = Hooks[object]()
@hooks.on.before_run
async def classify(ctx: RunContext[object]) -> None:
await inner.run('Which capability applies?')
outer = Agent(FunctionModel(lambda messages, info: make_text_response('done')), capabilities=[_refunds(), hooks])
with pytest.raises(UserError, match=r'can only be called where a model request follows'):
await outer.run('Was I refunded?')
def _load_refunds_after_tool_call_responses(results: list[bool]) -> Hooks[object]:
"""A `Hooks` capability whose `after_model_request` loads `refunds` on every response with tool calls."""
hooks = Hooks[object]()
@hooks.on.after_model_request
async def load_refunds(
ctx: RunContext[object], *, request_context: ModelRequestContext, response: ModelResponse
) -> ModelResponse:
if response.tool_calls:
results.append(ctx.load_capability('refunds'))
return response
return hooks
@pytest.mark.parametrize('mode', ['run', 'run_stream', 'iter'])
async def test_load_capability_after_a_response_with_tool_calls_takes_effect_on_the_next_request(mode: str) -> None:
"""`after_model_request` can load on a response whose tool calls the run executes: another request follows.
The load is recorded after that response's tool returns, like a load from one of its tools.
"""
requests: list[list[str]] = []
def respond(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
requests.append([tool.name for tool in info.function_tools])
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('open_case', {}, tool_call_id='open')])
return make_text_response('done')
async def stream_fn(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str | DeltaToolCalls]:
response = respond(messages, info)
if response.tool_calls:
yield {0: DeltaToolCall(name='open_case', json_args='{}', tool_call_id='open')}
else:
yield 'done'
results: list[bool] = []
agent = Agent(
FunctionModel(respond, stream_function=stream_fn),
capabilities=[_refunds(), _load_refunds_after_tool_call_responses(results)],
)
@agent.tool_plain
def open_case() -> str:
return 'Case opened.'
if mode == 'run':
messages = (await agent.run('Was I refunded?')).all_messages()
elif mode == 'run_stream':
async with agent.run_stream('Was I refunded?') as streamed:
await streamed.get_output()
messages = streamed.all_messages()
else:
async with agent.iter('Was I refunded?') as agent_run:
async for _ in agent_run:
pass
assert agent_run.result is not None
messages = agent_run.result.all_messages()
assert results == [True]
assert ['refund_status' in tools for tools in requests] == [False, True]
assert [type(part).__name__ for part in messages[2].parts] == [
'ToolReturnPart',
'CapabilityLoadDeltaPart',
'ToolAvailabilityDeltaPart',
'InstructionDeltaPart',
]
assert _load_records(messages) == [('refunds', None)]
async def test_load_capability_after_a_response_with_text_and_tool_calls() -> None:
"""A response with text as well as tool calls isn't final either: the run executes the calls and continues."""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(parts=[TextPart('Let me check.'), ToolCallPart('open_case', {}, tool_call_id='open')])
return make_text_response('done')
results: list[bool] = []
agent = Agent(FunctionModel(model_fn), capabilities=[_refunds(), _load_refunds_after_tool_call_responses(results)])
@agent.tool_plain
def open_case() -> str:
return 'Case opened.'
result = await agent.run('Was I refunded?')
assert (results, _load_records(result.all_messages())) == ([True], [('refunds', None)])
async def test_load_capability_after_an_output_tool_response_raises() -> None:
"""A response that only calls an output tool ends the run, so `after_model_request` can't load on it."""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
return ModelResponse(parts=[ToolCallPart(info.output_tools[0].name, {'response': 1})])
agent = Agent(
FunctionModel(model_fn),
output_type=ToolOutput(int),
capabilities=[_refunds(), _load_refunds_after_tool_call_responses([])],
)
with pytest.raises(UserError, match=r'can only be called where a model request follows'):
await agent.run('hi')
async def test_load_capability_after_a_response_whose_step_ends_the_run_is_discarded() -> None:
"""A tool call that needs approval ends the run after its step, so a load on that response is discarded."""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
return ModelResponse(parts=[ToolCallPart('needs_approval', {})])
results: list[bool] = []
agent = Agent(
FunctionModel(model_fn),
output_type=[str, DeferredToolRequests],
capabilities=[_refunds(), _load_refunds_after_tool_call_responses(results)],
)
@agent.tool_plain(requires_approval=True)
def needs_approval() -> str:
return 'Approved.' # pragma: no cover
result = await agent.run('hi')
assert (type(result.output).__name__, results, _load_records(result.all_messages())) == (
'DeferredToolRequests',
[True],
[],
)
async def test_load_capability_after_a_response_that_loads_it_itself() -> None:
"""When the response being handled calls `load_capability` for the same capability, the model's call decides."""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(
parts=[ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'refunds'}, tool_call_id='load')]
)
return make_text_response('done')
results: list[bool] = []
agent = Agent(FunctionModel(model_fn), capabilities=[_refunds(), _load_refunds_after_tool_call_responses(results)])
result = await agent.run('Was I refunded?')
assert (results, _load_records(result.all_messages())) == ([False], [('refunds', 'load')])
async def test_load_capability_in_a_run_nested_in_after_model_request_follows_its_own_rules() -> None:
"""A run started from `after_model_request` on a response with tool calls doesn't inherit its permission to load."""
inner = Agent(
FunctionModel(lambda messages, info: make_text_response('refunds')),
capabilities=[_refunds(), _load_refunds_from('after_model_request')],
)
hooks = Hooks[object]()
@hooks.on.after_model_request
async def classify(
ctx: RunContext[object], *, request_context: ModelRequestContext, response: ModelResponse
) -> ModelResponse:
await inner.run('Which capability applies?')
return response # pragma: no cover
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
return ModelResponse(parts=[ToolCallPart('open_case', {}, tool_call_id='open')])
outer = Agent(FunctionModel(model_fn), capabilities=[_refunds(), hooks])
@outer.tool_plain
def open_case() -> str:
return 'Case opened.' # pragma: no cover
with pytest.raises(UserError, match=r'can only be called where a model request follows'):
await outer.run('Was I refunded?')
async def test_load_capability_without_tools_before_run() -> None:
"""A capability without tools loaded from `before_run` is recorded with no tool reveal, and its instructions are stated."""
policy = Capability[object](
id='policy', description='Refund policy.', instructions='Refunds take 5 days.', defer_loading=True
)
hooks = Hooks[object]()
@hooks.on.before_run
async def load_policy(ctx: RunContext[object]) -> None:
ctx.load_capability('policy')
sent: list[str] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
sent.append(str(messages[-1]))
return make_text_response('done')
result = await Agent(FunctionModel(model_fn), capabilities=[policy, hooks]).run('How long do refunds take?')
assert ('Refunds take 5 days.' in sent[0], _load_records(result.all_messages())) == (True, [('policy', None)])
assert not any(isinstance(part, ToolAvailabilityDeltaPart) for part in result.all_messages()[0].parts)
@pytest.mark.parametrize(
'hook, mode',
[
('after_model_request', 'run'),
('after_model_request', 'run_stream'),
('after_node_run', 'run'),
('after_run', 'run'),
('after_run', 'run_stream'),
],
)
async def test_load_capability_after_the_final_answer_raises(hook: str, mode: str) -> None:
"""After a final model response no request follows, so a load from code there is refused.
`run_stream` ends with the streamed request's node, which `after_node_run` doesn't see complete.
"""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
return make_text_response('done')
async def stream_fn(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str]:
yield 'done'
agent = Agent(
FunctionModel(model_fn, stream_function=stream_fn), capabilities=[_refunds(), _load_refunds_from(hook)]
)
with pytest.raises(UserError, match=r'can only be called where a model request follows'):
if mode == 'run':
await agent.run('hi')
else:
async with agent.run_stream('hi') as streamed:
await streamed.get_output()
async def test_load_capability_from_output_tool_raises() -> None:
"""An output tool ends the run, so there's no next request for the load to take effect in."""
async def final_answer(ctx: RunContext[object], answer: str) -> str:
ctx.load_capability('refunds')
return answer # pragma: no cover
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
return ModelResponse(parts=[ToolCallPart(info.output_tools[0].name, {'answer': 'done'})])
agent = Agent(FunctionModel(model_fn), output_type=ToolOutput(final_answer), capabilities=[_refunds()])
with pytest.raises(UserError, match=r'cannot be called from an output tool, which ends the run'):
await agent.run('hi')
@pytest.mark.parametrize(
'ending_call, end_strategy, expected_output',
[
pytest.param('needs_approval', 'early', 'DeferredToolRequests', id='tool-needs-approval'),
pytest.param('deferred', 'early', 'DeferredToolRequests', id='tool-is-deferred'),
pytest.param('final_result', 'exhaustive', 'int', id='output-with-exhaustive-end-strategy'),
],
)
async def test_load_capability_is_discarded_when_the_step_ends_the_run(
ending_call: str, end_strategy: EndStrategy, expected_output: str
) -> None:
"""A load rides along with the next model request but never causes one, so a step that ends the run discards it.
The outcome is what the run produces without the load: the same output after one model request, and no load in history.
"""
model_requests = 0
loaded: list[bool] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
nonlocal model_requests
model_requests += 1
return ModelResponse(
parts=[
ToolCallPart(ending_call, {'response': 1} if ending_call == 'final_result' else {}),
ToolCallPart('open_case', {}),
]
)
agent = Agent(
FunctionModel(model_fn),
output_type=[ToolOutput(int, name='final_result'), DeferredToolRequests],
end_strategy=end_strategy,
capabilities=[_refunds()],
)
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
loaded.append(ctx.load_capability('refunds'))
return 'Case opened.'
@agent.tool_plain(requires_approval=True)
def needs_approval() -> str:
return 'Approved.' # pragma: no cover
@agent.tool_plain
def deferred() -> str:
raise CallDeferred
result = await agent.run('Was I refunded?')
outcome = (type(result.output).__name__, model_requests, loaded, _load_calls(result.all_messages()))
assert outcome == (expected_output, 1, [True], [])
@pytest.mark.parametrize('loader', ['sibling_tool', 'approved_tool'])
async def test_load_capability_after_an_approval_needs_the_resumed_tool(loader: str) -> None:
"""A load discarded when the run stops for an approval isn't redone on resume, since only the approved tool runs.
So the capability is only loaded after resuming when the load comes from the approved tool.
"""
tools_seen: list[list[str]] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
tools_seen.append(sorted(tool.name for tool in info.function_tools))
if len(messages) == 1:
return ModelResponse(
parts=[
ToolCallPart('open_case', {}, tool_call_id='open'),
ToolCallPart('refund', {}, tool_call_id='ok'),
]
)
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), output_type=[str, DeferredToolRequests], capabilities=[_refunds()])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
if loader == 'sibling_tool':
ctx.load_capability('refunds')
return 'Case opened.'
@agent.tool(requires_approval=True)
async def refund(ctx: RunContext[object]) -> str:
if loader == 'approved_tool':
ctx.load_capability('refunds')
return 'Refunded.'
paused = await agent.run('Refund me.')
assert isinstance(paused.output, DeferredToolRequests)
resumed = await agent.run(
message_history=paused.all_messages(), deferred_tool_results=DeferredToolResults(approvals={'ok': True})
)
loaded_after_resume = 'refund_status' in tools_seen[-1]
assert (parse_loaded_capabilities(resumed.all_messages()), loaded_after_resume) == (
({'refunds'}, True) if loader == 'approved_tool' else (set(), False)
)
async def test_load_capability_is_delivered_with_a_message_that_continues_the_run() -> None:
"""When another enqueued message continues a run that would have ended, the load is delivered with it."""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('final_result', {'response': 1}), ToolCallPart('open_case', {})])
return ModelResponse(parts=[ToolCallPart('final_result', {'response': 2})])
agent = Agent(
FunctionModel(model_fn),
output_type=ToolOutput(int, name='final_result'),
end_strategy='exhaustive',
capabilities=[_refunds()],
)
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability('refunds')
ctx.enqueue('Also check the refund policy.')
return 'Case opened.'
result = await agent.run('Was I refunded?')
assert [[type(part).__name__ for part in message.parts] for message in result.all_messages()] == snapshot(
[
['UserPromptPart', 'InstructionBaselinePart'],
['ToolCallPart', 'ToolCallPart'],
['ToolReturnPart', 'ToolReturnPart'],
['UserPromptPart', 'CapabilityLoadDeltaPart', 'ToolAvailabilityDeltaPart', 'InstructionDeltaPart'],
['ToolCallPart'],
['ToolReturnPart'],
]
)
async def test_load_capability_from_a_tool_attempt_that_retries_still_loads() -> None:
"""A load is queued when it's called, so it's delivered even if the tool then asks the model to retry."""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('open_case', {})])
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[_refunds()])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability('refunds')
raise ModelRetry('The case system is busy, try again.')
result = await agent.run('Was I refunded?')
assert parse_loaded_capabilities(result.all_messages()) == {'refunds'}
@dataclass
class _HotfixWorkflow(AbstractCapability[object]):
"""A deferred capability whose model settings and model-request hook record when they apply."""
id: str | None = 'hotfix'
description: str | None = 'Hotfix workflow.'
defer_loading: bool = True
hook_fired_at: list[int] = field(default_factory=list[int])
def get_model_settings(self) -> _ModelSettings:
return _ModelSettings(temperature=0.123)
async def before_model_request(
self, ctx: RunContext[object], request_context: ModelRequestContext
) -> ModelRequestContext:
self.hook_fired_at.append(ctx.run_step)
return request_context
@pytest.mark.parametrize('loaded_by', ['model', 'code'])
async def test_first_request_after_load_applies_capability_settings_and_hooks(loaded_by: str) -> None:
"""A load from code takes full effect on the next request, like a load the model makes.
Not just its tools: its model settings and model-request hooks apply to that request too.
"""
hotfix = _HotfixWorkflow()
temperatures: list[float | None] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
temperatures.append((info.model_settings or {}).get('temperature'))
if len(messages) == 1:
if loaded_by == 'model':
return ModelResponse(parts=[ToolCallPart(LOAD_CAPABILITY_TOOL_NAME, {'id': 'hotfix'})])
return ModelResponse(parts=[ToolCallPart('open_case', {})])
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[hotfix])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability('hotfix')
return 'Case opened.'
await agent.run('Ship the hotfix.')
assert (temperatures, hotfix.hook_fired_at) == ([None, 0.123], [2])
@pytest.mark.parametrize(
'hook, expected',
[
# Loaded before the first step resolves anything, so the first request has the capability in full.
('before_run', ([0.123, 0.123], [1, 2])),
# The request being prepared already resolved its settings and ran its hooks: it gets the capability's
# tools and instructions, and its settings and hooks from the next request.
('before_model_request', ([None, 0.123], [2])),
],
)
async def test_hook_load_applies_capability_settings_and_hooks(
hook: str, expected: tuple[list[float | None], list[int]]
) -> None:
"""When a capability loaded from `before_run` or `before_model_request` gets its model settings and hooks."""
hotfix = _HotfixWorkflow()
temperatures: list[float | None] = []
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
temperatures.append((info.model_settings or {}).get('temperature'))
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('open_case', {})])
return make_text_response('done')
hooks = Hooks[object]()
if hook == 'before_run':
@hooks.on.before_run
async def load_before_run(ctx: RunContext[object]) -> None:
ctx.load_capability('hotfix')
else:
@hooks.on.before_model_request
async def load_before_request(
ctx: RunContext[object], request_context: ModelRequestContext
) -> ModelRequestContext:
ctx.load_capability('hotfix')
return request_context
agent = Agent(FunctionModel(model_fn), capabilities=[hotfix, hooks])
@agent.tool_plain
def open_case() -> str:
return 'Case opened.'
await agent.run('Ship the hotfix.')
assert (temperatures, hotfix.hook_fired_at) == expected
async def test_load_capability_records_the_loading_tool_call() -> None:
"""The load's record names the tool call that loaded it, which a replay of the same run (as Temporal does with a
tool hook) gets from the same model response, so it records the same part.
"""
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('open_case', {}, tool_call_id='open')])
return make_text_response('done')
agent = Agent(FunctionModel(model_fn), capabilities=[_refunds()])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability('refunds')
return 'Case opened.'
result = await agent.run('Was I refunded?')
assert _load_records(result.all_messages()) == [('refunds', 'open')]
async def test_load_capability_of_a_deferred_group_member_raises() -> None:
"""A member of an unloaded deferred group loads with the group, so loading it on its own from code is refused."""
members = [Capability[object](id='editing_tools', instructions='Edit carefully.')]
group = CombinedCapability[object](members, id='editing', description='Editing.', defer_loading=True)
agent = Agent(FunctionModel(_open_case_then_check_refund), capabilities=[group])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability('editing_tools')
return 'Case opened.' # pragma: no cover
with pytest.raises(UserError) as exc_info:
await agent.run('Edit d1.')
assert str(exc_info.value) == snapshot(
"Capability 'editing_tools' is part of deferred capability 'editing' and loads with it. Load 'editing' instead."
)
async def test_load_capability_record_is_emitted_when_the_next_request_is_short_circuited() -> None:
"""A load's record is in history before the next request's hooks run, so it's emitted even if no model is called.
A `wrap_model_request` that answers without calling its handler skips the point where the record is normally
emitted, so it's emitted as the step finishes instead, for UI clients that rebuild history from events.
"""
@dataclass
class AnswerAfterTheLoad(AbstractCapability[object]):
async def wrap_model_request(
self, ctx: RunContext[object], *, request_context: ModelRequestContext, handler: WrapModelRequestHandler
) -> ModelResponse:
if ctx.loaded_capability_ids:
return make_text_response('Answered without the model.')
return await handler(request_context)
async def stream_fn(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[DeltaToolCalls]:
yield {0: DeltaToolCall(name='open_case', json_args='{}', tool_call_id='open')}
agent = Agent(FunctionModel(stream_function=stream_fn), capabilities=[_refunds(), AnswerAfterTheLoad()])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
ctx.load_capability('refunds')
return 'Case opened.'
events: list[AgentStreamEvent] = []
async def event_stream_handler(_: RunContext[object], stream: AsyncIterable[AgentStreamEvent]) -> None:
async for event in stream:
events.append(event)
result = await agent.run('Was I refunded?', event_stream_handler=event_stream_handler)
assert result.output == 'Answered without the model.'
assert [
event.part for event in events if isinstance(event, ToolAvailabilityDeltaEvent | CapabilityLoadDeltaEvent)
] == [
CapabilityLoadDeltaPart(loaded=['refunds'], tool_call_id='open'),
ToolAvailabilityDeltaPart(tools_added=['refund_status'], tool_call_id='open'),
]
async def test_load_capability_after_the_run_ended_raises() -> None:
"""A `RunContext` kept from a tool call can't load a capability once its run has ended."""
stored: list[RunContext[object]] = []
agent = Agent(FunctionModel(_open_case_then_check_refund), capabilities=[_refunds()])
@agent.tool
async def open_case(ctx: RunContext[object]) -> str:
stored.append(ctx)
return 'Case opened.'
await agent.run('Was I refunded?')
with pytest.raises(UserError, match='is not available because the agent run has ended'):
stored[0].load_capability('refunds')
async def test_the_catalog_reaches_models_in_the_request_parameters_and_the_wire_is_unchanged():
"""The step's catalog is on `ModelRequestParameters.deferred_capabilities`, with whether each one is active.
The `load_capability` definition carries none of it, so the tools block and the prefix a language model is
sent are byte-identical before and after a capability loads.
Not a VCR test: the promise is about every request body being identical, which is checked by rendering each
request as `AnthropicModel` would send it, without a provider round trip.
"""
pytest.importorskip('anthropic') # the slim test jobs don't install it, and it renders the request bodies
refunds = Capability[object](id='refunds', description='Refund things.', defer_loading=True)
@refunds.tool_plain
def refund_status() -> str:
return 'Refunded.' # pragma: no cover
shipping = Capability[object](id='shipping', defer_loading=True)
model: FunctionModel
recorded: list[RecordedRequest] = []
def respond(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
recorded.append(RecordedRequest(model, list(messages), info.model_settings, info.model_request_parameters))
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('load_capability', {'id': 'refunds'})])
return ModelResponse(parts=[TextPart('Done.')])
model = FunctionModel(respond)
await Agent(model, capabilities=[refunds, shipping]).run('Refund me.')
assert [request.model_request_parameters.deferred_capabilities for request in recorded] == snapshot(
[
[
DeferredCapabilityEntry(id='refunds', description='Refund things.'),
DeferredCapabilityEntry(id='shipping'),
],
[
DeferredCapabilityEntry(id='refunds', description='Refund things.', active=True),
DeferredCapabilityEntry(id='shipping'),
],
]
)
load_tools = [
next(tool for tool in request.model_request_parameters.function_tools if tool.tool_kind == 'capability-load')
for request in recorded
]
assert all(tool.metadata is None for tool in load_tools)
first, second = render_anthropic_bodies(recorded)
assert first is not None and second is not None
assert json.dumps(first['tools'], sort_keys=True) == json.dumps(second['tools'], sort_keys=True)
assert json.dumps(first['system'], sort_keys=True) == json.dumps(second['system'], sort_keys=True)
assert second['messages'][: len(first['messages'])] == first['messages']
async def test_a_callable_description_is_resolved_once_per_step():
"""The catalog in the instructions and the one in the request parameters are the same resolution, made once
per step after the step's tools are prepared.
Not a VCR test: a recording can't show how many times the description callable ran, or that it ran after the
step's tools were prepared.
"""
resolved_on_steps: list[tuple[int, list[str]]] = []
def describe(ctx: RunContext[object]) -> str:
resolved_on_steps.append((ctx.run_step, sorted(ctx.tools)))
return 'Refund things.'
refunds = Capability[object](id='refunds', description=describe, defer_loading=True)
@refunds.tool_plain
def refund_status() -> str:
return 'Refunded.'
def respond(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('load_capability', {'id': 'refunds'})])
if len(messages) == 3:
return ModelResponse(parts=[ToolCallPart('refund_status', {})])
return ModelResponse(parts=[TextPart('Done.')])
result = await Agent(FunctionModel(respond), capabilities=[refunds]).run('Refund me.')
assert result.output == 'Done.'
# Resolved after the step's tools are prepared, so a description can read them, from the first step on.
assert resolved_on_steps == [
(1, ['load_capability', 'refund_status']),
(2, ['load_capability', 'refund_status']),
(3, ['load_capability', 'refund_status']),
]