2066 lines
97 KiB
Python
2066 lines
97 KiB
Python
"""Tests for the `ImageGeneration` capability.
|
|
|
|
Split out of `test_capabilities.py` per #7304.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import dataclasses
|
|
import inspect
|
|
import re
|
|
from collections.abc import Callable, Sequence
|
|
from dataclasses import replace
|
|
from functools import cached_property
|
|
from typing import Any, Literal
|
|
|
|
import httpx2
|
|
import pytest
|
|
from pydantic import TypeAdapter
|
|
|
|
import pydantic_ai.images as images_module
|
|
from pydantic_ai._run_context import RunContext
|
|
from pydantic_ai._warnings import PydanticAIDeprecationWarning
|
|
from pydantic_ai.agent import Agent
|
|
from pydantic_ai.capabilities import (
|
|
ImageGeneration,
|
|
Instrumentation,
|
|
)
|
|
from pydantic_ai.exceptions import (
|
|
ContentFilterError,
|
|
UnexpectedModelBehavior,
|
|
UserError,
|
|
)
|
|
from pydantic_ai.images import (
|
|
ImageGenerationInput,
|
|
ImageGenerationModel,
|
|
ImageGenerationResult,
|
|
ImageGenerationSettings,
|
|
ImageGenerator,
|
|
TestImageGenerationModel,
|
|
)
|
|
from pydantic_ai.messages import (
|
|
BinaryImage,
|
|
FilePart,
|
|
ModelMessage,
|
|
ModelRequest,
|
|
ModelResponse,
|
|
RetryInfo,
|
|
TextPart,
|
|
ToolCallPart,
|
|
ToolReturnPart,
|
|
UserPromptPart,
|
|
)
|
|
from pydantic_ai.models import Model, ModelRequestParameters
|
|
from pydantic_ai.models.fallback import FallbackModel
|
|
from pydantic_ai.models.function import AgentInfo, FunctionModel
|
|
from pydantic_ai.models.instrumented import InstrumentationSettings
|
|
from pydantic_ai.models.wrapper import WrapperModel
|
|
from pydantic_ai.native_tools import (
|
|
AbstractNativeTool,
|
|
ImageGenerationTool,
|
|
)
|
|
from pydantic_ai.profiles import ModelProfile
|
|
from pydantic_ai.settings import ModelSettings
|
|
from pydantic_ai.tools import Tool
|
|
from pydantic_ai.usage import RequestUsage
|
|
|
|
from ._inline_snapshot import snapshot
|
|
from .conftest import IsDatetime, IsInstance, IsStr, iter_message_parts, try_import
|
|
|
|
_REQUEST_BODY_ADAPTER = TypeAdapter(dict[str, Any])
|
|
|
|
|
|
def _custom_local_tool(prompt: str) -> str:
|
|
"""A local tool of the user's own, for cases that only need `local` to be stated."""
|
|
return 'image_url' # pragma: no cover
|
|
|
|
|
|
with try_import() as openai_imports:
|
|
from pydantic_ai.images.openai import OpenAIImageGenerationModel, OpenAIImageGenerationSettings
|
|
from pydantic_ai.models.openai import OpenAIResponsesModel
|
|
from pydantic_ai.providers.openai import OpenAIProvider
|
|
|
|
with try_import() as google_imports:
|
|
from pydantic_ai.images.google import GoogleImageGenerationModel, GoogleImageGenerationSettings
|
|
from pydantic_ai.providers.google import GoogleProvider
|
|
|
|
with try_import() as xai_imports:
|
|
from pydantic_ai.images.xai import XaiImageGenerationModel, XaiImageGenerationSettings
|
|
from pydantic_ai.providers.xai import XaiProvider
|
|
|
|
with try_import() as logfire_imports_successful:
|
|
from logfire.testing import CaptureLogfire
|
|
|
|
|
|
# Each pair shares one provider instance and one model name, so `settings` is the only thing that
|
|
# differs between its two models — the whole point of the case they parametrize.
|
|
def _openai_models_differing_in_settings() -> tuple[ImageGenerationModel, ImageGenerationModel]:
|
|
provider = OpenAIProvider(api_key='test-key')
|
|
return (
|
|
OpenAIImageGenerationModel(
|
|
'gpt-image-2', provider=provider, settings=OpenAIImageGenerationSettings(openai_quality='low')
|
|
),
|
|
OpenAIImageGenerationModel(
|
|
'gpt-image-2', provider=provider, settings=OpenAIImageGenerationSettings(openai_quality='high')
|
|
),
|
|
)
|
|
|
|
|
|
def _google_models_differing_in_settings() -> tuple[ImageGenerationModel, ImageGenerationModel]:
|
|
provider = GoogleProvider(api_key='test-key')
|
|
return (
|
|
GoogleImageGenerationModel(
|
|
'gemini-3.1-flash-image',
|
|
provider=provider,
|
|
settings=GoogleImageGenerationSettings(google_image_config={'image_size': '1K'}),
|
|
),
|
|
GoogleImageGenerationModel(
|
|
'gemini-3.1-flash-image',
|
|
provider=provider,
|
|
settings=GoogleImageGenerationSettings(google_image_config={'image_size': '2K'}),
|
|
),
|
|
)
|
|
|
|
|
|
def _xai_models_differing_in_settings() -> tuple[ImageGenerationModel, ImageGenerationModel]:
|
|
provider = XaiProvider(api_key='test-key')
|
|
return (
|
|
XaiImageGenerationModel(
|
|
'grok-imagine-image', provider=provider, settings=XaiImageGenerationSettings(xai_resolution='1k')
|
|
),
|
|
XaiImageGenerationModel(
|
|
'grok-imagine-image', provider=provider, settings=XaiImageGenerationSettings(xai_resolution='2k')
|
|
),
|
|
)
|
|
|
|
|
|
class TestImageGenerationCapability:
|
|
def test_image_gen_init_params_cover_builtin_tool_and_direct_geometry(self):
|
|
"""ImageGeneration adds direct geometry without dropping existing native-tool fields."""
|
|
# partial_images is excluded — not useful for subagent fallback (no streaming).
|
|
# optional is excluded — applies to wire-side dropping, not local-fallback config.
|
|
builtin_fields = {
|
|
f.name
|
|
for f in dataclasses.fields(ImageGenerationTool)
|
|
if f.name not in ('kind', 'optional', 'partial_images')
|
|
}
|
|
builtin_fields.remove('model')
|
|
builtin_fields.add('image_model')
|
|
# Subtract framework-inherited kw-only params from `AbstractCapability`
|
|
# (forwarded so `dataclasses.replace` round-trips through the custom `__init__`).
|
|
init_params = set(inspect.signature(ImageGeneration.__init__).parameters.keys()) - {
|
|
'self',
|
|
'native',
|
|
'local',
|
|
'fallback_subagent_model',
|
|
# TODO(v3): drop with the deprecated `fallback_model` spelling itself.
|
|
'fallback_model',
|
|
'fallback_image_model',
|
|
'id',
|
|
'defer_loading',
|
|
'description',
|
|
}
|
|
assert init_params == (builtin_fields - {'provider_settings'}) | {'dimensions'}
|
|
|
|
# The spec-only constructor deliberately narrows runtime-only values, but must keep the
|
|
# same parameter names so YAML/JSON configuration cannot drift from the Python API.
|
|
spec_params = set(inspect.signature(ImageGeneration.from_spec).parameters)
|
|
runtime_params = set(inspect.signature(ImageGeneration.__init__).parameters) - {'self'}
|
|
assert spec_params == runtime_params
|
|
|
|
def test_image_generation_default(self):
|
|
"""ImageGeneration() provides only builtin, no local fallback."""
|
|
cap = ImageGeneration()
|
|
builtins = cap.get_native_tools()
|
|
assert len(builtins) == 1
|
|
assert isinstance(builtins[0], ImageGenerationTool)
|
|
# No default local
|
|
assert cap.local is None
|
|
assert cap.get_toolset() is None
|
|
|
|
def test_image_generation_with_custom_local(self):
|
|
"""ImageGeneration(local=custom) → provides custom local fallback."""
|
|
|
|
def my_gen(prompt: str) -> str:
|
|
return 'image_url' # pragma: no cover
|
|
|
|
cap = ImageGeneration(local=my_gen)
|
|
assert isinstance(cap.local, Tool)
|
|
assert cap.get_toolset() is not None
|
|
|
|
def test_image_generation_accepts_direct_image_model(self):
|
|
"""A direct image model is kept as declared; the capability tool is derived from it later."""
|
|
image_model = TestImageGenerationModel()
|
|
cap = ImageGeneration(fallback_image_model=image_model)
|
|
|
|
assert cap.fallback_image_model is image_model
|
|
assert cap.local is None
|
|
assert cap.get_toolset() is not None
|
|
|
|
def test_image_generation_accepts_a_generator_on_local(self):
|
|
"""A generator carries settings of its own, so it is one of the local implementations.
|
|
|
|
It is kept as declared rather than resolved into a tool, which is what lets
|
|
`dataclasses.replace` hand it back unchanged.
|
|
"""
|
|
generator = ImageGenerator(TestImageGenerationModel())
|
|
cap = ImageGeneration(native=False, local=generator)
|
|
|
|
assert cap.local is generator
|
|
assert cap.fallback_image_model is None
|
|
assert cap.get_toolset() is not None
|
|
assert replace(cap, dimensions=(1024, 1024)).local is generator
|
|
|
|
def test_image_generation_native_false_requires_a_fallback(self):
|
|
"""`native=False` with nothing to fall back to is a capability that contributes nothing.
|
|
|
|
The base raises for this as well, but it offers remedies -- a strategy string, `local=True`
|
|
-- that this capability rejects, and names neither fallback field.
|
|
"""
|
|
with pytest.raises(UserError, match=r'requires an explicit fallback.*fallback_image_model'):
|
|
ImageGeneration(native=False)
|
|
|
|
def test_image_generation_rejects_a_bare_image_model_on_local(self):
|
|
"""A bare model carries no settings, so it is a model, and `fallback_image_model` takes models."""
|
|
with pytest.raises(UserError, match=r'goes to `fallback_image_model`, not `local`'):
|
|
ImageGeneration(local=TestImageGenerationModel()) # pyright: ignore[reportArgumentType]
|
|
|
|
def test_image_generation_rejects_a_generator_on_fallback_image_model(self):
|
|
"""The field is named for a model, and a generator is a configured local implementation."""
|
|
with pytest.raises(UserError, match=r'goes to `local`, not `fallback_image_model`'):
|
|
ImageGeneration(fallback_image_model=ImageGenerator(TestImageGenerationModel())) # pyright: ignore[reportArgumentType]
|
|
|
|
def test_image_generation_accepts_direct_model_name(self):
|
|
"""A direct model name is kept as the name, with the model itself deferred.
|
|
|
|
Wrapping it in an `ImageGenerator` here would leave the field holding what it refuses to be
|
|
given, and `dataclasses.replace` feeds every field back through `__post_init__`.
|
|
"""
|
|
cap = ImageGeneration(native=False, fallback_image_model='openai:gpt-image-1.5')
|
|
|
|
assert cap.fallback_image_model == 'openai:gpt-image-1.5'
|
|
assert cap.get_toolset() is not None
|
|
assert replace(cap, dimensions=(1024, 1024)).fallback_image_model == 'openai:gpt-image-1.5'
|
|
|
|
def test_image_generation_direct_model_name_warns_for_native_only_settings(self):
|
|
"""The `fallback_image_model='provider:model'` arm drops native-only settings, and blames the caller's line.
|
|
|
|
The `stacklevel` that produces that attribution is a literal counted through four framework
|
|
frames, so the warning's own `filename` is what pins it.
|
|
"""
|
|
with pytest.warns(UserWarning, match='ignored native-tool setting.*quality') as recorded:
|
|
ImageGeneration(native=False, fallback_image_model='openai:gpt-image-1.5', quality='high')
|
|
|
|
assert [warning.filename for warning in recorded] == [__file__]
|
|
|
|
def test_image_generation_from_spec_warns_for_native_only_settings(self):
|
|
"""A spec-loaded model name drops the same settings, one frame short of the caller.
|
|
|
|
`from_spec` adds a frame the `stacklevel` literals don't count, so the warning lands on the
|
|
capability module itself rather than on the spec's loader.
|
|
"""
|
|
with pytest.warns(UserWarning, match='ignored native-tool setting.*quality') as recorded:
|
|
ImageGeneration.from_spec(native=False, fallback_image_model='openai:gpt-image-1.5', quality='high')
|
|
|
|
assert [warning.filename for warning in recorded] == [inspect.getsourcefile(ImageGeneration)]
|
|
|
|
@pytest.mark.parametrize(
|
|
('construct', 'expected'),
|
|
[
|
|
pytest.param(
|
|
lambda: ImageGeneration(
|
|
native=False,
|
|
local=_custom_local_tool,
|
|
background='transparent',
|
|
input_fidelity='high',
|
|
moderation='low',
|
|
output_compression=80,
|
|
output_format='webp',
|
|
quality='high',
|
|
size='1024x1024',
|
|
action='generate',
|
|
image_model='gpt-image-2',
|
|
dimensions=(1280, 720),
|
|
aspect_ratio='16:9',
|
|
),
|
|
'`ImageGeneration` ignored setting(s): `background`, `input_fidelity`, `moderation`, '
|
|
'`output_compression`, `output_format`, `quality`, `size`, `action`, `image_model`, '
|
|
'`dimensions`, `aspect_ratio`. With `native=False` the `local` tool you supplied is the only '
|
|
'implementation, and the capability passes it no settings; configure that tool instead.',
|
|
id='every-setting-native-aspect-ratio',
|
|
),
|
|
pytest.param(
|
|
lambda: ImageGeneration(
|
|
native=False,
|
|
local=_custom_local_tool,
|
|
background='transparent',
|
|
input_fidelity='high',
|
|
moderation='low',
|
|
output_compression=80,
|
|
output_format='webp',
|
|
quality='high',
|
|
size='1024x1024',
|
|
action='generate',
|
|
image_model='gpt-image-2',
|
|
dimensions=(1280, 720),
|
|
aspect_ratio='2:1',
|
|
),
|
|
'`ImageGeneration` ignored setting(s): `background`, `input_fidelity`, `moderation`, '
|
|
'`output_compression`, `output_format`, `quality`, `size`, `action`, `image_model`, '
|
|
'`dimensions`, `aspect_ratio`. With `native=False` the `local` tool you supplied is the only '
|
|
'implementation, and the capability passes it no settings; configure that tool instead.',
|
|
id='every-setting-direct-only-aspect-ratio',
|
|
),
|
|
pytest.param(
|
|
lambda: ImageGeneration(
|
|
native=False, local=_custom_local_tool, quality='high', dimensions=(1280, 720), aspect_ratio='16:9'
|
|
),
|
|
'`ImageGeneration` ignored setting(s): `quality`, `dimensions`, `aspect_ratio`. With '
|
|
'`native=False` the `local` tool you supplied is the only implementation, and the '
|
|
'capability passes it no settings; configure that tool instead.',
|
|
id='some-settings',
|
|
),
|
|
pytest.param(lambda: ImageGeneration(native=False, local=_custom_local_tool), None, id='no-settings'),
|
|
],
|
|
)
|
|
def test_image_generation_native_false_with_a_custom_local_tool_warns_for_every_setting_it_ignores(
|
|
self, construct: Callable[[], object], expected: str | None
|
|
):
|
|
"""With `native=False` the tool you supply is the only implementation, and the capability hands it nothing.
|
|
|
|
No native tool is built and the capability passes no settings to a tool it didn't build, so
|
|
every setting goes unapplied for that one reason and one notice names them all, whether or
|
|
not the native tool could have expressed the aspect ratio. The `dimensions` docstring sends
|
|
users to `native=False` to guarantee the setting takes effect, so the one arrangement that
|
|
applies nothing at all cannot be the silent one. Only the settings the caller stated are
|
|
named, and stating none warns about nothing. The notice blames the caller's line, which its
|
|
`filename` pins.
|
|
|
|
It warns at construction, before any request, so this is not a VCR test.
|
|
"""
|
|
if expected is None:
|
|
# `filterwarnings = ['error']` turns an unexpected notice into the failure.
|
|
construct()
|
|
else:
|
|
with pytest.warns(UserWarning, match=re.escape(expected)) as recorded:
|
|
construct()
|
|
assert [(str(warning.message), warning.filename) for warning in recorded] == [(expected, __file__)]
|
|
|
|
def test_image_generation_native_only_settings_are_not_ignored_when_native_is_enabled(self):
|
|
"""With native enabled these settings reach the native tool, so reporting them as dropped is wrong.
|
|
|
|
`filterwarnings = ['error']` turns the absent warning into the assertion: whether the direct
|
|
generator is used at all is decided per request against the model's profile, and on the
|
|
requests that drop it the native tool carries every one of these values.
|
|
"""
|
|
capability = ImageGeneration(local=ImageGenerator(TestImageGenerationModel()), quality='high', size='1024x1024')
|
|
|
|
native_tool = capability.get_native_tools()[0]
|
|
assert isinstance(native_tool, ImageGenerationTool)
|
|
assert native_tool.quality == 'high'
|
|
assert native_tool.size == '1024x1024'
|
|
|
|
async def test_image_generation_direct_fallback(self, allow_model_requests: None):
|
|
"""The direct fallback applies portable settings and warns for native-only settings."""
|
|
image_model = TestImageGenerationModel(
|
|
settings={
|
|
'extra_headers': {'x-test': 'preserved'},
|
|
}
|
|
)
|
|
generator = ImageGenerator(image_model)
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
with pytest.warns(UserWarning, match='ignored native-tool setting'):
|
|
capability = ImageGeneration(
|
|
native=False,
|
|
local=generator,
|
|
background='opaque',
|
|
input_fidelity='high',
|
|
moderation='low',
|
|
output_compression=80,
|
|
output_format='jpeg',
|
|
quality='low',
|
|
size='1024x1024',
|
|
dimensions=(1024, 1024),
|
|
)
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[capability],
|
|
)
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'done'
|
|
assert image_model.last_settings == {
|
|
'dimensions': (1024, 1024),
|
|
'extra_headers': {'x-test': 'preserved'},
|
|
}
|
|
tool_returns = list(iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart))
|
|
assert len(tool_returns) == 1
|
|
assert isinstance(tool_returns[0].content, BinaryImage)
|
|
assert tool_returns[0].content.media_type == 'image/png'
|
|
|
|
aspect_ratio_model = TestImageGenerationModel()
|
|
aspect_ratio_agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(native=False, fallback_image_model=aspect_ratio_model, aspect_ratio='1:1')],
|
|
)
|
|
await aspect_ratio_agent.run('Generate an image')
|
|
assert aspect_ratio_model.last_settings == {'aspect_ratio': '1:1'}
|
|
|
|
async def test_image_generation_spec_model_name_resolves_deferred_model_during_run(
|
|
self, allow_model_requests: None, monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
"""A spec-loaded model name stays unresolved until the tool generates, then applies the JSON dimensions."""
|
|
image_model = TestImageGenerationModel()
|
|
inferred_models: list[object] = []
|
|
|
|
def infer_model(model: object) -> TestImageGenerationModel:
|
|
inferred_models.append(model)
|
|
return image_model
|
|
|
|
monkeypatch.setattr(images_module, 'infer_image_generation_model', infer_model)
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
agent = Agent.from_spec(
|
|
{
|
|
'capabilities': [
|
|
{
|
|
'ImageGeneration': {
|
|
'native': False,
|
|
'fallback_image_model': 'openai:gpt-image-1.5',
|
|
'dimensions': [1280, 720],
|
|
}
|
|
}
|
|
]
|
|
},
|
|
model=FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset())),
|
|
)
|
|
assert inferred_models == snapshot([])
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert inferred_models == snapshot(['openai:gpt-image-1.5'])
|
|
assert image_model.last_settings == snapshot({'dimensions': (1280, 720)})
|
|
tool_returns = list(iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart))
|
|
assert tool_returns == snapshot(
|
|
[
|
|
ToolReturnPart(
|
|
tool_name='generate_image',
|
|
content=IsInstance(BinaryImage),
|
|
tool_call_id=IsStr(),
|
|
timestamp=IsDatetime(),
|
|
)
|
|
]
|
|
)
|
|
|
|
@pytest.mark.skipif(not logfire_imports_successful(), reason='logfire not installed')
|
|
async def test_image_generation_direct_fallback_instrumentation_omits_binary_tool_result(
|
|
self, allow_model_requests: None, capfire: CaptureLogfire
|
|
):
|
|
"""Tool span redaction does not change the binary result delivered to the outer model.
|
|
|
|
Scoped to the tool span's own result attribute. `include_binary_content=False` is not a
|
|
library-wide redaction guarantee: the run span's `final_result` and the serialized message
|
|
history carry binary content regardless.
|
|
"""
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[
|
|
ImageGeneration(native=False, fallback_image_model=TestImageGenerationModel()),
|
|
Instrumentation(settings=InstrumentationSettings(include_binary_content=False)),
|
|
],
|
|
)
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
tool_returns = list(iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart))
|
|
assert len(tool_returns) == 1
|
|
assert isinstance(tool_returns[0].content, BinaryImage)
|
|
|
|
spans = capfire.exporter.exported_spans_as_dict(parse_json_attributes=True)
|
|
tool_span = next(span for span in spans if span['name'] == 'execute_tool generate_image')
|
|
tool_result = tool_span['attributes']['gen_ai.tool.call.result']
|
|
assert tool_result['media_type'] == 'image/png'
|
|
assert 'data' not in tool_result
|
|
|
|
def test_image_generation_direct_only_rejects_edit_action_at_construction(self):
|
|
"""`native=False` makes the prompt-only direct tool the only path, so the edit is refused up front."""
|
|
with pytest.raises(UserError, match='cannot honor `action="edit"`'):
|
|
ImageGeneration(native=False, fallback_image_model=TestImageGenerationModel(), action='edit')
|
|
|
|
async def test_image_generation_direct_fallback_rejects_edit_action(self, allow_model_requests: None):
|
|
"""The prompt-only capability tool cannot silently turn a requested edit into generation.
|
|
|
|
With native enabled the native tool honors `action='edit'` on the models that carry it, so
|
|
the configuration is only unserviceable once a model without native image generation routes
|
|
the call to the direct tool instead.
|
|
"""
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(fallback_image_model=TestImageGenerationModel(), action='edit')],
|
|
)
|
|
|
|
with pytest.raises(UserError, match='cannot honor `action="edit"`'):
|
|
await agent.run('Edit an image')
|
|
|
|
async def test_image_generation_native_edit_action_survives_a_direct_generator(self, allow_model_requests: None):
|
|
"""A configured direct generator does not disqualify an edit the native tool can still perform."""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
assert info.function_tools == []
|
|
return ModelResponse(parts=[TextPart(content='native path')])
|
|
|
|
outer_model = FunctionModel(
|
|
outer_model_fn,
|
|
profile=ModelProfile(supported_native_tools=frozenset({ImageGenerationTool})),
|
|
)
|
|
capability = ImageGeneration(local=ImageGenerator(image_model), action='edit')
|
|
agent = Agent(outer_model, capabilities=[capability])
|
|
|
|
result = await agent.run('Edit an image')
|
|
|
|
assert result.output == 'native path'
|
|
native_tool = capability.get_native_tools()[0]
|
|
assert isinstance(native_tool, ImageGenerationTool)
|
|
assert native_tool.action == 'edit'
|
|
|
|
async def test_image_generation_direct_fallback_warns_for_image_model(self, allow_model_requests: None):
|
|
"""The direct model is `fallback_image_model`'s to name, so the native override says it is ignored."""
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[
|
|
ImageGeneration(
|
|
native=False,
|
|
fallback_image_model=TestImageGenerationModel(),
|
|
image_model='gpt-image-1',
|
|
)
|
|
],
|
|
)
|
|
|
|
with pytest.warns(UserWarning, match=r'ignored `image_model`'):
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'done'
|
|
|
|
def test_image_generation_rejects_local_true(self):
|
|
"""`local=True` is not an image generation strategy: the capability has no bundled local tool."""
|
|
with pytest.raises(UserError, match=r'`local=True` is not supported'):
|
|
ImageGeneration(local=True) # pyright: ignore[reportArgumentType]
|
|
|
|
@pytest.mark.parametrize(
|
|
('local', 'error'),
|
|
[
|
|
(False, 'both `native` and `local` cannot be False'),
|
|
(True, 'is not supported'),
|
|
('duckduckgo', 'is not supported'),
|
|
],
|
|
)
|
|
def test_image_generation_native_false_rejects_an_invalid_local_without_a_settings_notice(
|
|
self, local: bool | str, error: str
|
|
):
|
|
"""An invalid `local` is refused outright, not first reported as a tool that ignores the capability's settings.
|
|
|
|
It raises at construction, before any request, so this is not a VCR test.
|
|
"""
|
|
# `filterwarnings = ['error']` turns a notice emitted first into the failure this test guards against.
|
|
with pytest.raises(UserError, match=error):
|
|
ImageGeneration(native=False, local=local, quality='high') # pyright: ignore[reportArgumentType]
|
|
|
|
def test_image_generation_rejects_a_local_strategy_string(self):
|
|
"""Every `local` string is rejected, and the message names the field a model belongs on."""
|
|
with pytest.raises(UserError, match=r"`local='duckduckgo'` is not supported.*fallback_image_model"):
|
|
ImageGeneration(native=False, local='duckduckgo') # pyright: ignore[reportArgumentType]
|
|
|
|
def test_image_generation_rejects_a_model_name_without_a_provider_prefix(self):
|
|
"""A name no provider prefix can be split out of is rejected at construction.
|
|
|
|
Only the model resolution behind a well-formed id is deferred to the first generate call.
|
|
"""
|
|
with pytest.raises(UserError, match=r"`fallback_image_model='gpt-image-1.5'` is not a direct image model"):
|
|
ImageGeneration(native=False, fallback_image_model='gpt-image-1.5')
|
|
|
|
async def test_image_generation_direct_fallback_rejects_multiple_images(self, allow_model_requests: None):
|
|
"""The single-image capability contract never silently discards direct API outputs."""
|
|
|
|
class MultipleImageGenerationModel(TestImageGenerationModel):
|
|
async def generate(
|
|
self,
|
|
prompt: str,
|
|
*,
|
|
images: Sequence[ImageGenerationInput] | None = None,
|
|
settings: ImageGenerationSettings | None = None,
|
|
) -> ImageGenerationResult:
|
|
result = await super().generate(prompt, images=images, settings=settings)
|
|
return replace(result, images=[*result.images, *result.images])
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(native=False, fallback_image_model=MultipleImageGenerationModel())],
|
|
retries=0,
|
|
)
|
|
|
|
with pytest.raises(UnexpectedModelBehavior, match='returned 2 images; expected exactly one'):
|
|
await agent.run('Generate an image')
|
|
|
|
async def test_image_generation_prefers_native_over_direct_fallback(self, allow_model_requests: None):
|
|
"""The existing native-or-local routing suppresses the direct fallback when native is supported."""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
assert info.function_tools == []
|
|
return ModelResponse(parts=[TextPart(content='native path')])
|
|
|
|
outer_model = FunctionModel(
|
|
outer_model_fn,
|
|
profile=ModelProfile(supported_native_tools=frozenset({ImageGenerationTool})),
|
|
)
|
|
agent = Agent(outer_model, capabilities=[ImageGeneration(local=ImageGenerator(image_model))])
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'native path'
|
|
assert image_model.last_settings is None
|
|
|
|
async def test_image_generation_warns_when_native_supersedes_direct_only_geometry(self, allow_model_requests: None):
|
|
"""Dropping the direct generator drops `dimensions` with it, which only the request knows.
|
|
|
|
Whether the drop happens depends on the model's `supported_native_tools`, so the capability
|
|
can't tell at construction time; the warning has to come from the per-request prepare
|
|
function, and the model that has no native image generation must stay silent.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
assert info.function_tools == []
|
|
return ModelResponse(parts=[TextPart(content='native path')])
|
|
|
|
outer_model = FunctionModel(
|
|
outer_model_fn,
|
|
profile=ModelProfile(supported_native_tools=frozenset({ImageGenerationTool})),
|
|
)
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(local=ImageGenerator(image_model), dimensions=(1280, 720))],
|
|
)
|
|
|
|
with pytest.warns(UserWarning, match=r'direct-only setting\(s\) go unapplied: `dimensions`'):
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'native path'
|
|
assert image_model.last_settings is None
|
|
|
|
async def test_image_generation_direct_generator_survives_dataclass_replace(self, allow_model_requests: None):
|
|
"""The shipped capability skill tells users to reconfigure a capability with `replace()`.
|
|
|
|
The copy has to stay a direct generator on both counts: no construction-time `ignored
|
|
direct-only setting(s)` warning, and the per-request native-supersedes notice still
|
|
installed.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[TextPart(content='native path')])
|
|
|
|
outer_model = FunctionModel(
|
|
outer_model_fn,
|
|
profile=ModelProfile(supported_native_tools=frozenset({ImageGenerationTool})),
|
|
)
|
|
capability = ImageGeneration(local=ImageGenerator(image_model), dimensions=(1280, 720))
|
|
|
|
copy = replace(capability, aspect_ratio=None)
|
|
|
|
agent = Agent(outer_model, capabilities=[copy])
|
|
with pytest.warns(UserWarning, match=r'direct-only setting\(s\) go unapplied: `dimensions`'):
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'native path'
|
|
|
|
@pytest.fixture
|
|
def direct_generation_model(self) -> FunctionModel:
|
|
"""A model with no native image generation, which calls `generate_image` once and stops."""
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
return FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
|
|
async def test_image_generation_replace_sends_the_replaced_dimensions(
|
|
self, allow_model_requests: None, direct_generation_model: FunctionModel
|
|
):
|
|
"""The copy's own geometry is what the run sends, not the geometry it was copied from.
|
|
|
|
The capability's fields are the configuration and the `generate_image` tool is derived from
|
|
them when the toolset is requested, so nothing the original settled can outlive being
|
|
replaced.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
capability = ImageGeneration(native=False, fallback_image_model=image_model, dimensions=(1024, 1024))
|
|
|
|
agent = Agent(direct_generation_model, capabilities=[replace(capability, dimensions=(1536, 1024))])
|
|
await agent.run('Generate an image')
|
|
|
|
assert image_model.last_settings == snapshot({'dimensions': (1536, 1024)})
|
|
|
|
async def test_image_generation_direct_model_name_resolves_one_generator(
|
|
self,
|
|
allow_model_requests: None,
|
|
direct_generation_model: FunctionModel,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
):
|
|
"""One capability keeps one generator however often its toolset is resolved.
|
|
|
|
A `DynamicCapability` re-resolves the toolset per request, so a generator built per
|
|
resolution would infer the model — and build the provider client behind it — every time.
|
|
The model name is what proves it: the generator resolves it once and hands back the model
|
|
it already holds after that.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
inferred_models: list[object] = []
|
|
|
|
def infer_model(model: object) -> TestImageGenerationModel:
|
|
inferred_models.append(model)
|
|
return image_model
|
|
|
|
monkeypatch.setattr(images_module, 'infer_image_generation_model', infer_model)
|
|
|
|
capability = ImageGeneration(native=False, fallback_image_model='openai:gpt-image-1.5')
|
|
await Agent(direct_generation_model, capabilities=[capability]).run('Generate an image')
|
|
await Agent(direct_generation_model, capabilities=[capability]).run('Generate an image')
|
|
|
|
assert [model for model in inferred_models if isinstance(model, str)] == snapshot(['openai:gpt-image-1.5'])
|
|
|
|
def test_image_generation_replace_rejects_an_edit_action_the_constructor_would(self):
|
|
"""A copy is held to the construction-time checks, not just the instance it came from.
|
|
|
|
`native=False` makes the prompt-only direct tool the only path, so the edit is unserviceable
|
|
however the capability carrying it was built.
|
|
"""
|
|
capability = ImageGeneration(
|
|
native=False, fallback_image_model=TestImageGenerationModel(), dimensions=(1024, 1024)
|
|
)
|
|
|
|
with pytest.raises(UserError, match='cannot honor `action="edit"`'):
|
|
replace(capability, action='edit')
|
|
|
|
@pytest.mark.parametrize(
|
|
'setting',
|
|
[
|
|
pytest.param({'action': 'edit'}, id='action'),
|
|
pytest.param({'quality': 'high'}, id='quality'),
|
|
pytest.param({'image_model': 'gpt-image-2'}, id='image_model'),
|
|
],
|
|
)
|
|
async def test_image_generation_replace_clears_a_setting_from_the_direct_fallback(
|
|
self, allow_model_requests: None, direct_generation_model: FunctionModel, setting: dict[str, Any]
|
|
):
|
|
"""A setting `replace` cleared is gone from the direct fallback: it neither refuses nor reports it.
|
|
|
|
`native=True` resolves at construction to a native tool built from the capability's settings,
|
|
and `replace` hands that tool back as the copy's `native`. The direct fallback reads the
|
|
capability's own fields, so the copy runs as if the setting had never been set.
|
|
|
|
The edit refusal and both notices come before the generator runs, so this is not a VCR test.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
capability = ImageGeneration(fallback_image_model=image_model, **setting)
|
|
|
|
copy = replace(capability, **dict.fromkeys(setting))
|
|
# `filterwarnings = ['error']` turns a dropped-settings notice into the failure.
|
|
result = await Agent(direct_generation_model, capabilities=[copy]).run('Generate an image')
|
|
|
|
assert result.output == 'done'
|
|
assert image_model.last_settings == {}
|
|
|
|
async def test_image_generation_composed_capabilities_send_the_merged_dimensions(
|
|
self, allow_model_requests: None, direct_generation_model: FunctionModel
|
|
):
|
|
"""Two capabilities under one id are one configuration stated twice, and the merge is what runs.
|
|
|
|
The generator comes from the first and the geometry from the second, so a tool built from
|
|
either instance on its own would send the other's settings.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
with pytest.warns(UserWarning, match=r'ignored direct-only setting\(s\): `dimensions`'):
|
|
agent = Agent(
|
|
direct_generation_model,
|
|
capabilities=[
|
|
ImageGeneration(fallback_image_model=image_model),
|
|
ImageGeneration(dimensions=(1536, 1024)),
|
|
],
|
|
)
|
|
|
|
await agent.run('Generate an image')
|
|
|
|
assert image_model.last_settings == snapshot({'dimensions': (1536, 1024)})
|
|
|
|
async def test_image_generation_merged_fallback_image_model_takes_the_later_one(
|
|
self, allow_model_requests: None, direct_generation_model: FunctionModel
|
|
):
|
|
"""Two capabilities naming different direct models leave one unused, so the later one wins.
|
|
|
|
A single value, merged the way the scalar fields are: the pair cannot be reconciled and
|
|
nothing about a model makes the earlier one the answer.
|
|
"""
|
|
first = TestImageGenerationModel('first')
|
|
later = TestImageGenerationModel('later')
|
|
merged = ImageGeneration.combine(
|
|
[
|
|
ImageGeneration(native=False, fallback_image_model=first),
|
|
ImageGeneration(native=False, fallback_image_model=later, dimensions=(1536, 1024)),
|
|
]
|
|
)
|
|
|
|
await Agent(direct_generation_model, capabilities=[merged]).run('Generate an image')
|
|
|
|
assert first.last_settings is None
|
|
assert later.last_settings == snapshot({'dimensions': (1536, 1024)})
|
|
|
|
async def test_image_generation_merged_local_generator_takes_the_later_one(
|
|
self, allow_model_requests: None, direct_generation_model: FunctionModel
|
|
):
|
|
"""Two capabilities naming different generators leave one unused, so the later one wins.
|
|
|
|
`ImageGenerator` compares by identity, and that is what makes these two different values:
|
|
generated field equality would have compared only `instrument`, called them equal, and
|
|
merged them to the first, disagreeing with
|
|
`test_image_generation_merged_fallback_image_model_takes_the_later_one`.
|
|
"""
|
|
first_model = TestImageGenerationModel('first')
|
|
later_model = TestImageGenerationModel('later')
|
|
later = ImageGenerator(later_model)
|
|
merged = ImageGeneration.combine(
|
|
[
|
|
ImageGeneration(native=False, local=ImageGenerator(first_model)),
|
|
ImageGeneration(native=False, local=later, dimensions=(1536, 1024)),
|
|
]
|
|
)
|
|
assert isinstance(merged, ImageGeneration)
|
|
assert merged.local is later
|
|
|
|
await Agent(direct_generation_model, capabilities=[merged]).run('Generate an image')
|
|
|
|
assert first_model.last_settings is None
|
|
assert later_model.last_settings == snapshot({'dimensions': (1536, 1024)})
|
|
|
|
async def test_image_generation_merged_fallback_image_models_differing_only_in_settings(
|
|
self, allow_model_requests: None, direct_generation_model: FunctionModel
|
|
):
|
|
"""Two models alike but for their default settings are still two models, so the later one runs.
|
|
|
|
`_settings` lives on the non-dataclass `ImageGenerationModel` base, outside generated field
|
|
equality, so field equality would call these two equal, merge them to the first, and send the
|
|
earlier model's dimensions under the later one's name.
|
|
"""
|
|
first = TestImageGenerationModel(settings={'dimensions': (512, 512)})
|
|
later = TestImageGenerationModel(settings={'dimensions': (1024, 1024)})
|
|
merged = ImageGeneration.combine(
|
|
[
|
|
ImageGeneration(native=False, fallback_image_model=first),
|
|
ImageGeneration(native=False, fallback_image_model=later),
|
|
]
|
|
)
|
|
|
|
await Agent(direct_generation_model, capabilities=[merged]).run('Generate an image')
|
|
|
|
assert first.last_settings is None
|
|
assert later.last_settings == snapshot({'dimensions': (1024, 1024)})
|
|
|
|
@pytest.mark.parametrize(
|
|
'build_models',
|
|
[
|
|
pytest.param(
|
|
_openai_models_differing_in_settings,
|
|
id='openai',
|
|
marks=pytest.mark.skipif(not openai_imports(), reason='openai not installed'),
|
|
),
|
|
pytest.param(
|
|
_google_models_differing_in_settings,
|
|
id='google',
|
|
marks=pytest.mark.skipif(not google_imports(), reason='Google Gen AI SDK not installed'),
|
|
),
|
|
pytest.param(
|
|
_xai_models_differing_in_settings,
|
|
id='xai',
|
|
marks=pytest.mark.skipif(not xai_imports(), reason='xAI SDK not installed'),
|
|
),
|
|
],
|
|
)
|
|
def test_image_generation_merged_provider_models_differing_only_in_settings(
|
|
self, build_models: Callable[[], tuple[ImageGenerationModel, ImageGenerationModel]]
|
|
):
|
|
"""Every provider model compares by identity, so the merge keeps the pair apart.
|
|
|
|
The provider instance and the model name are shared, so `settings` is all that differs, and
|
|
`settings` is the one thing generated field equality cannot see.
|
|
"""
|
|
first, later = build_models()
|
|
|
|
assert first != later
|
|
|
|
merged = ImageGeneration.combine(
|
|
[
|
|
ImageGeneration(native=False, fallback_image_model=first),
|
|
ImageGeneration(native=False, fallback_image_model=later),
|
|
]
|
|
)
|
|
|
|
assert isinstance(merged, ImageGeneration)
|
|
assert merged.fallback_image_model is later
|
|
|
|
async def test_image_generation_merged_dimensions_take_the_later_pair(
|
|
self, allow_model_requests: None, direct_generation_model: FunctionModel
|
|
):
|
|
"""`dimensions` is a `(width, height)` value, so the default sequence union corrupts it.
|
|
|
|
Unioning two overlapping pairs flips the orientation to `(1024, 1536)`, and unioning two
|
|
disjoint ones yields a three-element tuple that is no size at all. Asserted through the run
|
|
rather than on the merged capability alone, since sending the geometry is the point.
|
|
"""
|
|
overlapping_model = TestImageGenerationModel()
|
|
overlapping = ImageGeneration.combine(
|
|
[
|
|
ImageGeneration(native=False, fallback_image_model=overlapping_model, dimensions=(1024, 1024)),
|
|
ImageGeneration(native=False, fallback_image_model=overlapping_model, dimensions=(1536, 1024)),
|
|
]
|
|
)
|
|
await Agent(direct_generation_model, capabilities=[overlapping]).run('Generate an image')
|
|
assert overlapping_model.last_settings == snapshot({'dimensions': (1536, 1024)})
|
|
|
|
disjoint_model = TestImageGenerationModel()
|
|
disjoint = ImageGeneration.combine(
|
|
[
|
|
ImageGeneration(native=False, fallback_image_model=disjoint_model, dimensions=(512, 768)),
|
|
ImageGeneration(native=False, fallback_image_model=disjoint_model, dimensions=(1024, 1024)),
|
|
]
|
|
)
|
|
await Agent(direct_generation_model, capabilities=[disjoint]).run('Generate an image')
|
|
assert disjoint_model.last_settings == snapshot({'dimensions': (1024, 1024)})
|
|
|
|
def test_image_generation_plain_tool_local_is_not_a_direct_generator(self):
|
|
"""A `Tool` the capability didn't build itself carries no direct settings, so geometry is dropped."""
|
|
|
|
def my_gen(prompt: str) -> str:
|
|
return 'image_url' # pragma: no cover
|
|
|
|
with pytest.warns(UserWarning, match='ignored direct-only setting.*dimensions'):
|
|
ImageGeneration(local=Tool(my_gen, name='generate_image'), dimensions=(1280, 720))
|
|
|
|
async def test_image_generation_callable_native_does_not_warn_about_direct_only_geometry(
|
|
self, allow_model_requests: None
|
|
):
|
|
"""A callable `native` that yields no tool leaves the generator in place, so nothing is unapplied.
|
|
|
|
The framework resolves the callable per request, so the capability cannot anticipate the
|
|
result without calling it a second time; warning on the mere possibility would be wrong here.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
assert [tool.name for tool in info.function_tools] == ['generate_image']
|
|
return ModelResponse(parts=[TextPart(content='local path')])
|
|
|
|
outer_model = FunctionModel(
|
|
outer_model_fn,
|
|
profile=ModelProfile(supported_native_tools=frozenset({ImageGenerationTool})),
|
|
)
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[
|
|
ImageGeneration(native=lambda ctx: None, local=ImageGenerator(image_model), dimensions=(1280, 720))
|
|
],
|
|
)
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'local path'
|
|
|
|
async def test_image_generation_applies_direct_only_geometry_without_native_support(
|
|
self, allow_model_requests: None
|
|
):
|
|
"""The same configuration on a model without native image generation applies and stays silent."""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(local=ImageGenerator(image_model), dimensions=(1280, 720))],
|
|
)
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'done'
|
|
assert image_model.last_settings == {'dimensions': (1280, 720)}
|
|
|
|
async def test_image_generation_dimensions_override_an_inherited_native_aspect_ratio(
|
|
self, allow_model_requests: None
|
|
):
|
|
"""A custom `native` instance is the base for the direct settings, and `dimensions` outranks it.
|
|
|
|
The two are mutually exclusive in `ImageGenerationSettings`, so inheriting the ratio
|
|
alongside `dimensions` would fail the `generate_image` call over a setting the user never
|
|
passed to the capability.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[
|
|
ImageGeneration(
|
|
native=ImageGenerationTool(aspect_ratio='16:9'),
|
|
local=ImageGenerator(image_model),
|
|
dimensions=(1280, 720),
|
|
)
|
|
],
|
|
)
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'done'
|
|
assert image_model.last_settings == snapshot({'dimensions': (1280, 720)})
|
|
|
|
def test_image_generation_rejects_dimensions_and_aspect_ratio_set_together(self):
|
|
"""Only inheritance yields to `dimensions`; two geometries the caller set himself stay a conflict.
|
|
|
|
Wiring the direct generator settles the pair, so it is refused up front instead of reaching
|
|
the direct model's own mutual-exclusion check on the first `generate_image` call.
|
|
"""
|
|
with pytest.raises(UserError, match=r'`dimensions` and `aspect_ratio` are mutually exclusive'):
|
|
ImageGeneration(
|
|
local=ImageGenerator(TestImageGenerationModel()),
|
|
dimensions=(1280, 720),
|
|
aspect_ratio='16:9',
|
|
)
|
|
|
|
async def test_image_generation_warns_when_the_direct_fallback_drops_native_only_settings(
|
|
self, allow_model_requests: None
|
|
):
|
|
"""With the default `native=True` the direct tool runs on a model with no native support, applying neither.
|
|
|
|
The mirror of the native-supersedes notice: the construction-time warning only fires for
|
|
`native=False`, where the direct generator is provably the only implementation, so this
|
|
configuration needs the per-request one to say the settings went nowhere.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(local=ImageGenerator(image_model), output_format='webp', quality='high')],
|
|
)
|
|
|
|
with pytest.warns(
|
|
UserWarning,
|
|
match=r"ignored native-tool setting\(s\) on 'function:outer_model_fn:': `output_format`, `quality`",
|
|
):
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'done'
|
|
assert image_model.last_settings == snapshot({})
|
|
|
|
async def test_image_generation_native_only_notice_keeps_its_shipped_prefix(
|
|
self, allow_model_requests: None, direct_generation_model: FunctionModel
|
|
):
|
|
"""A `warnings.filterwarnings(message=...)` keyed to the notice's shipped text still matches both paths.
|
|
|
|
That filter matches from the start of the message, so the per-request notice names its model
|
|
after `setting(s)` rather than before `ignored`.
|
|
|
|
Neither notice depends on a provider response, so this is not a VCR test.
|
|
"""
|
|
with pytest.warns(UserWarning) as recorded:
|
|
ImageGeneration(native=False, fallback_image_model=TestImageGenerationModel(), quality='high')
|
|
agent = Agent(
|
|
direct_generation_model,
|
|
capabilities=[ImageGeneration(fallback_image_model=TestImageGenerationModel(), quality='high')],
|
|
)
|
|
await agent.run('Generate an image')
|
|
|
|
per_request = (
|
|
"The direct `ImageGeneration` fallback ignored native-tool setting(s) on 'function:outer_model_fn:': "
|
|
'`quality`. Configure provider-specific direct settings on the `ImageGenerator` or '
|
|
'`ImageGenerationModel` instead.'
|
|
)
|
|
messages = [str(warning.message) for warning in recorded]
|
|
# The run makes two model requests, the one that calls `generate_image` and the one that answers.
|
|
assert messages == [
|
|
'The direct `ImageGeneration` fallback ignored native-tool setting(s): `quality`. Configure '
|
|
'provider-specific direct settings on the `ImageGenerator` or `ImageGenerationModel` instead.',
|
|
per_request,
|
|
per_request,
|
|
]
|
|
shipped_prefix = re.escape('The direct `ImageGeneration` fallback ignored native-tool setting(s)')
|
|
assert all(re.match(shipped_prefix, message) for message in messages)
|
|
|
|
@pytest.mark.parametrize(
|
|
('agent_model', 'capability', 'notice'),
|
|
[
|
|
pytest.param(
|
|
agent_model,
|
|
ImageGeneration(fallback_image_model=TestImageGenerationModel(), dimensions=(1280, 720)),
|
|
r"""supersedes the direct generator on 'native', so direct-only setting\(s\) go unapplied: `dimensions`""",
|
|
id=f'{agent_model}-direct-only',
|
|
)
|
|
for agent_model in ('fallback', 'wrapped-fallback')
|
|
]
|
|
+ [
|
|
pytest.param(
|
|
agent_model,
|
|
ImageGeneration(fallback_image_model=TestImageGenerationModel(), quality='high'),
|
|
r"""ignored native-tool setting\(s\) on 'no_native': `quality`""",
|
|
id=f'{agent_model}-native-only',
|
|
)
|
|
for agent_model in ('fallback', 'wrapped-fallback', 'wrapped')
|
|
]
|
|
+ [
|
|
pytest.param(
|
|
'wrapped',
|
|
ImageGeneration(fallback_image_model=TestImageGenerationModel(), dimensions=(1280, 720)),
|
|
None,
|
|
id='wrapped-direct-only',
|
|
),
|
|
],
|
|
)
|
|
async def test_image_generation_dropped_settings_notice_reads_each_routed_model(
|
|
self,
|
|
allow_model_requests: None,
|
|
agent_model: Literal['fallback', 'wrapped-fallback', 'wrapped'],
|
|
capability: ImageGeneration[object],
|
|
notice: str | None,
|
|
):
|
|
"""Each model a request can reach resolves the swap against its own profile, and the notice follows.
|
|
|
|
A `FallbackModel` has no profile, so each of its models is named for the setting it would drop,
|
|
whether the `FallbackModel` is the agent's model or sits inside a wrapper; a wrapper over a
|
|
regular model is read through its own profile, which drops `quality` but applies `dimensions`.
|
|
The notice fires while the toolset is prepared, before any request, so this is not a VCR test.
|
|
"""
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
|
|
no_native = FunctionModel(
|
|
outer_model_fn, model_name='no_native', profile=ModelProfile(supported_native_tools=frozenset())
|
|
)
|
|
native = FunctionModel(
|
|
outer_model_fn,
|
|
model_name='native',
|
|
profile=ModelProfile(supported_native_tools=frozenset({ImageGenerationTool})),
|
|
)
|
|
fallback_model = FallbackModel(no_native, native)
|
|
models = {
|
|
'fallback': fallback_model,
|
|
'wrapped-fallback': WrapperModel(fallback_model),
|
|
'wrapped': WrapperModel(no_native),
|
|
}
|
|
agent = Agent(models[agent_model], capabilities=[capability])
|
|
|
|
if notice is None:
|
|
# `filterwarnings = ['error']` turns an unexpected notice into the failure.
|
|
result = await agent.run('Generate an image')
|
|
else:
|
|
with pytest.warns(UserWarning, match=notice) as recorded:
|
|
result = await agent.run('Generate an image')
|
|
assert len(recorded) == 1
|
|
|
|
assert result.output == 'done'
|
|
|
|
@pytest.mark.parametrize('wrapped', [pytest.param(False, id='bare'), pytest.param(True, id='wrapped')])
|
|
async def test_image_generation_dropped_settings_notice_says_nothing_for_a_model_that_routes_itself(
|
|
self, allow_model_requests: None, wrapped: bool
|
|
):
|
|
"""A model with no profile of its own that routes each request itself gets no notice, bare or wrapped.
|
|
|
|
Like a `FallbackModel` it routes by rules the notice can't see, but it has no list of models
|
|
to read in its place, so the notice says nothing for it rather than crash reading its profile,
|
|
and the run goes ahead even though the model it routes to drops `quality`. The response
|
|
carries the router's own name, so the run went through it.
|
|
`filterwarnings = ['error']` turns a notice into the failure. The notice fires while the
|
|
toolset is prepared, before any request, so this is not a VCR test.
|
|
"""
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
|
|
no_native = FunctionModel(
|
|
outer_model_fn, model_name='no_native', profile=ModelProfile(supported_native_tools=frozenset())
|
|
)
|
|
|
|
class RouterModel(Model):
|
|
"""Answers every request through `no_native` under its own name, with no profile of its own."""
|
|
|
|
@property
|
|
def model_name(self) -> str:
|
|
return 'router'
|
|
|
|
@property
|
|
def system(self) -> str:
|
|
return 'router'
|
|
|
|
@cached_property
|
|
def profile(self) -> ModelProfile:
|
|
raise NotImplementedError('RouterModel does not have its own model profile.')
|
|
|
|
def prepare_messages(
|
|
self, messages: list[ModelMessage], model_request_parameters: ModelRequestParameters | None = None
|
|
) -> list[ModelMessage]:
|
|
return messages
|
|
|
|
async def request(
|
|
self,
|
|
messages: list[ModelMessage],
|
|
model_settings: ModelSettings | None,
|
|
model_request_parameters: ModelRequestParameters,
|
|
) -> ModelResponse:
|
|
response = await no_native.request(messages, model_settings, model_request_parameters)
|
|
return replace(response, model_name=self.model_name, provider_name=self.system)
|
|
|
|
router = RouterModel()
|
|
agent = Agent(
|
|
WrapperModel(router) if wrapped else router,
|
|
capabilities=[ImageGeneration(fallback_image_model=TestImageGenerationModel(), quality='high')],
|
|
)
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert (result.output, result.response.model_name, result.response.provider_name) == (
|
|
'done',
|
|
'router',
|
|
'router',
|
|
)
|
|
|
|
async def test_image_generation_native_only_settings_are_silent_when_the_native_tool_runs(
|
|
self, allow_model_requests: None
|
|
):
|
|
"""The other side of the same profile flag: the native tool carries them, so nothing is dropped.
|
|
|
|
`filterwarnings = ['error']` turns the absent warning into the assertion.
|
|
"""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[TextPart(content='native path')])
|
|
|
|
outer_model = FunctionModel(
|
|
outer_model_fn,
|
|
profile=ModelProfile(supported_native_tools=frozenset({ImageGenerationTool})),
|
|
)
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(local=ImageGenerator(image_model), output_format='webp', quality='high')],
|
|
)
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'native path'
|
|
assert image_model.last_settings is None
|
|
|
|
async def test_image_generation_warns_when_native_supersedes_non_native_aspect_ratio(
|
|
self, allow_model_requests: None
|
|
):
|
|
"""`'2:1'` is outside the native tool's vocabulary, so only the dropped generator could apply it."""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[TextPart(content='native path')])
|
|
|
|
outer_model = FunctionModel(
|
|
outer_model_fn,
|
|
profile=ModelProfile(supported_native_tools=frozenset({ImageGenerationTool})),
|
|
)
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(local=ImageGenerator(image_model), aspect_ratio='2:1')],
|
|
)
|
|
|
|
with pytest.warns(UserWarning, match=r'direct-only setting\(s\) go unapplied: `aspect_ratio`'):
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'native path'
|
|
assert image_model.last_settings is None
|
|
|
|
async def test_image_generation_native_vocabulary_aspect_ratio_does_not_warn(self, allow_model_requests: None):
|
|
"""`'16:9'` is forwarded to the native tool, so the native path applies it rather than dropping it."""
|
|
image_model = TestImageGenerationModel()
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[TextPart(content='native path')])
|
|
|
|
outer_model = FunctionModel(
|
|
outer_model_fn,
|
|
profile=ModelProfile(supported_native_tools=frozenset({ImageGenerationTool})),
|
|
)
|
|
capability = ImageGeneration(local=ImageGenerator(image_model), aspect_ratio='16:9')
|
|
agent = Agent(outer_model, capabilities=[capability])
|
|
|
|
result = await agent.run('Generate an image')
|
|
|
|
assert result.output == 'native path'
|
|
native_tool = capability.get_native_tools()[0]
|
|
assert isinstance(native_tool, ImageGenerationTool)
|
|
assert native_tool.aspect_ratio == '16:9'
|
|
|
|
def test_image_generation_with_fallback_subagent_model(self):
|
|
"""ImageGeneration(fallback_subagent_model=...) provides a local fallback tool.
|
|
|
|
The subagent tool is derived when the toolset is requested, so `local` keeps what was declared.
|
|
"""
|
|
cap = ImageGeneration(fallback_subagent_model='openai-responses:gpt-5.4')
|
|
assert cap.local is None
|
|
assert cap.get_toolset() is not None
|
|
builtins = cap.get_native_tools()
|
|
assert len(builtins) == 1
|
|
assert isinstance(builtins[0], ImageGenerationTool)
|
|
|
|
@pytest.mark.parametrize('native', [True, False])
|
|
def test_image_generation_fallback_subagent_model_warns_for_direct_only_geometry(self, native: bool):
|
|
"""The subagent fallback can't carry `dimensions` whether or not the native tool is also built.
|
|
|
|
`native=False` is the only configuration that reaches the check through the `fallback_subagent_model`
|
|
term alone, so both spellings have to warn.
|
|
"""
|
|
with pytest.warns(UserWarning, match='ignored direct-only setting.*dimensions'):
|
|
cap = ImageGeneration(
|
|
native=native,
|
|
fallback_subagent_model='openai-responses:gpt-5.4',
|
|
dimensions=(2048, 1152),
|
|
)
|
|
|
|
assert cap.get_toolset() is not None
|
|
|
|
def test_image_generation_forwards_config_to_builtin(self):
|
|
"""ImageGeneration config fields are forwarded to the ImageGenerationTool builtin."""
|
|
cap = ImageGeneration(
|
|
action='generate',
|
|
background='opaque',
|
|
input_fidelity='high',
|
|
moderation='low',
|
|
image_model='gpt-image-2',
|
|
output_compression=80,
|
|
output_format='jpeg',
|
|
quality='high',
|
|
size='1024x1024',
|
|
aspect_ratio='16:9',
|
|
)
|
|
builtins = cap.get_native_tools()
|
|
assert len(builtins) == 1
|
|
tool = builtins[0]
|
|
assert isinstance(tool, ImageGenerationTool)
|
|
assert tool.action == 'generate'
|
|
assert tool.background == 'opaque'
|
|
assert tool.input_fidelity == 'high'
|
|
assert tool.moderation == 'low'
|
|
assert tool.model == 'gpt-image-2'
|
|
assert tool.output_compression == 80
|
|
assert tool.output_format == 'jpeg'
|
|
assert tool.quality == 'high'
|
|
assert tool.size == '1024x1024'
|
|
assert tool.aspect_ratio == '16:9'
|
|
|
|
@pytest.mark.parametrize(
|
|
('kwargs', 'ignored'),
|
|
[
|
|
({'dimensions': (2048, 1152)}, 'dimensions'),
|
|
({'size': '2048x1024', 'aspect_ratio': '2:1'}, '`size`, `aspect_ratio`'),
|
|
],
|
|
)
|
|
def test_image_generation_legacy_ignores_direct_only_geometry(self, kwargs: dict[str, Any], ignored: str):
|
|
with pytest.warns(UserWarning, match=f'ignored direct-only setting.*{ignored}'):
|
|
cap = ImageGeneration(image_model='gpt-image-2', **kwargs)
|
|
builtins = cap.get_native_tools()
|
|
assert len(builtins) == 1
|
|
tool = builtins[0]
|
|
assert isinstance(tool, ImageGenerationTool)
|
|
assert tool.size is None
|
|
assert tool.aspect_ratio is None
|
|
|
|
@pytest.mark.parametrize(
|
|
('kwargs', 'ignored'),
|
|
[
|
|
({'dimensions': (1280, 720)}, 'dimensions'),
|
|
({'aspect_ratio': '2:1'}, 'aspect_ratio'),
|
|
],
|
|
)
|
|
@pytest.mark.parametrize('native_form', ['instance', 'callable'])
|
|
def test_image_generation_non_default_native_ignores_direct_only_geometry(
|
|
self, native_form: Literal['instance', 'callable'], kwargs: dict[str, Any], ignored: str
|
|
):
|
|
"""A custom or dynamic `native` drops direct-only geometry exactly as `native=True` does.
|
|
|
|
The native tool has no way to express either setting whichever form built it, and without a
|
|
direct generator nothing else will, so the byte-identical configuration cannot be silent
|
|
just because `native` was spelled as an instance or a factory.
|
|
"""
|
|
with pytest.warns(UserWarning, match=f'ignored direct-only setting.*{ignored}'):
|
|
if native_form == 'instance':
|
|
ImageGeneration(native=ImageGenerationTool(provider_settings={'openai': {'quality': 'high'}}), **kwargs)
|
|
else:
|
|
ImageGeneration(native=lambda ctx: None, **kwargs)
|
|
|
|
@pytest.mark.parametrize(
|
|
'kwargs',
|
|
[
|
|
{'dimensions': (1280, 720)},
|
|
{'aspect_ratio': '19.5:9'},
|
|
],
|
|
)
|
|
def test_image_generation_direct_generator_suppresses_ignored_geometry_warning(self, kwargs: dict[str, Any]):
|
|
"""Geometry the native tool can't express is not "ignored" when a direct generator applies it.
|
|
|
|
`native=True` is the default, so the native tool is still built and still drops these values —
|
|
but warning about it is wrong when a direct generator honors them. Both cases
|
|
use a value outside the native vocabulary so they take the non-native branch.
|
|
|
|
`size` is deliberately absent: the direct fallback carries only `dimensions` and
|
|
`aspect_ratio`, so a non-native `size` really is dropped by both paths and still warns.
|
|
"""
|
|
cap = ImageGeneration(local=ImageGenerator(TestImageGenerationModel()), **kwargs)
|
|
builtins = cap.get_native_tools()
|
|
|
|
assert len(builtins) == 1
|
|
tool = builtins[0]
|
|
assert isinstance(tool, ImageGenerationTool)
|
|
assert tool.size is None
|
|
assert tool.aspect_ratio is None
|
|
|
|
def test_image_generation_capability_fields_do_not_warn_and_stay_readable(self):
|
|
"""Capability users get no deprecation warning, and the built tool's fields read as they always have."""
|
|
tool = ImageGeneration(
|
|
action='generate',
|
|
background='opaque',
|
|
input_fidelity='high',
|
|
moderation='low',
|
|
image_model='gpt-image-2',
|
|
quality='high',
|
|
).get_native_tools()[0]
|
|
|
|
assert isinstance(tool, ImageGenerationTool)
|
|
assert (tool.action, tool.background, tool.input_fidelity, tool.moderation, tool.model, tool.quality) == (
|
|
'generate',
|
|
'opaque',
|
|
'high',
|
|
'low',
|
|
'gpt-image-2',
|
|
'high',
|
|
)
|
|
assert tool.provider_settings is None
|
|
|
|
def test_image_generation_fallback_merges_custom_native_with_overrides(self):
|
|
"""A custom native instance produces a local fallback tool.
|
|
|
|
What that fallback is actually handed is asserted through `agent.run` by
|
|
`tests/test_fallback_native_factory.py::test_instance_native_config_is_merged_for_fallback`.
|
|
"""
|
|
custom_native = ImageGenerationTool(provider_settings={'openai': {'quality': 'high'}}, size='1024x1024')
|
|
cap = ImageGeneration(
|
|
native=custom_native,
|
|
fallback_subagent_model='openai-responses:gpt-5.4',
|
|
output_format='jpeg', # capability-level override
|
|
)
|
|
assert cap.get_toolset() is not None
|
|
|
|
async def test_image_generation_custom_native_ratio_reaches_both_fallbacks(self, allow_model_requests: None):
|
|
"""A custom `native` instance's `aspect_ratio` is the base for the direct fallback too.
|
|
|
|
The `fallback_subagent_model` subagent has merged custom-native settings since the capability shipped;
|
|
the direct fallback has to honor the same instance, or the identical configuration produces
|
|
differently shaped images depending on which fallback is configured. Capability-level fields
|
|
still override it on both paths, which is the precedence the class docstring states.
|
|
"""
|
|
native = ImageGenerationTool(aspect_ratio='16:9')
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args={'prompt': 'tiny robot'})])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
|
|
direct_model = TestImageGenerationModel()
|
|
direct_agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(native=native, local=ImageGenerator(direct_model))],
|
|
)
|
|
await direct_agent.run('Generate an image')
|
|
assert direct_model.last_settings == snapshot({'aspect_ratio': '16:9'})
|
|
|
|
overridden_model = TestImageGenerationModel()
|
|
overridden_agent = Agent(
|
|
outer_model,
|
|
capabilities=[ImageGeneration(native=native, local=ImageGenerator(overridden_model), aspect_ratio='4:3')],
|
|
)
|
|
await overridden_agent.run('Generate an image')
|
|
assert overridden_model.last_settings == snapshot({'aspect_ratio': '4:3'})
|
|
|
|
subagent_native_tools: list[AbstractNativeTool] = []
|
|
|
|
def inner_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
subagent_native_tools.extend(info.model_request_parameters.native_tools)
|
|
return ModelResponse(
|
|
parts=[FilePart(content=BinaryImage(data=b'\x89PNG\r\n\x1a\n', media_type='image/png'))]
|
|
)
|
|
|
|
inner_model = FunctionModel(inner_model_fn, profile=ModelProfile(supports_image_output=True))
|
|
subagent_agent = Agent(
|
|
outer_model, capabilities=[ImageGeneration(native=native, fallback_subagent_model=inner_model)]
|
|
)
|
|
await subagent_agent.run('Generate an image')
|
|
assert subagent_native_tools == snapshot([ImageGenerationTool(aspect_ratio='16:9')])
|
|
|
|
def test_image_generation_callable_native_with_fallback(self):
|
|
"""When native is a callable, the fallback local tool still gets created."""
|
|
cap = ImageGeneration(
|
|
native=lambda ctx: ImageGenerationTool(provider_settings={'openai': {'quality': 'high'}}),
|
|
fallback_subagent_model='openai-responses:gpt-5.4',
|
|
)
|
|
# Callable native can't be resolved at init time, but the local fallback is still provided
|
|
assert cap.get_toolset() is not None
|
|
|
|
@pytest.mark.parametrize(
|
|
('kwargs', 'stated'),
|
|
[
|
|
pytest.param(
|
|
{'fallback_subagent_model': 'openai-responses:gpt-5.4', 'local': _custom_local_tool},
|
|
'`local`, `fallback_subagent_model`',
|
|
id='subagent-and-custom-tool',
|
|
),
|
|
pytest.param(
|
|
{'fallback_subagent_model': 'openai-responses:gpt-5.4', 'local': False},
|
|
'`local`, `fallback_subagent_model`',
|
|
id='subagent-and-disabled-local',
|
|
),
|
|
pytest.param(
|
|
{'fallback_subagent_model': 'openai-responses:gpt-5.4', 'fallback_image_model': 'openai:gpt-image-2'},
|
|
'`fallback_subagent_model`, `fallback_image_model`',
|
|
id='subagent-and-direct',
|
|
),
|
|
pytest.param(
|
|
{'fallback_image_model': 'openai:gpt-image-2', 'local': _custom_local_tool},
|
|
'`local`, `fallback_image_model`',
|
|
id='direct-and-custom-tool',
|
|
),
|
|
pytest.param(
|
|
{
|
|
'fallback_image_model': 'openai:gpt-image-2',
|
|
'local': ImageGenerator(TestImageGenerationModel()),
|
|
},
|
|
'`local`, `fallback_image_model`',
|
|
id='direct-name-and-generator',
|
|
),
|
|
],
|
|
)
|
|
def test_image_generation_rejects_more_than_one_fallback(self, kwargs: dict[str, Any], stated: str):
|
|
"""The three fallbacks are alternatives: two of them leave one silently unused."""
|
|
with pytest.raises(UserError, match=f'cannot specify more than one of {re.escape(stated)}'):
|
|
ImageGeneration(**kwargs)
|
|
|
|
def test_image_generation_deprecated_fallback_model_argument(self):
|
|
"""`fallback_model=` still configures the subagent, and warns at the caller's own line."""
|
|
with pytest.warns(
|
|
PydanticAIDeprecationWarning, match=r'`fallback_model` is deprecated; use `fallback_subagent_model`'
|
|
) as record:
|
|
cap = ImageGeneration(fallback_model='openai-responses:gpt-5.4')
|
|
assert [warning.filename for warning in record] == [__file__]
|
|
assert cap.fallback_subagent_model == 'openai-responses:gpt-5.4'
|
|
assert cap.get_toolset() is not None
|
|
|
|
def test_image_generation_deprecated_fallback_model_attribute(self):
|
|
"""Reading and writing `.fallback_model` proxies `fallback_subagent_model`, and warns."""
|
|
cap = ImageGeneration(fallback_subagent_model='openai-responses:gpt-5.4')
|
|
with pytest.warns(
|
|
PydanticAIDeprecationWarning, match=r'`fallback_model` is deprecated; use `fallback_subagent_model`'
|
|
):
|
|
assert cap.fallback_model == 'openai-responses:gpt-5.4' # pyright: ignore[reportDeprecated]
|
|
with pytest.warns(
|
|
PydanticAIDeprecationWarning, match=r'`fallback_model` is deprecated; use `fallback_subagent_model`'
|
|
):
|
|
cap.fallback_model = 'openai-responses:gpt-5.5' # pyright: ignore[reportDeprecated]
|
|
assert cap.fallback_subagent_model == 'openai-responses:gpt-5.5'
|
|
|
|
def test_image_generation_rejects_both_model_names(self):
|
|
"""Both spellings at once is a mistake to report, not one to resolve silently."""
|
|
with pytest.raises(UserError, match='cannot specify both `fallback_model` and `fallback_subagent_model`'):
|
|
ImageGeneration(
|
|
fallback_subagent_model='openai-responses:gpt-5.4', fallback_model='openai-responses:gpt-5.5'
|
|
)
|
|
|
|
async def test_image_generation_callable_fallback_subagent_model(self, allow_model_requests: None):
|
|
"""ImageGeneration with async callable fallback_subagent_model resolves the model per-run."""
|
|
image_data = b'\x89PNG\r\n\x1a\n' # minimal PNG header
|
|
|
|
def inner_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[FilePart(content=BinaryImage(data=image_data, media_type='image/png'))])
|
|
|
|
inner_model = FunctionModel(inner_model_fn, profile=ModelProfile(supports_image_output=True))
|
|
|
|
async def model_factory(ctx: RunContext) -> FunctionModel:
|
|
return inner_model
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='done')])
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args='{"prompt": "test"}')])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(outer_model, capabilities=[ImageGeneration(fallback_subagent_model=model_factory)])
|
|
result = await agent.run('Generate a test image')
|
|
assert result.output == 'done'
|
|
assert result.all_messages() == snapshot(
|
|
[
|
|
ModelRequest(
|
|
parts=[UserPromptPart(content='Generate a test image', timestamp=IsDatetime())],
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelResponse(
|
|
parts=[
|
|
ToolCallPart(
|
|
tool_name='generate_image',
|
|
args='{"prompt": "test"}',
|
|
tool_call_id=IsStr(),
|
|
)
|
|
],
|
|
usage=RequestUsage(input_tokens=54, output_tokens=5),
|
|
model_name='function:outer_model_fn:',
|
|
model_id='function:function:outer_model_fn:',
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelRequest(
|
|
parts=[
|
|
ToolReturnPart(
|
|
tool_name='generate_image',
|
|
content=BinaryImage(data=b'\x89PNG\r\n\x1a\n', media_type='image/png'),
|
|
tool_call_id=IsStr(),
|
|
timestamp=IsDatetime(),
|
|
)
|
|
],
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelResponse(
|
|
parts=[TextPart(content='done')],
|
|
usage=RequestUsage(input_tokens=54, output_tokens=6),
|
|
model_name='function:outer_model_fn:',
|
|
model_id='function:function:outer_model_fn:',
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
]
|
|
)
|
|
|
|
async def test_image_generation_callable_returns_image_only_model(self, allow_model_requests: None):
|
|
"""Callable fallback_subagent_model returning an image-only model name is caught at call time."""
|
|
|
|
def model_factory(ctx: RunContext) -> str:
|
|
return 'openai-responses:gpt-image-1'
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args='{"prompt": "test"}')])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(outer_model, capabilities=[ImageGeneration(fallback_subagent_model=model_factory)])
|
|
with pytest.raises(UserError, match="'gpt-image-1' is a dedicated image generation model"):
|
|
await agent.run('Generate a test image')
|
|
|
|
@pytest.mark.parametrize('fallback', ['subagent', 'direct'])
|
|
async def test_image_generation_content_filter_error_becomes_model_retry(
|
|
self, fallback: Literal['subagent', 'direct'], allow_model_requests: None
|
|
):
|
|
"""Both fallbacks turn a moderation block into a retry prompt for the outer model.
|
|
|
|
The outer model is the one that wrote the prompt, so rephrasing is its move to make. Keeping
|
|
the conversion on both paths also means neither capability tool ever lets the exception out:
|
|
a durable engine matches non-retryable errors by class name, and `ContentFilterError` is not
|
|
on that list, so an escape would leave the tool activity retrying a deterministic refusal.
|
|
`ImageGenerator.generate` called directly still raises `ContentFilterError`.
|
|
"""
|
|
|
|
def blocked_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
raise ContentFilterError('image generation was blocked for content moderation')
|
|
|
|
class BlockedImageGenerationModel(TestImageGenerationModel):
|
|
async def generate(
|
|
self,
|
|
prompt: str,
|
|
*,
|
|
images: Sequence[ImageGenerationInput] | None = None,
|
|
settings: ImageGenerationSettings | None = None,
|
|
) -> ImageGenerationResult:
|
|
raise ContentFilterError('image generation was blocked for content moderation')
|
|
|
|
capability: ImageGeneration[object] = (
|
|
ImageGeneration(
|
|
fallback_subagent_model=FunctionModel(
|
|
blocked_model_fn, profile=ModelProfile(supports_image_output=True)
|
|
)
|
|
)
|
|
if fallback == 'subagent'
|
|
else ImageGeneration(native=False, fallback_image_model=BlockedImageGenerationModel())
|
|
)
|
|
|
|
call_count = 0
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
nonlocal call_count
|
|
call_count += 1
|
|
if call_count == 1:
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args='{"prompt": "test"}')])
|
|
return ModelResponse(parts=[TextPart(content='gave up')])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(outer_model, capabilities=[capability])
|
|
|
|
result = await agent.run('Generate a test image')
|
|
|
|
assert result.output == 'gave up'
|
|
retry_parts = [
|
|
part
|
|
for part in iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart)
|
|
if part.outcome == 'retried'
|
|
]
|
|
assert [part.content for part in retry_parts] == snapshot(
|
|
['image generation was blocked for content moderation']
|
|
)
|
|
|
|
async def test_image_generation_subagent_error_becomes_model_retry(self, allow_model_requests: None):
|
|
"""UnexpectedModelBehavior from subagent becomes a retry prompt to the outer model."""
|
|
|
|
# FunctionModel that returns text but no image — triggers UnexpectedModelBehavior
|
|
def no_image_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
return ModelResponse(parts=[TextPart(content='No image generated.')])
|
|
|
|
inner_model = FunctionModel(no_image_model_fn, profile=ModelProfile(supports_image_output=True))
|
|
|
|
call_count = 0
|
|
|
|
def outer_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
nonlocal call_count
|
|
call_count += 1
|
|
if call_count == 1:
|
|
return ModelResponse(parts=[ToolCallPart(tool_name='generate_image', args='{"prompt": "test"}')])
|
|
return ModelResponse(parts=[TextPart(content='gave up')])
|
|
|
|
outer_model = FunctionModel(outer_model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(outer_model, capabilities=[ImageGeneration(fallback_subagent_model=inner_model)])
|
|
result = await agent.run('Generate a test image')
|
|
assert result.output == 'gave up'
|
|
assert result.all_messages() == snapshot(
|
|
[
|
|
ModelRequest(
|
|
parts=[UserPromptPart(content='Generate a test image', timestamp=IsDatetime())],
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelResponse(
|
|
parts=[
|
|
ToolCallPart(
|
|
tool_name='generate_image',
|
|
args='{"prompt": "test"}',
|
|
tool_call_id=IsStr(),
|
|
)
|
|
],
|
|
usage=RequestUsage(input_tokens=54, output_tokens=5),
|
|
model_name='function:outer_model_fn:',
|
|
model_id='function:function:outer_model_fn:',
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelRequest(
|
|
parts=[
|
|
ToolReturnPart(
|
|
content='Exceeded maximum output retries (1)',
|
|
tool_name='generate_image',
|
|
tool_call_id=IsStr(),
|
|
timestamp=IsDatetime(),
|
|
outcome='retried',
|
|
retry=RetryInfo(cause='model_retry', attempt=1, max_retries=1),
|
|
)
|
|
],
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelResponse(
|
|
parts=[TextPart(content='gave up')],
|
|
usage=RequestUsage(input_tokens=62, output_tokens=7),
|
|
model_name='function:outer_model_fn:',
|
|
model_id='function:function:outer_model_fn:',
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
]
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
|
'provider, model_name, suggestion',
|
|
[
|
|
('openai-responses', 'gpt-image-2.6-flare', 'openai-responses:gpt-5.5'),
|
|
('openai-responses', 'gpt-image-2.6-sunburst', 'openai-responses:gpt-5.5'),
|
|
('openai-responses', 'gpt-image-2', 'openai-responses:gpt-5.5'),
|
|
('openai-responses', 'gpt-image-1.5', 'openai-responses:gpt-5.5'),
|
|
('openai-responses', 'gpt-image-1', 'openai-responses:gpt-5.4'),
|
|
('openai-responses', 'gpt-image-1-mini', 'openai-responses:gpt-5.4'),
|
|
('google', 'imagen-3.0-generate-002', 'google:gemini-3-pro-image'),
|
|
('google', 'imagen-3.0-fast-generate-001', 'google:gemini-3-pro-image'),
|
|
# xAI has no conversational model that carries the `ImageGenerationTool`, so the
|
|
# suggested alternative crosses providers; `fallback_image_model=` stays on xAI.
|
|
('xai', 'grok-imagine-image', 'openai-responses:gpt-5.5'),
|
|
('xai', 'grok-imagine-image-2.0', 'openai-responses:gpt-5.5'),
|
|
('xai', 'grok-imagine-image-quality', 'openai-responses:gpt-5.5'),
|
|
],
|
|
)
|
|
def test_image_generation_rejects_image_only_model(self, provider: str, model_name: str, suggestion: str):
|
|
"""Using a dedicated image model raises a clear error with a conversational alternative."""
|
|
with pytest.raises(
|
|
UserError,
|
|
match=re.escape(
|
|
f'{model_name!r} is a dedicated image generation model that cannot be used as '
|
|
f'`fallback_subagent_model` directly. Pass it to `fallback_image_model` instead, or use a '
|
|
f'conversational model with image generation support, e.g. {suggestion!r}.'
|
|
),
|
|
):
|
|
ImageGeneration(fallback_subagent_model=f'{provider}:{model_name}')
|
|
|
|
@pytest.mark.skipif(not openai_imports(), reason='openai not installed')
|
|
@pytest.mark.vcr()
|
|
async def test_image_generation_local_fallback(self, allow_model_requests: None, openai_api_key: str):
|
|
"""The fallback subagent sends factory-produced native config with capability overrides."""
|
|
|
|
sent_bodies: list[dict[str, Any]] = []
|
|
|
|
async def capture_request(request: httpx2.Request) -> None:
|
|
sent_bodies.append(_REQUEST_BODY_ADAPTER.validate_json(request.content))
|
|
|
|
def native_factory(ctx: RunContext[Any]) -> ImageGenerationTool:
|
|
return ImageGenerationTool(provider_settings={'openai': {'quality': 'low'}})
|
|
|
|
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
# If we see a tool return, the image was generated — return final text
|
|
if any(
|
|
isinstance(part, ToolReturnPart)
|
|
for msg in messages
|
|
if isinstance(msg, ModelRequest)
|
|
for part in msg.parts
|
|
):
|
|
return ModelResponse(parts=[TextPart(content='Here is the generated image.')])
|
|
|
|
# First call: invoke the generate_image tool
|
|
assert info.function_tools, 'Expected generate_image tool to be available'
|
|
tool = info.function_tools[0]
|
|
return ModelResponse(parts=[ToolCallPart(tool_name=tool.name, args='{"prompt": "A cute baby sea otter"}')])
|
|
|
|
async with httpx2.AsyncClient(event_hooks={'request': [capture_request]}) as http_client:
|
|
inner_model = OpenAIResponsesModel(
|
|
'gpt-5.4', provider=OpenAIProvider(api_key=openai_api_key, http_client=http_client)
|
|
)
|
|
outer_model = FunctionModel(model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(
|
|
outer_model,
|
|
capabilities=[
|
|
ImageGeneration(
|
|
native=native_factory,
|
|
fallback_subagent_model=inner_model,
|
|
background='opaque',
|
|
),
|
|
],
|
|
)
|
|
result = await agent.run('Generate an image of a cute baby sea otter')
|
|
|
|
assert result.output == 'Here is the generated image.'
|
|
assert len(sent_bodies) == 1
|
|
generated_image = next(iter_message_parts(result.all_messages(), ModelRequest, ToolReturnPart)).content
|
|
assert isinstance(generated_image, BinaryImage)
|
|
# The format the provider actually returned, pinned here rather than only in the cassette.
|
|
assert generated_image.media_type == 'image/png'
|
|
assert sent_bodies[0]['tools'] == snapshot(
|
|
[
|
|
{
|
|
'type': 'image_generation',
|
|
'action': 'auto',
|
|
'background': 'opaque',
|
|
'moderation': 'auto',
|
|
'output_compression': 100,
|
|
'output_format': 'png',
|
|
'partial_images': 0,
|
|
'quality': 'low',
|
|
'size': 'auto',
|
|
}
|
|
]
|
|
)
|
|
assert result.all_messages() == snapshot(
|
|
[
|
|
ModelRequest(
|
|
parts=[
|
|
UserPromptPart(content='Generate an image of a cute baby sea otter', timestamp=IsDatetime())
|
|
],
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelResponse(
|
|
parts=[
|
|
ToolCallPart(
|
|
tool_name='generate_image',
|
|
args='{"prompt": "A cute baby sea otter"}',
|
|
tool_call_id=IsStr(),
|
|
)
|
|
],
|
|
usage=RequestUsage(input_tokens=59, output_tokens=9),
|
|
model_name='function:model_fn:',
|
|
model_id='function:function:model_fn:',
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelRequest(
|
|
parts=[
|
|
ToolReturnPart(
|
|
tool_name='generate_image',
|
|
content=IsInstance(BinaryImage),
|
|
tool_call_id=IsStr(),
|
|
timestamp=IsDatetime(),
|
|
)
|
|
],
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelResponse(
|
|
parts=[TextPart(content='Here is the generated image.')],
|
|
usage=RequestUsage(input_tokens=59, output_tokens=15),
|
|
model_name='function:model_fn:',
|
|
model_id='function:function:model_fn:',
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
]
|
|
)
|
|
|
|
@pytest.mark.vcr()
|
|
async def test_image_generation_local_fallback_google(self, allow_model_requests: None, gemini_api_key: str):
|
|
"""ImageGeneration fallback with Google image model."""
|
|
pytest.importorskip('google.genai', reason='google extra not installed')
|
|
from pydantic_ai.models.google import GoogleModel
|
|
from pydantic_ai.providers.google import GoogleProvider
|
|
|
|
def model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
if any(isinstance(p, ToolReturnPart) for m in messages if isinstance(m, ModelRequest) for p in m.parts):
|
|
return ModelResponse(parts=[TextPart(content='Here is the generated image.')])
|
|
assert info.function_tools, 'Expected generate_image tool to be available'
|
|
tool = info.function_tools[0]
|
|
return ModelResponse(parts=[ToolCallPart(tool_name=tool.name, args='{"prompt": "A cute baby sea otter"}')])
|
|
|
|
inner_model = GoogleModel('gemini-3-pro-image', provider=GoogleProvider(api_key=gemini_api_key))
|
|
outer_model = FunctionModel(model_fn, profile=ModelProfile(supported_native_tools=frozenset()))
|
|
agent = Agent(outer_model, capabilities=[ImageGeneration(fallback_subagent_model=inner_model)])
|
|
result = await agent.run('Generate an image of a cute baby sea otter')
|
|
assert result.output == 'Here is the generated image.'
|
|
assert result.all_messages() == snapshot(
|
|
[
|
|
ModelRequest(
|
|
parts=[
|
|
UserPromptPart(content='Generate an image of a cute baby sea otter', timestamp=IsDatetime())
|
|
],
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelResponse(
|
|
parts=[
|
|
ToolCallPart(
|
|
tool_name='generate_image',
|
|
args='{"prompt": "A cute baby sea otter"}',
|
|
tool_call_id=IsStr(),
|
|
)
|
|
],
|
|
usage=RequestUsage(input_tokens=59, output_tokens=9),
|
|
model_name='function:model_fn:',
|
|
model_id='function:function:model_fn:',
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelRequest(
|
|
parts=[
|
|
ToolReturnPart(
|
|
tool_name='generate_image',
|
|
content=IsInstance(BinaryImage),
|
|
tool_call_id=IsStr(),
|
|
timestamp=IsDatetime(),
|
|
)
|
|
],
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
ModelResponse(
|
|
parts=[TextPart(content='Here is the generated image.')],
|
|
usage=RequestUsage(input_tokens=59, output_tokens=15),
|
|
model_name='function:model_fn:',
|
|
model_id='function:function:model_fn:',
|
|
timestamp=IsDatetime(),
|
|
run_id=IsStr(),
|
|
conversation_id=IsStr(),
|
|
),
|
|
]
|
|
)
|