Installation

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

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

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

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

Download and extract to your repository:

.github/skills/developing-genkit-dart/

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

Skill Files (24)

SKILL.md 13.5 KB
---
name: developing-genkit-dart
description: >-
  Provides guidance on developing AI-powered applications using the Genkit Dart
  SDK. Use when the user asks to build AI agents in Dart, use Genkit flows, or
  integrate LLMs into Dart/Flutter applications. Don't use for Genkit in
  JavaScript/TypeScript, Go, or Python.
metadata:
  version: "1.0.0"
  category: AiAndMachineLearning
---

# Genkit Dart

Genkit Dart is an AI SDK for Dart that provides a unified interface for code
generation, structured outputs, tools, flows, and AI agents.

## Core Features and Usage
If you need help with initializing Genkit (`Genkit()`), Generation
(`ai.generate`), Tooling (`ai.defineTool`), Flows (`ai.defineFlow`), Embeddings
(`ai.embed`), streaming, or calling remote flow endpoints, please load the core
framework reference:
[references/genkit.md](references/genkit.md)

## 1.0 vs pre-1.0 APIs

This skill targets Genkit Dart **1.0** (`genkit: ^1.0.0`). Older code and
training data use pre-1.0 names that no longer compile; the common ones:

- HTTP: `startFlowServer` / per-route `shelfHandler` / `shelf_cors_headers` are
  now `GenkitRouter` + `serve()` or `asShelfHandler()`, with `CorsOptions`;
  context providers take `RequestData`
  ([genkit_shelf.md](references/genkit_shelf.md)).
- `StatusCodes.UNAUTHENTICATED` is `StatusCode.unauthenticated` (lowerCamelCase,
  same for `EvalStatus.pass`, `ToolChoice.required`).
- No `RetryPlugin`; `retry()` is built in and takes `Duration`s
  (`initialDelay`, `maxDelay`, also `cacheTtl` elsewhere).
- Renames: `GenerateResponseHelper` -> `GenerateResult` (`modelResponse`,
  `chunk.modelChunk`), `ExecutablePrompt` -> `Prompt<Input, Output>`,
  `embedMany` -> `embed`, `ToolFnArgs` -> `ToolFnArg`, `toolOutputSchema` ->
  `outputSchema`, `underlyingException` -> `cause`, `modelInfo:` -> `info:`,
  `RemoteAction.dispose()` -> `close()`,
  `prompt(input, PromptGenerateOptions(config: ...))`
  -> `prompt(input, config: ...)` (named options, like `generate`),
  `defineMiddleware` ->
  `ai.defineGenerateMiddleware` (app) / `generateMiddleware` (plugins).
- Provider config types are prefixed: `GeminiThinkingConfig`,
  `GeminiSafetySettings`, `GeminiGoogleSearch`, `GeminiSpeechConfig`,
  `GoogleGenAiEmbedderOptions`, `AnthropicThinkingConfig`.
- Removed: `ToolInterruptException` / `ctx.interrupt()` (return
  `.interrupt(...)`),
  `GoogleAiModels` / `OpenAIModels` constants (use `googleAI.gemini('...')`,
  `openAI.model('...')`). Simulated constrained output is opt-in via
  `simulateConstrainedGeneration()`.
- `.prompt` Picoschema is spec-compliant: `name: type, description`, never
  `name(description): type` ([dotprompt.md](references/dotprompt.md)).

## Prompts (Dotprompt)

`.prompt` files keep prompt content out of Dart code with YAML frontmatter plus
a
Handlebars template. See [references/dotprompt.md](references/dotprompt.md):
`promptDir`, `ai.prompt()` (call/stream/render), variants, partials, named
schemas via `defineSchema`, and the
`tools`/`maxTurns`/`returnToolRequests`/`use`
(middleware) frontmatter fields. A `.prompt` file can also back an agent
directly
via `definePromptAgent`.

## Agents

Genkit Dart has an **agent** API for persistent, multi-turn conversations
(sessions, snapshots, interrupts, branching, background execution, custom state,
artifacts, and multi-agent delegation). The agent/session/snapshot APIs are
**experimental** and live behind opt-in imports: server APIs come from
`package:genkit/experimental.dart` (alongside `package:genkit/genkit.dart`), the
browser/HTTP client from `package:genkit/experimental_client.dart` (alongside
`package:genkit/client.dart`), and `dart:io` extras like `FileSessionStore` from
`package:genkit/experimental_io.dart`. These entry points are `@experimental`,
so
importing them raises an `experimental_member_use` analyzer warning you can
silence in `analysis_options.yaml`. The `remoteAgent` client works from any Dart
app, including **Flutter**, and the backend is fully interchangeable — it can
talk
to a Genkit agent implemented in Dart, JS/TypeScript, or Go over the same HTTP
protocol. A few Dart specifics: interrupts are `ai.defineInterrupt(...)` or
tools that return `.interrupt(...)` (there is no `ctx.interrupt()`), sub-agent
delegation uses
the `agents()` middleware from `package:genkit_middleware`, and there is no
`artifacts()` middleware yet (define artifact tools directly).

For more details see:

-   [Agents](references/agents.md): defining/serving an agent and client-managed
    state (start here).
-   [Sessions & persistence](references/agents-sessions.md): session stores
    (`InMemorySessionStore`/`FileSessionStore`/`FirestoreSessionStore`).
-   [Human-in-the-loop / interrupts](references/agents-human-in-the-loop.md):
    pausing for approval/input via `.interrupt(...)` and resuming.
-   [Branching](references/agents-branching.md): forking a conversation from a
    snapshot.
-   [Background agents](references/agents-background.md): detaching long-running
    turns and polling.
-   [Working with state](references/agents-state.md): typed custom session
    state, auto-synced to the client.
-   [Artifacts](references/agents-artifacts.md): producing and reading named
    deliverables.
-   [Multi-agent orchestration](references/agents-multi-agent.md): delegating to
    sub-agents with the `agents()` middleware.
-   [Advanced custom agents](references/agents-custom.md): `defineCustomAgent`
    for full turn control.
-   [Deploying agents](references/agents-deployment.md): serving agents over
    HTTP with `GenkitRouter.addAgent` (multiple agents, shelf, CORS).

## Generative UI (A2UI)

