Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install developing-genkit-python@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin developing-genkit-python v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install developing-genkit-python

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/developing-genkit-python/

Extract the ZIP to .github/skills/ in your repo. The folder name must match developing-genkit-python for Copilot to auto-discover it.

Skill Files (18)

SKILL.md 10.1 KB
---
name: developing-genkit-python
description: >-
  Provides guidance on developing AI-powered applications using Genkit Python
  (0.13) and migrating Genkit Python 0.12 projects to 0.13. Use when building AI
  agents, flows, tools, structured outputs, or FastAPI routes in Python,
  upgrading from Genkit 0.12, or debugging Genkit imports, config errors, or
  traces. Don't use for Genkit in JavaScript/TypeScript, Go, or Dart.
metadata:
  version: "1.0.0"
  category: AiAndMachineLearning
---

# Genkit Python

Build AI features in Python — generation, structured output, streaming, tools,
flows, and multi-turn agents — with Genkit Python 0.13.

- **New project?** See [Setup](references/setup.md) and
  [Examples](references/examples.md).
- **Upgrading from 0.12 or fixing broken 0.12 imports/signatures?** Read
  [Migrating from 0.12 to 0.13](references/migrating-from-0.12.md) first.

## Prerequisites

- Python **3.10+** and **`uv`**
  ([install](https://docs.astral.sh/uv/getting-started/installation/))
- Genkit CLI: `npm install -g genkit-cli` if `genkit --version` is missing

## Hello World

```python
from genkit import Genkit
from genkit_google_genai import GoogleAI

ai = Genkit(
    plugins=[GoogleAI()],
    model=GoogleAI.gemini('gemini-flash-latest'),
)


async def main() -> None:
    response = await ai.generate(prompt='Suggest one seasonal pasta dish.')
    if response.error:
        raise RuntimeError(response.error.message)
    print(response.text)
    # => Lemony tagliatelle with asparagus, sweet peas, and herb ricotta


if __name__ == '__main__':
    ai.run_main(main())
```

`ai.generate` does not raise when the provider rejects or fails a call
(`INVALID_ARGUMENT`, `UNAVAILABLE`, rate limits). It returns `response.error`
(`Failure` with `.status` and `.message`), `finish_reason == 'failed'`, and
empty text. Problems caught before the call raise: `GoogleAI()` raises
`ValueError` without `GEMINI_API_KEY`; an unknown model, invalid key, or unknown
config field raises `GenkitError`. See
[Common Errors](references/common-errors.md).

## Agents (Experimental)

Multi-turn chats with history, typed state, human approval, branching, and
background work live under `genkit.exp` and `genkit.exp.agent`. Start here:
[Agents](references/agents.md).

```python
from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
agent = ai.define_agent(
    name='concierge',
    system='You are a concise hotel concierge.',
    store=InMemorySessionStore(),
)

chat = agent.chat()
res = await chat.send('Recommend a quiet dinner spot.')  # AgentResponse
print(res.text)
# => Try Osteria Lume on 5th; it has booths and low music.

turn = chat.send_stream('Is it open past 10pm?')  # AgentTurn
async for chunk in turn.stream:
    if chunk.text:
        print(chunk.text, end='')
final = await turn.response  # AgentResponse
```

More: [sessions](references/agents-sessions.md) ·
[HITL](references/agents-human-in-the-loop.md) ·
[branching](references/agents-branching.md) ·
[background](references/agents-background.md) ·
[state](references/agents-state.md) ·
[artifacts](references/agents-artifacts.md) ·
[custom](references/agents-custom.md) ·
[HTTP](references/agents-http.md)

## Imports

Every symbol lives in one public module (never import private `_` submodules;
see [Migrating from 0.12 to 0.13](references/migrating-from-0.12.md) if a 0.12
symbol moved):

- **Core app**: `from genkit import Genkit, FlowContext, ToolContext, Message, Part, Role, Media, Document, MultipartToolResponse, PublicError, GenkitError, Failure, ErrorReason`
- **Google GenAI & Vertex AI**: `from genkit_google_genai import GoogleAI, VertexAI, GeminiConfig, GeminiImageConfig, GeminiTtsConfig`
- **Other providers**: `from genkit_vertexai import ModelGarden` ·
  `from genkit_anthropic import Anthropic, AnthropicConfig` ·
  `from genkit_openai import OpenAI, OpenAIConfig` ·
  `from genkit_ollama import Ollama, OllamaConfig` ·
  `from genkit_amazon_bedrock import Bedrock, BedrockConfig`
- **Built-in middleware**: `from genkit_middleware import Middleware, Retry, Fallback, ToolApproval, Skills, Filesystem` (plus `from genkit_middleware.exp import Artifacts` for agent sessions)
- **Writing custom middleware**:
  `from genkit.middleware import Middleware, MiddlewareContext`
- **FastAPI & HTTP**:
  `from genkit_fastapi import serve_flow, genkit_fastapi_handler,
  handle_genkit_request` · `from genkit_fastapi.exp import serve_agent` ·
  `from genkit.web import RequestData, to_sse, error_body, error_status`
- **Agents (experimental)**: `from genkit.exp import Genkit, current_session` · `from genkit.exp.agent import Agent, Session, InMemorySessionStore, FileSessionStore, remote_agent`
- **Telemetry**: `from genkit_google_cloud import enable_google_cloud_telemetry`
  · `from genkit.telemetry import configure_instrumentation` ·
  `from genkit_otel import GenAiInstrumentation`
- **MCP (Client & Host)**: `from genkit_mcp import define_mcp_client, define_mcp_host, McpClient, McpHost`
- **Testing & Mocks**: `from genkit.testing import define_echo_model, define_scripted_model, EchoModel, ScriptedModel`
- **Evaluators (0.13 only; cut from 1.0, additive later)**:
  `from genkit_evaluators import register_genkit_evaluators` ·
  `from genkit.evaluator import BaseDataPoint, EvaluatorResponse, Score,
  ScoreDetails, ScoreStatus`

## Workflow

1. **Agent or flow?** Use `ai.define_agent` (on `genkit.exp.Genkit`, see
   [Agents](references/agents.md)) for multi-turn chats, state, or
   human-in-the-loop approval instead of hand-rolling a message loop inside a
   flow. Use `@ai.flow()` on `genkit.Genkit` for stateless request/response or
   streaming pipelines.
2. **Configure credentials & model refs.** Set **`GEMINI_API_KEY`**. Prefer
   typed refs (`GoogleAI.gemini('gemini-flash-latest')`) and typed flat configs
   (`GeminiConfig(...)`) so your type checker validates fields before runtime.
   Prefixed strings (`'googleai/gemini-flash-latest'`) also work.
3. **Enter via `ai.run_main(main())`** for standalone scripts and CLI apps so
   the process stays up for the Dev UI under `genkit start`. FastAPI apps skip
   `run_main`; uvicorn keeps the process alive:
   `genkit start -- uv run uvicorn main:app --reload`.
4. **Run with [Dev Workflow](references/dev-workflow.md)** (`genkit start` + Dev
   UI) and type-check with `pyright`, `mypy`, or `ty`.
5. **Verify with traces**, not a blind `uv run`. See
   [Genkit CLI](#genkit-cli-recommended).
6. **Stuck?** Check [Gotchas](#gotchas),
   [Common Errors](references/common-errors.md), or
   [Migrating from 0.12 to 0.13](references/migrating-from-0.12.md).

## Gotchas

- **Agents need `genkit.exp`**: `from genkit.exp import Genkit`. Stable
  `genkit.Genkit` has no `define_agent`.
- **Tools are async**: `@ai.tool()` raises `TypeError` on a plain `def`; use
  `async def`.
- **Check `response.error`**: provider failures come back on the response, not
  as exceptions (see [Hello World](#hello-world)).
- **Gemini thinking levels**: `GeminiConfig(thinking_level='MINIMAL')` fails on
  `gemini-flash-latest`; use `'LOW'`, `'MEDIUM'`, or `'HIGH'`.
- **Vertex AI model IDs**: Vertex does not serve `-latest` aliases. Pass a
  pinned model ID to `VertexAI.gemini(...)`.
- **Logging**: `genkit.get_logger` is structlog-based.
  `enable_google_cloud_telemetry()` injects trace context for GCP log-trace
  correlation.
- **Cloud telemetry auth**: call `enable_google_cloud_telemetry()` with
  Application Default Credentials or explicit `credentials=` (service account
  dict or `Credentials` instance).

## Genkit CLI (recommended)

`genkit start` wraps any Python program that uses Genkit, capturing traces from
every action while forwarding stdio cleanly. Running `uv run` directly skips
trace capture.

**Primary pattern (persistent server + Dev UI):**
```bash
genkit start -- uv run src/main.py
genkit start --noui -- uv run src/main.py   # persistent runtime without opening the Dev UI
```
`genkit start` runs until stopped with Ctrl+C (even with `--noui`). Do **not**
run `genkit start` as a blocking step in automated/non-interactive scripts; use
`flow:run` instead.

**Non-interactive use (agents/CI):** pass `--non-interactive` before `--` so the
CLI never blocks on prompts:
```bash
genkit start --non-interactive -- uv run src/main.py
```

**One-shot flow execution (`flow:run`):** spins up the runtime, invokes one
`@ai.flow()` by name, prints a `Trace ID`, and exits:
```bash
genkit flow:run myFlow '{"data": "input"}' -- uv run src/main.py
```
Note: `flow:run` invokes flows (`@ai.flow()`), not agents (`ai.define_agent`).
Wrap a single agent turn in a helper flow to exercise it via `flow:run` (see
[Agents](references/agents.md)).

**Inspecting traces:**
```bash
genkit trace:list                        # list recent trace IDs
genkit trace:get <traceId>               # human-readable trace inspection
genkit trace:get <traceId> --format json # machine-readable JSON for jq / scripts
```
Always pass `--format json` when piping into `jq` or other parsers.

See [Dev Workflow](references/dev-workflow.md) for the full pre-run checklist
and Dev UI walkthrough.

## References

- [Migrating from 0.12 to 0.13](references/migrating-from-0.12.md):
  Deterministic 0.12 -> 0.13 renames, config flattening, `PublicError`, and
  `exp` moves.
- [Examples](references/examples.md): Structured output, streaming, media parts,
  flows, tools, interrupts, cancellation, embeddings.
- [Setup](references/setup.md): Project bootstrap with `uv`, version alignment,
  and provider plugins.
- [Common Errors](references/common-errors.md): Fast fixes for 0.13 validation
  errors, HTTP 500 redaction, streaming, and sessions.
- [FastAPI](references/fastapi.md): `serve_flow`, `serve_agent`, `PublicError`,
  SSE streaming, and parallel flows.
- [Dotprompt](references/dotprompt.md): `.prompt` files, schema validation,
  variants, partials, and helpers.
- [Evals](references/evals.md): 0.13 evaluator syntax (deprecated; removed in
  1.0).
- [Dev Workflow](references/dev-workflow.md): `genkit start`, Dev UI, and trace
  verification checklist.
- [Agents (Experimental)](references/agents.md): Multi-turn stateful agents
  (`genkit.exp`).
references/
agents-artifacts.md 4.0 KB
# Agent Artifacts (Experimental)

> See [agents.md](agents.md) · [sessions](agents-sessions.md).

Artifacts are named session deliverables — markdown reports, SQL migrations,
generated files — persisted in `SessionState.artifacts` and exposed as
`chat.artifacts`, `res.artifacts`, and streamed `chunk.artifact`. Writing an
artifact whose `name` already exists replaces the previous version in place.

- [Artifacts middleware (genkit_middleware.exp)](#artifacts-middleware-genkit_middlewareexp): Lines 16-66
- [Writing artifacts from tools and custom agents](#writing-artifacts-from-tools-and-custom-agents): Lines 68-107
- [Reading artifact text](#reading-artifact-text): Lines 109-120

---

## `Artifacts` middleware (`genkit_middleware.exp`)

Import `Artifacts` from `genkit_middleware.exp` (`Middleware()` does not
register it). On every model call, `Artifacts()` appends an `<artifacts>`
listing of the session's current artifacts (name, size, source) to the system
prompt, and gives the model `write_artifact` and `read_artifact` tools. Pass
`Artifacts(readonly=True)` to expose only `read_artifact`. Outside an agent
session the tools return an error result instead of raising.

On a store-backed agent, `agent.chat(artifacts=...)` raises `AgentInitError`
(`FAILED_PRECONDITION`); have the model write artifacts on a turn, or write them
from a tool or [custom agent](agents-custom.md). Store-less agents can seed
`artifacts=` ([state](agents-state.md)).

```python
from genkit_google_genai import GoogleAI
from genkit_middleware.exp import Artifacts

from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore

ai = Genkit(plugins=[GoogleAI()])

agent = ai.define_agent(
    name='workspaceAgent',
    model=GoogleAI.gemini('gemini-flash-latest'),
    system='Use write_artifact to save deliverables and read_artifact to inspect them.',
    use=[Artifacts()],
    store=InMemorySessionStore(),
)


async def main() -> None:
    chat = agent.chat()

    # 1. Stream the turn and observe artifacts as they are written
    turn = chat.send_stream('Write schema.sql for a multi-tenant invoices table.')
    async for chunk in turn.stream:
        if chunk.artifact is not None:
            print('wrote artifact:', chunk.artifact.name)
            # => wrote artifact: schema.sql
    await turn.response

    # 2. Inspect persisted session artifacts
    print([a.name for a in chat.artifacts])
    # => ['schema.sql']


if __name__ == '__main__':
    ai.run_main(main())
```

## Writing artifacts from tools and custom agents

Inside an `@ai.tool()`, get the active session with `current_session()` from
`genkit.exp` (`None` outside an agent turn). Inside a custom agent, call the
same method on the `SessionRunner`. `add_artifacts` takes a `list[Artifact]`,
replaces by name, and emits one `chunk.artifact` per artifact to streaming
callers:

```python
from genkit import Part
from genkit.exp import current_session
from genkit.exp.agent import Artifact


@ai.tool(name='exportAuditReport', description='Save an audit report as a session artifact.')
async def export_audit_report(markdown_body: str) -> dict[str, object]:
    sess = current_session()
    if sess is None:
        return {'ok': False, 'error': 'no active agent session'}

    await sess.add_artifacts([
        Artifact(
            name='audit-report.md',
            parts=[Part.from_text(markdown_body)],
            metadata={'source': 'exportAuditReport'},
        )
    ])
    return {'ok': True, 'name': 'audit-report.md'}
```

From a custom agent's `handle_turn`:

```python
from genkit import Part
from genkit.exp.agent import Artifact, SessionRunner


async def save_report(sess: SessionRunner, body: str) -> None:
    await sess.add_artifacts([Artifact(name='report.md', parts=[Part.from_text(body)])])
```

## Reading artifact text

`Part.text` is `str | None`. This matches what `read_artifact` returns to the
model:

```python
from genkit.exp.agent import Artifact


def artifact_text(artifact: Artifact) -> str:
    return '\n'.join(p.text for p in artifact.parts if p.text)
```
agents-background.md 6.3 KB
# Background Agents & Cancellation (Experimental)

> Requires a [session store](agents-sessions.md). For abort to cancel a running
> turn, the store must also implement `SnapshotSubscriber`
> (`InMemorySessionStore`, `FileSessionStore`, and `FirestoreSessionStore` do).
> See [agents.md](agents.md).

`await chat.detach(...)` hands a turn to the server, reserves a `snapshot_id` in
`SnapshotStatus.PENDING` (with background heartbeat refreshes), and returns a
`DetachedTask` handle immediately without waiting for model or tool completion.

- [Detach, poll, and load results](#detach-poll-and-load-results): Lines 19-66
- [Client detach vs. server cancellation](#client-detach-vs-server-cancellation): Lines 68-110
- [Tool cancellation (asyncio.CancelledError)](#tool-cancellation-asynciocancellederror): Lines 112-134
- [Fan-out parallel research](#fan-out-parallel-research): Lines 136-162

---

## Detach, poll, and load results

Because the originating `chat` never streams a detached turn's chunks, rehydrate
the finished conversation with
`await agent.load_chat(snapshot_id=task.snapshot_id)` once the task settles:

```python
from genkit_google_genai import GoogleAI

from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore, SnapshotStatus

ai = Genkit(plugins=[GoogleAI()])

agent = ai.define_agent(
    name='backgroundAnalyst',
    model=GoogleAI.gemini('gemini-flash-latest'),
    system='Research analyst. Write concise markdown memos.',
    store=InMemorySessionStore(),
)


async def main() -> None:
    # 1. Start the turn on the server and get a snapshot handle immediately
    chat = agent.chat()
    task = await chat.detach('Summarize grid battery storage economics.')
    print(task.snapshot_id)

    # 2. Stream snapshot status updates (or await task.wait(interval=1.0) directly)
    snapshot = None
    async for snap in task.poll(interval=1.0):
        print(snap.status)
        snapshot = snap

    # 3. Verify terminal status and load the completed snapshot
    assert snapshot is not None and snapshot.status == SnapshotStatus.COMPLETED
    done = await agent.load_chat(snapshot_id=task.snapshot_id)
    print(done.messages[-1].text)


if __name__ == '__main__':
    ai.run_main(main())
```

Terminal snapshot statuses on `poll()` / `wait()` are `COMPLETED`, `FAILED`,
`ABORTED`, and `EXPIRED` (reported on read when a pending turn's heartbeat goes
stale). Always check `snapshot.status == SnapshotStatus.COMPLETED` before
reading reply messages.

## Client detach vs. server cancellation

Always `await` abort calls. Genkit distinguishes stopping a local listener from
cancelling work on the server:

- **Client detach (`await turn.abort()` or `asyncio.timeout` /
  `asyncio.wait_for`)**: stops streaming locally and resolves `turn.response` as
  cancelled immediately while the server turn keeps running to completion in the
  background. Wrapping `turn.stream` or `await turn.response` in
  `async with asyncio.timeout(...)` detaches the client the same way and
  re-raises `TimeoutError`.
- **Server cancel (`await task.abort()`, `await chat.abort()`, or
  `await agent.abort(snapshot_id)`)**: flips a pending snapshot to
  `SnapshotStatus.ABORTED` in the store and cancels the running server task.
  Returns the snapshot's **previous** `SnapshotStatus` (`SnapshotStatus.PENDING`
  if this call stopped a live turn; a terminal status if the turn had already
  finished).

`chat.abort()` targets the chat's last recorded snapshot, so calling it while a
foreground `send()` is in flight does not stop that turn: it returns the
previous turn's status (`SnapshotStatus.COMPLETED`), or raises `ValueError` on a
first turn with no snapshot yet. Use `detach()` + `task.abort()` to cancel a
running turn.

```python
chat = agent.chat()
task = await chat.detach('Audit every quarterly filing since 2015.')

# Cancel server-side execution; returns the status from *before* the abort write
previous_status = await task.abort()
# => SnapshotStatus.PENDING (the snapshot row is now SnapshotStatus.ABORTED)

# Aborted leaves are not resumable directly; continue from the last completed turn via session_id
recovered = agent.chat(session_id=chat.session_id)
res = await recovered.send('Audit only Q4 2025 instead.')
print(res.text)
# => Q4 2025 audit: ...
```

On the very first turn of a session, a client-side `turn.abort()` detaches
before the client receives `session_id` or `snapshot_id`. Prefer
`await chat.detach(...)` + `await task.abort()` whenever you need a recoverable
server-side cancel handle from turn start.

## Tool cancellation (`asyncio.CancelledError`)

When a server turn is aborted (or an in-process caller cancels), Python delivers
standard `asyncio.CancelledError` into active model requests, retry sleeps, and
running `@ai.tool()` coroutines at the current `await` (there is no abort-signal
attribute on `ToolContext`). Clean up partial external work in `try` / `finally`
(and always re-raise `CancelledError` if caught):

```python
import asyncio


@ai.tool(name='runBackfill', description='Run a multi-batch warehouse backfill.')
async def run_backfill(table: str) -> dict[str, object]:
    job_id = f'job-{table}'
    try:
        await asyncio.sleep(10.0)
        return {'job_id': job_id, 'status': 'completed'}
    finally:
        # Runs whether the tool returns normally, fails, or receives CancelledError
        print(f'releasing lease for {job_id}')
        # => releasing lease for job-orders  (also after await task.abort() mid-run)
```

## Fan-out parallel research

A single `AgentChat` runs one turn at a time. To run background branches
concurrently, fork independent chats from a shared checkpoint `snapshot_id`:

```python
import asyncio

root = agent.chat()
await root.send('Context: B2B SaaS workload, 50k RPS peak, strict multi-region RPO.')
checkpoint = root.snapshot_id
assert checkpoint is not None


async def research(engine: str) -> tuple[str, str]:
    branch = await agent.load_chat(snapshot_id=checkpoint)
    task = await branch.detach(f'Evaluate {engine} against our requirements.')
    snap = await task.wait(interval=1.0)
    if snap.status != SnapshotStatus.COMPLETED:
        return engine, f'unfinished ({snap.status})'
    done = await agent.load_chat(snapshot_id=task.snapshot_id)
    return engine, done.messages[-1].text


results = await asyncio.gather(research('Cloud Spanner'), research('AlloyDB'))
# => [('Cloud Spanner', '...'), ('AlloyDB', '...')]
```
agents-branching.md 3.7 KB
# Agent Branching & Time Travel (Experimental)

> Requires a [session store](agents-sessions.md). See [agents.md](agents.md).

Every store-backed turn writes a `SessionSnapshot` keyed by `snapshot_id`, with
`parent_id` pointing at the previous turn. Reopening an earlier `snapshot_id`
with `await agent.load_chat(snapshot_id=...)` and sending a new message writes a
sibling snapshot under the same parent. The original timeline is untouched, and
both branches keep the same `session_id`.

Loading a snapshot restores the **entire** `SessionState` at that point:
`messages`, custom `state`, and `artifacts` revert together. `load_chat` only
resumes `completed` snapshots (see [sessions](agents-sessions.md) for
`load_chat` vs `chat(snapshot_id=...)`).

## Fork sibling timelines

```python
from genkit_google_genai import GoogleAI

from genkit import GenkitError
from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore

ai = Genkit(plugins=[GoogleAI()])

# reject_ambiguous_session=True makes session_id lookups fail loudly once a session forks
store = InMemorySessionStore(reject_ambiguous_session=True)

agent = ai.define_agent(
    name='designer',
    model=GoogleAI.gemini('gemini-flash-latest'),
    system='You design product landing pages. Reply in two short sentences.',
    store=store,
)


async def main() -> None:
    # 1. Shared root turn; bookmark snapshot_id as the fork point
    root = agent.chat()
    await root.send('Plan a landing page for an AI note-taking app.')
    checkpoint = root.snapshot_id
    session_id = root.session_id
    assert checkpoint and session_id

    # 2. Fork two independent branches from the same checkpoint
    minimal = await agent.load_chat(snapshot_id=checkpoint)
    await minimal.send('Direction: minimal with generous whitespace.')

    bold = await agent.load_chat(snapshot_id=checkpoint)
    await bold.send('Direction: dark mode and high contrast.')
    chosen_leaf = bold.snapshot_id
    assert chosen_leaf

    print(bold.session_id == minimal.session_id == session_id)
    # => True
    print([m.text for m in bold.messages if m.role == 'user'])
    # => ['Plan a landing page for an AI note-taking app.', 'Direction: dark mode and high contrast.']

    # 3. With two leaves, a bare session_id lookup raises FAILED_PRECONDITION
    try:
        await store.get_snapshot(session_id=session_id)
    except GenkitError as err:
        print(err.status)
        # => FAILED_PRECONDITION

    # 4. Continue linearly from the chosen branch leaf
    resumed = await agent.load_chat(snapshot_id=chosen_leaf)
    await resumed.send('Add a pricing section.')


if __name__ == '__main__':
    ai.run_main(main())
```

## Branching rules

- **Resume by `snapshot_id` after forking**: Once a session has multiple leaf
  snapshots, "latest turn for `session_id`" is ambiguous. By default the store
  picks the most recently created leaf. Pass `reject_ambiguous_session=True` on
  `InMemorySessionStore` or `FileSessionStore` to fail instead:
  `store.get_snapshot(session_id=...)` and `agent.get_snapshot(session_id=...)`
  raise `GenkitError` (`FAILED_PRECONDITION`), and a turn sent on
  `agent.chat(session_id=...)` returns a failed turn with that status on
  `res.error`.
- **Edit-and-resubmit / regenerate**: Store each turn's `snapshot_id` alongside
  the message in your UI. When a user edits an earlier prompt or clicks
  regenerate, load the parent turn's `snapshot_id` and send the revised message.
  Previous answers stay intact as sibling branches.
- **Artifact time travel**: When an agent edits files via `Artifacts()`
  (`genkit_middleware.exp`, see [artifacts](agents-artifacts.md)) or a tool,
  rewinding with `load_chat(snapshot_id=checkpoint)` restores `chat.artifacts`
  and `chat.state` to their values at that turn.
agents-custom.md 7.6 KB
# Custom Agents — `define_custom_agent` (Experimental)

> See [agents.md](agents.md).

`ai.define_agent` runs a built-in model + tool loop. When you need custom
multi-step orchestration, subagent delegation, custom streaming, or manual
control over messages, custom state, and artifacts, register a custom turn loop
with `ai.define_custom_agent`. Callers still talk to the agent through
`chat.send(...)`, `chat.send_stream(...)`, `chat.detach(...)`, and
`serve_agent(...)`.

- [Anatomy](#anatomy): Lines 18-75
- [Streaming custom agent example](#streaming-custom-agent-example): Lines 77-143
- [Non-streaming handle_turn with tools](#non-streaming-handle_turn-with-tools): Lines 145-204

---

## Anatomy

Register one async `fn(sess: SessionRunner, ctx: AgentContext) -> AgentResult`.
Inside `fn`, define
`handle_turn(inp: AgentInput, turn_ctx: TurnContext) -> TurnResult | None`, pass
it to `await sess.run(handle_turn)`, and return `await sess.result()`:

```python
from genkit.exp.agent import (
    AgentContext,
    AgentFinishReason,
    AgentInput,
    AgentResult,
    SessionRunner,
    TurnContext,
    TurnResult,
)


async def custom_fn(sess: SessionRunner, ctx: AgentContext) -> AgentResult:
    async def handle_turn(inp: AgentInput, turn_ctx: TurnContext) -> TurnResult | None:
        # 1. inp.message is already appended to sess.get_messages() before handle_turn runs
        # 2. Emit live chunks with ctx.send_chunk(AgentStreamChunk(...))
        # 3. Persist assistant/tool messages via sess.add_messages([...]) or sess.set_messages([...])
        return TurnResult(finish_reason=AgentFinishReason.STOP)

    await sess.run(handle_turn)
    return await sess.result()
```

Runtime mechanics:

- **Automatic user message append**: Before calling `handle_turn`, `sess.run`
  appends `inp.message` (`AgentInput` carries `message`, `resume`, and `detach`)
  to session history. `await sess.get_messages()` already returns
  `list[Message]` including the current user prompt — do not wrap items in
  `Message(m)`.
- **`TurnContext` (`turn_ctx`)**: Exposes `snapshot_id` (pre-reserved at turn
  start when a `store` is configured, `None` otherwise), `parent_snapshot_id`,
  and `turn_index`. Pre-reserving `snapshot_id` lets you name external worktrees
  or scratch directories after the snapshot before the turn commits.
  `turn_index` is 0-based within one invocation; each `chat.send` starts a new
  invocation, so it does not count turns across the session.
- **`SessionRunner` (`sess`) helpers**: `get_messages()` / `add_messages([...])`
  / `set_messages([...])`, `get_custom()` / `update_custom(sync_fn)`, and
  `get_artifacts()` / `add_artifacts([...])`. Both `add_messages` and
  `add_artifacts` take a `list`.
- **Turn completion and failures**: `TurnResult` accepts
  `(finish_reason=..., error=...)` — it does **not** take `messages=`. Raising
  an exception inside `handle_turn` ends the turn with
  `finish_reason=AgentFinishReason.FAILED`, populates `res.error` on the
  caller's `AgentResponse`, and stops the turn loop. `chat.send` returns that
  failed turn; it does not raise.
- **Model failures do not raise**: `ai.generate` and `ai.generate_stream` report
  provider errors on `response.error` with `finish_reason='failed'`. Raise a
  `GenkitError` from it so the caller's `res.error` keeps the provider status
  (e.g. `UNAVAILABLE`); otherwise the caller sees a generic `UNKNOWN` "Agent
  turn failed." (or a silent `STOP` if you hardcode the finish reason).

## Streaming custom agent example

```python
from genkit_google_genai import GoogleAI

from genkit import GenkitError
from genkit.exp import Genkit
from genkit.exp.agent import (
    AgentContext,
    AgentFinishReason,
    AgentInput,
    AgentResult,
    AgentStreamChunk,
    InMemorySessionStore,
    SessionRunner,
    TurnContext,
    TurnResult,
)

ai = Genkit(plugins=[GoogleAI()])
store = InMemorySessionStore()


async def custom_coder_fn(sess: SessionRunner, ctx: AgentContext) -> AgentResult:
    async def handle_turn(inp: AgentInput, turn_ctx: TurnContext) -> TurnResult | None:
        # 1. Read history (already includes inp.message as list[Message])
        history = await sess.get_messages()

        # 2. Stream model chunks out through AgentContext
        stream_resp = ai.generate_stream(
            model=GoogleAI.gemini('gemini-flash-latest'),
            system='Concise Python systems assistant.',
            messages=history,
        )
        async for chunk in stream_resp.stream:
            ctx.send_chunk(AgentStreamChunk(model_chunk=chunk))

        # 3. Fail the turn on model errors (generate reports them instead of raising)
        res = await stream_resp.response
        if res.error is not None:
            raise GenkitError(status=res.error.status, message=res.error.message)

        # 4. Persist the assistant reply so subsequent turns see it
        if res.message:
            await sess.add_messages([res.message])

        # 5. Every model FinishReason value exists on AgentFinishReason
        return TurnResult(finish_reason=AgentFinishReason(res.finish_reason.value))

    await sess.run(handle_turn)
    return await sess.result()


agent = ai.define_custom_agent(name='customCoder', fn=custom_coder_fn, store=store)


async def main() -> None:
    chat = agent.chat()
    res = await chat.send('Show a dict comprehension that inverts keys and values.')
    print(res.text)
    # => inverted = {v: k for k, v in original.items()}
    #    (model reply, usually wrapped in a markdown code fence)


if __name__ == '__main__':
    ai.run_main(main())
```

## Non-streaming `handle_turn` with tools

When `ai.generate(..., tools=[...])` runs a multi-step tool loop inside
`handle_turn`, `res.messages` contains the full conversation transcript (prior
history + intermediate tool requests/responses + final model reply, plus a
leading `Role.SYSTEM` message when `system=` was passed). Strip `Role.SYSTEM`
and save the updated transcript with `await sess.set_messages(...)`:

```python
from datetime import datetime, timezone

from genkit_google_genai import GoogleAI

from genkit import GenkitError, Role
from genkit.exp import Genkit
from genkit.exp.agent import (
    AgentContext,
    AgentFinishReason,
    AgentInput,
    AgentResult,
    InMemorySessionStore,
    SessionRunner,
    TurnContext,
    TurnResult,
)

ai = Genkit(plugins=[GoogleAI()])


@ai.tool(name='utcNow', description='Return the current UTC timestamp.')
async def utc_now() -> str:
    return datetime.now(timezone.utc).isoformat()


async def ops_agent_fn(sess: SessionRunner, ctx: AgentContext) -> AgentResult:
    async def handle_turn(inp: AgentInput, turn_ctx: TurnContext) -> TurnResult | None:
        # 1. Run the model + tool loop over the session history
        history = await sess.get_messages()
        res = await ai.generate(
            model=GoogleAI.gemini('gemini-flash-latest'),
            system='Ops assistant. Use utcNow when asked for the current time.',
            messages=history,
            tools=[utc_now],
        )
        if res.error is not None:
            raise GenkitError(status=res.error.status, message=res.error.message)

        # 2. Persist tool-request, tool-response, and final model messages without duplicating system
        await sess.set_messages([m for m in res.messages if m.role != Role.SYSTEM])
        return TurnResult(finish_reason=AgentFinishReason(res.finish_reason.value))

    await sess.run(handle_turn)
    return await sess.result()


ops_agent = ai.define_custom_agent(name='opsAgent', fn=ops_agent_fn, store=InMemorySessionStore())
```

Related guides: [state](agents-state.md) · [artifacts](agents-artifacts.md) ·
[tools](agents.md#tools-progress-chunks-and-multipart-responses)
agents-http.md 8.8 KB
# Agent HTTP Serving & Remote Client (Experimental)

> See [agents.md](agents.md) · [FastAPI](fastapi.md).

Mount an agent on FastAPI with `serve_agent` from `genkit_fastapi.exp`, and
connect from another Python service or CLI with `remote_agent` from
`genkit.exp.agent`. Stable flows use `serve_flow` from `genkit_fastapi`
([FastAPI](fastapi.md)).

- [Serve an agent with FastAPI](#serve-an-agent-with-fastapi): Lines 17-59
- [Connect with remote_agent](#connect-with-remote_agent): Lines 61-105
- [Auth, context_dependency, and PublicError](#auth-context_dependency-and-publicerror): Lines 107-193
- [Custom HTTP routes](#custom-http-routes): Lines 195-238

---

## Serve an agent with FastAPI

`serve_agent(agent)` mounts `POST /{agent.name}` for turns: one-shot JSON by
default, SSE when the caller sends `Accept: text/event-stream` or
`?stream=true`. When the agent has a `store`, it also mounts
`POST /{agent.name}/getSnapshot` (`404` when the snapshot is missing) and
`POST /{agent.name}/abort`. Callers can pass `?session_id=` or `?thread_id=` to
continue a session when the body `init` carries no session id.

```python
import uvicorn
from fastapi import FastAPI
from genkit_fastapi.exp import serve_agent
from genkit_google_genai import GoogleAI

from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore

# 1. Initialize the experimental Genkit instance
ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))

# 2. Define a store-backed agent
agent = ai.define_agent(
    name='weatherAgent',
    system='Weather assistant. Keep answers under two sentences.',
    store=InMemorySessionStore(),
)

# 3. Mount /api/weatherAgent, /api/weatherAgent/getSnapshot, and /api/weatherAgent/abort
app = FastAPI()
app.include_router(serve_agent(agent), prefix='/api')

if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8080)
```

Override the route path with `serve_agent(agent, base_path='/chat')`. Add
FastAPI's `CORSMiddleware` as usual if browsers call the agent from another
origin. Run alongside the Developer UI with:

```bash
genkit start -- uv run server.py
```

## Connect with `remote_agent`

`remote_agent` returns an `AgentClient` with the same `chat()`, `load_chat()`,
`get_snapshot()`, and `abort()` surface as an in-process `Agent`. `timeout`
(default `60.0`) is the longest wait for the next bytes from the server, not a
cap on the whole turn.

```python
from genkit.exp.agent import remote_agent


async def run_client() -> None:
    client = remote_agent(
        url='http://127.0.0.1:8080/api/weatherAgent',
        state_management='server',  # use 'client' when the server agent has no store
        timeout=60.0,
    )

    # 1. One-shot turn
    chat = client.chat()
    res = await chat.send('Weather in Tokyo?')
    print(res.text)
    # => I don't have real-time weather data for Tokyo. Check a local forecast for live conditions.

    # 2. Streamed follow-up turn
    turn = chat.send_stream('What about humidity?')
    async for chunk in turn.stream:
        if chunk.text:
            print(chunk.text, end='', flush=True)
    final = await turn.response

    # 3. Rehydrate from the server store onto a new chat handle
    assert final.snapshot_id is not None
    resumed = await client.load_chat(snapshot_id=final.snapshot_id)
    answer = await resumed.send('Which city were we discussing?')
    print(answer.text)
    # => We were discussing Tokyo.
```

Pass `state_schema=MyStateModel` to `remote_agent(...)` when you want
`chat.state`, `res.state`, and `chunk.custom` validated into a Pydantic model on
the client. Omit any trailing slash on `url`; the client derives
`{url}/getSnapshot` and `{url}/abort` from it. A timeout surfaces as
`GenkitError` `DEADLINE_EXCEEDED`, a refused or dropped connection as
`UNAVAILABLE`.

## Auth, `context_dependency`, and `PublicError`

Resolve caller identity on the server with `context_dependency`, a FastAPI
dependency applied to the turn, `getSnapshot`, and `abort` routes. Return a
`dict`; other return values (such as Pydantic models) are dropped. Tools read it
from `ctx.context` (or `Genkit.current_context()`), and `SessionStore` methods
receive it as `context=`.

Errors surface at three boundaries:

- **Inside `context_dependency`**: FastAPI resolves it before Genkit runs, so
  Genkit's error mapping does not apply. Raise
  `fastapi.HTTPException(status_code=401, ...)`; a `PublicError` raised here
  becomes FastAPI's plain `500 Internal Server Error`.
- **Inside Genkit, before or outside a turn**: on `getSnapshot` and `abort`, a
  `PublicError` from your `SessionStore` keeps its status, message, and details
  (`PERMISSION_DENIED` -> `403`). `AgentInitError` (an init that does not match
  the agent's state mode) is a `PublicError` and keeps its status too
  (`FAILED_PRECONDITION` -> `400`). Any other exception returns a redacted
  `500`. Full rules:
  [HTTP Error Redaction](fastapi.md#http-error-redaction-and-publicerror).
- **Inside a running turn**: tool and store exceptions do not become HTTP
  errors. The response is `200` with `finishReason: "failed"` and `error`; the
  client sees `res.finish_reason == AgentFinishReason.FAILED` and `res.error`.

```python
from fastapi import FastAPI, Header, HTTPException
from genkit_fastapi.exp import serve_agent

from genkit import PublicError, ToolContext
from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore, SessionSnapshot, remote_agent
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))


# 1. Resolve the caller from a header; the dict becomes the action context
async def resolve_user(x_api_key: str | None = Header(default=None)) -> dict[str, object]:
    if not x_api_key:
        raise HTTPException(status_code=401, detail='Missing X-Api-Key header.')
    return {'tenant_id': 'acme', 'role': 'admin'}


# 2. Reject snapshot reads that carry no tenant
class TenantScopedStore(InMemorySessionStore):
    async def get_snapshot(
        self,
        *,
        snapshot_id: str | None = None,
        session_id: str | None = None,
        context: dict[str, object] | None = None,
    ) -> SessionSnapshot | None:
        if not (context or {}).get('tenant_id'):
            raise PublicError('PERMISSION_DENIED', 'Tenant context required.')
        return await super().get_snapshot(snapshot_id=snapshot_id, session_id=session_id, context=context)


# 3. Read the same context from a tool
@ai.tool(name='whoami', description='Inspect caller tenant context.')
async def whoami(ctx: ToolContext) -> dict[str, object]:
    auth = ctx.context or {}
    return {'tenant_id': auth.get('tenant_id'), 'role': auth.get('role')}


support_agent = ai.define_agent(
    name='supportAgent',
    system='Support assistant for the caller tenant.',
    tools=[whoami],
    store=TenantScopedStore(),
)

app = FastAPI()
app.include_router(
    serve_agent(support_agent, context_dependency=resolve_user),
    prefix='/api',
)
# POST /api/supportAgent with no X-Api-Key
# => 401 {"detail":"Missing X-Api-Key header."}

# 4. The remote client sends static headers, or a sync/async callable that returns them
authed_client = remote_agent(
    url='http://127.0.0.1:8080/api/supportAgent',
    state_management='server',
    headers={'X-Api-Key': 'sk-live-...'},
)
```

## Custom HTTP routes

Use `handle_genkit_request` (`genkit_fastapi`) when a route needs path
parameters or extra `Depends(...)` but should keep the Genkit JSON / SSE wire
format. Use `to_sse` (`genkit.web`) to frame any stream handle
(`chat.send_stream()`, `flow.stream()`) as `data: {"message": ...}` frames
followed by `data: {"result": ...}`. Generic flow patterns:
[Custom Route Escape Hatch](fastapi.md#3-custom-route-escape-hatch-handle_genkit_request-or-genkitweb).

```python
from fastapi import FastAPI, Request, Response
from fastapi.responses import StreamingResponse
from genkit_fastapi import handle_genkit_request
from pydantic import BaseModel

from genkit.web import to_sse

custom_app = FastAPI()


class TurnRequest(BaseModel):
    prompt: str


# Option A: full Genkit wire contract inside a custom route.
# Body: {"data": {"message": {"role": "user", "content": [{"text": "..."}]}}}
@custom_app.post('/tenants/{tenant_id}/chat')
async def tenant_agent_route(tenant_id: str, request: Request) -> Response:
    # Check the caller may act for tenant_id before trusting the path.
    return await handle_genkit_request(
        request,
        action=support_agent,
        context={'tenant_id': tenant_id},
    )


# Option B: stream one chat turn as SSE from a plain JSON body.
# agent.chat() takes no request context, so the store and tools see context=None.
@custom_app.post('/sessions/{session_id}/stream')
async def stream_session_turn(session_id: str, body: TurnRequest) -> StreamingResponse:
    chat = agent.chat(session_id=session_id)
    turn = chat.send_stream(body.prompt)
    return StreamingResponse(to_sse(turn), media_type='text/event-stream')
```
agents-human-in-the-loop.md 7.0 KB
# Agent Human-in-the-Loop / Interrupts (Experimental)

> See [agents.md](agents.md) · [sessions](agents-sessions.md).

An interrupt pauses an agent mid-turn so a human or policy check can inspect the
pending tool call, then resume execution. Interrupts work both with a store
(across separate HTTP requests) and without a store (in-process or round-tripped
client state).

Turn lifecycle: `chat.send(...)` ->
`res.finish_reason == AgentFinishReason.INTERRUPTED` with `res.interrupts` ->
human decision -> `chat.resume(...)` / `chat.resume_stream(...)`.

- [Gate tools with ToolApproval](#gate-tools-with-toolapproval): Lines 20-69
- [Detect and resume (restart vs respond)](#detect-and-resume-restart-vs-respond): Lines 71-138
- [Custom tool interrupts and Interrupt (BaseException)](#custom-tool-interrupts-and-interrupt-baseexception): Lines 140-187

---

## Gate tools with `ToolApproval`

`ToolApproval(allowed_tools=[...])` lets listed tools execute immediately and
interrupts all other tool calls. An empty list requires approval for every tool.
When pairing `ToolApproval` with `Filesystem` or `Artifacts`, list read-only
tools (`list_files`, `read_file`, `read_artifact`) in `allowed_tools` if only
writes (`write_file`, `edit_file`, `write_artifact`) should pause.

```python
from uuid import uuid4
from genkit_google_genai import GoogleAI
from genkit_middleware import Middleware, ToolApproval
from pydantic import BaseModel, Field

from genkit import Part
from genkit.exp import Genkit
from genkit.exp.agent import AgentFinishReason, InMemorySessionStore


class TransferInput(BaseModel):
    amount: float
    to_account: str = Field(alias='toAccount')

    model_config = {'populate_by_name': True}


class TransferOutput(BaseModel):
    success: bool
    transaction_id: str = Field(alias='transactionId')

    model_config = {'populate_by_name': True}


ai = Genkit(plugins=[GoogleAI(), Middleware()])


@ai.tool(name='transferMoney', description='Transfer money between accounts.')
async def transfer_money(input: TransferInput) -> TransferOutput:
    return TransferOutput(success=True, transactionId=f'txn-{uuid4().hex[:12]}')


agent = ai.define_agent(
    name='bankingAgent',
    model=GoogleAI.gemini('gemini-flash-latest'),
    system='Banking assistant. Call transferMoney when the user asks to transfer money.',
    tools=[transfer_money],
    use=[ToolApproval(allowed_tools=[])],
    store=InMemorySessionStore(),
)
```

## Detect and resume (`restart` vs `respond`)

Each entry in `res.interrupts` is an `AgentInterrupt` exposing `.name`, `.ref`,
and `.input` for rendering your approval UI, plus two methods that build `Part`
objects for `chat.resume(...)`:

- **`intr.restart(resumed_metadata={'tool_approved': True})`**: re-runs the
  interrupted tool on the server (`ctx.is_resumed()` becomes `True`).
  `ToolApproval` checks `tool_approved` (or `toolApproved`) in
  `resumed_metadata`. Restart inputs must exactly match the original tool
  request in session history; a forged or modified restart returns a failed turn
  (`AgentFinishReason.FAILED`, `res.error.status == 'INVALID_ARGUMENT'`) instead
  of running the tool.
- **`intr.respond(output)`**: builds a tool response `Part` without executing
  the tool. Use this to deny an action (e.g.
  `intr.respond({'ok': False, 'error': 'declined by user'})`) or answer a
  prompt-style interrupt created with `ai.define_interrupt(...)`.

A resumed turn can call more tools that also need approval, so loop until the
turn stops interrupting:

```python
async def main() -> None:
    chat = agent.chat()

    # 1. Turn pauses before transferMoney executes
    res = await chat.send('Transfer $500 to account 12345 for rent.')

    # 2. Approve pending interrupts until the turn finishes
    while res.finish_reason == AgentFinishReason.INTERRUPTED:
        for intr in res.interrupts:
            print(f'Approving {intr.name}: {intr.input}')
            # => Approving transferMoney: {'amount': 500, 'toAccount': '12345'}
        restart_parts: list[Part] = [
            intr.restart(resumed_metadata={'tool_approved': True})
            for intr in res.interrupts
        ]
        res = await chat.resume(restart=restart_parts)

    # 3. Read the final reply (check res.error if the turn failed)
    print(res.finish_reason, res.text)
    # => stop $500 has been successfully transferred to account 12345.


if __name__ == '__main__':
    ai.run_main(main())
```

Denials and streaming resumes use the same parts (`res` is an interrupted turn):

```python
# Deny without executing the tool:
denied = await chat.resume(
    respond=[intr.respond({'ok': False, 'error': 'transfer declined'}) for intr in res.interrupts],
)

# Or approve and stream the resumed turn:
turn = chat.resume_stream(
    restart=[intr.restart(resumed_metadata={'tool_approved': True}) for intr in res.interrupts],
)
async for chunk in turn.stream:
    if chunk.text:
        print(chunk.text, end='', flush=True)
final = await turn.response
```

Without a store, keep the same `chat` instance or round-trip `messages`,
`state`, and `artifacts` ([without a store](agents.md#without-a-store)).

## Custom tool interrupts and `Interrupt` (`BaseException`)

For domain-specific thresholds (such as only pausing transfers above `$1,000`),
raise `Interrupt` directly inside a tool or register a dedicated prompt tool
with `ai.define_interrupt(...)`:

- **`Interrupt` subclasses `BaseException`**, not `Exception` (like
  `asyncio.CancelledError`). A `try ... except Exception:` block inside a tool
  will **not** swallow an `Interrupt` and accidentally let execution proceed
  without approval. Only catch `Interrupt` explicitly if intended, and always
  re-raise it.
- Read `ctx.is_resumed()` and `ctx.resumed_metadata` on `ToolContext` when the
  caller resumes with `intr.restart(resumed_metadata=...)`. The keys are yours:
  the tool below expects `intr.restart(resumed_metadata={'approved': True})`.

```python
from genkit import Interrupt, ToolContext


@ai.tool(name='wireTransfer', description='Send an external wire transfer.')
async def wire_transfer(input: TransferInput, ctx: ToolContext) -> dict[str, object]:
    if input.amount > 1000 and not ctx.is_resumed():
        # BaseException: an `except Exception:` block can't swallow it
        raise Interrupt({'reason': 'high_value_transfer', 'amount': input.amount})

    if ctx.is_resumed() and not (ctx.resumed_metadata or {}).get('approved'):
        return {'ok': False, 'status': 'rejected'}

    return {'ok': True, 'amount': input.amount, 'to': input.to_account}
```

For pure question/confirmation tools that never run server logic themselves, use
`ai.define_interrupt(...)` and resume with `intr.respond(...)`:

```python
class ConfirmInput(BaseModel):
    action: str
    summary: str


ask_confirmation = ai.define_interrupt(
    name='askConfirmation',
    description='Ask the user to confirm before irreversible actions.',
    input_schema=ConfirmInput,
)
# Add to the agent's tools=[...], then answer with:
# chat.resume(respond=[intr.respond({'confirmed': True}) for intr in res.interrupts])
```
agents-sessions.md 4.2 KB
# Sessions & Persistence (Experimental)

> See [agents.md](agents.md).

With a `SessionStore`, the server owns conversation history. Every turn writes a
`SessionSnapshot` keyed by `snapshot_id`, enabling resume across restarts,
[branching](agents-branching.md), and
[detached background turns](agents-background.md).
[Interrupts](agents-human-in-the-loop.md) work with or without a store.

- [Choose a store](#choose-a-store): Lines 18-47
- [Persist and rehydrate a chat](#persist-and-rehydrate-a-chat): Lines 49-81
- [Resume and lookup methods](#resume-and-lookup-methods): Lines 83-98
- [Typed state and multi-user isolation](#typed-state-and-multi-user-isolation): Lines 100-108

---

## Choose a store

Import local stores from `genkit.exp.agent` and the production Firestore store
from `genkit_google_cloud.exp`:

```python
from genkit.exp.agent import FileSessionStore, InMemorySessionStore
from genkit_google_cloud.exp import FirestoreSessionStore

# 1. Local dev & tests (lost when the process exits)
mem_store = InMemorySessionStore()

# 2. Local disk persistence (one <snapshot_id>.json file per turn)
file_store = FileSessionStore(
    './.snapshots',
    max_persisted_chain_length=20,  # optional: prune oldest ancestors on save
    reject_ambiguous_session=True,  # optional: raise on session_id lookup after a fork
)

# 3. Production durable store (JSON Patch diffs + sharded checkpoints, ADC auth)
firestore_store = FirestoreSessionStore(
    collection='genkit-sessions',
    snapshot_path_prefix=lambda ctx: (ctx or {}).get('tenant_id', 'global'),
)
```

`FirestoreSessionStore` stores each turn as a JSON Patch diff from its parent
with periodic sharded checkpoints so large sessions stay below Firestore's 1 MiB
document limit without secondary indexes. Pass `snapshot_path_prefix` to isolate
multi-tenant paths from action `context`.

## Persist and rehydrate a chat

```python
from genkit_google_genai import GoogleAI

from genkit.exp import Genkit
from genkit.exp.agent import FileSessionStore

ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))

agent = ai.define_agent(
    name='logbookAgent',
    system='You are a concise engineering logbook assistant.',
    store=FileSessionStore('./.snapshots'),
)


async def main() -> None:
    # 1. Run turn 1; save res.snapshot_id in your app database
    chat = agent.chat()
    res = await chat.send('Log: migrated auth service to token exchange.')
    checkpoint = res.snapshot_id
    assert checkpoint is not None

    # 2. Rehydrate full state (messages, state, artifacts) onto a fresh chat
    resumed = await agent.load_chat(snapshot_id=checkpoint)
    res2 = await resumed.send('Add note: latency p99 stayed at 14ms.')
    print(res2.text)


if __name__ == '__main__':
    ai.run_main(main())
```

## Resume and lookup methods

- **`await agent.load_chat(snapshot_id=...)` / `load_chat(session_id=...)`**:
  reads the stored snapshot immediately and populates `chat.messages`,
  `chat.state`, and `chat.artifacts`. Pointing `load_chat` at a failed, aborted,
  or pending leaf loads that row as-is; calling `send()` on a non-completed
  snapshot returns `res.error` (`SNAPSHOT_NOT_RESUMABLE`).
- **`agent.chat(session_id=...)`**: attaches a lazy session handle without an
  upfront read. On the next `send()`, the server automatically walks back past
  any failed, aborted, or expired leaf to continue from the last completed turn
  (or starts a fresh session under `session_id` if no turn has completed yet).
- **`agent.chat(snapshot_id=...)`**: attaches a lazy resume handle to a specific
  completed snapshot.
- **`await agent.get_snapshot(snapshot_id=...)` /
  `get_snapshot(session_id=...)`**: inspects the raw `SessionSnapshot` without
  creating a chat.

## Typed state and multi-user isolation

- **Typed state**: Pass `state_schema=MyModel` on the agent. On a store-backed
  agent, `agent.chat(state=...)` raises `AgentInitError` immediately; mutate
  state from tools with `current_session()` from `genkit.exp` (see
  [state](agents-state.md)).
- **Multi-user sessions**: One `Agent` instance safely serves many users on a
  shared store. Each `agent.chat()` mints a distinct `session_id`; store
  `session_id` or `snapshot_id` per user in your application database.
agents-state.md 6.2 KB
# Agent State (Experimental)

> See [agents.md](agents.md) · [sessions](agents-sessions.md).

An agent session tracks three layers: `messages`, custom `state` (typed by
`state_schema`), and `artifacts`. When `state_schema` (a Pydantic `BaseModel`)
is set, `chat.state`, `res.state`, and streamed `chunk.custom` validate into
instances of that model instead of bare dicts.

- [Two state-management modes](#two-state-management-modes): Lines 18-32
- [Client-managed typed state](#client-managed-typed-state): Lines 34-76
- [Mutating state from tools (current_session)](#mutating-state-from-tools-current_session): Lines 78-131
- [Live state patches](#live-state-patches): Lines 133-151
- [Egress redaction (state_transform and chunk_transform)](#egress-redaction-state_transform-and-chunk_transform): Lines 153-188

---

## Two state-management modes

- **Server-managed (`store=...`)**: Genkit owns persistence. Resume with
  `snapshot_id` or `session_id`. Passing `state=`, `messages=`, or `artifacts=`
  to `agent.chat(...)` on a store-backed agent raises `AgentInitError`
  (`FAILED_PRECONDITION`).
- **Client-managed (`store=None`)**: Your caller owns persistence. Seed
  `agent.chat(state=...)` and pass `messages`, `state`, and `artifacts` back on
  subsequent chats.

Custom state holds application data (UI state, workflow counters, active ticket
IDs). Genkit does not inject `state` into the model prompt unless your system
prompt, messages, or tools expose it. Declaring `state_schema` alone leaves
`chat.state` as `None` until client seeding or `session.update_custom(...)`
writes a value.

## Client-managed typed state

```python
from genkit_google_genai import GoogleAI
from pydantic import BaseModel

from genkit.exp import Genkit


class DinerProfile(BaseModel):
    name: str
    allergies: list[str] = []


ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))

agent = ai.define_agent(
    name='conciergeAgent',
    system='Restaurant concierge. Keep replies brief.',
    state_schema=DinerProfile,
)


async def main() -> None:
    # 1. Seed typed state on a storeless agent
    chat = agent.chat(state=DinerProfile(name='Ada', allergies=['peanuts']))
    await chat.send('Recommend an appetizer.')
    assert chat.state is not None
    print(chat.state.name, chat.state.allergies)
    # => Ada ['peanuts']

    # 2. Round-trip messages, state, and artifacts to continue later
    resumed = agent.chat(
        messages=chat.messages,
        state=chat.state,
        artifacts=chat.artifacts,
    )
    await resumed.send('What about dessert?')


if __name__ == '__main__':
    ai.run_main(main())
```

## Mutating state from tools (`current_session`)

Inside an `@ai.tool()`, get the active session with `current_session()` from
`genkit.exp` (`None` outside an agent turn) and update custom state there.

`await sess.update_custom(fn)` is async; `fn` is sync. `fn` receives `None` on
the first write, then whatever the session currently holds: the model instance
you last returned, or a plain dict once state has round-tripped through JSON (a
persistent store, an HTTP client). Normalize it before building the new state:

```python
from typing import Any

from genkit_google_genai import GoogleAI
from pydantic import BaseModel, Field

from genkit.exp import Genkit, current_session
from genkit.exp.agent import InMemorySessionStore


class CaseState(BaseModel):
    case_id: str = ''
    status: str = 'open'


class OpenCaseInput(BaseModel):
    case_id: str = Field(description='Support case identifier')


ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))


@ai.tool(name='openCase', description='Open or switch the active support case.')
async def open_case(input: OpenCaseInput) -> dict[str, Any]:
    sess = current_session()
    if sess is None:
        return {'ok': False, 'error': 'no active agent session'}

    def mutate(c: CaseState | dict[str, Any] | None) -> CaseState:
        base = c if isinstance(c, CaseState) else CaseState.model_validate(c or {})
        return CaseState(case_id=input.case_id, status=base.status)

    await sess.update_custom(mutate)
    return {'ok': True, 'case_id': input.case_id}


agent = ai.define_agent(
    name='supportOps',
    system='Support ops assistant. Call openCase when given a case ID.',
    tools=[open_case],
    state_schema=CaseState,
    store=InMemorySessionStore(),
)
```

## Live state patches

Every `await sess.update_custom(...)` call (from a tool or a
[custom agent](agents-custom.md)) emits an RFC 6902 JSON Patch chunk
(`chunk.raw.custom_patch`). `AgentTurn.stream` applies the patch and puts the
resolved state on `chunk.custom`, typed by `state_schema`. With the `supportOps`
agent above:

```python
chat = agent.chat()
turn = chat.send_stream('Open case SUP-402.')
async for chunk in turn.stream:
    if chunk.custom is not None:
        print(chunk.custom.case_id, chunk.custom.status)
        # => SUP-402 open
res = await turn.response
print(res.state)
# => case_id='SUP-402' status='open'
```

## Egress redaction (`state_transform` and `chunk_transform`)

`state_transform` and `chunk_transform` filter what leaves the server without
altering persisted snapshots:

- **`state_transform(state: SessionState) -> SessionState`**: shapes snapshot
  reads, client-managed `AgentOutput.state`, and streamed custom-patch
  baselines. Must return a `SessionState` (use `state.model_copy(update=...)` so
  `session_id` is preserved).
- **`chunk_transform(chunk: AgentStreamChunk) -> AgentStreamChunk | None`**:
  reshapes or drops individual stream chunks; return `None` to suppress a chunk.

```python
from genkit.exp.agent import AgentStreamChunk, InMemorySessionStore, SessionState


def redact_state(state: SessionState) -> SessionState:
    custom = dict(state.custom or {})
    custom.pop('internal_token', None)
    return state.model_copy(update={'custom': custom})


def drop_debug_artifacts(chunk: AgentStreamChunk) -> AgentStreamChunk | None:
    if chunk.artifact and chunk.artifact.name == 'debug.log':
        return None
    return chunk


guarded_agent = ai.define_agent(
    name='guardedAgent',
    system='Concise support agent.',
    state_transform=redact_state,
    chunk_transform=drop_debug_artifacts,
    store=InMemorySessionStore(),
)
```
agents.md 10.6 KB
# Agents (Experimental)

> Experimental APIs live under `.exp` modules (`genkit.exp`, `genkit.exp.agent`,
> `genkit_fastapi.exp`, `genkit_middleware.exp`, `genkit_google_cloud.exp`) and
> can change between minor releases.

Turn a model and tools into a stateful multi-turn conversation with snapshots,
typed custom state, human approvals, branching, and detached background runs.

Deeper topics: [sessions](agents-sessions.md) ·
[HITL](agents-human-in-the-loop.md) · [branching](agents-branching.md) ·
[background](agents-background.md) · [state](agents-state.md) ·
[artifacts](agents-artifacts.md) · [custom](agents-custom.md) ·
[HTTP](agents-http.md)

- [Define an agent](#define-an-agent): Lines 26-85
- [Tools, progress chunks, and multipart responses](#tools-progress-chunks-and-multipart-responses): Lines 87-117
- [Middleware](#middleware): Lines 119-169
- [Chat and streaming](#chat-and-streaming): Lines 171-206
- [Errors and cancellation](#errors-and-cancellation): Lines 208-247
- [Without a store](#without-a-store): Lines 249-271
- [Verify an agent from the CLI (flow:run)](#verify-an-agent-from-the-cli-flowrun): Lines 273-290

---

## Define an agent

Import `Genkit` from `genkit.exp` to opt into `define_agent`,
`define_prompt_agent`, `define_custom_agent`, and `ai.agent(name)`. Stable
`from genkit import Genkit` does not expose agent methods.

```python
from genkit_google_genai import GoogleAI
from pydantic import BaseModel

from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore


class WeatherInput(BaseModel):
    location: str


class WeatherOutput(BaseModel):
    weather: str
    temperature: str


# 1. Initialize experimental Genkit instance
ai = Genkit(plugins=[GoogleAI()])


# 2. Define a typed tool
@ai.tool(name='getWeather', description='Get weather for a city.')
async def get_weather(input: WeatherInput) -> WeatherOutput:
    return WeatherOutput(weather=f'Sunny in {input.location}', temperature='21°C')


# 3. Register a store-backed agent
agent = ai.define_agent(
    name='weatherAgent',
    model=GoogleAI.gemini('gemini-flash-latest'),
    system='Weather assistant. Use getWeather for weather questions.',
    tools=[get_weather],
    store=InMemorySessionStore(),  # omit store= for client-managed history
)
```

Key `define_agent` keyword arguments:

- **`model`**: `GoogleAI.gemini('gemini-flash-latest')` (or a `'plugin/model'`
  string)
- **`config`**: typed config such as `GeminiConfig(thinking_level='HIGH')` or
  `AnthropicConfig(thinking='adaptive', effort='high')`
- **`use`**: middleware instances (`Retry`, `Fallback`, `ToolApproval`,
  `Filesystem`, `Skills`, `Artifacts`, `Surfaces`)
- **`state_schema`**: Pydantic `BaseModel` typing `chat.state`, `res.state`, and
  `chunk.custom` ([state](agents-state.md))
- **`max_turns`**: tool-loop ceiling per user message (default 50)
- **`state_transform` / `chunk_transform`**: egress hooks that redact client
  views without altering stored state

For `.prompt` files or `ai.define_prompt(...)`, wire the registered prompt name
directly with `ai.define_prompt_agent(name='greeterPrompt', store=...)`. For
custom turn loops, use [`ai.define_custom_agent(...)`](agents-custom.md).

## Tools, progress chunks, and multipart responses

A tool takes at most one typed input parameter (a Pydantic `BaseModel` for
structured arguments or a scalar like `str`, or no input parameter) plus an
optional `ToolContext[ChunkT]` parameter.

```python
import asyncio
from pydantic import BaseModel

from genkit import MultipartToolResponse, Part, ToolContext


class PrepProgress(BaseModel):
    stage: str
    percent: int


@ai.tool(name='prepareOrder', description='Prepare a kitchen order and stream stage progress.')
async def prepare_order(dish: str, ctx: ToolContext[PrepProgress]) -> MultipartToolResponse[dict[str, str]]:
    # 1. Stream partial tool progress (arrives on chunk.tool_responses with part.is_partial == True)
    ctx.send_chunk(PrepProgress(stage='searing', percent=40))
    await asyncio.sleep(0.2)
    ctx.send_chunk(PrepProgress(stage='plating', percent=90))

    # 2. Return structured output alongside extra content parts (e.g. media or text)
    return MultipartToolResponse(
        output={'status': 'ready', 'dish': dish},
        content=[Part.from_text(f'Ticket closed for {dish}.')],
    )
```

## Middleware

Import standard middleware from `genkit_middleware`, session-bound `Artifacts`
from `genkit_middleware.exp`, and generative UI `Surfaces` from `genkit_a2ui`.
Register `Middleware()` in `plugins=[...]` when you want standard middleware
listed in the Dev UI or referenced by `.prompt` files; passing instances in
`use=[...]` works either way.

- **`Filesystem`** (`genkit_middleware`): `list_files` and `read_file` scoped to
  `root_dir`; pass `allow_write_access=True` to add `write_file` and
  `edit_file`.
- **`ToolApproval`** (`genkit_middleware`): tools in `allowed_tools` run
  automatically; all other tools pause the turn with an interrupt
  ([HITL](agents-human-in-the-loop.md)). It gates every tool call, including the
  ones `Filesystem` and `Artifacts` add.
- **`Skills`** (`genkit_middleware`): injects `SKILL.md` descriptions and
  exposes `use_skill`.
- **`Retry` / `Fallback`** (`genkit_middleware`): `Retry` retries transient
  failures (`UNAVAILABLE`, `DEADLINE_EXCEEDED`, `RESOURCE_EXHAUSTED`, `ABORTED`,
  `INTERNAL` by default); `Fallback` switches to alternate models.
- **`Artifacts`** (`genkit_middleware.exp`): adds `read_artifact` and
  `write_artifact` tools plus an active artifact listing in the system prompt
  ([artifacts](agents-artifacts.md)).
- **`Surfaces`** (`genkit_a2ui`): A2UI surface instructions, validation, and
  part parsing.

```python
from genkit_google_genai import GoogleAI
from genkit_middleware import Filesystem, Middleware, Retry, Skills, ToolApproval
from genkit_middleware.exp import Artifacts

from genkit.exp import Genkit
from genkit.exp.agent import FileSessionStore

ai = Genkit(plugins=[GoogleAI(), Middleware()])

coding_agent = ai.define_agent(
    name='codingAgent',
    model=GoogleAI.gemini('gemini-flash-latest'),
    system='Coding assistant. Explore with list_files/read_file before editing.',
    use=[
        ToolApproval(allowed_tools=['list_files', 'read_file', 'read_artifact', 'use_skill']),
        Filesystem(root_dir='./workspace', allow_write_access=True),
        Artifacts(),
        Skills(skill_paths=['./skills']),
        Retry(max_retries=3),
    ],
    store=FileSessionStore('./.snapshots'),
    max_turns=30,
)
```

## Chat and streaming

Run one turn at a time per `AgentChat`. Use `ai.run_main(main())` for standalone
scripts.

```python
async def main() -> None:
    chat = agent.chat()

    # 1. One-shot turn
    res = await chat.send('Weather in Tokyo?')
    print(res.text, res.snapshot_id)
    # => It is 21°C and sunny in Tokyo. 8f3c...

    # 2. Streamed turn (.stream yields AgentChunk, .response resolves to AgentResponse)
    turn = chat.send_stream('What about Paris?')
    async for chunk in turn.stream:
        if chunk.text:
            print(chunk.accumulated_text, end='\r', flush=True)
    final = await turn.response

    # 3. Rehydrate history from the store on a new chat instance
    resumed = await agent.load_chat(snapshot_id=final.snapshot_id)
    followup = await resumed.send('Which cities did we check?')
    print(followup.text)


if __name__ == '__main__':
    ai.run_main(main())
```

- **`await agent.load_chat(snapshot_id=...)`**: fetches the stored snapshot
  immediately so `chat.messages`, `chat.state`, and `chat.artifacts` are
  populated locally.
- **`agent.chat(session_id=...)`**: attaches a lazy resume handle that continues
  from the session's last completed turn, skipping any failed or aborted leaf.

## Errors and cancellation

Genkit separates turn failures from call failures:

- **Turn failure (`res.error`)**: When an agent turn starts and fails at
  runtime, `chat.send(...)` does **not** raise. It returns `AgentResponse` with
  `res.finish_reason == AgentFinishReason.FAILED`, `res.text == ''`, and
  `res.error` (`Failure` with `status`, `message`, `details`, and
  `reason: ErrorReason`). The chat drops the unanswered user prompt from
  `chat.messages`, and the next `send()` continues from the last completed
  snapshot.
- **No turn result (`GenkitError`)**: When no turn runs at all (dropped HTTP
  connection, or `AgentInitError` from passing `snapshot_id` to a storeless
  agent), `chat.send(...)` raises `GenkitError` and restores local chat state.
  Mismatched init arguments (a `state` blob to a store-backed agent, or
  `messages`/`state` mixed with a resume id) raise `AgentInitError` from
  `agent.chat(...)` itself.
- **Cancellation**: native `asyncio.CancelledError`; put tool cleanup in `try` /
  `finally`. `await turn.abort()` detaches the client stream only. To cancel a
  running turn server-side, start it with `chat.detach(...)` and call
  `await task.abort()`; `chat.abort()` during a foreground `send()` does not
  stop that turn
  ([background](agents-background.md#client-detach-vs-server-cancellation)).

```python
from genkit import ErrorReason, GenkitError
from genkit.exp.agent import AgentFinishReason

try:
    res = await chat.send('Run portfolio rebalance.')
except GenkitError as err:
    # No turn ran (transport drop or invalid init)
    print(err.status, err.message)
else:
    if res.error:
        # Turn ran and failed; res.finish_reason == AgentFinishReason.FAILED
        assert res.finish_reason == AgentFinishReason.FAILED
        if res.error.reason == ErrorReason.INVALID_OUTPUT:
            print('Truncated structured output:', res.error.message)
```

## Without a store

Omit `store=` when the client owns conversation state. `snapshot_id` stays
`None`; round-trip `messages`, `state`, and `artifacts` into the next
`agent.chat(...)` call:

```python
stateless = ai.define_agent(
    name='echoNoStore',
    model=GoogleAI.gemini('gemini-flash-latest'),
    system='Answer briefly and remember context.',
)

chat = stateless.chat()
await chat.send('My name is Ada.')

resumed = stateless.chat(
    messages=chat.messages,
    state=chat.state,
    artifacts=chat.artifacts,
)
await resumed.send('What is my name? One word.')
```

## Verify an agent from the CLI (`flow:run`)

`genkit flow:run` invokes flows, not agents directly. Wrap a turn in a small
flow and propagate `res.error` so failures surface cleanly:

```python
from genkit import GenkitError


@ai.flow()
async def try_weather_agent(message: str) -> str:
    res = await agent.chat().send(message)
    if res.error:
        raise GenkitError(status=res.error.status, message=res.error.message, details=res.error.details)
    return res.text

# genkit flow:run try_weather_agent '"Weather in Tokyo?"' -- uv run src/main.py
```
common-errors.md 15.2 KB
# Common Errors — Genkit Python 0.13

Find the symptom, apply the fix. Every message below comes from a real 0.13 run.
Upgrading a 0.12 codebase? Read
[Migrating from 0.12 to 0.13](migrating-from-0.12.md).

- [ai.generate Returns Empty Text and Does Not Raise](#aigenerate-returns-empty-text-and-does-not-raise): Lines 25-57
- [Thinking level MINIMAL is not supported for this model](#thinking-level-minimal-is-not-supported-for-this-model): Lines 61-80
- [ImportError on ActionRunContext, ToolRunContext, MediaPart, TextPart, or genkit.agent](#importerror-on-actionruncontext-toolruncontext-mediapart-textpart-or-genkitagent): Lines 84-119
- [GenkitError INVALID_ARGUMENT on Config Keys](#genkiterror-invalid_argument-on-config-keys): Lines 123-151
- [GenkitError INVALID_ARGUMENT: API Key in config](#genkiterror-invalid_argument-api-key-in-config): Lines 155-167
- [GenkitError NOT_FOUND: Unprefixed Model String](#genkiterror-not_found-unprefixed-model-string): Lines 171-183
- [Vertex AI Fails on gemini-flash-latest](#vertex-ai-fails-on-gemini-flash-latest): Lines 187-197
- [TypeError When Defining or Calling Flows and Tools](#typeerror-when-defining-or-calling-flows-and-tools): Lines 201-232
- [Served Flow Returns 404, 500, or the Wrong Auth Status](#served-flow-returns-404-500-or-the-wrong-auth-status): Lines 236-271
- [response.output Is None on Structured Output](#responseoutput-is-none-on-structured-output): Lines 275-290
- [response.json Is Not the Model Output](#responsejson-is-not-the-model-output): Lines 294-305
- [Prompt Variable Sent Literally](#prompt-variable-sent-literally): Lines 309-319
- [Streaming TypeError or a Flow That Keeps Running After break](#streaming-typeerror-or-a-flow-that-keeps-running-after-break): Lines 323-344
- [Cloud Telemetry Enabled but Spans Do Not Reach Cloud Trace](#cloud-telemetry-enabled-but-spans-do-not-reach-cloud-trace): Lines 348-359
- [Interrupts and Agent Session Pitfalls](#interrupts-and-agent-session-pitfalls): Lines 363-392

---

## `ai.generate` Returns Empty Text and Does Not Raise

`ai.generate` boxes model-side failures into the response: provider rejections,
`UNAVAILABLE`, rate limits, and model IDs the provider does not serve. You get
`response.text == ''`, `response.finish_reason == 'failed'`, and a `Failure` on
`response.error`. Code that only reads `response.text` silently continues with
an empty string.

```python
from genkit import Genkit
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()])

# 1. Prefixed but unserved model ID: no exception
res = await ai.generate(model='googleai/gemini-9-ultra', prompt='Suggest a dish.')
print(repr(res.text), res.finish_reason)
# => '' FinishReason.FAILED

# 2. Check response.error after every call
if res.error:
    print(res.error.status, res.error.message)
    # => NOT_FOUND models/gemini-9-ultra is not found for API version v1beta, or is not supported for generateContent. ...
```

Problems caught before the request is sent raise instead:

- **`ValueError`** from `GoogleAI()` when `GEMINI_API_KEY` is unset
  (`[Genkit] GEMINI_API_KEY environment variable not set.`).
- **`GenkitError` `UNAUTHENTICATED`** on the first `ai.generate` when the key is
  invalid (`API key not valid. Please pass a valid API key.`).
- **`GenkitError`** for an unprefixed model string, unknown config keys, and
  `api_key` in config (sections below).

---

## `Thinking level MINIMAL is not supported for this model`

`gemini-flash-latest` rejects `thinking_level='MINIMAL'`. The call returns a
failed response (see above), not an exception:

```python
from genkit_google_genai import GeminiConfig

res = await ai.generate(prompt='Name one dessert.', config=GeminiConfig(thinking_level='MINIMAL'))
print(res.error.status, res.error.message)
# => INVALID_ARGUMENT Thinking level MINIMAL is not supported for this model. Please retry with other thinking level.
```

Use `'LOW'`, `'MEDIUM'`, or `'HIGH'`:

```python
res = await ai.generate(prompt='Name one dessert.', config=GeminiConfig(thinking_level='LOW'))
print(res.text)
# => Tiramisu.
```

---

## `ImportError` on `ActionRunContext`, `ToolRunContext`, `MediaPart`, `TextPart`, or `genkit.agent`

```text
ImportError: cannot import name 'ActionRunContext' from 'genkit'
ImportError: cannot import name 'MediaPart' from 'genkit'
ModuleNotFoundError: No module named 'genkit.agent'
AttributeError: 'Genkit' object has no attribute 'define_agent'
ValidationError: 1 validation error for Part
  Value error, Part(root=...) is gone; use Part.from_text or Part(text=...)
```

Each symbol has one public home:

```python
# Contexts
from genkit import FlowContext, ToolContext
from genkit.model import ModelContext

# Parts
from genkit import Media, Message, Part, Role
text_part = Part.from_text('Hello')
img_part = Part.from_media('https://example.com/photo.jpg', content_type='image/jpeg')

# Experimental agents and integrations (define_agent exists only on genkit.exp.Genkit)
from genkit.exp import Genkit, current_session
from genkit.exp.agent import Agent, InMemorySessionStore, Session
from genkit_fastapi.exp import serve_agent
from genkit_middleware.exp import Artifacts
```

Two different `Middleware` imports:

- `from genkit_middleware import Middleware, Retry, ToolApproval` imports the
  **`Middleware()` plugin** and built-in middleware.
- `from genkit.middleware import Middleware, MiddlewareContext` imports the
  **base class** for custom middleware.

---

## `GenkitError` `INVALID_ARGUMENT` on Config Keys

Genkit validates config before calling the model. Typos, nested dicts, and
fields that moved off config all raise:

```text
INVALID_ARGUMENT: googleai/gemini-flash-latest: unknown config key 'temprature'; put provider-only settings in config['extra']
INVALID_ARGUMENT: thinking_config was flattened; use include_thoughts / thinking_budget / thinking_level
INVALID_ARGUMENT: googleai/gemini-flash-latest: unknown config key 'tool_choice'; put provider-only settings in config['extra']
```

Use flat typed config, put provider-native keys in `extra`, and pass
`tool_choice` on the call:

```python
from genkit_google_genai import GeminiConfig

cfg = GeminiConfig(
    temperature=0.2,
    thinking_level='HIGH',
    include_thoughts=True,
    extra={'seed': 7},
)
res = await ai.generate(prompt='Pick a wine for salmon.', config=cfg, tool_choice='required', tools=[...])
```

`GeminiConfig.extra` is wire-shaped and deep-merged into the request body, so
nested provider fields go under their wire key (for example
`extra={'generationConfig': {...}}`).

---

## `GenkitError` `INVALID_ARGUMENT`: API Key in `config`

```text
INVALID_ARGUMENT: API key belongs in context.secrets, not config. Pass the key as context={'secrets': {'api_key': ...}}.
```

Set the key on the plugin, or pass a per-request key in `context`:

```python
# Whole app: GoogleAI(api_key=...), OpenAI(api_key=...)
# Per request:
await ai.generate(prompt='Hello', context={'secrets': {'api_key': user_key}})
```

---

## `GenkitError` `NOT_FOUND`: Unprefixed Model String

```text
NOT_FOUND: Failed to resolve model 'gemini-flash-latest'. Ensure the model name includes the plugin namespace (e.g., 'plugin/model').
```

Plain strings need the `<plugin>/` prefix (`'googleai/gemini-flash-latest'`,
`'openai/gpt-4o'`). Model ref helpers (`GoogleAI.gemini('gemini-flash-latest')`,
`Anthropic.claude('claude-sonnet-4-6')`, `OpenAI.gpt('gpt-5.2')`) add it for
you.

A prefixed ID the provider does not serve resolves and fails at call time on
`response.error` instead (see the first section).

---

## Vertex AI Fails on `gemini-flash-latest`

Vertex AI does not serve the Gemini API's rotating `-latest` aliases
(`gemini-flash-latest`, `gemini-flash-lite-latest`, `gemini-pro-latest`). The
Vertex plugin's known-model list omits them. Use a versioned ID:

```python
from genkit_google_genai import VertexAI

ai = Genkit(plugins=[VertexAI(location='us-central1')], model=VertexAI.gemini('gemini-3.5-flash'))
```

---

## `TypeError` When Defining or Calling Flows and Tools

```text
TypeError: Tool function must be async. Got sync function: lookup_reservation
TypeError: Flow must be async: sync_menu
TypeError: tool 'check_allergens' takes one input, but 'allergen' is a second parameter. Put the fields on one input model, or annotate 'allergen' as ToolContext.
TypeError: Genkit() takes no positional arguments, got 1. Pass keyword arguments instead, e.g. Genkit(plugins=[...], model="...").
TypeError: Action.run() takes from 1 to 2 positional arguments but 3 were given
```

- `@ai.tool()` and `@ai.flow()` functions must be `async def`.
- Each takes at most one input parameter. A context parameter must be annotated
  (`ctx: FlowContext` or `ctx: ToolContext`); an unannotated `ctx` counts as a
  second input. Wrap multi-field input in one Pydantic `BaseModel`.
- Constructors (`Genkit`, plugins, `GenkitError`) and every option after the
  input on `.run(...)` are keyword-only:

```python
from pydantic import BaseModel
from genkit import ToolContext

class AllergenCheck(BaseModel):
    dish: str
    allergen: str

@ai.tool()
async def check_allergens(check: AllergenCheck, ctx: ToolContext) -> bool:
    """Return True if the dish contains the allergen."""
    return check.allergen in MENU[check.dish].allergens

res = await plan_menu.run(payload, on_chunk=handle_chunk, context={'uid': 'u1'})
```

---

## Served Flow Returns 404, 500, or the Wrong Auth Status

Over HTTP (`serve_flow`, `serve_agent`, `genkit_fastapi_handler`,
`handle_genkit_request`):

- **`404 {"detail":"Not Found"}`**: the route is the Python function name.
  `menu_suggestion_flow` mounts at `POST /menu_suggestion_flow`, not
  `/menuSuggestionFlow`. Override with `serve_flow(flow, base_path=...)`.
- **`500 {"message":"Internal Error","status":"INTERNAL"}`**: the flow raised
  `GenkitError` or any non-`PublicError` exception. Genkit logs the traceback
  server-side and redacts the body. Raise `PublicError` for errors the client
  should see.
- **`400 ... "status":"INVALID_ARGUMENT"`**: the request `data` failed input
  validation.
- **`500 Internal Server Error` (plain text) from a `context_dependency`**:
  `serve_flow(..., context_dependency=...)` runs a FastAPI dependency before
  Genkit's handler, so a `PublicError` raised there is not mapped. Raise
  `fastapi.HTTPException(status_code=401)` in dependencies;
  `PublicError('UNAUTHENTICATED', ...)` maps to 401 only inside a
  `genkit_fastapi_handler` `context_provider` or the flow itself.

```python
from genkit import PublicError

@ai.flow()
async def get_invoice(invoice_id: str) -> dict:
    inv = await find_invoice(invoice_id)
    if inv is None:
        raise PublicError('NOT_FOUND', f'Invoice {invoice_id} not found')
    return inv

# POST /get_invoice {"data": "INV-9"}
# => 404 {"message":"Invoice INV-9 not found","status":"NOT_FOUND"}
```

Full status mapping: [FastAPI](fastapi.md#http-error-redaction-and-publicerror).

---

## `response.output` Is `None` on Structured Output

When a JSON response is truncated (often by `max_output_tokens`) or does not
parse against the schema, `response.output` is `None` and
`response.error.reason` is `ErrorReason.INVALID_OUTPUT`:

```python
from genkit import ErrorReason

res = await ai.generate(prompt='Summarize this invoice.', output_schema=InvoiceSummary)
if res.output is None and res.error and res.error.reason == ErrorReason.INVALID_OUTPUT:
    print(res.error.message)
    # => Model output was not valid JSON for the requested schema: {"vendor": "Acme", "total": 12
```

Raise `max_output_tokens` or simplify the schema, then retry.

---

## `response.json` Is Not the Model Output

`response.json` is Pydantic's deprecated `BaseModel.json` method. Calling it
serializes the whole `ModelResponse` and emits `PydanticDeprecatedSince20`.
Read:

- `response.text` for plain text.
- `response.output` for structured output.
- `response.message` for the full message.

`GenkitError` exposes `e.message`, `e.status`, `e.details`, `e.reason`, and
`e.__cause__`. `e.original_message` raises `AttributeError`.

---

## Prompt Variable Sent Literally

`ai.generate(prompt=..., system=...)` sends strings verbatim. The model receives
`Say hello to {{name}}.` as written. Render templates through `ai.define_prompt`
or a `.prompt` file:

```python
greet = ai.define_prompt(name='greet', prompt='Say hello to {{name}}.')
res = await greet({'name': 'Sam'})
# Model receives: Say hello to Sam.
```

---

## Streaming `TypeError` or a Flow That Keeps Running After `break`

```text
TypeError: object ModelStreamResponse can't be used in 'await' expression
```

1. Do not `await` `ai.generate_stream(...)`, `flow.stream(...)`, or
   `chat.send_stream(...)`. Iterate the stream, then `await` the final response:
   ```python
   sr = ai.generate_stream(prompt='Describe the tasting menu.')
   async for chunk in sr.stream:
       print(chunk.text, end='')
   final = await sr.response
   ```
2. To stop a flow stream early, use `async with`. Leaving the block cancels the
   flow:
   ```python
   async with course_flow.stream(payload) as stream:
       async for chunk in stream:
           if chunk == 'dessert':
               break  # course_flow receives CancelledError
   ```

---

## Cloud Telemetry Enabled but Spans Do Not Reach Cloud Trace

By default in local development (`GENKIT_ENV=dev`),
`enable_google_cloud_telemetry()` runs in local-only mode to prevent polluting
Cloud Trace with local run data. To export traces to GCP from local development,
pass `force_dev_export=True`:

```python
from genkit_google_cloud import enable_google_cloud_telemetry

enable_google_cloud_telemetry(project='bistro-prod', force_dev_export=True)
```

---

## Interrupts and Agent Session Pitfalls

- **`except Exception:` does not catch `Interrupt`**: `Interrupt` subclasses
  `BaseException`, so a tool's catch-all cannot swallow approval interrupts. Put
  side-effect cleanup in `finally`.
- **Approval resume**: build restart parts with
  `part.restart(resumed_metadata={'tool_approved': True})` on items from
  `res.interrupts` (see
  [agents-human-in-the-loop.md](agents-human-in-the-loop.md)).
- **`ImportError: cannot import name 'AgentError'`**: failed turns do not raise.
  `chat.send()` returns a turn with `finish_reason == AgentFinishReason.FAILED`
  and `res.error`. `AgentInitError` raises from `agent.chat(...)` on bad init;
  `send` raises `GenkitError` only when no turn result arrives.
- **`res.snapshot_id` is `None`**: the agent has no store. Pass
  `store=InMemorySessionStore()` to `define_agent` (see [agents.md](agents.md)).
- **`AgentInitError: FAILED_PRECONDITION: Cannot send 'state' to a
  server-managed agent (one with a store). Send 'snapshot_id' or 'session_id'
  instead.`**: store-backed chats resume by ID. Mutate state inside the turn
  (see [agents-state.md](agents-state.md)).
- **Resume picks the wrong branch after a fork**: `session_id` resumes the most
  recently created leaf. Pass the branch's `snapshot_id` (see
  [agents-branching.md](agents-branching.md)).
- **Resume after a failed turn**: only `completed` snapshots resume by
  `snapshot_id`. Use `agent.chat(session_id=...)` to continue from the last good
  turn.
- **`chat.abort()` does nothing**: during a foreground `send` it is a no-op. Run
  the turn with `detach()` and call `await task.abort()` (see
  [agents-background.md](agents-background.md)).
- **Remote client mismatches**: align `state_management` with the server and
  omit trailing slashes on the base URL (see [agents-http.md](agents-http.md)).
dev-workflow.md 6.0 KB
# Dev Workflow — Genkit Python

- [Agent Responsibility](#agent-responsibility): Lines 14-30
- [Step 1: Get a Gemini API Key](#step-1-get-a-gemini-api-key): Lines 34-37
- [Step 2: Export the API Key](#step-2-export-the-api-key): Lines 41-51
- [Step 3: Install Dependencies](#step-3-install-dependencies): Lines 55-65
- [Step 4: Start the Dev UI](#step-4-start-the-dev-ui): Lines 69-114
- [Step 5: Test in the Dev UI](#step-5-test-in-the-dev-ui): Lines 118-130
- [CLI Commands](#cli-commands): Lines 134-183
- [Troubleshooting](#troubleshooting): Lines 187-195

---

## Agent Responsibility

After generating or migrating code:

1. Run the project's type checker (`pyright`, `mypy`, or `ty`) in `.venv` so
   typed configs (`GeminiConfig`), generic contexts (`FlowContext[T]`,
   `ToolContext[T]`), keyword-only signatures, and `OutputT | None` checks pass
   before handing off.
2. Give the developer:
   - Copy-paste setup commands with absolute paths
   - The `genkit start` command to run in their foreground terminal (expected to
     block)
   - Exact Dev UI steps to exercise the flow or agent and inspect traces

Do not run `genkit start` as an interactive blocking command on the developer's
behalf unless explicitly asked; use `genkit flow:run` for automated one-shot
verification.

---

## Step 1: Get a Gemini API Key

If the developer needs a key, create one at
`https://aistudio.google.com/apikey`.

---

## Step 2: Export the API Key

```bash
export GEMINI_API_KEY=your-api-key-here
```

Persist across shell sessions if desired:

```bash
echo 'export GEMINI_API_KEY=your-api-key-here' >> ~/.zshrc && source ~/.zshrc
```

---

## Step 3: Install Dependencies

Replace `/path/to/your-project` with the project's absolute path:

```bash
cd /path/to/your-project
uv add 'genkit==0.13.*' 'genkit-google-genai==0.13.*'
```

(Run `uv init` first if `pyproject.toml` does not exist yet — see
[Setup](setup.md).)

---

## Step 4: Start the Dev UI

The examples below use this `src/main.py`:

```python
from pydantic import BaseModel

from genkit import Genkit

ai = Genkit()


class OrderInput(BaseModel):
    text: str


@ai.flow()
async def order_flow(inp: OrderInput) -> str:
    return f'order: {inp.text}'


async def main() -> None:
    print(await order_flow(OrderInput(text='smoked salmon tartine')))


if __name__ == '__main__':
    ai.run_main(main())
    # => order: smoked salmon tartine
    #    Under `genkit start`, the process stays up for the Dev UI until Ctrl+C.
```

Run in a foreground terminal (blocks until stopped with `Ctrl+C`):

```bash
cd /path/to/your-project
GEMINI_API_KEY=your-api-key-here genkit start -- uv run src/main.py
```

For FastAPI apps, run uvicorn under `genkit start` instead; the reflection
server starts on a background thread (see [FastAPI](fastapi.md)):

```bash
GEMINI_API_KEY=your-api-key-here genkit start -- uv run uvicorn main:app --reload
```

Wait for the CLI to print `Genkit Developer UI: http://localhost:4000`.

---

## Step 5: Test in the Dev UI

1. Open **`http://localhost:4000`** in a browser.
2. Pick the registered flow, prompt, or model from the left sidebar. Flows
   appear under their Python function name (e.g. `order_flow`).
3. Paste JSON matching the flow's single input parameter, e.g. for
   `order_flow(inp: OrderInput)`:
   ```json
   {"text": "smoked salmon tartine"}
   ```
4. Click **Run** and inspect the validated output on the right.
5. Open **Traces** in the left sidebar to inspect every span, rendered prompt,
   tool call, token count, latency, and unwrapped error stack trace.

---

## CLI Commands

`genkit start` sets `GENKIT_ENV=dev`, runs your command, and stores local traces
from every Genkit action under `.genkit/` in the project root. The app's stdout
and stderr pass through. Running `uv run` directly skips the reflection server
and local trace capture.

**Persistent dev runtime:**
```bash
genkit start -- uv run src/main.py
genkit start --noui -- uv run src/main.py                 # no Dev UI; runtime still blocks until Ctrl+C
genkit start --non-interactive -- uv run src/main.py      # CLI prompts take the default choice (CI/agents)
genkit start --port 4001 -- uv run src/main.py            # Dev UI on another port
```

**One-shot flow execution (`flow:run`):** with `-- <cmd>`, it starts the app,
runs one `@ai.flow()` by its Python function name, prints `Result:` and
`Trace ID:`, and exits:
```bash
genkit flow:run order_flow '{"text": "smoked salmon tartine"}' -- uv run src/main.py
# => Result:
#    order: smoked salmon tartine
#    Trace ID: 395f73c3d0d662c28711239a4354bf53
```
Without `-- <cmd>`, `flow:run` targets a runtime already started by
`genkit start` in the same directory, and fails with `No runtimes found` if none
is running. A `str` input is a JSON string: `'"risotto"'`.

`flow:run` runs `@ai.flow()` actions, not agents. Wrap one agent turn in a small
flow to test it (see [Agents](agents.md#verify-an-agent-from-the-cli-flowrun)).

**Inspecting traces from the terminal:**
```bash
genkit trace:list --limit 5              # recent trace IDs with status, input, output
genkit trace:get <traceId>               # human-readable execution tree
genkit trace:get <traceId> --format json # machine-readable JSON: spans, attributes, input, output
```
Always pass `--format json` when piping into `jq` or other parsers (without it,
`trace:get` prints a human-readable execution tree):
```bash
genkit trace:get <traceId> --format json | jq -r '.spans[].displayName'
# => order_flow
```

**Built-in CLI documentation lookup:**
```bash
genkit docs:search "streaming" python
genkit docs:list python
genkit docs:read python/flows.md
```

---

## Troubleshooting

- `genkit: command not found` — `npm install -g genkit-cli`
- `GEMINI_API_KEY` missing — `export GEMINI_API_KEY=your-key`
- Port 4000 busy — `genkit start --port 4001 -- uv run src/main.py`
- `uv: command not found` — `pipx install uv` or `pip install uv`
- Action missing in Dev UI — ensure standalone scripts enter via
  `ai.run_main(main())` and check terminal output for startup import or
  validation errors (see [Common Errors](common-errors.md)).
dotprompt.md 6.6 KB
# Dotprompt — Genkit Python

- [What It Is](#what-it-is): Lines 15-20
- [File Format](#file-format): Lines 22-65
- [Python Setup](#python-setup): Lines 67-88
- [Calling a Prompt (Prompt)](#calling-a-prompt-prompt): Lines 90-125
- [Streaming from a Prompt](#streaming-from-a-prompt): Lines 127-145
- [Render Without Generating](#render-without-generating): Lines 147-161
- [Helpers](#helpers): Lines 163-187
- [Variants and Partials](#variants-and-partials): Lines 189-196
- [Prompts with Tools and Middleware](#prompts-with-tools-and-middleware): Lines 198-220

---

## What It Is

`.prompt` files pair YAML frontmatter (model, config, input/output schemas,
tools, middleware) with Handlebars templates. Handlebars templates **only**
render inside `.prompt` files and `ai.define_prompt(...)` — strings passed to
`ai.generate(prompt=..., system=...)` are sent to the model verbatim.

## File Format

Place `.prompt` files inside `prompts/` and pass `prompt_dir=...` to
`Genkit(...)`:

```yaml
---
model: googleai/gemini-flash-latest
config:
  temperature: 0.4
input:
  default:
    tone: practical
  schema:
    food: string
    tone?: string                 # optional scalar - `field?: type`
    ingredients?(array): string   # optional array/object uses parenthetical syntax
output:
  schema: Recipe                  # references a schema registered via ai.define_schema()
  format: json
---
{{role "system"}}
You are a chef. Keep recipes {{tone}}.

{{role "user"}}
Generate a recipe for {{food}}.
{{#if ingredients}}
Prefer these ingredients:
{{list ingredients}}
{{/if}}
```

Use `{{role "system"}}` and `{{role "user"}}` to emit distinct message roles; a
template without `{{role ...}}` becomes a single user message.

**Input & output validation:**

- Prompt inputs **are validated** against `input.schema` (or `input_schema=` on
  `define_prompt`) before calling the model, and `input.default` values from
  `.prompt` frontmatter are filled in automatically.
- When `output.schema` names a Pydantic class registered with
  `ai.define_schema('Recipe', Recipe)`, `response.output` is validated and
  returned directly as `Recipe | None` (`None` when the model's JSON is
  truncated or malformed; check `response.finish_reason`).

## Python Setup

```python
from pathlib import Path
from pydantic import BaseModel
from genkit import Genkit, Prompt
from genkit_google_genai import GoogleAI

ai = Genkit(
    plugins=[GoogleAI()],
    model=GoogleAI.gemini('gemini-flash-latest'),
    prompt_dir=Path(__file__).resolve().parent.parent / 'prompts',
)


class Recipe(BaseModel):
    title: str
    steps: list[str]


ai.define_schema('Recipe', Recipe)
```

## Calling a Prompt (`Prompt`)

`ai.prompt(...)` and `ai.define_prompt(...)` return a `Prompt`. There is no
`.execute()` method — call and `await` the `Prompt` directly:

```python
recipe_prompt: Prompt = ai.prompt('recipe')

# Call options use the same keyword names as `ai.generate`.
# `config` merges key-by-key over the prompt's frontmatter config.
# `output_schema` is fixed by the prompt and cannot be overridden per call.
response = await recipe_prompt(
    {'food': 'banana bread', 'ingredients': ['walnuts', 'cinnamon']},
    config={'temperature': 0.2},
)
if response.output is not None:
    recipe: Recipe = response.output

# Variant (`prompts/recipe.quick.prompt`)
quick_res = await ai.prompt('recipe', variant='quick')({'food': 'banana bread'})
```

### Code-Defined Prompts (`ai.define_prompt`)

```python
class GreetingInput(BaseModel):
    name: str


greet = ai.define_prompt(
    name='greet',
    input_schema=GreetingInput,
    prompt='Say hello to {{name}}.',
)
res = await greet(GreetingInput(name='Ana'))
```

## Streaming from a Prompt

`prompt.stream(...)` is synchronous (do not `await` it); iterate `.stream` and
`await` `.response`:

```python
from genkit import FlowContext

@ai.flow()
async def stream_recipe(food: str, ctx: FlowContext[str]) -> str:
    sr = ai.prompt('recipe').stream({'food': food})
    chunks: list[str] = []
    async for chunk in sr.stream:
        if chunk.text:
            ctx.send_chunk(chunk.text)
            chunks.append(chunk.text)
    final = await sr.response
    return final.text or ''.join(chunks)
```

## Render Without Generating

`render(...)` takes the same arguments as a call and returns the
`GenerateActionOptions` (model, config, messages, output schema) without calling
a model. Use it to debug templates and input defaults:

```python
rendered = await ai.prompt('recipe').render({'food': 'focaccia'})
print(rendered.model, rendered.config)
# => googleai/gemini-flash-latest {'temperature': 0.4}
for message in rendered.messages:
    print(message.role, message.text.strip())
# => system You are a chef. Keep recipes practical.
# => user Generate a recipe for focaccia.
```

## Helpers

Register Handlebars helpers with `ai.define_helper(name, fn)`. Dotprompt calls
every helper as `fn(params, options)`: `params` is the list of positional
template arguments, `options` carries hash arguments. A one-argument function
raises `TypeError` at render time.

```python
from typing import Any


def list_helper(params: list[Any], options: Any) -> str:
    items = params[0] if params else None
    if not isinstance(items, list):
        return ''
    return '\n'.join(f'- {item}' for item in items)


ai.define_helper('list', list_helper)
```

Built-in helpers: `role`, `json`, `media`, `history`, `section`, `ifEquals`,
`unlessEquals`.

Use `{{list ingredients}}` in the `.prompt` body.

## Variants and Partials

- **Variants**: save `<name>.<variant>.prompt` (e.g. `recipe.vegan.prompt`) and
  load with `ai.prompt('recipe', variant='vegan')`.
- **Partials**: prefix partial files with `_` (e.g.
  `prompts/_disclaimer.prompt`) or register with
  `ai.define_partial('disclaimer', '...')`, then include via `{{>disclaimer}}`
  or `{{>disclaimer region=region}}`.

## Prompts with Tools and Middleware

- **Tools**: list registered tool names under `tools:` in YAML frontmatter, or
  pass `tools=[lookup_rate]` when calling
  `await prompt(input, tools=[lookup_rate])`. The tool loop stops after
  `maxTurns` (frontmatter) or `max_turns=` (call), default 50.
- **Middleware**: pass instances at call time with `use=[Retry(max_retries=2)]`.
  To name middleware under `use:` in frontmatter, register it first: add
  `Middleware()` from `genkit_middleware` to `Genkit(plugins=[...])` (registers
  `retry`, `fallback`, `tool_approval`, `skills`, `filesystem`) or define your
  own with `@ai.middleware`. An unregistered name fails with `NOT_FOUND`.

```yaml
---
model: googleai/gemini-flash-latest
tools: [lookup_rate]
use:
  - name: retry
    config:
      max_retries: 2
---
Convert {{amount}} USD to EUR.
```
evals.md 7.3 KB
# Evals — Genkit Python (0.13 Only; Removed in 1.0)

> **Warning:** 0.13 is the last release with evaluators (`ai.define_evaluator`,
> `ai.define_batch_evaluator`, `ai.evaluate`, `genkit.evaluator`). Genkit 1.0
> cuts them and the `genkit-evaluators` package from the 1.0 release; evaluation
> will return as an additive feature in a later release. `genkit-evaluators`
> 0.13 requires `genkit<1`.
> - **New projects:** do not add `genkit-evaluators` or `define_evaluator`
>   unless you intend to stay pinned to `genkit==0.13.*`. Prefer `pytest`
>   assertions against your flows and prompts until evaluation returns.
> - **Migrating from 0.12:** stop and ask the developer before porting evaluator
>   code (see [Migrating from 0.12 to 0.13](migrating-from-0.12.md)).

The patterns below document the `0.13.*` evaluator API for projects staying on
the 0.13 release line.

- [Install (0.13 Only)](#install-013-only): Lines 27-31
- [Two Evaluator Types](#two-evaluator-types): Lines 33-41
- [Dataset Format](#dataset-format): Lines 43-56
- [Built-In Evaluators and Programmatic Execution](#built-in-evaluators-and-programmatic-execution): Lines 58-84
- [BYO Evaluator (EvaluatorResponse, Score, ScoreStatus, ScoreDetails)](#byo-evaluator-evaluatorresponse-score-scorestatus-scoredetails): Lines 86-131
- [LLM-Based Judge](#llm-based-judge): Lines 133-193
- [CLI Execution](#cli-execution): Lines 195-210

---

## Install (0.13 Only)

```bash
uv add 'genkit-evaluators==0.13.*'
```

## Two Evaluator Types

1. **Built-in** — provided by `genkit-evaluators`, registered via
   `register_genkit_evaluators(ai)` (`genkitEval/regex`,
   `genkitEval/deep_equal`, `genkitEval/jsonata`). They are deterministic and
   need no model plugin or `GEMINI_API_KEY`. Pass `metrics=['regex']` to
   register a subset.
2. **BYO** — custom row-by-row (`ai.define_evaluator`) or batch
   (`ai.define_batch_evaluator`) functions, including LLM judges.

## Dataset Format

`genkit eval:run` reads a JSON array:

```json
[
  {"testCaseId": "dessert", "input": "Suggest a dessert.", "output": "Banana bread", "reference": "(?i)banana"},
  {"testCaseId": "starter", "input": "Suggest a starter.", "output": "Tomato soup", "reference": "(?i)banana"}
]
```

**Fields:** `testCaseId`, `input`, `output`, `reference` (optional for
reference-free evaluators). In Python, the same rows are
`BaseDataPoint(test_case_id=..., input=..., output=..., reference=...)`.

## Built-In Evaluators and Programmatic Execution

```python
from genkit import Genkit
from genkit.evaluator import BaseDataPoint
from genkit_evaluators import register_genkit_evaluators

# 1. Register the built-in evaluators
ai = Genkit()
register_genkit_evaluators(ai)

# 2. Build the dataset
dataset = [
    BaseDataPoint(test_case_id='dessert', input='Suggest a dessert.', output='Banana bread', reference='(?i)banana'),
    BaseDataPoint(test_case_id='starter', input='Suggest a starter.', output='Tomato soup', reference='(?i)banana'),
]

# 3. Run one evaluator per call; returns list[EvaluatorResponse] in dataset order
results = await ai.evaluate(evaluator='genkitEval/regex', dataset=dataset)
for row in results:
    print(row.test_case_id, row.evaluation[0].score, row.evaluation[0].status)
# => dessert True PASS
#    starter False FAIL
```

`config=` is passed to the evaluator as its second argument (`None` when unset).
An unregistered evaluator name raises `GenkitError` with `NOT_FOUND`.

## BYO Evaluator (`EvaluatorResponse`, `Score`, `ScoreStatus`, `ScoreDetails`)

`ai.define_evaluator` takes `(name, fn)` positionally with required keyword-only
`display_name=` and `definition=`. `EvaluatorResponse` requires `test_case_id`,
and `evaluation` takes a `list[Score]`:

```python
from genkit.evaluator import (
    BaseDataPoint,
    EvaluatorResponse,
    Score,
    ScoreDetails,
    ScoreStatus,
)


async def exact_match(datapoint: BaseDataPoint, _options: object | None = None) -> EvaluatorResponse:
    output = str(datapoint.output or '').strip()
    reference = str(datapoint.reference or '').strip()
    passed = output == reference
    return EvaluatorResponse(
        test_case_id=datapoint.test_case_id or '',
        evaluation=[
            Score(
                score=1.0 if passed else 0.0,
                status=ScoreStatus.PASS if passed else ScoreStatus.FAIL,
                details=ScoreDetails(reasoning='Exact match check'),
            )
        ],
    )


ai.define_evaluator(
    'byo/exact_match',
    exact_match,
    display_name='Exact Match',
    definition='Checks exact match of output against reference.',
)
```

For batch evaluation across the whole dataset at once, register
`async def my_batch_eval(req: EvaluatorRequest) -> list[EvaluatorResponse]:`
with
`ai.define_batch_evaluator('byo/batch', my_batch_eval, display_name='...',
definition='...')` (`from genkit.evaluator import EvaluatorRequest`). The batch
function takes exactly one argument; read options from `req.options`.

## LLM-Based Judge

`prompts/judge.prompt` (load it with `Genkit(prompt_dir='prompts', ...)`;
`prompts/` is the default):

```yaml
---
model: googleai/gemini-flash-latest
input:
  schema:
    output: string
    reference: string
---
Score how well the candidate matches the reference from 0.0 to 1.0.
Reply with ONLY a number (e.g. 0.8), nothing else.

Reference: {{reference}}
Candidate: {{output}}
```

```python
from genkit import Genkit
from genkit.evaluator import BaseDataPoint, EvaluatorResponse, Score, ScoreStatus
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()])


async def llm_judge(datapoint: BaseDataPoint, _options: object | None = None) -> EvaluatorResponse:
    # 1. Run the judge prompt; the model comes from the .prompt frontmatter
    response = await ai.prompt('judge')(
        {'output': str(datapoint.output), 'reference': str(datapoint.reference)}
    )

    # 2. Parse the score; treat anything unparseable as 0.0
    try:
        score = min(max(float((response.text or '').strip()), 0.0), 1.0)
    except ValueError:
        score = 0.0

    return EvaluatorResponse(
        test_case_id=datapoint.test_case_id or '',
        evaluation=[Score(score=score, status=ScoreStatus.PASS if score >= 0.5 else ScoreStatus.FAIL)],
    )


ai.define_evaluator(
    'byo/llm_judge',
    llm_judge,
    display_name='LLM Judge',
    definition='Scores candidate vs reference with a judge model.',
    is_billed=True,
)
```

`is_billed=True` makes `genkit eval:run` ask for confirmation before calling the
model; pass `--force` in CI.

Built-in `genkitEval/regex` and `genkitEval/deep_equal` scores are `bool`
(`True` / `False`); BYO numeric scores are typically `0.0`–`1.0`. Normalize
before aggregating.

## CLI Execution

`genkit eval:run` requires an active Genkit runtime (either already running via
`genkit start` or launched inline after `--`):

```bash
# One-shot: launches the app runtime, evaluates, and exits
genkit eval:run datasets/menu_dataset.json --evaluators=genkitEval/regex,byo/exact_match -- uv run src/main.py

# Write machine-readable results to a file (--output-format json|csv, default json)
genkit eval:run datasets/menu_dataset.json --evaluators=byo/exact_match --output=eval_out.json -- uv run src/main.py
```

Omitting `--evaluators` runs every registered evaluator. `No runtimes found`
means no Genkit runtime is active — pass `-- uv run src/main.py` or run
`genkit start` in another terminal.
examples.md 11.1 KB
# Genkit Python Examples

Minimal patterns for generation, structured output, streaming, media, flows,
tools, interrupts, cancellation, and embeddings.

- [Public Imports and Initialization](#public-imports-and-initialization): Lines 17-66
- [Structured Output](#structured-output): Lines 70-106
- [Streaming (Text and Structured Output)](#streaming-text-and-structured-output): Lines 110-138
- [Media Input and Output (Part)](#media-input-and-output-part): Lines 142-206
- [Flows and Streaming Flows](#flows-and-streaming-flows): Lines 210-244
- [Tools, Multipart Tool Responses, and Interrupts](#tools-multipart-tool-responses-and-interrupts): Lines 248-311
- [Cancellation](#cancellation): Lines 315-343
- [Embeddings](#embeddings): Lines 347-374

---

## Public Imports and Initialization

Import only from public modules (`genkit`, `genkit_google_genai`,
`genkit_fastapi`, `genkit_middleware`, `genkit.model`, `genkit.embedder`,
`genkit.middleware`, `genkit.web`, `genkit.exp`, `genkit.exp.agent`). Never
import private `_` submodules.

```python
from genkit import Genkit
from genkit_google_genai import GoogleAI

ai = Genkit(
    plugins=[GoogleAI()],
    model=GoogleAI.gemini('gemini-flash-latest'),
)
```

For multi-turn stateful agents, import `Genkit` from `genkit.exp` and session
types from `genkit.exp.agent` (see [Agents](agents.md)).

### Provider Model Refs & Typed Config

Other providers follow the same `Plugin.helper('model-id')` + `<Plugin>Config`
shape (import list in `SKILL.md`).

```python
from genkit_google_genai import GeminiConfig, GoogleAI

# Typed config with flat fields + `extra` escape hatch for unmodeled provider fields
res = await ai.generate(
    model=GoogleAI.gemini('gemini-flash-latest'),
    prompt='Check recent FDA allergen labeling updates.',
    config=GeminiConfig(
        thinking_level='HIGH',
        include_thoughts=True,
        google_search=True,
        extra={'seed': 42},
    ),
)

# Per-request API key (never pass `api_key` inside `config` - that raises GenkitError)
tenant_res = await ai.generate(
    prompt='Summarize invoice #4821.',
    context={'secrets': {'api_key': tenant_api_key}},
)
```

Config defaults merge key-by-key (`ModelRef` < `Prompt` < call); pass `None` on
a field to clear an inherited key. Unknown config keys raise `GenkitError`
(`INVALID_ARGUMENT`) before calling the provider.

---

## Structured Output

`response.output` is typed `OutputT | None`. If the model reply is cut off
(`max_output_tokens`) or malformed, `response.output` is `None` and
`response.error` (`Failure`) has `reason == ErrorReason.INVALID_OUTPUT`.

```python
from pydantic import BaseModel, TypeAdapter
from genkit import ErrorReason

class CityInfo(BaseModel):
    name: str
    population: int
    country: str

response = await ai.generate(
    prompt='Give facts about Tokyo.',
    output_schema=CityInfo,
)
if response.output is None:
    if response.error and response.error.reason == ErrorReason.INVALID_OUTPUT:
        raise RuntimeError(f'Incomplete structured output: {response.error.message}')
    raise RuntimeError('No structured output returned')

city: CityInfo = response.output

# Arrays
schema = TypeAdapter(list[CityInfo]).json_schema()
list_res = await ai.generate(
    prompt='List 3 cities in Japan.',
    output_format='array',
    output_schema=schema,
)
```

Built-in `output_format` values: `'text'`, `'json'`, `'array'`, `'enum'`,
`'jsonl'`.

---

## Streaming (Text and Structured Output)

```python
sr = ai.generate_stream(prompt='Explain sourdough fermentation.')
async for chunk in sr.stream:
    if chunk.text:
        print(chunk.text, end='', flush=True)
final = await sr.response
```

Streaming structured output yields partial typed objects on `chunk.output`
without raising on incomplete JSON:

```python
class RecipeCard(BaseModel):
    title: str
    prep_minutes: int
    steps: list[str]

sr = ai.generate_stream(
    prompt='Create a weeknight shakshuka recipe.',
    output_schema=RecipeCard,
)
async for chunk in sr.stream:
    if chunk.output:
        print(chunk.output)
final = await sr.response
recipe = final.output  # RecipeCard | None
```

---

## Media Input and Output (`Part`)

Construct parts with `Part.from_text(...)` and `Part.from_media(...)`. Inspect
parts via `part.text` and `part.media`.

### Sending Image / Media Input

```python
import base64
from pathlib import Path
from genkit import Message, Part, Role

# Direct HTTPS URL (< 20 MB) or base64 data URI
b64 = base64.b64encode(Path('receipt.png').read_bytes()).decode()
data_uri = f'data:image/png;base64,{b64}'

msg = Message(
    role=Role.USER,
    content=[
        Part.from_text('Extract the total amount from this receipt.'),
        Part.from_media(data_uri, content_type='image/png'),
    ],
)
response = await ai.generate(messages=[msg])
print(response.text)
```

Media URLs larger than **20 MB** fail instead of downloading into memory, and
`Ollama` does not read local filesystem paths for media.

### Generating Image / Audio / Video Output

```python
from genkit_google_genai import GeminiImageConfig, GeminiTtsConfig, GoogleAI, VertexAI

# Image generation (Imagen catalog is retired; use gemini_image)
img_res = await ai.generate(
    model=GoogleAI.gemini_image('gemini-2.5-flash-image'),
    prompt='Minimalist watercolor illustration of an espresso machine.',
    config=GeminiImageConfig(aspect_ratio='1:1'),
)
for media in img_res.media:
    print(media.content_type, (media.url or '')[:60])

# Inspecting parts directly on a message
if img_res.message:
    for part in img_res.message.content:
        if part.media:
            print(part.media.content_type)

# Text-to-speech
tts_res = await ai.generate(
    model=GoogleAI.gemini_tts('gemini-2.5-flash-preview-tts'),
    prompt='Order 42 is ready at the counter.',
    config=GeminiTtsConfig(voice='Kore'),
)

# Background video generation (Veo via Vertex AI)
op = await ai.generate_operation(
    model=VertexAI.veo('veo-3.1-generate-preview'),
    prompt='Aerial shot of coastal cliffs at sunrise.',
)
while not op.done:
    op = await ai.check_operation(op)
```

---

## Flows and Streaming Flows

Flows validate both input and return values against their type annotations.
Calling `await summarize(inp)` or `await summarize.run(inp)` raises body
exceptions unwrapped in-process; over HTTP, raise `PublicError` for
client-visible 4xx errors (see [FastAPI](fastapi.md)).

```python
from genkit import FlowContext, PublicError

class SummarizeInput(BaseModel):
    text: str

@ai.flow()
async def summarize(input: SummarizeInput) -> str:
    if not input.text.strip():
        raise PublicError('INVALID_ARGUMENT', 'text must not be empty')
    response = await ai.generate(prompt=f'Summarize in two sentences: {input.text}')
    return response.text

# Streaming flow: declare the chunk type on FlowContext[ChunkT]
@ai.flow()
async def stream_story(subject: str, ctx: FlowContext[str]) -> str:
    sr = ai.generate_stream(prompt=f'Write a short story about {subject}.')
    chunks: list[str] = []
    async for chunk in sr.stream:
        if chunk.text:
            ctx.send_chunk(chunk.text)
            chunks.append(chunk.text)
    return ''.join(chunks)
```

Options after the flow's single input on `.run(...)` are keyword-only:
`await stream_story.run('lighthouses', on_chunk=print, context={'role':
'reader'})`.

---

## Tools, Multipart Tool Responses, and Interrupts

Use `@ai.tool()` (there is no `define_tool`). A tool takes **at most one input
parameter** (scalar or Pydantic `BaseModel`) plus an optional
`ctx: ToolContext[ChunkT]`. Use a `BaseModel` whenever a tool needs multiple
arguments or field descriptions.

```python
from pydantic import BaseModel, Field
from genkit import MultipartToolResponse, Part, ToolContext

class OrderLookup(BaseModel):
    order_id: str = Field(description='Order identifier, e.g. ORD-104')
    include_receipt_image: bool = False

class ToolProgress(BaseModel):
    stage: str

@ai.tool()
async def lookup_order(input: OrderLookup, ctx: ToolContext[ToolProgress]) -> str | MultipartToolResponse:
    ctx.send_chunk(ToolProgress(stage='fetching_record'))
    if not input.include_receipt_image:
        return f'Order {input.order_id}: delivered'
    receipt_png = Part.from_media('data:image/png;base64,iVBORw0KGgo=', content_type='image/png')
    return MultipartToolResponse(
        output={'order_id': input.order_id, 'status': 'delivered'},
        content=[receipt_png],
    )

res = await ai.generate(
    prompt='Check status of ORD-104.',
    tools=[lookup_order],
    tool_choice='required',  # 'auto' | 'required' | 'none'
)
```

### Tool Interrupts (Human-in-the-Loop)

Raise `Interrupt(...)` inside a tool (or register a tool via
`ai.define_interrupt(...)`) to pause the generate loop. `Interrupt` subclasses
`BaseException`, so `except Exception:` inside a tool will not swallow it.
Resume using `intr.restart(...)` or `intr.respond(...)`:

```python
from genkit import Interrupt

class RefundInput(BaseModel):
    order_id: str
    amount_cents: int

@ai.tool()
async def issue_refund(input: RefundInput, ctx: ToolContext) -> dict:
    if not ctx.is_resumed():
        raise Interrupt({'order_id': input.order_id, 'amount_cents': input.amount_cents})
    return {'refunded': True, 'approved_by': (ctx.resumed_metadata or {}).get('manager')}

turn1 = await ai.generate(prompt='Refund $25 (2500 cents) on ORD-104.', tools=[issue_refund])
if turn1.interrupts:
    turn2 = await ai.generate(
        messages=turn1.messages,
        tools=[issue_refund],
        resume_restart=[i.restart(resumed_metadata={'manager': 'alex'}) for i in turn1.interrupts],
    )
```

---

## Cancellation

Cancellation uses standard `asyncio.CancelledError`; it reaches model calls,
retry backoff, and running tools at any `await`:

```python
import asyncio

# 1. Cancel an in-flight generate or flow task
task = asyncio.create_task(ai.generate(prompt='Write a detailed migration plan.'))
task.cancel()

# 2. Stop a flow stream early - use `async with` (or `await stream.aclose()`)
# so breaking out of the loop cancels the background flow immediately.
async with stream_story.stream('glaciers') as stream:
    async for chunk in stream:
        if len(chunk) > 0:
            break

# 3. Clean up partial side effects inside `finally` in tools
@ai.tool()
async def hold_inventory(sku: str) -> dict:
    reservation = await reserve_sku(sku)
    try:
        return await commit_reservation(reservation)
    finally:
        if not reservation.committed:
            await release_reservation(reservation)
```

---

## Embeddings

Build embedder refs with `.embedder(...)` and pass provider options in
`config=`:

```python
from genkit import Document
from genkit_google_genai import GoogleAI

embedder = GoogleAI.embedder('gemini-embedding-001')
embeddings = await ai.embed(
    embedder=embedder,
    content='Sourdough starter hydration ratio.',
    config={'task_type': 'RETRIEVAL_DOCUMENT'},
)
vector: list[float] = embeddings[0].embedding

batch = await ai.embed_many(
    embedder=embedder,
    content=['First paragraph.', 'Second paragraph.'],
)

# Multimodal embedding input via Document
image_embeddings = await ai.embed(
    embedder=GoogleAI.embedder('gemini-embedding-2'),
    content=Document.from_media('data:image/png;base64,iVBORw0KGgo=', 'image/png'),
)
```
fastapi.md 11.3 KB
# FastAPI — Genkit Python

- [Install](#install): Lines 14-35
- [Serve a Flow or Agent](#serve-a-flow-or-agent): Lines 39-95
- [HTTP Error Redaction and PublicError](#http-error-redaction-and-publicerror): Lines 99-114
- [Streaming (SSE)](#streaming-sse): Lines 118-171
- [Auth and Context Providers](#auth-and-context-providers): Lines 175-254
- [Advanced Flow Composition](#advanced-flow-composition): Lines 258-332
- [Structured Output Endpoint](#structured-output-endpoint): Lines 336-360
- [Python HTTP Client](#python-http-client): Lines 364-376

---

## Install

```bash
uv add 'genkit-fastapi==0.13.*' fastapi uvicorn
```

Imports are split between stable flow serving and experimental agent serving:

- **Stable flows (`genkit_fastapi`)**:
  - `serve_flow` — mount a flow as a FastAPI `APIRouter` (supports `base_path=`
    and `context_dependency=`)
  - `genkit_fastapi_handler` — decorator stacking `@app.post('/...')` directly
    over `@ai.flow()` (supports `context_provider=`)
  - `handle_genkit_request` — low-level handler for custom `@app.post` routes
    with multiple FastAPI `Depends(...)` parameters
- **Experimental agents (`genkit_fastapi.exp`)**:
  - `serve_agent` — mount an experimental `Agent` (`genkit.exp.Genkit`) as an
    `APIRouter` (see [Agent HTTP](agents-http.md))
- **Framework-agnostic web utilities (`genkit.web`)**:
  - `RequestData`, `ContextProvider`, `StreamHandle`, `to_sse`, `read_body`,
    `wants_stream`, `result_json`, `error_body`, `error_json`, `error_sse`,
    `error_status`

---

## Serve a Flow or Agent

```python
import os
import uvicorn
from fastapi import FastAPI
from genkit import PublicError
from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore
from genkit_fastapi import serve_flow
from genkit_fastapi.exp import serve_agent
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))

concierge = ai.define_agent(
    name='conciergeAgent',
    system='Hotel concierge. Keep answers under 40 words.',
    store=InMemorySessionStore(),
)


@ai.flow()
async def lookup_reservation(code: str) -> dict:
    if not code.startswith('RES-'):
        raise PublicError('NOT_FOUND', f'Reservation {code} not found')  # HTTP 404
    return {'code': code, 'status': 'confirmed'}


app = FastAPI()
# Paths default to the agent name and the flow's Python function name (override via base_path=...):
#   POST /api/conciergeAgent (+ /getSnapshot and /abort, since the agent has a store)
#   POST /api/lookup_reservation
app.include_router(serve_agent(concierge), prefix='/api')
app.include_router(serve_flow(lookup_reservation), prefix='/api')


async def main() -> None:
    config = uvicorn.Config(app, host='0.0.0.0', port=int(os.environ.get('PORT', '8080')))
    await uvicorn.Server(config).serve()


if __name__ == '__main__':
    ai.run_main(main())
```

If your app only serves flows (no agents), import `Genkit` from `genkit` instead
of `genkit.exp`.

With `GENKIT_ENV=dev` (which `genkit start` sets automatically), the Dev UI
reflection server starts on a background thread, so either entrypoint works:

```bash
genkit start -- uv run uvicorn main:app --reload   # reload-friendly ASGI dev server + Dev UI
genkit start -- uv run src/main.py                 # driven via ai.run_main(main()) + Dev UI
uvicorn main:app                                   # production (no Dev UI)
```

---

## HTTP Error Redaction and `PublicError`

Over HTTP (`serve_flow`, `serve_agent`, `genkit_fastapi_handler`,
`handle_genkit_request`), Genkit separates internal errors from caller-visible
errors:

- **`PublicError(status, message, details)`**: returns the corresponding HTTP
  status (`NOT_FOUND` -> 404, `INVALID_ARGUMENT` -> 400, `UNAUTHENTICATED` ->
  401, `PERMISSION_DENIED` -> 403) with `status`, `message`, and `details`. Keep
  secrets and cross-tenant data out of `PublicError`.
- **Invalid flow input**: returns HTTP 400 with field names and Pydantic's
  built-in messages (never echoing submitted values; custom validator text shows
  as `Invalid value` unless the validator raises `PublicError`).
- **Any other `GenkitError`, provider error, or Python exception**: logged
  server-side with full traceback (`5xx`) and returned to the client as
  `500 {"status": "INTERNAL", "message": "Internal Error"}`.

---

## Streaming (SSE)

`serve_flow`, `serve_agent`, `genkit_fastapi_handler`, and
`handle_genkit_request` stream Server-Sent Events when the client sends
`Accept: text/event-stream` (or `?stream=true`), and automatically cancel the
running flow if the client disconnects. Otherwise they return `{"result": ...}`.

**Wire format (SSE):**
```text
data: {"message": "<chunk>"}
data: {"message": "<chunk>"}
data: {"result": "<final output>"}
```
Errors during streaming emit `data: {"error": {...}}` formatted with the same
`PublicError` redaction rules.

**Minimal streaming FastAPI flow (`FlowContext`):**

```python
from pydantic import BaseModel
from fastapi import FastAPI
from genkit import FlowContext, Genkit
from genkit_fastapi import serve_flow
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))


class BriefInput(BaseModel):
    topic: str


@ai.flow()
async def stream_brief(input: BriefInput, ctx: FlowContext[str]) -> str:
    sr = ai.generate_stream(prompt=f'Write a concise brief on {input.topic}.')
    parts: list[str] = []
    async for chunk in sr.stream:
        if chunk.text:
            ctx.send_chunk(chunk.text)  # each call emits one SSE frame
            parts.append(chunk.text)
    return ''.join(parts)


app = FastAPI()
app.include_router(serve_flow(stream_brief), prefix='/api')  # POST /api/stream_brief
```

**Test with `curl`:**
```bash
curl -N -X POST http://localhost:8080/api/stream_brief \
  -H 'Content-Type: application/json' \
  -H 'Accept: text/event-stream' \
  -d '{"data": {"topic": "zero-downtime Postgres migrations"}}'
```

---

## Auth and Context Providers

### 1. FastAPI `Depends` via `serve_flow(..., context_dependency=...)`

FastAPI resolves `context_dependency` (and route `Depends(...)` parameters)
before Genkit's handler runs, so raise `fastapi.HTTPException` here rather than
`PublicError` (reserve `PublicError` for `context_provider` or the flow body):

```python
from fastapi import Header, HTTPException
from genkit import FlowContext
from genkit_fastapi import serve_flow


async def require_auth(authorization: str | None = Header(default=None)) -> dict:
    if not authorization:
        raise HTTPException(status_code=401, detail='Missing Authorization header')
    return {'auth': {'token': authorization}}


@ai.flow()
async def account_summary(account_id: str, ctx: FlowContext) -> dict:
    caller = (ctx.context or {}).get('auth')
    return {'account_id': account_id, 'caller': caller}


app.include_router(
    serve_flow(account_summary, context_dependency=require_auth),
    prefix='/api',
)
```

### 2. Decorator Style (`@genkit_fastapi_handler`) with `genkit.web.RequestData`

```python
from genkit import PublicError
from genkit.web import RequestData
from genkit_fastapi import genkit_fastapi_handler


async def auth_provider(req: RequestData) -> dict:
    token = req.headers.get('authorization')
    if not token:
        raise PublicError('UNAUTHENTICATED', 'Missing bearer token')  # 401
    return {'user_token': token}


@app.post('/api/ask')
@genkit_fastapi_handler(ai, context_provider=auth_provider)
@ai.flow()
async def ask(question: str) -> str:
    res = await ai.generate(prompt=question)
    return res.text
```

### 3. Custom Route Escape Hatch (`handle_genkit_request` or `genkit.web`)

When a route needs multiple `Depends(...)` parameters while keeping the Genkit
wire format:

```python
from fastapi import Depends, Request
from genkit_fastapi import handle_genkit_request


@app.post('/api/custom-brief')
async def custom_brief(
    request: Request,
    auth_ctx: dict = Depends(require_auth),
):
    return await handle_genkit_request(
        request,
        action=stream_brief,
        context=auth_ctx,
    )
```

If writing a completely custom non-Genkit JSON wrapper around
`await my_flow.run(data)`, map exceptions with `error_body(e)` and
`error_status(e)` from `genkit.web` so internal errors stay redacted.

---

## Advanced Flow Composition

### Nested Flow Streaming

Forward a child flow's chunks to the parent's SSE stream via
`await child.run(input, on_chunk=ctx.send_chunk)`. All arguments after the input
on `.run(...)` are keyword-only:

```python
class SectionInput(BaseModel):
    topic: str


@ai.flow()
async def draft_body(input: SectionInput, ctx: FlowContext[str]) -> str:
    sr = ai.generate_stream(prompt=f'Explain {input.topic} with concrete examples.')
    chunks: list[str] = []
    async for chunk in sr.stream:
        if chunk.text:
            ctx.send_chunk(chunk.text)
            chunks.append(chunk.text)
    return ''.join(chunks)


@ai.flow()
async def draft_headline(input: SectionInput) -> str:
    res = await ai.generate(prompt=f'One-line title for: {input.topic}')
    return res.text.strip()


@ai.flow()
async def full_report(input: SectionInput, ctx: FlowContext[str]) -> str:
    headline = await draft_headline(input)
    ctx.send_chunk(f'# {headline}\n\n')
    body = (await draft_body.run(input, on_chunk=ctx.send_chunk)).response
    return f'# {headline}\n\n{body}'
```

### Parallel Flows (`asyncio.gather`)

```python
import asyncio


class CodeReviewInput(BaseModel):
    diff: str


class ReviewFindings(BaseModel):
    findings: list[str]


@ai.flow()
async def check_security(input: CodeReviewInput) -> ReviewFindings:
    res = await ai.generate(
        prompt=f'List security issues in this diff: {input.diff[:2000]}',
        output_schema=ReviewFindings,
    )
    return res.output or ReviewFindings(findings=[])


@ai.flow()
async def check_correctness(input: CodeReviewInput) -> ReviewFindings:
    res = await ai.generate(
        prompt=f'List logic bugs in this diff: {input.diff[:2000]}',
        output_schema=ReviewFindings,
    )
    return res.output or ReviewFindings(findings=[])


@ai.flow()
async def review_diff(input: CodeReviewInput) -> ReviewFindings:
    sec, bugs = await asyncio.gather(check_security(input), check_correctness(input))
    return ReviewFindings(findings=sec.findings + bugs.findings)
```

---

## Structured Output Endpoint

Check `response.output is None` before returning so truncated model replies
surface cleanly instead of failing output validation:

```python
from genkit import PublicError


class SentimentResult(BaseModel):
    sentiment: str
    confidence: float
    key_phrases: list[str]


@ai.flow()
async def analyze_sentiment(text: str) -> SentimentResult:
    response = await ai.generate(
        prompt=f'Analyze customer sentiment: {text}',
        output_schema=SentimentResult,
    )
    if response.output is None:
        raise RuntimeError(f'Model returned incomplete JSON: {response.error}')
    return response.output
```

---

## Python HTTP Client

Genkit HTTP endpoints expect `{"data": ...}` on input (`{"data": null}` uses the
flow parameter's default) and return `{"result": ...}`:

```python
import httpx

async with httpx.AsyncClient(base_url='http://127.0.0.1:8080') as client:
    resp = await client.post('/api/analyze_sentiment', json={'data': 'Fast shipping, great packaging.'})
    resp.raise_for_status()
    result = resp.json()['result']
```
migrating-from-0.12.md 26.2 KB
# Migrating from Genkit Python 0.12 to 0.13

Genkit Python 0.13 aligns every symbol, signature, and error contract ahead of
1.0 without deprecation aliases. Use this reference when upgrading a 0.12
codebase or replacing 0.12 patterns (`ActionRunContext`, `ToolRunContext`,
`*_model()`, `GeminiConfigSchema`, `options=`, `abort_signal`, `restart_tool`,
`RuntimeErrorReason`, `add_gcp_telemetry`, `MediaPart`, `TextPart`, or
`from genkit.exp import Agent`).

- [Agent Guardrails Before Editing](#agent-guardrails-before-editing): Lines 25-51
- [1. Upgrade Packages Together](#1-upgrade-packages-together): Lines 55-70
- [2. Single-Home Namespace Layout](#2-single-home-namespace-layout): Lines 74-164
- [3. Removed Symbols and Enums Replaced by Strings](#3-removed-symbols-and-enums-replaced-by-strings): Lines 168-206
- [4. Model and Embedder Helpers, Constructors, and Plugins](#4-model-and-embedder-helpers-constructors-and-plugins): Lines 210-267
- [5. Config Classes, extra, tool_choice, and API Keys](#5-config-classes-extra-tool_choice-and-api-keys): Lines 271-327
- [6. Typed Contexts, Multipart Tools, Interrupts, and Cancellation](#6-typed-contexts-multipart-tools-interrupts-and-cancellation): Lines 331-421
- [7. Errors, HTTP Redaction (PublicError), and genkit.web](#7-errors-http-redaction-publicerror-and-genkitweb): Lines 425-488
- [8. Prompts, Structured Output, Validation, and Telemetry](#8-prompts-structured-output-validation-and-telemetry): Lines 492-525
- [9. Plugin and Custom Middleware Authors](#9-plugin-and-custom-middleware-authors): Lines 529-567
- [10. Evaluators (0.13 Only, Removed in 1.0)](#10-evaluators-013-only-removed-in-10): Lines 571-601
- [11. Verification Checklist](#11-verification-checklist): Lines 605-616

---

## Agent Guardrails Before Editing

1. **Stop before porting evaluators.** Evaluators (`define_evaluator`,
   `ai.evaluate`, `genkit.evaluator`, `genkit-evaluators`) still run in 0.13,
   but this is their last release: **Genkit 1.0 cuts them from the 1.0 release**
   (evaluation will return as an additive feature in a later release;
   `genkit-evaluators` 0.13 requires `genkit<1`). If the project contains
   evaluator code, stop and ask the developer before porting it. Recommend
   deleting evaluator code now; apply the 0.13 renames below only if the
   developer chooses to stay pinned to `0.13.*`.
2. **Audit HTTP-served error paths.** Over HTTP (`serve_flow`, `serve_agent`,
   `genkit_fastapi_handler`, `handle_genkit_request`, `genkit_flask_handler`,
   `genkit_django_handler`, `genkit.web`), `GenkitError` and unhandled
   exceptions now return
   `500 {"status": "INTERNAL", "message": "Internal Error"}`. Convert errors
   meant for callers (404, 401/403, domain validation) to
   `PublicError(status, message, details)`. Ask the developer before exposing
   any error message whose contents might include internal data or tenant state.
3. **Audit silent behavior changes.** Type checkers catch symbol renames and
   signatures, not runtime behavior changes:
   - Search for `{{` inside `ai.generate(prompt=..., system=...)` — strings
     there are now sent literally instead of rendered as Handlebars templates.
   - Search for reads of `response.output` — truncated or malformed JSON now
     returns `None` and sets `response.error` (`Failure` with
     `ErrorReason.INVALID_OUTPUT`).
   - Check `try` / `except GenkitError` blocks around `await my_flow(x)` or
     `await my_flow.run(x)` — actions now raise body exceptions unwrapped.

---

## 1. Upgrade Packages Together

Keep `genkit` and every `genkit-*` package on the same `0.13.*` minor line:

```bash
uv add 'genkit==0.13.*' 'genkit-google-genai==0.13.*'  # include every genkit-* package in use
```

- **Vertex AI Model Garden extras**: install extras for third-party SDKs:
  ```bash
  uv add 'genkit-vertexai[anthropic]'  # Claude on Model Garden
  uv add 'genkit-vertexai[openai]'     # Llama, Mistral, and OpenAI-compatible models
  ```
- **Flask**: `genkit-flask` no longer pulls in `genkit-google-genai`
  transitively. Run `uv add 'genkit-google-genai==0.13.*'` if the app uses
  Gemini.

---

## 2. Single-Home Namespace Layout

Every public symbol lives in one module listed in its `__all__`. Plugin
submodules (such as `genkit_openai.models` or `genkit_vertexai.model_garden`)
are private; import from each plugin's top-level package (`genkit_google_genai`,
`genkit_vertexai`, `genkit_openai`, etc.).

- **`genkit`**: application code (`Genkit`, `Message`, `Role`, `Part`, `Media`,
  `Document`, `ToolChoice`, `ModelResponse`, `ModelResponseChunk`,
  `ModelStreamResponse`, `StreamResponse`, `FinishReason`, `Failure`,
  `ErrorReason`, `GenkitError`, `PublicError`, `Flow`, `FlowContext`, `Tool`,
  `ToolContext`, `Interrupt`, `MultipartToolResponse`, `Prompt`, `Embedding`,
  `Operation`, `GenkitLogger`, `get_logger`).
- **`genkit.model`**: custom models and model inspection (`Model`, `ModelRef`,
  `BackgroundModel`, `ModelContext`, `ModelRequest`, `ModelInfo`,
  `ModelSupports`, `ModelStage`, `GenerationUsage`, `ConstrainedSupport`,
  `ModelConfig`).
- **`genkit.embedder`**: custom embedders (`Embedder`, `EmbedderRef`,
  `EmbedRequest`, `EmbedResponse`, `EmbedderInfo`, `EmbedderSupports`).
- **`genkit.evaluator`**: evaluator types (`Evaluator`, `BatchEvaluator`,
  `BaseDataPoint`, `EvaluatorResponse`, `Score`, `ScoreDetails`, `ScoreStatus`).
- **`genkit.middleware`**: writing custom middleware (`Middleware`,
  `MiddlewareContext`, `GenerateHookParams`, `ModelHookParams`,
  `ToolHookParams`). Note: the `Middleware()` plugin that registers `Retry`,
  `Fallback`, `ToolApproval`, `Skills`, and `Filesystem` lives in
  `genkit_middleware`.
- **`genkit.formats`**: custom output formatters (`Formatter`,
  `FormatterConfig`, `FormatHandler`).
- **`genkit.plugin_api`**: writing plugins (`Plugin`, `Action`, `ActionKind`,
  `GenkitConfig`, `provider_error`, `loop_local_client`, `GENKIT_USER_AGENT`).
- **`genkit.web`**: HTTP serving helpers (`RequestData`, `ContextProvider`,
  `to_sse`, `read_body`, `wants_stream`, `result_json`, `error_body`,
  `error_json`, `error_sse`, `error_status`).
- **`genkit.telemetry`**: custom tracing (`Instrumentation`, `SpanContext`,
  `configure_instrumentation`).
- **`genkit.testing`**: test doubles (`EchoModel`, `ScriptedModel`,
  `StaticResponseModel`, `define_echo_model`, `define_scripted_model`,
  `define_static_response_model`).
- **`genkit.exp` & `genkit.exp.agent`**: experimental agent APIs
  (`from genkit.exp import Genkit, current_session`;
  `from genkit.exp.agent import Agent, Session, InMemorySessionStore,
  FileSessionStore, remote_agent`).

Look up any moved symbol directly from the installed environment:

```bash
python - <<'EOF'
import importlib
target = 'ModelSupports'
for mod in [
    'genkit', 'genkit.model', 'genkit.embedder', 'genkit.evaluator',
    'genkit.middleware', 'genkit.formats', 'genkit.plugin_api', 'genkit.web',
    'genkit.telemetry', 'genkit.testing', 'genkit.exp', 'genkit.exp.agent',
]:
    if target in importlib.import_module(mod).__all__:
        print(mod)
EOF
```

### Renamed While Moving

```python
# Old (0.12)
from genkit import Constrained, ExecutablePrompt, ModelUsage, RuntimeErrorReason, Stage, Supports

# New (0.13)
from genkit import ErrorReason, Prompt
from genkit.model import ConstrainedSupport, GenerationUsage, ModelStage, ModelSupports
```

### Experimental (`exp`) Moves

```python
# Old (0.12)
from genkit.exp import Agent, AgentError, InMemorySessionStore, Session
from genkit_fastapi import serve_agent
from genkit_middleware import Artifacts

# New (0.13)
from genkit.exp import Genkit, current_session
from genkit.exp.agent import Agent, InMemorySessionStore, Session
from genkit_fastapi.exp import serve_agent
from genkit_middleware.exp import Artifacts
from genkit_google_cloud.exp import FirestoreSessionStore
```

`define_agent`, `define_custom_agent`, `define_prompt_agent`, and `@ai.agent()`
exist on `genkit.exp.Genkit`, not `genkit.Genkit`. `AgentError` is removed: a
failed turn sets `res.error` (`Failure`), and a call that produces no turn
raises `GenkitError`. Tools in a detached turn are cancelled with
`await task.abort()` instead of polling `abort_signal`.

---

## 3. Removed Symbols and Enums Replaced by Strings

0.12 model and config enums (`GoogleAIGeminiVersion`, `KnownGemini*`,
`KnownGpt`, `KnownClaude`, `*Version`, `GeminiEmbeddingModels`,
`VertexEmbeddingModels`, `EmbeddingTaskType`, `VertexAIEvaluationMetricType`)
are removed. Pass plain string values; helper signatures use `Literal` unions
for static checking while still accepting new model IDs as strings.

```python
# Old (0.12)
from genkit_google_genai import GoogleAI, GoogleAIGeminiVersion

model = GoogleAI.gemini_model(GoogleAIGeminiVersion.GEMINI_3_FLASH_PREVIEW)

# New (0.13)
from genkit_google_genai import GeminiConfig, GoogleAI

model = GoogleAI.gemini('gemini-3-flash-preview')
cfg = GeminiConfig(thinking_level='HIGH')  # checked against 'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH'
```

Other removed items and their 0.13 replacements:

- **`MediaPart` and `TextPart` (`Part(root=...)`)**: removed (`Part(root=...)`
  raises `ValueError`). Construct parts with `Part.from_text('...')` (or
  `Part(text='...')`) and `Part.from_media(url, content_type='image/jpeg')` (or
  `Part(media=Media(url=..., content_type=...))`). Read via `part.text` and
  `part.media`.
- **Name helpers** (`bedrock_name`, `anthropic_name`, `ollama_name`,
  `openai_model`, `genkit_eval_name`, `package_name`): pass `'plugin/model'`
  strings (e.g. `'openai/gpt-4o'`) or typed model refs (`OpenAI.gpt('gpt-4o')`).
- **`GoogleAI.imagen_model(...)`**: Imagen catalog is retired; use
  `GoogleAI.gemini_image('gemini-2.5-flash-image')`.
- **`Candidate`**: read `response.message` directly.
- **`Document.data`, `Document.data_type`, `Document.from_data()`**: construct
  with `Document(content=[...], metadata=...)`, `Document.from_text(...)`, or
  `Document.from_media(...)`.
- **`ai.registry`**: use lookup helpers directly on `Genkit` (e.g.
  `ai.prompt(...)`).

---

## 4. Model and Embedder Helpers, Constructors, and Plugins

Model helpers drop `_model`, and `.embedding()` becomes `.embedder()`:

```python
# Old (0.12)
GoogleAI.gemini_model('gemini-flash-latest')
GoogleAI.gemini_image_model('gemini-2.5-flash-image')
GoogleAI.gemini_tts_model('gemini-2.5-flash-preview-tts')
GoogleAI.embedding('gemini-embedding-001')
VertexAI.veo_model('veo-3.1-generate-001')
Anthropic.claude_model('claude-sonnet-4-6')

# New (0.13)
GoogleAI.gemini('gemini-flash-latest')
GoogleAI.gemini_image('gemini-2.5-flash-image')
GoogleAI.gemini_tts('gemini-2.5-flash-preview-tts')
GoogleAI.embedder('gemini-embedding-001')
VertexAI.veo('veo-3.1-generate-001')
Anthropic.claude('claude-sonnet-4-6')
OpenAI.gpt('gpt-5.2')
```

### Keyword-Only Signatures

`Genkit(...)`, plugin constructors, `GenkitError(...)`, and options after an
action's single input on `.run(...)` are keyword-only:

```python
# Old (0.12)
ai = Genkit([GoogleAI()], GoogleAI.gemini_model('gemini-flash-latest'))
out = await my_flow.run(data, on_chunk, ctx)

# New (0.13)
ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
out = await my_flow.run(data, on_chunk=on_chunk, context=ctx)
```

### Provider Plugin Updates

```python
# VertexAI (in genkit_google_genai): project_id= -> project=
from genkit_google_genai import VertexAI
VertexAI(project='my-project', location='us-central1')

# Vertex AI Model Garden (in genkit_vertexai): ModelGardenPlugin -> ModelGarden
from genkit_vertexai import ModelGarden
ModelGarden(project='my-project', location='us-central1')

# Ollama: server_address= -> base_url=; pulled models resolve automatically (no ModelDefinition/EmbeddingDefinition)
import os
from genkit_ollama import Ollama
Ollama(base_url=os.getenv('OLLAMA_HOST'))  # local file paths for media are no longer read

# Amazon Bedrock: ModelDefinition removed; BedrockImageConfig -> StabilityImageConfig
from genkit_amazon_bedrock import Bedrock, StabilityImageConfig
Bedrock(region='us-east-1', models=['us.amazon.nova-lite-v1:0'])
```

---

## 5. Config Classes, `extra`, `tool_choice`, and API Keys

### Flat Config Classes

`*ConfigSchema` classes drop the `Schema` suffix and flatten nested provider
dicts. Unknown or nested keys (such as `thinking_config` or a typo like
`'temprature'`) raise `GenkitError` (`INVALID_ARGUMENT`) before calling the
model.

```python
# Old (0.12)
from genkit_google_genai import GeminiConfigSchema, GeminiImageConfigSchema, GeminiTtsConfigSchema, GemmaConfigSchema
config = {'thinking_config': {'thinking_level': 'HIGH', 'include_thoughts': True}}
config = {'google_search_retrieval': True}
config = {'speech_config': {'voice_config': {'prebuilt_voice_config': {'voice_name': 'Kore'}}}}

# New (0.13)
from genkit_google_genai import GeminiConfig, GeminiImageConfig, GeminiTtsConfig, GemmaConfig
cfg1 = GeminiConfig(thinking_level='HIGH', include_thoughts=True, google_search=True)
cfg2 = GeminiTtsConfig(voice='Kore')
```

```python
# Anthropic flat config (ThinkingConfig, OutputConfig, TaskBudget, RequestMetadata, *ToolChoice removed)
from genkit_anthropic import AnthropicConfig
cfg = AnthropicConfig(thinking='enabled', thinking_budget=1024)
cfg_adaptive = AnthropicConfig(thinking='adaptive', effort='high', task_budget=20000, user_id='diner-42')
```

- **Unmodeled provider fields (`extra`)**: pass provider-specific keys not
  declared on the config class in `extra={...}` (supported across Gemini, Veo,
  Interactions, OpenAI, Anthropic, Ollama, and Bedrock). `OpenAIConfig.user` is
  removed; use `extra={'user': '...'}` if needed.
  ```python
  from genkit_amazon_bedrock import BedrockConfig
  cfg = BedrockConfig(extra={'some_provider_option': 1})
  ```
- **Config layering**: defaults merge key-by-key (`ModelRef` < `Prompt` < call).
  Pass `None` for a field to clear an inherited key.
- **`tool_choice` on `generate`**: moved out of `config` onto
  `ai.generate(...)`:
  ```python
  # Old (0.12): config={'tool_choice': {'type': 'any'}}
  await ai.generate(prompt='Check weather in Tokyo.', tools=[get_weather], tool_choice='required')  # 'auto' | 'required' | 'none'
  ```
- **`options=` -> `config=` on `embed` and `evaluate`**:
  ```python
  await ai.embed(embedder=GoogleAI.embedder('gemini-embedding-001'), content='doc', config={'task_type': 'RETRIEVAL_DOCUMENT'})
  ```
- **API keys rejected in `config`**: passing `api_key` in `config` now raises
  `GenkitError` (`INVALID_ARGUMENT`) in every plugin. Set the key on the plugin
  or pass per-request keys in `context`:
  ```python
  await ai.generate(prompt='Hello', context={'secrets': {'api_key': user_key}})
  ```
  Note: `ModelGarden` uses ADC only and rejects per-request keys; `ai.embed()`
  has no `context` parameter and always uses the plugin's key.

---

## 6. Typed Contexts, Multipart Tools, Interrupts, and Cancellation

### Typed Contexts (`FlowContext`, `ToolContext`, `ModelContext`)

`ActionRunContext` and `ToolRunContext` are removed from `genkit`. Chunk types
move from `@ai.flow(chunk_type=...)` into the generic parameter on `FlowContext`
/ `ToolContext`. Every action accepts at most one input parameter plus an
optional typed context; Genkit finds the context by its type annotation. The new
contexts subclass `ActionRunContext`, so an old annotation still type-checks
once the import is fixed.

```python
from pydantic import BaseModel
from genkit import FlowContext, ModelResponse, MultipartToolResponse, Part, ToolContext
from genkit.model import ModelContext, ModelRequest

class Status(BaseModel):
    step: str

# Flow streaming typed chunks
@ai.flow()
async def plan_trip(city: str, ctx: FlowContext[Status]) -> str:
    ctx.send_chunk(Status(step='searching flights'))
    return f'Planned {city}'

# Tool streaming typed chunks + returning multipart content
@ai.tool()
async def capture_chart(metric: str, ctx: ToolContext[Status]) -> MultipartToolResponse:
    ctx.send_chunk(Status(step='rendering'))
    png = Part.from_media('data:image/png;base64,iVBORw0KGgo=', content_type='image/png')
    return MultipartToolResponse(output={'ok': True, 'metric': metric}, content=[png])

# Custom model implementation
async def my_model_fn(request: ModelRequest, ctx: ModelContext) -> ModelResponse:
    ...
```

### Multipart Tool Responses

`from genkit import response` is removed. Replace
`response({'ok': True}, parts=[png])` with
`MultipartToolResponse(output={'ok': True}, content=[png])` (see `capture_chart`
above).

### Interrupts

- `restart_tool` and `respond_to_interrupt` are replaced by methods on the
  interrupt `Part`:
  ```python
  # Old (0.12): restart_tool(interrupt=intr, resumed_metadata={'approved': True})
  # Old (0.12): respond_to_interrupt({'status': 'declined'}, interrupt=intr)

  # New (0.13)
  restart = intr.restart(resumed_metadata={'approved': True})
  reply = intr.respond({'status': 'declined'})
  ```
- `Interrupt` now subclasses `BaseException` (like `asyncio.CancelledError`) so
  a tool's `except Exception:` cannot swallow an approval interrupt. Catch
  `Interrupt` explicitly only if inspecting and re-raising it.

### Native `asyncio` Cancellation

`ctx.abort_signal` is removed. Delete `if ctx.abort_signal.is_set(): raise ...`
checks; cancellation uses standard `asyncio.CancelledError`, propagating into
model requests, retry sleeps, and running tools at any `await`. If a tool
catches `asyncio.CancelledError`, it must re-raise it.

```python
import asyncio

# Cancel an in-flight call
task = asyncio.create_task(ai.generate(prompt='Draft a long report.'))
task.cancel()

# Stop a flow stream early - MUST use `async with` (or `await stream.aclose()`),
# otherwise a bare `break` leaves the background flow running.
async with plan_trip.stream('Kyoto') as stream:
    async for chunk in stream:
        if chunk.step == 'searching flights':
            break  # cancels plan_trip; stream.response raises CANCELLED

# Put partial-work cleanup in `finally` inside tools
@ai.tool()
async def reserve_table(party_size: int) -> dict:
    hold_id = await acquire_hold(party_size)
    try:
        return await confirm_hold(hold_id)
    finally:
        if not await is_confirmed(hold_id):
            await release_hold(hold_id)
```

---

## 7. Errors, HTTP Redaction (`PublicError`), and `genkit.web`

### Returned vs Raised Errors

- **Returned errors (`Failure`)**: `res.error`, `operation.error`, and
  `agent_res.error` are typed `Failure`
  (`from genkit import ErrorReason, Failure`) with `.status`, `.message`,
  `.details`, and `.reason`. `RuntimeErrorReason` is renamed to `ErrorReason`.
- **Raised errors (`GenkitError`)**: `e.original_message`, `e.http_code`,
  `e.trace_id`, and `e.cause` are removed. Read `e.message`, `e.status`,
  `e.details`, `e.reason`, and `e.__cause__`.
- **Plugin exception classes removed**: classes like `OllamaConnectionError` are
  gone; inspect `e.status` (e.g. `if e.status == 'UNAVAILABLE':`).
- **Action exceptions are unwrapped**: `await my_flow.run(x)` raises the
  exception the body raised. Replace `except GenkitError` wrappers that were
  catching your own exception types with those types directly. `Retry` and
  `Fallback` only retry failures a plugin classified (such as `UNAVAILABLE`).

### HTTP Serving & `PublicError`

In-process calls (`await my_flow(x)`, `await my_flow.run(x)`) see full unwrapped
exceptions. Over HTTP, Genkit redacts internal failures:

- **`PublicError(status, message, details)`**: returns the matching HTTP status
  (e.g. `NOT_FOUND` -> 404, `UNAUTHENTICATED` -> 401, `PERMISSION_DENIED` ->
  403) with `status`, `message`, and `details`.
- **Invalid top-level flow input**: returns 400 with field names and Pydantic's
  built-in messages (custom validator strings are replaced with `Invalid value`
  unless the validator raises `PublicError`).
- **All other `GenkitError`s, provider errors, and Python exceptions**: logged
  server-side with traceback and returned to the client as
  `500 {"status": "INTERNAL", "message": "Internal Error"}`.
- **Streaming**: the same body arrives inside a `data: {"error": {...}}` SSE
  frame.

Everything in a `PublicError`'s `message` and `details` reaches the client
verbatim; keep secrets and other tenants' IDs out of it.

**Context providers**: `RequestData` moves from `genkit.plugin_api` to
`genkit.web` and exposes `.method`, `.headers`, and `.input` on Flask, FastAPI,
and Django. Replace framework-specific reads like
`req.request.META.get('HTTP_AUTHORIZATION')` with
`req.headers.get('authorization')`.

```python
from genkit import PublicError
from genkit.web import RequestData, error_body, error_status

async def auth_context(req: RequestData) -> dict:
    token = req.headers.get('authorization')
    if not token:
        raise PublicError('UNAUTHENTICATED', 'Missing bearer token')  # 401
    return {'user': await verify_token(token)}

@ai.flow()
async def get_order(order_id: str) -> dict:
    order = await db_find(order_id)
    if order is None:
        raise PublicError('NOT_FOUND', f'Order {order_id} not found')  # 404
    return order
```

For hand-written HTTP routes that call `my_flow.run(...)` directly, serialize
errors with `error_body(e)` and `error_status(e)` from `genkit.web`.

---

## 8. Prompts, Structured Output, Validation, and Telemetry

- **No Handlebars rendering in `ai.generate`**:
  `ai.generate(prompt='Hi {{name}}')` sends `'Hi {{name}}'` verbatim. Move
  templates to `ai.define_prompt(name='greet', prompt='Hi {{name}}')` or
  `.prompt` files.
- **Prompt calls & validation**:
  `await prompt({'dish': 'pie'}, config={'temperature': 0.2})` validates input
  against `input.schema`, fills in `.prompt` defaults, merges `config`
  key-by-key over the prompt's config, and locks `output_schema` at definition
  time.
- **Truncated structured output**: if a reply hits `max_output_tokens` or
  produces invalid JSON, `res.output` is `None` and
  `res.error.reason == ErrorReason.INVALID_OUTPUT`:
  ```python
  res = await ai.generate(prompt='...', output_schema=City)
  if res.output is None:
      raise RuntimeError(f'Structured output failed: {res.error}')
  ```
- **Flow I/O validation**: flow inputs and return values are validated against
  their type annotations, so a flow that returns the wrong shape raises;
  `{"data": null}` over HTTP uses the parameter default.
- **Media URL limit**: media URLs over 20 MB fail instead of downloading into
  memory.
- **Telemetry**:
  ```python
  # Old (0.12): add_gcp_telemetry(project_id='my-project', force_dev_export=True)
  # New (0.13): FIREBASE_PROJECT_ID fallback removed; pass project= or set GOOGLE_CLOUD_PROJECT
  from genkit_google_cloud import enable_google_cloud_telemetry
  enable_google_cloud_telemetry(project='my-project')

  # Custom trace instrumentation (replaces tracer / add_custom_exporter / AdjustingTraceExporter)
  from genkit.telemetry import Instrumentation, configure_instrumentation
  ```

---

## 9. Plugin and Custom Middleware Authors

```python
# Custom middleware: BaseMiddleware -> Middleware, GenerateMiddlewareContext -> MiddlewareContext
from pydantic import BaseModel
from genkit.middleware import Middleware, MiddlewareContext

class PiiRedactConfig(BaseModel):
    mask: str = '[REDACTED]'

@ai.middleware
class PiiRedact(Middleware[PiiRedactConfig]):
    name = 'pii_redact'

    async def model(self, params, ctx: MiddlewareContext, next_fn):
        return await next_fn(params, ctx)
```

- `GenerateMiddleware`, `MiddlewareRef`, `MiddlewarePlugin`, and
  `new_middleware` are removed; `Middleware.tools()` returns `Tool` handles.
- Removed `genkit.plugin_api` helpers and their replacements:
  ```python
  # Old (0.12)
  from genkit.plugin_api import model, model_ref, background_model, embedder, embedder_ref, ModelConfig
  from genkit.plugin_api import wrap_http_error, from_http_code, parse_retry_after_ms
  from genkit.plugin_api import get_cached_client, GENKIT_CLIENT_HEADER, GENKIT_VERSION, tracer, add_custom_exporter

  # New (0.13)
  from genkit import get_logger
  from genkit.embedder import Embedder, EmbedderRef
  from genkit.model import BackgroundModel, Model, ModelConfig, ModelRef
  from genkit.plugin_api import GENKIT_USER_AGENT, GenkitConfig, loop_local_client, provider_error
  from genkit.telemetry import Instrumentation, configure_instrumentation
  ```
- Custom formatters import `Formatter`, `FormatterConfig`, and `FormatHandler`
  from `genkit.formats`.
- `Plugin.resolve(kind, name)` now receives `name` **without** the `'myplugin/'`
  prefix. `Plugin.model()`, `Plugin.embedder()`, and `Supports.context` are
  removed. `generate_operation` receives only what a background start uses.

---

## 10. Evaluators (0.13 Only, Removed in 1.0)

Apply only if the developer explicitly confirms keeping evaluators pinned to
`genkit==0.13.*`. Renames: `EvalFnResponse` -> `EvaluatorResponse`,
`EvalStatusEnum` -> `ScoreStatus`, `Details` -> `ScoreDetails`; `evaluation` is
now a `list[Score]`; `ai.define_evaluator(name=..., fn=...)` becomes positional
`(name, fn)`; `display_name=` and `definition=` stay required keywords.
`EvaluatorResponse` requires `test_case_id`.

```python
from genkit.evaluator import BaseDataPoint, EvaluatorResponse, Score, ScoreDetails, ScoreStatus

async def exact_match(dp: BaseDataPoint, _options: object = None) -> EvaluatorResponse:
    passed = str(dp.output or '').strip() == str(dp.reference or '').strip()
    return EvaluatorResponse(
        test_case_id=dp.test_case_id or '',
        evaluation=[
            Score(
                score=1.0 if passed else 0.0,
                status=ScoreStatus.PASS if passed else ScoreStatus.FAIL,
                details=ScoreDetails(reasoning='Exact string match'),
            )
        ],
    )

# Positional (name, fn); display_name and definition are required keywords
ai.define_evaluator('byo/exact_match', exact_match, display_name='Exact Match', definition='Exact string match.')

# options= -> config=; returns list[EvaluatorResponse] directly (no .root)
results = await ai.evaluate(evaluator='byo/exact_match', dataset=rows, config={})
```

---

## 11. Verification Checklist

1. Run the project's type checker (`pyright`, `mypy`, or `ty`) — catches moved
   imports, enum-to-`Literal` arguments, keyword-only calls,
   `FlowContext`/`ToolContext` generics, and `OutputT | None` checks on
   `response.output`.
2. Grep for `{{` inside `ai.generate(` calls and move templates to
   `ai.define_prompt` or `.prompt` files. Grep for reads of `response.output`
   that assume it is never `None`.
3. Grep for `GenkitError` inside HTTP-served flows and context providers;
   convert caller-facing errors to `PublicError`.
4. Run the test suite.
setup.md 3.7 KB
# Setup — Genkit Python

## New project

**Always use a virtual environment** — never install Genkit into the system
interpreter. With **uv**, `uv add` and `uv run` manage `.venv` automatically.

```bash
mkdir my-app && cd my-app
uv init
# Genkit requires Python 3.10+. If `uv init` pins a newer interpreter in
# pyproject.toml or .python-version than you have installed, adjust it first.
uv venv --python 3.12 .venv
uv add 'genkit==0.13.*' 'genkit-google-genai==0.13.*'

export GEMINI_API_KEY=your_key_here
```

Keep `genkit` and every `genkit-*` package on the **same `0.13.*` release**.
`pydantic` is installed automatically with `genkit`, though adding `pydantic`
directly to `pyproject.toml` is fine when defining your own `BaseModel` schemas.

Place your entrypoint at `src/main.py` (or match the file generated by
`uv init`) and run it under `genkit start -- uv run src/main.py`.

## `pyproject.toml`

```toml
[project]
name = "my-app"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = [
    "genkit==0.13.*",
    "genkit-google-genai==0.13.*",
]
```

## Packages and Imports

PyPI distribution names use hyphens (`genkit-*`); Python import modules use
underscores (`genkit_*`). Import everything from each package's top-level module
(or `.exp` for experimental agent integrations):

- **`genkit-google-genai`**:
  `from genkit_google_genai import GoogleAI, VertexAI, GeminiConfig` (Gemini API
  via `GEMINI_API_KEY`, or Google Cloud Vertex AI via ADC).
- **`genkit-vertexai`**: `from genkit_vertexai import ModelGarden` (third-party
  models on Vertex AI Model Garden). Install the extra matching the models you
  call:
  - `uv add 'genkit-vertexai[anthropic]'` for Claude models
  - `uv add 'genkit-vertexai[openai]'` for Llama, Mistral, and OpenAI-compatible
    models
- **`genkit-anthropic`**:
  `from genkit_anthropic import Anthropic, AnthropicConfig`
  (`ANTHROPIC_API_KEY`).
- **`genkit-openai`**: `from genkit_openai import OpenAI, OpenAIConfig`
  (`OPENAI_API_KEY` or custom `base_url=`).
- **`genkit-ollama`**: `from genkit_ollama import Ollama, OllamaConfig` (local
  Ollama server; auto-discovers pulled models).
- **`genkit-amazon-bedrock`**: `from genkit_amazon_bedrock import Bedrock, BedrockConfig, StabilityImageConfig`.
- **`genkit-middleware`**: `from genkit_middleware import Middleware, Retry, Fallback, ToolApproval, Skills, Filesystem` (plus `from genkit_middleware.exp import Artifacts` for agent sessions).
- **`genkit-fastapi`**: `from genkit_fastapi import serve_flow, genkit_fastapi_handler, handle_genkit_request` (plus `from genkit_fastapi.exp import serve_agent`).
- **`genkit-flask`**: `from genkit_flask import genkit_flask_handler` (requires
  `flask[async]`; does not install `genkit-google-genai` automatically; add your
  model plugin explicitly).
- **`genkit-django`**: `from genkit_django import genkit_django_handler`.
- **`genkit-mcp`**: `from genkit_mcp import McpClient, McpHost, define_mcp_client, define_mcp_host` (Model Context Protocol clients and tool hosts).
- **`genkit-google-cloud`**:
  `from genkit_google_cloud import enable_google_cloud_telemetry` (plus
  `from genkit_google_cloud.exp import FirestoreSessionStore`).
- **`genkit-otel`**: `from genkit_otel import GenAiInstrumentation, ContentCapturingMode, OtelEventLogger` (OpenTelemetry GenAI spans and metrics).
- **`genkit-evaluators`**:
  `from genkit_evaluators import register_genkit_evaluators`. Last release with
  evaluators; Genkit 1.0 cuts evaluators from the 1.0 release (evaluation will
  return as an additive feature in a later release). Requires `genkit<1` (see
  [Evals](evals.md)).

## Python version

**Python 3.10+**. Upgrading an existing 0.12 app? Follow
[Migrating from 0.12 to 0.13](migrating-from-0.12.md).

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE