diff --git a/README.md b/README.md
index 1e276bfaf..97083ba04 100644
--- a/README.md
+++ b/README.md
@@ -26,16 +26,25 @@ from genkit_google_genai import GoogleAI
ai = Genkit(plugins=[GoogleAI()])
-# Stream text responses in real-time
-stream = ai.generate_stream(
- model="googleai/gemini-flash-latest",
- prompt="Stream a 2-line poem about space.",
-)
-async for chunk in stream:
- print(chunk.text, end="")
-# Access final response metadata
-response = await stream.response
+async def main() -> None:
+ # 1. Stream text as the model writes it
+ stream = ai.generate_stream(
+ model="googleai/gemini-flash-latest",
+ prompt="Stream a 2-line poem about space.",
+ )
+ async for chunk in stream:
+ print(chunk.text, end="")
+ print()
+
+ # 2. Await the final response for usage and finish reason
+ response = await stream.response
+ print(response.finish_reason)
+ # => stop
+
+
+if __name__ == "__main__":
+ ai.run_main(main())
```
### 2. Streaming Tool Calling & Structured Output
@@ -47,50 +56,70 @@ from genkit_google_genai import GoogleAI
ai = Genkit(plugins=[GoogleAI()])
-# Define a tool with Pydantic type annotations
+
+# 1. Define a tool with a Pydantic input
class WeatherInput(BaseModel):
city: str = Field(description="Target city name")
+
@ai.tool(description="Get current weather for a location")
async def get_weather(input: WeatherInput) -> str:
return f"Sunny, 72°F in {input.city}"
-# Define structured output schema
+
+# 2. Define the structured output schema
class ActivityPlan(BaseModel):
activities: list[str]
outfit: str
-# Stream response with automatic tool execution and structured output
-stream = ai.generate_stream(
- model="googleai/gemini-flash-latest",
- prompt="Suggest activities for Seattle today.",
- tools=[get_weather],
- output_schema=ActivityPlan,
-)
-async for chunk in stream:
- if chunk.text:
- print(chunk.text, end="")
-# Access validated Pydantic output object
-response = await stream.response
-print(response.output)
-# => ActivityPlan(activities=['Kayak on Lake Union', 'Discovery Park'], outfit='Light jacket')
+async def main() -> None:
+ # 3. Stream; Genkit runs the tool calls and parses the output
+ stream = ai.generate_stream(
+ model="googleai/gemini-flash-latest",
+ prompt="Suggest activities for Seattle today.",
+ tools=[get_weather],
+ output_schema=ActivityPlan,
+ )
+ async for chunk in stream:
+ if chunk.text:
+ print(chunk.text, end="")
+ print()
+
+ # 4. Read the validated Pydantic object
+ response = await stream.response
+ print(response.output)
+ # => activities=['Kayak on Lake Union', 'Discovery Park'] outfit='Light jacket'
+
+
+if __name__ == "__main__":
+ ai.run_main(main())
```
### 3. Tool Approval Middleware & Restarts
```python
-from genkit import Genkit
+from pydantic import BaseModel
+from genkit.exp import Genkit
from genkit_google_genai import GoogleAI
from genkit_middleware import Middleware, ToolApproval
ai = Genkit(plugins=[GoogleAI(), Middleware()])
tool_approval = ToolApproval(allowed_tools=[])
+
+# 1. A tool takes one input, so group the fields in a model
+class Transfer(BaseModel):
+ amount: float
+ to_account: str
+
+
@ai.tool(description="Transfer money to an account")
-async def transfer_money(amount: float, to_account: str) -> str:
- return f"Transferred ${amount} to {to_account}"
+async def transfer_money(transfer: Transfer) -> str:
+ return f"Transferred ${transfer.amount} to {transfer.to_account}"
+
+# 2. Every tool call pauses for approval (allowed_tools=[])
agent = ai.define_agent(
name="bankingAgent",
model="googleai/gemini-flash-latest",
@@ -99,15 +128,23 @@ agent = ai.define_agent(
use=[tool_approval],
)
-chat = agent.chat()
-out1 = await chat.send("Transfer $100 to account 999.")
-# => Returns INTERRUPTED status because transfer_money requires approval
-# Approve pending tool interrupts and resume execution
-restarts = [intr.restart(resumed_metadata={"tool_approved": True}) for intr in out1.interrupts]
-out2 = await chat.resume(restart=restarts)
-print(out2.text)
-# => "$100 has been successfully transferred to account 999."
+async def main() -> None:
+ # 3. The turn stops at the pending transfer
+ chat = agent.chat()
+ out1 = await chat.send("Transfer $100 to account 999.")
+ print(out1.finish_reason)
+ # => interrupted
+
+ # 4. Approve the pending calls and resume
+ restarts = [intr.restart(resumed_metadata={"tool_approved": True}) for intr in out1.interrupts]
+ out2 = await chat.resume(restart=restarts)
+ print(out2.text)
+ # => $100 has been transferred to account 999.
+
+
+if __name__ == "__main__":
+ ai.run_main(main())
```
### 4. Agent Loops & Persistent Sessions
@@ -125,10 +162,10 @@ from genkit_google_genai import GoogleAI
ai = Genkit(plugins=[GoogleAI()])
-# Persist multi-turn session history in Cloud Firestore
+# 1. Persist multi-turn session history in Cloud Firestore
store = FirestoreSessionStore()
-# Define an agent with persistent session memory
+# 2. Define an agent backed by the store
agent = ai.define_agent(
name="supportAgent",
model="googleai/gemini-flash-latest",
@@ -136,12 +173,18 @@ agent = ai.define_agent(
store=store,
)
-# Multi-turn chat with automatic persistent session state
-chat = agent.chat()
-res1 = await chat.send("Hi, my name is Alex.")
-res2 = await chat.send("What was my name again?")
-print(res2.text)
-# => "Your name is Alex!"
+
+async def main() -> None:
+ # 3. Each turn is saved; the next one sees the history
+ chat = agent.chat()
+ await chat.send("Hi, my name is Alex.")
+ res = await chat.send("What was my name again?")
+ print(res.text)
+ # => Your name is Alex.
+
+
+if __name__ == "__main__":
+ ai.run_main(main())
```
---
@@ -151,11 +194,11 @@ print(res2.text)
| Type-Safe by Design |
- Leverage native Python type annotations and Pydantic models for structured inputs, outputs, and automatic tool schema generation. |
+ Native Python type annotations and Pydantic models drive structured inputs, outputs, and tool schemas. |
| Unified Model API |
- Switch effortlessly between Google Gemini, Anthropic Claude, OpenAI, Ollama, and Vertex AI using a single consistent interface. |
+ Switch between Google Gemini, Anthropic Claude, OpenAI, Ollama, and Vertex AI with one interface. |
| Integrated Observability |
@@ -171,7 +214,7 @@ print(res2.text)
## Developer Tools & Dev UI
-Accelerate AI development with the local Genkit Developer UI and CLI.
+Run flows, prompts and tools locally with the Genkit Developer UI and CLI.
```bash
genkit start -- uv run main.py
@@ -180,7 +223,6 @@ genkit start -- uv run main.py
Key features:
- **Playground**: Run and experiment with Genkit flows, prompts, and tools in dedicated playgrounds.
- **Trace Inspector**: Analyze detailed execution traces, including step-by-step breakdowns of complex flows.
-- **Evaluations**: Review performance metrics and evaluate model outputs over time.
@@ -188,12 +230,12 @@ Key features:
## Exploring Samples & Onboarding
-Jumpstart your app with copy-pasteable reference implementations in [`samples/`](samples/):
+Reference implementations live in [`samples/`](samples/):
-- **[Basic Flows](samples/basic-flows)**: Text generation, real-time streaming, structured Pydantic schemas, and type-safe tools
+- **[Basic Flows](samples/basic-flows)**: Typed flows, named `ai.run` steps, streaming, and serving over FastAPI. No model or API key needed
- **[Agents](samples/agents)**: Autonomous multi-turn agents, session state persistence, and memory
- **[Multimodal & Advanced Gemini](samples/google-genai-media)**: Multimodal media processing, context caching, and code execution
-- **[Model Evaluation](samples/evaluators)**: Automated quality evaluation, scoring metrics, and assertion suites
+- **[Tool Interrupts](samples/tool-interrupts)**: Pausing tool calls for human approval and resuming the turn
### Running Samples Locally
@@ -201,7 +243,7 @@ Clone the repository and launch any sample with the interactive Dev UI:
```bash
cd samples/
-genkit start -- uv run main.py
+genkit start -- uv run src/main.py
```
---
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 ca0d99d33..4507cc64f 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.
@@ -404,7 +404,7 @@ async def run(n: int, ctx: ActionRunContext) -> str:
```python
from genkit import FlowContext
-@ai.flow()
+@ai.flow
async def run(n: int, ctx: FlowContext[Status]) -> str:
ctx.send_chunk(Status(step='search'))
```
@@ -427,7 +427,7 @@ async def prepare(dish: str, ctx: ToolRunContext) -> str: ...
```python
from genkit import ToolContext
-@ai.tool()
+@ai.tool
async def prepare(dish: str, ctx: ToolContext[Progress]) -> str:
ctx.send_chunk(Progress(stage='searing', percent=40))
```
@@ -472,7 +472,7 @@ async def slow(x: dict, ctx: ToolRunContext) -> dict:
**New:**
```python
-@ai.tool()
+@ai.tool
async def slow(x: dict) -> dict:
while not done:
await step() # cancellation raises asyncio.CancelledError here
@@ -485,7 +485,7 @@ task = asyncio.create_task(ai.generate(prompt=p))
task.cancel()
```
-To stop a stream early, use `async with` (or call `aclose()`). A bare `break` without it leaves the flow running.
+To stop a stream early, use `async with` (or call `aclose()`). After a bare `break`, the flow keeps running until the stream object is garbage-collected.
```python
stream = my_flow.stream(x)
@@ -498,7 +498,7 @@ async with stream:
Cancellation can now land at any `await` in your tool, so put cleanup for partial work in `finally`. If you catch `asyncio.CancelledError` yourself, re-raise it.
```python
-@ai.tool()
+@ai.tool
async def book_trip(trip: Trip) -> Booking:
hold = await reserve_seats(trip)
try:
@@ -660,7 +660,7 @@ async def get_order(order_id: str) -> Order:
```python
from genkit import PublicError
-@ai.flow()
+@ai.flow
async def get_order(order_id: str) -> Order:
order = await db.find(order_id)
if order is None:
@@ -783,7 +783,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
@@ -912,9 +915,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 51f29129b..7e690575d 100644
--- a/packages/genkit-amazon-bedrock/README.md
+++ b/packages/genkit-amazon-bedrock/README.md
@@ -81,10 +81,10 @@ Anything the chain does not cover goes through `session=`, which takes a
pre-configured `boto3.session.Session`. Region resolution is separate from
credentials and is described under [Usage](#usage).
-Every call runs on these credentials. A per-request key in
-`context={'secrets': {'api_key': ...}}` is ignored, so a flow that carries
-another provider's key can still call Bedrock models. Reading that key as a
-per-request Bedrock API key is tracked in
+Every call runs on these credentials, `ai.generate` and `ai.embed` alike. A
+per-request key in `context={'secrets': {'api_key': ...}}` is ignored, so a
+flow that carries another provider's key can still call Bedrock models.
+Reading that key as a per-request Bedrock API key is tracked in
[#6976](https://github.com/genkit-ai/genkit/issues/6976).
## Usage
@@ -115,9 +115,14 @@ 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())
```
The constructors follow Bedrock's output modalities: `Bedrock.text` (TEXT,
@@ -233,14 +238,21 @@ from genkit import Part
from genkit_amazon_bedrock import cache_point_part
CLAUDE = 'bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0'
+DELIVERY_POLICY = open('delivery_policy.md').read() # well over 1,000 tokens
+
+# 1. The cache point goes after the content it should cache
+system = [Part.from_text(DELIVERY_POLICY), cache_point_part()]
-# The cache point goes after the content it should cache.
-system = [Part.from_text(LONG_STATIC_PROMPT), cache_point_part()]
-first = await ai.generate(model=CLAUDE, system=system, prompt='What are the delivery tiers?')
-second = await ai.generate(model=CLAUDE, system=system, prompt='Which tier needs a signature?')
+async def main() -> None:
+ # 2. The first call writes the cache, the second reads it
+ await ai.generate(model=CLAUDE, system=system, prompt='What are the delivery tiers?')
+ second = await ai.generate(model=CLAUDE, system=system, prompt='Which tier needs a signature?')
-print(second.usage.cached_content_tokens)
+ # 3. Cached tokens show up on the second call only
+ if second.usage:
+ print(second.usage.cached_content_tokens)
+ # => 1843
```
Notes:
@@ -322,11 +334,22 @@ ai = Genkit(
]
)
-response = await ai.generate(
- model=Bedrock.stability('stability.sd3-5-large-v1:0'),
- prompt='A tabby cat asleep on a sunlit windowsill, watercolour.',
-)
-image = response.media.url # data:image/png;base64,...
+
+async def main() -> None:
+ # 1. Generate an image
+ response = await ai.generate(
+ model=Bedrock.stability('stability.sd3-5-large-v1:0'),
+ prompt='A tabby cat asleep on a sunlit windowsill, watercolour.',
+ )
+
+ # 2. Read the data URL off the first media part
+ if response.media:
+ print(response.media.url[:22])
+ # => data:image/png;base64,
+
+
+if __name__ == '__main__':
+ ai.run_main(main())
```
The plugin infers the route from the ID: the image IDs below take the
@@ -363,8 +386,9 @@ response = await ai.generate(
# 'aspect_ratio': '16:9', 'seed': 42, 'negative_prompt': 'blurry'}
# 2. The media part's MIME type follows output_format
-print(response.media.content_type)
-# => image/jpeg
+if response.media:
+ print(response.media.content_type)
+ # => image/jpeg
```
`StabilityImageConfig` extends `GenkitConfig`, like the Veo config, not
diff --git a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_config.py b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_config.py
index 5b7165b6d..52c59a2c1 100644
--- a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_config.py
+++ b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_config.py
@@ -95,8 +95,9 @@ class StabilityImageConfig(GenkitConfig):
)
# 2. The MIME type follows output_format
- print(response.media.content_type)
- # => image/jpeg
+ if response.media:
+ print(response.media.content_type)
+ # => image/jpeg
```
"""
diff --git a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_plugin.py b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_plugin.py
index 5a63131cb..76af39120 100644
--- a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_plugin.py
+++ b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_plugin.py
@@ -243,8 +243,9 @@ def stability(
prompt='A food truck at dusk, string lights.',
config=StabilityImageConfig(aspect_ratio='16:9', output_format='jpeg'),
)
- print(response.media.content_type)
- # => image/jpeg
+ if response.media:
+ print(response.media.content_type)
+ # => image/jpeg
```
"""
return _model_ref(name, family='stability', config_schema=StabilityImageConfig, config=config)
diff --git a/packages/genkit-anthropic/README.md b/packages/genkit-anthropic/README.md
index 361b1ad4c..e352ffbed 100644
--- a/packages/genkit-anthropic/README.md
+++ b/packages/genkit-anthropic/README.md
@@ -26,11 +26,18 @@ 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())
```
Set `ANTHROPIC_API_KEY` in the environment, or pass `api_key=` to `Anthropic()`.
@@ -71,7 +78,11 @@ config = AnthropicConfig(
)
# 2. Generate with it
-res = await ai.generate(model='anthropic/claude-opus-4-6', prompt='Plan a tasting menu.', config=config)
+await ai.generate(
+ model=Anthropic.claude('claude-opus-4-6'),
+ prompt='Plan a tasting menu.',
+ config=config,
+)
# Sent as:
# thinking={'display': 'summarized', 'type': 'adaptive'}
# output_config={'effort': 'high', 'task_budget': {'type': 'tokens', 'total': 20000}}
@@ -98,11 +109,11 @@ claude = Anthropic.claude('claude-sonnet-4-6', config=AnthropicConfig(thinking='
# 2. Turn it off for one call; the inherited budget isn't sent
await ai.generate(model=claude, prompt='Is shellfish safe for this guest?', config={'thinking': 'disabled'})
-# => thinking={'type': 'disabled'}
+# Sent as: thinking={'type': 'disabled'}
# 3. Raise the budget for another; the mode is inherited
await ai.generate(model=claude, prompt='Plan a nut-free tasting menu.', config={'thinking_budget': 8192})
-# => thinking={'type': 'enabled', 'budget_tokens': 8192}
+# Sent as: thinking={'type': 'enabled', 'budget_tokens': 8192}
```
A budget over an inherited `thinking='disabled'` stays disabled. Pass
diff --git a/packages/genkit-anthropic/src/genkit_anthropic/__init__.py b/packages/genkit-anthropic/src/genkit_anthropic/__init__.py
index 419a98bab..1effef23e 100644
--- a/packages/genkit-anthropic/src/genkit_anthropic/__init__.py
+++ b/packages/genkit-anthropic/src/genkit_anthropic/__init__.py
@@ -16,31 +16,39 @@
"""Anthropic plugin for Genkit.
-This plugin provides integration with Anthropic's Claude models for the
-Genkit framework. It registers Claude models as Genkit actions, enabling
-text generation operations.
+Registers Claude models as Genkit model actions under ``anthropic/``. Any
+Claude id resolves on demand; ``Anthropic.claude()`` returns a typed ref bound
+to ``AnthropicConfig``.
Example:
```python
from genkit import Genkit
- from genkit_anthropic import Anthropic, AnthropicConfig
+ from genkit_anthropic import Anthropic
# 1. Initialize Genkit with the Anthropic plugin
ai = Genkit(plugins=[Anthropic()])
- # 2. Generate content using Claude Sonnet 4.6
- res = await ai.generate(
- model=Anthropic.claude('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.
+ async def main() -> None:
+ # 2. Generate with Claude Sonnet 4.6
+ res = await ai.generate(
+ model=Anthropic.claude('claude-sonnet-4-6'),
+ prompt='Explain recursion in 10 words.',
+ )
+
+ # 3. Read the text
+ print(res.text)
+ # => A function that solves a problem by calling itself repeatedly.
+
+
+ if __name__ == '__main__':
+ ai.run_main(main())
```
-Requirements:
- - Requires the ``ANTHROPIC_API_KEY`` environment variable or explicit ``api_key``.
+Credentials:
+ The plugin key comes from ``api_key=`` or ``ANTHROPIC_API_KEY``. A call
+ can bring its own key as ``context={'secrets': {'api_key': ...}}``; a
+ plugin with no key of its own serves only those calls.
See Also:
- Anthropic documentation: https://docs.anthropic.com/
diff --git a/packages/genkit-django/README.md b/packages/genkit-django/README.md
index 5b9cb8ac3..8ece2a6ff 100644
--- a/packages/genkit-django/README.md
+++ b/packages/genkit-django/README.md
@@ -1,6 +1,6 @@
# Genkit Django Plugin
-`genkit-django` exposes Genkit flows as HTTP endpoints in a Django application. It mirrors `genkit-flask` and `genkit-fastapi`: one decorator turns a `@ai.flow()` into a Django view that speaks the Genkit HTTP protocol (JSON envelope, optional SSE streaming, structured error responses).
+`genkit-django` exposes Genkit flows as HTTP endpoints in a Django application. It mirrors `genkit-flask` and `genkit-fastapi`: one decorator turns a `@ai.flow` into a Django view that speaks the Genkit HTTP protocol (JSON envelope, optional SSE streaming, structured error responses).
> **Building with a coding agent? Install the Genkit Python skill first.**
>
@@ -15,7 +15,7 @@
## Install
```bash
-uv add genkit-django
+uv add genkit-django genkit-google-genai
```
## Usage
@@ -24,12 +24,13 @@ uv add genkit-django
# myapp/views.py
from genkit import Genkit
from genkit_django import genkit_django_handler
+from genkit_google_genai import GoogleAI
-ai = Genkit(plugins=[...])
+ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
@genkit_django_handler(ai)
-@ai.flow()
+@ai.flow
async def chat(prompt: str) -> str:
response = await ai.generate(prompt=prompt)
return response.text
@@ -60,6 +61,7 @@ uvicorn myproject.asgi:application
## Context provider
```python
+from genkit import FlowContext
from genkit.web import RequestData
@@ -68,8 +70,9 @@ async def auth(request_data: RequestData) -> dict[str, object]:
@genkit_django_handler(ai, context_provider=auth)
-@ai.flow()
-async def chat(prompt, ctx):
- user = ctx.context.get('username')
- ...
+@ai.flow
+async def chat(prompt: str, ctx: FlowContext) -> str:
+ user = ctx.context.get('username') # what auth returned
+ response = await ai.generate(prompt=prompt)
+ return response.text
```
diff --git a/packages/genkit-django/src/genkit_django/__init__.py b/packages/genkit-django/src/genkit_django/__init__.py
index ee64aa470..fa54eb3d1 100644
--- a/packages/genkit-django/src/genkit_django/__init__.py
+++ b/packages/genkit-django/src/genkit_django/__init__.py
@@ -33,7 +33,7 @@
# 2. Define flow and decorate as Django view
@genkit_django_handler(ai)
- @ai.flow()
+ @ai.flow
async def chat(prompt: str) -> str:
res = await ai.generate(
model=GoogleAI.gemini('gemini-flash-latest'),
diff --git a/packages/genkit-django/src/genkit_django/_handler.py b/packages/genkit-django/src/genkit_django/_handler.py
index 09eb97658..ec4ee738a 100644
--- a/packages/genkit-django/src/genkit_django/_handler.py
+++ b/packages/genkit-django/src/genkit_django/_handler.py
@@ -104,12 +104,13 @@ def genkit_django_handler(
@genkit_django_handler(ai)
- @ai.flow()
+ @ai.flow
async def say_hi(name: str, ctx: FlowContext) -> str:
stream = ai.generate_stream(prompt=f'tell a joke about {name}')
- async for chunk in stream.stream:
- if chunk.text:
- ctx.send_chunk(chunk.text)
+ async with stream.stream as chunks:
+ async for chunk in chunks:
+ if chunk.text:
+ ctx.send_chunk(chunk.text)
res = await stream.response
return res.text
diff --git a/packages/genkit-fastapi/README.md b/packages/genkit-fastapi/README.md
index a613a1b61..1eeb27186 100644
--- a/packages/genkit-fastapi/README.md
+++ b/packages/genkit-fastapi/README.md
@@ -15,9 +15,11 @@ Expose Genkit flows and agents as HTTP endpoints in a FastAPI application.
## Installation
```bash
-uv add genkit-fastapi genkit-google-genai
+uv add genkit-fastapi genkit-google-genai uvicorn
```
+`uvicorn` runs the examples below. Any ASGI server works; the adapter doesn't depend on one.
+
## Usage
### Serving Flows (`serve_flow`)
@@ -39,7 +41,7 @@ async def get_weather(location: str) -> str:
return f'Sunny in {location}'
-@ai.flow()
+@ai.flow
async def chat_flow(prompt: str) -> str:
response = await ai.generate(
prompt=prompt,
@@ -78,7 +80,8 @@ weather_agent = ai.define_agent(
tools=[get_weather],
)
-# Mount agent turn route at POST /api/weatherAgent (plus /getSnapshot and /abort companion endpoints)
+# Mount agent turn route at POST /api/weatherAgent
+# (/getSnapshot and /abort are added only when the agent has a store=)
app.include_router(serve_agent(weather_agent), prefix='/api')
```
@@ -87,7 +90,7 @@ app.include_router(serve_agent(weather_agent), prefix='/api')
Customize the base path or resolve request context using FastAPI's dependency injection system:
```python
-from fastapi import Depends, Header
+from fastapi import Header
from genkit_fastapi import serve_flow
@@ -119,12 +122,14 @@ ai = Genkit(...)
app = FastAPI()
-@ai.flow()
+@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')
@@ -172,7 +177,7 @@ from genkit_fastapi import genkit_fastapi_handler
@app.post('/custom-chat')
@genkit_fastapi_handler(ai)
-@ai.flow()
+@ai.flow
async def custom_chat(prompt: str) -> str:
response = await ai.generate(
prompt=prompt,
diff --git a/packages/genkit-fastapi/src/genkit_fastapi/__init__.py b/packages/genkit-fastapi/src/genkit_fastapi/__init__.py
index 1aefeb2f9..49a16630a 100644
--- a/packages/genkit-fastapi/src/genkit_fastapi/__init__.py
+++ b/packages/genkit-fastapi/src/genkit_fastapi/__init__.py
@@ -29,7 +29,7 @@
app = FastAPI()
-@ai.flow()
+@ai.flow
async def suggest_dish(cuisine: str) -> str:
response = await ai.generate(prompt=f'Suggest one {cuisine} dish.')
return response.text
@@ -39,7 +39,7 @@ async def suggest_dish(cuisine: str) -> str:
app.include_router(serve_flow(suggest_dish), prefix='/api')
```
-For a custom route, stack ``@genkit_fastapi_handler(ai)`` over ``@ai.flow()``.
+For a custom route, stack ``@genkit_fastapi_handler(ai)`` over ``@ai.flow``.
Agents are experimental, so their routes come from ``genkit_fastapi.exp``::
diff --git a/packages/genkit-fastapi/src/genkit_fastapi/_handler.py b/packages/genkit-fastapi/src/genkit_fastapi/_handler.py
index 49b17e092..eb304e26a 100644
--- a/packages/genkit-fastapi/src/genkit_fastapi/_handler.py
+++ b/packages/genkit-fastapi/src/genkit_fastapi/_handler.py
@@ -205,7 +205,7 @@ def genkit_fastapi_handler(
```python
@app.post('/chat')
@genkit_fastapi_handler(ai)
- @ai.flow()
+ @ai.flow
async def chat(prompt: str) -> str:
response = await ai.generate(prompt=prompt)
return response.text
@@ -219,7 +219,7 @@ async def chat():
return my_flow
- @ai.flow()
+ @ai.flow
async def my_flow(prompt: str) -> str: ...
```
diff --git a/packages/genkit-fastapi/src/genkit_fastapi/exp/_agent.py b/packages/genkit-fastapi/src/genkit_fastapi/exp/_agent.py
index 5c63c83d1..74781a5cc 100644
--- a/packages/genkit-fastapi/src/genkit_fastapi/exp/_agent.py
+++ b/packages/genkit-fastapi/src/genkit_fastapi/exp/_agent.py
@@ -100,7 +100,7 @@ def serve_agent(
base_path: str | None = None,
context_dependency: Callable[..., Any] | None = None,
) -> APIRouter:
- """Build an APIRouter serving an agent and its snapshot/abort endpoints over HTTP.
+ """Build an APIRouter serving an agent over HTTP.
Mount the returned router like any other::
@@ -114,7 +114,8 @@ def serve_agent(
Use this to reuse existing ``Depends``-based auth / resources.
Returns:
- An APIRouter with the turn route plus snapshot/abort endpoints.
+ An APIRouter with the turn route. When the agent has a ``store``, it
+ also serves ``/getSnapshot`` and ``/abort``.
"""
resolved_base_path = f'/{agent.name}' if base_path is None else base_path
router = APIRouter(tags=[agent.name])
diff --git a/packages/genkit-flask/README.md b/packages/genkit-flask/README.md
index becd294a0..0df4f9fae 100644
--- a/packages/genkit-flask/README.md
+++ b/packages/genkit-flask/README.md
@@ -32,7 +32,7 @@ ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
@app.post('/api/greet')
@genkit_flask_handler(ai)
-@ai.flow()
+@ai.flow
async def greet_user(name: str) -> str:
res = await ai.generate(prompt=f'Say hello to {name} in one sentence.')
return res.text
diff --git a/packages/genkit-flask/src/genkit_flask/__init__.py b/packages/genkit-flask/src/genkit_flask/__init__.py
index 83373a60e..50150249a 100644
--- a/packages/genkit-flask/src/genkit_flask/__init__.py
+++ b/packages/genkit-flask/src/genkit_flask/__init__.py
@@ -35,7 +35,7 @@
# 2. Stack Flask route + Genkit handler + flow on one function
@app.post('/api/greet')
@genkit_flask_handler(ai)
- @ai.flow()
+ @ai.flow
async def greet_user(name: str) -> str:
res = await ai.generate(prompt=f'Say hello to {name} in one sentence.')
return res.text
diff --git a/packages/genkit-flask/src/genkit_flask/_handler.py b/packages/genkit-flask/src/genkit_flask/_handler.py
index 5de6eeb43..a47968362 100644
--- a/packages/genkit-flask/src/genkit_flask/_handler.py
+++ b/packages/genkit-flask/src/genkit_flask/_handler.py
@@ -144,12 +144,13 @@ def genkit_flask_handler(
@app.post('/chat')
@genkit_flask_handler(ai)
- @ai.flow()
+ @ai.flow
async def say_hi(name: str, ctx: FlowContext) -> str:
stream = ai.generate_stream(prompt=f'tell a joke about {name}')
- async for chunk in stream.stream:
- if chunk.text:
- ctx.send_chunk(chunk.text)
+ async with stream.stream as chunks:
+ async for chunk in chunks:
+ if chunk.text:
+ ctx.send_chunk(chunk.text)
res = await stream.response
return res.text
```
diff --git a/packages/genkit-google-cloud/README.md b/packages/genkit-google-cloud/README.md
index 2663b42d7..ceabeb942 100644
--- a/packages/genkit-google-cloud/README.md
+++ b/packages/genkit-google-cloud/README.md
@@ -81,8 +81,9 @@ pip install 'genkit-google-cloud[firestore]'
```python
from genkit.exp import Genkit
from genkit_google_cloud.exp import FirestoreSessionStore
+from genkit_google_genai import GoogleAI
-ai = Genkit()
+ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
store = FirestoreSessionStore() # uses Application Default Credentials
agent = ai.define_agent(name='assistant', store=store)
```
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 f567dc205..0367bd3bb 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
```
@@ -28,7 +29,7 @@ To use Google AI models, obtain an API key from [Google AI Studio](https://aistu
export GEMINI_API_KEY=''
```
-`GOOGLE_API_KEY` and `GOOGLE_GENAI_API_KEY` are read next, in that order. For a per-tenant key, start `GoogleAI()` with no key and pass `context={'secrets': {'api_key': tenant_key}}` on each `generate`, `generate_operation`, `embed`, or `embed_many` call. With no key from any of these, `GoogleAI()` logs one warning when it's constructed (to stderr unless your app configures `logging`), and a call with no plugin key and no secret fails with `FAILED_PRECONDITION`. A key the API rejects fails with `UNAUTHENTICATED` and the API's message.
+`GOOGLE_API_KEY` and `GOOGLE_GENAI_API_KEY` are read next, in that order. For a per-tenant key, start `GoogleAI()` with no key and pass `context={'secrets': {'api_key': tenant_key}}` on each `generate`, `generate_operation`, `check_operation`, `embed`, or `embed_many` call. With no key from any of these, `GoogleAI()` logs one warning when it's constructed (to stderr unless your app configures `logging`), and a call with no plugin key and no secret fails with `FAILED_PRECONDITION`. A key the API rejects fails with `UNAUTHENTICATED` and `reason=ErrorReason.INVALID_CREDENTIALS`, carrying the API's message.
### Vertex AI (Google Cloud)
@@ -49,15 +50,20 @@ ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
# 2. Define a typed flow
-@ai.flow()
+@ai.flow
async def greet(name: str) -> str:
res = await ai.generate(prompt=f'Say hello to {name}.')
return res.text
-# 3. Execute and inspect output
-print(await greet('Grace'))
-# => Hello Grace! How can I help you today?
+# 3. Call the flow from main and run it
+async def main() -> None:
+ print(await greet('Grace'))
+ # => Hello Grace! How can I help you today?
+
+
+if __name__ == '__main__':
+ ai.run_main(main())
```
## Features
@@ -85,28 +91,33 @@ ai = Genkit(plugins=[GoogleAI()])
# 2. Define a function tool
-@ai.tool()
+@ai.tool
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
@@ -117,20 +128,28 @@ 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 if res.media else '')
+ # => data:audio/L16;codec=pcm;rate=24000;base64,AAAAAP7/AQD+/w...
+
+
+if __name__ == '__main__':
+ ai.run_main(main())
```
+Gemini returns raw 16-bit PCM at 24 kHz. Wrap it in a WAV header (stdlib `wave`) before saving to `.wav`.
+
#### Image generation with GeminiImageConfig
```python
@@ -139,18 +158,25 @@ 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',
+ ),
+ )
+
+ if res.media:
+ print(res.media.url[:40])
+ # => data:image/jpeg;base64,/9j/4AAQSkZJRgABA
+
+
+if __name__ == '__main__':
+ ai.run_main(main())
```
#### Default config on model references
@@ -184,10 +210,17 @@ 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: the
+call returns `finish_reason='failed'` with
+`response.error.status == 'INVALID_ARGUMENT'`:
-- `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`.
@@ -251,8 +284,7 @@ function tools (`generate(tools=...)` raises). Blocks with defaults, such as
`agent_config` and `environment`, merge key by key.
`timeout` on these three configs (and in Deep Research's `check_operation` /
-`cancel_operation` `config`) is the HTTP timeout in seconds. It used to be
-milliseconds: `config={'timeout': 30000}` becomes `config={'timeout': 30}`.
+`cancel_operation` `config`) is the HTTP timeout in seconds.
```python
op = await ai.generate_operation(
@@ -273,6 +305,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
@@ -280,8 +317,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,
@@ -309,45 +352,63 @@ 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-preview'),
+ prompt='A paper airplane gliding through a bright classroom',
+ )
+ while not operation.done:
+ await asyncio.sleep(5)
+ operation = await ai.check_operation(operation)
+
+ # 3. Read the finished video off the response
+ if operation.output and operation.output.media:
+ print(operation.output.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. Read the finished video off the response
+ if operation.output and operation.output.media:
+ print(operation.output.media.url)
+ # => data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28y...
+
-# 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-python/tree/main/samples/google-genai-media).
@@ -366,24 +427,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 media in response.media_parts:
+ print(media.url)
+ # => data:image/png;base64,iVBORw0KGgoAAAANSU...
+
+
+if __name__ == '__main__':
+ ai.run_main(main())
```
Runnable snippets are in [`samples`](../../samples).
diff --git a/packages/genkit-google-genai/src/genkit_google_genai/__init__.py b/packages/genkit-google-genai/src/genkit_google_genai/__init__.py
index 3af7d0e02..d5c6b40b4 100644
--- a/packages/genkit-google-genai/src/genkit_google_genai/__init__.py
+++ b/packages/genkit-google-genai/src/genkit_google_genai/__init__.py
@@ -73,7 +73,9 @@
```
Requirements:
- - GoogleAI requires the ``GEMINI_API_KEY`` environment variable or explicit ``api_key``.
+ - GoogleAI reads ``api_key``, then ``GEMINI_API_KEY``, ``GOOGLE_API_KEY``,
+ ``GOOGLE_GENAI_API_KEY``. With none set it still loads; pass
+ ``context={'secrets': {'api_key': ...}}`` per call.
- VertexAI requires Google Cloud Application Default Credentials (ADC) or explicit credentials.
See Also:
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 a695578d9..6653be097 100644
--- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py
+++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py
@@ -492,12 +492,10 @@ class GoogleAI(GoogleFamilyRefs, Plugin):
models work without an SDK update. The live catalog is listed only when
the Dev UI asks for it, then cached.
- Model Types:
- | Type | Action Kind | Example |
- |---|---|---|
- | Gemini / Gemma | MODEL | ``googleai/gemini-flash-latest`` |
- | Embedders | EMBEDDER | ``googleai/gemini-embedding-001`` |
- | Veo (Video) | BACKGROUND_MODEL | ``googleai/veo-3.1-generate-preview`` |
+ Model types:
+ - Gemini / Gemma (MODEL): ``googleai/gemini-flash-latest``
+ - Embedders (EMBEDDER): ``googleai/gemini-embedding-001``
+ - Veo (BACKGROUND_MODEL): ``googleai/veo-3.1-generate-preview``
Example:
```python
@@ -1016,13 +1014,11 @@ class VertexAI(GoogleFamilyRefs, Plugin):
- Data residency controls
- IAM-based access control
- Model Types:
- | Type | Action Kind | Example |
- |---|---|---|
- | Gemini | MODEL | ``vertexai/gemini-2.5-flash`` |
- | Veo (Video) | BACKGROUND_MODEL | ``vertexai/veo-3.1-generate-001`` |
- | Virtual Try-On | MODEL | ``vertexai/virtual-try-on-001`` |
- | Embedders | EMBEDDER | ``vertexai/text-embedding-005`` |
+ Model types:
+ - Gemini (MODEL): ``vertexai/gemini-2.5-flash``
+ - Veo (BACKGROUND_MODEL): ``vertexai/veo-3.1-generate-001``
+ - Virtual Try-On (MODEL): ``vertexai/virtual-try-on-001``
+ - Embedders (EMBEDDER): ``vertexai/text-embedding-005``
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 4ecb46b24..c612046dc 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
@@ -677,7 +677,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(
@@ -765,7 +767,7 @@ class GeminiTtsConfig(GeminiConfig):
# 3. Access synthesized audio parts
print(res.media.url if res.media else '')
- # => data:audio/wav;base64,UklGRiQAAABXQVZFZ...
+ # => data:audio/L16;codec=pcm;rate=24000;base64,AAAAAP7/AQD+/w...
```
"""
@@ -804,7 +806,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',
@@ -813,8 +815,9 @@ class GeminiImageConfig(GeminiConfig):
)
# 3. Access generated image media
- print(res.media.url if res.media else '')
- # => data:image/png;base64,iVBORw0KGgoAAAANSU...
+ if res.media:
+ print(res.media.url[:40])
+ # => data:image/jpeg;base64,/9j/4AAQSkZJRgABA
```
"""
@@ -947,11 +950,24 @@ class GemmaConfig(GeminiConfig):
supports=GEMINI_TEXT_SUPPORTS,
)
+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, above, shares the 3.7/3.8 tool-loop restriction).
+GEMINI_PRO_LATEST = ModelInfo(
+ label='Google AI - Gemini Pro Latest',
+ supports=GEMINI_3_PRO_PREVIEW.supports,
+)
+
GEMINI_IMAGE_SUPPORTS = ModelSupports(
multiturn=True,
media=True,
@@ -1082,8 +1098,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',
@@ -1097,11 +1111,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',
@@ -1115,11 +1136,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',
]
@@ -1145,9 +1161,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_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/tests/google_genai_plugin_test.py b/packages/genkit-google-genai/tests/google_genai_plugin_test.py
index a1cd99c84..f3789c5de 100644
--- a/packages/genkit-google-genai/tests/google_genai_plugin_test.py
+++ b/packages/genkit-google-genai/tests/google_genai_plugin_test.py
@@ -1191,25 +1191,25 @@ async def test_generate_googleai_model_resolves_unchanged(mock_list_models: Magi
async def test_googleai_init_and_resolve_build_the_same_action_name(
mock_list_models: MagicMock, mock_client: MagicMock
) -> None:
- """`googleai/gemini-2.5-flash` from init and resolve is the same name and sends the bare id."""
+ """`googleai/gemini-flash-latest` from init and resolve is the same name and sends the bare id."""
listed = GenaiModels()
- listed.gemini = ['gemini-2.5-flash']
+ listed.gemini = ['gemini-flash-latest']
mock_list_models.return_value = listed
mock_client.return_value.aio.models.generate_content = AsyncMock(return_value=_gemini_reply('hello'))
plugin = GoogleAI(api_key='test-key')
- init_action = next(a for a in await plugin.init() if a.name == 'googleai/gemini-2.5-flash')
- resolved = await plugin.resolve(ActionKind.MODEL, 'gemini-2.5-flash')
+ init_action = next(a for a in await plugin.init() if a.name == 'googleai/gemini-flash-latest')
+ resolved = await plugin.resolve(ActionKind.MODEL, 'gemini-flash-latest')
ai = Genkit(plugins=[GoogleAI(api_key='test-key')])
- response = await ai.generate(model='googleai/gemini-2.5-flash', prompt='hi')
+ response = await ai.generate(model='googleai/gemini-flash-latest', prompt='hi')
- assert init_action.name == 'googleai/gemini-2.5-flash'
+ assert init_action.name == 'googleai/gemini-flash-latest'
assert resolved is not None
- assert resolved.name == 'googleai/gemini-2.5-flash'
+ assert resolved.name == 'googleai/gemini-flash-latest'
assert response.text == 'hello'
sent = mock_client.return_value.aio.models.generate_content.await_args
assert sent is not None
- assert sent.kwargs['model'] == 'gemini-2.5-flash'
+ assert sent.kwargs['model'] == 'gemini-flash-latest'
@patch('genkit_google_genai._google.genai.client.Client')
diff --git a/packages/genkit-google-genai/tests/google_plugin_test.py b/packages/genkit-google-genai/tests/google_plugin_test.py
index b871d6bf0..3c2fd9018 100644
--- a/packages/genkit-google-genai/tests/google_plugin_test.py
+++ b/packages/genkit-google-genai/tests/google_plugin_test.py
@@ -1125,7 +1125,7 @@ async def test_failed_listing_keeps_static_catalog_and_retries() -> None:
catalog = await ai._registry.list_actions()
await ai._registry.list_actions()
- assert '/model/googleai/gemini-2.5-flash' in catalog
+ assert '/model/googleai/gemini-flash-latest' in catalog
assert '/embedder/googleai/gemini-embedding-001' in catalog
assert mock_client.aio.models.list.call_count == 2
@@ -1206,14 +1206,17 @@ async def test_vertexai_resolves_unlisted_and_tuned_models_without_listing(verte
async def test_static_init_catalog_matches_backend_capabilities(
googleai_plugin_instance: GoogleAI, vertexai_plugin_instance: VertexAI
) -> None:
- """GoogleAI init registers Gemma 3/4 and -latest; VertexAI skips them; neither registers retired previews."""
+ """GoogleAI init registers Gemma 4 and -latest; VertexAI keeps 2.5 Flash/Pro and skips Gemma/-latest."""
google_names = {a.name for a in await googleai_plugin_instance.init()}
vertex_names = {a.name for a in await vertexai_plugin_instance.init()}
- assert {'googleai/gemma-3-12b-it', 'googleai/gemma-4-31b-it', 'googleai/gemini-flash-latest'} <= google_names
+ assert {'googleai/gemma-4-26b-a4b-it', 'googleai/gemma-4-31b-it', 'googleai/gemini-flash-latest'} <= google_names
+ assert 'googleai/gemma-3-12b-it' not in google_names
+ assert 'googleai/gemini-2.5-flash' not in google_names
assert 'googleai/gemini-2.5-pro-exp-03-25' not in google_names
assert 'googleai/gemini-2.5-flash-image-preview' not in google_names
+ assert 'vertexai/gemini-2.5-flash' in vertex_names
assert not any('gemma-' in name for name in vertex_names)
assert not any(name.endswith('-latest') for name in vertex_names)
assert 'vertexai/gemini-2.5-pro-exp-03-25' not in vertex_names
diff --git a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py
index 02af6b0dc..09f772556 100644
--- a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py
+++ b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py
@@ -697,7 +697,7 @@ def test_stable_gemini_text_models_register_real_capabilities(
('gemini-2.5-flash-001', ConstrainedSupport.NO_TOOLS, None),
('models/gemini-2.0-flash-001', ConstrainedSupport.NO_TOOLS, None),
('gemini-1.5-pro-002', ConstrainedSupport.NO_TOOLS, None),
- ('gemini-3.5-flash-lite', ConstrainedSupport.ALL, None),
+ ('gemini-3.9-flash-lite', ConstrainedSupport.ALL, None),
('gemini-4-carbon', ConstrainedSupport.ALL, None),
('gemini-4-argon', ConstrainedSupport.ALL, None),
('endpoints/1234567890', ConstrainedSupport.ALL, None),
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-mcp/README.md b/packages/genkit-mcp/README.md
index edad9de81..0e5836622 100644
--- a/packages/genkit-mcp/README.md
+++ b/packages/genkit-mcp/README.md
@@ -10,8 +10,6 @@ Tracking issue:
The example uses Gemini through `genkit-google-genai` and needs `GEMINI_API_KEY` set. Any model plugin works.
```python
-import asyncio
-
from genkit import Genkit
from genkit_google_genai import GoogleAI
from genkit_mcp import define_mcp_client
@@ -27,28 +25,32 @@ client = define_mcp_client(
async def main() -> None:
- try:
- # What the server offers, under the names a model is shown.
- tools = await client.get_active_tools()
- for tool in tools:
- print(tool.name, tool.description)
-
- # Every tool of this server, or just one.
- result = await ai.generate(prompt='Echo "hello".', tools=['everything:tool/*'])
- one = f'{client.name}:tool/{client.tool_name("echo")}'
- result = await ai.generate(prompt='Echo "hello".', tools=[one])
-
- # The listing itself is a list of Genkit tools, so it can be handed to a
- # generate call or called directly.
- result = await ai.generate(prompt='Echo "hello".', tools=tools)
- print(result.text)
- echoed = (await tools[0]({'message': 'hello'})).output
- print(echoed)
- finally:
- await client.close()
-
-
-asyncio.run(main())
+ # 1. What the server offers, under the names a model sees
+ tools = await client.get_active_tools()
+ for tool in tools:
+ print(tool.name)
+ # => everything_echo
+ # everything_add
+ # ...
+
+ # 2. Bind every tool of this server, or just one
+ result = await ai.generate(prompt='Echo "hello".', tools=['everything:tool/*'])
+ one = f'{client.name}:tool/{client.tool_name("echo")}'
+ print(one)
+ # => everything:tool/everything_echo
+ result = await ai.generate(prompt='Echo "hello".', tools=[one])
+ print(result.text)
+ # => Echo: hello
+
+ # 3. The listing is a list of Genkit tools: hand it to generate or call one directly
+ result = await ai.generate(prompt='Echo "hello".', tools=tools)
+ echoed = (await tools[0]({'message': 'hello'})).output
+ print(echoed)
+ # => Echo: hello
+
+
+if __name__ == '__main__':
+ ai.run_main(main())
```
## Tool names
@@ -118,6 +120,8 @@ host = define_mcp_host(
result = await ai.generate(prompt='Echo "hello".', tools=['hosted:tool/*'])
one = f'{host.name}:tool/{host.tool_name("everything", "echo")}'
+print(one)
+# => hosted:tool/everything_echo
result = await ai.generate(prompt='Echo "hello".', tools=[one])
```
diff --git a/packages/genkit-middleware/README.md b/packages/genkit-middleware/README.md
index 3e88dece1..31c63458a 100644
--- a/packages/genkit-middleware/README.md
+++ b/packages/genkit-middleware/README.md
@@ -30,18 +30,25 @@ Import the middleware classes you need and pass instances directly into `use=[]`
```python
from genkit import Genkit
from genkit_google_genai import GoogleAI
-from genkit_middleware import Retry, Fallback, Middleware
+from genkit_middleware import Fallback, Middleware, Retry
ai = Genkit(plugins=[GoogleAI(), Middleware()])
-response = await ai.generate(
- model=GoogleAI.gemini('gemini-flash-latest'),
- prompt='Hello!',
- use=[
- Retry(max_retries=5),
- Fallback(models=['googleai/gemini-3.1-pro-preview']),
- ],
-)
+
+async def main() -> None:
+ response = await ai.generate(
+ model=GoogleAI.gemini('gemini-flash-latest'),
+ prompt='Hello!',
+ use=[
+ Retry(max_retries=5),
+ Fallback(models=['googleai/gemini-3.1-pro-preview']),
+ ],
+ )
+ print(response.text)
+
+
+if __name__ == '__main__':
+ ai.run_main(main())
```
Every middleware works when you pass an instance in `use=[]`; no plugin
@@ -58,7 +65,8 @@ uv add genkit-middleware genkit-google-genai
### Retry
-Automatically retries model calls on transient failures with configurable exponential backoff:
+Retries a failed model call with exponential backoff. A `GenkitError` is retried only
+when its status is in `statuses`; any other exception is retried:
```python
from genkit_google_genai import GoogleAI
@@ -78,11 +86,16 @@ response = await ai.generate(
prompt='Hello!',
use=[retry],
)
+print(response.text)
+# => Hello! How can I help you today?
```
### Fallback
-Falls back to alternative models on retryable errors:
+Tries each backup model in order when the primary fails with a listed `GenkitError`
+status (defaults: the transient statuses plus `NOT_FOUND` and `UNIMPLEMENTED`). Other
+exceptions are raised as-is. Order matters: `use=[Retry(...), Fallback(...)]` retries
+the whole sequence; `use=[Fallback(...), Retry(...)]` retries only the primary:
```python
from genkit_google_genai import GoogleAI
@@ -101,6 +114,8 @@ response = await ai.generate(
prompt='Hello!',
use=[fallback],
)
+print(response.text)
+# => Hello! How can I help you today?
```
### ToolApproval
@@ -118,7 +133,7 @@ class DeleteInput(BaseModel):
name: str = Field(description='Database name to delete')
-@ai.tool()
+@ai.tool
async def delete_database(input: DeleteInput) -> str:
return f'Deleted {input.name}'
@@ -136,19 +151,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, so the call fails before the model or the tool runs. It
+doesn't raise; it returns `finish_reason='failed'` with `response.error.status ==
+'FAILED_PRECONDITION'` and `response.error.reason == 'INVALID_RESUME'`.
```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:
@@ -166,6 +189,8 @@ response = await ai.generate(
prompt='Help me with Python',
use=[skills],
)
+print(response.text)
+# => Sure. Loaded python-expert. What are you working on?
```
Each direct subdirectory of a skill path that holds a `SKILL.md` is a skill, named after the directory (`skills/python-expert/SKILL.md` is `python-expert`). Frontmatter `description` shows up in the catalog; frontmatter `name` doesn't rename the skill:
@@ -200,6 +225,8 @@ response = await ai.generate(
prompt='List files in the current directory',
use=[fs],
)
+print(response.text)
+# => The workspace has menu.md and orders.csv.
```
Provides four tools:
@@ -218,12 +245,11 @@ system prompt. It only works inside an agent, so it's experimental and lives in
register it, so it isn't listed in the Dev UI and a `.prompt` file can't name it:
```python
-from genkit_middleware import Middleware
-from genkit_middleware.exp import Artifacts
-
from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore
from genkit_google_genai import GoogleAI
+from genkit_middleware import Middleware
+from genkit_middleware.exp import Artifacts
ai = Genkit(plugins=[GoogleAI(), Middleware()])
@@ -236,5 +262,6 @@ agent = ai.define_agent(
chat = agent.chat()
await chat.send('Write poem.txt with a short poem about Python agents.')
-# chat.artifacts now includes poem.txt
+print([a.name for a in chat.artifacts])
+# => ['poem.txt']
```
diff --git a/packages/genkit-middleware/src/genkit_middleware/exp/__init__.py b/packages/genkit-middleware/src/genkit_middleware/exp/__init__.py
index 1229680aa..d901b86b4 100644
--- a/packages/genkit-middleware/src/genkit_middleware/exp/__init__.py
+++ b/packages/genkit-middleware/src/genkit_middleware/exp/__init__.py
@@ -21,11 +21,25 @@
```python
from genkit.exp import Genkit
+ from genkit.exp.agent import InMemorySessionStore
+ from genkit_google_genai import GoogleAI
from genkit_middleware import Middleware
from genkit_middleware.exp import Artifacts
+ # 1. Register the plugin and pass Artifacts straight to the agent
ai = Genkit(plugins=[GoogleAI(), Middleware()])
- agent = ai.define_agent(name='workspaceAgent', model=..., use=[Artifacts()])
+ agent = ai.define_agent(
+ name='workspaceAgent',
+ model=GoogleAI.gemini('gemini-flash-latest'),
+ use=[Artifacts()],
+ store=InMemorySessionStore(),
+ )
+
+ # 2. The model writes an artifact through write_artifact
+ chat = agent.chat()
+ await chat.send('Write poem.txt with a short poem about Python agents.')
+ print([a.name for a in chat.artifacts])
+ # => ['poem.txt']
```
``Artifacts`` isn't registered by the ``Middleware()`` plugin, so it doesn't
diff --git a/packages/genkit-ollama/README.md b/packages/genkit-ollama/README.md
index 675f1feea..c9a138916 100644
--- a/packages/genkit-ollama/README.md
+++ b/packages/genkit-ollama/README.md
@@ -46,25 +46,40 @@ ai = Genkit(
model='ollama/llama3.2',
)
-response = await ai.generate(prompt='Write a haiku about local models.')
-print(response.text)
-embeddings = await ai.embed(embedder='ollama/nomic-embed-text', content='local inference')
-print(len(embeddings[0].embedding))
-```
+async def main() -> None:
+ # 1. Generate on the local server
+ response = await ai.generate(prompt='Write a haiku about local models.')
+ print(response.text)
+ # => Weights on my own disk
+ # no packet leaves the building
+ # the fan hums along
+
+ # 2. Embed with a pulled embedding model
+ embeddings = await ai.embed(embedder='ollama/nomic-embed-text', content='local inference')
+ print(len(embeddings[0].embedding))
+ # => 768
-These snippets assume an async context (`await` inside an `async def`); pasting
-them at module top level raises `SyntaxError: 'await' outside function`. See the
-[runnable sample](https://github.com/genkit-ai/genkit-python/tree/main/samples/ollama-sample)
-for a complete `async def main()` plus `ai.run_main(...)` entry point.
+
+if __name__ == '__main__':
+ ai.run_main(main())
+```
### Streaming
```python
-stream_response = ai.generate_stream(prompt='Stream a haiku about Ollama.')
-async for chunk in stream_response.stream:
- print(chunk.text, end='', flush=True)
-final = await stream_response.response
+async def main() -> None:
+ # 1. Print chunks as they arrive
+ stream_response = ai.generate_stream(prompt='Stream a haiku about Ollama.')
+ async for chunk in stream_response.stream:
+ print(chunk.text, end='', flush=True)
+ print()
+ # => Weights on my own disk ...
+
+ # 2. The final response arrives after the last chunk
+ final = await stream_response.response
+ print(final.finish_reason)
+ # => stop
```
### Tool calling
@@ -77,7 +92,7 @@ class WeatherInput(BaseModel):
city: str = Field(description='City to look up')
-@ai.tool()
+@ai.tool
async def current_weather(input: WeatherInput) -> str:
return f'{input.city} is 18°C and partly cloudy.'
@@ -87,6 +102,7 @@ response = await ai.generate(
tools=['current_weather'],
)
print(response.text)
+# => It's 18°C and partly cloudy in London.
```
Ollama tool inputs are object schemas, so wrap primitive inputs in a Pydantic
@@ -109,7 +125,9 @@ response = await ai.generate(
prompt='Write a haiku about local models.',
output_schema=Haiku,
)
-print(response.output)
+if response.output:
+ print(response.output.line_one)
+ # => Weights on my own disk
```
### Ollama-specific config (`OllamaConfig`)
diff --git a/packages/genkit-ollama/src/genkit_ollama/__init__.py b/packages/genkit-ollama/src/genkit_ollama/__init__.py
index 794b8d71e..2b080a820 100644
--- a/packages/genkit-ollama/src/genkit_ollama/__init__.py
+++ b/packages/genkit-ollama/src/genkit_ollama/__init__.py
@@ -20,8 +20,9 @@
embedders directly on your own infrastructure.
Prerequisites:
- - Install Ollama: https://ollama.ai/
- - Ensure the Ollama server is running (default: ``http://localhost:11434``).
+ - Install Ollama: https://ollama.com/download
+ - Ensure the Ollama server is running (default: ``http://127.0.0.1:11434``,
+ or ``OLLAMA_HOST``).
- Pull target models locally (e.g., ``ollama pull llama3.2``).
Example:
@@ -44,7 +45,7 @@
```
See Also:
- - Ollama documentation: https://ollama.ai/
+ - Ollama documentation: https://ollama.com/
"""
from genkit_ollama._models import OllamaConfig
diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md
index 4f10d5b75..d562d3a3b 100644
--- a/packages/genkit-openai/README.md
+++ b/packages/genkit-openai/README.md
@@ -27,11 +27,19 @@ 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())
```
Set `OPENAI_API_KEY` in the environment, or pass `api_key=` to `OpenAI()`.
@@ -54,21 +62,22 @@ before the request is sent, so a typo fails by name:
```python
res = await ai.generate(
- model='openai/gpt-4o',
+ model=OpenAI.gpt('gpt-4o'),
prompt='Write a haiku about the sea.',
config={
'temperature': 0.2,
'max_output_tokens': 200, # caps reply length
- 'extra': {'reasoning': {'effort': 'low'}}, # fields OpenAIConfig doesn't declare
+ 'extra': {'user': 'diner-42'}, # a field OpenAIConfig doesn't declare
},
)
```
- `max_output_tokens` (`maxOutputTokens` in the Dev UI) caps reply length.
It goes out as `max_tokens`, or as `max_completion_tokens` on reasoning
- models. `stop_sequences` goes out as `stop`. OpenAI's own names
- (`max_tokens`, `max_completion_tokens`, `stop`) are not declared on
- `OpenAIConfig`, so passing them at the top level raises `INVALID_ARGUMENT`.
+ models and whenever `reasoning_effort` is set. `stop_sequences` goes out as
+ `stop`. OpenAI's own names (`max_tokens`, `max_completion_tokens`, `stop`)
+ are not declared on `OpenAIConfig`, so passing them at the top level raises
+ `INVALID_ARGUMENT`.
- `extra` goes out as top-level request body fields. A key in `extra`
replaces a setting of the same name (including `max_tokens` or
`max_completion_tokens` for OpenAI-compatible servers). An API key in
@@ -78,12 +87,12 @@ res = await ai.generate(
## Per-request API key
To bill a call to someone else's OpenAI account, pass their key in
-`context.secrets`. It's used for that call only, on chat, image,
-text-to-speech, and transcription models:
+`context.secrets`. It's used for that call only, on every model and embedder
+the plugin serves:
```python
res = await ai.generate(
- model='openai/gpt-4o',
+ model=OpenAI.gpt('gpt-4o'),
prompt='hi',
context={'secrets': {'api_key': tenant_key}},
)
@@ -97,9 +106,10 @@ res = await ai.generate(
timeouts and other `default_headers` carry over. A plugin whose
`default_headers` pin `Authorization` refuses a tenant key with
`FAILED_PRECONDITION`.
-- The plugin doesn't need a key of its own for chat, image, text-to-speech,
- and transcription models: `OpenAI()` with no `OPENAI_API_KEY` serves every
- call that brings a key in `context.secrets`, and a call without one fails
- with `FAILED_PRECONDITION`.
-- Embedders run on the plugin's key only, since `ai.embed()` takes no
- `context`. On a plugin without a key they fail with `FAILED_PRECONDITION`.
+- The plugin doesn't need a key of its own: `OpenAI()` with no
+ `OPENAI_API_KEY` serves every `generate()` or `embed()` call that brings a
+ key in `context.secrets`, and a call without one fails with
+ `FAILED_PRECONDITION`.
+- Embedders read the same key:
+ `ai.embed(..., context={'secrets': {'api_key': tenant_key}})`. A call
+ without one runs on the plugin's key.
diff --git a/packages/genkit-openai/src/genkit_openai/__init__.py b/packages/genkit-openai/src/genkit_openai/__init__.py
index 8fa053f89..2d2964d8d 100644
--- a/packages/genkit-openai/src/genkit_openai/__init__.py
+++ b/packages/genkit-openai/src/genkit_openai/__init__.py
@@ -17,32 +17,41 @@
"""OpenAI-compatible model provider for Genkit.
-This plugin provides integration with OpenAI and any OpenAI-compatible API
-endpoints (such as Azure OpenAI, Together AI, or Anyscale) using the official
-OpenAI Python SDK.
+Registers OpenAI chat, image, text-to-speech, transcription, and embedding
+models under ``openai/``, using the official OpenAI Python SDK. ``base_url=``
+points it at any OpenAI-compatible server, such as Azure OpenAI or Together AI.
Example:
```python
from genkit import Genkit
from genkit_openai import OpenAI
- # 1. Initialize Genkit with OpenAI plugin
+ # 1. Initialize Genkit with the OpenAI plugin
ai = Genkit(plugins=[OpenAI()])
- # 2. Generate content using GPT-5.2
- res = await ai.generate(
- model=OpenAI.gpt('gpt-5.2'),
- prompt='Suggest 2 catchy names for an AI newsletter.',
- )
- # 3. Inspect output shapes directly
- print(res.text)
- # => 1. Prompt Daily
- # 2. Neural Notes
+ async def main() -> None:
+ # 2. Generate with GPT-5.2
+ res = await ai.generate(
+ model=OpenAI.gpt('gpt-5.2'),
+ prompt='Suggest 2 catchy names for an AI newsletter.',
+ )
+
+ # 3. Read the text
+ print(res.text)
+ # => 1. The Neural Brief
+ # 2. Prompt & Circumstance
+
+
+ if __name__ == '__main__':
+ ai.run_main(main())
```
-Requirements:
- - Requires the ``OPENAI_API_KEY`` environment variable or explicit ``api_key``.
+Credentials:
+ The plugin key comes from ``api_key=`` or ``OPENAI_API_KEY``. A
+ ``generate()`` or ``embed()`` call can bring its own key as
+ ``context={'secrets': {'api_key': ...}}``; a plugin with no key of its
+ own serves only those calls.
See Also:
- OpenAI documentation: https://platform.openai.com/docs/
diff --git a/packages/genkit-otel/README.md b/packages/genkit-otel/README.md
index 2070fac8e..d00d66e24 100644
--- a/packages/genkit-otel/README.md
+++ b/packages/genkit-otel/README.md
@@ -4,8 +4,6 @@ OpenTelemetry instrumentation and backend for [Genkit](https://github.com/genkit
It provides `GenAiInstrumentation`: OpenTelemetry GenAI semantic-conventions instrumentation emitting `gen_ai.*` spans and metrics.
-Pass `tracer` to mint on that tracer instead of the process-global one.
-
## GenAI Semantic Conventions Instrumentation
Plugs into Genkit's pluggable instrumentation system and emits telemetry that follows the
@@ -26,7 +24,7 @@ The application owns the OpenTelemetry SDK and picks its exporter. Install
them alongside this package:
```sh
-pip install genkit-otel opentelemetry-sdk opentelemetry-exporter-otlp
+uv add genkit-otel opentelemetry-sdk opentelemetry-exporter-otlp
```
Initialize the SDK, then register the provider before creating `Genkit`:
@@ -82,12 +80,10 @@ provider you built them from. `GenAiInstrumentation` can't reach it.
Prompt and response content may contain PII, so capture is off by default.
`content_capturing_mode` is one of the spec tokens:
-| Mode | Where content goes |
-| --- | --- |
-| `NO_CONTENT` (default) | not captured |
-| `SPAN_ONLY` | span attributes (`gen_ai.*.messages`) as JSON strings |
-| `EVENT_ONLY` | a `gen_ai.client.inference.operation.details` log event |
-| `SPAN_AND_EVENT` | both |
+- **`NO_CONTENT`** (default): not captured.
+- **`SPAN_ONLY`**: span attributes (`gen_ai.*.messages`) as JSON strings.
+- **`EVENT_ONLY`**: a `gen_ai.client.inference.operation.details` log event.
+- **`SPAN_AND_EVENT`**: both.
```python
from genkit_otel import GenAiInstrumentation
@@ -125,14 +121,12 @@ mode: ContentCapturingMode = 'SPAN_ONLY'
### Options
-| Option | Default | Description |
-| --- | --- | --- |
-| `content_capturing_mode` | env var, else `NO_CONTENT` | Where spec-shaped `gen_ai.*` message content is recorded. |
-| `capture_action_io` | `False` | Capture raw Genkit input/output as `genkit.input`/`genkit.output` on every span (debugging / Dev UI). |
-| `emit_metrics` | `True` | Emit token-usage and operation-duration metrics. |
-| `emit_tool_spans` | `False` | Emit `execute_tool` spans for tool actions. |
-| `scope_name` | `genkit-genai` | Instrumentation scope for tracer/meter/logger. |
-| `tracer` / `meter` / `otel_logger` | resolved lazily | Escape hatches to inject explicit instances. |
+- **`content_capturing_mode`** (env var, else `NO_CONTENT`): where spec-shaped `gen_ai.*` message content is recorded.
+- **`capture_action_io`** (`False`): records raw Genkit input/output as `genkit.input`/`genkit.output` on every span (debugging / Dev UI).
+- **`emit_metrics`** (`True`): emits token-usage and operation-duration metrics.
+- **`emit_tool_spans`** (`False`): emits `execute_tool` spans for tool actions.
+- **`scope_name`** (`genkit-genai`): instrumentation scope for the tracer, meter and logger.
+- **`tracer` / `meter` / `otel_logger`** (resolved lazily): explicit instances to use instead of the process-global ones.
## Example
diff --git a/packages/genkit-otel/src/genkit_otel/__init__.py b/packages/genkit-otel/src/genkit_otel/__init__.py
index 4553fb98f..be6dc9d24 100644
--- a/packages/genkit-otel/src/genkit_otel/__init__.py
+++ b/packages/genkit-otel/src/genkit_otel/__init__.py
@@ -29,8 +29,9 @@
from genkit.telemetry import configure_instrumentation
from genkit_otel import GenAiInstrumentation
-trace.set_tracer_provider(TracerProvider())
-trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
+provider = TracerProvider()
+provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
+trace.set_tracer_provider(provider)
configure_instrumentation(GenAiInstrumentation())
ai = Genkit()
diff --git a/packages/genkit-vertexai/README.md b/packages/genkit-vertexai/README.md
index daf427401..5dc22347f 100644
--- a/packages/genkit-vertexai/README.md
+++ b/packages/genkit-vertexai/README.md
@@ -35,14 +35,23 @@ 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.
+Authenticates with Google Cloud Application Default Credentials (ADC). The
+project comes from `project=`, then `GCLOUD_PROJECT` / `GOOGLE_CLOUD_PROJECT`,
+then the ADC project.
Every call runs on those Google Cloud credentials. A per-request key in
`context={'secrets': {'api_key': ...}}` fails with `INVALID_ARGUMENT` before
diff --git a/packages/genkit-vertexai/src/genkit_vertexai/__init__.py b/packages/genkit-vertexai/src/genkit_vertexai/__init__.py
index 3b169e745..4fe118edf 100644
--- a/packages/genkit-vertexai/src/genkit_vertexai/__init__.py
+++ b/packages/genkit-vertexai/src/genkit_vertexai/__init__.py
@@ -29,19 +29,26 @@
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:
- - Requires Google Cloud Application Default Credentials (ADC) or explicit credentials.
+ - Uses Google Cloud Application Default Credentials (ADC); there is no
+ explicit-credentials option.
- Claude models need ``genkit-vertexai[anthropic]``; Llama, Mistral, and other
OpenAI-compatible models need ``genkit-vertexai[openai]``.
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 30c3631b6..a3691dd0c 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
@@ -36,7 +39,7 @@ class Issue(BaseModel):
suggestion: str = Field(description='How to fix it')
-@ai.flow()
+@ai.flow
async def review(code: str) -> Issue:
result = await ai.generate(
prompt=f'Review this code:\n{code}',
@@ -52,6 +55,11 @@ async def review(code: str) -> Issue:
async def main() -> None:
print((await review('eval(user_input)')).model_dump_json(indent=2))
+ # => {
+ # "title": "Arbitrary code execution via eval",
+ # "severity": "critical",
+ # "suggestion": "Parse input with ast.literal_eval or a schema instead of eval."
+ # }
if __name__ == '__main__':
diff --git a/packages/genkit/src/genkit/__init__.py b/packages/genkit/src/genkit/__init__.py
index 3501ee19f..c500d1d99 100644
--- a/packages/genkit/src/genkit/__init__.py
+++ b/packages/genkit/src/genkit/__init__.py
@@ -14,10 +14,9 @@
#
# SPDX-License-Identifier: Apache-2.0
-"""Genkit — production-ready SDK for AI-powered applications.
+"""Genkit: generation, tools, structured output, flows and agents for Python.
-Build AI agents with structured generation, tool calling, streaming, and
-observability. Register plugins, define flows and tools, and run generation.
+Register plugins, define flows and tools, and run generation.
Example:
from genkit import Genkit
@@ -25,13 +24,17 @@
ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
- @ai.flow()
- async def my_flow(prompt: str) -> str:
- res = await ai.generate(prompt=prompt)
+ @ai.flow
+ async def suggest_dish(cuisine: str) -> str:
+ res = await ai.generate(prompt=f'Suggest one {cuisine} dish.')
return res.text
+ async def main() -> None:
+ print(await suggest_dish('Thai'))
+ # => Green curry with chicken
+
if __name__ == '__main__':
- ai.run_main(my_flow('Weather in Paris?'))
+ ai.run_main(main())
"""
from genkit._ai._aio import Genkit
diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py
index 4cd699c70..0a64b5aff 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.
@@ -185,17 +185,21 @@ class Genkit:
ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
- @ai.tool()
+ @ai.tool
async def current_weather(city: str) -> str:
return f'Sunny in {city}'
- @ai.flow()
- async def my_flow(prompt: str) -> str:
- res = await ai.generate(prompt=prompt, tools=['current_weather'])
+ @ai.flow
+ async def weather_report(prompt: str) -> str:
+ res = await ai.generate(prompt=prompt, tools=[current_weather])
return res.text
+ async def main() -> None:
+ print(await weather_report('Weather in Paris?'))
+ # => It's sunny in Paris.
+
if __name__ == '__main__':
- ai.run_main(my_flow('Weather in Paris?'))
+ ai.run_main(main())
"""
_registry: Registry
@@ -232,7 +236,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 +406,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:
@@ -685,14 +719,14 @@ async def lookup_model(self, name: str) -> Action[ModelRequest, ModelResponse, M
async def lookup_tool(self, name: str) -> Tool | None:
"""Return the tool registered under ``name``, or None.
- The same handle ``@ai.tool()`` returns, so a tool defined in one module
+ The same handle ``@ai.tool`` returns, so a tool defined in one module
can be called or passed in ``tools=[...]`` from another without
importing it.
Example:
```python
# 1. Define a tool in one module
- @ai.tool()
+ @ai.tool
async def menu_price(dish: str) -> float:
return 14.5
@@ -700,6 +734,7 @@ async def menu_price(dish: str) -> float:
# 2. Find it by name somewhere else
price_tool = await ai.lookup_tool('menu_price')
response = await ai.generate(prompt='How much is the ramen?', tools=[price_tool])
+ print(response.text)
# => The ramen is $14.50.
```
"""
@@ -979,6 +1014,7 @@ def define_prompt(
joke = ai.define_prompt(name='joke', prompt='Tell a joke about {{topic}}.')
res = await joke(input={'topic': 'cats'})
print(res.text)
+ # => Why did the cat sit on the keyboard? To keep an eye on the mouse.
"""
executable_prompt = Prompt(
self,
@@ -1280,7 +1316,7 @@ def run_main(self, coro: Coroutine[Any, Any, T]) -> T:
ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
- @ai.flow()
+ @ai.flow
async def suggest_dish(cuisine: str) -> str:
response = await ai.generate(prompt=f'Suggest one {cuisine} dish.')
return response.text
@@ -1573,7 +1609,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
@@ -1598,19 +1634,18 @@ class Weather(BaseModel):
res = await ai.generate(
prompt='Weather in Paris?',
- tools=['current_weather'],
+ tools=[current_weather],
output_schema=Weather,
)
- print(res.text)
- print(res.output)
+ if res.output:
+ print(res.output)
+ # => city='Paris' forecast='Sunny'
``prompt`` and ``system`` strings are sent exactly as written. Braces
- are content (JSON, code, or another template), not Handlebars. If a
- generate string used to rely on a registered partial (``{{> persona}}``),
- a ``define_helper`` helper, or ``{{media url=...}}``, move it into
- ``define_prompt`` (or a ``.prompt`` file), or build the text /
- ``Part.from_media(...)`` yourself. ``{{role}}`` in a generate string
- already raised; it now goes to the model as written too.
+ are content (JSON, code, or another template), not Handlebars.
+ Partials (``{{> persona}}``), ``define_helper`` helpers and
+ ``{{media url=...}}`` only render in ``define_prompt`` or a ``.prompt``
+ file; otherwise build the text or ``Part.from_media(...)`` yourself.
"""
return await self._generate(
model=model,
@@ -1781,11 +1816,27 @@ def generate_stream(
ending at the last complete turn, so it's safe to send back. The
chunks you already received are the record of what was shown.
+ 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='')
+ print()
+ # => 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):
@@ -1932,9 +1983,10 @@ async def embed(
``context`` reaches the embedder as ``ctx.context``, as on
``generate``. Omitted, the embedder sees the enclosing action's
- context. Provider plugins read a per-request key from
- ``context={'secrets': {'api_key': ...}}`` so the tenant, not the
- plugin key, is billed.
+ context. The GoogleAI, VertexAI and OpenAI embedders read a
+ per-request key from ``context={'secrets': {'api_key': ...}}``, so
+ the tenant, not the plugin key, is billed. Ollama and Bedrock
+ embedders always use the plugin's client.
Example:
from genkit_google_genai import GoogleAI
@@ -2003,7 +2055,21 @@ async def run(
fn: Callable[[], Awaitable[T]],
metadata: dict[str, Any] | None = None,
) -> T:
- """Run a function as a discrete traced step within a flow."""
+ """Run a coroutine function as a discrete traced step within a flow.
+
+ ``fn`` is a zero-argument ``async def`` function; each call creates its
+ own ``flowStep`` span in the trace.
+
+ Example:
+ ```python
+ # 1. Wrap a step in an async def and pass it with name= and fn=
+ async def fetch_menu() -> list[str]:
+ return await load_daily_specials()
+
+
+ menu = await ai.run(name='fetch-menu', fn=fetch_menu)
+ ```
+ """
if not inspect.iscoroutinefunction(fn):
raise TypeError('fn must be a coroutine function')
@@ -2068,7 +2134,8 @@ async def check_operation(
# 3. Poll until done; output is a ModelResponse
while not op.done:
op = await ai.check_operation(op)
- print(op.output.media.url)
+ if op.output and op.output.media:
+ print(op.output.media.url)
# => https://storage.googleapis.com/.../risotto.mp4
```
"""
diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py
index f71b53d50..5c77db936 100644
--- a/packages/genkit/src/genkit/_core/_action.py
+++ b/packages/genkit/src/genkit/_core/_action.py
@@ -243,7 +243,7 @@ class StreamResponse(Generic[ChunkT_co, OutputT_co]):
Example:
```python
- @ai.flow()
+ @ai.flow
async def track_order(order_id: str, ctx: FlowContext[str]) -> str:
ctx.send_chunk('Out for delivery')
return f'Order {order_id} delivered'
@@ -869,7 +869,7 @@ class ActionRunContext(Generic[ChunkT]):
``genkit.model.ModelContext``, and ``genkit.exp.agent.AgentContext``.
``ChunkT`` is the type ``send_chunk`` accepts.
- @ai.flow()
+ @ai.flow
async def plate_dish(dish: str, ctx: FlowContext[str]) -> str:
ctx.send_chunk('searing')
return f'{dish} for {ctx.context.get("table", "walk-in")}'
@@ -937,11 +937,11 @@ def user_id(ctx: FlowContext | ToolContext) -> str:
return ctx.context['auth']['uid']
# 2. Call it from a flow and from a tool
- @ai.flow()
+ @ai.flow
async def reorder_last(dish: str, ctx: FlowContext) -> str:
return f'{dish} for {user_id(ctx)}'
- @ai.tool()
+ @ai.tool
async def check_allergies(dish: str, ctx: ToolContext) -> str:
return f'{dish}: nut-free for {user_id(ctx)}'
diff --git a/packages/genkit/src/genkit/_core/_context.py b/packages/genkit/src/genkit/_core/_context.py
index 162522cae..b9bc22eee 100644
--- a/packages/genkit/src/genkit/_core/_context.py
+++ b/packages/genkit/src/genkit/_core/_context.py
@@ -58,7 +58,7 @@ async def django_user(request: RequestData) -> dict[str, object]:
# 2. The flow reads it from ctx.context
@genkit_django_handler(ai, context_provider=django_user)
- @ai.flow()
+ @ai.flow
async def reorder(order_id: str, ctx: FlowContext) -> str:
return f'reordered {order_id} for {ctx.context["user_id"]}'
# => reordered ORD-9921 for 42
diff --git a/packages/genkit/src/genkit/_core/_logger.py b/packages/genkit/src/genkit/_core/_logger.py
index f8ae00048..d473319a6 100644
--- a/packages/genkit/src/genkit/_core/_logger.py
+++ b/packages/genkit/src/genkit/_core/_logger.py
@@ -417,7 +417,7 @@ def get_logger(name: str | None = None) -> GenkitLogger:
# 2. Log inside a flow; lines attach to the flow's trace
- @ai.flow()
+ @ai.flow
async def lookup_menu(restaurant_id: str) -> int:
logger.info('menu lookup', restaurant_id=restaurant_id, items=12)
# => console: menu lookup restaurant_id=r-42 items=12
diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py
index b2ee78963..94ce50e81 100644
--- a/packages/genkit/src/genkit/_core/_model.py
+++ b/packages/genkit/src/genkit/_core/_model.py
@@ -1858,6 +1858,9 @@ def output(self) -> OutputT | None:
values that already match a member (even if more digits may follow).
``(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
@@ -1974,7 +1977,7 @@ class MultipartToolResponse(GenkitModel, Generic[OutputT]):
Example:
```python
- @ai.tool()
+ @ai.tool
async def screenshot(label: str) -> MultipartToolResponse[Shot]:
return MultipartToolResponse(output=Shot(label=label), content=[png])
```
diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py
index 7bffd5fe0..c65749d1f 100644
--- a/packages/genkit/src/genkit/_core/_tool.py
+++ b/packages/genkit/src/genkit/_core/_tool.py
@@ -246,7 +246,7 @@ class ToolContext(ActionRunContext[ChunkT]):
Annotate a tool parameter with it to receive it:
- @ai.tool()
+ @ai.tool
async def check_allergens(dish: str, ctx: ToolContext) -> str:
return 'resumed' if ctx.is_resumed() else ctx.context.get('user', 'guest')
@@ -258,12 +258,26 @@ def user_id(ctx: FlowContext | ToolContext) -> str:
return ctx.context['auth']['uid']
# 2. Call it from the tool
- @ai.tool()
+ @ai.tool
async def list_allergies(guest: str, ctx: ToolContext) -> str:
return f'{guest} ({user_id(ctx)}): shellfish'
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
+ ``resumed_metadata is None`` so static type checkers narrow the dict:
+
+ @ai.tool
+ async def refund_order(order_id: str, ctx: ToolContext) -> str:
+ # Interrupt is exported from genkit
+ if ctx.resumed_metadata is None:
+ 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
@@ -410,7 +428,7 @@ def __init__(
) -> None:
"""Build a tool from an async function without registering it.
- ``define_tool`` / ``@ai.tool()`` register it. Passed straight to
+ ``define_tool`` / ``@ai.tool`` register it. Passed straight to
``generate(tools=[...])``, it is an ephemeral tool for that call.
Args:
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/samples/README.md b/samples/README.md
index 0796674cc..edc8e2c8d 100644
--- a/samples/README.md
+++ b/samples/README.md
@@ -1,6 +1,6 @@
# Samples
-Snippets you can run tonight. Most need `GEMINI_API_KEY`.
+Each folder runs one feature end to end. Most need `GEMINI_API_KEY`.
```bash
cd samples/
@@ -8,6 +8,8 @@ uv sync
uv run src/main.py
```
+Web-framework samples (flask-hello, django-hello) list their own server command.
+
For traces while it runs:
```bash
diff --git a/samples/agents/.gitignore b/samples/agents/.gitignore
new file mode 100644
index 000000000..2c4338f13
--- /dev/null
+++ b/samples/agents/.gitignore
@@ -0,0 +1,4 @@
+# Runtime state the samples write next to themselves.
+.snapshots*/
+testapp/workspace/
+basic/.workspaces/
diff --git a/samples/agents/basic/01_define_agent_with_store.py b/samples/agents/basic/01_define_agent_with_store.py
index 94655fd57..1820720e2 100644
--- a/samples/agents/basic/01_define_agent_with_store.py
+++ b/samples/agents/basic/01_define_agent_with_store.py
@@ -21,7 +21,7 @@
restart, ``load_chat(snapshot_id=...)`` rehydrates the conversation and the
agent still remembers turn 1.
-These samples use ``InMemorySessionStore`` so they run tonight. The same
+These samples use ``InMemorySessionStore`` so they run without GCP. The same
``store=`` slot takes ``FirestoreSessionStore`` from ``genkit_google_cloud.exp``
when you ship (install ``genkit-google-cloud[firestore]``). Requires GEMINI_API_KEY.
"""
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/agents/basic/07_artifacts_custom_patch.py b/samples/agents/basic/07_artifacts_custom_patch.py
index 335c44391..117763e94 100644
--- a/samples/agents/basic/07_artifacts_custom_patch.py
+++ b/samples/agents/basic/07_artifacts_custom_patch.py
@@ -21,10 +21,9 @@
insights count) via a typed model while continuously building an executive briefing
artifact (`research_brief.md`).
-Declaring a ``state_schema`` means custom state comes back as a typed model — so
-``chat.state``, ``response.state``, and each streamed ``chunk.custom`` are a ``ResearchState``
-with typed attribute access. This demonstrates how live state patches and session
-artifacts work together in a real-world custom agent workflow. Requires GEMINI_API_KEY.
+Declaring a ``state_schema`` types the client view: ``chat.state``,
+``response.state``, and each streamed ``chunk.custom`` come back as
+``ResearchState``. Requires GEMINI_API_KEY.
"""
from __future__ import annotations
@@ -67,7 +66,7 @@ async def handle_turn(inp: AgentInput, _: TurnContext) -> TurnResult | None:
prompt_text += p.text
topic = prompt_text.strip() or 'General Overview'
- # 1. Update custom state (typed ResearchState model)
+ # 1. Update custom state (a dict on the server; the client reads it back as ResearchState)
await sess.update_custom(
lambda c: {
'topics_explored': [*(c or {}).get('topics_explored', []), topic[:40]],
diff --git a/samples/agents/basic/09_detach.py b/samples/agents/basic/09_detach.py
index b71dc2e0b..6efada0a9 100644
--- a/samples/agents/basic/09_detach.py
+++ b/samples/agents/basic/09_detach.py
@@ -55,15 +55,8 @@ class JobState(BaseModel):
store = InMemorySessionStore()
-@ai.tool(name='slowWork', description='Simulate long background work.')
-async def slow_work(_: dict) -> dict:
- for _i in range(10):
- await asyncio.sleep(0.5) # pretend each step is real work
- return {'done': True}
-
-
async def long_task_fn(sess: SessionRunner, _: AgentContext) -> AgentResult:
- # Define tool inside turn handler closure so it can mutate custom session state on each step:
+ # Define the tool inside the agent fn so it can write this session's custom state on each step.
@ai.tool(name='slowWork', description='Simulate long background work.')
async def slow_work_closure(_: dict) -> dict:
for i in range(1, 11):
diff --git a/samples/agents/basic/12_abort_client_and_server.py b/samples/agents/basic/12_abort_client_and_server.py
index ebb66edce..aa03033b2 100644
--- a/samples/agents/basic/12_abort_client_and_server.py
+++ b/samples/agents/basic/12_abort_client_and_server.py
@@ -88,9 +88,9 @@ async def main() -> None:
await asyncio.sleep(2.0) # let the tool start churning
# chat.abort() cancels slowWork on the server. The call returns the
- # previous status (PENDING) — not ABORTED. The prompt stays in history;
- # it was still asked. Reload before the next send() so you are not still
- # pointed at the aborted leaf.
+ # previous status (PENDING), not ABORTED. The prompt stays in history;
+ # it was still asked. Continue with worker.chat(session_id=...) before the
+ # next send() so you are not pointed at the aborted leaf.
status = await worker_chat.abort()
assert status == SnapshotStatus.PENDING
await asyncio.sleep(0.5) # let the background task unwind
diff --git a/samples/agents/basic/13_deadline_timeout.py b/samples/agents/basic/13_deadline_timeout.py
index 05e96996c..64028566d 100644
--- a/samples/agents/basic/13_deadline_timeout.py
+++ b/samples/agents/basic/13_deadline_timeout.py
@@ -21,7 +21,7 @@
it: wrap `await turn.response` (or the `.stream`) in `asyncio.wait_for(...)`, or
cancel the surrounding task, and the turn detaches just like turn.abort() — the client
stops listening, the server finishes in the background, and the prompt you sent
-stays in history. The deadline then surfaces as TimeoutError. Requires
+stays in history. The deadline then surfaces as asyncio.TimeoutError. Requires
GEMINI_API_KEY.
"""
diff --git a/samples/agents/basic/14_abort_failure_store_drift.py b/samples/agents/basic/14_abort_failure_store_drift.py
index 2f0407927..c5b64037e 100644
--- a/samples/agents/basic/14_abort_failure_store_drift.py
+++ b/samples/agents/basic/14_abort_failure_store_drift.py
@@ -24,7 +24,7 @@
1. turn.abort() — a *client-side* detach. You stop listening, but the server
turn keeps running and completes. The store shows a finished turn with no
trace of the abort, while your in-memory chat is left holding an unanswered
- prompt. The client view drifts ahead of (really, behind) the store.
+ prompt. The client view now lags the store.
2. task.abort() — a *server-side* cancel of a detached turn. The snapshot
settles ABORTED and never becomes the session's resume point. abort()
@@ -136,8 +136,8 @@ async def server_side_task_abort() -> None:
status = await task.abort()
# abort() returns the *previous* status: pending, because the turn was still running.
assert status == SnapshotStatus.PENDING
- # The prompt stays — it was still asked. The chat still points at the
- # aborted leaf, so a send returns res.error until you reload.
+ # The prompt stays; it was still asked. The chat still points at the
+ # aborted leaf, so a send returns res.error until you switch to chat(session_id=).
assert turns(chat) == ['a1/user', 'reply/model', 'slow a2/user']
# The store's session leaf is that aborted row; chat(session_id=) is how
diff --git a/samples/agents/basic/17_client_transform.py b/samples/agents/basic/17_client_transform.py
index 5948bc3e4..797c9b1d6 100644
--- a/samples/agents/basic/17_client_transform.py
+++ b/samples/agents/basic/17_client_transform.py
@@ -27,8 +27,10 @@
drop it.
Here the agent keeps an api_key in its custom state and emits an internal
-artifact, but the client sees neither: state strips the key, chunk drops the
-artifact. Requires GEMINI_API_KEY.
+artifact. state_transform strips the key from every state the client reads.
+chunk_transform drops the artifact chunk from the stream, but the settled
+output still lists session artifacts, so filter those in the agent fn if they
+must never leave the server. Requires GEMINI_API_KEY.
"""
from __future__ import annotations
@@ -116,7 +118,7 @@ async def main() -> None:
assert 'api_key' not in chunk.custom
res = await turn.response
- # chunk hook dropped every artifact chunk before it reached us.
+ # chunk hook dropped the artifact chunk from the stream (res.artifacts still lists it).
assert not saw_artifact_chunk
# state hook stripped the secret but kept the public counter.
assert res.state is not None
diff --git a/samples/agents/testapp/README.md b/samples/agents/testapp/README.md
index 560020d8a..20f39fa26 100644
--- a/samples/agents/testapp/README.md
+++ b/samples/agents/testapp/README.md
@@ -1,7 +1,7 @@
# Agent backend
A FastAPI process with the agents in this folder mounted at `/api/`.
-Sessions stay in memory or on disk so it runs on `GEMINI_API_KEY` tonight.
+Sessions stay in memory or on disk, so it runs on `GEMINI_API_KEY` alone.
Swap in `FirestoreSessionStore()` from `genkit_google_cloud.exp` when you
deploy; it needs `uv add 'genkit-google-cloud[firestore]'`.
diff --git a/samples/agents/testapp/_ai.py b/samples/agents/testapp/_ai.py
index 2ee684593..f021cc49b 100644
--- a/samples/agents/testapp/_ai.py
+++ b/samples/agents/testapp/_ai.py
@@ -18,7 +18,7 @@
Each agent file registers itself on this ``ai`` the moment it's imported, so the
Dev UI (running a single file) and the FastAPI server (importing all of them)
-both see the same registry. Same idea as the JS testapp's ``genkit.ts``.
+both see the same registry.
Requires GEMINI_API_KEY.
"""
diff --git a/samples/agents/testapp/background_agent.py b/samples/agents/testapp/background_agent.py
index 233113c2d..ed0ebc1ab 100644
--- a/samples/agents/testapp/background_agent.py
+++ b/samples/agents/testapp/background_agent.py
@@ -45,7 +45,7 @@
)
-@ai.flow()
+@ai.flow
async def test_background_agent(text: str, ctx: FlowContext) -> dict[str, Any]:
"""Detach a report, poll to completion, and return the settled status."""
chat = background_agent.chat()
diff --git a/samples/agents/testapp/banking_agent.py b/samples/agents/testapp/banking_agent.py
index e2c4810d9..0ddf6ebdd 100644
--- a/samples/agents/testapp/banking_agent.py
+++ b/samples/agents/testapp/banking_agent.py
@@ -79,7 +79,7 @@ async def transfer_money(_input: TransferInput) -> TransferOutput:
)
-@ai.flow()
+@ai.flow
async def test_banking_agent(text: str, ctx: FlowContext) -> dict[str, Any]:
"""Run a turn that pauses for approval, approve it, then let the transfer land."""
chat = banking_agent.chat()
diff --git a/samples/agents/testapp/branching_agent.py b/samples/agents/testapp/branching_agent.py
index b81b6806a..1f0719df0 100644
--- a/samples/agents/testapp/branching_agent.py
+++ b/samples/agents/testapp/branching_agent.py
@@ -41,7 +41,7 @@
)
-@ai.flow()
+@ai.flow
async def test_branching_agent(text: str, ctx: FlowContext) -> dict[str, Any]:
"""Establish a root turn, then fork two branches off the same snapshot."""
root = branching_agent.chat()
diff --git a/samples/agents/testapp/client_state_agent.py b/samples/agents/testapp/client_state_agent.py
index 65221a096..3c4cf79c0 100644
--- a/samples/agents/testapp/client_state_agent.py
+++ b/samples/agents/testapp/client_state_agent.py
@@ -33,6 +33,7 @@
from weather_agent import get_weather # reuse the same tool
from genkit import FlowContext
+from genkit.exp.agent import SessionState
# No store → client-managed. The turn returns the full state; the caller echoes
# it back next time. Nothing about the conversation lives on the server.
@@ -49,10 +50,14 @@ class StatelessTurn(BaseModel):
text: str = 'What is the weather in Tokyo?'
-@ai.flow()
+@ai.flow
async def test_weather_agent_stateless(input: StatelessTurn, ctx: FlowContext) -> dict[str, Any]:
"""Resume from the client-held state (or start fresh), then hand it back."""
- chat = weather_agent_stateless.chat(state=input.state) if input.state else weather_agent_stateless.chat()
+ if input.state:
+ prev = SessionState.model_validate(input.state)
+ chat = weather_agent_stateless.chat(messages=prev.messages, artifacts=prev.artifacts, state=prev.custom)
+ else:
+ chat = weather_agent_stateless.chat()
turn = chat.send_stream(input.text)
async for chunk in turn:
if chunk.text:
diff --git a/samples/agents/testapp/coding_agent.py b/samples/agents/testapp/coding_agent.py
index 40f9526ae..b1d74edc1 100644
--- a/samples/agents/testapp/coding_agent.py
+++ b/samples/agents/testapp/coding_agent.py
@@ -34,7 +34,7 @@
from _ai import ai, reply_text
from genkit_middleware import Filesystem, ToolApproval
-from genkit import FlowContext
+from genkit import FlowContext, PublicError
from genkit.exp.agent import FileSessionStore
WORKSPACE_DIR = Path(__file__).resolve().parent / 'workspace'
@@ -61,7 +61,7 @@
)
-@ai.flow()
+@ai.flow
async def test_coding_agent(text: str, ctx: FlowContext) -> str:
"""Auto-approve every write so the agent can finish a task unattended."""
chat = coding_agent.chat()
@@ -102,18 +102,20 @@ def _walk(directory: Path) -> list[dict[str, Any]]:
return entries
-@ai.flow()
+@ai.flow
async def list_workspace_files(_: Any = None) -> dict[str, Any]:
"""The file tree the web UI renders beside the chat."""
return {'files': _walk(WORKSPACE_DIR)}
-@ai.flow()
+@ai.flow
async def read_workspace_file(path: str) -> dict[str, str]:
"""Read one file, refusing anything that tries to climb out of the workspace."""
full = (WORKSPACE_DIR / path).resolve()
if os.path.commonpath([str(full), str(WORKSPACE_DIR)]) != str(WORKSPACE_DIR):
- raise ValueError('Path outside workspace')
+ raise PublicError('INVALID_ARGUMENT', 'Path outside workspace')
+ if not full.is_file():
+ raise PublicError('NOT_FOUND', f'No such file: {path}')
return {'path': path, 'content': full.read_text()}
diff --git a/samples/agents/testapp/file_store_agent.py b/samples/agents/testapp/file_store_agent.py
index 583070cd9..7bb960e7b 100644
--- a/samples/agents/testapp/file_store_agent.py
+++ b/samples/agents/testapp/file_store_agent.py
@@ -70,7 +70,7 @@ class FileStoreResult(BaseModel):
reply2: str
-@ai.flow()
+@ai.flow
async def test_file_store_agent(user_name: str, ctx: FlowContext) -> FileStoreResult:
"""Two turns on one chat: the note logged in turn 1 is recalled in turn 2."""
chat = file_store_agent.chat()
@@ -90,7 +90,7 @@ async def test_file_store_agent(user_name: str, ctx: FlowContext) -> FileStoreRe
return FileStoreResult(snapshot_id1=res1.snapshot_id, reply1=reply_text(res1), reply2=reply_text(res2))
-@ai.flow()
+@ai.flow
async def test_file_store_chain_pruning(user_name: str, ctx: FlowContext) -> dict[str, Any]:
"""Run four turns against the capped store and report what survived on disk.
diff --git a/samples/agents/testapp/orchestrator_agent.py b/samples/agents/testapp/orchestrator_agent.py
index 8d5ef3e55..cc4c9119c 100644
--- a/samples/agents/testapp/orchestrator_agent.py
+++ b/samples/agents/testapp/orchestrator_agent.py
@@ -72,7 +72,7 @@ async def delegate_to_coder(input: Task) -> str:
)
-@ai.flow()
+@ai.flow
async def test_orchestrator_agent(text: str, ctx: FlowContext) -> str:
chat = orchestrator_agent.chat()
turn = chat.send_stream(text or 'Research quicksort, then write a Python implementation of it.')
diff --git a/samples/agents/testapp/research_agent.py b/samples/agents/testapp/research_agent.py
index 6ee34414e..37cfde595 100644
--- a/samples/agents/testapp/research_agent.py
+++ b/samples/agents/testapp/research_agent.py
@@ -110,10 +110,10 @@ async def handle_turn(inp: AgentInput, _: TurnContext) -> TurnResult | None:
research_agent = ai.define_custom_agent(name='researchAgent', fn=research_fn, state_schema=ResearchState)
-@ai.flow()
+@ai.flow
async def test_research_agent(text: str, ctx: FlowContext) -> str:
"""Watch the status line advance (chunk.custom) while the answer streams in."""
- chat = research_agent.chat(state={'custom': {'status': '', 'sub_questions': []}, 'messages': [], 'artifacts': []})
+ chat = research_agent.chat()
turn = chat.send_stream(text or 'What are the environmental and economic impacts of electric vehicles?')
async for chunk in turn:
if chunk.custom is not None and chunk.custom.status:
diff --git a/samples/agents/testapp/task_agent.py b/samples/agents/testapp/task_agent.py
index 8eebb2677..d3f932209 100644
--- a/samples/agents/testapp/task_agent.py
+++ b/samples/agents/testapp/task_agent.py
@@ -134,10 +134,10 @@ def mutate(custom: dict[str, Any] | None) -> dict[str, Any]:
)
-@ai.flow()
+@ai.flow
async def test_task_agent(text: str, ctx: FlowContext) -> dict[str, Any]:
- """Seed an empty list, run one turn, and hand back the live typed state."""
- chat = task_agent.chat(state={'custom': {'tasks': [], 'next_id': 1}, 'messages': [], 'artifacts': []})
+ """Run one turn on an empty list and hand back the live typed state."""
+ chat = task_agent.chat()
turn = chat.send_stream(text or 'Add a task: buy groceries')
async for chunk in turn:
if chunk.text:
diff --git a/samples/agents/testapp/trip_planner_agent.py b/samples/agents/testapp/trip_planner_agent.py
index d6dd1b379..94c399592 100644
--- a/samples/agents/testapp/trip_planner_agent.py
+++ b/samples/agents/testapp/trip_planner_agent.py
@@ -70,7 +70,7 @@ async def get_flight_info(input: FlightInput) -> dict[str, list[str]]:
)
-@ai.flow()
+@ai.flow
async def test_trip_planner_agent(text: str, ctx: FlowContext) -> str:
chat = trip_planner_agent.chat()
turn = chat.send_stream(text or 'I want to plan a trip to Paris. What should I see there?')
diff --git a/samples/agents/testapp/weather_agent.py b/samples/agents/testapp/weather_agent.py
index c5f6a8728..0d0c8427b 100644
--- a/samples/agents/testapp/weather_agent.py
+++ b/samples/agents/testapp/weather_agent.py
@@ -62,7 +62,7 @@ async def get_weather(input: WeatherInput) -> WeatherOutput:
)
-@ai.flow()
+@ai.flow
async def test_weather_agent(text: str, ctx: FlowContext) -> str:
"""One streamed turn. Tools light up as they're called; text streams as it lands."""
chat = weather_agent.chat()
@@ -77,7 +77,7 @@ async def test_weather_agent(text: str, ctx: FlowContext) -> str:
return reply_text(res)
-@ai.flow()
+@ai.flow
async def test_weather_agent_stream(text: str, ctx: FlowContext) -> str:
"""Multi-turn: one chat carries history across turns, so the follow-up just knows."""
chat = weather_agent.chat()
diff --git a/samples/agents/testapp/workspace_agent.py b/samples/agents/testapp/workspace_agent.py
index b267db0db..2ee3379b3 100644
--- a/samples/agents/testapp/workspace_agent.py
+++ b/samples/agents/testapp/workspace_agent.py
@@ -61,7 +61,7 @@ async def write_artifact(input: WriteArtifactInput) -> dict[str, str]:
)
-@ai.flow()
+@ai.flow
async def test_workspace_agent(text: str, ctx: FlowContext) -> dict[str, Any]:
"""Ask for a file; watch it arrive as an artifact chunk, then in chat.artifacts."""
chat = workspace_agent.chat()
diff --git a/samples/amazon-bedrock-sample/src/main.py b/samples/amazon-bedrock-sample/src/main.py
index 4dcc08df2..6a08a5cc6 100644
--- a/samples/amazon-bedrock-sample/src/main.py
+++ b/samples/amazon-bedrock-sample/src/main.py
@@ -38,7 +38,7 @@ class CityInput(BaseModel):
city: str
-@ai.tool()
+@ai.tool
async def current_weather(input: CityInput) -> str:
return f'The weather in {input.city} is 31C and humid.'
diff --git a/samples/anthropic-sample/src/main.py b/samples/anthropic-sample/src/main.py
index 96f94ea45..94c6eef50 100644
--- a/samples/anthropic-sample/src/main.py
+++ b/samples/anthropic-sample/src/main.py
@@ -45,12 +45,15 @@ async def main() -> None:
)
print(cat.output)
- # thinking= is how you see the model's reasoning stream.
+ # thinking= streams reasoning parts on chunk.content ahead of the answer.
stream = ai.generate_stream(
prompt='What is 17 * 23? Think it through, then state the answer.',
- config={'thinking': 'enabled', 'thinkingBudget': 1024},
+ config={'thinking': 'enabled', 'thinking_budget': 1024},
)
async for chunk in stream.stream:
+ for part in chunk.content:
+ if part.reasoning:
+ print(part.reasoning, end='', flush=True)
if chunk.text:
print(chunk.text, end='', flush=True)
print()
diff --git a/samples/basic-flows/src/main.py b/samples/basic-flows/src/main.py
index 76b98139b..2bc2bb440 100644
--- a/samples/basic-flows/src/main.py
+++ b/samples/basic-flows/src/main.py
@@ -32,7 +32,7 @@ class StatusChunk(BaseModel):
label: str
-@ai.flow()
+@ai.flow
async def welcome(name: str) -> str:
# ai.run names a step so it shows up as its own span when something
# looks wrong. Nested flows nest the same way.
@@ -47,7 +47,7 @@ async def draft() -> str:
return await ai.run(name='draft', fn=draft)
-@ai.flow()
+@ai.flow
async def status(count: int, ctx: FlowContext[StatusChunk]) -> str:
# send_chunk is what Dev UI and the HTTP stream paint as progress.
for i in range(count):
@@ -56,7 +56,7 @@ async def status(count: int, ctx: FlowContext[StatusChunk]) -> str:
return f'done after {count} updates'
-@ai.flow()
+@ai.flow
async def whoami(name: str, ctx: FlowContext) -> str:
# Request context (auth, tenant) lands here, not as extra args.
return f'{name} as {ctx.context}'
diff --git a/samples/context/src/main.py b/samples/context/src/main.py
index 142c8310b..517695b12 100644
--- a/samples/context/src/main.py
+++ b/samples/context/src/main.py
@@ -34,7 +34,7 @@ class AccountNeed(BaseModel):
need: str
-@ai.tool()
+@ai.tool
async def account_record(input: AccountNeed, ctx: ToolContext) -> str:
# Tenant is not a tool argument, so a prompt cannot hop to another customer.
key = (str(ctx.context.get('user_id', '')), str(ctx.context.get('tenant_id', '')))
diff --git a/samples/django-hello/recipes/views.py b/samples/django-hello/recipes/views.py
index d903d10ff..930c2389b 100644
--- a/samples/django-hello/recipes/views.py
+++ b/samples/django-hello/recipes/views.py
@@ -39,7 +39,7 @@ async def auth_context(request: RequestData) -> dict[str, object]:
@genkit_django_handler(ai, context_provider=auth_context)
-@ai.flow()
+@ai.flow
async def say_hi(input: SayHiInput, ctx: FlowContext) -> ModelResponse:
username = ctx.context.get('username', 'guest')
stream = ai.generate_stream(
diff --git a/samples/flask-hello/README.md b/samples/flask-hello/README.md
index 1db50844d..034fba998 100644
--- a/samples/flask-hello/README.md
+++ b/samples/flask-hello/README.md
@@ -9,7 +9,8 @@ uv run src/main.py
```
```bash
-curl -X POST http://localhost:8080/say_hi \
+curl -N -X POST http://localhost:8080/say_hi \
-H 'Content-Type: application/json' \
+ -H 'Accept: text/event-stream' \
-d '{"data":"Mittens"}'
```
diff --git a/samples/flask-hello/src/main.py b/samples/flask-hello/src/main.py
index 130838437..ae50d9e8b 100755
--- a/samples/flask-hello/src/main.py
+++ b/samples/flask-hello/src/main.py
@@ -31,7 +31,7 @@
@app.post('/say_hi')
@genkit_flask_handler(ai)
-@ai.flow()
+@ai.flow
async def say_hi(name: str, ctx: FlowContext) -> str:
# generate_stream + send_chunk is how the Flask handler streams tokens.
stream = ai.generate_stream(prompt=f'tell a short joke about {name}')
diff --git a/samples/gemini-context-caching/README.md b/samples/gemini-context-caching/README.md
index 2c9ba9ba7..883826681 100644
--- a/samples/gemini-context-caching/README.md
+++ b/samples/gemini-context-caching/README.md
@@ -8,4 +8,5 @@ uv sync
uv run src/main.py
```
-The second call prints `cached_content_tokens`.
+Each call prints `cached_content_tokens`: the first call creates the cache,
+and every question after it sends only its own tokens.
diff --git a/samples/gemini-context-caching/src/main.py b/samples/gemini-context-caching/src/main.py
index 62d435fac..4ad8108c2 100755
--- a/samples/gemini-context-caching/src/main.py
+++ b/samples/gemini-context-caching/src/main.py
@@ -25,9 +25,9 @@
ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-3-flash-preview'))
handbook = (Path(__file__).resolve().parent.parent / 'handbook.md').read_text()
-# Gemini only caches prefixes past ~180k characters. A real handbook is
-# already that long; this stand-in is padded so the second call shows
-# cached_content_tokens.
+# Gemini only caches prefixes above a per-model minimum token count. A real
+# handbook is already that long; this stand-in is padded so
+# cached_content_tokens shows up.
handbook = handbook + ('\n# appendix\n' * 20_000)
# The cache lives on the model turn of this prefix. Later generate()
diff --git a/samples/google-genai-deep-research/src/main.py b/samples/google-genai-deep-research/src/main.py
index bf0c87131..7c2e613aa 100644
--- a/samples/google-genai-deep-research/src/main.py
+++ b/samples/google-genai-deep-research/src/main.py
@@ -58,7 +58,7 @@ async def deep_research_flow(input: ResearchInput) -> dict[str, str | bool | Non
async def main() -> None:
"""Start one Deep Research job and check it once — does not wait for the report."""
- print(await deep_research_flow(ResearchInput())) # noqa: T201
+ print(await deep_research_flow(ResearchInput()))
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/google-genai-media/src/main.py b/samples/google-genai-media/src/main.py
index 997755245..9345208a6 100644
--- a/samples/google-genai-media/src/main.py
+++ b/samples/google-genai-media/src/main.py
@@ -32,18 +32,20 @@ async def main() -> None:
prompt='Welcome to the Genkit media sample.',
config={'voice': 'Kore'},
)
- print(voice.media.url if voice.media else 'no audio')
+ print(voice.media.url[:60] if voice.media else 'no audio')
+ # => data:audio/L16;codec=pcm;rate=24000;base64,...
# Image: same generate(), different model.
poster = await ai.generate(
model=GoogleAI.gemini_image('gemini-2.5-flash-image'),
prompt='A watercolor postcard of San Francisco at sunrise',
)
- print(poster.media.url if poster.media else 'no image')
+ print(poster.media.url[:60] if poster.media else 'no image')
+ # => data:image/png;base64,...
# Video is a job, not a round-trip. generate_operation hands back a
# ticket; check_operation is how you find out when the video is ready.
- # Vertex often returns the mp4 inline; operation.output still has a url.
+ # Vertex often returns the mp4 inline, so media.url can be a data: URL.
operation = await ai.generate_operation(
model=VertexAI.veo('veo-3.1-generate-001'),
prompt='A paper airplane gliding through a bright classroom',
@@ -51,7 +53,9 @@ async def main() -> None:
while not operation.done:
await asyncio.sleep(3)
operation = await ai.check_operation(operation)
- print(operation.output)
+ video = operation.output.media if operation.output else None
+ print(video.url[:60] if video else operation.error)
+ # => data:video/mp4;base64,...
if __name__ == '__main__':
diff --git a/samples/mcp-hello/src/main.py b/samples/mcp-hello/src/main.py
index 2ab536faa..17904cd8b 100644
--- a/samples/mcp-hello/src/main.py
+++ b/samples/mcp-hello/src/main.py
@@ -37,7 +37,7 @@
)
-@ai.flow()
+@ai.flow
async def browse_shelves(topic: str) -> str:
"""Shop for a book on a topic with every bookshop tool on offer."""
res = await ai.generate(
@@ -47,7 +47,7 @@ async def browse_shelves(topic: str) -> str:
return res.text
-@ai.flow()
+@ai.flow
async def ask_opening_hours(day: str) -> str:
"""Ask about a day's opening hours with just the one tool that answers it."""
res = await ai.generate(
diff --git a/samples/middleware/src/main.py b/samples/middleware/src/main.py
index 18be059d0..ffee436fe 100644
--- a/samples/middleware/src/main.py
+++ b/samples/middleware/src/main.py
@@ -22,14 +22,38 @@
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_value(value: object) -> object:
+ if isinstance(value, str):
+ return _redact(value)
+ if isinstance(value, BaseModel):
+ return _redact_value(value.model_dump())
+ if isinstance(value, dict):
+ return {_redact_value(k): _redact_value(v) for k, v in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [_redact_value(item) for item in value]
+ return value
+
+
+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 +62,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 result.output is not None:
+ update['output'] = _redact_value(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__':
diff --git a/samples/multipart-tools/src/main.py b/samples/multipart-tools/src/main.py
index c542bbc58..b43222ec3 100644
--- a/samples/multipart-tools/src/main.py
+++ b/samples/multipart-tools/src/main.py
@@ -42,20 +42,22 @@ class PrepProgress(BaseModel):
percent: int
-# A tool takes one input; several fields go on one model the model fills in.
-@ai.tool()
+# A tool takes one input. For several fields, wrap them in one Pydantic model.
+# A bare return is wrapped as output-only.
+@ai.tool
async def weather(input: WeatherInput) -> str:
- """Look up the weather. A bare return is wrapped as output-only."""
+ """Look up the current weather for a city."""
return f'Sunny and 22{input.unit} in {input.city}'
-@ai.tool()
+# Return MultipartToolResponse to send the PNG next to the output.
+@ai.tool
async def screenshot(label: str) -> MultipartToolResponse:
- """Take a screenshot. Return ``MultipartToolResponse`` to send the PNG with the output."""
+ """Take a screenshot of the lab camera."""
return MultipartToolResponse(output={'ok': True, 'label': label}, content=[_PNG], metadata={'src': 'lab-cam'})
-@ai.tool()
+@ai.tool
async def prepare_order(dish: str, ctx: ToolContext[PrepProgress]) -> str:
"""Prepare a dish and emit live progress updates before returning."""
ctx.send_chunk(PrepProgress(stage_name='searing', percent=40))
@@ -65,7 +67,7 @@ async def prepare_order(dish: str, ctx: ToolContext[PrepProgress]) -> str:
return f'{dish} ready'
-@ai.flow()
+@ai.flow
async def ask_about_the_lab() -> str:
res = await ai.generate(
prompt='What is the weather in Austin, and take a screenshot of the lab camera.',
@@ -74,13 +76,14 @@ async def ask_about_the_lab() -> str:
return res.text
-@ai.flow()
+@ai.flow
async def prep_with_progress(dish: str, ctx: FlowContext[PrepProgress]) -> str:
stream = ai.generate_stream(prompt=f'Prepare {dish}.', tools=[prepare_order])
- async for chunk in stream:
- for part in chunk.tool_responses:
- if part.is_partial and part.tool_response is not None:
- ctx.send_chunk(PrepProgress.model_validate(part.tool_response.output))
+ async with stream.stream as chunks:
+ async for chunk in chunks:
+ for part in chunk.tool_responses:
+ if part.is_partial and part.tool_response is not None:
+ ctx.send_chunk(PrepProgress.model_validate(part.tool_response.output))
return (await stream.response).text
@@ -88,8 +91,9 @@ async def main() -> None:
print(await ask_about_the_lab())
stream = prep_with_progress.stream('smoked salmon tartine')
- async for progress in stream:
- print(f'[{progress.percent}%] {progress.stage_name}')
+ async with stream.stream as chunks:
+ async for progress in chunks:
+ print(f'[{progress.percent}%] {progress.stage_name}')
print(await stream.response)
diff --git a/samples/ollama-sample/src/main.py b/samples/ollama-sample/src/main.py
index 6a80837cb..3817fe026 100644
--- a/samples/ollama-sample/src/main.py
+++ b/samples/ollama-sample/src/main.py
@@ -36,7 +36,7 @@ class WeatherInput(BaseModel):
city: str
-@ai.tool()
+@ai.tool
async def current_weather(input: WeatherInput) -> str:
return f'The weather in {input.city} is 18C and partly cloudy.'
@@ -55,8 +55,7 @@ async def main() -> None:
raise SystemExit(1)
print(response.text)
- # Ollama streams text on the chunks and returns an empty final
- # message, so join the chunks instead of reading response.text.
+ # Chunks print as Ollama streams them; stream.response holds the joined text.
stream = ai.generate_stream(prompt='One sentence on why local models matter.')
async for chunk in stream.stream:
if chunk.text:
diff --git a/samples/otel-jaeger/README.md b/samples/otel-jaeger/README.md
index baf4034b5..d7c00e52e 100644
--- a/samples/otel-jaeger/README.md
+++ b/samples/otel-jaeger/README.md
@@ -1,15 +1,15 @@
# Genkit OpenTelemetry sample (Jaeger)
-Demonstrates `genkit-otel`: OpenTelemetry GenAI semantic-conventions
-instrumentation for Genkit. Traces go to Jaeger, metrics (token usage and
-operation duration) go to a local collector's debug log.
+`genkit-otel` emitting OpenTelemetry GenAI semantic-convention spans. Traces
+go to Jaeger; token-usage and operation-duration metrics go to a local
+collector's debug log.
The telemetry stack runs from downloaded release binaries.
## What it wires up
```
-python src/main.py --OTLP:4318--> otelcol-contrib --OTLP:14317--> Jaeger (UI :16686)
+uv run src/main.py --OTLP:4318--> otelcol-contrib --OTLP:14317--> Jaeger (UI :16686)
\--debug--> .otel/collector.log (metrics)
```
@@ -37,9 +37,10 @@ app-facing `4317`/`4318`.
2. In another terminal, run the sample:
```sh
- export GEMINI_API_KEY=your-key
+ export GEMINI_API_KEY=your-api-key
export OTEL_SERVICE_NAME=genkit-otel-sample # optional; names the service
- python src/main.py
+ uv sync
+ uv run src/main.py
```
3. Open Jaeger at http://localhost:16686, pick your service, and inspect the
diff --git a/samples/tool-interrupts/src/main.py b/samples/tool-interrupts/src/main.py
index 2e3bda228..f106bfbcc 100644
--- a/samples/tool-interrupts/src/main.py
+++ b/samples/tool-interrupts/src/main.py
@@ -30,7 +30,7 @@ class TransferRequest(BaseModel):
memo: str = ''
-@ai.tool()
+@ai.tool
async def request_transfer(body: TransferRequest, ctx: ToolContext) -> dict:
# First call pauses. After you resume, is_resumed() is True and the
# wire actually runs.
diff --git a/samples/tracing/src/main.py b/samples/tracing/src/main.py
index 86e9abca8..28cde3798 100644
--- a/samples/tracing/src/main.py
+++ b/samples/tracing/src/main.py
@@ -42,7 +42,7 @@ class Triage(BaseModel):
reply: str
-@ai.flow()
+@ai.flow
async def triage_ticket(ticket: Ticket) -> Triage:
# The lookup is a real step on the ticket path, so it gets its own
# span next to the model calls — that's what you inspect when a
diff --git a/samples/vertexai-image/src/main.py b/samples/vertexai-image/src/main.py
index b6e65e196..832beb59b 100755
--- a/samples/vertexai-image/src/main.py
+++ b/samples/vertexai-image/src/main.py
@@ -28,7 +28,8 @@ async def main() -> None:
prompt='Draw a cat in a hat',
model=VertexAI.gemini_image('gemini-2.5-flash-image'),
)
- print(response.media.url if response.media else response.text)
+ print(response.media.url[:40] if response.media else response.text)
+ # => data:image/png;base64,...
if __name__ == '__main__':