Genkit Dart has an **A2UI** (Agent-to-UI) plugin (`genkit_a2ui`)
that lets an agent stream interactive UI **surfaces** (cards, lists, forms,
buttons), not just prose. The whole server-side integration is the `a2ui()`
model
middleware in an agent's (or `ai.generate`'s) `use` list; the Flutter client
renders surfaces with the [`genui`](https://pub.dev/packages/genui) package plus
the helpers in `package:genkit_a2ui/client.dart`. Dart specific: you must
register `A2uiPlugin()` in `Genkit(plugins: [...])` (unlike JS, middleware is
resolved by name from the registry).

-   [A2UI](references/a2ui.md): server middleware, options, Flutter/genui client
    rendering, user actions/forms, custom catalogs, and the security/trust
    boundary.

## Genkit CLI (recommended)

`genkit start` unintrusively wraps any Dart program that uses the Genkit
library, running it unchanged while capturing traces from every Genkit action so
you can prove tools were actually called and inspect model I/O from the
terminal, even for headless checks. It forwards stdio, so interactive CLI tools
that rely on stdin/stdout work without issues. Running the app directly
(`dart run`) skips trace capture, so you're debugging blind. Check install with
`genkit --version`.

**Installation:**
```bash
curl -sL cli.genkit.dev | bash # Native CLI
# OR
npm install -g genkit-cli # Via npm
# OR run commands directly with npx without a global install (prefix every genkit command):
# npx genkit-cli start -- dart run main.dart
```

**Primary pattern (default):** prefix `genkit start --` to your normal run
command. This collects telemetry from any Genkit code your program runs, whether
triggered from the dev UI, your own web server/web UI, or a plain script. Starts
the Developer UI (usually http://localhost:4000) for running flows, model and
agent playground, and browsing traces:

```bash
genkit start -- dart run main.dart
genkit start --noui -- dart run main.dart   # same, without the Dev UI (still a persistent server)
```
`genkit start` runs until you stop it with Ctrl+C. That is expected and correct
for the common cases: a server your web/mobile app calls, or an interactive CLI
you exit yourself. `--noui` only drops the Dev UI; it is **not** a one-shot
command and will not exit on its own. Do **not** use `genkit start` as a
blocking step in automated/non-interactive contexts; use `flow:run` (below) for
that.

**Non-interactive use (agents/CI):** add the global `--non-interactive` flag
before `--` so the CLI uses defaults and never blocks on a prompt (e.g. the
first-run analytics notice):
`genkit start --non-interactive -- dart run main.dart` (works with `flow:run`
too).

**Run a flow (`flow:run`):** invoke a specific flow by name from the CLI. Append
your run command after `--` to spin up the runtime just for this run (the
command runs as-is to register your flows):
```bash
genkit flow:run myFlow '{"data": "input"}' -- dart run main.dart
```
This is **self-terminating**: it runs the flow once, prints a `Trace ID`, then
exits, so it's the right choice for a quick, non-interactive check (unlike
`genkit start`). Note: `flow:run` runs **flows** (`ai.defineFlow`), not agents;
you can't `flow:run` an agent (`ai.defineAgent`) directly. To exercise an agent
from the CLI, wrap one turn in a throwaway flow and run that (see
[Agents](references/agents.md)). Traces for this run can be inspected using the
trace commands below.

**Gotcha: top-level `final` declarations are lazy.** Flows and agents defined as
top-level `final` register with Genkit only when the symbol is first evaluated.
An empty `main()` registers nothing, so `flow:run` fails with
`Process exited before runtime was ready`. Reference the flow/agent symbols from
`main()` (or import a module that does) so their `define*` calls actually run.

**Debugging with traces:** the fastest way to see prompts, model inputs/outputs,
tool calls, latencies, and errors. Inspect from the terminal after any run under
`genkit start`:
```bash
genkit trace:list                        # find recent trace IDs
genkit trace:get <traceId>               # full trace details (inputs, outputs, tool calls, errors)
genkit trace:get <traceId> --format json # machine-readable JSON, safe to pipe into jq or other parsers
```

For machine-readable output, pass `--format json` to get clean JSON you can pipe
into `jq` or other parsers. The **default** output is human-oriented (banner/log
lines, possible truncation on large traces), so don't pipe that form directly;
use `--format json`, grep, or the Dev UI trace viewer.

**Documentation:**
```bash
genkit docs:search "streaming" dart
genkit docs:list dart
genkit docs:read dart/flows.md
```

## Plugin Ecosystem
Genkit relies on a large suite of plugins to perform generative AI actions,
interface with external LLMs, or host web servers.

When asked to use any given plugin, always verify usage by referring to its
corresponding reference below. You should load the reference when you need to
know the specific initialization arguments, tools, models, and usage patterns
for the plugin:

| Plugin Name | Reference Link | Description |
| ---- | ---- | ---- |
| `genkit_google_genai` | [references/genkit_google_genai.md](references/genkit_google_genai.md) | Load for Google Gemini plugin interface usage. |
| `genkit_vertexai` | [references/genkit_vertexai.md](references/genkit_vertexai.md) | Load for Gemini via Vertex AI (Google Cloud auth, versioned model IDs, embeddings incl. multimodal). |
| `genkit_anthropic` | [references/genkit_anthropic.md](references/genkit_anthropic.md) | Load for Anthropic plugin interface for Claude models. |
| `genkit_openai` | [references/genkit_openai.md](references/genkit_openai.md) | Load for OpenAI plugin interface for GPT models, Groq, and custom compatible endpoints. |
| `genkit_middleware` | [references/genkit_middleware.md](references/genkit_middleware.md) | Load for Tooling for specific agentic behavior: `filesystem`, `skills`, and `toolApproval` interrupts. |
| `genkit_mcp` | [references/genkit_mcp.md](references/genkit_mcp.md) | Load for Model Context Protocol integration (Server, Host, and Client capabilities). |
| `genkit_chrome` | [references/genkit_chrome.md](references/genkit_chrome.md) | Load for Running Gemini Nano locally inside the Chrome browser using the Prompt API. |
| `genkit_shelf` | [references/genkit_shelf.md](references/genkit_shelf.md) | Load for serving flows/models/agents over HTTP: `GenkitRouter` (core `package:genkit/io.dart`, standalone `dart:io`) and mounting it into Shelf apps. |
| `genkit_firebase_ai` | [references/genkit_firebase_ai.md](references/genkit_firebase_ai.md) | Load for Firebase AI plugin interface (Gemini API via Vertex AI). |
| `genkit_a2ui` | [references/a2ui.md](references/a2ui.md) | Load for A2UI (Agent-to-UI): streaming generative UI surfaces via the `a2ui()` middleware, rendered on the client with `genui`. |

## External Dependencies
Whenever you define schemas mapping inside of Tools, Flows, and Prompts, you
must use the [schemantic](https://pub.dev/packages/schemantic) library.
To learn how to use schemantic, ensure you read
[references/schemantic.md](references/schemantic.md) for how to implement type
safe generated Dart code. This is particularly relevant when you encounter
symbols like `@Schema()`, `SchemanticType`, or classes with the `$` prefix.
Genkit Dart uses schemantic for all of its data models so it's a CRITICAL skill
to understand for using Genkit Dart.

## Best Practices

- **Agent or flow?** If the task is conversational, multi-turn, or described as
  "an agent", "assistant", or "chatbot", build it with `ai.defineAgent` (see
  [Agents](references/agents.md)) rather than hand-rolling a `generate` + tools
  loop inside a flow. Reach for a plain flow only for single-shot, stateless
  generation.
- Always check that code cleanly compiles using `dart analyze` before generating
  the final response.
- Always use the Genkit CLI for local development and debugging.
- Verify with traces, not a blind run. Running the app directly (`dart run`)
  does not capture dev traces. See the [Genkit CLI](#genkit-cli-recommended)
  section for how to run your app and capture traces.
references/
a2ui.md 15.2 KB
# A2UI (Agent-to-UI) generative UI

The `genkit_a2ui` package brings
> [A2UI](https://a2ui.org/), a transport-agnostic, JSON-based streaming UI
> protocol, to Genkit Dart agents.
>
> A2UI builds on the agent client. Server APIs come from
> `package:genkit/genkit.dart`; the browser/Flutter client comes from
> `package:genkit/client.dart`. Read [Agents](agents.md) first if you have not.

An A2UI-enabled agent streams more than prose. It streams interactive UI
**surfaces** (cards, lists, forms, buttons) that a client renders incrementally
as the model responds. The entire server-side integration is a single model
middleware: add `a2ui()` to an agent's `use` list and nothing else changes.

- [Install](#install): Lines 26-49
- [Server: add the a2ui() middleware](#server-add-the-a2ui-middleware): Lines 51-124
- [Client: render surfaces (Flutter and genui)](#client-render-surfaces-flutter-and-genui): Lines 126-184
- [Handling user actions](#handling-user-actions): Lines 186-248
- [Custom catalogs](#custom-catalogs): Lines 250-330
- [Security and the trust boundary](#security-and-the-trust-boundary): Lines 332-355
- [How it works](#how-it-works): Lines 357-378

---

## Install

On the **server** (the shelf app that hosts the agent), add `genkit_a2ui`
alongside the packages the agent already needs. List `genkit` explicitly even
though `genkit_a2ui` pulls it in transitively, otherwise `dart analyze` warns
with `depend_on_referenced_packages` (the server code imports
`package:genkit/genkit.dart` directly):

```bash
dart pub add genkit genkit_a2ui genkit_google_genai
```

To render surfaces you also need a renderer. The Flutter renderer for A2UI is
[`genui`](https://pub.dev/packages/genui). On the **client** Flutter app, add it
plus `a2ui_core`, and `genkit` + `genkit_a2ui` for the client helpers
(`remoteAgent`, `a2uiEnvelopesFromParts`, `actionToMessage`):

```bash
flutter pub add genkit genkit_a2ui 'genui:^0.10.4' 'a2ui_core:^0.1.1'
```

Pin these versions: the client code below targets the `genui` 0.10 API with
`a2ui_core` 0.1. An unpinned add can resolve an older `genui` and a newer,
incompatible `a2ui_core`, and the snippets then fail to compile.

## Server: add the `a2ui()` middleware

Add `a2ui()` to your agent's `use` list. That is the whole server-side setup.

**Dart specific:** Dart middleware is resolved by name from
the registry, so you MUST register `A2uiPlugin()` in `Genkit(plugins: [...])`
before referencing it via `a2ui()`.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, InMemorySessionStore
import 'package:genkit_a2ui/a2ui.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart';

// A2uiPlugin() registers the a2ui() middleware so `use: [a2ui()]` resolves.
final ai = Genkit(plugins: [googleAI(), A2uiPlugin()]);

final uiAgent = ai.defineAgent(
  name: 'uiAgent',
  model: googleAI.gemini('gemini-flash-latest'),
  system:
      'You help users. Render an A2UI surface whenever a result is clearer '
      'shown than told (weather, comparisons, lists, forms). Keep prose brief; '
      'put the substance in the UI.',
  use: [a2ui()], // defaults to the bundled 'basic' catalog
  store: InMemorySessionStore(),
);
```

It works identically on a one-shot `ai.generate`:

```dart
final res = await ai.generate(
  model: googleAI.gemini('gemini-flash-latest'),
  prompt: 'Show me the weather in Tokyo',
  use: [a2ui()],
);
```

Serve the agent over HTTP with `GenkitRouter` (see
[Deploying agents](agents-deployment.md)). `addAgent` mounts the turn route plus
`/getSnapshot` and `/abort` for a server-managed agent:

```dart
import 'package:genkit/experimental_io.dart';
import 'package:genkit/io.dart';

void main() async {
  final genkit = GenkitRouter()..addAgent(uiAgent, path: '/api/uiAgent');
  await genkit.serve(
    port: 8080,
    // Flutter web runs on another origin.
    cors: const CorsOptions(
      allowedHeaders: ['Content-Type', 'Accept', 'X-Genkit-Stream-Id'],
    ),
  );
}
```

### Options

Pass options to `a2ui(...)`:

| Option         | Default    | Description                                                                                             |
| -------------- | ---------- | ------------------------------------------------------------------------------------------------------- |
| `catalog`      | `'basic'`  | Id of the catalog describing what the agent may render.                                                 |
| `instructions` | `'system'` | Where to inject catalog capabilities. `'none'` injects nothing (supply your own instructions instead).  |
| `validate`     | `'warn'`   | Validate emitted envelopes. `'warn'` logs and drops bad blocks; `'strict'` throws; `'off'` skips it.    |
| `surfaceId`    | fresh UUID | Surface id policy. Defaults to a new UUID per surface; pass a fixed string to reuse one id per surface. |
| `version`      | `'v0.9'`   | Protocol version stamped on envelopes.                                                                  |

Use `validate: 'strict'` during development to fail fast on malformed JSON or
components outside the catalog. See [Security](#security-and-the-trust-boundary)
for what `'strict'` does and does not check.

## Client: render surfaces (Flutter and genui)

`package:genkit_a2ui/client.dart` is browser/Flutter-safe (no `dart:io`).
Consume
the agent with `remoteAgent`, pull A2UI envelopes off each chunk's content with
`a2uiEnvelopesFromParts`, convert each envelope to a genui `A2uiMessage`, and
feed
it to a `SurfaceController`. A2UI travels as `data` parts on the raw model
chunk,
so read them from `chunk.raw.modelChunk?.content`.

```dart
import 'package:a2ui_core/a2ui_core.dart' as core;
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent, AgentApi
import 'package:genkit_a2ui/client.dart';
import 'package:genui/genui.dart' hide basicCatalogId, DataPart;

// remoteAgent returns an AgentApi<State> (not a `RemoteAgent`).
final agent = remoteAgent(
  url: 'http://localhost:8080/api/uiAgent',
  getSnapshotUrl: 'http://localhost:8080/api/uiAgent/getSnapshot',
  abortUrl: 'http://localhost:8080/api/uiAgent/abort',
);
final chat = agent.chat();

// genui registers an empty stub for an unknown catalog id, so re-tag its basic
// catalog with the id the plugin's bundled basic catalog advertises.
final catalog = BasicCatalogItems.asCatalog().copyWith(catalogId: basicCatalogId);
final surfaceController = SurfaceController(catalogs: [catalog]);

final turn = chat.sendStream(text: 'What is the weather in Tokyo?');
await for (final chunk in turn.stream) {
  if (chunk.text.isNotEmpty) appendProse(chunk.text);
  for (final envelope in a2uiEnvelopesFromParts(chunk.raw.modelChunk?.content)) {
    surfaceController.handleMessage(core.A2uiMessage.fromJson(envelope));
  }
}
await turn.response;
```

**Dart specific:** importing both `package:genkit/client.dart` and
`package:genui/genui.dart` collides on two symbols, so hide genui's:

- `basicCatalogId`: both packages export one with *different* values. You want
  the plugin's; if the ids do not match, genui registers an empty stub and
  surfaces render blank.
- `DataPart`: genkit's client and genui (via `genai_primitives`) both export a
  `DataPart` class, so referencing `DataPart` unqualified is ambiguous.

Hence `import 'package:genui/genui.dart' hide basicCatalogId, DataPart;`.

`remoteAgent` manages the session id for you, so a single `chat` keeps the whole
conversation server-side (the agent's session store holds history).

In a Flutter app, listen to `surfaceController.surfaceUpdates` to add a
`Surface(surfaceContext: surfaceController.contextFor(id))` widget to your chat
log when a `SurfaceAdded` update arrives, and listen to
`surfaceController.onSubmit` to route actions back to the agent (see below).

## Handling user actions

When a user interacts with a surface (for example, presses a `Button`),
`surfaceController.onSubmit` emits a genui `ChatMessage`. That message is *not*
an
`A2uiClientAction` you can hand straight to `actionToMessage`: genui reports the
interaction as a `UiInteractionPart` whose payload is a JSON string
`{ "version": ..., "action": { name, surfaceId, widgetId, context } }`. Decode
that part into an `A2uiClientAction`, then `actionToMessage(...)` it and send it
as the next turn:

```dart
import 'dart:convert';
import 'package:genkit_a2ui/client.dart';
import 'package:genui/genui.dart' hide basicCatalogId, DataPart;

surfaceController.onSubmit.listen((ChatMessage message) {
  final action = _actionFromSubmit(message);
  // Guard against re-entrancy: ignore a new action while a turn is still
  // streaming, otherwise two concurrent turns interleave.
  if (action == null || busy) return;
  final turn = chat.sendStream(message: actionToMessage(action));
  // ...consume turn.stream like above (prose + a2uiEnvelopesFromParts)...
});

/// Extracts an [A2uiClientAction] from a genui onSubmit [ChatMessage].
A2uiClientAction? _actionFromSubmit(ChatMessage message) {
  for (final part in message.parts) {
    final interaction = part.asUiInteractionPart?.interaction;
    if (interaction == null) continue;
    final decoded = jsonDecode(interaction);
    final action = decoded is Map ? decoded['action'] : null;
    if (action is Map) {
      final m = action.cast<String, dynamic>();
      return A2uiClientAction(
        name: (m['name'] as String?) ?? 'action',
        surfaceId: (m['surfaceId'] as String?) ?? '',
        // genui names it `widgetId`; A2uiClientAction calls it sourceComponentId.
        sourceComponentId: (m['widgetId'] as String?) ?? '',
        timestamp: DateTime.now().toUtc().toIso8601String(),
        context: (m['context'] as Map?)?.cast<String, dynamic>() ?? const {},
      );
    }
  }
  return null;
}
```

The action's `name` is sent as the user message; the full action (including its
`context`) is attached as an a2ui data part so the agent can react to it.

### Forms

Input components (`TextField`, `CheckBox`, `Slider`) do **not** send their
values
automatically. To capture what the user entered, the model must:

1. Bind each input's `value` to a data-model path (`{ "path": "/email" }`).
2. Echo those same paths in the submit `Button`'s `action.event.context`.

The catalog capabilities injected into the system prompt already instruct the
model to do this. Without both steps, the action arrives with an empty
`context`.

## Custom catalogs

The `catalog` option is a **catalog id** resolved from the Genkit registry. The
bundled `'basic'` catalog is the default and needs no registration. A catalog
describes the components the model may emit:

- `id`: globally-unique URI (also used as `catalogId` on `createSurface`).
- `components`: each with `name` (matches the renderer type), `description`
  (one-line summary), and `props` (a compact, model-facing text description of
  the component's props, kept as plain text to minimize prompt tokens).

A custom catalog has two halves that MUST agree on a catalog id: the **server**
catalog (what the model is told it may render, and validated against) and the
**client** renderer (the widgets that actually paint the components). Define the
id once and share it.

### Server: register the catalog

Start from `basicCatalog` and add your own component, then register it with
`loadCatalog` before serving any turns and reference it by id:

```dart
import 'package:genkit_a2ui/a2ui.dart';

const weatherCatalogId = 'com.example.a2ui.weather';

final weatherCatalog = A2uiCatalog(
  id: weatherCatalogId,
  components: [
    ...basicCatalog.components,
    const A2uiCatalogComponent(
      name: 'Gauge',
      description: 'A circular gauge visualizing a single numeric value.',
      props: 'value: number or { path } binding (required); min?: number; '
          'max?: number; label?: string; unit?: string.',
    ),
  ],
);

// Call once at startup, before the agent handles a turn.
Future<void> registerCatalogs() =>
    loadCatalog(ai, id: weatherCatalogId, catalog: weatherCatalog);

final uiAgent = ai.defineAgent(
  name: 'uiAgent',
  model: googleAI.gemini('gemini-flash-latest'),
  use: [a2ui(catalog: weatherCatalogId, validate: 'strict')],
  store: InMemorySessionStore(),
);
```

You can also load a catalog from a JSON file:
`loadCatalog(ai, id: 'my-catalog', file: './my-catalog.json')`.

### Client: register a matching widget

On the Flutter client, implement the matching component as a genui `CatalogItem`
(a `name`, a prop `dataSchema`, and a `widgetBuilder`) and re-tag the catalog
with
the SAME id:

```dart
final gaugeCatalogItem = CatalogItem(
  name: 'Gauge', // MUST match the server component name
  dataSchema: _gaugeSchema, // built with json_schema_builder's `S`
  widgetBuilder: (itemContext) {
    // Resolve { path } bindings via genui's Bound* widgets, then paint.
    return _GaugeWidget(...);
  },
);

final catalog = BasicCatalogItems.asCatalog().copyWith(
  newItems: [gaugeCatalogItem],
  catalogId: weatherCatalogId, // MUST match the server catalog id
);
```

If the `name` or catalog id disagree, the model emits a component the client
cannot render, or the client registers widgets under an id no surface
references.
Catalogs live in the registry under value type `a2ui-catalog`.

## Security and the trust boundary

Generative UI moves model output into the UI, so treat every surface an agent
emits as **untrusted input**. The `validate` option (including `'strict'`)
checks
envelope structure and component *type names* against the catalog only. It does
**not** validate component props or data-model values: model-controlled values
such as `Image.url` and `Text` (inline Markdown that a renderer may turn into
rich content) pass through untouched. `'strict'` is a well-formedness check, not
a
security boundary.

- **The renderer/catalog owns prop sanitization.** Whatever renders a surface
  (for example `genui` plus your Markdown renderer) is responsible for escaping
  and sanitizing prop values before they reach the UI.
- **Restrict remote sources at the host.** On the web, serve the app with a
  Content Security Policy that limits `img-src` and other fetch directives to
  origins you trust.
- **Do not put secrets in the data model.** Anything bound into a surface's data
  model can be echoed back through an action's `context`.

For server-side control over props (for example, allow-listing image hosts), add
your own model middleware after `a2ui()` to inspect and rewrite the emitted a2ui
parts.

## How it works

A2UI rides on its own part channel: a Genkit `data` part with mime type
`application/a2ui+json` whose `data` is `{ "envelopes": [...] }`. On each model
call inside the agent's tool loop, `a2ui()`:

1. Injects the catalog's capabilities into the system prompt (unless
   `instructions: 'none'`).
2. Intercepts the model output (streamed chunks and the final message).
3. Extracts `a2ui` fenced code blocks from the model's text.
4. Validates them against the catalog (per `validate`).
5. Rewrites them into canonical a2ui data parts.

Inbound a2ui parts (a surface action sent back as the next turn, or replayed
history) are summarized into plain text before the underlying model sees them,
so
a model that does not understand the a2ui mime type can still reason about prior
surfaces and user actions.

For a complete, runnable example (a shelf server plus a Flutter genui client
with
a custom `Gauge` catalog), see the `a2ui` testapp in the Genkit Dart repo.

agents-artifacts.md 6.1 KB
# Working with Artifacts

> The `Artifact` type is stable and comes from `package:genkit/genkit.dart`, but
> the surrounding agent APIs (`defineAgent`, `currentSession`,
> `InMemorySessionStore`) are experimental and come from
> `package:genkit/experimental.dart`. Read [agents.md](agents.md) first.

**Artifacts** are named, content-bearing deliverables an agent produces during a
session — files, reports, code, etc. They live in the session (deduplicated by
name) and are returned in `res.artifacts` / tracked on the client's
`chat.artifacts`.

> **Dart has no `artifacts()` middleware yet.** Define `write_artifact` /
> `read_artifact` tools directly on top of the session artifact API
> (`ai.currentSession().addArtifacts()` / `getArtifacts()`).

> **Session artifacts vs. real files.** Artifacts (this page) live *in the
> session state* — they travel with the conversation and stream to the client.
> If instead you want the agent to work against **real files on disk** (a
> sandboxed workspace), use the `filesystem()` middleware from
> `package:genkit_middleware/filesystem.dart`
> (`filesystem(rootDirectory: ...)`, backed by `FilesystemPlugin()`), which
> gives the model `list_files` / `read_file` / `write_file` /
> `search_and_replace` tools rooted at a directory. See
> [middleware](genkit_middleware.md). The two approaches are complementary:
> session artifacts for conversation-scoped deliverables, `filesystem()` for
> persistent on-disk work.

- [Give the model artifact tools](#give-the-model-artifact-tools): Lines 37-99
- [How artifacts flow](#how-artifacts-flow): Lines 101-113
- [The Artifact shape](#the-artifact-shape): Lines 115-124
- [Programmatic access (inside tools and custom agents)](#programmatic-access-inside-tools-and-custom-agents): Lines 126-142
- [Reading artifacts on the client](#reading-artifacts-on-the-client): Lines 144-171

---

## Give the model artifact tools

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, currentSession
import 'package:schemantic/schemantic.dart';

import 'genkit.dart';

part 'workspace_agent.g.dart';

@Schema()
abstract class $WriteArtifactInput {
  @Field(description: 'The name (e.g. filename) of the artifact.')
  String get name;
  @Field(description: 'The full content of the artifact.')
  String get content;
}

@Schema()
abstract class $ReadArtifactInput {
  @Field(description: 'The name of the artifact to read.')
  String get name;
}

final writeArtifact = ai.defineTool(
  name: 'write_artifact',
  description: 'Create or overwrite a named artifact (e.g. a file). Pass the '
      'filename as "name" and the full content as "content".',
  inputSchema: WriteArtifactInput.$schema,
  outputSchema: SchemanticType.string(),
  fn: (input, _) async {
    final session = ai.currentSession()!;
    session.addArtifacts([
      Artifact(name: input.name, parts: [TextPart(text: input.content)]),
    ]);
    return .response('Wrote artifact "${input.name}".');
  },
);

final readArtifact = ai.defineTool(
  name: 'read_artifact',
  description: 'Read the content of a previously created artifact by name.',
  inputSchema: ReadArtifactInput.$schema,
  outputSchema: SchemanticType.string(),
  fn: (input, _) async {
    final session = ai.currentSession()!;
    final match = session.getArtifacts().where((a) => a.name == input.name);
    if (match.isEmpty) return .response('Artifact "${input.name}" not found.');
    return .response(match.first.parts.map((p) => p.text ?? '').join());
  },
);

final workspaceAgent = ai.defineAgent(
  name: 'workspaceAgent',
  system: 'You are a code generation assistant. Use write_artifact to create '
      'files (pass the filename as "name" and the full content as "content"). '
      'Use read_artifact to review or modify a previously created file.',
  tools: [writeArtifact, readArtifact],
  use: [retry()],
  store: InMemorySessionStore(),
);
```

## How artifacts flow

Adding an artifact to the session emits an event that the agent runtime forwards
to the client as an `artifact` stream chunk. Artifacts are **deduplicated by
name** — writing the same `name` again replaces it.

Run it; artifacts are produced via the tool and returned in the response:

```dart
final chat = workspaceAgent.chat();
final res = await chat.send(text: 'Write poem.txt with a poem about Genkit');
print(res.artifacts); // List<Artifact>
```

## The `Artifact` shape

```dart
// An artifact's content lives in `parts` (text parts). `name` and `metadata`
// are optional on the type but you should always set `name`.
final artifact = Artifact(
  name: 'poem.txt',
  parts: [TextPart(text: 'Roses are red…')],
);
```

## Programmatic access (inside tools and custom agents)

Use the active session. `ai.currentSession()` returns `null` when there's no
active session, so only call it inside an agent turn.

```dart
final session = ai.currentSession()!;

// Read all artifacts:
final all = session.getArtifacts(); // List<Artifact>
final found = all.where((a) => a.name == 'poem.txt').firstOrNull;

// Create / replace artifacts:
session.addArtifacts([
  Artifact(name: 'notes.md', parts: [TextPart(text: '# Notes')]),
]);
```

## Reading artifacts on the client

The `remoteAgent` client tracks artifacts on `chat.artifacts`; each response
exposes `res.artifacts`; and each streamed chunk exposes `chunk.artifact` as it
arrives.

```dart
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent

final agent = remoteAgent(url: '/api/workspaceAgent');
final chat = agent.chat();

final turn = chat.sendStream(text: 'Create index.html and styles.css');
await for (final chunk in turn.stream) {
  final artifact = chunk.artifact;
  if (artifact != null) {
    // artifact.name, artifact.parts - render/store it live.
  }
}
final res = await turn.response;
print(res.artifacts); // artifacts produced this turn
print(chat.artifacts); // all artifacts tracked for the session
```

> In [multi-agent orchestration](agents-multi-agent.md), the `agents()`
> delegation middleware can merge sub-agent artifacts into the parent session
> (namespaced by an invocation id) via its `artifactStrategy` option.
agents-background.md 4.1 KB
# Background Agents / Detaching

> Detaching **requires a [session store](agents-sessions.md)** — the server
> needs somewhere to write the result when background work finishes. Read
> [agents.md](agents.md) first.

Detaching runs a turn in the background: the server saves a `pending` snapshot
and returns a `snapshotId` **immediately**, keeps processing, then updates the
snapshot to a terminal status (`completed` / `failed` / `aborted` / `expired`).
The client polls for completion and can abort.

- [Define the agent (store required)](#define-the-agent-store-required): Lines 19-46
- [Client-side: detach, poll, and abort](#client-side-detach-poll-and-abort): Lines 48-87
- [Server-side: detach and wait](#server-side-detach-and-wait): Lines 89-101
- [Status values](#status-values): Lines 103-115

---

## Define the agent (store required)

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, InMemorySessionStore

import 'genkit.dart';

final backgroundAgent = ai.defineAgent(
  name: 'backgroundAgent',
  system: 'You are a senior research analyst. Produce a comprehensive '
      'markdown report.',
  use: [retry()],
  store: InMemorySessionStore(), // REQUIRED for detach
);
```

Expose its companion actions so the client can poll/abort (see
[agents.md](agents.md#serve-an-agent-over-http)):

```dart
import 'package:genkit/experimental_io.dart';
import 'package:genkit/io.dart';

// The store makes addAgent mount /getSnapshot and /abort next to the turn route.
final genkit = GenkitRouter()
  ..addAgent(backgroundAgent, path: '/api/backgroundAgent');
```

## Client-side: detach, poll, and abort

On the client (`package:genkit/client.dart`), `chat.detach(text: ...)` (or
`chat.detach(...)`) resolves immediately with a `DetachedTask` carrying the
`snapshotId`. `task.poll(...)` yields `AgentSnapshot`s until a terminal status;
`task.abort()` cancels the background work. Each `AgentSnapshot` surfaces
`.status`, `.messages`, `.artifacts`, and typed `.custom` state directly.

```dart
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent, DetachedTask

final agent = remoteAgent(url: '/api/backgroundAgent');

// Submit - resolves immediately with a handle.
final task = await agent.chat().detach(text: 'Quantum computing impact');
print(task.snapshotId);

// Poll until a terminal status.
await for (final snap in task.poll(interval: Duration(milliseconds: 1500))) {
  final status = snap.status?.value ?? 'pending';
  if (status == 'completed') {
    final messages = snap.messages;
    final lastModel =
        messages.where((m) => m.role == Role.model).lastOrNull;
    final text =
        (lastModel?.content ?? []).map((p) => p.text ?? '').join();
    print(text);
    break;
  } else if (status == 'failed') {
    throw Exception('Background task failed on the server.');
  } else if (status == 'aborted' || status == 'expired') {
    break;
  }
  // 'pending' → keep polling
}

// Abort an in-flight task at any time:
await task.abort();
```

## Server-side: detach and wait

You can also detach from a server-side chat and wait for the result. `task.wait`
polls the store until a terminal state and resolves with the final snapshot.

```dart
final chat = backgroundAgent.chat();
final task = await chat.detach(text: 'Write a report on renewable energy trends');
print(task.snapshotId); // available immediately

final snapshot = await task.wait(interval: Duration(seconds: 2));
print(snapshot?.status?.value); // 'completed' | 'failed' | 'aborted' | 'expired'
```

## Status values

- `pending` — still processing.
- `completed` — completed successfully (read the result from
  `snapshot.messages`).
- `failed` — error during processing.
- `aborted` — cancelled by the client via `abort()`.
- `expired` — the background worker stopped responding (e.g. server restart);
  terminal, the task can never complete.

> Equivalent low-level wire protocol: the client sends `{ detach: true }` with
> the message; `poll`/`wait` hit the agent's `getSnapshot` action, and `abort`
> hits the `abort` action. `remoteAgent` wraps all of this for you.
agents-branching.md 3.8 KB
# Agent Branching

> Requires a [session store](agents-sessions.md) so snapshots are persistent.
> Read [agents.md](agents.md) first.

A `snapshotId` is an **immutable checkpoint**, like a git commit. You can fork
as
many independent timelines as you want from the same snapshot — each turn from a
snapshot creates a new, independent snapshot; the original is unchanged.

To branch, open a new `chat` attached to an earlier snapshot via
`agent.chat(snapshotId: ...)`.

- [Server-side branching](#server-side-branching): Lines 20-47
- [Client-side branching ("pick a variant")](#client-side-branching-pick-a-variant): Lines 49-80
- [Restoring history from a snapshot](#restoring-history-from-a-snapshot): Lines 82-110

---

## Server-side branching

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, InMemorySessionStore

import 'genkit.dart';

final assistant = ai.defineAgent(
  name: 'assistant',
  system: 'You are a helpful assistant.',
  store: InMemorySessionStore(),
);

final root = assistant.chat();
final res1 = await root.send(text: 'Hello!');
final checkpoint = res1.snapshotId; // branch point

// Branch A - forks from `checkpoint`.
final branchA = assistant.chat(snapshotId: checkpoint);
await branchA.send(text: 'My name is Bob.');
final resA = await branchA.send(text: 'What is my name?'); // -> Bob

// Branch B - forks from the SAME `checkpoint`, fully independent.
final branchB = assistant.chat(snapshotId: checkpoint);
await branchB.send(text: 'My name is John.');
final resB = await branchB.send(text: 'What is my name?'); // -> John
```

## Client-side branching ("pick a variant")

A common pattern: generate two variants from the same checkpoint in parallel,
let the user pick one, and continue from the chosen snapshot.

```dart
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent, AgentChat

final agent = remoteAgent(url: '/api/branchingAgent');
String? snapshotId; // current branch point

Future<(AgentResponse, AgentResponse)> twoVariants(String text) async {
  // Each variant gets its own chat branching from the same snapshot
  // (or a fresh session when there's no branch point yet).
  AgentChat makeChat() =>
      snapshotId != null ? agent.chat(snapshotId: snapshotId) : agent.chat();

  final results = await Future.wait([
    makeChat().send(text: text),
    makeChat().send(text: text),
  ]);
  // results[0].snapshotId != results[1].snapshotId - both branch from the
  // same point.
  return (results[0], results[1]);
}

// When the user picks a variant, its snapshotId becomes the new branch point:
void pick(String chosenSnapshotId) {
  snapshotId = chosenSnapshotId;
}
```

## Restoring history from a snapshot

Use `agent.getSnapshot(snapshotId: ...)` to read a snapshot's state without
starting a turn — handy for restoring a UI after a reload (e.g. a snapshotId
stored in the URL). The server must expose the agent's `getSnapshotDataAction`
(see [agents.md](agents.md#serve-an-agent-over-http)).

`getSnapshot(...)` returns an `AgentSnapshot<State>` — a typed veneer that
surfaces `.messages`, `.artifacts`, and typed `.custom` state directly (use
`.sessionState` for the raw `SessionState` if you need it).

```dart
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent, AgentSnapshot

final agent = remoteAgent(url: '/api/branchingAgent');

final snapshot = await agent.getSnapshot(snapshotId: snapshotId);
final history = (snapshot?.messages ?? [])
    .where((m) => m.role == Role.user || m.role == Role.model)
    .map((m) => (
          role: m.role.value,
          text: m.content.map((p) => p.text ?? '').join(),
        ))
    .toList();
```

> Abandoned branches simply remain in the store as immutable snapshots; nothing
> is overwritten when you branch.
agents-custom.md 6.9 KB
# Advanced Custom Agents — `defineCustomAgent`

> `ai.defineCustomAgent` is experimental and comes from
> `package:genkit/experimental.dart`. Read [agents.md](agents.md) and
> [agent state](agents-state.md) first.

`defineAgent` runs a single prompt + tool loop. When you need **full control of
the turn** — multiple sequential model calls, custom logic between them, manual
message/state management, or custom progress streaming — use
`ai.defineCustomAgent`. You provide the handler that runs the turn.

- [When to use it](#when-to-use-it): Lines 19-29
- [Signature](#signature): Lines 31-62
- [Example: multi-step research agent](#example-multi-step-research-agent): Lines 64-174
- [Custom status streaming](#custom-status-streaming): Lines 176-199

---

## When to use it

Reach for `defineCustomAgent` when a turn needs to:

- make **multiple model calls** with your own orchestration between them;
- run **multi-step workflows** (decompose → research → synthesize);
- **manually manage** messages and custom state;
- **stream custom status** updates to the client mid-turn.

Otherwise prefer `defineAgent` (simpler; custom state still works — see
[agent state](agents-state.md)).

## Signature

```dart
Agent<State> defineCustomAgent<State>({
  required String name,
  String? description,
  SchemanticType<State>? stateSchema,
  SessionStore? store,
  ClientTransform? clientTransform,
  required AgentFn fn, // (SessionRunner sess, AgentFnOptions options) => Future<AgentResult>
});
```

The handler receives a session runner `sess` and `AgentFnOptions options`
(`options.sendChunk(...)` streams chunks to the client; `options.context` holds
the ambient [per-turn context](agents.md#per-turn-ambient-context) — e.g. auth,
derived server-side for remote agents). It returns an `AgentResult`, typically
carrying the final `message` for the turn (`AgentResult.message` is nullable —
pass `message: null` when the turn produced no message).

Key `sess` methods:

- `sess.run((input, ctx) async {...})` — runs the turn; adds `input.message`
  (the incoming user message) to the session before calling your callback, so
  `sess.getMessages()` includes it. `input.message?.content` holds the parts.
- `sess.getMessages()` — the full message history.
- `sess.addMessages([...])` — append messages (e.g. your final model response).
- `sess.updateCustom(mutator)` / `sess.getCustom()` — read and mutate typed
  custom state directly on the runner (no `ai.currentSession()` needed). The
  mutator is `(State? state) => State`; each call auto-emits a `customPatch`
  chunk. Its typing follows `stateSchema` — with the map schema below the state
  is `Map<String, dynamic>?`; with a generated `.$schema` it's your typed class.

## Example: multi-step research agent

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineCustomAgent, SessionRunner
import 'package:schemantic/schemantic.dart';

import 'genkit.dart';

Map<String, dynamic> _state(Map<String, dynamic>? custom) {
  if (custom == null) {
    return {'subQuestions': <dynamic>[], 'subAnswers': <dynamic>[]};
  }
  return custom;
}

final researchAgent = ai.defineCustomAgent(
  name: 'researchAgent',
  stateSchema: .map(.string(), .dynamicSchema()),
  fn: (sess, options) async {
    Message? lastMessage;

    await sess.run((input, ctx) async {
      final userText = input.message?.content.firstOrNull?.text ?? '';

      // Step 1: decompose (a fast model). Mutating custom state auto-emits a
      // `customPatch` chunk so the client's tracked state stays live.
      sess.updateCustom((s) {
        final state = _state(s);
        state['status'] = 'Decomposing question into sub-topics…';
        return state;
      });

      final decompose = await ai.generate(
        model: liteModel,
        prompt: 'Break this into 2-3 sub-questions. Return ONLY a JSON array '
            'of strings.\nUser question: "$userText"',
        use: [retry()],
        outputFormat: 'json',
        outputSchema: SchemanticType.list(SchemanticType.string()),
      );
      final subQuestions =
          (decompose.output ?? [userText]).map((e) => e.toString()).toList();

      sess.updateCustom((s) {
        final state = _state(s);
        state['subQuestions'] = subQuestions;
        state['subAnswers'] = <dynamic>[];
        return state;
      });

      // Step 2: research each sub-question (main model).
      final subAnswers = <Map<String, dynamic>>[];
      for (var i = 0; i < subQuestions.length; i++) {
        sess.updateCustom((s) {
          final state = _state(s);
          state['status'] =
              'Researching (${i + 1}/${subQuestions.length})';
          return state;
        });
        final research = await ai.generate(
          use: [retry()],
          prompt: 'Answer concisely in 2-3 paragraphs.\n\n'
              'Question: ${subQuestions[i]}',
        );
        subAnswers.add({'question': subQuestions[i], 'answer': research.text});
      }
      sess.updateCustom((s) {
        final state = _state(s);
        state['subAnswers'] = subAnswers;
        return state;
      });

      // Step 3: synthesize and STREAM the final answer to the client.
      sess.updateCustom((s) {
        final state = _state(s);
        state['status'] = 'Synthesizing final response…';
        return state;
      });

      final synthesis = ai.generateStream(
        use: [retry()],
        prompt: 'Synthesize a unified markdown answer to "$userText" from:\n'
            '${subAnswers.map((a) => '${a['question']}: ${a['answer']}').join('\n\n')}',
      );
      await for (final chunk in synthesis) {
        options.sendChunk(AgentStreamChunk(modelChunk: chunk.modelChunk));
      }
      final finalResponse = await synthesis.onResult;
      lastMessage = finalResponse.message;
      if (lastMessage != null) sess.addMessages([lastMessage!]);

      sess.updateCustom((s) {
        final state = _state(s);
        state['status'] = 'Done';
        return state;
      });

      return null;
    });

    return AgentResult(
      message: lastMessage ??
          Message(
            role: Role.model,
            content: [TextPart(text: 'Research complete.')],
          ),
    );
  },
);
```

## Custom status streaming

Calling `sess.updateCustom(...)` during the turn automatically emits a
`customPatch` chunk, so the `remoteAgent` client's tracked
[custom state](agents-state.md) (e.g. the `status` field) stays live
**mid-stream** without any extra wiring. Stream model output separately with
`options.sendChunk(AgentStreamChunk(modelChunk: ...))`.

Seed and run a custom agent exactly like a regular one:

```dart
final chat = researchAgent.chat(
  state: SessionState(
    custom: {'subQuestions': <dynamic>[], 'subAnswers': <dynamic>[]},
    messages: [],
    artifacts: [],
  ),
);
final turn = chat.sendStream(text: 'Impacts of electric vehicles?');
await for (final chunk in turn.stream) {
  // chunk.text for model output; chunk.custom['status'] for live progress
}
await turn.response;
```
agents-deployment.md 4.3 KB
# Deploying / Serving Agents over HTTP

> Uses `GenkitRouter` (`package:genkit/io.dart`) with `addAgent`
> (`package:genkit/experimental_io.dart`). Read [agents.md](agents.md) first.
> For general HTTP serving (standalone, shelf, auth), see
> [genkit_shelf.md](genkit_shelf.md).

`addAgent(agent)` mounts the agent's routes, defaulting to `/<agent name>`:

- `POST <path>`: runs a turn (streams with `?stream=true`). Always.
- `POST <path>/getSnapshot`: reads a snapshot. Only for server-managed agents
  (defined with a `store`). Needed for [snapshot restore](agents-branching.md)
  and [background](agents-background.md) polling.
- `POST <path>/abort`: cancels a [background](agents-background.md) turn. Only
  when the store can signal the running turn.

So a client-managed (stateless) agent gets only its turn route. These paths
match the `remoteAgent` client defaults (`${url}/getSnapshot`, `${url}/abort`),
so a client only needs the base `url`. `hideGetSnapshot: true` /
`hideAbort: true` remove supported routes; they can't force unsupported ones.

- [Serving several agents (shelf)](#serving-several-agents-shelf): Lines 30-78
- [Auth](#auth): Lines 80-84
- [CORS for browser clients](#cors-for-browser-clients): Lines 86-90
- [Registering agents/flows](#registering-agentsflows): Lines 92-98
- [Notes](#notes): Lines 100-111

---

## Serving several agents (shelf)

```dart
import 'dart:io';

import 'package:genkit/experimental_io.dart'; // addAgent
import 'package:genkit/io.dart'; // GenkitRouter, CorsOptions
import 'package:genkit_shelf/genkit_shelf.dart'; // asShelfHandler
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';

import 'package:agents_sample/background_agent.dart';
import 'package:agents_sample/weather_agent.dart';
import 'package:agents_sample/weather_agent_stateless.dart';

void main() async {
  final api = GenkitRouter()
    ..addAgent(weatherAgent) // turn + /getSnapshot (+ /abort if supported)
    ..addAgent(backgroundAgent)
    ..addAgent(weatherAgentStateless) // turn only
    // Plain flows used by the UI, on custom paths:
    ..addAction(listWorkspaceFiles, path: '/workspace/files');

  final router = Router()
    // `mount` strips the prefix: agents are at /api/<agentName>.
    ..mount(
      '/api/',
      api.asShelfHandler(
        // Browser clients on another origin (Jaspr/Flutter web dev server).
        cors: const CorsOptions(
          allowedHeaders: ['Content-Type', 'Accept', 'X-Genkit-Stream-Id'],
        ),
      ),
    );

  final port = int.tryParse(Platform.environment['PORT'] ?? '') ?? 8080;
  final server = await io.serve(
    const Pipeline().addMiddleware(logRequests()).addHandler(router.call),
    InternetAddress.anyIPv4,
    port,
  );
  print('Agents API server running on http://localhost:${server.port}');
}
```

Without shelf, skip the `Router` and call
`api.serve(cors: const CorsOptions(...))`; pass `path: '/api/weatherAgent'` to
`addAgent` to keep the `/api` prefix.

## Auth

`addAgent(agent, contextProvider: bearerAuth)` applies the provider to every
route of that agent, so reading or aborting a snapshot is authorized like a
turn. See [genkit_shelf.md](genkit_shelf.md#auth-contextprovider).

## CORS for browser clients

Pass `CorsOptions` to `serve()` / `asShelfHandler()` (no `shelf_cors_headers`).
Browser streaming clients send `X-Genkit-Stream-Id`, which is **not** in the
default `allowedHeaders`, so list it explicitly as above.

## Registering agents/flows

Agents register with Genkit when their defining top-level `final` is evaluated.
Importing the module (e.g. in your server's `bin/server.dart`) and referencing
the agent, as `addAgent(...)` does, ensures the `defineAgent` call runs. Agents
referenced only by name (e.g. sub-agents for `agents(...)` middleware) must be
touched explicitly before use.

## Notes

- The wire body matches the Genkit client:
  `{ "data": <input>, "init": <init> }`.
- For persistence across restarts, use `FileSessionStore`
  (`package:genkit/experimental_io.dart`) or `FirestoreSessionStore`
  (`package:genkit_google_cloud`) instead of `InMemorySessionStore`. See
  [sessions](agents-sessions.md).
- Consuming these endpoints from Dart/Flutter/web uses `remoteAgent` from
  `package:genkit/experimental_client.dart` (alongside
  `package:genkit/client.dart`) — see
  [agents.md](agents.md#consume-an-agent-from-a-client-remoteagent).
agents-human-in-the-loop.md 8.4 KB
# Agent Human-in-the-Loop / Interrupts

> Read [agents.md](agents.md) first.

An **interrupt** pauses an agent mid-turn and hands control back to your code
(or
a human) — e.g. to approve a sensitive action, collect missing input, or confirm
a plan. Internally it's a **tool call used as control flow**: the interrupt tool
never runs to completion on the server; it pauses the turn. You then **resume**
from the exact point it paused.

> Two ways to define an interrupt:
>
> - `ai.defineInterrupt(...)`: an interrupt-only tool that always pauses and
>   never runs logic. `outputSchema` describes what the caller supplies on
>   resume.
> - A normal `ai.defineTool` whose body returns `.interrupt(data)`: pauses
>   conditionally (e.g. only for large transfers) or after some work.
>
> There is no `ctx.interrupt(...)`; return `.interrupt(...)` from the tool.

```dart
final askUser = ai.defineInterrupt(
  name: 'askUser',
  description: 'Ask the user a clarifying question.',
  inputSchema: .string(), // the question
  outputSchema: .string(), // the answer, supplied on resume
);
```

Interrupts are **orthogonal to persistence** — they work the same whether the
agent uses a [session store](agents-sessions.md) or
[client-managed state](agents.md#client-managed-state-no-server-store). Just
resume on the same `chat` (or, for raw calls, carry the returned state/snapshot
back into the resume).

Flow: `chat.send(text: ...)` → response has `res.interrupts` → collect human
input
→ `chat.resume(respond: [...])`.

- [Define an interrupt (a tool that interrupts)](#define-an-interrupt-a-tool-that-interrupts): Lines 49-113
- [Detect and resume (server-side)](#detect-and-resume-server-side): Lines 115-172
- [Client-side (browser) interrupts](#client-side-browser-interrupts): Lines 174-205
- [Interrupts with tool-approval middleware](#interrupts-with-tool-approval-middleware): Lines 207-232
- [Notes and gotchas](#notes-and-gotchas): Lines 234-248

---

## Define an interrupt (a tool that interrupts)

The example below uses tools that return `.interrupt(...)`, which pauses the
turn; its argument is the data shown to the human. Add interrupts (either kind)
to the agent's `tools`.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, InMemorySessionStore
import 'package:schemantic/schemantic.dart';

import 'genkit.dart';

part 'banking_agent.g.dart';

@Schema()
abstract class $UserApprovalInput {
  @Field(description: 'The action to be approved')
  String get action;
  @Field(description: 'Details about the action')
  String get details;
}

@Schema()
abstract class $TransferMoneyInput {
  double get amount;
  String get toAccount;
}

@Schema()
abstract class $TransferMoneyOutput {
  bool get success;
  String get transactionId;
}

/// Interrupt: always pauses. The caller provides `{ approved, feedback }` on
/// resume. No `outputSchema` - the output comes from the resume call.
final userApproval = ai.defineTool(
  name: 'userApproval',
  description: 'Ask the user for approval before a sensitive action.',
  inputSchema: UserApprovalInput.$schema,
  fn: (input, ctx) async => .interrupt(),
);

/// Executes the transfer. Only reached after the user approves.
final transferMoney = ai.defineTool(
  name: 'transferMoney',
  description: 'Transfer money to a specified account.',
  inputSchema: TransferMoneyInput.$schema,
  outputSchema: TransferMoneyOutput.$schema,
  fn: (input, _) async => .response(TransferMoneyOutput(
    success: true,
    transactionId: 'txn-${DateTime.now().millisecondsSinceEpoch}',
  )),
);

final bankingAgent = ai.defineAgent(
  name: 'bankingAgent',
  system: 'You are a banking assistant. ALWAYS use the userApproval interrupt '
      'to confirm before executing transferMoney.',
  tools: [userApproval, transferMoney],
  use: [retry()],
  store: InMemorySessionStore(),
);
```

## Detect and resume (server-side)

`res.interrupts` is non-empty when the agent paused. Each `AgentInterrupt`
exposes:

- `.name` — the interrupt's name.
- `.input` — the data the model passed in.
- `.respond(output)` — **builder** returning a resume entry that supplies the
  tool's output (without executing it). Does **not** send.
- `.restart([payload])` — **builder** re-issuing the original tool request
  (retry
  / let the tool actually run). Pass an optional `Map` payload; it is nested
  under `metadata.resumed` and read back tool-side via `ctx.resumed`. Does
  **not** send.

Resume the **same** chat with `chat.resume(...)` / `chat.resumeStream(...)`,
passing `respond` / `restart` entries directly:

```dart
final chat = bankingAgent.chat();
var res = await chat.send(text: 'Transfer \$500 to my savings account.');

final approval =
    res.interrupts.where((i) => i.name == 'userApproval').firstOrNull;
if (approval != null) {
  print(approval.input); // { action, details } - show this to the human

  // Collect the human decision, then resume with the interrupt's output:
  res = await chat.resume(
    respond: [
      approval.respond({'approved': true, 'feedback': 'Looks good'}),
    ],
  );
}
print(res.text); // final confirmation
```

Streaming variant:

```dart
final turn = chat.resumeStream(
  respond: [approval.respond({'approved': true})],
);
await for (final chunk in turn.stream) {
  stdout.write(chunk.text);
}
final res = await turn.response;
```

You can resume multiple interrupts at once by passing several builders, and mix
`respond` (supply output) with `restart` (re-run the tool):

```dart
await chat.resume(
  respond: [a.respond({'approved': true})],
  restart: [b.restart()],
);
```

## Client-side (browser) interrupts

The same pattern works over HTTP with `remoteAgent` from
`package:genkit/client.dart`. The client tracks the snapshot, so resuming the
same `chat` continues exactly where it paused.

```dart
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent, AgentInterrupt

final agent = remoteAgent(url: '/api/bankingAgent');
final chat = agent.chat();

// 1. Send and detect the pause.
final res = await chat.send(text: 'Transfer \$500 to savings.');
final pending =
    res.interrupts.where((i) => i.name == 'userApproval').firstOrNull;

if (pending != null) {
  // pending.input → { action, details }; render an approval dialog.

  // 2. After the human approves/denies, resume the SAME chat.
  final turn = chat.resumeStream(
    respond: [pending.respond({'approved': true, 'feedback': 'ok'})],
  );
  await for (final chunk in turn.stream) {
    /* render chunk.text */
  }
  final finalRes = await turn.response;
  // If finalRes.interrupts is non-empty, the agent paused again - repeat.
}
```

## Interrupts with tool-approval middleware

The [`toolApproval`](genkit_middleware.md) middleware turns selected tools into
approval interrupts without any custom interrupt code. The middleware gates each
tool call itself: a tool is allowed to run only if it is in the `approved` list
or its `resumed` payload carries `{ 'tool-approved': true }`. To let an approved
tool through on resume, **restart** the paused interrupt with that payload — the
`.restart(...)` builder nests it under `metadata.resumed`, exactly what the
middleware reads:

```dart
// `interrupt` is the paused AgentInterrupt from `res.interrupts`.
// Pass this restart entry back when resuming the chat:
await chat.resume(
  restart: [interrupt.restart({'tool-approved': true})],
);
```

If instead you write your own `.interrupt(...)` gate inside a tool (as in the
`coding_agent` sample), you inspect the resume payload yourself via the
`ctx.resumed` getter:

```dart
final resumed = ctx.resumed; // the payload passed to `.restart(...)`
final isApproved = resumed is Map && resumed['tool-approved'] == true;
```

## Notes and gotchas

- **No store required.** Interrupts work with either a
  [session store](agents-sessions.md) or
  [client-managed state](agents.md#client-managed-state-no-server-store).
- **`respond`/`restart` are builders.** They return resume entries; they do not
  send. You still call `chat.resume(...)`.
- **Resume validation.** The server validates each `respond`/`restart` entry
  against the conversation history — always build entries from the interrupt
  objects in the response, not hand-rolled parts.
- **Re-pausing.** After resuming, the new response may interrupt again; loop
  until `res.interrupts` is empty.
- **UX tip:** don't render a model message bubble for an interrupted turn; show
  the approval UI from `interrupt.input` instead, then render the model's reply
  after resuming.
agents-multi-agent.md 6.0 KB
# Multi-Agent Orchestration / Sub-Agents

> Sub-agent delegation uses the `agents()` middleware from
> `package:genkit_middleware/agents.dart`. Read [agents.md](agents.md) first.

A common pattern is an **orchestrator** agent that delegates tasks to
specialized **sub-agents** (e.g. a `researcher` and a `coder`). The `agents()`
middleware injects one delegation tool per sub-agent (`delegate_to_<name>`),
appends a `<sub-agents>` block to the orchestrator's system prompt, and — when
the model calls a delegation tool — runs the sub-agent and returns its response
as the tool result.

To make the middleware available, register `AgentsPlugin()` on the `Genkit`
instance:

```dart
import 'package:genkit_middleware/agents.dart';

final ai = Genkit(plugins: [googleAI(), AgentsPlugin()]); // retry() is built in
```

- [1. Define the sub-agents](#1-define-the-sub-agents): Lines 31-58
- [2. Wire up the orchestrator](#2-wire-up-the-orchestrator): Lines 60-102
- [agents() options](#agents-options): Lines 104-114
- [Background (async) delegation](#background-async-delegation): Lines 116-144
- [Sharing artifacts between agents](#sharing-artifacts-between-agents): Lines 146-156
- [Other middleware](#other-middleware): Lines 158-168

---

## 1. Define the sub-agents

Give each sub-agent a `description` — it's auto-discovered from registry
metadata
and shown to the orchestrator so the model knows when to delegate.

```dart
import 'package:genkit/experimental.dart'; // defineAgent

import 'genkit.dart';

final researcher = ai.defineAgent(
  name: 'researcher',
  description:
      'A thorough research assistant that provides well-sourced answers.',
  system: 'You are a thorough research assistant. When asked a question, '
      'provide a clear, well-structured, and well-sourced answer.',
  maxTurns: 10,
);

final coder = ai.defineAgent(
  name: 'coder',
  description: 'Writes, debugs, and explains code. Use for any programming tasks.',
  system: 'You are an expert programmer. Provide clean, well-commented code '
      'with explanations. Use Dart by default unless asked otherwise.',
  maxTurns: 10,
);
```

## 2. Wire up the orchestrator

Add `agents()` to the orchestrator's `use: [...]`. Pass the sub-agent **names**;
their descriptions are auto-discovered from the registry.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, InMemorySessionStore
import 'package:genkit_middleware/agents.dart';

import 'genkit.dart';

final orchestratorAgent = ai.defineAgent(
  name: 'orchestratorAgent',
  system: '''
You are a helpful project assistant.

Analyze the user's request and delegate to the appropriate sub-agent.
If the request requires both research AND code, call them sequentially.
After receiving sub-agent responses, synthesize a final answer for the user.''',
  use: [
    agents(
      agents: ['researcher', 'coder'],
      maxDelegations: 5, // guard rail against runaway delegation loops
      historyLength: 4, // forward the last N user/model messages as context
    ),
  ],
  store: InMemorySessionStore(),
);
```

Run it like any other agent:

```dart
final chat = orchestratorAgent.chat();
final turn = chat.sendStream(
  text: 'Research the best sorting algorithms, then write a Dart quicksort.',
);
await for (final chunk in turn.stream) {
  stdout.write(chunk.text);
}
final res = await turn.response;
```

## `agents()` options

- `agents` (required): `List<String>` of sub-agent names. Each description is
  auto-discovered from the registry.
- `toolPrefix`: prefix for generated tool names. Defaults to `delegate_to` →
  `delegate_to_<agent>`.
- `maxDelegations`: max delegations per `generate` call. Prevents runaway loops.
- `historyLength`: number of recent user/model messages forwarded to sub-agents
  as context. `0`/omitted sends only the task description.
- `artifactStrategy`: `'inline'` (default) or `'session'` — see below.
- `async`: enable background delegation — see below.

## Background (async) delegation

Set `async: true` to let the orchestrator run sub-agents in the background. Each
delegation tool then accepts a `background` flag that starts the sub-agent and
returns a `taskId` immediately, and the middleware adds
`check_background_tasks`, `wait_for_background_tasks`, and
`abort_background_tasks` tools so the model can launch several tasks in parallel
and collect them later. A `continue_task` tool lets the model retry a
failed/aborted task or follow up on a completed one.

```dart
final orchestratorAgent = ai.defineAgent(
  name: 'orchestratorAgent',
  system: 'Delegate independent tasks in the background, then collect the '
      'results before answering.',
  use: [
    agents(
      agents: ['researcher', 'coder'],
      async: true, // adds background delegation + the background-task tools
    ),
  ],
  store: InMemorySessionStore(),
);
```

> Background delegation requires **server-managed sub-agents** — each sub-agent
> needs a session `store` that supports detach (see
> [background agents](agents-background.md)). A sub-agent without a store cannot
> be run in the background.

## Sharing artifacts between agents

Sub-agents can produce [artifacts](agents-artifacts.md). `artifactStrategy`
controls how they reach the orchestrator:

- `'inline'` (default): artifact content is included in the delegation tool
  result (so the model sees it directly) **and** merged into the parent session.
- `'session'`: artifacts are merged into the parent session only; the tool
  result
  lists artifact names, not content. Merged artifacts are namespaced by an
  invocation id (`<invocationId>/<name>`).

## Other middleware

`package:genkit_middleware` also exports `filesystem`, `skills`, and
`toolApproval`; `retry` ships in core `package:genkit`. They attach the same way
via `use: [...]` on an agent (or on `ai.generate`) — see
[using middleware](genkit_middleware.md). `retry()` is commonly paired with
delegation.

> Note: if a sub-agent triggers an [interrupt](agents-human-in-the-loop.md), it
> is reported back to the orchestrator as a normal tool response (not propagated
> as a resumable interrupt). Delegate self-contained tasks.
agents-sessions.md 7.1 KB
# Agent Sessions & Persistence

> Sessions are experimental. `InMemorySessionStore` and `Session`/`SessionStore`
> come from `package:genkit/experimental.dart`; `FileSessionStore` from
> `package:genkit/experimental_io.dart` (needs `dart:io`);
> `FirestoreSessionStore`
> from `package:genkit_google_cloud`. See [agents.md](agents.md) for the basics
> and the experimental-import note first.

When an agent has a `store`, the **server** owns the session history. Each turn
produces an immutable **snapshot**; the snapshot chain is what carries
conversation state forward. A store also enables
[branching](agents-branching.md)
and [background execution](agents-background.md). (Interrupts work with or
without
a store — see [human-in-the-loop](agents-human-in-the-loop.md).)

- [Pick a store](#pick-a-store): Lines 26-74
- [Typed session state](#typed-session-state): Lines 76-115
- [Interrupts (human-in-the-loop)](#interrupts-human-in-the-loop): Lines 117-122
- [Firestore session store (scalable)](#firestore-session-store-scalable): Lines 124-167
- [Implementing a custom SessionStore](#implementing-a-custom-sessionstore): Lines 169-207

---

## Pick a store

```dart
import 'package:genkit/experimental.dart'; // InMemorySessionStore
import 'package:genkit/experimental_io.dart'; // FileSessionStore (dart:io)

// In-memory: great for tests/dev; lost on restart.
final memStore = InMemorySessionStore();

// File-backed: snapshots persisted as JSON under <dir>/global/.
final fileStore = FileSessionStore('./.snapshots');

// File store with chain pruning - keep only the last N snapshots in a chain.
final pruning = FileSessionStore('./.snapshots', maxPersistedChainLength: 3);
```

Attach it to the agent:

```dart
import 'genkit.dart';

final logbookAgent = ai.defineAgent(
  name: 'logbookAgent',
  system: 'You are a personal logbook assistant.',
  store: fileStore,
);
```

A single `chat` persists to the store and threads the snapshot forward
automatically:

```dart
final chat = logbookAgent.chat();
final res1 = await chat.send(text: 'Log this: I started studying Genkit today.');
final res2 = await chat.send(text: 'What did I study today?'); // remembers turn 1
print('${res1.snapshotId} ${res2.snapshotId}');
```

Resume a prior conversation by snapshot id (server-side):

```dart
// Continue an existing session from a snapshot, restoring its history.
final resumed = await logbookAgent.loadChat(snapshotId: res2.snapshotId);
await resumed.send(text: 'Add another note.');
```

`agent.chat(snapshotId: ...)` opens a new chat that **branches** from a snapshot
without pre-loading its history; `agent.loadChat(...)` returns a chat with the
history restored. See [branching](agents-branching.md).

## Typed session state

Use `stateSchema` to attach typed custom state to the session. It is validated
when a snapshot is loaded. Seed initial custom state when opening the chat via
the `state` argument (a `SessionState`, whose `custom` field holds your data).

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, InMemorySessionStore
import 'package:schemantic/schemantic.dart';

import 'genkit.dart';

part 'profile_agent.g.dart';

@Schema()
abstract class $Profile {
  String get name;
  String get tier; // 'free' | 'pro'
}

final profileAgent = ai.defineAgent(
  name: 'profileAgent',
  system: 'Greet the user by name and tailor answers to their tier.',
  stateSchema: Profile.$schema,
  store: InMemorySessionStore(),
);

// Custom state lives under `.custom` of the SessionState.
final chat = profileAgent.chat(
  state: SessionState(
    custom: {'name': 'Ada', 'tier': 'pro'},
    messages: [],
    artifacts: [],
  ),
);
```

See [working with state](agents-state.md) for reading/mutating custom state
inside tools and syncing it to the client.

## Interrupts (human-in-the-loop)

Interrupts pause a turn so a human can approve/provide input, then resume from
the exact pause point. They work with a store or with client-managed state
(persistence is orthogonal). See the dedicated reference:
[Human-in-the-loop / interrupts](agents-human-in-the-loop.md).

## Firestore session store (scalable)

For production, `FirestoreSessionStore` (from `package:genkit_google_cloud`)
persists each turn as an incremental JSON Patch diff anchored to periodic
sharded
checkpoints — no single document approaches Firestore's 1 MiB limit, and
reads/writes per turn are bounded by `checkpointInterval` rather than total
session length (scales to long-lived chat/coding agents).

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent
import 'package:genkit_google_cloud/firestore_session_store.dart';

import 'genkit.dart';

final myAgent = ai.defineAgent(
  name: 'myAgent',
  system: 'You are a helpful assistant.',
  // Defaults to a new Firestore() using Application Default Credentials.
  store: FirestoreSessionStore(),
);
```

> **Project id.** ADC alone may not carry a project id, so the default
> `Firestore()` can fail at write time with `Project ID has not been discovered
> yet. Initialize the SDK with credentials that include a project ID, set
> project
> ID in Settings, or set the GOOGLE_CLOUD_PROJECT environment variable.` Export
> `GOOGLE_CLOUD_PROJECT` (the Firestore client also reads a small set of
> standard
> GCP project-id env vars), or pass an explicit `Firestore` via `db`.

Options:

- `db`: explicit `Firestore` instance (defaults to a new `Firestore()`, honoring
  `FIRESTORE_EMULATOR_HOST`).
- `collection`: snapshot collection (default `'genkit-sessions'`). Companion
  collections `'<collection>-pointers'` and `'<collection>-shards'` are derived.
- `checkpointInterval`: turns between full-state checkpoints (default `25`).
  Lower for small, read-heavy state; raise for large per-turn state.
- `shardSize`: max bytes per shard/diff document (default `512 KiB`).
- `snapshotPathPrefix`: `String Function(Map<String, dynamic>? context)?` — a
  per-tenant prefix derived from the call context (defaults to `'global'`).

## Implementing a custom `SessionStore`

Implement the `SessionStore` interface. `getSnapshot` loads by `snapshotId` OR
`sessionId`; `saveSnapshot` atomically reads → mutates → persists. Optionally
implement `SnapshotChangeNotifier.onSnapshotStateChange` (used by background
agents) to subscribe to snapshot status changes.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // SessionStore, SessionSnapshot, SnapshotMutator

class MySessionStore implements SessionStore {
  @override
  Future<SessionSnapshot?> getSnapshot({
    String? snapshotId,
    String? sessionId,
    Map<String, dynamic>? context,
  }) async {
    // Load and return a snapshot, or null.
    return null;
  }

  @override
  Future<String?> saveSnapshot(
    String? snapshotId,
    SnapshotMutator mutator, {
    Map<String, dynamic>? context,
  }) async {
    // Read → mutate → persist; return the snapshotId used, or null when the
    // mutator returns null.
    return snapshotId;
  }
}
```

> Check the exact `SessionStore` method signatures in your installed version
> with
> `dart doc` or by inspecting `package:genkit` — the shape above matches the
> in-memory and file stores.
agents-state.md 7.4 KB
# Working with Agent State

> Read [agents.md](agents.md) first.

Beyond message history, an agent session can hold typed **custom state** — your
own structured data (a task list, a workflow status, counters, etc.). Tools read
and mutate it during a turn, and it is automatically synced to the
[`remoteAgent`](agents.md#consume-an-agent-from-a-client-remoteagent) client via
`customPatch` chunks (so the client's tracked state stays live mid-stream).

- [Declare the state shape](#declare-the-state-shape): Lines 18-55
- [Read and mutate state inside tools](#read-and-mutate-state-inside-tools): Lines 57-160
- [Seed and read state (server-side)](#seed-and-read-state-server-side): Lines 162-186
- [Auto-sync to the remoteAgent client](#auto-sync-to-the-remoteagent-client): Lines 188-227

---

## Declare the state shape

Pass a `stateSchema` (a schemantic `.$schema`) to `defineAgent`. It's validated
when a snapshot is loaded.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, currentSession
import 'package:schemantic/schemantic.dart';

import 'genkit.dart';

part 'task_agent.g.dart';

@Schema()
abstract class $TaskItem {
  int get id;
  String get title;
  bool get done;
}

@Schema()
abstract class $TaskState {
  List<$TaskItem> get tasks;
  int get nextId;
}

final taskAgent = ai.defineAgent(
  name: 'taskAgent',
  stateSchema: TaskState.$schema,
  system: "You manage the user's task list. Use the tools to modify it.",
  tools: [addTask /*, toggleTask, removeTask */],
  use: [retry()],
);
```

`stateSchema` works with the standard `defineAgent` — you do **not** need
`defineCustomAgent` for custom state.

## Read and mutate state inside tools

Tools call `ai.currentSession<State>()` to access the live, **typed** session,
then `session.getCustom()` / `session.updateCustom(mutator)`. `updateCustom` is
fully typed: the mutator is `(State? state) => State` — it receives the current
typed state (`null` before it's first set) and returns the new state. Each call
auto-emits a `customPatch` chunk to the client.

```dart
@Schema()
abstract class $AddTaskInput {
  @Field(description: 'Short description of the task')
  String get title;
}

@Schema()
abstract class $ToggleTaskInput {
  @Field(description: 'The task ID to toggle')
  int get id;
}

final addTask = ai.defineTool(
  name: 'addTask',
  description: 'Add a new task. Returns the created task.',
  inputSchema: AddTaskInput.$schema,
  outputSchema: TaskItem.$schema,
  fn: (input, _) async {
    final session = ai.currentSession<TaskState>()!;
    late TaskItem newTask;
    session.updateCustom((state) {
      state ??= TaskState(tasks: [], nextId: 1);
      newTask = TaskItem(id: state.nextId, title: input.title, done: false);
      state.tasks = [...state.tasks, newTask];
      state.nextId += 1;
      return state;
    });
    return .response(newTask);
  },
);
```

Because the state is typed, you work with the generated `TaskState` / `TaskItem`
classes directly — no manual `Map` munging or `fromJson`. Assign back to the
setters (e.g. `state.tasks = [...]`) so the mutated values are written to the
session.

> **Make computed/optional state fields nullable.** Non-nullable schemantic
> getters are hard casts and throw (`Null is not a subtype of num`) when a
> partially populated state blob is reloaded (e.g. a computed field that was
> never written). Make such fields nullable or give them a `defaultValue`. See
> [non-nullable getters throw on partial
> data](schemantic.md#non-nullable-getters-throw-on-partial-data).

> **Prefer whole-collection tools over append-one-item tools.** The model may
> emit several tool calls in a single **parallel** batch. Each
> `session.updateCustom` reads the current custom state, mutates, and writes it
> back; when the calls run in one batch they all read the same base and the last
> write wins, silently dropping the others. An incremental `addTask` tool is
> only
> safe if the model calls it sequentially. For anything the model may batch,
> prefer a single idempotent "replace the whole collection" tool (e.g.
> `setTasks(items: [...])`) that writes the entire collection in one call.

`ai.currentSession<State>()` returns `null` when called outside an active
session
(e.g. a tool invoked without a running agent turn), so only use it inside agent
tools.

For tools that look up and mutate an existing item, a small shared helper keeps
the not-found handling in one place:

```dart
Map<String, dynamic> _mutateTaskById(
  int id,
  Map<String, dynamic> Function(List<TaskItem> tasks, int idx) onFound,
) {
  final session = ai.currentSession<TaskState>()!;
  var result = <String, dynamic>{'success': false};
  session.updateCustom((state) {
    state ??= TaskState(tasks: [], nextId: 1);
    final tasks = state.tasks;
    final idx = tasks.indexWhere((t) => t.id == id);
    if (idx >= 0) {
      result = onFound(tasks, idx);
      // Reassign so the mutated list is written back to the session state.
      state.tasks = tasks;
    } else {
      result = {'success': false, 'error': 'Task $id not found'};
    }
    return state;
  });
  return result;
}

final toggleTask = ai.defineTool(
  name: 'toggleTask',
  description: 'Toggle a task done/undone by its ID.',
  inputSchema: ToggleTaskInput.$schema,
  fn: (input, _) async => .response(_mutateTaskById(input.id, (tasks, idx) {
    tasks[idx].done = !tasks[idx].done;
    return {'success': true, 'task': tasks[idx].toJson()};
  })),
);
```

## Seed and read state (server-side)

Seed initial custom state when opening a chat. The `state` argument is a
`SessionState`: custom data goes under `.custom` (alongside `messages` and
`artifacts`).

```dart
final chat = taskAgent.chat(
  state: SessionState(
    custom: {'tasks': <dynamic>[], 'nextId': 1},
    messages: [],
    artifacts: [],
  ),
);

final res = await chat.send(text: 'Add a task: buy groceries');
print(res.state); // res.state returns the custom state directly
```

> **Typed state.** When you supply a `stateSchema`, `res.state` / `chat.state`
> (and `snapshot.custom`) are **parsed into the typed `State` object** (here a
> `TaskState`), not a raw `Map`. `Agent`/`AgentChat`/`AgentResponse` are generic
> over `State`, so the type flows through automatically. Without a
> `stateSchema`,
> `state` is an untyped view over the JSON.

## Auto-sync to the `remoteAgent` client

When you talk to the agent over HTTP, the `remoteAgent` client tracks custom
state for you. Seed it the same way (`state.custom`), read live updates off each
streamed chunk (`chunk.custom`), and read the authoritative state off
`chat.state` after the turn completes.

```dart
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent

final agent = remoteAgent(url: '/api/taskAgent');
final chat = agent.chat(
  state: SessionState(
    custom: {'tasks': <dynamic>[], 'nextId': 1},
    messages: [],
    artifacts: [],
  ),
);

final turn = chat.sendStream(text: 'Add buy groceries, then mark it done');
await for (final chunk in turn.stream) {
  // Live custom state arrives via customPatch chunks:
  if (chunk.custom != null) {
    // e.g. render (chunk.custom as Map)['tasks']
  }
  // chunk.text for model output
}
final res = await turn.response;

// Authoritative state after the turn:
print(res.state);
print(chat.state);
```

State updates ride on the streamed chunks — there is no `onStateChange`
subscription. For live mid-stream status updates from a multi-step custom agent,
see [advanced custom agents](agents-custom.md), which emit `customPatch` chunks
as
state changes.
agents.md 15.3 KB
# Agents

> **Agents are experimental.** The agent/session/snapshot APIs are NOT covered
> by semantic-versioning stability and live behind opt-in imports:
>
> - Server (agents, sessions, snapshots): `package:genkit/experimental.dart`
>   (alongside the stable `package:genkit/genkit.dart`).
> - Browser/HTTP client (`remoteAgent`, `AgentChat`, ...):
>   `package:genkit/experimental_client.dart` (alongside
>   `package:genkit/client.dart`).
> - `dart:io` extras (`FileSessionStore`):
>   `package:genkit/experimental_io.dart`.
>
> The entry points are marked `@experimental`, so importing them produces an
> `experimental_member_use` analyzer warning on the import line. Opt out once
> you
> accept the churn by adding to `analysis_options.yaml`:
>
> ```yaml
> analyzer:
>   errors:
>     experimental_member_use: ignore
> ```
>
> `CancellationController` / `CancellationToken` are stable and stay on
> `package:genkit/genkit.dart` / `client.dart`, not behind these imports.

An **agent** is a persistent, multi-turn conversation primitive built on top of
prompts + tools. Compared to a bare `ai.generate`/`ai.definePrompt` loop, an
agent adds:

- **Sessions**: multi-turn history tracked as immutable **snapshots**.
- **State**: typed session state (messages + custom data + artifacts).
- **Interrupts**: human-in-the-loop pause/resume.
- **Branching**: fork a conversation from any snapshot.
- **Detaching**: run a turn in the background and poll for the result.

Progressive disclosure — read the file for the level you need:

- This file: defining an agent, serving it, and **client-managed state** (no
  store).
- [Sessions & persistence](agents-sessions.md): `SessionStore`,
  `InMemorySessionStore`, `FileSessionStore`, `FirestoreSessionStore`.
- [Human-in-the-loop / interrupts](agents-human-in-the-loop.md): pausing for
  approval/input and resuming.
- [Branching](agents-branching.md): forking a conversation from a snapshot.
- [Background agents](agents-background.md): detaching long-running turns and
  polling.
- [Working with state](agents-state.md): typed custom session state and client
  auto-sync.
- [Artifacts](agents-artifacts.md): producing/reading named deliverables.
- [Multi-agent orchestration](agents-multi-agent.md): delegating to sub-agents.
- [Advanced custom agents](agents-custom.md): `defineCustomAgent` for full turn
  control.
- [Deploying agents](agents-deployment.md): serving multiple agents over HTTP
  with `GenkitRouter.addAgent`, shelf, CORS.

- [Setup](#setup): Lines 70-92
- [Define an agent](#define-an-agent): Lines 94-164
- [Agents and middleware go hand in hand](#agents-and-middleware-go-hand-in-hand): Lines 166-208
- [Chat with an agent (server-side)](#chat-with-an-agent-server-side): Lines 210-252
- [Verify an agent from the CLI (flow:run)](#verify-an-agent-from-the-cli-flowrun): Lines 254-268
- [Serve an agent over HTTP](#serve-an-agent-over-http): Lines 270-291
- [Consume an agent from a client (remoteAgent)](#consume-an-agent-from-a-client-remoteagent): Lines 293-328
- [Using from Flutter](#using-from-flutter): Lines 330-405
- [Client-managed state (no server store)](#client-managed-state-no-server-store): Lines 407-446

---

## Setup

Register the plugins your agents need on a shared `Genkit` instance. `retry` is
built into the core `package:genkit/genkit.dart` (no plugin); the other agentic
middleware (`agents`, `filesystem`, `skills`, `toolApproval`) come from
`package:genkit_middleware` and need their plugins registered.

```dart
// genkit.dart - shared instance + model refs.
import 'package:genkit/genkit.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart';

/// The default (capable) model used by most agents.
final ModelRef defaultModel = googleAI.gemini('gemini-flash-latest');

/// A fast/cheap model for auxiliary tasks.
final ModelRef liteModel = googleAI.gemini('gemini-flash-lite-latest');

final Genkit ai = Genkit(
  plugins: [googleAI()],
  model: defaultModel,
);
```

## Define an agent

`ai.defineAgent` combines prompt + tool config + (optional) session store into a
single registered action.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, InMemorySessionStore
import 'package:schemantic/schemantic.dart';

import 'genkit.dart';

part 'weather_agent.g.dart';

@Schema()
abstract class $GetWeatherInput {
  String get location;
}

@Schema()
abstract class $GetWeatherOutput {
  String get weather;
  String get temperature;
}

final getWeather = ai.defineTool(
  name: 'getWeather',
  description: 'Get the current weather for a given location.',
  inputSchema: GetWeatherInput.$schema,
  outputSchema: GetWeatherOutput.$schema,
  fn: (input, _) async => .response(GetWeatherOutput(
    weather: 'Sunny in ${input.location}',
    temperature: '71F',
  )),
);

final weatherAgent = ai.defineAgent(
  name: 'weatherAgent',
  system: 'You are a helpful weather assistant. Use the getWeather tool. '
      'Be concise.',
  tools: [getWeather],
  use: [retry()],
  store: InMemorySessionStore(),
);
```

Common `defineAgent` options:

- `name` (required): action name.
- `description`: shown to an orchestrator that delegates to this agent (see
  [multi-agent](agents-multi-agent.md)).
- `system` / `prompt`: the prompt template (same as `definePrompt`).
- `tools`: tools and interrupt-tools available to the agent.
- `model`: override the default model (e.g. `model: liteModel`).
- `use`: middleware layered on the turn (`retry()`, `filesystem(...)`, etc.).
- `store`: a `SessionStore` for server-side persistence. See
  [sessions](agents-sessions.md).
- `stateSchema`: a `SchemanticType<State>` describing custom session state.
- `maxTurns`: cap the tool-calling loop (e.g. `maxTurns: 30`).

> Schemas use the **schemantic** library (`@Schema()`, `.$schema`, `$`-prefixed
> abstract classes with a generated `.g.dart` part). See
> [references/schemantic.md](schemantic.md).

> **An agent needs a model.** Set `model:` on the agent, or a default `model:`
> on
> the shared `Genkit` instance (as the [Setup](#setup) snippet does). Without
> either, the turn fails with
> `AgentError(INVALID_ARGUMENT): Model must be provided`. The examples here rely
> on the instance default, so if you copy an agent block without it, add a
> `model:`.

## Agents and middleware go hand in hand

Agents and [middleware](genkit_middleware.md) are built for each other: the
`use: [...]` array is where you layer in sophisticated behavior without writing
it yourself — sub-agent delegation, filesystem access, skill loading, tool
approval, retries — each is one line.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/experimental.dart'; // defineAgent, InMemorySessionStore
import 'package:genkit_middleware/filesystem.dart';
import 'package:genkit_middleware/skills.dart';
import 'package:genkit_middleware/tool_approval.dart';

import 'genkit.dart';

final codingAgent = ai.defineAgent(
  name: 'codingAgent',
  system: 'You are an expert AI coding assistant working in a sandboxed '
      'workspace.',
  tools: [runShell, askUser], // your own custom tools/interrupts
  use: [
    // Require user approval (interrupt) before risky tools; reads/run auto-approved.
    // Order matters: keep toolApproval before filesystem.
    toolApproval(
      approved: ['list_files', 'read_file', 'use_skill', 'run_shell', 'ask_user'],
    ),
    // list_files / read_file / write_file / search_and_replace, sandboxed.
    filesystem(rootDirectory: workspaceDir),
    // Load coding conventions on demand via a use_skill tool.
    skills(skillPaths: [skillsDir]),
    // Automatic retry on transient model errors.
    retry(),
  ],
  store: InMemorySessionStore(), // needed for tool approval
  maxTurns: 30,
);
```

Register the corresponding plugins (`FilesystemPlugin()`, `SkillsPlugin()`,
`ToolApprovalPlugin()`) on the `Genkit` instance so the `use: [...]` refs
resolve at runtime (`retry()` is built in). See
[using middleware](genkit_middleware.md).

## Chat with an agent (server-side)

`agent.chat()` opens a conversation. A single `chat` carries state forward
automatically across turns.

```dart
final chat = weatherAgent.chat();

// Non-streaming turn:
final res = await chat.send(text: 'Weather in Tokyo?');
print(res.text);
print(res.snapshotId); // immutable checkpoint id for this turn

// Follow-up turn - history is carried automatically:
final res2 = await chat.send(text: 'What about Paris?');

// Streaming turn:
final turn = chat.sendStream(text: 'And London?');
await for (final chunk in turn.stream) {
  stdout.write(chunk.text);
}
final finalRes = await turn.response;
```

### Per-turn ambient context

`send`, `sendStream`, and `detach` all accept an optional `context` map —
ambient per-turn data (auth, request metadata, etc.) that tools can read via
`ctx.context` (and custom agents via `options.context`).

```dart
final res = await chat.send(
  text: 'What can I do?',
  context: {
    'auth': {'name': 'Ada', 'tier': 'pro'},
  },
);
```

> **In-process only.** The in-process transport honors `context`. The
> **`remoteAgent` (HTTP) transport rejects a non-empty `context` with
> `UnsupportedError`** — remote agents derive context server-side from the HTTP
> request (headers/auth), so don't pass it from the client.

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

`genkit flow:run` only runs **flows**, not agents, so you can't `flow:run` an
agent directly. To exercise an agent from the CLI (e.g. a quick,
self-terminating
check), wrap one turn in a throwaway flow and run that:

```dart
final tryWeatherAgent = ai.defineFlow(
  name: 'tryWeatherAgent',
  fn: (String message, _) async =>
      (await weatherAgent.chat().send(text: message)).text,
);
// genkit flow:run tryWeatherAgent '"Weather in Tokyo?"' -- dart run main.dart
```

## Serve an agent over HTTP

Use `GenkitRouter` (`package:genkit/io.dart`) with `addAgent`
(`package:genkit/experimental_io.dart`). It mounts the turn route plus the
`/getSnapshot` and `/abort` companions the agent supports (based on its store).

```dart
import 'package:genkit/experimental_io.dart';
import 'package:genkit/io.dart';

void main() async {
  final genkit = GenkitRouter()
    ..addAgent(weatherAgent, path: '/api/weatherAgent');
  await genkit.serve(port: 8080); // plain dart:io, no shelf needed
}
```

In a shelf app: `Router()..mount('/api/', genkit.asShelfHandler())` (from
`genkit_shelf`).

For serving multiple agents, CORS/streaming headers for browser clients, and a
full server, see [Deploying agents](agents-deployment.md).

## Consume an agent from a client (`remoteAgent`)

The browser/Dart client lives in `package:genkit/client.dart`. `remoteAgent`
returns a typed HTTP client; `getSnapshotUrl`/`abortUrl` default to
`${url}/getSnapshot` and `${url}/abort`.

`remoteAgent` talks to any Genkit agent endpoint over HTTP, so the **backend is
fully interchangeable** — the agent can be implemented in Dart, JS/TypeScript,
or
Go. The wire protocol is the same; point `url` at whatever server hosts the
agent.

```dart
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent, AgentError

final weather = remoteAgent(url: 'http://localhost:8080/api/weatherAgent');

final chat = weather.chat();
final turn = chat.sendStream(text: 'Weather in Tokyo?');
await for (final chunk in turn.stream) {
  stdout.write(chunk.text);
}
final res = await turn.response;
print('${res.snapshotId} ${chat.snapshotId} ${chat.state}');

// Multi-turn - the client carries state forward automatically:
await chat.send(text: 'What about Paris?');

// Errors surface as AgentError with an HTTP-ish status:
try {
  await remoteAgent(url: '$base/api/nope').chat().send(text: 'hi');
} catch (err) {
  if (err is AgentError) print(err.status);
}
```

## Using from Flutter

There is nothing Flutter-specific about the client: a Flutter app uses the same
`remoteAgent` from `package:genkit/client.dart` as any other Dart program. Two
things matter in a real app — **auth headers** and **lifecycle**.

Pass `headers` to attach per-request auth (e.g. a Firebase/OAuth bearer token).
It's a `FutureOr<Map<String, String>?> Function()`, so it can be async and is
called on every request:

```dart
final agent = remoteAgent(
  url: 'https://your-backend.example.com/api/weatherAgent',
  headers: () async => {
    'Authorization': 'Bearer ${await getIdToken()}',
  },
);
```

Create the agent once (e.g. in `initState`, or a provider/singleton) and
`close()` it when done to release the underlying HTTP client. To own the client
yourself, pass `httpClient:` — then it stays caller-owned and `close()` leaves
it
open.

A minimal streaming chat widget — pump `turn.stream` into the UI with
`setState`, then await `turn.response`:

```dart
import 'package:flutter/material.dart';
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent, AgentApi

class ChatView extends StatefulWidget {
  const ChatView({super.key});
  @override
  State<ChatView> createState() => _ChatViewState();
}

class _ChatViewState extends State<ChatView> {
  late final AgentApi _agent = remoteAgent(
    url: 'http://localhost:8080/api/weatherAgent',
  );
  late final _chat = _agent.chat();
  var _reply = '';

  @override
  void dispose() {
    _agent.close(); // release the HTTP client
    super.dispose();
  }

  Future<void> _send(String text) async {
    setState(() => _reply = '');
    final turn = _chat.sendStream(text: text);
    await for (final chunk in turn.stream) {
      setState(() => _reply += chunk.text); // append tokens live
    }
    await turn.response; // final AgentResponse (state already tracked on _chat)
  }

  @override
  Widget build(BuildContext context) => Column(
    children: [
      Expanded(child: SingleChildScrollView(child: Text(_reply))),
      TextField(onSubmitted: _send),
    ],
  );
}
```

The `_chat` instance carries conversation state forward automatically across
turns (`_chat.state`, `_chat.messages`, `_chat.snapshotId`), exactly as on the
server. [Interrupts](agents-human-in-the-loop.md),
[custom state](agents-state.md), and [artifacts](agents-artifacts.md) all work
the same way from Flutter.

## Client-managed state (no server store)

If the agent has **no `store`**, the server is fully stateless and the session
state blob (messages + custom + artifacts) is owned by the caller. The
`remoteAgent` client tracks it and round-trips it on every turn automatically —
no `SessionStore`, no snapshot ids to manage.

```dart
// Server: no `store` → stateless. Client owns the state blob.
import 'package:genkit/experimental.dart'; // defineAgent

final weatherAgentStateless = ai.defineAgent(
  name: 'weatherAgentStateless',
  system: 'You are a helpful weather assistant. Use the getWeather tool. '
      'Be concise.',
  tools: [getWeather],
  use: [retry()],
);
```

```dart
// Client: reuse one `chat` and the state threads automatically.
import 'package:genkit/client.dart';
import 'package:genkit/experimental_client.dart'; // remoteAgent

final agent = remoteAgent(url: '$base/api/weatherAgentStateless');
final chat = agent.chat();

await chat.send(text: 'Weather in London?');
await chat.send(text: 'Is it sunny in Tokyo?'); // remembers prior turns

// The tracked state is available after each turn:
print(chat.state);
print(chat.messages.length);
```

Use client-managed state when you don't want to run server-side storage. Use a
[session store](agents-sessions.md) when the server should own history, or when
you need branching or background execution.
([Interrupts](agents-human-in-the-loop.md) work either way.)
dotprompt.md 8.4 KB
# Dotprompt (.prompt files) — Genkit Dart

- [What it is](#what-it-is): Lines 15-19
- [Where files live](#where-files-live): Lines 21-34
- [File format](#file-format): Lines 36-81
- [Loading and calling a prompt](#loading-and-calling-a-prompt): Lines 83-157
- [Registering named schemas](#registering-named-schemas): Lines 159-191
- [Variants](#variants): Lines 193-201
- [Partials](#partials): Lines 203-213
- [Tools, tool-loop control, and middleware](#tools-tool-loop-control-and-middleware): Lines 215-266
- [Backing an agent with a .prompt file](#backing-an-agent-with-a-prompt-file): Lines 268-282

---

## What it is

`.prompt` files combine YAML frontmatter (model, config, schemas, tools,
middleware) with a Handlebars template. They keep prompt logic out of Dart code
and make variants and iteration easy.

## Where files live

By default Genkit loads `.prompt` files from `./prompts`. Configure with the
`promptDir` parameter on `Genkit(...)` (set to `null` to disable auto-loading):

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart';

final ai = Genkit(
  plugins: [googleAI()],
  promptDir: './prompts', // default
);
```

## File format

`prompts/greeting.prompt`:
```
---
model: googleai/gemini-flash-latest
input:
  schema:
    name: string
    style: string
---
{{role "system"}}
You are a {{style}} greeter.

{{role "user"}}
Greet {{name}}.
```

Schema fields use Picoschema (the compact form above) or you can reference a
named schema registered with `defineSchema`. A top-level `type` or
`properties` key makes it plain JSON Schema instead.

Picoschema follows the [spec](https://genkit.dev/docs/dotprompt/#picoschema),
same as JS/Go/Python:

```yaml
schema:
  name: string, the person to greet     # description goes after a comma
  nickname?: string                      # optional (and nullable)
  tags(array, relevant tags): string     # array of strings
  steps(array):                          # array of objects
    instruction: string
  address?(object):                      # nested object
    city: string
  status(enum, approval status): [PENDING, APPROVED]
  extra?: any
  (*): string                            # wildcard: additionalProperties
```

The parenthetical is only for a type keyword (`array`, `object`, `enum`) plus an
optional description. `email(the user email): string` is **invalid**; write
`email: string, the user email`. A prompt with an invalid schema logs a warning
when the folder loads and throws `GenkitException` (`invalidArgument`) when it
is rendered; other prompts keep working. A schema name that is still not
registered with `defineSchema` at render time throws too (`failedPrecondition`);
names may be registered after the folder loads.

## Loading and calling a prompt

`ai.prompt(name, {variant})` returns a `Future<Prompt<Input, Output>>`. The
resolved `Prompt` is a **callable object**: invoke it like a function. The
input is a **positional** argument (there is no `input:` named parameter).

```dart
// Non-streaming
final greetingPrompt = await ai.prompt('greeting');
final response = await greetingPrompt({
  'name': 'World',
  'style': 'cheerful',
});
print(response.text);
```

Per-call generation options are **named parameters** after the input, with the
same names as `ai.generate`: `config`, `model`, `messages`, `tools`,
`toolNames`, `toolChoice`, `returnToolRequests`, `maxTurns`, `output`,
`context`, `use`, `cancel` (`render` takes all but `context`/`cancel`). There is
no options object to wrap them in.

```dart
final followUp = await greetingPrompt(
  {'name': 'World', 'style': 'cheerful'},
  config: {'temperature': 0.2}, // merged per key with the prompt's config
  messages: history, // prior turns
  tools: [lookupTool], // appended to the prompt's tools (same for toolNames/use)
  use: [retry()],
);
```

### Typed output

`response.output` is typed by the prompt's `Output`. A `.prompt` file's
`output.schema` has no Dart type, so pass `outputParserSchema` to parse into
one (it is never sent to the model; the file's schema is):

```dart
// Inferred as Prompt<dynamic, Recipe>
final recipePrompt = await ai.prompt(
  'recipe',
  outputParserSchema: Recipe.$schema,
);
final Recipe? recipe = (await recipePrompt({'food': 'pasta'})).output;

// Code-defined with outputSchema: already typed, just name the types.
final joke = await ai.prompt<JokeInput, Joke>('joke');
```

`ai.definePrompt(..., outputSchema: Joke.$schema)` returns a
`Prompt<JokeInput, Joke>` directly. A prompt's `.ref` is a `PromptRef`
(`name`, `metadata`).

### Streaming

```dart
final storyPrompt = await ai.prompt('story');
final stream = storyPrompt.stream({'subject': 'a robot'});
await for (final chunk in stream) {
  print(chunk.text);
}
```

### Render without generating

Returns `GenerateActionOptions` (messages, model, config) without calling the
model — useful for building `ai.generate` calls or evals:

```dart
final greetingPrompt = await ai.prompt('greeting');
final rendered = await greetingPrompt.render({'name': 'World', 'style': 'casual'});
rendered.model;    // resolved model
rendered.messages; // rendered messages
```

## Registering named schemas

Reference a schema by name in `.prompt` frontmatter (`input.schema` /
`output.schema`) after registering it with `defineSchema` (a JSON Schema map):

```dart
ai.defineSchema('Recipe', {
  'type': 'object',
  'properties': {
    'title': {'type': 'string'},
    'steps': {'type': 'array', 'items': {'type': 'string'}},
  },
  'required': ['title', 'steps'],
});
```

Then in `recipe.prompt`:
```
---
model: googleai/gemini-flash-latest
input:
  schema:
    food: string
output:
  schema: Recipe
  format: json
---
Generate a recipe for {{food}}.
```

For code-defined prompts (`ai.definePrompt`) you typically pass a
[schemantic](schemantic.md)-generated schema (e.g. `JokeInput.schema`) as
`inputSchema`.

## Variants

Name the file `<name>.<variant>.prompt` — e.g. `greeting.formal.prompt`. Load
with the `variant` argument:

```dart
final formalPrompt = await ai.prompt('greeting', variant: 'formal');
final response = await formalPrompt({'name': 'Dr. Smith', 'title': 'Professor'});
```

## Partials

Reusable template fragments. Name a partial file `_<name>.prompt` and include it
with `{{> name param=value}}`.

`prompts/_signature.prompt` referenced from another template:
```
Write a short email to {{recipient}} about {{subject}}.

{{> signature}}
```

## Tools, tool-loop control, and middleware

`.prompt` frontmatter can configure tool calling and attach middleware, so an
agent-style prompt is fully described in the file. This is based on
`prompts/tripPlanner.prompt` from the agents testapp (with
`returnToolRequests` shown for completeness):

```
---
model: googleai/gemini-flash-latest
input:
  schema:
    tone: string
tools:
  - getAttractions
  - getFlightInfo
maxTurns: 20              # max tool-call loop iterations
returnToolRequests: false # return tool requests instead of running them
use:
  - name: retry           # bare string also works: `- retry`
    config:
      maxRetries: 4
---
{{role "system"}}
You are a friendly trip planning assistant. Help users plan trips by suggesting
attractions and looking up flight information. Use the available tools to provide
accurate, up-to-date information. Keep your tone {{tone}}.

{{history}}
```

- `tools`: list of registered tool names.
- `toolChoice`, `maxTurns`, `returnToolRequests`: same semantics as the
  equivalent `ai.generate` options.
- `use`: list of middleware refs. Each entry is a bare string (middleware name)
  or a map with `name` and optional `config`. Names resolve against middleware
  registered on the Genkit instance. `retry` (above) is built in; for
  `genkit_middleware` names, register the plugin so the name is available:

```dart
import 'package:genkit_middleware/skills.dart';

final ai = Genkit(
  plugins: [
    googleAI(),
    SkillsPlugin(), // makes `use: [skills]` resolve
  ],
  promptDir: './prompts',
);
```

See [genkit_middleware](genkit_middleware.md) for the middleware package.

## Backing an agent with a .prompt file

`definePromptAgent` wires an agent directly to a `.prompt` file by name. The
frontmatter (`tools`, `maxTurns`, `use`, ...) applies to the agent, and
`promptInput` supplies template variables:

```dart
final tripPlannerAgent = ai.definePromptAgent(
  promptName: 'tripPlanner',            // -> prompts/tripPlanner.prompt
  promptInput: {'tone': 'enthusiastic'}, // fills {{tone}}
  store: InMemorySessionStore(),
);
```

See [Agents](agents.md) for defining and serving agents.
genkit.md 17.0 KB
# Genkit Core Framework

Genkit Dart is an AI SDK for Dart that provides a unified interface for text
generation, structured output, tool calling, and agentic workflows.

- [Initialization](#initialization): Lines 23-34
- [Reliability: retry transient errors](#reliability-retry-transient-errors): Lines 36-56
- [Generate Text](#generate-text): Lines 58-68
- [Stream Responses](#stream-responses): Lines 70-80
- [Embed Text](#embed-text): Lines 82-96
- [Define Tools](#define-tools): Lines 98-144
- [Structured Output](#structured-output): Lines 146-168
- [Errors and finish reasons](#errors-and-finish-reasons): Lines 170-227
- [Cancellation](#cancellation): Lines 229-257
- [Telemetry (instrumentation)](#telemetry-instrumentation): Lines 259-280
- [Define Flows](#define-flows): Lines 282-331
- [Calling remote Flows from a dart client](#calling-remote-flows-from-a-dart-client): Lines 333-375
- [Calling remote Flows from a Javascript client](#calling-remote-flows-from-a-javascript-client): Lines 377-431
- [Data Models](#data-models): Lines 433-573

---

## Initialization

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart'; // Or any other plugin

void main() async {
  // Pass plugins to use into the Genkit constructor. Built-in middleware such
  // as `retry` needs no plugin.
  final ai = Genkit(plugins: [googleAI()]);
}
```

## Reliability: retry transient errors

Model backends routinely return transient errors (Gemini "high demand" surfaces
as `StatusCode.internal`, plus `unavailable` / `resourceExhausted` under load).
In practice `retry()` is close to mandatory for reliable runs. It is a **core**
middleware, always registered (no plugin, no extra package): just add
`use: [retry()]` to a call. By default it retries `unavailable`,
`deadlineExceeded`, `resourceExhausted`, `aborted`, and `internal`, and it works
the same on `generate`, `generateStream`, prompts, and flows. The examples below
add it where it matters.

```dart
retry(
  maxRetries: 5,
  initialDelay: const Duration(milliseconds: 500), // Durations, not ms ints
  maxDelay: const Duration(seconds: 30),
  statuses: [StatusCode.unavailable, StatusCode.resourceExhausted],
  // noRetryModel: true, // skip model retries (on by default)
  // retryTools: true,   // also retry failed tools (off by default)
)
```

## Generate Text

```dart
final response = await ai.generate(
  model: googleAI.gemini('gemini-flash-latest'), // Needs a model reference from a plugin
  prompt: 'Explain quantum computing in simple terms.',
  use: [retry()], // recommended; stream/embed/prompts/flows take the same `use:`
);

print(response.text);
```

## Stream Responses
```dart
final stream = ai.generateStream(
  model: googleAI.gemini('gemini-flash-latest'),
  prompt: 'Write a short story about a robot learning to paint.',
);

await for (final chunk in stream) {
  print(chunk.text);
}
```

## Embed Text

`ai.embed` takes either `document:` (one) or `documents:` (many) and always
returns `List<Embedding>`. There is no `embedMany`.

```dart
final embeddings = await ai.embed(
  documents: [
    DocumentData(content: [TextPart(text: 'Hello world')]),
  ],
  embedder: googleAI.textEmbedding('gemini-embedding-001'),
);

print(embeddings.first.embedding);
```

## Define Tools
Models can use define actions and access external data via custom defined tools.
Requires the `schemantic` library for schema definitions.

```dart
import 'package:schemantic/schemantic.dart';

@Schema()
abstract class $WeatherInput {
  String get location;
}

final weatherTool = ai.defineTool(
  name: 'getWeather',
  description: 'Gets the current weather for a location',
  inputSchema: WeatherInput.$schema,
  fn: (input, _) async {
    // Call your weather API here
    return .response('Weather in ${input.location}: 72°F and sunny');
  },
);

final response = await ai.generate(
  model: googleAI.gemini('gemini-flash-latest'),
  prompt: 'What\'s the weather like in San Francisco?',
  toolNames: ['getWeather'], // Use the tools
);
```

> **Tool functions return a `ToolResult`.** A tool's `fn` returns a
> `ToolResult<Output>`, built with dot-shorthand:
>
> - `return .response(output)` for a normal result.
> - `return .response(output, parts: [...])` to attach media parts alongside the
>   structured output (multipart), e.g. an image the tool produced.
> - `return .interrupt(data)` to pause the generation loop (see
>   [human-in-the-loop](agents-human-in-the-loop.md)).
>
> ```dart
> fn: (input, _) async => .response(
>   {'result': 'captured'},
>   parts: [MediaPart(media: Media(contentType: 'image/png', url: dataUri))],
> );
> ```
>
> Reading a tool's direct result (e.g. via `tool.call`) also yields a
> `ToolResult`; read `(result as ToolResponseResult).output`.

## Structured Output

You can ensure the generative model returns a typed JSON object by providing an
`outputSchema`.

```dart
@Schema()
abstract class $Person {
  String get name;
  int get age;
}

// ... inside main ...

final response = await ai.generate(
  model: googleAI.gemini('gemini-flash-latest'),
  prompt: 'Generate a person named John Doe, age 30',
  outputSchema: Person.$schema, // Force the model to return this schema
);

final person = response.output; // Typed Person object
print('Name: ${person.name}, Age: ${person.age}');
```

## Errors and finish reasons

`generate` and `generateStream` do **not** throw for model errors, throwing
tools, cancellation, or hitting `maxTurns`. They resolve to a response whose
`finishReason` tells you what happened; branch on it instead of wrapping the
call in `try`/`catch`:

```dart
final res = await ai.generate(
  model: googleAI.gemini('gemini-flash-latest'),
  prompt: 'hi',
  toolNames: ['myTool'],
);

switch (res.finishReason) {
  case FinishReason.failed:
    // A model error or a throwing tool. `res.error` is a structured
    // RuntimeError; `res.cause` is the thrown object (in-process only, it
    // does not cross the HTTP/reflection boundary).
    // - Model error: `cause` is what the model call threw. A GenkitException
    //   keeps its status; anything else maps to INTERNAL.
    // - Throwing tool: `cause` is a GenkitException (INTERNAL,
    //   'tool "x" failed: ...') wrapping the tool's error, so the original
    //   is one level down, on its own `.cause`.
    print(res.error?.status);
    final cause = res.cause;
    final original = cause is GenkitException ? cause.cause ?? cause : cause;
    if (original is SocketException) {/* retry later */}
  case FinishReason.aborted:
    // Cancelled, or hit maxTurns.
    print('aborted: ${res.finishMessage}');
  default:
    print(res.text);
}
```

Only a tool returning `.interrupt(...)` is treated as a turn outcome
(`FinishReason.interrupted`) rather than a failure. See
[human-in-the-loop](agents-human-in-the-loop.md).

### Resume from the last-good state

On a `failed` or `aborted` response, `res.messages` holds the **last-good
conversation state**: the request messages plus every tool turn that completed
before the failure/abort (the failing turn's own partial output is dropped).
You do not have to start over. Feed `res.messages` straight back into a fresh
`generate` (with a new, uncancelled token if you were cancelling) to continue
from where it stopped:

```dart
if (res.finishReason == FinishReason.failed ||
    res.finishReason == FinishReason.aborted) {
  final resumed = await ai.generate(
    model: googleAI.gemini('gemini-flash-latest'),
    messages: res.messages, // last-good history: pick up where it stopped
  );
}
```

## Cancellation

`generate`, `generateStream`, and action calls accept a `CancellationToken`. The
caller owns a `CancellationController` and hands its token to the call. These
are
stable core types from `package:genkit/genkit.dart` (and `client.dart`).

```dart
final controller = CancellationController();

final stream = ai.generateStream(
  model: googleAI.gemini('gemini-flash-latest'),
  prompt: 'Write a long, detailed essay about the history of the internet.',
  cancel: controller.token,
);

controller.cancel('user pressed stop');

// Chunks emitted before the cancel still arrive; the stream then closes.
await for (final chunk in stream) {
  stdout.write(chunk.text);
}

final res = await stream.onResult;
if (res.finishReason == FinishReason.aborted) {
  // res.messages holds the last-good history, so you can resume later.
  print('\nCancelled: ${res.finishMessage}');
}
```

## Telemetry (instrumentation)

Telemetry is a pluggable abstraction, not a hardcoded OpenTelemetry dependency.
By default Genkit is not instrumented. In the dev environment (under
`genkit start`) a built-in provider is auto-injected so the Developer UI
receives
traces with no setup, so most users never touch this API. For production, stack
one or more `Instrumentation` providers before creating `Genkit`:

```dart
import 'package:genkit/telemetry.dart';

void main() {
  configureInstrumentation(myInstrumentation());
  final ai = Genkit(plugins: [googleAI()]);
  // ...
}
```

Providers compose as a middleware chain, so multiple can be active at once. A
third-party platform can implement `Instrumentation` without taking an OTel
dependency.

## Define Flows
Wrap your AI logic in flows for better observability, testing, and deployment:

```dart
final jokeFlow = ai.defineFlow(
  name: 'tellJoke',
  inputSchema: .string(),
  outputSchema: .string(),
  fn: (topic, _) async {
    final response = await ai.generate(
      model: googleAI.gemini('gemini-flash-latest'),
      prompt: 'Tell me a joke about $topic',
    );
    return response.text; // Value return
  },
);

final joke = await jokeFlow('programming');
print(joke);
```

> **Top-level `final` flows are lazy.** A flow declared as a top-level `final`
> registers only when the symbol is first evaluated, so an empty `main()`
> registers nothing and `genkit flow:run` fails with `Process exited before
> runtime was ready`. Reference the flow from `main()` (or import a module that
> does) so its `defineFlow` call runs.

### Streaming Flows
Stream data from your flows using `context.sendChunk(...)` and returning the
final value:

```dart
final streamStory = ai.defineFlow(
  name: 'streamStory',
  inputSchema: .string(),
  outputSchema: .string(),
  streamSchema: .string(),
  fn: (topic, context) async {
    final stream = ai.generateStream(
      model: googleAI.gemini('gemini-flash-latest'),
      prompt: 'Write a story about $topic',
    );

    await for (final chunk in stream) {
      context.sendChunk(chunk.text); // Stream the chunks
    }
    return 'Story complete'; // Value return
  },
);
```

## Calling remote Flows from a dart client
The `genkit` package provides `package:genkit/client.dart` representing remote
Genkit actions that can be invoked or streamed using type-safe definitions.

1. Defines a remote action
```dart
import 'package:genkit/client.dart';

final stringAction = defineRemoteAction(
  url: 'http://localhost:3400/my-flow',
  inputSchema: .string(),
  outputSchema: .string(),
);
```

2. Call the Remote Action (Non-streaming)
```dart
final response = await stringAction(input: 'Hello from Dart!');
print('Flow Response: $response');
```

3. Call the Remote Action (Streaming)
Use the `.stream()` method on the action flow, and access `stream.onResult` to
wait on the async return value.
```dart
final streamAction = defineRemoteAction(
  url: 'http://localhost:3400/stream-story',
  inputSchema: .string(),
  outputSchema: .string(),
  streamSchema: .string(),
);

final stream = streamAction.stream(
  input: 'Tell me a short story about a Dart developer.',
);

await for (final chunk in stream) {
  print('Chunk: $chunk'); 
}

final finalResult = await stream.onResult;
print('\nFinal Response: $finalResult');
```

## Calling remote Flows from a Javascript client

Install `genkit` npm package:

```bash
npm install genkit
```

1. Call a remote flow (non-streaming)

```ts
import { runFlow } from 'genkit/beta/client';

async function callHelloFlow() {
  try {
    const result = await runFlow({
      url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL
      input: { name: 'Genkit User' },
    });
    console.log('Non-streaming result:', result.greeting);
  } catch (error) {
    console.error('Error calling helloFlow:', error);
  }
}

callHelloFlow();
```

2. Call a remote flow (streaming)

```ts
import { streamFlow } from 'genkit/beta/client';

async function streamHelloFlow() {
  try {
    const result = streamFlow({
      url: 'http://127.0.0.1:3400/helloFlow', // Replace with your deployed flow's URL
      input: { name: 'Streaming User' },
    });

    // Process the stream chunks as they arrive
    for await (const chunk of result.stream) {
      console.log('Stream chunk:', chunk);
    }

    // Get the final complete response
    const finalOutput = await result.output;
    console.log('Final streaming output:', finalOutput.greeting);
  } catch (error) {
    console.error('Error streaming helloFlow:', error);
  }
}

streamHelloFlow();
```

## Data Models

Genkit uses standard data models for representing prompts (messages & parts) and
responses. These classes are implemented using schemantic library.

```dart
import 'package:genkit/genkit.dart';
import 'package:schemantic/schemantic.dart';

@Schema()
abstract class $MyDataModel {
  // uses Genkit's Message schema (not schemantic's Message)
  List<$Message> get messages;
  List<$Part> get parts;
}

void example() {
  // --- Parts ---
  // A Text part
  final textPart = TextPart(text: 'some text', metadata: {'foo': 'bar'});

  // A Media/Image part
  final mediaPart = MediaPart(
    media: Media(url: 'https://...', contentType: 'image/png'),
    metadata: {'foo': 'bar'},
  );

  // A Tool Request initiated by the model
  final toolRequestPart = ToolRequestPart(
    toolRequest: ToolRequest(
      name: 'get_weather',
      ref: 'abc',
      input: {'location': 'Paris, France'},
    ),
    metadata: {'foo': 'bar'},
  );

  // The resulting data from a Tool execution
  final toolResponsePart = ToolResponsePart(
    toolResponse: ToolResponse(
      name: 'get_weather',
      ref: 'abc',
      output: {'temperature': '20C'},
    ),
    metadata: {'foo': 'bar'},
  );

  // Model reasoning (e.g. for Claude's "thinking" models)
  final reasoningPart = ReasoningPart(
    reasoning: 'thinking...',
    metadata: {'foo': 'bar'},
  );

  // A custom fallback part
  final customPart = CustomPart(
    custom: {'provider': {'specific': 'data'}},
    metadata: {'foo': 'bar'},
  );

  // --- Messages ---
  final systemMessage = Message(
    role: Role.system,
    content: [textPart, mediaPart],
    metadata: {'foo': 'bar'},
  );

  final userMessage = Message(
    role: Role.user,
    content: [textPart, mediaPart], // Can contain media (multimodal)
  );

  final modelMessage = Message(
    role: Role.model,
    // Models can emit text, tool requests, reasoning, or custom parts
    content: [textPart, toolRequestPart, reasoningPart, customPart],
  );

  // --- Ergonomic Data Access (schema_extensions.dart) ---
  // The Genkit SDK provides extensions on `Message` and `Part` to easily access fields
  // without needing to cast them manually.

  // Get concatenated text from all TextParts in a Message
  print(modelMessage.text); 
  
  // Get the first Media object from a Message
  print(modelMessage.media?.url);

  // Iterate over tool requests in a Message
  for (final toolReq in modelMessage.toolRequests) {
    print(toolReq.name);
  }

  // Inspect individual parts
  for (final part in modelMessage.content) {
    if (part.isText) print(part.text);
    if (part.isMedia) print(part.media?.url);
    if (part.isToolRequest) print(part.toolRequest?.name);
    if (part.isToolResponse) print(part.toolResponse?.name);
    if (part.isReasoning) print(part.reasoning);
    if (part.isCustom) print(part.custom);
  }

  // --- Streaming Chunks ---
  // Data emitted by ai.generateStream() calls
  final generateResponseChunk = ModelResponseChunk(
    content: [textPart],
    index: 0, // Index of the message this chunk belongs to
    aggregated: false, 
  );

  // Chunks also have text and media accessors
  print(generateResponseChunk.text);

  // --- Advanced: Schemas ---
  // Use Genkit type schemas directly in Schemantic validations
  final messageSchema = Message.$schema;
  final partSchema = Part.$schema;
  
  final mySchema = SchemanticType.map(
    .string(),
    .list(Message.$schema), // Requires a list of Messages
  );

  // --- Generate Response ---
  // ai.generate() returns a read-only GenerateResult<Output> view over the
  // underlying ModelResponse:
  final response = await ai.generate(...);
  
  print(response.text); // Concatenated text
  print(response.media?.url); // First media part
  print(response.toolRequests); // All tool requests
  print(response.interrupts); // Tool requests that triggered an interrupt
  print(response.messages); // Full history of the conversation, including the request and response
  print(response.output); // Structured typed output (if outputSchema was used)
  print(response.usage?.inputTokens); // int? token counts
  print(response.modelResponse); // the raw ModelResponse (modelRequest too)

  // Stream chunks are GenerateResponseChunk<Output>; `chunk.modelChunk` is the
  // raw ModelResponseChunk (e.g. to forward with ctx.sendChunk in a model).
}
```
genkit_anthropic.md 1.7 KB
# Genkit Anthropic Plugin (`genkit_anthropic`)

The Anthropic plugin for Genkit Dart, used for interacting with the Claude
models.

## Usage

Requires `ANTHROPIC_API_KEY` to be passed to the init block.

```dart
import 'dart:io';
import 'package:genkit/genkit.dart';
import 'package:genkit_anthropic/genkit_anthropic.dart';

void main() async {
  final ai = Genkit(
    plugins: [
      anthropic(apiKey: Platform.environment['ANTHROPIC_API_KEY']!),
    ],
  );

  final response = await ai.generate(
    model: anthropic.model('claude-sonnet-4-5'),
    prompt: 'Tell me a joke about a developer.',
    use: [retry()], // recommended for reliable runs
  );
  
  print(response.text);
}
```

## Claude Thinking Configurations

Provides specific configurations for utilizing Claude 3.7+ "thinking" model
capabilities.

```dart
final response = await ai.generate(
  model: anthropic.model('claude-sonnet-4-5'),
  prompt: 'Solve this 24 game: 2, 3, 10, 10',
  config: AnthropicOptions(
    thinking: AnthropicThinkingConfig(budgetTokens: 2048),
  ),
);

// The thinking content is available in the message parts
print(response.message?.content);
```

> **Multi-turn reasoning is preserved.** Thinking blocks are re-sent on later
> turns of a thinking + tool loop, so reasoning is not dropped on the second
> turn. The signature metadata key is `thoughtSignature` (matching the Gemini
> plugins and Genkit JS), and redacted thinking comes back as
> `CustomPart(custom: {redactedThinking})`. History persisted by older versions
> still replays.

> **Overloads are retried.** HTTP 529 (overloaded) maps to `UNAVAILABLE`, so the
> `retry()` middleware retries it instead of surfacing a non-retriable error.
genkit_chrome.md 0.5 KB
# Genkit Chrome AI Plugin (`genkit_chrome`)

Chrome Built-in AI (Gemini Nano) plugin for Genkit Dart, allowing local offline
execution within a Chrome application.

## Usage

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_chrome/genkit_chrome.dart';

void main() async {
  final ai = Genkit(plugins: [ChromeAIPlugin()]);

  final stream = ai.generateStream(
    model: modelRef('chrome/gemini-nano'),
    prompt: 'Write a story about a robot.',
  );

  await for (final chunk in stream) {
    print(chunk.text);
  }
}
```
genkit_firebase_ai.md 0.6 KB
# Genkit Firebase AI Plugin (`genkit_firebase_ai`)

The Firebase AI plugin for Genkit Dart, used for interacting with Gemini APIs
through Firebase AI Logic.

## Usage

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_firebase_ai/genkit_firebase_ai.dart';

void main() async {
  // Initialize Genkit with the Firebase AI plugin
  final ai = Genkit(plugins: [firebaseAI()]);

  // Generate text
  final response = await ai.generate(
    model: firebaseAI.gemini('gemini-flash-latest'),
    prompt: 'Tell me a joke about a developer.',
  );

  print(response.text);
}
```
genkit_google_genai.md 4.1 KB
# Genkit Google GenAI Plugin (`genkit_google_genai`)

The Google AI plugin provides an interface against the official Google AI Gemini
API.

- [Usage](#usage): Lines 15-35
- [Model refs and Gemma](#model-refs-and-gemma): Lines 37-49
- [Embeddings](#embeddings): Lines 51-62
- [Config types are provider-prefixed](#config-types-are-provider-prefixed): Lines 64-86
- [Image Generation](#image-generation): Lines 88-115
- [Text-to-Speech (TTS)](#text-to-speech-tts): Lines 117-151

---

## Usage

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart';

void main() async {
  // Initialize Genkit with the Google AI plugin.
  final ai = Genkit(plugins: [googleAI()]);

  // Generate text
  final response = await ai.generate(
    model: googleAI.gemini('gemini-flash-latest'),
    prompt: 'Tell me a joke about a developer.',
    // Built-in; transient "high demand" errors are common.
    use: [retry()],
  );

  print(response.text);
}
```

## Model refs and Gemma

`googleAI.gemini('<name>')` builds a ref for any Gemini model. Gemma models the
Gemini API serves have a dedicated `googleAI.gemma('<name>')` alias (it reads
correctly at call sites). Refer to models by name; there are no
`GoogleAiModels` constants.

```dart
final response = await ai.generate(
  model: googleAI.gemma('gemma-4-31b-it'),
  prompt: 'Tell me a joke about a developer.',
);
```

## Embeddings

```dart
final embeddings = await ai.embed(
  embedder: googleAI.textEmbedding('gemini-embedding-001'),
  documents: [
    DocumentData(content: [TextPart(text: 'Hello world')]),
  ],
  // Optional per-request tuning.
  options: GoogleGenAiEmbedderOptions(outputDimensionality: 768),
);
```

## Config types are provider-prefixed

Nested config classes carry a `Gemini` prefix (embedder options use
`GoogleGenAi`). Unprefixed names like `ThinkingConfig` do not exist here.

```dart
config: GeminiOptions(
  // Allowed levels depend on the model ('LOW' is widely supported).
  thinkingConfig: GeminiThinkingConfig(thinkingLevel: 'LOW'),
  safetySettings: [
    GeminiSafetySettings(
      category: 'HARM_CATEGORY_HATE_SPEECH',
      threshold: 'BLOCK_MEDIUM_AND_ABOVE',
    ),
  ],
  googleSearch: GeminiGoogleSearch(),
),
```

Also: `GeminiFunctionCallingConfig`, `GeminiFileSearch`, `GeminiSpeechConfig`,
`GeminiVoiceConfig`, `GeminiPrebuiltVoiceConfig`,
`GeminiMultiSpeakerVoiceConfig`, `GeminiSpeakerVoiceConfig`. The same types are
re-exported by `genkit_vertexai`.

## Image Generation

The plugin also supports image generation models such as
`gemini-3.1-flash-image`.

### Example (Nano Banana)

```dart
// Define an image generation flow
ai.defineFlow(
  name: 'imageGenerator',
  inputSchema: .string(defaultValue: 'A banana riding a bike'),
  outputSchema: Media.$schema,
  fn: (input, context) async {
    final response = await ai.generate(
      model: googleAI.gemini('gemini-3.1-flash-image'),
      prompt: input,
    );
    if (response.media == null) {
      throw Exception('No media generated');
    }
    return response.media!;
  },
);
```

The media (url field) contain base64 encoded data uri. You can decode it and
save it as a file.

## Text-to-Speech (TTS)

You can use text-to-speech models to generate audio from text. The generated
`Media` object will contain base64 encoded PCM audio in its data URI.

```dart
// Define a TTS flow
ai.defineFlow(
  name: 'textToSpeech',
  inputSchema: .string(defaultValue: 'Genkit is an amazing AI framework!'),
  outputSchema: Media.$schema,
  fn: (prompt, _) async {
    final response = await ai.generate(
      model: googleAI.gemini('gemini-3.1-flash-tts-preview'),
      prompt: prompt,
      config: GeminiTtsOptions(
        responseModalities: ['AUDIO'],
        speechConfig: GeminiSpeechConfig(
          voiceConfig: GeminiVoiceConfig(
            prebuiltVoiceConfig: GeminiPrebuiltVoiceConfig(voiceName: 'Puck'),
          ),
        ),
      ),
    );
    
    if (response.media != null) {
      return response.media!;
    }
    throw Exception('No audio generated');
  },
);
```

Google AI also supports multi-speaker TTS by configuring a
`MultiSpeakerVoiceConfig` inside `SpeechConfig`.
genkit_mcp.md 4.5 KB
# Genkit MCP (`genkit_mcp`)

MCP (Model Context Protocol) integration for Genkit Dart, built on `mcp_dart`.
It prefers the stateless MCP 2026-07-28 protocol and falls back to
initialization-based peers automatically.

> **Namespaced tool names are shortened on the wire.** A tool like
> `my-server/weatherTool` is presented to the model as `weatherTool`; the full
> name is preserved in `metadata.originalName` and tool requests still resolve
> correctly.

- [MCP Host (Recommended)](#mcp-host-recommended): Lines 18-74
- [MCP Client (Advanced or Single Server)](#mcp-client-advanced-or-single-server): Lines 76-110
- [MCP Server](#mcp-server): Lines 112-165

---

## MCP Host (Recommended)
Connect to one or more MCP servers and aggregate their capabilities into the
Genkit registry automatically.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_mcp/genkit_mcp.dart';

void main() async {
  final ai = Genkit();

  final host = defineMcpHost(
    ai,
    McpHostOptionsWithCache(
      name: 'my-host',
      mcpServers: {
        'fs': McpServerConfig(
          command: 'npx',
          args: ['-y', '@modelcontextprotocol/server-filesystem', '.'],
        ),
      },
    ),
  );

  // Tools can be discovered and executed dynamically using a wildcard...
  final response = await ai.generate(
    model: googleAI.gemini('gemini-flash-latest'),
    prompt: 'Summarize the contents of README.md',
    toolNames: ['my-host:tool/fs/*'],
  );
  
  // ...or by specifying the exact tool name
  final exactResponse = await ai.generate(
    model: googleAI.gemini('gemini-flash-latest'),
    prompt: 'Read README.md',
    toolNames: ['my-host:tool/fs/read_file'],
  );
}
```

### Connect over Streamable HTTP

Point `McpServerConfig` at a URL instead of a command to connect over Streamable
HTTP. (There is no public `StreamableHttpClientTransport` to construct directly;
custom client transports implement the `McpClientTransport` interface.)

```dart
final host = defineMcpHost(
  ai,
  McpHostOptionsWithCache(
    name: 'my-host',
    mcpServers: {
      'remote': McpServerConfig(url: Uri.parse('https://mcp.example.com/mcp')),
    },
  ),
);
```

## MCP Client (Advanced or Single Server)
Connecting to a single MCP server with a client object is an advanced usecase
for when you need manual control over the client lifecycle. Standalone clients
do not automatically register tools into the registry, so they must be passed
into `generate` or `defineDynamicActionProvider` manually.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_mcp/genkit_mcp.dart';

void main() async {
  final ai = Genkit();

  final client = createMcpClient(
    McpClientOptions(
      name: 'my-client',
      mcpServer: McpServerConfig(
        command: 'npx',
        args: ['-y', '@modelcontextprotocol/server-filesystem', '.'],
      ),
    ),
  );
  
  await client.ready();

  // Retrieve the tools from the connected client
  final tools = await client.getActiveTools(ai);
  
  final response = await ai.generate(
    model: googleAI.gemini('gemini-flash-latest'),
    prompt: 'Read the contents of README.md',
    tools: tools,
  );
}
```

## MCP Server
Expose Genkit actions (tools, prompts, resources) over MCP.

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_mcp/genkit_mcp.dart';

void main() async {
  final ai = Genkit();

  ai.defineTool(
    name: 'add',
    description: 'Add two numbers together',
    inputSchema: .map(.string(), .dynamicSchema()),
    fn: (input, _) async => .response((input['a'] + input['b']).toString()),
  );

  ai.defineResource(
    name: 'my-resource',
    uri: 'my://resource',
    fn: (_, _) async => ResourceOutput(content: [TextPart(text: 'my resource')]),
  );

  // Stdio transport by default
  final server = createMcpServer(ai, McpServerOptions(name: 'my-server'));
  await server.start();
}
```

### Streamable HTTP Transport
```dart
import 'dart:io';

final transport = await StreamableHttpServerTransport.bind(
  address: InternetAddress.loopbackIPv4,
  port: 3000,
);
await server.start(transport);
```

> **DNS-rebinding protection and batch rejection are on by default.** Loopback
> hosts work unconfigured, but a non-loopback deployment must set `allowedHosts`
> (and should set `allowedOrigins`) or requests are rejected. Legacy clients
> that
> send JSON-RPC batches can opt out with `rejectBatchJsonRpcPayloads: false`.
>
> ```dart
> final transport = await StreamableHttpServerTransport.bind(
>   address: InternetAddress.anyIPv4,
>   port: 3000,
>   allowedHosts: ['mcp.example.com'],
>   allowedOrigins: ['https://app.example.com'],
> );
> ```
genkit_middleware.md 5.0 KB
# Genkit Middleware (`genkit_middleware`)

A collection of useful middleware for Genkit Dart to enhance your agent's
capabilities. Register plugins when initializing Genkit:

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_middleware/genkit_middleware.dart';

void main() {
  final ai = Genkit(
    plugins: [
      FilesystemPlugin(),
      SkillsPlugin(),
      ToolApprovalPlugin(),
    ],
  );
}
```

- [Filesystem Middleware](#filesystem-middleware): Lines 28-43
- [Skills Middleware](#skills-middleware): Lines 45-60
- [Tool Approval Middleware](#tool-approval-middleware): Lines 62-105
- [Custom Middleware (core package:genkit)](#custom-middleware-core-packagegenkit): Lines 107-168

---

## Filesystem Middleware
Allows the agent to list, read, write, and search/replace files within a
restricted root directory.

```dart
final response = await ai.generate(
  prompt: 'Check the logs in the current directory.',
  use: [
    filesystem(rootDirectory: '/path/to/secure/workspace'),
  ],
);
```

**Tools Provided:**

- `list_files`, `read_file`, `write_file`, `search_and_replace`

## Skills Middleware
Injects specialized instructions (skills) into the system prompt from `SKILL.md`
files located in specified directories.

```dart
final response = await ai.generate(
  prompt: 'Help me debug this issue.',
  use: [
    skills(skillPaths: ['/path/to/skills']),
  ],
);
```

**Tools Provided:**

- `use_skill`: Retrieve the full content of a skill by name.

## Tool Approval Middleware
Intercepts tool execution for specified tools and requires explicit approval.
Returns `FinishReason.interrupted`.

A tool is allowed through only if it is in the `approved` list or its request's
`resumed` payload carries `{ 'tool-approved': true }`. To approve on resume,
re-issue the paused `ToolRequestPart` with `.restart({'tool-approved': true})` —
the builder nests the payload under `metadata.resumed`, exactly what the
middleware reads.

```dart
final response = await ai.generate(
  prompt: 'Delete the database.',
  use: [
    // Require approval for all tools EXCEPT those below
    toolApproval(approved: ['read_file', 'list_files']),
  ],
);

if (response.finishReason == FinishReason.interrupted) {
  // `response.interrupts` is a List<ToolRequestPart>.
  final interrupt = response.interrupts.first;

  // Ask user for approval
  final isApproved = await askUser();

  if (isApproved) {
    final resumeResponse = await ai.generate(
      messages: response.messages, // Pass history
      toolChoice: ToolChoice.none, // Prevent immediate re-call
      interruptRestart: [
        // `.restart(...)` nests the payload under `metadata.resumed`.
        interrupt.restart({'tool-approved': true}),
      ],
    );
  }
}
```

> **Agent-side resume.** When resuming an agent chat rather than a raw
> `ai.generate` call, the interrupts are `AgentInterrupt`s; pass the same
> `.restart(...)` builder directly to `chat.resume`:
> `chat.resume(restart: [interrupt.restart({'tool-approved': true})])`.
> See [human-in-the-loop](agents-human-in-the-loop.md).

## Custom Middleware (core `package:genkit`)

Extend `GenerateMiddleware` and override the hooks you need (`generate`,
`model`, `tool`). Register it with `ai.defineGenerateMiddleware` and call the
returned definition to build the ref for `use:`. `create` runs once per
`generate` call; `ctx.ai` is a `GenkitAI` the middleware can use for its own
calls (classifiers, guardrails).

```dart
class LoggingMiddleware extends GenerateMiddleware {
  @override
  Future<ModelResponse> model(
    ModelRequest request,
    ActionFnArg<ModelResponseChunk, ModelRequest, void> ctx,
    Future<ModelResponse> Function(
      ModelRequest request,
      ActionFnArg<ModelResponseChunk, ModelRequest, void> ctx,
    ) next,
  ) async {
    print('Calling the model with ${request.messages.length} messages');
    return next(request, ctx);
  }
}

final logging = ai.defineGenerateMiddleware<void>(
  name: 'logging',
  create: (config, ctx) => LoggingMiddleware(),
);

await ai.generate(prompt: 'Hello', use: [logging(), retry(maxRetries: 2)]);
```

For typed config, pass `configSchema: MyOptions.$schema` (a schemantic type)
and call `logging(MyOptions(...))`.

To ship middleware in a plugin, build the definition with the top-level
`generateMiddleware` (it does not register anything) and return it from
`GenkitPlugin.middleware()`. The definition is callable, so a named-parameter
helper is a one-liner:

```dart
final loggerDef = generateMiddleware<LoggerOptions>(
  name: 'logger',
  configSchema: LoggerOptions.$schema,
  create: (config, ctx) => LoggerMiddleware(verbose: config?.verbose ?? false),
);

class LoggerPlugin extends GenkitPlugin {
  @override
  String get name => 'logger';

  @override
  List<GenerateMiddlewareDef> middleware() => [loggerDef];
}

GenerateMiddlewareRef<LoggerOptions> logger({bool? verbose}) =>
    loggerDef(LoggerOptions(verbose: verbose));
```

There is no `defineMiddleware`. Prefer calling the definition over
`middlewareRef(name: ...)`, which is only needed to reference middleware by
name without its definition.
genkit_openai.md 2.8 KB
# Genkit OpenAI Plugin (`genkit_openai`)

OpenAI-compatible API plugin for Genkit Dart. Supports OpenAI models and other
compatible APIs (xAI, DeepSeek, Together AI, Groq, etc.).

## Basic Usage

```dart
import 'dart:io';
import 'package:genkit/genkit.dart';
import 'package:genkit_openai/genkit_openai.dart';

void main() async {
  final ai = Genkit(plugins: [
    openAI(apiKey: Platform.environment['OPENAI_API_KEY']),
  ]);

  final response = await ai.generate(
    model: openAI.model('gpt-5'),
    prompt: 'Tell me a joke.',
    use: [retry()], // recommended for reliable runs
  );
}
```

The plugin does **not** require network access or an API key at startup; a key
is
only needed when you actually call a model.

## Model and embedder refs

The plugin ships a curated per-model catalog (internal, not exported).
Reference models and embedders by name: `openAI.model('<name>')` and
`openAI.embedder('<name>')` accept any id (uncurated ids still resolve via
dated-suffix aliases and generic defaults). There are no `OpenAIModels` /
`OpenAIEmbedders` constants.

```dart
final response = await ai.generate(
  model: openAI.model('gpt-5-mini'),
  prompt: 'Tell me a joke.',
);

final embeddings = await ai.embed(
  embedder: openAI.embedder('text-embedding-3-small'),
  documents: [DocumentData(content: [TextPart(text: 'Hello world')])],
);
```

For a custom model that should behave like a curated one, start from its info:
`CustomModelDefinition(name: 'my-gpt-proxy', info: modelInfoFor('gpt-5.5'))`
(also `xaiModelInfoFor` / `deepSeekModelInfoFor`).

> Capability detection is data-driven (per-model), not name-matching. `-pro`
> tiers are not curated because they are Responses API only and this plugin
> speaks Chat Completions (they still come back from discovery).

## Options

`OpenAIOptions` allows configuring sampling temperature, nucleus sampling, token
generation, seed, etc:
`config: OpenAIOptions(temperature: 0.7, maxTokens: 100)`

> **Schemaless JSON output is advisory.** When you request JSON output without a
> schema, the plugin now sends `json_object` (was strict `json_schema`), so
> schema conformance is best-effort rather than guaranteed. Provide an
> `outputSchema` when you need enforced structure.

## Groq API override

Specify custom `baseUrl` and custom models to integrate with third-party
providers.

```dart
final ai = Genkit(plugins: [
  openAI(
    apiKey: Platform.environment['GROQ_API_KEY'],
    baseUrl: 'https://api.groq.com/openai/v1',
    models: [
      CustomModelDefinition(
        name: 'llama-3.3-70b-versatile',
        info: ModelInfo(
          label: 'Llama 3.3 70B',
          supports: {'multiturn': true, 'tools': true, 'systemRole': true},
        ),
      ),
    ],
  ),
]);

final response = await ai.generate(
  model: openAI.model('llama-3.3-70b-versatile'),
  prompt: 'Hello!',
);
```
genkit_shelf.md 4.7 KB
# Serving over HTTP (`GenkitRouter`, `genkit_shelf`)

HTTP serving lives in core `package:genkit/io.dart` (`GenkitRouter`, plain
`dart:io`, no web framework). `genkit_shelf` is only an adapter that mounts a
`GenkitRouter` into a [shelf](https://pub.dev/packages/shelf) app.

> There is no `startFlowServer` and no `FlowWithContextProvider`. Do not add
> `shelf_cors_headers`; CORS is `CorsOptions`.

- [Standalone server (no shelf)](#standalone-server-no-shelf): Lines 20-55
- [Existing shelf app](#existing-shelf-app): Lines 57-88
- [Own dart:io server](#own-dartio-server): Lines 90-104
- [Auth: contextProvider](#auth-contextprovider): Lines 106-121
- [Agents](#agents): Lines 123-127
- [CORS](#cors): Lines 129-134
- [Older clients](#older-clients): Lines 136-144

---

## Standalone server (no shelf)

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit/io.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart';

void main() async {
  final ai = Genkit(plugins: [googleAI()]);

  final flow = ai.defineFlow(
    name: 'myFlow',
    inputSchema: .string(),
    outputSchema: .string(),
    fn: (String input, _) async => 'Hello $input',
  );

  // Any action can be served, including models (here for remote clients
  // using defineRemoteModel).
  final geminiFlash = googleAI().model('gemini-flash-latest');

  final genkit = GenkitRouter()
    ..addAction(flow) // POST /myFlow (stream with ?stream=true)
    ..addAction(geminiFlash, path: '/v1/gemini');

  await genkit.serve(
    port: 8080, // default: $PORT, then 3400. Host defaults to 0.0.0.0.
    cors: const CorsOptions(allowedOrigins: ['https://myapp.dev']), // default: no CORS
  );
}
```

`addAction` returns `void`; use cascades (`..`), not method chaining.
`serve` logs its address via `package:logging`
(`Logger.root.onRecord.listen(print)`
to see it).

## Existing shelf app

```dart
import 'dart:io';

import 'package:genkit/io.dart';
import 'package:genkit_shelf/genkit_shelf.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';

void main() async {
  // `flow`, `geminiFlash`: as above. `bearerAuth`: see Auth below.
  final genkit = GenkitRouter()
    ..addAction(flow) // served at /api/myFlow below
    ..addAction(geminiFlash, contextProvider: bearerAuth);

  final app = Router()
    ..get('/health', (Request request) => Response.ok('OK'))
    ..mount('/api/', genkit.asShelfHandler(cors: const CorsOptions()));

  await io.serve(
    const Pipeline().addMiddleware(logRequests()).addHandler(app.call),
    InternetAddress.anyIPv4,
    8080,
  );
}
```

Unknown paths get a `404`, so it also works in a shelf `Cascade`. To serve one
action on a route of your choosing:
`router.post('/myFlow', shelfHandler(flow, contextProvider: bearerAuth))`.

## Own `dart:io` server

```dart
final server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
await for (final request in server) {
  if (await genkit.handleHttpRequest(request, basePath: '/api')) continue;
  // ... your own routes; or ioHandler(action) for a single action
  request.response
    ..statusCode = HttpStatus.notFound
    ..close();
}
```

Other frameworks: adapt the framework-neutral `GenkitRouter.handle` /
`actionHandler` (`GenkitHttpRequest` -> `GenkitHttpResponse`), plus `withCors`.

## Auth: `contextProvider`

A `ContextProvider` gets a framework-neutral `RequestData` (lowercased
`headers`, `method`, parsed `input`) and returns the action context
(`ctx.context` in the flow). A thrown `GenkitException` is answered with its
status; anything else with `403`.

```dart
Future<Map<String, dynamic>> bearerAuth(RequestData request) async {
  final user = await checkUserToken(request.headers['authorization']);
  if (user == null) {
    throw GenkitException('Unauthorized', status: StatusCode.unauthenticated); // 401
  }
  return {'userId': user.id};
}
```

## Agents

`addAgent` (from `package:genkit/experimental_io.dart`) mounts the turn route
plus the `/getSnapshot` and `/abort` companions the agent supports. See
[agents-deployment.md](agents-deployment.md).

## CORS

`CorsOptions()` defaults: any origin, `Content-Type` + `Authorization`
request headers, exposes `x-genkit-trace-id` / `x-genkit-span-id`. Browser
streaming clients (JS `remoteAgent`/`streamFlow`) also send
`X-Genkit-Stream-Id`, so add it to `allowedHeaders` for those.

## Older clients

Streamed failures end with a `data: {"error": ...}` frame. Dart/Flutter clients
on `package:genkit` 0.17 or earlier only understand the older frame; while such
clients are in the field, use `GenkitRouter(sendLegacyErrorFrame: true)` (also
on `shelfHandler`/`ioHandler`).

Consume served endpoints with `defineRemoteAction` / `defineRemoteModel`
(`package:genkit/client.dart`), `remoteAgent`, or the JS client.
genkit_vertexai.md 2.6 KB
# Genkit Vertex AI Plugin (`genkit_vertexai`)

Gemini models and embedders through Vertex AI (Gemini Enterprise API), with
Google Cloud authentication instead of an API key. Same model surface and option
types as [genkit_google_genai](genkit_google_genai.md), which it re-exports
(`GeminiOptions`, `GeminiThinkingConfig`, `GoogleGenAiEmbedderOptions`, ...).

```bash
dart pub add genkit genkit_vertexai
```

## Setup

```dart
import 'package:genkit/genkit.dart';
import 'package:genkit_vertexai/genkit_vertexai.dart';

void main() async {
  final ai = Genkit(
    plugins: [
      vertexAI(
        projectId: 'my-project', // default: $GOOGLE_CLOUD_PROJECT / $GCLOUD_PROJECT
        location: 'us-central1', // default: 'global'
      ),
    ],
  );

  final response = await ai.generate(
    model: vertexAI.gemini('gemini-3.6-flash'),
    prompt: 'Tell me a joke about a developer.',
    use: [retry()],
  );
  print(response.text);
}
```

- **Auth:** Application Default Credentials. Locally run
  `gcloud auth application-default login`; on Cloud Run and other Google Cloud
  runtimes it is automatic. The account needs `roles/aiplatform.user`.
- **No API key.** For API-key access use `genkit_google_genai` (`googleAI()`).
- `authClient:` takes your own authenticated `http.Client`; the plugin never
  closes it.

## Model IDs

Use versioned Vertex model IDs (`gemini-3.6-flash`, `gemini-3.1-pro-preview`,
`gemini-3.5-flash-lite`, ...). The Gemini API's `-latest` aliases
(`gemini-flash-latest`, `gemini-pro-latest`) **do not exist on Vertex** and
fail at request time. Vertex TTS models use their own IDs (e.g.
`gemini-2.5-flash-tts`), not the Gemini API TTS names.

```dart
final response = await ai.generate(
  model: vertexAI.gemini('gemini-3.6-flash'),
  prompt: 'What are the top tech news stories this week?',
  config: GeminiOptions(
    thinkingConfig: GeminiThinkingConfig(thinkingLevel: 'LOW'),
    googleSearch: GeminiGoogleSearch(),
  ),
);
```

## Embeddings

`text-embedding-*`, `gemini-embedding-*` and `multimodalembedding` all go
through `vertexAI.textEmbedding`:

```dart
final embeddings = await ai.embed(
  embedder: vertexAI.textEmbedding('gemini-embedding-001'),
  documents: [DocumentData(content: [TextPart(text: 'Hello world')])],
  options: GoogleGenAiEmbedderOptions(
    outputDimensionality: 256,
    taskType: 'RETRIEVAL_DOCUMENT',
  ),
);
```

`multimodalembedding` embeds text, images and video (`MediaPart` with a `data:`,
`gs://` or `https` URL plus `contentType`). One document can yield several
embeddings (one per modality / video segment); map them back with
`embedding.metadata?['documentIndex']`, `['modality']`, `['partIndex']`,
`['segmentIndex']`.
schemantic.md 5.2 KB
# Schemantic

Schemantic is a general-purpose Dart library used for defining strongly typed
data classes that automatically bind to reusable runtime JSON schemas. It is
standard for the `genkit-dart` framework but works independently as well.

- [Core Concepts](#core-concepts): Lines 18-27
- [Installation](#installation): Lines 29-49
- [Basic Usage](#basic-usage): Lines 51-107
- [Primitive Schemas](#primitive-schemas): Lines 109-122
- [Union Types (AnyOf)](#union-types-anyof): Lines 124-142
- [Field Annotations](#field-annotations): Lines 144-165
- [Recursive Schemas](#recursive-schemas): Lines 167-180
- [Non-nullable getters throw on partial data](#non-nullable-getters-throw-on-partial-data): Lines 182-190

---

## Core Concepts

Always use `schemantic` when strongly typed JSON parsing or programmatic schema
validation is required.

- Annotate your abstract classes with `@Schema()`.
- Use the `$` prefix for abstract schema class names (e.g.,
  `abstract class $User`).
- Always run `dart run build_runner build` to generate the `.g.dart` schema
  files.

## Installation

Add dependencies. The code generator lives in a **separate**
`schemantic_builder` package, so you must add it as a dev dependency too:

```bash
dart pub add schemantic
dart pub add dev:schemantic_builder
dart pub add dev:build_runner
```

> **Gotcha:** if `schemantic_builder` is missing, `dart run build_runner build`
> completes "successfully" but reports `wrote 0 outputs` and generates no
> `.g.dart` files, with no error explaining why. If you see zero outputs,
> confirm
> `schemantic_builder` is in your `dev_dependencies`.

> **Note:** plain `dart run build_runner build` is correct. Recent
> `build_runner`
> versions removed `--delete-conflicting-outputs` (it is now ignored and warns
> "These options have been removed and were ignored"), so do not pass it.

## Basic Usage

1. **Defining a schema:**

```dart
import 'package:schemantic/schemantic.dart';

part 'my_file.g.dart'; // Must match the filename

@Schema()
abstract class $MyObj {
  String get name;
  $MySubObj get subObj;
}

@Schema()
abstract class $MySubObj {
  String get foo;
}
```

2. **Using the Generated Class:**

The builder creates a concrete class `MyObj` (no `$`) with a factory constructor
(`MyObj.fromJson`) and a regular constructor.

```dart
// Creating an instance
final obj = MyObj(name: 'test', subObj: MySubObj(foo: 'bar'));

// Serializing to JSON
print(obj.toJson()); 

// Parsing from JSON
final parsed = MyObj.fromJson({'name': 'test', 'subObj': {'foo': 'bar'}});
```

3. **Accessing Schemas at Runtime:**

The generated data classes have a static `$schema` field (of type
`SchemanticType<T>`) which can be used to pass the definition into functions or
to extract the raw JSON schema.

```dart
// The JSON Schema, as a plain map
final Map<String, Object?> jsonSchema = MyObj.$schema.jsonSchema();
print(jsonEncode(jsonSchema)); // import 'dart:convert';

// Validate arbitrary JSON at runtime (empty list = valid)
final errors = await MyObj.$schema.validate({'invalid': 'data'});
for (final e in errors) {
  print(e);
}

// Parse JSON into the typed class
final MyObj obj = MyObj.$schema.parse({'name': 'x', 'subObj': {'foo': 'y'}});
```

## Primitive Schemas

When a full data class is not required, Schemantic provides functions to create
schemas dynamically.

```dart
final ageSchema = SchemanticType.integer(description: 'Age in years', minimum: 0);
final nameSchema = SchemanticType.string(minLength: 2);
final nothingSchema = SchemanticType.voidSchema();
final anySchema = SchemanticType.dynamicSchema();

final userSchema = SchemanticType.map(.string(), .integer()); // Map<String, int>
final tagsSchema = SchemanticType.list(.string()); // List<String>
```

## Union Types (AnyOf)

To allow a field to accept multiple types, use `@AnyOf`.

```dart
@Schema()
abstract class $Poly {
  @AnyOf([int, String, $MyObj])
  Object? get id;
}
```

Schemantic generates a specific helper class (e.g., `PolyId`) to handle the
values:

```dart
final poly1 = Poly(id: PolyId.int(123));
final poly2 = Poly(id: PolyId.string('abc'));
```

## Field Annotations

You can use specialized annotations for more validation boundaries:

```dart
@Schema()
abstract class $User {
  @IntegerField(
    name: 'years_old', // Change JSON key
    description: 'Age of the user',
    minimum: 0,
    defaultValue: 18,
  )
  int? get age;

  @StringField(
    minLength: 2,
    enumValues: ['user', 'admin'], 
  )
  String get role;
}
```

## Recursive Schemas

For recursive structures (like trees), must use `useRefs: true` inside the
generated jsonSchema property. You define it normally:

```dart
@Schema()
abstract class $Node {
  String get id;
  List<$Node>? get children;
}
```
*Note*: `Node.$schema.jsonSchema(useRefs: true)` generates schemas with JSON
Schema `$ref`.

## Non-nullable getters throw on partial data

Generated getters for required fields are non-nullable casts (e.g.
`_json['estimatedCostUsd'] as num`). A JSON blob that is missing such a field
throws on access (`Null is not a subtype of num`) rather than returning a
default — this commonly bites computed/optional values that were never written,
e.g. when reloading a partially populated state blob. Make computed or optional
fields nullable (`num?`) or give them a `defaultValue` so partial data can still
be read.

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