diff --git a/docs/index.md b/docs/index.md index 1e8a88cf3..c5481c1fe 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,7 +1,7 @@ # API Reference !!! note - Full Genkit documentation is available at [genkit.dev](https://genkit.dev/python/docs/get-started/) + Full Genkit documentation is available at [genkit.dev](https://genkit.dev/docs/python/get-started/) ## genkit diff --git a/docs/migrating-from-0.12.md b/docs/migrating-from-0.12.md index 861912ccf..919a58b5b 100644 --- a/docs/migrating-from-0.12.md +++ b/docs/migrating-from-0.12.md @@ -204,7 +204,7 @@ If you're a coding agent, replace each enum member with its string value. The va Every removed name, and what to use instead: -- **Model enums** (`KnownGemini*`, `KnownGpt`, `KnownClaude`, `*Version`, `GeminiEmbeddingModels`, `VertexEmbeddingModels`): pass the model name as a string, such as `'openai/gpt-4o'`. +- **Model enums** (`KnownGeminiModels`, `KnownGemini*`, `KnownGpt`, `KnownClaude`, `*Version`, `GeminiEmbeddingModels`, `VertexEmbeddingModels`): pass a typed ref such as `GoogleAI.gemini('gemini-flash-latest')` or `OpenAI.gpt('gpt-4o')`, or the model name as a string, such as `'openai/gpt-4o'`. - **Name helpers** (`bedrock_name`, `anthropic_name`, `ollama_name`, `openai_model`, `genkit_eval_name`, `package_name`): use the full `'plugin/model'` string. - **`Candidate`**: use the response's `message`. - **`Document.data`, `Document.data_type`, `Document.from_data()`**: build a `Document` with its constructor. @@ -808,7 +808,10 @@ model = openai_model('gpt-4o') **New:** ```python -model = 'openai/gpt-4o' +from genkit_openai import OpenAI + +model = OpenAI.gpt('gpt-4o') # typed ref; autocompletes and binds OpenAIConfig +model = 'openai/gpt-4o' # plain string also works ``` ## Ollama @@ -907,6 +910,22 @@ if res.output is None: With `raise_on_error=True`, an incomplete reply raises `GenkitError` with reason `INVALID_OUTPUT` instead. +## Non-model output schemas + +`output_schema` now hydrates any type pydantic validates (`list[T]`, dataclasses, `TypedDict`, `Enum`, `Literal`, `Decimal`, `UUID`, `datetime`), not just `BaseModel`, so drop workarounds for the old raw JSON: index a dataclass by attribute (`res.output.name`, not `res.output['name']`), compare a plain `Enum` to its member (`Status.OPEN`, not `'OPEN'`), and do `Decimal` math instead of `float` math. + +## Typed `output` + +With `output_schema=T`, `response.output` types as `T` instead of `T | None`, for `generate`, `generate_stream`'s final response, and prompts. Drop the `cast()`. With no schema, or a JSON-schema dict, it types as `Any`. `chunk.output` stays `T | None`: early chunks have nothing to parse yet. + +```python +res = await ai.generate(prompt='Suggest a dish.', output_schema=Dish) +print(res.output.name) +# => Smoked Salmon Tartine +``` + +The static type does not model `None`, but `output` is still `None` at runtime when the reply has no output. With the default `raise_on_error=False`, that includes a reply that doesn't match the schema (`error` is set). It also covers an interrupt, a `blocked` finish, or a stream you stopped early. Keep a guard, or pass `raise_on_error=True` so a non-matching reply raises instead. Under strict pyright, `if res.output is None:` now reports `reportUnnecessaryComparison`; guard on `res.error`, `res.finish_reason`, or `res.interrupts` instead. + ## Flow input and output validation Flow input and output are now validated against their type annotations. A flow that returns the wrong shape now raises. For served flows, `{"data": null}` means "use the default". @@ -939,9 +958,11 @@ from genkit.middleware import Middleware, MiddlewareContext @ai.middleware class PiiRedact(Middleware[Cfg]): name = 'pii_redact' - async def model(self, params, ctx: MiddlewareContext, next_fn): ... + async def wrap_model(self, params, ctx: MiddlewareContext, next_fn): ... ``` +Hooks are now `wrap_generate`, `wrap_model`, and `wrap_tool`. A method still named `model` is never called; the class inherits the pass-through `wrap_model` and the request goes to the provider unchanged, with no error. + `tools()` returns `Tool` handles. `GenerateMiddleware`, `MiddlewareRef`, `MiddlewarePlugin` and `new_middleware` are removed. ### Defining models and embedders diff --git a/packages/genkit-amazon-bedrock/README.md b/packages/genkit-amazon-bedrock/README.md index 7a6da5769..2700ba8e3 100644 --- a/packages/genkit-amazon-bedrock/README.md +++ b/packages/genkit-amazon-bedrock/README.md @@ -115,11 +115,18 @@ from genkit_amazon_bedrock import Bedrock, BedrockConfig claude = Bedrock.text('us.anthropic.claude-sonnet-4-5-20250929-v1:0', config=BedrockConfig(max_output_tokens=512)) # 2. Generate -response = await ai.generate(model=claude, prompt='Pair a wine with mushroom risotto.') -print(response.text) -# => A dry white such as a Pinot Grigio ... +async def main() -> None: + response = await ai.generate(model=claude, prompt='Pair a wine with mushroom risotto.') + print(response.text) + # => A dry white such as a Pinot Grigio ... + + +if __name__ == '__main__': + ai.run_main(main()) ``` +Later snippets use `await` and show only the call; run them inside `async def main()` as above. + The constructors follow Bedrock's output modalities: `Bedrock.text` (TEXT, served over Converse, including models that take image or document input), `Bedrock.stability` (IMAGE, the Stability text-to-image models), and diff --git a/packages/genkit-anthropic/README.md b/packages/genkit-anthropic/README.md index 361b1ad4c..2b7037d6b 100644 --- a/packages/genkit-anthropic/README.md +++ b/packages/genkit-anthropic/README.md @@ -26,13 +26,22 @@ from genkit_anthropic import Anthropic ai = Genkit(plugins=[Anthropic()]) -res = await ai.generate( - model=Anthropic.claude('claude-sonnet-4-6'), - prompt='Explain recursion in 10 words.', -) -print(res.text) + +async def main() -> None: + res = await ai.generate( + model=Anthropic.claude('claude-sonnet-4-6'), + prompt='Explain recursion in 10 words.', + ) + print(res.text) + # => A function that solves a problem by calling itself repeatedly. + + +if __name__ == '__main__': + ai.run_main(main()) ``` +Later snippets use `await` and show only the call; run them inside `async def main()` as above. + Set `ANTHROPIC_API_KEY` in the environment, or pass `api_key=` to `Anthropic()`. `base_url=` points the plugin at another server. Pass the origin with no `/v1` suffix; the SDK appends `/v1/messages`. Any other `AsyncAnthropic` setting goes diff --git a/packages/genkit-django/src/genkit_django/__init__.py b/packages/genkit-django/src/genkit_django/__init__.py index ee64aa470..9b5309ece 100644 --- a/packages/genkit-django/src/genkit_django/__init__.py +++ b/packages/genkit-django/src/genkit_django/__init__.py @@ -57,7 +57,7 @@ async def chat(prompt: str) -> str: ``` Requirements: - - Django 4.1+ (async views require ASGI) + - Django 5.0+ (async views require ASGI) - An ASGI server such as ``uvicorn`` or ``daphne``: ```bash diff --git a/packages/genkit-fastapi/README.md b/packages/genkit-fastapi/README.md index a613a1b61..c45a9f715 100644 --- a/packages/genkit-fastapi/README.md +++ b/packages/genkit-fastapi/README.md @@ -121,10 +121,12 @@ app = FastAPI() @ai.flow() async def ask_chef(prompt: str, ctx: FlowContext[str]) -> str: - stream = ai.generate_stream(prompt=prompt) - async for chunk in stream: - ctx.send_chunk(chunk.text) - return (await stream.response).text + result = ai.generate_stream(prompt=prompt) + # The context manager closes the model stream if the client disconnects. + async with result.stream as chunks: + async for chunk in chunks: + ctx.send_chunk(chunk.text) + return (await result.response).text @app.post('/chat/stream') diff --git a/packages/genkit-google-cloud/src/genkit_google_cloud/__init__.py b/packages/genkit-google-cloud/src/genkit_google_cloud/__init__.py index c3e0bce9c..17ca5b6e3 100644 --- a/packages/genkit-google-cloud/src/genkit_google_cloud/__init__.py +++ b/packages/genkit-google-cloud/src/genkit_google_cloud/__init__.py @@ -34,8 +34,15 @@ # All subsequent Genkit actions automatically export telemetry ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest')) - await ai.generate(prompt='Hello, world!') - # => Traces exported asynchronously to Cloud Trace (latency, tokens, status) + + + async def main() -> None: + await ai.generate(prompt='Hello, world!') + # => Traces exported asynchronously to Cloud Trace (latency, tokens, status) + + + if __name__ == '__main__': + ai.run_main(main()) ``` Requirements: diff --git a/packages/genkit-google-genai/README.md b/packages/genkit-google-genai/README.md index 93a38863b..8a798c27e 100644 --- a/packages/genkit-google-genai/README.md +++ b/packages/genkit-google-genai/README.md @@ -15,6 +15,7 @@ This Genkit plugin provides a unified interface for Google AI (Gemini) and Verte ## Setup environment ```bash +uv init my-genkit-app && cd my-genkit-app uv add genkit genkit-google-genai ``` @@ -53,11 +54,15 @@ async def greet(name: str) -> str: return res.text -# 3. Execute and inspect output -print(await greet('Grace')) -# => Hello Grace! How can I help you today? +# 3. Run the flow from the script entry point +if __name__ == '__main__': + print(ai.run_main(greet('Grace'))) + # => Hello Grace! How can I help you today? ``` +The snippets below use `await`, so run them inside an `async def main()` and +call `ai.run_main(main())`, as shown here. + ## Features ### Dynamic Models @@ -88,23 +93,28 @@ async def check_inventory(ingredient: str) -> dict[str, int]: return {'pesto': 12, 'pine_nuts': 4} -# 3. Generate with flat thinking, safety, search grounding, and a tool -res = await ai.generate( - model=GoogleAI.gemini('gemini-flash-latest'), - prompt='Check pesto inventory and cite current safety storage guidelines.', - tools=[check_inventory], - config=GeminiConfig( - thinking_level='HIGH', - include_thoughts=True, - safety_settings=[ - {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'threshold': 'BLOCK_ONLY_HIGH'}, - ], - google_search=True, - ), -) +# 3. Generate with flat thinking and safety settings, and let the model call the tool +async def main() -> None: + res = await ai.generate( + model=GoogleAI.gemini('gemini-flash-latest'), + prompt='How many jars of pesto do we have, and how should opened jars be stored?', + tools=[check_inventory], + tool_choice='auto', + config=GeminiConfig( + thinking_level='HIGH', + include_thoughts=True, + safety_settings=[ + {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'threshold': 'BLOCK_ONLY_HIGH'}, + ], + ), + ) + print(res.text) + # => We have 12 jars of pesto in stock. Refrigerate opened jars and use + # them within 7 to 10 days. + -print(res.text) -# => Inventory verified: 12 jars of pesto in stock. Storage guidelines require refrigeration at 40°F (4°C) or below after opening. +if __name__ == '__main__': + ai.run_main(main()) ``` #### Audio generation with GeminiTtsConfig @@ -115,18 +125,24 @@ from genkit_google_genai import GeminiTtsConfig, GoogleAI ai = Genkit(plugins=[GoogleAI()]) -# Generate multi-speaker audio dialog -res = await ai.generate( - model=GoogleAI.gemini_tts('gemini-2.5-flash-preview-tts'), - prompt='Host: Welcome to Morning Roaster. Chef: Today we review Ethiopian beans.', - config=GeminiTtsConfig( - speakers={'Host': 'Kore', 'Chef': 'Puck'}, - language_code='en-US', - ), -) -print(res.media.url) -# => data:audio/wav;base64,UklGRiQAAABXQVZFZ... +# Generate multi-speaker audio dialog +async def main() -> None: + res = await ai.generate( + model=GoogleAI.gemini_tts('gemini-2.5-flash-preview-tts'), + prompt='Host: Welcome to Morning Roaster. Chef: Today we review Ethiopian beans.', + config=GeminiTtsConfig( + speakers={'Host': 'Kore', 'Chef': 'Puck'}, + language_code='en-US', + ), + ) + + print(res.media.url) + # => data:audio/wav;base64,UklGRiQAAABXQVZFZ... + + +if __name__ == '__main__': + ai.run_main(main()) ``` #### Image generation with GeminiImageConfig @@ -137,18 +153,24 @@ from genkit_google_genai import GeminiImageConfig, GoogleAI ai = Genkit(plugins=[GoogleAI()]) -# Generate high-resolution image with specified aspect ratio and size -res = await ai.generate( - model=GoogleAI.gemini_image('gemini-2.5-flash-preview-image-generation'), - prompt='A modern minimalist espresso bar with warm cedar accents.', - config=GeminiImageConfig( - aspect_ratio='16:9', - image_size='2K', - ), -) -print(res.media.url) -# => data:image/png;base64,iVBORw0KGgoAAAANSU... +# Generate high-resolution image with specified aspect ratio and size +async def main() -> None: + res = await ai.generate( + model=GoogleAI.gemini_image('gemini-3.1-flash-image'), + prompt='A modern minimalist espresso bar with warm cedar accents.', + config=GeminiImageConfig( + aspect_ratio='16:9', + image_size='2K', + ), + ) + + print(res.media.url) + # => data:image/png;base64,iVBORw0KGgoAAAANSU... + + +if __name__ == '__main__': + ai.run_main(main()) ``` #### Default config on model references @@ -182,10 +204,18 @@ Function calling mode is controlled by `ai.generate(tool_choice=...)`, not confi `'auto'`, `'required'`, or `'none'`. In `'required'` mode, Gemini binds the request's function tools as `allowedFunctionNames`. -Settings that can't be combined raise before anything is sent: +Settings that can't be combined never reach Gemini: + +- `thinking_level` with `thinking_budget`, and `voice` with `speakers`, raise + `INVALID_ARGUMENT` from `generate` (`GeminiConfig(...)` raises a Pydantic + `ValidationError` on construction). When one comes from a model reference + default, pass `None` for it on the call. + +The model checks the rest when it builds the request. These don't raise by +default: the call returns `finish_reason='failed'` with +`response.error.status == 'INVALID_ARGUMENT'`. Pass `raise_on_error=True` to +raise instead. -- `thinking_level` with `thinking_budget`, and `voice` with `speakers`. When - one comes from a model reference default, pass `None` for it on the call. - `google_search_start_time` without `google_search_end_time`, and `file_search_top_k` or `file_search_metadata_filter` without `file_search_store_names`. @@ -253,7 +283,7 @@ function tools (`generate(tools=...)` raises). Blocks with defaults, such as milliseconds: `config={'timeout': 30000}` becomes `config={'timeout': 30}`. ```python -op = await ai.generate_operation( +op = await ai.generate_operation( # inside async def main() model='googleai/deep-research-preview-04-2026', prompt='Summarize recent advances in quantum error correction.', config={'thinking_summaries': 'auto', 'extra': {'agent_config': {'visualization': 'auto'}}}, @@ -271,6 +301,11 @@ bounds reach the model as written. ```python from pydantic import BaseModel +from genkit import Genkit +from genkit_google_genai import GoogleAI + +ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest')) + class Country(BaseModel): name: str @@ -278,8 +313,14 @@ class Country(BaseModel): population: int -response = await ai.generate(prompt='Give quick facts about Japan.', output_schema=Country) -print(response.output) +async def main() -> None: + response = await ai.generate(prompt='Give quick facts about Japan.', output_schema=Country) + print(response.output) + # => name='Japan' capital='Tokyo' population=123000000 + + +if __name__ == '__main__': + ai.run_main(main()) ``` To send the schema as the older OpenAPI-style `responseSchema` field instead, @@ -307,45 +348,61 @@ download URL, Vertex often sends the mp4 inline. **With `GoogleAI`:** ```python +import asyncio + from genkit import Genkit from genkit_google_genai import GoogleAI # 1. Initialize Genkit with GoogleAI ai = Genkit(plugins=[GoogleAI()]) -# 2. Launch background video generation -operation = await ai.generate_operation( - model=GoogleAI.veo('veo-3.1-fast-generate-preview'), - prompt='A paper airplane gliding through a bright classroom', -) -while not operation.done: - operation = await ai.check_operation(operation) +# 2. Launch background video generation and poll until it finishes +async def main() -> None: + operation = await ai.generate_operation( + model=GoogleAI.veo('veo-3.1-lite-generate-001'), + prompt='A paper airplane gliding through a bright classroom', + ) + while not operation.done: + await asyncio.sleep(5) + operation = await ai.check_operation(operation) -# 3. Access output media artifact -print(operation.output.message.content[0].media.url) -# => https://generativelanguage.googleapis.com/v1beta/files/preview.mp4 + # 3. Access output media artifact + print(operation.output.message.content[0].media.url) + # => https://generativelanguage.googleapis.com/v1beta/files/preview.mp4 + + +if __name__ == '__main__': + ai.run_main(main()) ``` **With `VertexAI`:** ```python +import asyncio + from genkit import Genkit from genkit_google_genai import VertexAI # 1. Initialize Genkit with VertexAI ai = Genkit(plugins=[VertexAI()]) -# 2. Launch background video generation -operation = await ai.generate_operation( - model=VertexAI.veo('veo-3.1-generate-001'), - prompt='A paper airplane gliding through a bright classroom', -) -while not operation.done: - operation = await ai.check_operation(operation) +# 2. Launch background video generation and poll until it finishes +async def main() -> None: + operation = await ai.generate_operation( + model=VertexAI.veo('veo-3.1-generate-001'), + prompt='A paper airplane gliding through a bright classroom', + ) + while not operation.done: + await asyncio.sleep(5) + operation = await ai.check_operation(operation) -# 3. Access output media artifact -print(operation.output.message.content[0].media.url) -# => gs://my-bucket/videos/output.mp4 + # 3. Access output media artifact + print(operation.output.message.content[0].media.url) + # => gs://my-bucket/videos/output.mp4 + + +if __name__ == '__main__': + ai.run_main(main()) ``` Runnable version: [google-genai-media](https://github.com/genkit-ai/genkit/tree/main/py/samples/google-genai-media). @@ -364,24 +421,31 @@ from genkit_google_genai import VertexAI ai = Genkit(plugins=[VertexAI()]) -response = await ai.generate( - model=VertexAI.virtual_try_on('virtual-try-on-001'), - messages=[ - Message( - role=Role.USER, - content=[ - Part.from_media( - 'gs://my-bucket/person.png', content_type='image/png', metadata={'type': 'personImage'} - ), - Part.from_media( - 'gs://my-bucket/shirt.png', content_type='image/png', metadata={'type': 'productImage'} - ), - ], - ) - ], -) -for part in response.message.content: - print(part.media.url) + +async def main() -> None: + response = await ai.generate( + model=VertexAI.virtual_try_on('virtual-try-on-001'), + messages=[ + Message( + role=Role.USER, + content=[ + Part.from_media( + 'gs://my-bucket/person.png', content_type='image/png', metadata={'type': 'personImage'} + ), + Part.from_media( + 'gs://my-bucket/shirt.png', content_type='image/png', metadata={'type': 'productImage'} + ), + ], + ) + ], + ) + for part in response.message.content: + print(part.media.url) + # => data:image/png;base64,iVBORw0KGgoAAAANSU... + + +if __name__ == '__main__': + ai.run_main(main()) ``` Runnable snippets are in [`py/samples`](../../samples). diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_google.py b/packages/genkit-google-genai/src/genkit_google_genai/_google.py index 864fe63ed..3687b523e 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -458,7 +458,7 @@ class GoogleAI(GoogleFamilyRefs, Plugin): |---|---|---| | Gemini / Gemma | MODEL | ``googleai/gemini-flash-latest`` | | Embedders | EMBEDDER | ``googleai/gemini-embedding-001`` | - | Veo (Video) | BACKGROUND_MODEL | ``googleai/veo-3.1-generate-preview`` | + | Veo (Video) | BACKGROUND_MODEL | ``googleai/veo-3.1-generate-001`` | Example: ```python diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py index 5887515f3..264fe8059 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py @@ -651,7 +651,9 @@ def _reject_contradictions(self) -> Self: default=None, description=( 'For Gemini 3 and later - the thinking level. A higher level is associated with more ' - 'detailed thinking, which is needed for solving more complex tasks. Not with thinking_budget.' + 'detailed thinking, which is needed for solving more complex tasks. Not with thinking_budget. ' + 'Supported levels vary by model: gemini-3.8-flash and gemini-3.1-pro-preview reject MINIMAL ' + 'with INVALID_ARGUMENT. Gemini 2.5 models reject thinking_level; use thinking_budget.' ), ) thinking_budget: int | None = Field( @@ -778,7 +780,7 @@ class GeminiImageConfig(GeminiConfig): # 2. Generate architectural artwork with specified aspect ratio and size res = await ai.generate( - model=GoogleAI.gemini_image('gemini-2.5-flash-preview-image-generation'), + model=GoogleAI.gemini_image('gemini-3.1-flash-image'), prompt='A modern minimalist espresso bar with warm cedar accents.', config=GeminiImageConfig( aspect_ratio='16:9', @@ -1005,11 +1007,28 @@ class GemmaConfig(GeminiConfig): ), ) +GEMINI_3_5_FLASH_LITE = ModelInfo( + label='Google AI - Gemini 3.5 Flash Lite', + supports=GEMINI_3_1_FLASH_LITE.supports, +) + GEMINI_FLASH_LITE_LATEST = ModelInfo( label='Google AI - Gemini Flash Lite Latest', supports=GEMINI_TEXT_SUPPORTS, ) +# The ``-latest`` aliases rotate server side, so their labels name the alias, +# not a generation. Capabilities match the generation they point at today. +GEMINI_FLASH_LATEST = ModelInfo( + label='Google AI - Gemini Flash Latest', + supports=GEMINI_3_5_FLASH.supports, +) + +GEMINI_PRO_LATEST = ModelInfo( + label='Google AI - Gemini Pro Latest', + supports=GEMINI_3_PRO_PREVIEW.supports, +) + GEMINI_IMAGE_SUPPORTS = ModelSupports( multiturn=True, media=True, @@ -1146,8 +1165,6 @@ class GemmaConfig(GeminiConfig): # Constructors take ``Known* | str``, so an unlisted id still type-checks # and routes. KnownSharedGemini: TypeAlias = Literal[ - 'gemini-2.5-flash', - 'gemini-2.5-pro', 'gemini-2.5-flash-lite', 'gemini-3-flash-preview', 'gemini-3.1-flash-lite', @@ -1161,11 +1178,18 @@ class GemmaConfig(GeminiConfig): # Vertex AI does not serve the rotating ``-latest`` aliases. KnownGoogleAIGemini: TypeAlias = Literal[ KnownSharedGemini, + 'gemini-3.5-flash-lite', 'gemini-flash-latest', 'gemini-flash-lite-latest', 'gemini-pro-latest', ] -KnownVertexAIGemini: TypeAlias = KnownSharedGemini +# The Gemini API (v1beta) returns 404 for the 2.5 Flash and Pro ids; Vertex AI +# still lists them. +KnownVertexAIGemini: TypeAlias = Literal[ + KnownSharedGemini, + 'gemini-2.5-flash', + 'gemini-2.5-pro', +] KnownGeminiTts: TypeAlias = Literal[ 'gemini-2.5-flash-preview-tts', 'gemini-2.5-pro-preview-tts', @@ -1179,11 +1203,6 @@ class GemmaConfig(GeminiConfig): 'gemini-3.1-flash-image', ] KnownGemma: TypeAlias = Literal[ - 'gemma-3-1b-it', - 'gemma-3-4b-it', - 'gemma-3-12b-it', - 'gemma-3-27b-it', - 'gemma-3n-e4b-it', 'gemma-4-26b-a4b-it', 'gemma-4-31b-it', ] @@ -1209,8 +1228,11 @@ def _add_model(model_info: ModelInfo, names: list[str]) -> None: _add_model(GEMINI_2_5_FLASH_LITE, ['gemini-2.5-flash-lite']) _add_model(GEMINI_FLASH_LITE_LATEST, ['gemini-flash-lite-latest']) _add_model(GEMINI_3_FLASH_PREVIEW, ['gemini-3-flash-preview']) -_add_model(GEMINI_3_PRO_PREVIEW, ['gemini-3-pro-preview', 'gemini-pro-latest']) -_add_model(GEMINI_3_5_FLASH, ['gemini-3.5-flash', 'gemini-flash-latest']) +_add_model(GEMINI_3_PRO_PREVIEW, ['gemini-3-pro-preview']) +_add_model(GEMINI_PRO_LATEST, ['gemini-pro-latest']) +_add_model(GEMINI_3_5_FLASH, ['gemini-3.5-flash']) +_add_model(GEMINI_FLASH_LATEST, ['gemini-flash-latest']) +_add_model(GEMINI_3_5_FLASH_LITE, ['gemini-3.5-flash-lite']) _add_model(GEMINI_3_6_FLASH, ['gemini-3.6-flash']) _add_model(GEMINI_3_7_FLASH, ['gemini-3.7-flash']) _add_model(GEMINI_3_8_FLASH, ['gemini-3.8-flash']) diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_registry.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_registry.py index 6fe3e6c0e..3ce3ec4b0 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_registry.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_registry.py @@ -65,6 +65,7 @@ def model_info( KnownLyria: TypeAlias = Literal[ 'lyria-3-clip-preview', 'lyria-3-pro-preview', + 'lyria-3.5', ] KNOWN_LYRIA_MODELS: tuple[str, ...] = get_args(KnownLyria) @@ -103,6 +104,7 @@ def list_known_lyria_models() -> list[str]: KNOWN_ANTIGRAVITY_MODELS: dict[str, ModelInfo] = { 'antigravity-preview-09-2026': ANTIGRAVITY_INFO, + 'antigravity-preview-latest': ANTIGRAVITY_INFO, } diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_utils.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_utils.py index 8c79d8396..6878ce2c1 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_utils.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_utils.py @@ -71,7 +71,7 @@ def api_key_for_context(context: dict[str, Any], plugin_api_key: str | None) -> status='FAILED_PRECONDITION', message=( 'Please pass in the API key or set the GEMINI_API_KEY or GOOGLE_API_KEY environment variable.\n' - 'For more details see https://genkit.dev/docs/plugins/google-genai/' + 'For more details see https://genkit.dev/docs/python/integrations/google-genai/' ), ) return api_key diff --git a/packages/genkit-google-genai/tests/models/model_refs_test.py b/packages/genkit-google-genai/tests/models/model_refs_test.py index 18a800c42..e6674b890 100644 --- a/packages/genkit-google-genai/tests/models/model_refs_test.py +++ b/packages/genkit-google-genai/tests/models/model_refs_test.py @@ -53,9 +53,8 @@ from genkit.embedder import EmbedderRef from genkit.model import ModelRef +_VERTEXAI_ONLY = {'gemini-2.5-flash', 'gemini-2.5-pro'} _SHARED_GEMINI = { - 'gemini-2.5-flash', - 'gemini-2.5-pro', 'gemini-2.5-flash-lite', 'gemini-3-flash-preview', 'gemini-3.1-flash-lite', @@ -67,6 +66,7 @@ 'gemini-3.8-flash', } _GOOGLEAI_LATEST = {'gemini-flash-latest', 'gemini-flash-lite-latest', 'gemini-pro-latest'} +_GOOGLEAI_ONLY = _GOOGLEAI_LATEST | {'gemini-3.5-flash-lite'} _SHARED_TTS = { 'gemini-2.5-flash-preview-tts', 'gemini-2.5-pro-preview-tts', @@ -87,18 +87,13 @@ _RETIRED_IMAGE = {'gemini-2.5-flash-image-preview', 'gemini-3-pro-image-preview', 'gemini-3.1-flash-image-preview'} _BACKEND_IDS: dict[tuple[type, str], set[str] | None] = { - (GoogleAI, 'gemini'): _SHARED_GEMINI | _GOOGLEAI_LATEST, - (VertexAI, 'gemini'): _SHARED_GEMINI, + (GoogleAI, 'gemini'): _SHARED_GEMINI | _GOOGLEAI_ONLY, + (VertexAI, 'gemini'): _SHARED_GEMINI | _VERTEXAI_ONLY, (GoogleAI, 'gemini_tts'): _SHARED_TTS, (VertexAI, 'gemini_tts'): _SHARED_TTS, (GoogleAI, 'gemini_image'): _SHARED_IMAGE, (VertexAI, 'gemini_image'): _SHARED_IMAGE, (GoogleAI, 'gemma'): { - 'gemma-3-1b-it', - 'gemma-3-4b-it', - 'gemma-3-12b-it', - 'gemma-3-27b-it', - 'gemma-3n-e4b-it', 'gemma-4-26b-a4b-it', 'gemma-4-31b-it', }, @@ -380,8 +375,8 @@ def test_known_gemini_matches_catalog(self) -> None: googleai = set(get_args(KnownGoogleAIGemini)) vertexai = set(get_args(KnownVertexAIGemini)) assert googleai | vertexai <= registered - assert registered - googleai == _RETIRED_GEMINI - assert registered - vertexai == _RETIRED_GEMINI | _GOOGLEAI_LATEST + assert registered - googleai == _RETIRED_GEMINI | _VERTEXAI_ONLY + assert registered - vertexai == _RETIRED_GEMINI | _GOOGLEAI_ONLY assert not any(is_tts_model(value) or is_image_model(value) or is_gemma_model(value) for value in googleai) def test_known_gemini_image_matches_catalog(self) -> None: diff --git a/packages/genkit-middleware/README.md b/packages/genkit-middleware/README.md index ba87f8480..e839d1d30 100644 --- a/packages/genkit-middleware/README.md +++ b/packages/genkit-middleware/README.md @@ -27,6 +27,8 @@ This plugin provides concrete middleware implementations for common use cases: Import the middleware classes you need and pass instances directly into `use=[]`: +The snippets in this README use `await`; run them inside an `async def main()` and call `ai.run_main(main())`. + ```python from genkit import Genkit from genkit_google_genai import GoogleAI @@ -136,19 +138,27 @@ first = await ai.generate( ``` When a non-allowed tool is called, execution is interrupted. Approve and re-run the -tool by restarting it with ``resumed_metadata`` that includes ``tool_approved``: +tool by restarting it with `resumed_metadata` that includes `tool_approved`. Pass the +history in `messages=` and leave out `prompt=`: a new prompt appends a user turn after +the pending tool request, and the call returns a failed response +(`finish_reason='failed'`, `response.error.status == 'FAILED_PRECONDITION'`) instead +of running the tool. ```python response = await ai.generate( model=GoogleAI.gemini('gemini-flash-latest'), - prompt='Delete the database', messages=list(first.messages), tools=['delete_database'], use=[approval], resume_restart=first.interrupts[0].restart(resumed_metadata={'tool_approved': True}), ) +print(response.text) +# => The database has been deleted. ``` +Inside the tool, `ctx.is_resumed()` is `True` on the approved re-run and +`ctx.resumed_metadata` holds the dict you passed (`{'tool_approved': True}`). + ### Skills Scans directories for SKILL.md files and exposes them as loadable instructions: diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 4f10d5b75..2c51212bd 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -27,13 +27,22 @@ from genkit_openai import OpenAI ai = Genkit(plugins=[OpenAI()]) -res = await ai.generate( - model=OpenAI.gpt('gpt-5.2'), - prompt='Suggest 2 catchy names for an AI newsletter.', -) -print(res.text) + +async def main() -> None: + res = await ai.generate( + model=OpenAI.gpt('gpt-5.2'), + prompt='Suggest 2 catchy names for an AI newsletter.', + ) + print(res.text) + # => 1. The Neural Brief 2. Prompt & Circumstance + + +if __name__ == '__main__': + ai.run_main(main()) ``` +Later snippets use `await` and show only the call; run them inside `async def main()` as above. + Set `OPENAI_API_KEY` in the environment, or pass `api_key=` to `OpenAI()`. `base_url=` points the plugin at another OpenAI-compatible server. Pass the URL up to and including `/v1`; the SDK appends `/chat/completions`. Any other @@ -53,8 +62,8 @@ OpenAI( before the request is sent, so a typo fails by name: ```python -res = await ai.generate( - model='openai/gpt-4o', +res = await ai.generate( # inside async def main() + model=OpenAI.gpt('gpt-4o'), prompt='Write a haiku about the sea.', config={ 'temperature': 0.2, @@ -82,8 +91,8 @@ To bill a call to someone else's OpenAI account, pass their key in text-to-speech, and transcription models: ```python -res = await ai.generate( - model='openai/gpt-4o', +res = await ai.generate( # inside async def main() + model=OpenAI.gpt('gpt-4o'), prompt='hi', context={'secrets': {'api_key': tenant_key}}, ) diff --git a/packages/genkit-vertexai/README.md b/packages/genkit-vertexai/README.md index daf427401..b7b07a014 100644 --- a/packages/genkit-vertexai/README.md +++ b/packages/genkit-vertexai/README.md @@ -35,11 +35,19 @@ ai = Genkit( plugins=[ModelGarden(project='my-project', location='us-central1')], ) -res = await ai.generate( - model='modelgarden/anthropic/claude-3-5-sonnet-v2@20241022', - prompt='Explain recursion in 10 words.', -) -print(res.text) + + +async def main() -> None: + res = await ai.generate( + model='modelgarden/anthropic/claude-sonnet-4-6', + prompt='Explain recursion in 10 words.', + ) + print(res.text) + # => A function that solves a problem by calling itself repeatedly. + + +if __name__ == '__main__': + ai.run_main(main()) ``` Requires Google Cloud Application Default Credentials (ADC) or explicit credentials. diff --git a/packages/genkit-vertexai/src/genkit_vertexai/__init__.py b/packages/genkit-vertexai/src/genkit_vertexai/__init__.py index 3b169e745..46b7dc4a7 100644 --- a/packages/genkit-vertexai/src/genkit_vertexai/__init__.py +++ b/packages/genkit-vertexai/src/genkit_vertexai/__init__.py @@ -29,15 +29,21 @@ plugins=[ModelGarden(project='my-project', location='us-central1')], ) + # 2. Call models under the modelgarden/ namespace (not vertexai/) - res = await ai.generate( - model='modelgarden/anthropic/claude-3-5-sonnet-v2@20241022', - prompt='Explain recursion in 10 words.', - ) + async def main() -> None: + res = await ai.generate( + model='modelgarden/anthropic/claude-sonnet-4-6', + prompt='Explain recursion in 10 words.', + ) + + # 3. Inspect output shapes directly + print(res.text) + # => A function calling itself until reaching a base stopping condition. + - # 3. Inspect output shapes directly - print(res.text) - # => A function calling itself until reaching a base stopping condition. + if __name__ == '__main__': + ai.run_main(main()) ``` Requirements: diff --git a/packages/genkit-vertexai/src/genkit_vertexai/_model_garden/_anthropic.py b/packages/genkit-vertexai/src/genkit_vertexai/_model_garden/_anthropic.py index 65870320d..66a1756dc 100644 --- a/packages/genkit-vertexai/src/genkit_vertexai/_model_garden/_anthropic.py +++ b/packages/genkit-vertexai/src/genkit_vertexai/_model_garden/_anthropic.py @@ -48,7 +48,7 @@ def __init__( Args: model: The name of the specific model to be used from Model Garden - in the way / (e.g., 'anthropic/claude-3-5-sonnet-v2@20241022'). + in the way / (e.g., 'anthropic/claude-sonnet-4-6'). location: The Google Cloud region where the Model Garden service is hosted (e.g., 'us-central1'). project: The Google Cloud project ID where the Model Garden diff --git a/packages/genkit/README.md b/packages/genkit/README.md index 7d8bd5d01..721f925bc 100644 --- a/packages/genkit/README.md +++ b/packages/genkit/README.md @@ -19,9 +19,12 @@ Vertex AI, Cloud Trace, and Firestore are there if you want them. So are OpenAI, ## Install ```bash +uv init my-genkit-app && cd my-genkit-app uv add genkit genkit-google-genai ``` +Using pip instead: `pip install genkit genkit-google-genai`. + ```python from pydantic import BaseModel, Field from genkit import Genkit, PublicError diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index f755a9228..c74b1ad88 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -174,7 +174,7 @@ class Genkit: Registers plugins, defines flows and tools, and runs generation. Both ``Genkit(model=...)`` and ``ai.generate(model=...)`` accept a typed ``ModelRef`` from a plugin constructor (recommended, e.g. - ``GoogleAI.gemini_model('gemini-flash-latest')``) or a plugin-prefixed + ``GoogleAI.gemini('gemini-flash-latest')``) or a plugin-prefixed string (``'googleai/gemini-flash-latest'``). Plugins resolve models lazily on demand when ``ai.generate()`` is called, without needing pre-registration or SDK updates. @@ -232,7 +232,7 @@ def __init__( # noqa: D417 plugins: Plugins to register (e.g. ``[GoogleAI()]``). Plugins resolve models lazily on demand when ``ai.generate()`` is called. model: Default model for ``ai.generate()``. Accepts a typed ``ModelRef`` - (recommended, e.g. ``GoogleAI.gemini_model('gemini-flash-latest')``) or + (recommended, e.g. ``GoogleAI.gemini('gemini-flash-latest')``) or a plugin-prefixed string (``'googleai/gemini-flash-latest'``). prompt_dir: Optional directory for loading ``.prompt`` files. """ @@ -402,7 +402,37 @@ async def streaming_flow(x: int, ctx: FlowContext[str]) -> str: return _FlowDecorator(self._registry, name, description) def define_helper(self, name: str, fn: Callable[..., Any]) -> None: - """Register a Handlebars helper function.""" + """Register a Handlebars helper for prompt templates. + + Dotprompt calls the helper as ``fn(params, options)``: ``params`` is a + list of the positional arguments from the template, and ``options`` + carries the named arguments in ``options.hash``. A one-argument + function such as ``lambda s: s.upper()`` raises ``TypeError`` at + render time. Return a ``str``. + + Example: + ```python + # 1. Register a helper that takes one positional and one named argument + def menu_item(params: list[Any], options: Any) -> str: + dish = str(params[0]) + return dish.upper() if options.hash.get('loud') else dish + + + ai.define_helper('menu_item', menu_item) + + # 2. Use it in a prompt template + special = ai.define_prompt( + name='special', + model='googleai/gemini-flash-latest', + prompt="Describe today's special, {{menu_item dish loud=true}}, in one line.", + ) + + # 3. Render to check the expanded text + request = await special.render(input={'dish': 'smoked salmon tartine'}) + print(request.messages[0].content[0].text) + # => Describe today's special, SMOKED SALMON TARTINE, in one line. + ``` + """ define_helper(self._registry, name, fn) def define_partial(self, name: str, source: str) -> None: @@ -1237,7 +1267,9 @@ def _initialize_registry(self, model: ModelArg | None, plugins: list[Plugin] | N if isinstance(plugin, Plugin): # pyright: ignore[reportUnnecessaryIsInstance] self._registry.register_plugin(plugin) else: - raise ValueError(f'Invalid {plugin=} provided to Genkit: must be of type `genkit.ai.Plugin`') + raise ValueError( + f'Invalid {plugin=} provided to Genkit: must be of type `genkit.plugin_api.Plugin`' + ) def _register_plugin_middleware(self, plugins: list[Plugin] | None) -> None: """Register middleware classes returned by ``Plugin.list_middleware``.""" @@ -1555,7 +1587,7 @@ async def generate( """Generate text or structured data using a language model. ``model`` accepts a typed ``ModelRef`` from a plugin constructor - (recommended, e.g. ``GoogleAI.gemini_model('gemini-flash-latest')``, + (recommended, e.g. ``GoogleAI.gemini('gemini-flash-latest')``, which takes the bare model ID, stamps the ``'googleai/'`` namespace prefix, and type-checks ``config``), a plugin-prefixed string (``'googleai/gemini-flash-latest'``), a registered model ``Action``, or @@ -1779,11 +1811,26 @@ def generate_stream( ``raise_on_error=True`` the ``async for`` raises that error after the chunks already sent, and so does ``await result.response``. + Use ``async with result.stream as stream:`` so that leaving the loop + early (``break``, an exception, a disconnected client) closes the + stream and stops the model call. + Example: + ```python + # 1. Start streaming result = ai.generate_stream(prompt='Write a haiku about rain.') - async for chunk in result.stream: - print(chunk.text) + + # 2. Print chunks as they arrive; the context manager closes the stream + async with result.stream as stream: + async for chunk in stream: + print(chunk.text, end='') + # => Soft rain on the roof... + + # 3. Await the final response final = await result.response + print(final.finish_reason) + # => stop + ``` """ initial_msgs: list[Message] = [] if not isinstance(messages, str): diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index a6d9a9525..5dc7467e3 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -29,7 +29,7 @@ from dataclasses import dataclass from typing import Any, TypeVar, cast -from pydantic import BaseModel, ValidationError +from pydantic import ValidationError from genkit._ai import _aio from genkit._ai._background_model import ensure_model_operation @@ -1032,7 +1032,7 @@ def __init__( self, message_index: int, formatter: FormatHandler[Any, Any] | None, - schema_type: type[BaseModel] | None = None, + schema_type: Any = None, # noqa: ANN401 ) -> None: self.message_index = message_index self.formatter = formatter @@ -1960,7 +1960,7 @@ def check_handoff(params: ModelHookParams, mw: MiddlewareDef) -> None: parse = formatter.parse_message response._message_parser = lambda msg: parse(msg) schema_type = options.output.schema_type if options.output else None - if schema_type: + if schema_type is not None: response._schema_type = schema_type return response @@ -2176,7 +2176,7 @@ def stamp_output( if formatter and response._message_parser is None: parse = formatter.parse_message response._message_parser = lambda msg: parse(msg) - if out and out.schema_type: + if out and out.schema_type is not None: response._schema_type = out.schema_type response._assert_valid_schema() return response diff --git a/packages/genkit/src/genkit/_ai/_prompt.py b/packages/genkit/src/genkit/_ai/_prompt.py index aab6e80db..d0a6ae70b 100644 --- a/packages/genkit/src/genkit/_ai/_prompt.py +++ b/packages/genkit/src/genkit/_ai/_prompt.py @@ -221,7 +221,9 @@ class GenerateCall(BaseModel): metadata: dict[str, Any] | None = None # OutputSettings: the type that comes back. Fixed so Prompt[In, Out] holds. - output_schema: type | dict[str, Any] | str | None = None + # Any type form pydantic validates (list[T], Literal, Annotated, ...), a + # JSON schema dict, or a registered name; not `type`, which rejects aliases. + output_schema: Any = None output_format: str | None = None output_content_type: str | None = None output_instructions: bool | str | None = None @@ -343,11 +345,11 @@ async def _ensure_resolved(self) -> None: return resolved = await lookup_prompt(self._ai._registry, self._name, self._variant) - # Keep a Pydantic output type the caller passed: it wins over the file's - # dict schema or registered name, and the type is what gives typed output. + # Keep an output type the caller passed: it wins over the file's dict + # schema or registered name, and the type is what gives typed output. keep: dict[str, Any] = {} schema = self._def.output_schema - if isinstance(schema, type) and issubclass(schema, BaseModel): + if schema is not None and not isinstance(schema, (dict, str)): keep['output_schema'] = schema original_input = self._def.input_schema if original_input is not None: @@ -766,12 +768,13 @@ def resolve_output_schema( Handles three types of output_schema: - str: Schema name - look up JSON schema and type from registry - - Pydantic type: Store both JSON schema and type for runtime validation - dict: Raw JSON schema - convert directly + - Any other type (model, list[T], dataclass, Enum, ...): store both JSON + schema and type; the type hydrates ``.output`` through a TypeAdapter Args: registry: The registry to use for schema lookups. - output_schema: The schema to resolve (string name, Pydantic type, or dict). + output_schema: The schema to resolve (string name, Python type, or dict). output: The output config to populate with json_schema and schema_type. """ if output_schema is None: @@ -786,13 +789,11 @@ def resolve_output_schema( schema_type = registry.lookup_schema_type(output_schema) if schema_type: output.schema_type = schema_type - elif isinstance(output_schema, type) and issubclass(output_schema, BaseModel): - # Pydantic type - store both JSON schema and type + elif isinstance(output_schema, dict): output.json_schema = to_json_schema(output_schema) - output.schema_type = output_schema else: - # dict (raw JSON schema) output.json_schema = to_json_schema(output_schema) + output.schema_type = output_schema async def to_generate_options( diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index 4a2c2cc9f..8a793e3fa 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -35,7 +35,6 @@ Field, GetJsonSchemaHandler, PrivateAttr, - RootModel, ValidationError, ValidationInfo, field_validator, @@ -54,8 +53,8 @@ from genkit._core._extract_json import extract_json, extract_partial_json, is_complete_json from genkit._core._logger import get_logger from genkit._core._operation import Operation -from genkit._core._partial import construct_partial -from genkit._core._schema import parse_schema +from genkit._core._partial import hydrate_partial +from genkit._core._schema import output_adapter, parse_schema from genkit._core._typing import ( AgentFinishReason, Artifact as ArtifactData, @@ -1500,7 +1499,8 @@ class ModelResponse(GenkitModel, Generic[OutputT]): # _message_parser and _schema_type are set by the framework after construction # when output format parsing or schema validation is needed. _message_parser: Callable[[Message], object] | None = PrivateAttr(None) - _schema_type: type[BaseModel] | None = PrivateAttr(None) + # The output_schema type: a model, list[T], dataclass, Enum, Decimal, ... + _schema_type: Any = PrivateAttr(None) _failure: BoxedFailure | None = PrivateAttr(None) # Wire fields (must be declared for extra='forbid' to accept wire responses) message: Message | None = None @@ -1642,17 +1642,26 @@ def _assert_valid_schema(self) -> None: self._mark_invalid_output(error.message) return - # A custom format's parser can return a scalar (e.g. enum string). - # Skip Pydantic model validation for scalars. - is_custom_scalar = self._message_parser is not None and not isinstance(parsed, (dict, list)) - if is_custom_scalar or self._schema_type is None: + if self._keeps_raw(parsed): return try: - _ = self._schema_type.model_validate(parsed) + _ = output_adapter(self._schema_type).validate_python(parsed) except ValidationError: self._mark_invalid_output('Model output did not match the requested schema.') + def _keeps_raw(self, parsed: object) -> bool: + """Whether ``parsed`` is returned as-is instead of validated into the schema type.""" + if self._schema_type is None or parsed is None: + return True + # A custom format's parser can return a scalar (e.g. an enum string) + # that a model class can't take. + return ( + self._message_parser is not None + and _is_model_class(self._schema_type) + and not isinstance(parsed, (dict, list)) + ) + def _raw_parsed_output(self) -> object: if self._message_parser and self.message is not None: return self._message_parser(self.message) @@ -1684,14 +1693,28 @@ def text(self) -> str: return self.message.text @property - def output(self) -> OutputT | None: - """Parsed structured output, or None when the reply is not that shape. - - generate() does not throw when the text is not the schema. If you - asked for a schema and this is not it, read ``error`` / ``.text``. - Only complete JSON counts: a reply cut off mid-object is None (check - ``finish_reason == 'length'`` to tell a token cap from bad JSON). + def output(self) -> OutputT: + """Parsed structured output, typed as the ``output_schema`` you passed. + + With ``output_schema=Recipe`` this types as ``Recipe``, not + ``Recipe | None``, so the happy path needs no guard. With no schema, + or a JSON-schema dict, it types as ``Any``. + + It's still ``None`` at runtime when the reply carries no output, which + the static type does not model: + - A failed turn, or a reply that doesn't match the schema: ``error`` + is set and ``.text`` holds the raw reply. + - ``finish_reason`` is ``interrupted`` (check ``interrupts``), + ``blocked``, ``other``, or ``aborted`` (a stream you stopped). + - A reply cut off mid-object: only complete JSON counts (check + ``finish_reason == 'length'`` to tell a token cap from bad JSON). """ + # One cast at the boundary: the value comes from the parser and the + # runtime schema type, which a type checker can't follow. + return cast(OutputT, self._parse_output()) + + def _parse_output(self) -> object: + """The parsed output, or None when the reply is not the requested shape.""" # BLOCKED and FAILED carry no legitimate content at all, so there is # nothing to hand back even when the caller only asked for a format. # The rest of ABNORMAL_FINISH_REASONS can still hold usable parts (an @@ -1717,14 +1740,11 @@ def output(self) -> OutputT | None: except GenkitError: return None - # A custom format's parser can return a scalar (e.g. enum string). - # Skip Pydantic model validation for scalars. - is_custom_scalar = self._message_parser is not None and not isinstance(parsed, (dict, list)) - if is_custom_scalar or self._schema_type is None or parsed is None: - return cast(OutputT, parsed) + if self._keeps_raw(parsed): + return parsed try: - return cast(OutputT, self._schema_type.model_validate(parsed)) + return output_adapter(self._schema_type).validate_python(parsed) except ValidationError: return None @@ -1778,7 +1798,7 @@ class ModelResponseChunk(GenkitModel, Generic[OutputT]): # construction so the constructor a plugin types is just the wire fields. _previous_chunks: list[Any] = PrivateAttr(default_factory=list) _chunk_parser: Callable[..., object] | None = PrivateAttr(default=None) - _schema_type: type[BaseModel] | None = PrivateAttr(default=None) + _schema_type: Any = PrivateAttr(default=None) @field_validator('content', mode='before') @classmethod @@ -1818,7 +1838,7 @@ def tool_responses(self) -> list[Part]: """All tool response parts in this chunk.""" return [p for p in self.content if p.tool_response is not None] - @cached_property + @property def output(self) -> OutputT | None: """The reply so far, parsed as far as it goes. Never raises. @@ -1836,32 +1856,40 @@ def output(self) -> OutputT | None: stay at ``None`` (or their default) until closed. Open numbers still pass through raw for ``datetime`` fields and for numeric ``Literal`` values that already match a member (even if more digits may follow). + - Once the JSON is complete the value is validated like the final + response; if that fails, this is ``None``. + + Other schema types hydrate the same way: ``list[Recipe]`` is a list of + ``Recipe``, an ``Enum`` is a member once the value is whole. A + dataclass or ``TypedDict`` stays a dict until the JSON closes. ``(await stream.response).output`` is the only fully validated ``Recipe``. + The partial is built without validation, so a required ``title: str`` + can read ``None`` here even though the type says ``str``. Guard each + field before you use it: ``if chunk.output and chunk.output.title:``. With no schema class, this is the JSON value so far (dict, list, or scalar). It's ``None`` before an object starts or while the text can't be parsed. + + Unlike ``ModelResponse.output`` this stays ``OutputT | None``: early + chunks routinely have nothing to parse yet. """ + # Plain property over a cached helper: some checkers (ty) drop the + # class type parameter from a cached_property's return type. + return cast('OutputT | None', self._partial_output) + + @cached_property + def _partial_output(self) -> object: + """Parsed once per chunk; ``.output`` adds the static type.""" if self.role is not None and self.role != Role.MODEL: return None try: text = self.accumulated_text parsed = self._chunk_parser(self) if self._chunk_parser else extract_partial_json(text) - if ( - self._schema_type is not None - and isinstance(parsed, dict) - and not issubclass(self._schema_type, RootModel) - ): - return cast( - 'OutputT | None', - construct_partial( - schema_type=self._schema_type, - data=parsed, - closed=is_complete_json(text), - ), - ) - return cast('OutputT | None', parsed) + if self._schema_type is None: + return parsed + return hydrate_partial(schema=self._schema_type, data=parsed, closed=is_complete_json(text)) except Exception: # one odd chunk shouldn't end a stream whose final reply may still parse. logger.debug('chunk.output could not be parsed; returning None', exc_info=True) @@ -1885,7 +1913,7 @@ def chunk_for_stream( index: float | None = None, previous_chunks: list[Any] | None = None, chunk_parser: Callable[..., object] | None = None, - schema_type: type[BaseModel] | None = None, + schema_type: Any = None, # noqa: ANN401 ) -> ModelResponseChunk[OutputT]: """Copy a plugin chunk and stamp stream index / parser on the copy. diff --git a/packages/genkit/src/genkit/_core/_partial.py b/packages/genkit/src/genkit/_core/_partial.py index 3d62b952e..ce8bfa73b 100644 --- a/packages/genkit/src/genkit/_core/_partial.py +++ b/packages/genkit/src/genkit/_core/_partial.py @@ -34,10 +34,12 @@ from types import UnionType from typing import Annotated, Any, ForwardRef, Literal, TypeGuard, Union, cast, get_args, get_origin, get_type_hints -from pydantic import AliasChoices, BaseModel, Discriminator, RootModel, TypeAdapter +from pydantic import AliasChoices, BaseModel, Discriminator, RootModel, TypeAdapter, ValidationError from pydantic.fields import FieldInfo from pydantic_core import SchemaValidator, core_schema +from genkit._core._schema import output_adapter + SEQUENCE_ORIGINS = (list, tuple, Sequence, MutableSequence) MAPPING_ORIGINS = (dict, Mapping, MutableMapping) UNION_ORIGINS = (Union, UnionType) @@ -98,7 +100,7 @@ def extract_discriminator(*, annotation: Any, info: FieldInfo | None = None) -> return None -def lookup_name(*, name: str, schema_type: type[BaseModel]) -> type[BaseModel] | None: +def lookup_name(*, name: str, schema_type: type) -> type[BaseModel] | None: # list['Post'] stores the name they wrote, not the class. The class # lives next to the schema on its module, or is the schema itself. if name == schema_type.__name__ and is_model(schema_type): @@ -108,7 +110,7 @@ def lookup_name(*, name: str, schema_type: type[BaseModel]) -> type[BaseModel] | return obj if is_model(obj) else None -def resolve(*, annotation: Any, schema_type: type[BaseModel]) -> Any: # noqa: ANN401 +def resolve(*, annotation: Any, schema_type: type) -> Any: # noqa: ANN401 annotation = unwrap_annotated(annotation=annotation) if isinstance(annotation, ForwardRef): annotation = annotation.__forward_arg__ @@ -118,7 +120,7 @@ def resolve(*, annotation: Any, schema_type: type[BaseModel]) -> Any: # noqa: A return annotation -def union_members(*, annotation: Any, schema_type: type[BaseModel]) -> tuple[Any, ...]: # noqa: ANN401 +def union_members(*, annotation: Any, schema_type: type) -> tuple[Any, ...]: # noqa: ANN401 annotation = resolve(annotation=annotation, schema_type=schema_type) origin = get_origin(annotation) if origin in UNION_ORIGINS: @@ -129,7 +131,7 @@ def union_members(*, annotation: Any, schema_type: type[BaseModel]) -> tuple[Any return (annotation,) -def unwrap_optional_container(*, annotation: Any, schema_type: type[BaseModel]) -> Any: # noqa: ANN401 +def unwrap_optional_container(*, annotation: Any, schema_type: type) -> Any: # noqa: ANN401 annotation = resolve(annotation=annotation, schema_type=schema_type) if get_origin(annotation) in UNION_ORIGINS: non_none = [ @@ -253,7 +255,7 @@ def overlap(*, schema_type: type[BaseModel], data: dict[str, Any]) -> int: return len(keys & data.keys()) -def pick_model(*, annotation: Any, data: dict[str, Any], schema_type: type[BaseModel]) -> type[BaseModel] | None: # noqa: ANN401 +def pick_model(*, annotation: Any, data: dict[str, Any], schema_type: type) -> type[BaseModel] | None: # noqa: ANN401 candidates = [ member for member in union_members(annotation=annotation, schema_type=schema_type) if is_model(member) ] @@ -269,7 +271,7 @@ def _cached_adapter(annotation: Any, module_name: str) -> TypeAdapter[Any]: # n return TypeAdapter(annotation, module=module_name) -def validate_closed_value(*, annotation: Any, raw: Any, schema_type: type[BaseModel]) -> tuple[Any, bool]: # noqa: ANN401 +def validate_closed_value(*, annotation: Any, raw: Any, schema_type: type) -> tuple[Any, bool]: # noqa: ANN401 try: try: adapter = _cached_adapter(annotation, schema_type.__module__) @@ -363,7 +365,7 @@ def validate_closed_field( return None, False -def accepts_open_scalar(*, annotation: Any, raw: Any, schema_type: type[BaseModel]) -> bool: # noqa: ANN401 +def accepts_open_scalar(*, annotation: Any, raw: Any, schema_type: type) -> bool: # noqa: ANN401 members = [m for m in union_members(annotation=annotation, schema_type=schema_type) if m is not type(None)] if not members or any(m in (Any, object) for m in members): return True @@ -384,7 +386,7 @@ def coerce( *, annotation: Any, # noqa: ANN401 raw: Any, # noqa: ANN401 - schema_type: type[BaseModel], + schema_type: type, closed: bool = False, discriminator: str | object | None = None, ) -> Any: # noqa: ANN401 @@ -411,7 +413,7 @@ def coerce( if handled: if matched is None: return _UNRESOLVED - return construct_partial(schema_type=matched, data=raw, closed=closed) + return build_partial(schema_type=matched, data=raw, closed=closed) if closed: validated, ok = validate_closed_value(annotation=annotation, raw=raw, schema_type=schema_type) @@ -422,7 +424,7 @@ def coerce( if isinstance(raw, dict): model = pick_model(annotation=annotation, data=raw, schema_type=schema_type) if model is not None: - return construct_partial(schema_type=model, data=raw, closed=closed) + return build_partial(schema_type=model, data=raw, closed=closed) origin = get_origin(container_annotation) if origin in MAPPING_ORIGINS: args = get_args(container_annotation) @@ -476,10 +478,20 @@ def construct_partial(*, schema_type: type[BaseModel], data: dict[str, Any], clo and missing required fields are ``None``. Keys and list items before the trailing open frontier run field validation (``@field_validator`` and field constraints, while ``@model_validator`` waits until the object itself - closes); closed values that fail validation fall back to - ``model_construct`` / raw values. ``(await stream.response).output`` - remains the only fully validated value. + closes); nested closed values that fail validation fall back to + ``model_construct`` / raw values. + + With ``closed=True`` the whole object is done, so it is validated like the + final response and a ``ValidationError`` propagates: the closing chunk + never carries an object that skipped validators. """ + if closed: + return schema_type.model_validate(data) + return build_partial(schema_type=schema_type, data=data, closed=False) + + +def build_partial(*, schema_type: type[BaseModel], data: dict[str, Any], closed: bool) -> BaseModel: + """``construct_partial`` for a nested object: a closed one that fails validation is still built.""" if closed: with suppress(Exception): return schema_type.model_validate(data) @@ -516,3 +528,59 @@ def construct_partial(*, schema_type: type[BaseModel], data: dict[str, Any], clo ) values[name] = default_value(info=info, validated_data=values) if coerced is _UNRESOLVED else coerced return schema_type.model_construct(**values) + + +def _is_root_model(annotation: Any) -> TypeGuard[type[RootModel[Any]]]: # noqa: ANN401 + try: + return isinstance(annotation, type) and issubclass(annotation, RootModel) + except TypeError: # list[int] passes isinstance(_, type) on 3.10 + return False + + +def anchor_type(annotation: Any) -> type: # noqa: ANN401 + """The first user class inside ``annotation``; its module resolves string forward refs.""" + pending: list[Any] = [annotation] + while pending: + current = pending.pop(0) + if isinstance(current, type) and get_origin(current) is None and current.__module__ != 'builtins': + return current + pending.extend(get_args(current)) + return object + + +def hydrate_partial(*, schema: Any, data: Any, closed: bool) -> Any: # noqa: ANN401 + """Turn a streamed JSON value into ``schema`` as far as it goes. + + ``schema`` is any ``output_schema`` type. With ``closed=True`` the JSON is + complete, so the value is validated like the final response and a + ``ValidationError`` propagates. An open value is built leniently: models + through ``construct_partial``, lists and dicts item by item. A scalar + that can't be used yet (a prefix of an ``Enum`` value) is ``None``. A + dataclass or ``TypedDict`` has no partial form and stays raw JSON until + the value closes. + """ + if data is None: + return None + # A model class only takes an object; anything else (a custom format's + # scalar) passes through as parsed. + if is_model(schema) and not isinstance(data, dict): + return data + if closed: + return output_adapter(schema).validate_python(data) + if _is_root_model(schema): + info = schema.model_fields['root'] + root = coerce( + annotation=field_annotation(schema_type=schema, name='root', info=info), + raw=data, + schema_type=schema, + ) + return None if root is _UNRESOLVED else schema.model_construct(root=root) + value = coerce(annotation=schema, raw=data, schema_type=anchor_type(schema)) + if value is not _UNRESOLVED: + return value + # An open scalar the walker can't use may already be a whole value, e.g. + # the enum format's unquoted 'ESCALATE'. + try: + return output_adapter(schema).validate_python(data) + except ValidationError: + return None diff --git a/packages/genkit/src/genkit/_core/_schema.py b/packages/genkit/src/genkit/_core/_schema.py index f23df6c76..270fa117e 100644 --- a/packages/genkit/src/genkit/_core/_schema.py +++ b/packages/genkit/src/genkit/_core/_schema.py @@ -92,6 +92,25 @@ def fixed_json_schema(cls: type) -> dict[str, Any]: return copy.deepcopy(_generated_schema(cls)) +@functools.lru_cache(maxsize=512) +def _cached_output_adapter(schema_type: Any) -> TypeAdapter[Any]: # noqa: ANN401 + return TypeAdapter(schema_type) + + +def output_adapter(schema_type: Any) -> TypeAdapter[Any]: # noqa: ANN401 + """The ``TypeAdapter`` that turns parsed JSON into an ``output_schema`` value. + + Works for any type pydantic validates: a model, ``list[T]``, ``dict``, + ``Literal``, ``Annotated``, a dataclass, ``TypedDict``, ``Enum``, + ``Decimal``, ``UUID``, ``datetime``. Built once per type; an annotation + whose metadata isn't hashable gets a fresh adapter each call. + """ + try: + return _cached_output_adapter(schema_type) + except TypeError: + return TypeAdapter(schema_type) + + def check_output_schema(json_schema: dict[str, Any]) -> None: """Raise if ``json_schema`` is not itself a JSON Schema. diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index 7bffd5fe0..615fea9a5 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -264,6 +264,20 @@ async def list_allergies(guest: str, ctx: ToolContext) -> str: await list_allergies('Ana', context={'auth': {'uid': 'diner-42'}}) # => 'Ana (diner-42): shellfish' + + On a restart after an interrupt, ``is_resumed()`` is ``True`` and + ``resumed_metadata`` is the dict passed to + ``interrupt.restart(resumed_metadata=...)``, or ``{}`` when the restart + carried none. On a first run, ``resumed_metadata`` is ``None``. Check + ``is_resumed()`` to branch, and read keys from ``resumed_metadata``: + + @ai.tool() + async def refund_order(order_id: str, ctx: ToolContext) -> str: + # Interrupt is exported from genkit + if not ctx.is_resumed(): + raise Interrupt({'reason': 'needs approval'}) + approved = ctx.resumed_metadata.get('approved_by') + return f'Refunded {order_id} (approved by {approved})' """ def __init__( @@ -288,7 +302,11 @@ def __init__( self.original_input = original_input def is_resumed(self) -> bool: - """Return True if this execution is resuming after an interrupt.""" + """Return True if this run is a restart after an interrupt. + + Same as ``self.resumed_metadata is not None``. An empty ``{}`` still + counts as resumed. + """ return self.resumed_metadata is not None diff --git a/packages/genkit/tests/genkit/ai/generate_test.py b/packages/genkit/tests/genkit/ai/generate_test.py index 3aad4b4fc..1f5feb434 100644 --- a/packages/genkit/tests/genkit/ai/generate_test.py +++ b/packages/genkit/tests/genkit/ai/generate_test.py @@ -8586,11 +8586,12 @@ class Recipe(BaseModel): @pytest.mark.asyncio -async def test_model_response_output_is_typed_optional() -> None: - """ai.generate(output_schema=City).output is typed City | None. +async def test_model_response_output_is_typed_as_schema() -> None: + """ai.generate(output_schema=City).output is typed City, not City | None. - assert_type is a no-op at runtime; the ty CI job enforces it. The runtime - INVALID_OUTPUT / output is None behavior is covered by the INVALID_OUTPUT tests. + assert_type is a no-op at runtime; the ty CI job enforces it. A reply that + isn't a City is still None at runtime with INVALID_OUTPUT set; the type + doesn't model that (see tests/typecheck/output_narrowing_contract_test.py). """ class City(BaseModel): @@ -8608,7 +8609,9 @@ class City(BaseModel): response = await ai.generate(prompt='a city', output_schema=City, raise_on_error=False) - assert_type(response.output, City | None) + assert_type(response.output, City) + assert response.output is None + assert response.error is not None @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/ai/genkit_api_test.py b/packages/genkit/tests/genkit/ai/genkit_api_test.py index 03f9a1c85..a7b42d2c9 100644 --- a/packages/genkit/tests/genkit/ai/genkit_api_test.py +++ b/packages/genkit/tests/genkit/ai/genkit_api_test.py @@ -646,4 +646,4 @@ def test_genkit_init_has_docstring() -> None: assert 'plugins:' in doc assert 'model:' in doc assert 'prompt_dir:' in doc - assert 'GoogleAI.gemini_model' in doc + assert "GoogleAI.gemini('gemini-flash-latest')" in doc diff --git a/packages/genkit/tests/genkit/ai/output_hydration_test.py b/packages/genkit/tests/genkit/ai/output_hydration_test.py new file mode 100644 index 000000000..032a25be1 --- /dev/null +++ b/packages/genkit/tests/genkit/ai/output_hydration_test.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +# +# Copyright 2026 Google LLC +# SPDX-License-Identifier: Apache-2.0 + +"""output_schema hydrates every type pydantic validates, not just BaseModel. + +``ai.generate(output_schema=T)`` types ``.output`` as ``T``; these tests pin +that runtime returns a ``T`` too, for responses, stream chunks, and prompts. +""" + +import dataclasses +import datetime +import enum +import uuid +from decimal import Decimal +from typing import Annotated, Any, Literal + +import pytest +from pydantic import BaseModel, Field, RootModel, ValidationError, field_validator +from pydantic.dataclasses import dataclass as pydantic_dataclass +from typing_extensions import TypedDict + +from genkit import Genkit, Message, ModelResponse, ModelResponseChunk, Part +from genkit._core._partial import construct_partial, hydrate_partial +from genkit._core._typing import Role +from genkit.testing import define_scripted_model + + +class InvoiceItem(BaseModel): + sku: str + quantity: int + + +class InvoiceList(RootModel[list[InvoiceItem]]): + pass + + +@dataclasses.dataclass +class Vendor: + vendor_name: str + risk_score: int + + +@pydantic_dataclass +class PydanticVendor: + vendor_name: str + risk_score: int + + +class VendorDict(TypedDict): + vendor_name: str + risk_score: int + + +class Triage(enum.Enum): + APPROVE = 'APPROVE' + ESCALATE = 'ESCALATE' + + +class TriageStr(str, enum.Enum): # noqa: UP042 # enum.StrEnum is 3.11+ + APPROVE = 'APPROVE' + ESCALATE = 'ESCALATE' + + +class Pickup(BaseModel): + pickup_time: str + + +class Delivery(BaseModel): + address: str + + +@dataclasses.dataclass +class Contact: + vendor: Vendor + emails: list[str] + + +class PurchaseOrder(BaseModel): + lines: list[VendorDict] + contact: Contact | None = None + + +def _ai_with_reply(text: str, chunks: list[str] | None = None) -> Genkit: + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text(text)]))] + if chunks is not None: + pm.chunks = [[ModelResponseChunk(role=Role.MODEL, content=[Part.from_text(c)]) for c in chunks]] + return ai + + +VENDOR_JSON = '{"vendor_name": "Acme", "risk_score": 12}' +UID = '550e8400-e29b-41d4-a716-446655440000' + +CASES: list[tuple[str, Any, str, Any]] = [ + ('list_of_models', list[InvoiceItem], '[{"sku": "CH-1", "quantity": 2}]', [InvoiceItem(sku='CH-1', quantity=2)]), + ('root_model', InvoiceList, '[{"sku": "CH-1", "quantity": 2}]', InvoiceList([InvoiceItem(sku='CH-1', quantity=2)])), + ('dict', dict[str, int], '{"a": 1}', {'a': 1}), + ('literal', Literal['APPROVE', 'ESCALATE'], '"ESCALATE"', 'ESCALATE'), + ('annotated', Annotated[int, Field(gt=0)], '7', 7), + ('dataclass', Vendor, VENDOR_JSON, Vendor(vendor_name='Acme', risk_score=12)), + ('pydantic_dataclass', PydanticVendor, VENDOR_JSON, PydanticVendor(vendor_name='Acme', risk_score=12)), + ('typed_dict', VendorDict, VENDOR_JSON, {'vendor_name': 'Acme', 'risk_score': 12}), + ('enum', Triage, '"ESCALATE"', Triage.ESCALATE), + ('str_enum', TriageStr, '"ESCALATE"', TriageStr.ESCALATE), + ('decimal', Decimal, '14250.75', Decimal('14250.75')), + ('uuid', uuid.UUID, f'"{UID}"', uuid.UUID(UID)), + ( + 'datetime', + datetime.datetime, + '"2026-10-15T14:30:00Z"', + datetime.datetime(2026, 10, 15, 14, 30, tzinfo=datetime.timezone.utc), + ), + ('optional_model', InvoiceItem | None, '{"sku": "CH-1", "quantity": 2}', InvoiceItem(sku='CH-1', quantity=2)), + ('union_of_models', Pickup | Delivery, '{"address": "1 Main St"}', Delivery(address='1 Main St')), + ( + 'nested_dataclass', + Contact, + f'{{"vendor": {VENDOR_JSON}, "emails": ["ap@acme.test"]}}', + Contact(vendor=Vendor(vendor_name='Acme', risk_score=12), emails=['ap@acme.test']), + ), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize(('schema', 'reply', 'expected'), [c[1:] for c in CASES], ids=[c[0] for c in CASES]) +async def test_generate_hydrates_output_schema(schema: Any, reply: str, expected: Any) -> None: # noqa: ANN401 + response = await _ai_with_reply(reply).generate(prompt='hi', output_schema=schema) + + assert response.error is None + assert response.output == expected + assert type(response.output) is type(expected) + + +@pytest.mark.asyncio +async def test_decimal_keeps_its_lexeme() -> None: + response = await _ai_with_reply('{"amount": 0.1}').generate(prompt='hi', output_schema=dict[str, Decimal]) + + assert response.output == {'amount': Decimal('0.1')} + + +@pytest.mark.asyncio +async def test_wrong_shape_is_invalid_output_for_non_model_schema() -> None: + response = await _ai_with_reply('[{"sku": "CH-1"}]').generate( + prompt='hi', output_schema=list[InvoiceItem], raise_on_error=False + ) + + assert response.output is None + assert response.error is not None + assert response.error.details == {'reason': 'INVALID_OUTPUT'} + + +@pytest.mark.asyncio +async def test_enum_format_returns_member() -> None: + response = await _ai_with_reply('ESCALATE').generate(prompt='hi', output_schema=TriageStr, output_format='enum') + + assert response.output is TriageStr.ESCALATE + + +@pytest.mark.asyncio +async def test_array_format_with_list_schema_hydrates_chunks_and_response() -> None: + ai = _ai_with_reply( + '[{"sku": "CH-1", "quantity": 2}, {"sku": "DK-2", "quantity": 5}]', + chunks=['[{"sku": "CH-1", "quantity": 2}, ', '{"sku": "DK-2", "quantity": 5}]'], + ) + stream = ai.generate_stream(prompt='hi', output_schema=list[InvoiceItem], output_format='array') + outputs = [chunk.output async for chunk in stream.stream] + response = await stream.response + + assert outputs == [[InvoiceItem(sku='CH-1', quantity=2)], [InvoiceItem(sku='DK-2', quantity=5)]] + assert response.output == [InvoiceItem(sku='CH-1', quantity=2), InvoiceItem(sku='DK-2', quantity=5)] + + +@pytest.mark.asyncio +async def test_stream_model_with_nested_dataclass_and_typed_dict() -> None: + reply = f'{{"lines": [{VENDOR_JSON}], "contact": {{"vendor": {VENDOR_JSON}, "emails": []}}}}' + ai = _ai_with_reply(reply, chunks=[reply[:30], reply[30:]]) + stream = ai.generate_stream(prompt='hi', output_schema=PurchaseOrder) + outputs = [chunk.output async for chunk in stream.stream] + + # Open: the model is partial; the open TypedDict line stays a raw dict. + assert isinstance(outputs[0], PurchaseOrder) + assert outputs[0].lines == [{'vendor_name': 'Ac'}] + assert outputs[0].contact is None + # Closed: the nested dataclass is hydrated, same as the final response. + expected = PurchaseOrder( + lines=[{'vendor_name': 'Acme', 'risk_score': 12}], + contact=Contact(vendor=Vendor(vendor_name='Acme', risk_score=12), emails=[]), + ) + assert outputs[1] == expected + assert (await stream.response).output == expected + + +@pytest.mark.asyncio +async def test_stream_chunks_of_list_schema_are_models() -> None: + ai = _ai_with_reply( + '[{"sku": "CH-1", "quantity": 2}]', + chunks=['[{"sku": "CH-1", "qu', 'antity": 2}]'], + ) + stream = ai.generate_stream(prompt='hi', output_schema=list[InvoiceItem]) + outputs = [chunk.output async for chunk in stream.stream] + + # Open: the half-written item is an InvoiceItem with holes. + first = outputs[0] + assert first is not None + assert isinstance(first[0], InvoiceItem) + assert first[0].sku == 'CH-1' + assert first[0].quantity is None + # Closed: validated like the final response. + assert outputs[1] == [InvoiceItem(sku='CH-1', quantity=2)] + assert (await stream.response).output == outputs[1] + + +@pytest.mark.asyncio +async def test_define_prompt_accepts_generic_alias_schema() -> None: + ai = _ai_with_reply('[{"sku": "CH-1", "quantity": 2}]') + prompt = ai.define_prompt(name='invoice', prompt='List items.', output_schema=list[InvoiceItem]) + + response = await prompt() + + assert response.output == [InvoiceItem(sku='CH-1', quantity=2)] + + +@pytest.mark.asyncio +async def test_looked_up_prompt_keeps_caller_generic_alias_schema() -> None: + ai = _ai_with_reply('[{"sku": "CH-1", "quantity": 2}]') + ai.define_prompt(name='invoice', prompt='List items.', output_schema={'type': 'array'}) + + prompt = ai.prompt('invoice', output_schema=list[InvoiceItem]) + response = await prompt() + + assert response.output == [InvoiceItem(sku='CH-1', quantity=2)] + + +class Dish(BaseModel): + name: str + + @field_validator('name') + @classmethod + def _capitalized(cls, v: str) -> str: + if not v[:1].isupper(): + raise ValueError('must be capitalized') + return v + + +def test_construct_partial_closed_raises_instead_of_model_construct() -> None: + with pytest.raises(ValidationError): + construct_partial(schema_type=Dish, data={'name': 'salmon'}, closed=True) + + +def test_construct_partial_open_still_builds() -> None: + out = construct_partial(schema_type=Dish, data={'name': 'salm'}) + + assert isinstance(out, Dish) + assert out.name == 'salm' + + +def test_hydrate_partial_enum_prefix_is_none_until_whole() -> None: + assert hydrate_partial(schema=TriageStr, data='ESC', closed=False) is None + assert hydrate_partial(schema=TriageStr, data='ESCALATE', closed=False) is TriageStr.ESCALATE + + +def test_hydrate_partial_dataclass_stays_raw_until_closed() -> None: + assert hydrate_partial(schema=Vendor, data={'vendor_name': 'Ac'}, closed=False) == {'vendor_name': 'Ac'} + assert hydrate_partial(schema=Vendor, data={'vendor_name': 'Acme', 'risk_score': 1}, closed=True) == Vendor( + vendor_name='Acme', risk_score=1 + ) diff --git a/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py b/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py index 91084696d..27309762f 100644 --- a/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py +++ b/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py @@ -144,12 +144,15 @@ def test_non_dict_parse_result_passes_through(self) -> None: assert _chunk('[1, 2, 3]', schema_type=Recipe).output == [1, 2, 3] def test_wrong_typed_value_does_not_raise(self) -> None: - # Failed validation falls back to the raw value instead of crashing - # the caller's loop; the final response surfaces the ValidationError. - out = _chunk('{"title": 123}', schema_type=Recipe).output + # Mid-stream, a wrong-typed value passes through raw instead of + # crashing the caller's loop. + out = _chunk('{"title": 123', schema_type=Recipe).output assert isinstance(out, Recipe) assert out.title == 123 assert out.steps is None + # The closing chunk is validated like the final response: no + # model_construct that skipped validation, just None. + assert _chunk('{"title": 123}', schema_type=Recipe).output is None def test_camel_case_alias_populates_python_field(self) -> None: class UserProfile(BaseModel): @@ -170,12 +173,14 @@ class User(BaseModel): assert isinstance(out, User) assert out.first_name == 'Ada' - def test_root_model_dict_stays_extracted_json(self) -> None: + def test_root_model_hydrates_like_the_final_response(self) -> None: class DictRoot(RootModel[dict[str, int]]): pass - out = _chunk('{"a": 1, "b": 2}', schema_type=DictRoot).output - assert out == {'a': 1, 'b': 2} + open_out = _chunk('{"a": 1, "b": 2', schema_type=DictRoot).output + assert isinstance(open_out, DictRoot) + assert open_out.root == {'a': 1, 'b': 2} + assert _chunk('{"a": 1, "b": 2}', schema_type=DictRoot).output == DictRoot({'a': 1, 'b': 2}) class TestNestedAndConstrainedOutput: @@ -195,13 +200,15 @@ def _capitalized(cls, v: str) -> str: return v out = _chunk( - '{"servings": -5, "rating": 99, "title": "lowercase"}', + '{"servings": -5, "rating": 99, "title": "lowercase"', schema_type=Strict, ).output assert isinstance(out, Strict) assert out.servings == -5 assert out.rating == 99 assert out.title == 'lowercase' + # Once the object closes, the same values fail validation: None. + assert _chunk('{"servings": -5, "rating": 99, "title": "lowercase"}', schema_type=Strict).output is None def test_union_member_is_the_matching_class(self) -> None: class Cat(BaseModel): @@ -214,7 +221,7 @@ class Dog(BaseModel): class Pet(BaseModel): animal: Cat | Dog - out = _chunk('{"animal": {"bark": "woof"}}', schema_type=Pet).output + out = _chunk('{"animal": {"bark": "woof"}', schema_type=Pet).output assert isinstance(out, Pet) assert isinstance(out.animal, Dog) assert out.animal.bark == 'woof' @@ -234,7 +241,7 @@ class Plan(BaseModel): by_id: Mapping[str, Item] out = _chunk( - '{"steps": [{"title": "mix"}], "by_id": {"a": {"name": "axe"}}}', + '{"steps": [{"title": "mix"}], "by_id": {"a": {"name": "axe"}}', schema_type=Plan, ).output assert isinstance(out, Plan) @@ -255,7 +262,7 @@ class Inventory(BaseModel): featured: tuple[Item, ...] out = _chunk( - '{"by_id": {"a": {"name": "axe"}}, "featured": [{"qty": 2}]}', + '{"by_id": {"a": {"name": "axe"}}, "featured": [{"qty": 2}]', schema_type=Inventory, ).output assert isinstance(out, Inventory) @@ -270,7 +277,7 @@ class Node(BaseModel): child: 'Node | None' = None out = _chunk( - '{"name": "root", "child": {"child": {"name": "leaf"}}}', + '{"name": "root", "child": {"child": {"name": "leaf"}}', schema_type=Node, ).output assert isinstance(out, Node) @@ -283,7 +290,7 @@ class Node(BaseModel): def test_mutually_recursive_models(self) -> None: """A quoted sibling in list['Post'] is a Post, with holes as None.""" out = _chunk( - '{"name": "a", "posts": [{"author": {"posts": []}}]}', + '{"name": "a", "posts": [{"author": {"posts": []}}]', schema_type=Author, ).output assert isinstance(out, Author) @@ -359,7 +366,7 @@ def test_half_arrived_deep_child_name_is_prefix(self) -> None: def test_dict_quoted_post_yields_post_instances(self) -> None: """dict[str, 'QuotedItem'] values are QuotedItem, with holes as None.""" out = _chunk( - '{"by_id": {"a": {"name": "axe"}}, "featured": []}', + '{"by_id": {"a": {"name": "axe"}}, "featured": []', schema_type=QuotedInventory, ).output assert isinstance(out, QuotedInventory) @@ -370,7 +377,7 @@ def test_dict_quoted_post_yields_post_instances(self) -> None: def test_tuple_quoted_post_yields_post_instances(self) -> None: """tuple['QuotedItem', ...] values are QuotedItem, with holes as None.""" out = _chunk( - '{"by_id": {}, "featured": [{"qty": 2}]}', + '{"by_id": {}, "featured": [{"qty": 2}]', schema_type=QuotedInventory, ).output assert isinstance(out, QuotedInventory) @@ -381,7 +388,7 @@ def test_tuple_quoted_post_yields_post_instances(self) -> None: def test_list_quoted_self_yields_node_instances(self) -> None: """list['NodeTree'] children are NodeTree, with holes as None.""" out = _chunk( - '{"name": "root", "children": [{"children": [{"name": "leaf"}]}]}', + '{"name": "root", "children": [{"children": [{"name": "leaf"}]}]', schema_type=NodeTree, ).output assert isinstance(out, NodeTree) @@ -394,7 +401,7 @@ def test_list_quoted_self_yields_node_instances(self) -> None: def test_list_quoted_unknown_name_stays_dicts(self) -> None: """A quoted name that is not a model stays extracted JSON; the loop does not crash.""" out = _chunk( - '{"items": [{"name": "x"}]}', + '{"items": [{"name": "x"}]', schema_type=UnknownQuotedList, ).output assert isinstance(out, UnknownQuotedList) @@ -710,9 +717,9 @@ async def test_stream_final_output_is_validated_instance() -> None: @pytest.mark.asyncio async def test_stream_final_output_missing_field_is_none_after_partial_chunks() -> None: - """Chunks showed a Recipe with steps None, but a final reply that never sends steps gives `output is None`.""" + """Open chunks show a Recipe with steps None; a reply that closes without steps is None, chunk and final.""" outputs, response = await _stream_outputs( - ['{"title": "Fluffy Pancakes"}'], + ['{"title": "Fluffy Pancakes"', '}'], '{"title": "Fluffy Pancakes"}', output_schema=Recipe, raise_on_error=False, @@ -720,6 +727,7 @@ async def test_stream_final_output_missing_field_is_none_after_partial_chunks() assert isinstance(outputs[0], Recipe) assert outputs[0].steps is None + assert outputs[1] is None assert response.output is None assert response.error is not None @@ -1073,12 +1081,9 @@ def _after_check(self) -> 'Booking': assert (before_calls, after_calls) == (1, 1) assert b4 == Booking(guest='ANN', nights=2, total=200.0) - # If the closed root violates @model_validator, fallback still preserves @field_validator outputs. + # A closed root that violates @model_validator is None, not an unvalidated Booking. b_invalid = _chunk('{"guest": "ann", "nights": 2, "total": 999.0}', schema_type=Booking).output - assert isinstance(b_invalid, Booking) - assert b_invalid.guest == 'ANN' - assert b_invalid.nights == 2 - assert b_invalid.total == 999.0 + assert b_invalid is None def test_open_numbers_and_invalid_closed_enum_match_documented_edge_cases(self) -> None: class EventPayload(BaseModel): diff --git a/packages/genkit/tests/typecheck/output_narrowing_contract_test.py b/packages/genkit/tests/typecheck/output_narrowing_contract_test.py new file mode 100644 index 000000000..fc88535dc --- /dev/null +++ b/packages/genkit/tests/typecheck/output_narrowing_contract_test.py @@ -0,0 +1,176 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Type-checker contract for ``.output`` narrowing (PR2-15). + +With ``output_schema=T``, ``response.output`` types as ``T``: no ``None`` +guard and no ``cast()`` on the happy path. Stream chunks stay ``T | None`` +because early chunks have nothing to parse. With no schema or a JSON-schema +dict, ``.output`` types as ``Any`` so untyped callers can index it. + +pyright, pyrefly, and ty check this file (see ``[tool.pyright]``); the tests +also run so each static type matches the runtime value. +""" + +from dataclasses import dataclass +from enum import Enum +from typing import Any + +import pytest +from pydantic import BaseModel +from typing_extensions import assert_type + +from genkit import Genkit, Message, ModelResponse, ModelResponseChunk, Part, Role +from genkit.testing import define_scripted_model, define_static_response_model + + +class Order(BaseModel): + dish: str + quantity: int + + +@dataclass +class Allergen: + name: str + + +class Spice(Enum): + MILD = 'mild' + HOT = 'hot' + + +def _scripted(ai: Genkit, text: str, chunks: list[str] | None = None) -> None: + define_scripted_model( + ai, + name='kitchen', + responses=[ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text(text)]))], + chunks=[[ModelResponseChunk(role=Role.MODEL, content=[Part.from_text(c)]) for c in chunks]] if chunks else None, + ) + + +@pytest.mark.asyncio +async def test_generate_output_is_schema_type() -> None: + """``output_schema=Order`` gives ``Order``, usable without a guard.""" + ai = Genkit() + _scripted(ai, '{"dish": "tartine", "quantity": 2}') + + res = await ai.generate(model='kitchen', prompt='order', output_schema=Order) + + assert_type(res, ModelResponse[Order]) + assert_type(res.output, Order) + total: int = res.output.quantity * 3 + assert total == 6 + + +@pytest.mark.asyncio +async def test_generate_output_with_config_dict_is_schema_type() -> None: + """The ``config={...}`` overload narrows the same way.""" + ai = Genkit() + _scripted(ai, '{"dish": "soup", "quantity": 1}') + + res = await ai.generate(model='kitchen', prompt='order', config={'temperature': 0.1}, output_schema=Order) + + assert_type(res.output, Order) + assert res.output.dish == 'soup' + + +@pytest.mark.asyncio +async def test_generate_output_non_model_schemas() -> None: + """``list[T]``, dataclasses, and ``Enum`` narrow to the hydrated type.""" + ai = Genkit() + _, _ = define_static_response_model(ai, '[{"dish": "tartine", "quantity": 1}]', name='orders') + _, _ = define_static_response_model(ai, '{"name": "peanut"}', name='allergen') + _, _ = define_static_response_model(ai, '"hot"', name='spice') + + orders = await ai.generate(model='orders', prompt='x', output_schema=list[Order]) + assert_type(orders.output, list[Order]) + assert orders.output[0].dish == 'tartine' + + allergen = await ai.generate(model='allergen', prompt='x', output_schema=Allergen) + assert_type(allergen.output, Allergen) + assert allergen.output.name == 'peanut' + + spice = await ai.generate(model='spice', prompt='x', output_schema=Spice) + assert_type(spice.output, Spice) + assert spice.output is Spice.HOT + + +@pytest.mark.asyncio +async def test_untyped_output_is_any() -> None: + """No schema or a dict schema types as ``Any``, so indexing type-checks.""" + ai = Genkit() + _, _ = define_static_response_model(ai, '{"dish": "tartine"}', name='menu') + + res = await ai.generate(model='menu', prompt='x') + assert_type(res.output, Any) + + res_dict = await ai.generate(model='menu', prompt='x', output_schema={'type': 'object'}) + assert_type(res_dict.output, Any) + assert res_dict.output['dish'] == 'tartine' + + +@pytest.mark.asyncio +async def test_stream_final_output_narrows_chunks_stay_optional() -> None: + """Chunks are ``Order | None``; the awaited response is ``Order``.""" + ai = Genkit() + _scripted(ai, '{"dish": "tartine", "quantity": 2}', chunks=['{"dish": "tar', 'tine", "quantity": 2}']) + + stream = ai.generate_stream(model='kitchen', prompt='order', output_schema=Order) + seen: list[Order | None] = [] + async for chunk in stream.stream: + assert_type(chunk, ModelResponseChunk[Order]) + assert_type(chunk.output, Order | None) + seen.append(chunk.output) + final = await stream.response + + assert_type(final.output, Order) + assert final.output.quantity == 2 + last = seen[-1] + assert last is not None and last.dish == 'tartine' + + +@pytest.mark.asyncio +async def test_prompt_output_narrows() -> None: + """``define_prompt`` / ``ai.prompt`` with ``output_schema`` narrow on call and stream.""" + ai = Genkit() + _, _ = define_static_response_model(ai, '{"dish": "tartine", "quantity": 2}', name='kitchen') + order_prompt = ai.define_prompt(name='order', model='kitchen', prompt='order', output_schema=Order) + + res = await order_prompt() + assert_type(res.output, Order) + assert res.output.dish == 'tartine' + + looked_up = ai.prompt('order', output_schema=Order) + looked_up_res = await looked_up() + assert_type(looked_up_res.output, Order) + assert looked_up_res.output.quantity == 2 + + stream = order_prompt.stream() + async for chunk in stream.stream: + assert_type(chunk.output, Order | None) + final = await stream.response + assert_type(final.output, Order) + assert final.output.dish == 'tartine' + + +def test_bare_model_response_output_is_object() -> None: + """Unparameterized ``ModelResponse`` defaults ``OutputT`` to ``object``.""" + + def read(res: ModelResponse) -> object: + assert_type(res.output, object) + return res.output + + assert read(ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('hi')]))) is None diff --git a/samples/agents/basic/02_define_agent_no_store.py b/samples/agents/basic/02_define_agent_no_store.py index 127fb5334..ce729148c 100644 --- a/samples/agents/basic/02_define_agent_no_store.py +++ b/samples/agents/basic/02_define_agent_no_store.py @@ -46,6 +46,7 @@ async def main() -> None: # streaming (or abort/timeout handles); awaiting turn.response skips the stream. out = await turn.response assert out.text + print(out.text) # No store means no snapshot to reload. Resume by handing back the # messages / state / artifacts you kept. @@ -56,7 +57,9 @@ async def main() -> None: messages, state, artifacts = chat.messages, chat.state, chat.artifacts resumed = agent.chat(messages=messages, state=state, artifacts=artifacts) - await resumed.send('What is my name? One word.') + reply = await resumed.send('What is my name? One word.') + print(reply.text) + # => Ada if __name__ == '__main__': diff --git a/samples/google-genai-media/README.md b/samples/google-genai-media/README.md index 233345ea9..5de4c1d75 100644 --- a/samples/google-genai-media/README.md +++ b/samples/google-genai-media/README.md @@ -6,6 +6,7 @@ Google AI Studio; video uses Vertex (`VertexAI.veo`). ```bash export GEMINI_API_KEY=your-api-key +export GOOGLE_CLOUD_PROJECT=your-project-id # Veo runs on Vertex AI gcloud auth application-default login uv sync uv run src/main.py diff --git a/samples/middleware/src/main.py b/samples/middleware/src/main.py index 18be059d0..d0f64c34c 100644 --- a/samples/middleware/src/main.py +++ b/samples/middleware/src/main.py @@ -22,14 +22,26 @@ from genkit_google_genai import GoogleAI from pydantic import BaseModel -from genkit import Genkit, ModelResponse, Part -from genkit.middleware import Middleware, MiddlewareContext, ModelHookParams +from genkit import Genkit, Message, ModelResponse, MultipartToolResponse, Part +from genkit.middleware import GenerateHookParams, Middleware, MiddlewareContext, ToolHookParams ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest')) _EMAIL = re.compile(r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}') +def _redact(text: str) -> str: + return _EMAIL.sub('[REDACTED_EMAIL]', text) + + +def _redact_parts(parts: list[Part]) -> list[Part]: + return [Part.from_text(_redact(p.text), metadata=p.metadata) if p.text is not None else p for p in parts] + + +def _redact_message(message: Message) -> Message: + return message.model_copy(update={'content': _redact_parts(message.content)}) + + class PiiRedactConfig(BaseModel): pass @@ -38,36 +50,51 @@ class PiiRedactConfig(BaseModel): class PiiRedact(Middleware[PiiRedactConfig]): name = 'pii_redact' - # The provider sees whatever we put on params.request, including on - # retries. This is the last place a ticket's email can be removed. - async def wrap_model( + # wrap_generate sees the history before Genkit builds the model request + # and response.messages from it, so scrubbing here keeps the email out of + # the provider call and out of the history you store. + async def wrap_generate( self, - params: ModelHookParams, + params: GenerateHookParams, ctx: MiddlewareContext, - next_fn: Callable[[ModelHookParams, MiddlewareContext], Awaitable[ModelResponse]], + next_fn: Callable[[GenerateHookParams, MiddlewareContext], Awaitable[ModelResponse]], ) -> ModelResponse: - new_messages = [] - for message in params.request.messages: - new_parts = [] - for part in message.content: - if part.text is not None: - redacted = _EMAIL.sub('[REDACTED_EMAIL]', part.text) - new_parts.append(Part.from_text(redacted, metadata=part.metadata)) - else: - new_parts.append(part) - new_messages.append(message.model_copy(update={'content': new_parts})) - params.request = params.request.model_copy(update={'messages': new_messages}) + messages = [_redact_message(m) for m in params.options.messages] + params.options = params.options.model_copy(update={'messages': messages}) return await next_fn(params, ctx) + # Tool results go back to the model on the next turn; scrub them too. + async def wrap_tool( + self, + params: ToolHookParams, + ctx: MiddlewareContext, + next_fn: Callable[[ToolHookParams, MiddlewareContext], Awaitable[MultipartToolResponse]], + ) -> MultipartToolResponse: + result = await next_fn(params, ctx) + update: dict[str, object] = {} + if isinstance(result.output, str): + update['output'] = _redact(result.output) + if result.content: + update['content'] = _redact_parts(result.content) + return result.model_copy(update=update) if update else result + + +@ai.tool() +async def lookup_customer(order_id: str) -> str: + """Look up the customer on an order.""" + return f'Order {order_id} belongs to Ada Lovelace, ada@example.com.' + async def main() -> None: - ticket = 'Charged twice. Email me at ada@example.com when the refund lands.' + ticket = 'Charged twice on order 1042. Email me at ada@example.com when the refund lands.' response = await ai.generate( prompt=ticket, system='Draft a short support reply. Do not ask the customer to repeat contact details.', + tools=[lookup_customer], use=[PiiRedact()], ) print(response.text) + # => Thanks for flagging the double charge on order 1042. We've issued the refund... if __name__ == '__main__':