1
---
2
name: developing-genkit-dart
3
description: >-
4
Provides guidance on developing AI-powered applications using the Genkit Dart
5
SDK. Use when the user asks to build AI agents in Dart, use Genkit flows, or
6
integrate LLMs into Dart/Flutter applications. Don't use for Genkit in
7
JavaScript/TypeScript, Go, or Python.
8
metadata:
9
version: "1.0.0"
10
category: AiAndMachineLearning
11
---
12
13
# Genkit Dart
14
15
Genkit Dart is an AI SDK for Dart that provides a unified interface for code
16
generation, structured outputs, tools, flows, and AI agents.
17
18
## Core Features and Usage
19
If you need help with initializing Genkit (`Genkit()`), Generation
20
(`ai.generate`), Tooling (`ai.defineTool`), Flows (`ai.defineFlow`), Embeddings
21
(`ai.embed`), streaming, or calling remote flow endpoints, please load the core
22
framework reference:
23
[references/genkit.md](references/genkit.md)
24
25
## 1.0 vs pre-1.0 APIs
26
27
This skill targets Genkit Dart **1.0** (`genkit: ^1.0.0`). Older code and
28
training data use pre-1.0 names that no longer compile; the common ones:
29
30
- HTTP: `startFlowServer` / per-route `shelfHandler` / `shelf_cors_headers` are
31
now `GenkitRouter` + `serve()` or `asShelfHandler()`, with `CorsOptions`;
32
context providers take `RequestData`
33
([genkit_shelf.md](references/genkit_shelf.md)).
34
- `StatusCodes.UNAUTHENTICATED` is `StatusCode.unauthenticated` (lowerCamelCase,
35
same for `EvalStatus.pass`, `ToolChoice.required`).
36
- No `RetryPlugin`; `retry()` is built in and takes `Duration`s
37
(`initialDelay`, `maxDelay`, also `cacheTtl` elsewhere).
38
- Renames: `GenerateResponseHelper` -> `GenerateResult` (`modelResponse`,
39
`chunk.modelChunk`), `ExecutablePrompt` -> `Prompt<Input, Output>`,
40
`embedMany` -> `embed`, `ToolFnArgs` -> `ToolFnArg`, `toolOutputSchema` ->
41
`outputSchema`, `underlyingException` -> `cause`, `modelInfo:` -> `info:`,
42
`RemoteAction.dispose()` -> `close()`,
43
`prompt(input, PromptGenerateOptions(config: ...))`
44
-> `prompt(input, config: ...)` (named options, like `generate`),
45
`defineMiddleware` ->
46
`ai.defineGenerateMiddleware` (app) / `generateMiddleware` (plugins).
47
- Provider config types are prefixed: `GeminiThinkingConfig`,
48
`GeminiSafetySettings`, `GeminiGoogleSearch`, `GeminiSpeechConfig`,
49
`GoogleGenAiEmbedderOptions`, `AnthropicThinkingConfig`.
50
- Removed: `ToolInterruptException` / `ctx.interrupt()` (return
51
`.interrupt(...)`),
52
`GoogleAiModels` / `OpenAIModels` constants (use `googleAI.gemini('...')`,
53
`openAI.model('...')`). Simulated constrained output is opt-in via
54
`simulateConstrainedGeneration()`.
55
- `.prompt` Picoschema is spec-compliant: `name: type, description`, never
56
`name(description): type` ([dotprompt.md](references/dotprompt.md)).
57
58
## Prompts (Dotprompt)
59
60
`.prompt` files keep prompt content out of Dart code with YAML frontmatter plus
61
a
62
Handlebars template. See [references/dotprompt.md](references/dotprompt.md):
63
`promptDir`, `ai.prompt()` (call/stream/render), variants, partials, named
64
schemas via `defineSchema`, and the
65
`tools`/`maxTurns`/`returnToolRequests`/`use`
66
(middleware) frontmatter fields. A `.prompt` file can also back an agent
67
directly
68
via `definePromptAgent`.
69
70
## Agents
71
72
Genkit Dart has an **agent** API for persistent, multi-turn conversations
73
(sessions, snapshots, interrupts, branching, background execution, custom state,
74
artifacts, and multi-agent delegation). The agent/session/snapshot APIs are
75
**experimental** and live behind opt-in imports: server APIs come from
76
`package:genkit/experimental.dart` (alongside `package:genkit/genkit.dart`), the
77
browser/HTTP client from `package:genkit/experimental_client.dart` (alongside
78
`package:genkit/client.dart`), and `dart:io` extras like `FileSessionStore` from
79
`package:genkit/experimental_io.dart`. These entry points are `@experimental`,
80
so
81
importing them raises an `experimental_member_use` analyzer warning you can
82
silence in `analysis_options.yaml`. The `remoteAgent` client works from any Dart
83
app, including **Flutter**, and the backend is fully interchangeable — it can
84
talk
85
to a Genkit agent implemented in Dart, JS/TypeScript, or Go over the same HTTP
86
protocol. A few Dart specifics: interrupts are `ai.defineInterrupt(...)` or
87
tools that return `.interrupt(...)` (there is no `ctx.interrupt()`), sub-agent
88
delegation uses
89
the `agents()` middleware from `package:genkit_middleware`, and there is no
90
`artifacts()` middleware yet (define artifact tools directly).
91
92
For more details see:
93
94
- [Agents](references/agents.md): defining/serving an agent and client-managed
95
state (start here).
96
- [Sessions & persistence](references/agents-sessions.md): session stores
97
(`InMemorySessionStore`/`FileSessionStore`/`FirestoreSessionStore`).
98
- [Human-in-the-loop / interrupts](references/agents-human-in-the-loop.md):
99
pausing for approval/input via `.interrupt(...)` and resuming.
100
- [Branching](references/agents-branching.md): forking a conversation from a
101
snapshot.
102
- [Background agents](references/agents-background.md): detaching long-running
103
turns and polling.
104
- [Working with state](references/agents-state.md): typed custom session
105
state, auto-synced to the client.
106
- [Artifacts](references/agents-artifacts.md): producing and reading named
107
deliverables.
108
- [Multi-agent orchestration](references/agents-multi-agent.md): delegating to
109
sub-agents with the `agents()` middleware.
110
- [Advanced custom agents](references/agents-custom.md): `defineCustomAgent`
111
for full turn control.
112
- [Deploying agents](references/agents-deployment.md): serving agents over
113
HTTP with `GenkitRouter.addAgent` (multiple agents, shelf, CORS).
114
115
## Generative UI (A2UI)
116
117
Genkit Dart has an **A2UI** (Agent-to-UI) plugin (`genkit_a2ui`)
118
that lets an agent stream interactive UI **surfaces** (cards, lists, forms,
119
buttons), not just prose. The whole server-side integration is the `a2ui()`
120
model
121
middleware in an agent's (or `ai.generate`'s) `use` list; the Flutter client
122
renders surfaces with the [`genui`](https://pub.dev/packages/genui) package plus
123
the helpers in `package:genkit_a2ui/client.dart`. Dart specific: you must
124
register `A2uiPlugin()` in `Genkit(plugins: [...])` (unlike JS, middleware is
125
resolved by name from the registry).
126
127
- [A2UI](references/a2ui.md): server middleware, options, Flutter/genui client
128
rendering, user actions/forms, custom catalogs, and the security/trust
129
boundary.
130
131
## Genkit CLI (recommended)
132
133
`genkit start` unintrusively wraps any Dart program that uses the Genkit
134
library, running it unchanged while capturing traces from every Genkit action so
135
you can prove tools were actually called and inspect model I/O from the
136
terminal, even for headless checks. It forwards stdio, so interactive CLI tools
137
that rely on stdin/stdout work without issues. Running the app directly
138
(`dart run`) skips trace capture, so you're debugging blind. Check install with
139
`genkit --version`.
140
141
**Installation:**
142
```bash
143
curl -sL cli.genkit.dev | bash # Native CLI
144
# OR
145
npm install -g genkit-cli # Via npm
146
# OR run commands directly with npx without a global install (prefix every genkit command):
147
# npx genkit-cli start -- dart run main.dart
148
```
149
150
**Primary pattern (default):** prefix `genkit start --` to your normal run
151
command. This collects telemetry from any Genkit code your program runs, whether
152
triggered from the dev UI, your own web server/web UI, or a plain script. Starts
153
the Developer UI (usually http://localhost:4000) for running flows, model and
154
agent playground, and browsing traces:
155
156
```bash
157
genkit start -- dart run main.dart
158
genkit start --noui -- dart run main.dart # same, without the Dev UI (still a persistent server)
159
```
160
`genkit start` runs until you stop it with Ctrl+C. That is expected and correct
161
for the common cases: a server your web/mobile app calls, or an interactive CLI
162
you exit yourself. `--noui` only drops the Dev UI; it is **not** a one-shot
163
command and will not exit on its own. Do **not** use `genkit start` as a
164
blocking step in automated/non-interactive contexts; use `flow:run` (below) for
165
that.
166
167
**Non-interactive use (agents/CI):** add the global `--non-interactive` flag
168
before `--` so the CLI uses defaults and never blocks on a prompt (e.g. the
169
first-run analytics notice):
170
`genkit start --non-interactive -- dart run main.dart` (works with `flow:run`
171
too).
172
173
**Run a flow (`flow:run`):** invoke a specific flow by name from the CLI. Append
174
your run command after `--` to spin up the runtime just for this run (the
175
command runs as-is to register your flows):
176
```bash
177
genkit flow:run myFlow '{"data": "input"}' -- dart run main.dart
178
```
179
This is **self-terminating**: it runs the flow once, prints a `Trace ID`, then
180
exits, so it's the right choice for a quick, non-interactive check (unlike
181
`genkit start`). Note: `flow:run` runs **flows** (`ai.defineFlow`), not agents;
182
you can't `flow:run` an agent (`ai.defineAgent`) directly. To exercise an agent
183
from the CLI, wrap one turn in a throwaway flow and run that (see
184
[Agents](references/agents.md)). Traces for this run can be inspected using the
185
trace commands below.
186
187
**Gotcha: top-level `final` declarations are lazy.** Flows and agents defined as
188
top-level `final` register with Genkit only when the symbol is first evaluated.
189
An empty `main()` registers nothing, so `flow:run` fails with
190
`Process exited before runtime was ready`. Reference the flow/agent symbols from
191
`main()` (or import a module that does) so their `define*` calls actually run.
192
193
**Debugging with traces:** the fastest way to see prompts, model inputs/outputs,
194
tool calls, latencies, and errors. Inspect from the terminal after any run under
195
`genkit start`:
196
```bash
197
genkit trace:list # find recent trace IDs
198
genkit trace:get <traceId> # full trace details (inputs, outputs, tool calls, errors)
199
genkit trace:get <traceId> --format json # machine-readable JSON, safe to pipe into jq or other parsers
200
```
201
202
For machine-readable output, pass `--format json` to get clean JSON you can pipe
203
into `jq` or other parsers. The **default** output is human-oriented (banner/log
204
lines, possible truncation on large traces), so don't pipe that form directly;
205
use `--format json`, grep, or the Dev UI trace viewer.
206
207
**Documentation:**
208
```bash
209
genkit docs:search "streaming" dart
210
genkit docs:list dart
211
genkit docs:read dart/flows.md
212
```
213
214
## Plugin Ecosystem
215
Genkit relies on a large suite of plugins to perform generative AI actions,
216
interface with external LLMs, or host web servers.
217
218
When asked to use any given plugin, always verify usage by referring to its
219
corresponding reference below. You should load the reference when you need to
220
know the specific initialization arguments, tools, models, and usage patterns
221
for the plugin:
222
223
| Plugin Name | Reference Link | Description |
224
| ---- | ---- | ---- |
225
| `genkit_google_genai` | [references/genkit_google_genai.md](references/genkit_google_genai.md) | Load for Google Gemini plugin interface usage. |
226
| `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). |
227
| `genkit_anthropic` | [references/genkit_anthropic.md](references/genkit_anthropic.md) | Load for Anthropic plugin interface for Claude models. |
228
| `genkit_openai` | [references/genkit_openai.md](references/genkit_openai.md) | Load for OpenAI plugin interface for GPT models, Groq, and custom compatible endpoints. |
229
| `genkit_middleware` | [references/genkit_middleware.md](references/genkit_middleware.md) | Load for Tooling for specific agentic behavior: `filesystem`, `skills`, and `toolApproval` interrupts. |
230
| `genkit_mcp` | [references/genkit_mcp.md](references/genkit_mcp.md) | Load for Model Context Protocol integration (Server, Host, and Client capabilities). |
231
| `genkit_chrome` | [references/genkit_chrome.md](references/genkit_chrome.md) | Load for Running Gemini Nano locally inside the Chrome browser using the Prompt API. |
232
| `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. |
233
| `genkit_firebase_ai` | [references/genkit_firebase_ai.md](references/genkit_firebase_ai.md) | Load for Firebase AI plugin interface (Gemini API via Vertex AI). |
234
| `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`. |
235
236
## External Dependencies
237
Whenever you define schemas mapping inside of Tools, Flows, and Prompts, you
238
must use the [schemantic](https://pub.dev/packages/schemantic) library.
239
To learn how to use schemantic, ensure you read
240
[references/schemantic.md](references/schemantic.md) for how to implement type
241
safe generated Dart code. This is particularly relevant when you encounter
242
symbols like `@Schema()`, `SchemanticType`, or classes with the `$` prefix.
243
Genkit Dart uses schemantic for all of its data models so it's a CRITICAL skill
244
to understand for using Genkit Dart.
245
246
## Best Practices
247
248
- **Agent or flow?** If the task is conversational, multi-turn, or described as
249
"an agent", "assistant", or "chatbot", build it with `ai.defineAgent` (see
250
[Agents](references/agents.md)) rather than hand-rolling a `generate` + tools
251
loop inside a flow. Reach for a plain flow only for single-shot, stateless
252
generation.
253
- Always check that code cleanly compiles using `dart analyze` before generating
254
the final response.
255
- Always use the Genkit CLI for local development and debugging.
256
- Verify with traces, not a blind run. Running the app directly (`dart run`)
257
does not capture dev traces. See the [Genkit CLI](#genkit-cli-recommended)
258
section for how to run your app and capture traces.
259