Installation
Install as Agent Plugin
Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install developing-genkit-js@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin developing-genkit-js v1.0.0 follows the Agent Plugins spec.
Install with the gh extension
gh skills-hub install developing-genkit-js Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/developing-genkit-js/ Extract the ZIP to .github/skills/ in your repo. The folder name must match developing-genkit-js for Copilot to auto-discover it.
Skill Files (21)
SKILL.md 13.1 KB
---
name: developing-genkit-js
description: >-
Provides guidance on developing AI-powered applications using Genkit in
Node.js/TypeScript. Use when the user asks about Genkit, AI agents, flows, or
tools in JavaScript/TypeScript, or when encountering Genkit errors, validation
issues, type errors, or API problems. Don't use for Genkit in Python, Go, or
Dart.
metadata:
version: "1.0.0"
category: AiAndMachineLearning
---
# Genkit JS
## Prerequisites
Ensure the `genkit` CLI is available.
- Run `genkit --version` to verify. Minimum CLI version needed: **1.29.0**
- If not found or if an older version (1.x < 1.29.0) is present,
install/upgrade it: `npm install -g genkit-cli@^1.29.0`.
**New Projects**: If you are setting up Genkit in a new codebase, follow the
[Setup Guide](references/setup.md).
## Hello World
```ts
import { z, genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
// Initialize Genkit with the Google AI plugin
const ai = genkit({
plugins: [googleAI()],
});
export const myFlow = ai.defineFlow({
name: 'myFlow',
inputSchema: z.string().default('AI'),
outputSchema: z.string(),
}, async (subject) => {
const response = await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: `Tell me a joke about ${subject}`,
});
return response.text;
});
```
## Prompts (Dotprompt)
`.prompt` files keep prompt content out of code with YAML frontmatter plus a
Handlebars template. See [Dotprompt](references/dotprompt.md): `promptDir`,
`ai.prompt()` (call/stream/render), variants, partials, named schemas via
`ai.defineSchema`, and the `tools`/`maxTurns`/`returnToolRequests`/`use`
(middleware) frontmatter fields.
## Agents (Beta)
Genkit has a preview **agent** API for persistent, multi-turn conversations
(sessions, snapshots, interrupts, branching, background execution). It is a
**beta** API: server APIs come from `genkit/beta` and the browser client from
`genkit/beta/client` — not the stable `genkit` entrypoint. **Requires `genkit`
>= 1.39.0.**
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
(`InMemory`/`File`/`Firestore`).
- [Human-in-the-loop / interrupts](references/agents-human-in-the-loop.md):
pausing for approval/input and resuming.
- [Branching](references/agents-branching.md): forking a conversation from a
snapshot.
- [Background agents](references/agents-background.md): detaching long-running
turns, waiting, and resuming failed or aborted runs.
- [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, including background delegation and `continue_task`.
- [Advanced custom agents](references/agents-custom.md): `defineCustomAgent`
for full turn control.
- [Deploying agents](references/agents-deployment.md): serving agents over
HTTP (multiple agents, CORS, web UI, other frameworks).
## Generative UI (A2UI)
Genkit has an **A2UI** (Agent-to-UI) plugin (`@genkit-ai/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` array; the browser renders
surfaces with an `@a2ui/*` renderer plus the helpers in
`@genkit-ai/a2ui/client`.
It builds on the beta agent client (`genkit/beta` + `genkit/beta/client`).
- [A2UI](references/a2ui.md): server middleware, options, client rendering,
user actions/forms, custom catalogs, and the security/trust boundary.
## Middleware
Middleware wraps generation (retries, fallback, extra tools, request/response
transforms) and attaches via the `use: [...]` array on `ai.generate`, prompts,
and agents.
- [Using middleware](references/middleware.md): the `use` array and the
`@genkit-ai/middleware` package (`retry`, `fallback`, `artifacts`, `agents`,
`filesystem`, `skills`, `toolApproval`, `contextCompression`) plus built-in
core middleware.
- [Building custom middleware](references/middleware-custom.md): writing your
own with `generateMiddleware` and registering it via `.plugin()`.
## Observability
Traces show up in the Dev UI under `genkit start` with no setup. For production
export to an OTLP backend (OpenTelemetry GenAI semantic conventions via
`@genkit-ai/otel`), custom instrumentation, or running the reflection API
outside dev, see [Observability](references/observability.md).
## Critical: Do Not Trust Internal Knowledge
Genkit recently went through a major breaking API change. Your knowledge is
outdated. You MUST lookup docs. Recommended:
```sh
genkit docs:read js/get-started.md
genkit docs:read js/flows.md
```
See [Common Errors](references/common-errors.md) for a list of deprecated APIs
(e.g., `configureGenkit`, `response.text()`, `defineFlow` import) and their v1.x
replacements.
**ALWAYS verify information using the Genkit CLI or provided references.**
## Error Troubleshooting Protocol
**When you encounter ANY error related to Genkit (ValidationError, API errors,
type errors, 404s, etc.):**
1. **MANDATORY FIRST STEP**: Read [Common Errors](references/common-errors.md)
2. Identify if the error matches a known pattern
3. Apply the documented solution
4. Only if not found in common-errors.md, then consult other sources (e.g.
`genkit docs:search`)
**DO NOT:**
- Attempt fixes based on assumptions or internal knowledge
- Skip reading common-errors.md "because you think you know the fix"
- Rely on patterns from pre-1.0 Genkit
**This protocol is non-negotiable for error handling.**
## Development Workflow
1. **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.
2. **Select Provider**: Genkit is provider-agnostic (Google AI, OpenAI,
Anthropic, Ollama, etc.).
- If the user does not specify a provider, default to **Google AI**.
- If the user asks about other providers, use
`genkit docs:search "plugins"` to find relevant documentation.
3. **Detect Framework**: Check `package.json` to identify the runtime (Next.js,
Firebase, Express).
- Look for `@genkit-ai/next`, `@genkit-ai/firebase`, or
`@genkit-ai/google-cloud`.
- Adapt implementation to the specific framework's patterns.
4. **Follow Best Practices**:
- See [Best Practices](references/best-practices.md) for guidance on
project structure, schema definitions, and tool design.
- **Be Minimal**: Only specify options that differ from defaults. When
unsure, check docs/source.
5. **Ensure Correctness**:
- Run type checks (e.g., `npx tsc --noEmit`) after making changes.
- If type checks fail, consult
[Common Errors](references/common-errors.md) before searching source
code.
- Verify with traces, not a blind run. Running the app directly
(`node`/`tsx`/`npm start`) does **not** capture dev traces. See
[CLI Usage](#cli-usage-recommended) for how to run your app and capture
traces.
6. **Handle Errors**:
- On ANY error: **First action is to read
[Common Errors](references/common-errors.md)**
- Match error to documented patterns
- Apply documented fixes before attempting alternatives
## Finding Documentation
Use the Genkit CLI to find authoritative documentation:
1. **Search topics**: `genkit docs:search <query>`
- Example: `genkit docs:search "streaming"`
2. **List all docs**: `genkit docs:list`
3. **Read a guide**: `genkit docs:read <path>`
- Example: `genkit docs:read js/flows.md`
## CLI Usage (recommended)
`genkit start` unintrusively wraps any Node.js 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 your app directly
(`node`/`tsx`/`npm start`) skips trace capture, so you're debugging blind.
**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:
```bash
genkit start -- npx tsx --watch src/index.ts
genkit start --noui -- npx tsx src/index.ts # 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.
**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 -- npx tsx src/index.ts` (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"}' -- npx tsx src/index.ts
```
This is **self-terminating**: it runs the flow once, prints a `Trace ID`, then
exits (inspect it with `genkit trace:get <id>`). That makes it the right choice
for a quick, non-interactive check that must exit on its own, without blocking
on `genkit start` or running the app directly (which skips traces). Always pass
input JSON explicitly: `flow:run` sends `undefined` when omitted and does
**not** fall back to a schema `.default()`. 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)).
**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.
See [CLI Reference](references/docs-and-cli.md) for more commands, and
`genkit --help` for the full list.
## References
- [Best Practices](references/best-practices.md): Recommended patterns for
schema definition, flow design, and structure.
- [Dotprompt](references/dotprompt.md): `.prompt` files — `promptDir`,
`ai.prompt()`, variants, partials, named schemas, and
`tools`/`maxTurns`/`returnToolRequests`/`use` frontmatter.
- [Docs & CLI Reference](references/docs-and-cli.md): Documentation search,
CLI tasks, and workflows.
- [Common Errors](references/common-errors.md): Critical "gotchas", migration
guide, and troubleshooting.
- [Setup Guide](references/setup.md): Manual setup instructions for new
projects.
- [Examples](references/examples.md): Minimal reproducible examples (Basic
generation, Multimodal, Thinking mode, Embeddings).
- [Agents (Beta)](references/agents.md): Agent basics, serving, and
client-managed state. Deeper topics:
[sessions](references/agents-sessions.md),
[human-in-the-loop](references/agents-human-in-the-loop.md),
[branching](references/agents-branching.md),
[background agents](references/agents-background.md),
[state](references/agents-state.md),
[artifacts](references/agents-artifacts.md),
[multi-agent](references/agents-multi-agent.md),
[custom agents](references/agents-custom.md),
[deployment](references/agents-deployment.md).
- [Middleware](references/middleware.md): using middleware and the
`@genkit-ai/middleware` package. See also
[building custom middleware](references/middleware-custom.md).
- [Observability](references/observability.md): `@genkit-ai/otel`
(OpenTelemetry GenAI semantic conventions), custom `Instrumentation`, and
the reflection API outside dev.
- [A2UI (Generative UI)](references/a2ui.md): the `@genkit-ai/a2ui` plugin
(the `a2ui()` middleware), options, client rendering, user actions/forms,
custom catalogs, and security.
references/
a2ui.md 12.3 KB
# A2UI (Agent-to-UI) generative UI
The `@genkit-ai/a2ui` plugin brings
> [A2UI](https://a2ui.org/), a transport-agnostic, JSON-based streaming UI
> protocol, to Genkit agents.
>
> A2UI builds on the agent client, so it uses the agent APIs: `genkit/beta` on
> the server and `genkit/beta/client` in the browser. 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` array and nothing else changes.
- [Install](#install): Lines 26-41
- [Server: add the a2ui() middleware](#server-add-the-a2ui-middleware): Lines 43-106
- [Client: render surfaces](#client-render-surfaces): Lines 108-162
- [Handling user actions](#handling-user-actions): Lines 164-224
- [Custom catalogs](#custom-catalogs): Lines 226-276
- [Security and the trust boundary](#security-and-the-trust-boundary): Lines 278-298
- [How it works](#how-it-works): Lines 300-321
---
## Install
```bash
npm i @genkit-ai/a2ui
```
To render surfaces in the browser you also need a renderer. A2UI ships renderers
for [`@a2ui/lit`](https://www.npmjs.com/package/@a2ui/lit),
[`@a2ui/react`](https://www.npmjs.com/package/@a2ui/react), and
[`@a2ui/angular`](https://www.npmjs.com/package/@a2ui/angular). The examples
here
use Lit:
```bash
npm i @a2ui/lit @a2ui/web_core @a2ui/markdown-it lit @lit/context
```
## Server: add the `a2ui()` middleware
Add `a2ui()` to your agent's `use` array. That is the whole server-side setup.
`use` auto-registers the middleware, so no plugin entry is required in
`genkit({ plugins: [...] })`.
```ts
import { googleAI } from '@genkit-ai/google-genai';
import { a2ui } from '@genkit-ai/a2ui';
import { genkit } from 'genkit/beta';
const ai = genkit({ plugins: [googleAI()] });
export const uiAgent = ai.defineAgent({
name: 'uiAgent',
model: googleAI.model('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
});
```
It works identically on a one-shot `ai.generate`:
```ts
const res = await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: 'Show me the weather in Tokyo',
use: [a2ui()],
});
```
Serve the agent over HTTP with `expressHandler` (see
[Deploying agents](agents-deployment.md)); the browser talks to it with
`remoteAgent`. `expressHandler` reads the request body, so mount
`express.json()` before the route or the first turn fails with
`request.body is undefined`:
```ts
import { expressHandler } from '@genkit-ai/express';
import express from 'express';
const app = express();
app.use(express.json()); // required: expressHandler reads req.body
app.post('/api/uiAgent', expressHandler(uiAgent));
```
### 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
`@genkit-ai/a2ui/client` is browser-safe (no Node dependencies). Consume the
agent with `remoteAgent`, pull A2UI envelopes off each chunk with
`a2uiEnvelopesFromParts`, and feed whole envelopes to a renderer. A2UI travels
as
`data` parts on the raw model chunk, so read them from
`chunk.raw.modelChunk?.content`.
```ts
import { A2uiSurface, basicCatalog } from '@a2ui/lit/v0_9';
import '@a2ui/lit/v0_9'; // registers <a2ui-surface> + basic components
import { MessageProcessor } from '@a2ui/web_core/v0_9';
import { a2uiEnvelopesFromParts } from '@genkit-ai/a2ui/client';
import { remoteAgent } from 'genkit/beta/client';
const chat = remoteAgent({ url: '/api/uiAgent' }).chat();
const processor = new MessageProcessor([basicCatalog]);
processor.onSurfaceCreated((surface) => {
// `a2ui-surface` is not in the DOM's tag map, so narrow to the renderer's
// element class for a typed `.surface` property.
const el = document.createElement('a2ui-surface') as A2uiSurface;
el.surface = surface;
document.getElementById('log')!.appendChild(el);
});
const turn = chat.sendStream('What is the weather in Tokyo?');
for await (const chunk of turn.stream) {
if (chunk.text) appendProse(chunk.text);
const envelopes = a2uiEnvelopesFromParts(chunk.raw.modelChunk?.content);
if (envelopes.length) processor.processMessages(envelopes);
}
await turn.response; // surfaces any server error / finalizes the turn
```
`remoteAgent` manages the session id for you, so a single `chat` keeps the whole
conversation server-side (the agent's session store holds history).
### Lightweight helper (no full agent client)
If you do not want to drive `remoteAgent` yourself, the client entrypoint also
ships `streamA2uiAgent`, an async generator that yields `{ type: 'text' }` and
`{ type: 'envelopes' }` events:
```ts
import { streamA2uiAgent } from '@genkit-ai/a2ui/client';
for await (const ev of streamA2uiAgent({ url: '/api/uiAgent', message: 'weather in Tokyo' })) {
if (ev.type === 'text') appendProse(ev.text);
else processor.processMessages(ev.envelopes);
}
```
`StreamA2uiAgentOptions` also accepts `sessionId`, `headers`, and `abortSignal`.
## Handling user actions
When a user interacts with a surface (for example, presses a `Button`), the
renderer's action callback hands you a typed `A2uiClientAction`. Turn it into an
agent input with `actionToMessage` and send it as the next turn:
```ts
import { actionToMessage } from '@genkit-ai/a2ui/client';
const processor = new MessageProcessor([basicCatalog], (action) => {
const turn = chat.sendStream({ message: actionToMessage(action) });
// ...consume turn.stream like above...
});
```
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`.
### Renderer requirements (Lit basic catalog)
The `@a2ui/lit` basic catalog needs two host-side pieces to render fully:
- A **MarkdownRenderer** provided via Lit context (for example, backed by
`@a2ui/markdown-it`). `Text` heading `variant`s render as Markdown; without a
renderer, headings show as literal `##`.
- The **Material Symbols Outlined** font. The `Icon` component renders names as
font ligatures; without the font, icon names show as literal text. Load it in
your HTML:
```html
<link rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0..1,0" />
```
Wire up the Markdown renderer and inject the basic catalog styles once at
startup:
```ts
import { Context } from '@a2ui/lit/v0_9';
import { renderMarkdown } from '@a2ui/markdown-it';
import { injectBasicCatalogStyles } from '@a2ui/web_core/v0_9/basic_catalog';
import { ContextProvider } from '@lit/context';
injectBasicCatalogStyles();
new ContextProvider(document.body as any, {
context: Context.markdown,
initialValue: renderMarkdown,
});
```
## Custom catalogs
The `catalog` option is a **catalog id** resolved from the Genkit registry. The
bundled `'basic'` catalog (mirroring `@a2ui/web_core`'s 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).
Register a catalog with `loadCatalog`, then reference it by id. Load from a JSON
file:
```ts
import { loadCatalog } from '@genkit-ai/a2ui';
await loadCatalog(ai, { id: 'my-catalog', file: './my-catalog.json' });
```
Or define one in memory (start from `basicCatalog` and add your own component):
```ts
import { a2ui, basicCatalog, loadCatalog, type A2uiCatalog } from '@genkit-ai/a2ui';
const myCatalog: A2uiCatalog = {
id: 'https://my-app.org/catalogs/weather.json',
components: [
...basicCatalog.components,
{
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.',
},
],
};
await loadCatalog(ai, { id: 'my-catalog', catalog: myCatalog });
export const uiAgent = ai.defineAgent({
name: 'uiAgent',
model: googleAI.model('gemini-flash-latest'),
use: [a2ui({ catalog: 'my-catalog', validate: 'strict' })],
});
```
The **client must register a matching renderer** under the same catalog id, and
the component `name` must match on both sides. Otherwise the model emits a
component the client cannot render. Catalogs live in the registry under value
type `a2ui-catalog`.
## Security and the trust boundary
Generative UI moves model output into the DOM, 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
HTML) pass through untouched. `'strict'` is a well-formedness check, not a
security boundary.
- **The renderer/catalog owns prop sanitization.** Whatever renders a surface is
responsible for escaping and sanitizing prop values before they reach the DOM.
- **Restrict remote sources at the host.** 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 (Express backend plus a Vite + Lit frontend),
see the `a2ui` testapp in the Genkit JS repo.
agents-artifacts.md 3.8 KB
# Working with Artifacts (Beta)
> **Beta / preview API.** The `artifacts()` middleware comes from
> `@genkit-ai/middleware`; the `Artifact` type from `genkit/beta`. 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`.
- [Give the model artifact tools](#give-the-model-artifact-tools): Lines 20-52
- [The Artifact shape](#the-artifact-shape): Lines 54-67
- [Programmatic access (inside tools and custom agents)](#programmatic-access-inside-tools-and-custom-agents): Lines 69-83
- [Reading artifacts on the client](#reading-artifacts-on-the-client): Lines 85-98
- [Sharing artifacts across agents](#sharing-artifacts-across-agents): Lines 100-113
---
## Give the model artifact tools
The `artifacts()` middleware (see [using middleware](middleware.md)) adds
`write_artifact` and `read_artifact` tools and injects an `<artifacts>` listing
into the system prompt each turn (names + sizes, not full content). No custom
tool code needed.
```ts
import { artifacts } from '@genkit-ai/middleware';
import { ai } from './genkit.js';
export const 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.`,
use: [artifacts()],
});
```
Run it; artifacts are produced via the tool and returned in the response:
```ts
const chat = workspaceAgent.chat();
const res = await chat.send('Write poem.txt with a poem about Genkit');
console.log(res.artifacts); // Artifact[]
```
Options:
- `readonly` (default `false`): when `true`, only `read_artifact` is provided —
the model can read but not create/update artifacts. Useful on an orchestrator
that should review (but not produce) sub-agent artifacts.
## The `Artifact` shape
```ts
import type { Artifact } from 'genkit/beta';
// An artifact's content lives in `parts` (text parts). `metadata` is optional.
const artifact: Artifact = {
name: 'poem.txt',
parts: [{ text: 'Roses are red…' }],
metadata: { source: 'workspaceAgent' }, // optional
};
```
Writing the same `name` again **replaces** the artifact (dedup by name).
## Programmatic access (inside tools and custom agents)
Use the active session. `ai.currentSession()` throws when there's no active
session, so only call it inside an agent turn.
```ts
const session = ai.currentSession();
// Read all artifacts:
const all = session.getArtifacts(); // Artifact[]
const found = all.find((a) => a.name === 'poem.txt');
// Create / replace artifacts:
session.addArtifacts([{ name: 'notes.md', parts: [{ text: '# Notes' }] }]);
```
## Reading artifacts on the client
The `remoteAgent` client tracks artifacts on `chat.artifacts` (and each response
exposes `res.artifacts`):
```ts
import { remoteAgent } from 'genkit/beta/client';
const agent = remoteAgent({ url: '/api/workspaceAgent' });
const chat = agent.chat();
const res = await chat.send('Create index.html and styles.css');
console.log(res.artifacts); // Artifact[] produced this turn
console.log(chat.artifacts); // all artifacts tracked for the session
```
## Sharing artifacts across agents
In [multi-agent orchestration](agents-multi-agent.md), set the `agents()`
middleware's `artifactStrategy: 'session'` so sub-agent artifacts are merged
into the parent session (namespaced by invocation ID), and add
`artifacts({ readonly: true })` to the orchestrator so it can `read_artifact`
them:
```ts
use: [
agents({ agents: ['researcher', 'coder'], artifactStrategy: 'session' }),
artifacts({ readonly: true }),
];
```
agents-background.md 5.6 KB
# Background Agents / Detaching (Beta)
> **Beta / preview API.** 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 21-54
- [Server-side: detach and wait](#server-side-detach-and-wait): Lines 56-74
- [Resume a failed or aborted task](#resume-a-failed-or-aborted-task): Lines 76-91
- [Client-side: detach, poll, and abort](#client-side-detach-poll-and-abort): Lines 93-133
- [Status values](#status-values): Lines 135-155
---
## Define the agent (store required)
```ts
import { InMemorySessionStore } from 'genkit/beta';
import { ai } from './genkit.js';
export const backgroundAgent = ai.defineAgent({
name: 'backgroundAgent',
system:
'You are a senior research analyst. Produce a comprehensive markdown report.',
store: new InMemorySessionStore(), // REQUIRED for detach
});
```
Expose its companion actions so the client can poll/abort (see
[agents.md](agents.md#serve-an-agent-over-http)):
```ts
app.post('/api/backgroundAgent', expressHandler(backgroundAgent));
app.post(
'/api/backgroundAgent/getSnapshot',
expressHandler(backgroundAgent.getSnapshotDataAction)
);
app.post(
// Optional (genkit >= 1.43.0): lets remoteAgent's task.wait() block on the
// server in one request instead of polling getSnapshot.
'/api/backgroundAgent/waitForSnapshot',
expressHandler(backgroundAgent.waitForSnapshotAction)
);
app.post(
'/api/backgroundAgent/abort',
expressHandler(backgroundAgent.abortAgentAction)
);
```
## Server-side: detach and wait
`chat.detach(message)` returns a `DetachedTask` carrying the `snapshotId`.
`task.wait()` blocks until a terminal state and resolves with the final
snapshot. The wait happens next to the store, so there is no polling loop on
your side.
```ts
const chat = backgroundAgent.chat();
const task = await chat.detach('Write a report on renewable energy trends');
console.log(task.snapshotId); // available immediately
// Bound the wait with an abort signal; the task keeps running if it fires.
const snapshot = await task.wait({ abortSignal: AbortSignal.timeout(60_000) });
console.log(snapshot.status); // 'completed' | 'failed' | 'aborted' | 'expired'
```
Without a `DetachedTask` handle, `backgroundAgent.waitForSnapshot(snapshotId)`
does the same from a stored ID.
## Resume a failed or aborted task
> Requires `genkit >= 1.43.0`. Earlier versions only resumed `completed`
> snapshots.
`failed` and `aborted` snapshots hold the conversation up to the last completed
tool round, so they are resume points. `send({})` (no message, no resume)
re-runs the turn without repeating finished tool calls:
```ts
const snap = await task.wait();
if (snap.status === 'failed' || snap.status === 'aborted') {
const retry = await backgroundAgent.loadChat({ snapshotId: snap.snapshotId });
await retry.send({}); // or retry.send('Try again, but skip X.')
}
```
## Client-side: detach, poll, and abort
On the client (`genkit/beta/client`), `task.poll()` yields snapshots until a
terminal status; `task.abort()` cancels the background work.
```ts
import { remoteAgent, type DetachedTask } from 'genkit/beta/client';
import type { MessageData, Part } from 'genkit/beta';
const agent = remoteAgent({ url: '/api/backgroundAgent' });
// Submit - resolves immediately with a handle.
const task: DetachedTask = await agent.chat().detach('Quantum computing impact');
console.log(task.snapshotId);
// Poll until a terminal status.
for await (const snap of task.poll({ intervalMs: 2000 })) {
if (snap.status === 'completed') {
const messages: MessageData[] = snap.state?.messages ?? [];
const lastModel = messages.filter((m) => m.role === 'model').at(-1);
const text = (lastModel?.content ?? [])
.filter((p: Part) => p.text)
.map((p: Part) => p.text)
.join('');
console.log(text);
break;
} else if (snap.status === 'failed') {
throw new Error('Background task failed on the server.');
} else if (snap.status === 'aborted') {
break;
} else if (snap.status === 'expired') {
// Worker stopped sending heartbeats (e.g. the server restarted) so the
// task can never complete - treat as terminal.
break;
}
// 'pending' → keep polling
}
// Abort an in-flight task at any time:
await task.abort();
```
## Status values
- `pending`: still processing.
- `aborting`: `abort()` was called; the worker is winding down. Not terminal:
`wait()` keeps waiting until it settles as `aborted`.
- `completed`: completed successfully (read the result from
`snapshot.state.messages`).
- `failed`: error during processing. Resumable (see above).
- `aborted`: stopped by the caller. Carries the state the run had committed;
resumable.
- `expired`: the background worker stopped responding (e.g. server restart);
terminal, the task can never complete.
Pass `metadataOnly: true` in the `getSnapshot` request body to read status
without loading the conversation state.
> Equivalent low-level wire protocol: the client sends `{ detach: true }` with
> the message; `poll` hits the agent's `getSnapshot` action, `wait` hits
> `waitForSnapshot` (falling back to polling `getSnapshot` when it is not
> mounted), and `abort` hits the `abort` action. `remoteAgent` wraps all of
> this for you.
agents-branching.md 3.2 KB
# Agent Branching (Beta)
> **Beta / preview API.** 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
`chat({ snapshotId })`.
## Server-side branching
```ts
import { z } from 'genkit';
import { InMemorySessionStore } from 'genkit/beta';
import { ai } from './genkit.js';
export const assistant = ai.defineAgent({
name: 'assistant',
system: 'You are a helpful assistant.',
store: new InMemorySessionStore(),
});
const root = assistant.chat();
const res1 = await root.send('Hello!');
const checkpoint = res1.snapshotId; // branch point
// Branch A - forks from `checkpoint`.
const branchA = assistant.chat({ snapshotId: checkpoint });
await branchA.send('My name is Bob.');
const resA = await branchA.send('What is my name?'); // -> Bob
// Branch B - forks from the SAME `checkpoint`, fully independent.
const branchB = assistant.chat({ snapshotId: checkpoint });
await branchB.send('My name is John.');
const resB = await branchB.send('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.
```ts
import { remoteAgent } from 'genkit/beta/client';
const agent = remoteAgent({ url: '/api/branchingAgent' });
let snapshotId: string | undefined; // current branch point
async function twoVariants(text: string) {
// Each variant gets its own chat branching from the same snapshot
// (or a fresh session when there's no branch point yet).
const makeChat = () =>
snapshotId ? agent.chat({ snapshotId }) : agent.chat();
const [a, b] = await Promise.all([
makeChat().send(text),
makeChat().send(text),
]);
// a.snapshotId !== b.snapshotId - both branch from the same point.
return { a, b };
}
// When the user picks a variant, its snapshotId becomes the new branch point:
function pick(chosenSnapshotId: string) {
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. snapshotId stored in the
URL). The server must expose the agent's `getSnapshotDataAction` (see
[agents.md](agents.md#serve-an-agent-over-http)).
```ts
import type { Part } from 'genkit/beta';
import { remoteAgent } from 'genkit/beta/client';
const agent = remoteAgent({ url: '/api/branchingAgent' });
const snapshot = await agent.getSnapshot(snapshotId);
const history = (snapshot?.state?.messages ?? [])
.filter((m) => m.role === 'user' || m.role === 'model')
.map((m) => ({
role: m.role,
text: (m.content ?? [])
.filter((p: Part) => p.text)
.map((p: Part) => p.text)
.join(''),
}));
```
> Abandoned branches simply remain in the store as immutable snapshots; nothing
> is overwritten when you branch.
agents-custom.md 5.2 KB
# Advanced Custom Agents — `defineCustomAgent` (Beta)
> **Beta / preview API.** `ai.defineCustomAgent` comes from `genkit/beta`. 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 18-28
- [Signature](#signature): Lines 30-54
- [Example: multi-step research agent](#example-multi-step-research-agent): Lines 56-127
- [Custom status streaming](#custom-status-streaming): Lines 129-149
---
## 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
```ts
ai.defineCustomAgent(
config: {
name: string;
description?: string;
stateSchema?: z.ZodType<State>;
store?: SessionStore<State>;
},
fn: async (sess, { sendChunk }) => { message: MessageData }
);
```
The handler receives a session runner `sess` and a turn context (`sendChunk` to
stream chunks to the client). It must return `{ message }` — the final model
message for the turn.
Key `sess` methods:
- `sess.run(async (input) => {...})` — 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).
## Example: multi-step research agent
```ts
import { z } from 'genkit';
import { ai, liteModel } from './genkit.js';
interface ResearchState {
status?: string; // live progress shown to the client
subQuestions: string[];
subAnswers: { question: string; answer: string }[];
}
export const researchAgent = ai.defineCustomAgent(
{ name: 'researchAgent' },
async (sess, { sendChunk }) => {
let lastMessage: any;
const session = ai.currentSession<ResearchState>();
await sess.run(async (input) => {
const userText = input.message?.content[0]?.text ?? '';
// Step 1: decompose (a fast model). Mutating custom state auto-emits a
// `customPatch` chunk so the client's tracked state stays live.
session.updateCustom((s) => ({
...s!,
status: 'Decomposing question…',
}));
const decompose = await ai.generate({
model: liteModel,
prompt: `Break this into 2-3 sub-questions (JSON array): "${userText}"`,
output: { format: 'json', schema: z.array(z.string()).min(2).max(3) },
});
const subQuestions = decompose.output ?? [userText];
session.updateCustom((s) => ({ ...s!, subQuestions, subAnswers: [] }));
// Step 2: research each sub-question (main model).
const subAnswers: { question: string; answer: string }[] = [];
for (let i = 0; i < subQuestions.length; i++) {
session.updateCustom((s) => ({
...s!,
status: `Researching (${i + 1}/${subQuestions.length})`,
}));
const research = await ai.generate({ prompt: subQuestions[i] });
subAnswers.push({ question: subQuestions[i], answer: research.text });
}
session.updateCustom((s) => ({ ...s!, subAnswers }));
// Step 3: synthesize and STREAM the final answer to the client.
session.updateCustom((s) => ({ ...s!, status: 'Synthesizing…' }));
const synthesis = ai.generateStream({
prompt: `Synthesize a unified answer from:\n${JSON.stringify(subAnswers)}`,
});
for await (const chunk of synthesis.stream) {
sendChunk({ modelChunk: chunk }); // stream model output to the client
}
const final = await synthesis.response;
lastMessage = final.message;
// Record the final response in the session history.
if (lastMessage) sess.addMessages([lastMessage]);
session.updateCustom((s) => ({ ...s!, status: 'Done' }));
});
return {
message: lastMessage ?? {
role: 'model' as const,
content: [{ text: 'Research complete.' }],
},
};
}
);
```
## Custom status streaming
Calling `session.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
`sendChunk({ modelChunk })`.
Seed and run a custom agent exactly like a regular one:
```ts
const chat = researchAgent.chat({
state: { custom: { subQuestions: [], subAnswers: [] }, messages: [], artifacts: [] },
});
const turn = chat.sendStream('Impacts of electric vehicles?');
for await (const chunk of turn.stream) {
/* chunk.text for model output; chat.state.status for live progress */
}
await turn.response;
```
agents-deployment.md 6.3 KB
# Deploying / Serving Agents over HTTP (Beta)
> **Beta / preview API.** Uses `expressHandler` from `@genkit-ai/express` and
> the
> agent's beta companion actions. Read [agents.md](agents.md) first.
An agent is served as an HTTP endpoint with `expressHandler`. Most agents also
expose two companion actions:
- `agent.getSnapshotDataAction` → `POST /api/<name>/getSnapshot` — read a
snapshot's state. Needed for [snapshot restore](agents-branching.md) and
[background](agents-background.md) polling.
- `agent.abortAgentAction` → `POST /api/<name>/abort` — cancel a
[background](agents-background.md) turn.
These paths match the `remoteAgent` client defaults (`${url}/getSnapshot`,
`${url}/abort`), so a client only needs the base `url`.
- [A reusable exposeAgent helper](#a-reusable-exposeagent-helper): Lines 27-76
- [CORS for browser clients](#cors-for-browser-clients): Lines 78-99
- [Serving a static web UI (optional)](#serving-a-static-web-ui-optional): Lines 101-119
- [Registering agents/flows](#registering-agentsflows): Lines 121-138
- [Other host frameworks](#other-host-frameworks): Lines 140-200
---
## A reusable `exposeAgent` helper
When serving several agents, a small helper keeps registration consistent.
```ts
import { expressHandler } from '@genkit-ai/express';
import { Agent } from 'genkit/beta';
import express from 'express';
const app = express();
app.use(express.json());
// Register an agent at `/api/<name>`, optionally wiring up its companion
// `/getSnapshot` and `/abort` sub-actions.
function exposeAgent(
name: string,
agent: Agent,
opts: { snapshot?: boolean; abort?: boolean } = {}
) {
app.post(`/api/${name}`, expressHandler(agent));
if (opts.snapshot) {
app.post(
`/api/${name}/getSnapshot`,
expressHandler(agent.getSnapshotDataAction)
);
}
if (opts.abort) {
app.post(`/api/${name}/abort`, expressHandler(agent.abortAgentAction));
}
}
// Plain conversational agent - no companions needed:
exposeAgent('weatherAgent', weatherAgent);
// Snapshot restore / branching - needs getSnapshot:
exposeAgent('branchingAgent', branchingAgent, { snapshot: true });
// Background agent - needs both getSnapshot (polling) and abort:
exposeAgent('backgroundAgent', backgroundAgent, { snapshot: true, abort: true });
app.listen(process.env.PORT ? parseInt(process.env.PORT) : 8080);
```
Which companions to enable:
| Agent capability | `snapshot` | `abort` |
| ----------------------------------------- | ---------- | ------- |
| Plain chat (client- or server-state) | – | – |
| Snapshot restore / [branching](agents-branching.md) | ✓ | – |
| [Background](agents-background.md) / detach | ✓ | ✓ |
## CORS for browser clients
A browser `remoteAgent` calling a different origin (e.g. a Vite dev server)
needs CORS. **Streaming requires the `X-Genkit-Stream-Id` header** to be allowed
on the request and exposed on the response.
```ts
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Content-Type, Accept, X-Genkit-Stream-Id'
);
res.header('Access-Control-Expose-Headers', 'X-Genkit-Stream-Id');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
if (req.method === 'OPTIONS') {
res.sendStatus(204);
return;
}
next();
});
```
## Serving a static web UI (optional)
To ship a single server that hosts both the API and a built SPA, serve the
static bundle and add a non-`/api` fallback so client-side routing works on deep
links / reloads.
```ts
import { existsSync } from 'node:fs';
import { join } from 'node:path';
const webDist = join(__dirname, '..', 'web', 'dist');
if (existsSync(webDist)) {
app.use(express.static(webDist));
// SPA fallback - send index.html for any non-API GET request.
app.get(/^\/(?!api\/).*/, (_req, res) => {
res.sendFile(join(webDist, 'index.html'));
});
}
```
## Registering agents/flows
Agents and flows must be imported so they register with Genkit. Side-effect
imports work, but explicitly referencing them makes the available actions clear:
```ts
import { weatherAgent } from './weather-agent.js';
import { backgroundAgent } from './background-agent.js';
// Force-reference so the modules' top-level defineAgent/defineFlow run.
void [weatherAgent, backgroundAgent];
```
You can also expose plain flows the same way (e.g. helper endpoints):
```ts
app.post('/api/workspace/files', expressHandler(listWorkspaceFiles));
```
## Other host frameworks
`expressHandler` is one of several adapters — an agent is just an action, so any
of these works. Expose the companion actions
(`agent.getSnapshotDataAction`, `agent.abortAgentAction`) at the matching
sub-paths the same way when you need snapshot restore / background.
### Next.js (`@genkit-ai/next`)
`appRoute` turns an agent into an App Router route handler. Put companions in
their own route files.
```ts
// app/api/weatherAgent/route.ts
import { appRoute } from '@genkit-ai/next';
import { weatherAgent } from '@/lib/agents';
export const POST = appRoute(weatherAgent);
// app/api/weatherAgent/getSnapshot/route.ts
export const POST = appRoute(weatherAgent.getSnapshotDataAction);
```
### Web Fetch (`@genkit-ai/fetch`)
Works with any Fetch-API runtime (Hono, Bun, Deno, Cloudflare Workers, Vercel/
Netlify Edge, etc.). `fetchHandler(action)` returns
`(request) => Promise<Response>`;
`fetchHandlers(actions, prefix)` path-routes multiple actions by name.
```ts
import { fetchHandler } from '@genkit-ai/fetch';
import { Hono } from 'hono';
import { weatherAgent } from './agents.js';
const app = new Hono();
app.all('/api/weatherAgent', (c) => fetchHandler(weatherAgent)(c.req.raw));
app.all('/api/weatherAgent/getSnapshot', (c) =>
fetchHandler(weatherAgent.getSnapshotDataAction)(c.req.raw)
);
```
### Fastify (`@genkit-ai/fastify`)
```ts
import Fastify from 'fastify';
import { fastifyHandler } from '@genkit-ai/fastify';
import { weatherAgent } from './agents.js';
const app = Fastify();
app.post('/api/weatherAgent', fastifyHandler(weatherAgent));
app.post(
'/api/weatherAgent/getSnapshot',
fastifyHandler(weatherAgent.getSnapshotDataAction)
);
await app.listen({ port: 8080 });
```
> The `@genkit-ai/vercel-ai` plugin additionally offers a `GenkitChatTransport`
> for the Vercel AI SDK's `useChat`, which tracks the `chatId → snapshotId`
> mapping for you (no client `SessionStore` needed).
agents-human-in-the-loop.md 6.7 KB
# Agent Human-in-the-Loop / Interrupts (Beta)
> **Beta / preview API.** 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 executes on the server; it exists only to pause the turn. You then
**resume** from the exact point it paused.
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). The
paused turn just needs to be carried back into the resume call: with a store the
snapshot does it; without one the client round-trips the state blob (the
`remoteAgent` client handles this for you).
Flow: `chat.send(...)` → response has `res.interrupts` → collect human input →
`chat.resume({ respond: [...] })`.
- [Define an interrupt](#define-an-interrupt): Lines 29-73
- [Detect and resume (server-side)](#detect-and-resume-server-side): Lines 75-126
- [Client-side (browser) interrupts](#client-side-browser-interrupts): Lines 128-168
- [Notes and gotchas](#notes-and-gotchas): Lines 170-188
---
## Define an interrupt
Define it like a tool (with `inputSchema`/`outputSchema`) and add it to the
agent's `tools`. No store is required; this example uses one so the multi-turn
conversation also persists server-side.
```ts
import { z } from 'genkit';
import { InMemorySessionStore } from 'genkit/beta';
import { ai } from './genkit.js';
export const userApproval = ai.defineInterrupt({
name: 'userApproval',
description: 'Ask the user for approval before a sensitive action.',
// What the model passes in when it pauses (shown to the human):
inputSchema: z.object({ action: z.string(), details: z.string() }),
// What the human/your code returns to resume:
outputSchema: z.object({
approved: z.boolean(),
feedback: z.string().optional(),
}),
});
export const transferMoney = ai.defineTool(
{
name: 'transferMoney',
description: 'Transfer money to a specified account.',
inputSchema: z.object({ amount: z.number(), toAccount: z.string() }),
outputSchema: z.object({ success: z.boolean(), transactionId: z.string() }),
},
async ({ amount, toAccount }) => ({
success: true,
transactionId: `txn-${Date.now()}`,
})
);
export const bankingAgent = ai.defineAgent({
name: 'bankingAgent',
system:
'You are a banking assistant. ALWAYS use the userApproval interrupt to ' +
'confirm before executing transferMoney.',
tools: [userApproval, transferMoney],
store: new InMemorySessionStore(),
});
```
## Detect and resume (server-side)
`res.interrupts` is non-empty when the agent paused. Each entry exposes:
- `.name` — the interrupt's name.
- `.input` — the data the model passed in (typed by the interrupt's
`inputSchema`).
- `.respond(output)` — **builder** returning a `toolResponse` part to resume
with
(provides the tool's output without executing it). Does **not** send.
- `.restart()` — **builder** re-issuing the original tool request (use to retry
/
let the tool actually run). Does **not** send.
Resume the **same** chat with `chat.resume(...)` (or `chat.resumeStream(...)`),
which is sugar for `send({ resume })`:
```ts
const chat = bankingAgent.chat();
let res = await chat.send('Transfer $500 to my savings account.');
const approval = res.interrupts.find((i) => i.name === 'userApproval');
if (approval) {
console.log(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' })],
});
}
console.log(res.text); // final confirmation
```
Streaming variant:
```ts
const turn = chat.resumeStream({
respond: [approval.respond({ approved: true })],
});
for await (const chunk of turn.stream) process.stdout.write(chunk.text ?? '');
const 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):
```ts
await chat.resume({
respond: [a.respond({ approved: true })],
restart: [b.restart()],
});
```
## Client-side (browser) interrupts
The same pattern works over HTTP with `remoteAgent`. Types come from
`genkit/beta/client`. The client tracks the snapshot, so resuming the same
`chat`
continues exactly where it paused.
```ts
import {
remoteAgent,
type AgentChat,
type AgentInterrupt,
type AgentResponse,
} from 'genkit/beta/client';
const agent = remoteAgent({ url: '/api/bankingAgent' });
const chat: AgentChat = agent.chat();
// 1. Send and detect the pause.
const res: AgentResponse = await chat.send('Transfer $500 to savings.');
const pending: AgentInterrupt | undefined = res.interrupts.find(
(i) => i.name === 'userApproval'
);
if (pending) {
// pending.input → { action, details }; render an approval dialog.
// 2. After the human approves/denies, resume the SAME chat.
const respond = pending.respond({ approved: true, feedback: 'ok' });
const turn = chat.resumeStream({ respond: [respond] });
for await (const chunk of turn.stream) {
/* render chunk.text */
}
const final = await turn.response;
// If final.interrupts is non-empty, the agent paused again - repeat.
}
```
> UX tip: don't render a model message bubble for an interrupted turn
> (`res.interrupts.length > 0`); show the approval UI from `interrupt.input`
> instead, then render the model's reply after resuming.
## 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) —
persistence is orthogonal. Just resume on the same `chat` (or, for raw calls,
carry the returned state/snapshot back into the resume).
- **`respond`/`restart` are builders.** They return parts for the `resume`
payload; they do not send. You still call `chat.resume(...)`.
- **Resume validation.** The server validates every `respond`/`restart` entry
against the conversation history (name/ref must match; `restart` input must be
unchanged). A mismatch is rejected — always build entries from the interrupt
objects in the response, not hand-rolled parts.
- **Resumable snapshots.** `completed` snapshots are resumable, and since
`genkit` 1.43.0 so are `failed` and `aborted` ones (they hold the conversation
up to the last completed tool round; `chat.send({})` retries). `pending` and
`aborting` snapshots are rejected until they settle.
- **Re-pausing.** After resuming, the new response may interrupt again; loop
until `res.interrupts` is empty.
agents-multi-agent.md 8.3 KB
# Multi-Agent Orchestration / Sub-Agents (Beta)
> **Beta / preview API.** Sub-agent delegation uses the `agents()` middleware
> from `@genkit-ai/middleware`. 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.
- [1. Define the sub-agents](#1-define-the-sub-agents): Lines 23-51
- [2. Wire up the orchestrator](#2-wire-up-the-orchestrator): Lines 53-95
- [agents() options](#agents-options): Lines 97-112
- [Background delegation (async: true)](#background-delegation-async-true): Lines 114-154
- [Continuing a task (continue_task)](#continuing-a-task-continue_task): Lines 156-174
- [Sharing artifacts between agents](#sharing-artifacts-between-agents): Lines 176-187
- [Other middleware](#other-middleware): Lines 189-214
---
## 1. Define the sub-agents
Give each sub-agent a `description` — it's auto-discovered and shown to the
orchestrator so the model knows when to delegate.
```ts
import { artifacts, retry } from '@genkit-ai/middleware';
import { ai, defaultModel } from './genkit.js';
export const researcher = ai.defineAgent({
name: 'researcher',
description:
'A thorough research assistant that searches the web and provides ' +
'well-sourced answers.',
model: defaultModel,
system:
'You are a thorough research assistant. Save findings with write_artifact.',
maxTurns: 10,
use: [retry(), artifacts()],
});
export const coder = ai.defineAgent({
name: 'coder',
description: 'An expert programmer that writes clean, well-commented code.',
system: 'You are an expert programmer. Save code with write_artifact.',
maxTurns: 10,
use: [artifacts(), retry()],
});
```
## 2. Wire up the orchestrator
Add `agents()` to the orchestrator's `use: [...]`. Each entry is a name string
(description auto-discovered) or `{ name, description }` to override.
```ts
import { agents, artifacts, retry } from '@genkit-ai/middleware';
import { ai } from './genkit.js';
export const orchestratorAgent = ai.defineAgent({
name: 'orchestratorAgent',
system: `You are a helpful project assistant. Analyze the request and
delegate to the appropriate sub-agent. If it needs research AND code, call them
sequentially, then synthesize a final answer.`,
use: [
agents({
agents: [
'researcher', // auto-discovered description
{
name: 'coder',
description: 'Writes, debugs, and explains code. Use for programming.',
},
],
maxDelegations: 5, // guard rail against runaway delegation loops
historyLength: 4, // forward the last N user/model messages as context
artifactStrategy: 'session', // see "Sharing artifacts" below
}),
artifacts({ readonly: true }), // read sub-agent artifacts via read_artifact
retry(),
],
});
```
Run it like any other agent:
```ts
const chat = orchestratorAgent.chat();
const turn = chat.sendStream(
'Research the best sorting algorithms, then write a TypeScript quicksort.'
);
for await (const chunk of turn.stream) process.stdout.write(chunk.text ?? '');
const res = await turn.response;
```
## `agents()` options
- `agents` (required): array of sub-agent refs. A `string` (name, description
auto-discovered from the registry) or `{ name, description? }` (explicit
override).
- `toolPrefix`: prefix for generated tool names. Default `"delegate_to"` →
`delegate_to_<agent>`. Empty string uses bare agent names.
- `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. (Only client-managed
sub-agents — no `store` — accept ad-hoc seeded history; server-managed
sub-agents skip it and just receive the task.)
- `artifactStrategy`: `'inline'` (default) or `'session'` — see below.
- `async`: enables background delegation (see below).
- `maxWaitSeconds`: caps one `wait_for_background_tasks` call, whatever timeout
the model asks for.
## Background delegation (`async: true`)
> Requires `genkit >= 1.43.0`.
By default a delegation blocks the orchestrator's turn. With `async: true`,
each delegation tool accepts `background: true` and returns a task ID
(`<agent>:<snapshotId>`) immediately; the orchestrator keeps working and
collects results later. Three tools are added:
- `check_background_tasks({ taskIds })`: current status, no waiting.
- `wait_for_background_tasks({ taskIds, timeoutSeconds?, waitFor? })`: blocks
until they settle (`waitFor: "first"` returns on the first one).
- `abort_background_tasks({ taskIds })`: stops tasks no longer needed.
**The sub-agent needs a `store`.** Background work is tracked by a pending
snapshot; a store-less sub-agent can only be delegated to synchronously.
```ts
import { InMemorySessionStore } from 'genkit/beta';
const logAnalyst = ai.defineAgent({
name: 'logAnalyst',
description: 'Reads service logs and reports what they show.',
store: new InMemorySessionStore(), // required for background delegation
tools: [readLogs],
});
const commander = ai.defineAgent({
name: 'commander',
system:
'Start investigations IN THE BACKGROUND ("background": true), post a status ' +
'update while they run, then collect them with wait_for_background_tasks.',
tools: [postStatus],
maxTurns: 20, // background work adds tool rounds; raise the ceiling
use: [agents({ agents: ['logAnalyst', 'deployHistorian'], async: true })],
});
```
Tell the orchestrator in its system prompt to set `"background": true`; the
model decides per call. History is never forwarded to a store-backed sub-agent,
so task descriptions must stand alone.
## Continuing a task (`continue_task`)
> Requires `genkit >= 1.43.0`.
A delegation to a store-backed sub-agent returns `{ response, taskId, status }`
even when synchronous. The
`continue_task({ taskId, instructions?, background? })`
tool picks it up:
- `failed` / `aborted`: retries from the last saved progress (finished tool
calls are not repeated); `instructions` steer the retry.
- `completed`: follow-up `instructions` in the sub-agent's own session.
- `expired`: fences the dead worker, then continues.
- `pending` / `aborting`: refused; use the wait/check tool.
Task IDs are scoped to the conversation: the tools only accept IDs this
conversation's delegations returned. Two `agents()` instances in one call need
distinct `toolPrefix` values, or both register `continue_task` and the call is
rejected.
## 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. Pair with the `artifacts()`
middleware so the orchestrator can `read_artifact` on demand (the pattern
shown above). Merged artifacts are namespaced by an invocation ID
(`<agentName>_<rand>/<name>`).
## Other middleware
`@genkit-ai/middleware` also exports `retry`, `fallback`, `filesystem`,
`skills`, `toolApproval`, and `contextCompression`. They attach the same way via
`use: [...]` on an
agent (or on `ai.generate`) — see [using middleware](middleware.md). `retry()`
is commonly paired with delegation:
```ts
import { retry } from '@genkit-ai/middleware';
retry({
maxRetries: 3, // default 3
initialDelayMs: 1000, // default 1000
maxDelayMs: 60000, // default 60000
backoffFactor: 2, // default 2 (exponential backoff)
// statuses defaults to UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED,
// ABORTED, INTERNAL
});
```
> Note: if a sub-agent triggers an [interrupt](agents-human-in-the-loop.md) or
> fails, it is reported back to the orchestrator as a normal tool response (not
> propagated as a resumable interrupt or thrown). Tell the orchestrator how to
> handle failures, e.g. with `continue_task`. Interactive, stateful sub-agent
> interrupts are a future feature, so delegate self-contained tasks.
agents-sessions.md 5.3 KB
# Agent Sessions & Persistence (Beta)
> **Beta / preview API.** Session stores are imported from `genkit/beta`
> (`InMemorySessionStore`, `FileSessionStore`) and
> `@genkit-ai/google-cloud/beta`
> (`FirestoreSessionStore`). See [agents.md](agents.md) for the basics 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 24-69
- [Typed session state](#typed-session-state): Lines 71-93
- [Interrupts (human-in-the-loop)](#interrupts-human-in-the-loop): Lines 95-100
- [Firestore session store (scalable, Beta)](#firestore-session-store-scalable-beta): Lines 102-136
- [Implementing a custom SessionStore](#implementing-a-custom-sessionstore): Lines 138-159
---
## Pick a store
```ts
import { InMemorySessionStore, FileSessionStore } from 'genkit/beta';
// In-memory: great for tests/dev; lost on restart.
const memStore = new InMemorySessionStore();
// File-backed: snapshots persisted under <dir>/global/<snapshotId>.json
const fileStore = new FileSessionStore('./.snapshots');
// File store with chain pruning - keep only the last N snapshots in a chain.
const pruning = new FileSessionStore('./.snapshots', {
maxPersistedChainLength: 3,
});
```
Attach it to the agent:
```ts
import { ai } from './genkit.js';
export const 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:
```ts
const chat = logbookAgent.chat();
const res1 = await chat.send('Log this: I started studying Genkit today.');
const res2 = await chat.send('What did I study today?'); // remembers turn 1
console.log(res1.snapshotId, res2.snapshotId);
```
Resume a prior conversation by snapshot id:
```ts
// Continue an existing session from its latest snapshot.
const resumed = logbookAgent.chat({ snapshotId: res2.snapshotId });
await resumed.send('Add another note.');
```
## Typed session state
Use `stateSchema` to attach typed custom state to the session. `State` is
inferred from the schema and validated when a snapshot is loaded.
```ts
import { z } from 'genkit';
const Profile = z.object({ name: z.string(), tier: z.enum(['free', 'pro']) });
export const profileAgent = ai.defineAgent({
name: 'profileAgent',
system: 'Greet the user by name and tailor answers to their tier.',
store: new InMemorySessionStore<z.infer<typeof Profile>>(),
stateSchema: Profile,
});
// Seed custom state when opening the chat. Custom state lives under `.custom`
// of the `SessionState` (that's what `stateSchema` validates).
const chat = profileAgent.chat({
state: { custom: { name: 'Ada', tier: 'pro' } },
});
```
## 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, Beta)
For production, `FirestoreSessionStore` (from `@genkit-ai/google-cloud/beta`)
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).
```ts
import { genkit } from 'genkit/beta';
import { FirestoreSessionStore } from '@genkit-ai/google-cloud/beta';
const ai = genkit({ plugins: [/* ... */] });
const myAgent = ai.defineAgent({
name: 'myAgent',
system: 'You are a helpful assistant.',
// Defaults to a new Firestore() using Application Default Credentials.
store: new FirestoreSessionStore(),
});
```
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`).
> On Firebase, `@genkit-ai/firebase` re-exports this store with Firebase app
> setup (a `firebaseApp` option). See its README.
## Implementing a custom `SessionStore`
```ts
import type { SessionStore } from 'genkit/beta';
// S is the custom state type.
const store: SessionStore<MyState> = {
// Load a snapshot by snapshotId OR sessionId (exactly one).
async getSnapshot(opts) {
/* ... */ return undefined;
},
// Atomically read → mutate → persist. Returns the snapshotId used,
// or null when the mutator returns null.
async saveSnapshot(snapshotId, mutator, options) {
/* ... */ return snapshotId ?? 'new-id';
},
// Optional: subscribe to snapshot state changes (used by background agents).
onSnapshotStateChange(snapshotId, callback, options) {
return () => {}; // unsubscribe
},
};
```
agents-state.md 4.2 KB
# Working with Agent State (Beta)
> **Beta / preview API.** 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.
- [Declare the state shape](#declare-the-state-shape): Lines 17-45
- [Read and mutate state inside tools](#read-and-mutate-state-inside-tools): Lines 47-83
- [Seed and read state (server-side)](#seed-and-read-state-server-side): Lines 85-102
- [Auto-sync to the remoteAgent client](#auto-sync-to-the-remoteagent-client): Lines 104-140
---
## Declare the state shape
Pass a `stateSchema` (Zod) to `defineAgent`. `State` is inferred from it and
validated when a snapshot is loaded.
```ts
import { z } from 'genkit';
import { ai } from './genkit.js';
const TaskItem = z.object({
id: z.number(),
title: z.string(),
done: z.boolean(),
});
const TaskState = z.object({
tasks: z.array(TaskItem),
nextId: z.number(),
});
export const taskAgent = ai.defineAgent({
name: 'taskAgent',
stateSchema: TaskState,
system: 'You manage the user\'s task list. Use the tools to modify it.',
tools: [
/* addTask, toggleTask, removeTask - below */
],
});
```
## Read and mutate state inside tools
Tools call `ai.currentSession<S>()` to access the live session, then
`session.getCustom()` / `session.updateCustom(mutator)`. `updateCustom` takes
`(custom?: S) => S` and returns the new state.
```ts
type TaskState = z.infer<typeof TaskState>;
const addTask = ai.defineTool(
{
name: 'addTask',
description: 'Add a new task. Returns the created task.',
inputSchema: z.object({ title: z.string() }),
outputSchema: z.object({
id: z.number(),
title: z.string(),
done: z.boolean(),
}),
},
async (input) => {
const session = ai.currentSession<TaskState>();
let created!: { id: number; title: string; done: boolean };
session.updateCustom((state) => {
const s = state ?? { tasks: [], nextId: 1 };
created = { id: s.nextId, title: input.title, done: false };
s.tasks.push(created);
s.nextId++;
return s;
});
return created;
}
);
```
`ai.currentSession()` throws if called outside an active session (e.g. a tool
invoked without a running agent turn), so only use it inside agent tools.
## Seed and read state (server-side)
Seed initial custom state when opening a chat. The `state` argument is a
`SessionState<S>`: custom data goes under `.custom` (alongside `messages` and
`artifacts`).
```ts
const chat = taskAgent.chat({
state: {
custom: { tasks: [], nextId: 1 },
messages: [],
artifacts: [],
},
});
const res = await chat.send('Add a task: buy groceries');
console.log(res.state); // res.state returns the custom state directly
```
## Auto-sync to the `remoteAgent` client
When you talk to the agent over HTTP, the `remoteAgent` client tracks custom
state for you. Parameterize the client with your state type, seed it the same
way (`state.custom`), and after a turn read it off `chat.state`.
**Important:** on the client, custom fields are **flattened directly onto
`chat.state`** (e.g. `chat.state.tasks`) — not under `chat.state.custom`.
```ts
import { remoteAgent, type AgentChat } from 'genkit/beta/client';
interface TaskState {
tasks: { id: number; title: string; done: boolean }[];
nextId: number;
}
const agent = remoteAgent<TaskState>({ url: '/api/taskAgent' });
const chat: AgentChat<TaskState> = agent.chat({
state: { custom: { tasks: [], nextId: 1 }, messages: [], artifacts: [] },
});
const turn = chat.sendStream('Add buy groceries, then mark it done');
for await (const chunk of turn.stream) {
/* render chunk.text */
}
await turn.response;
// Custom state is flattened onto chat.state:
console.log(chat.state?.tasks);
```
There is **no `onStateChange` subscription** — state updates ride on the
streamed chunks. Read the authoritative state from `chat.state` after
`await turn.response`. (For live mid-stream status updates from a custom agent,
see [advanced custom agents](agents-custom.md), which emit `customPatch` chunks
as state changes.)
agents.md 10.7 KB
# Agents (Beta)
> **Beta / preview API.** Agents are not yet stable. Server APIs come from
> `genkit/beta`; the browser client comes from `genkit/beta/client`. Import
> paths
> and signatures may change. Always use `genkit/beta`, not `genkit`, for agents.
>
> **Requires `genkit` >= 1.39.0.**
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,
CORS, web UI, other frameworks.
- [Setup](#setup): Lines 51-62
- [Define an agent](#define-an-agent): Lines 64-102
- [Agents and middleware go hand in hand](#agents-and-middleware-go-hand-in-hand): Lines 104-144
- [Chat with an agent (server-side)](#chat-with-an-agent-server-side): Lines 146-168
- [Verify an agent from the CLI (flow:run)](#verify-an-agent-from-the-cli-flowrun): Lines 170-187
- [Serve an agent over HTTP](#serve-an-agent-over-http): Lines 189-222
- [Consume an agent from a client (remoteAgent)](#consume-an-agent-from-a-client-remoteagent): Lines 224-252
- [Client-managed state (no server store)](#client-managed-state-no-server-store): Lines 254-301
---
## Setup
```ts
// genkit.ts - note the `genkit/beta` import (required for agents)
import { genkit } from 'genkit/beta';
import { googleAI } from '@genkit-ai/google-genai';
export const ai = genkit({
plugins: [googleAI()],
model: googleAI.model('gemini-flash-latest'),
});
```
## Define an agent
`ai.defineAgent` combines prompt + tool config + (optional) session store into a
single registered action.
```ts
import { z } from 'genkit';
import { ai } from './genkit.js';
const getWeather = ai.defineTool(
{
name: 'getWeather',
description: 'Look up the current weather for a city.',
inputSchema: z.object({ city: z.string() }),
outputSchema: z.object({ tempC: z.number(), summary: z.string() }),
},
async ({ city }) => ({ tempC: 21, summary: 'Sunny' })
);
export const weatherAgent = ai.defineAgent({
name: 'weatherAgent',
system:
'You are a helpful weather assistant. Use the getWeather tool. Be concise.',
tools: [getWeather],
// `store` is optional. Omit it for client-managed state (see below).
});
```
Common `defineAgent` options:
- `name` (required): action name.
- `system` / `prompt` / dotprompt fields: same as `definePrompt`.
- `tools`: tools and interrupts available to the agent.
- `model`: override the default model.
- `store`: a `SessionStore` for server-side persistence. See
[sessions](agents-sessions.md).
- `stateSchema`: a `z.ZodType<State>` describing custom session state. When set,
`State` is inferred and validated at load time.
- `input` / `inputSchema`: input variables for the prompt template.
## Agents and middleware go hand in hand
Agents and [middleware](middleware.md) are built for each other: the
`use: [...]`
array is where you layer in sophisticated behavior without writing it yourself.
Most agent capabilities — sub-agent delegation, artifacts, filesystem access,
skill loading, tool approval, retries — are just middleware you drop in.
For example, a full coding assistant is mostly configuration:
```ts
import { filesystem, retry, skills, toolApproval } from '@genkit-ai/middleware';
import { FileSessionStore } from 'genkit/beta';
import { ai } from './genkit.js';
export const 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 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: WORKSPACE_DIR, allowWriteAccess: true }),
// Load coding conventions on demand via a use_skill tool.
skills({ skillPaths: [SKILLS_DIR] }),
// Automatic retry on transient model errors.
retry(),
],
store: new FileSessionStore('./.snapshots-coding'), // needed for tool approval
maxTurns: 30,
});
```
That single `use` array gives the agent filesystem tools, an on-demand skills
library, human-in-the-loop approval for writes, and retries — each is one line.
See [using middleware](middleware.md) for the full catalog and
[building custom middleware](middleware-custom.md) to write your own.
## Chat with an agent (server-side)
`agent.chat()` opens a conversation. A single `chat` carries state forward
automatically across turns.
```ts
const chat = weatherAgent.chat();
// Non-streaming turn:
const res = await chat.send('Weather in Tokyo?');
console.log(res.text);
console.log(res.snapshotId); // immutable checkpoint id for this turn
// Follow-up turn - history is carried automatically:
const res2 = await chat.send('What about Paris?');
// Streaming turn:
const turn = chat.sendStream('And London?');
for await (const chunk of turn.stream) {
process.stdout.write(chunk.text ?? '');
}
const final = await turn.response;
```
## 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:
```ts
import { z } from 'genkit';
import { weatherAgent } from './weather-agent.js';
import { ai } from './genkit.js';
export const tryWeatherAgent = ai.defineFlow(
{ name: 'tryWeatherAgent', inputSchema: z.string(), outputSchema: z.string() },
async (message) => (await weatherAgent.chat().send(message)).text
);
// genkit flow:run tryWeatherAgent '"Weather in Tokyo?"' -- npx tsx src/index.ts
```
## Serve an agent over HTTP
Use `expressHandler` from `@genkit-ai/express`. Optionally expose the agent's
companion `getSnapshotDataAction` (for state lookup/restore) and
`abortAgentAction` (for background aborts).
```ts
import { expressHandler } from '@genkit-ai/express';
import express from 'express';
import { weatherAgent } from './weather-agent.js';
const app = express();
app.use(express.json());
// Main turn endpoint:
app.post('/api/weatherAgent', expressHandler(weatherAgent));
// Optional companions (needed for snapshot restore / branching / background):
app.post(
'/api/weatherAgent/getSnapshot',
expressHandler(weatherAgent.getSnapshotDataAction)
);
app.post(
'/api/weatherAgent/abort',
expressHandler(weatherAgent.abortAgentAction)
);
app.listen(8080);
```
For serving multiple agents, CORS/streaming headers for browser clients, a
static
web UI, and other host frameworks (Next.js, Firebase), see
[Deploying agents](agents-deployment.md).
## Consume an agent from a client (`remoteAgent`)
The browser/Node client lives in `genkit/beta/client`. `remoteAgent` returns a
typed HTTP client; `getSnapshotUrl`/`abortUrl` default to `${url}/getSnapshot`
and `${url}/abort`.
```ts
import { remoteAgent, AgentError } from 'genkit/beta/client';
const weather = remoteAgent({ url: 'http://localhost:8080/api/weatherAgent' });
const chat = weather.chat();
const turn = chat.sendStream('Weather in Tokyo?');
for await (const chunk of turn.stream) {
process.stdout.write(chunk.text ?? '');
}
const res = await turn.response;
console.log(res.snapshotId, chat.snapshotId, chat.state);
// Multi-turn - the client carries state forward automatically:
await chat.send('What about Paris?');
// Errors surface as AgentError with an HTTP-ish status:
try {
await remoteAgent({ url: '/api/nope' }).chat().send('hi');
} catch (err) {
if (err instanceof AgentError) console.log(err.status);
}
```
## 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.
```ts
// Server: no `store` → stateless. Client owns the state blob.
export const weatherAgentStateless = ai.defineAgent({
name: 'weatherAgentStateless',
system: 'You are a helpful weather assistant. Use getWeather. Be concise.',
tools: [getWeather],
});
```
```ts
// Client: reuse one `chat` and the state threads automatically.
import { remoteAgent, type AgentChat } from 'genkit/beta/client';
const agent = remoteAgent({ url: '/api/weatherAgentStateless' });
const chat: AgentChat = agent.chat();
await chat.send('Weather in London?');
await chat.send('Is it sunny in Tokyo?'); // remembers prior turns
// The full state blob is available after each turn:
const res = await chat.send('And Paris?');
console.log(JSON.stringify(res.raw.state, null, 2));
```
If you call the stateless agent directly (e.g. from a flow) instead of via
`remoteAgent`, you must round-trip the state yourself:
```ts
async function turn(state: unknown | undefined, text: string) {
// Resume from prior state, or start fresh on the first turn.
const chat = weatherAgentStateless.chat(state ? { state } : undefined);
const res = await chat.send(text);
// Return the updated state so the caller can pass it back next turn.
return { state: res.raw.state, text: res.text };
}
```
Use client-managed state when you don't want to run server-side storage (e.g.
the client persists history itself). 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.)
best-practices.md 1.7 KB
# Genkit Best Practices
## Project Structure
- **Organized Layout**: Keep flows and tools in separate directories (e.g.,
`src/flows`, `src/tools`) to maintain a clean codebase.
- **Index Exports**: Use `index.ts` files to export flows and tools, making it
easier to import them into your main configuration.
## Model Selection (Google AI)
- **Gemini Models**: If using Google AI, ALWAYS use the latest alias
(`gemini-flash-latest` or `gemini-pro-latest`).
- **Recommended**: `gemini-flash-latest` for general use,
`gemini-pro-latest` for complex tasks.
## Model Selection (Other Providers)
- **Consult Documentation**: For other providers (OpenAI, Anthropic, etc.),
refer to the provider's official documentation for the latest recommended
model versions.
## Schema Definition
- **Use `z` from `genkit`**: Always import `z` from the `genkit` package to
ensure compatibility.
```ts
import { z } from "genkit";
```
- **Descriptive Schemas**: Use `.describe()` on Zod fields. LLMs use these
descriptions to understand how to populate the fields.
## Flow and Tool Design
- **Modularize**: Keep flows and tools in separate files/modules and import
them into your main Genkit configuration.
- **Single Responsibility**: Tools should do one thing well. Complex logic
should be broken down.
## Configuration
- **Environment Variables**: Store sensitive keys (like API keys) in
environment variables or `.env` files. Do not hardcode them.
## Development
- **Use Dev Mode**: Run your app with `genkit start -- <start cmd>` to enable
the Developer UI.
- It is recommended to configure a watcher to auto-reload your app (e.g.
`node --watch` or `tsx --watch`)
common-errors.md 6.9 KB
# Common Errors & Pitfalls
- [When Typecheck Fails](#when-typecheck-fails): Lines 13-16
- [Genkit v1.x vs Pre-1.0 Migration](#genkit-v1x-vs-pre-10-migration): Lines 18-124
- [Zod and Schema Errors](#zod-and-schema-errors): Lines 126-135
- [Tool Usage](#tool-usage): Lines 137-142
- [Handling Failures in Tool Loops](#handling-failures-in-tool-loops): Lines 144-175
- [Multimodal and Image Generation](#multimodal-and-image-generation): Lines 177-187
- [Audio and Speech Generation](#audio-and-speech-generation): Lines 189-196
---
## When Typecheck Fails
**Before searching source code or docs**, check the sections below. Many type
errors are caused by deprecated APIs or incorrect imports.
## Genkit v1.x vs Pre-1.0 Migration
Genkit v1.x introduced significant API changes. This section covers critical
syntax updates.
### Package Imports
- **Correct (v1.x)**: Import core functionality (zod, genkit) from the main
`genkit` package and plugins from their specific packages.
```ts
import { z, genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
```
- **Incorrect (Pre-1.0)**: Importing from `@genkit-ai/ai`, `@genkit-ai/core`, or
`@genkit-ai/flow`. These packages are internal/deprecated for direct use.
```ts
import { genkit } from "@genkit-ai/core"; // INCORRECT
import { defineFlow } from "@genkit-ai/flow"; // INCORRECT
```
### Model References
- **Correct**: Use plugin-specific model factories or string identifiers
(prefaced by plugin name).
```ts
// Using model factory (v1.x - Preferred)
await ai.generate({ model: googleAI.model('gemini-flash-latest'), ... });
// Using string identifier
await ai.generate({ model: 'googleai/gemini-flash-latest', ...});
// Or
await ai.generate({ model: 'vertexai/gemini-flash-latest', ...});
```
- **Incorrect**: Using imported model objects directly or string identifiers
without plugin name.
```ts
await ai.generate({ model: gemini15Pro, ... }); // INCORRECT (Pre-1.0)
await ai.generate({ model: 'gemini-flash-latest', ... }); // INCORRECT (No plugin prefix)
```
### Model Selection (Gemini)
- **Preferred**: Use latest model aliases (e.g. `gemini-flash-latest`) for best
performance and features.
```ts
model: googleAI.model('gemini-flash-latest') // PREFERRED
```
- **DEPRECATED**: Versioned legacy models (like `gemini-1.5-flash` or
`gemini-2.5-flash`) should be updated to latest aliases.
```ts
model: googleAI.model('gemini-1.5-flash') // DEPRECATED (Use gemini-flash-latest instead)
```
### Response Access
- **Correct (v1.x)**: Access properties directly.
```ts
response.text; // CORRECT
response.output; // CORRECT
```
- **Incorrect (Pre-1.0)**: Calling as methods.
```ts
response.text(); // INCORRECT
response.output(); // INCORRECT
```
### Streaming Generation
- **Correct (v1.x)**: Do NOT await `generateStream`. Iterate over `stream`
directly. Await `response` property for final result.
```ts
const {stream, response} = ai.generateStream(...); // NO await here
for await (const chunk of stream) { ... } // Iterate stream
const finalResponse = await response; // Await response property
```
- **Incorrect (Pre-1.0)**: Calling stream as a function or awaiting the
generator incorrectly.
```ts
for await (const chunk of stream()) { ... } // INCORRECT
await response(); // INCORRECT
```
### Initialization
- **Correct (v1.x)**: Instantiate `genkit`.
```ts
const ai = genkit({ plugins: [...] });
```
- **Incorrect (Pre-1.0)**: Global configuration.
```ts
configureGenkit({ plugins: [...] }); // INCORRECT
```
### Flow Definitions
- **Correct (v1.x)**: Define flows on the `ai` instance.
```ts
ai.defineFlow({...}, (input) => {...});
```
- **Incorrect (Pre-1.0)**: Importing `defineFlow` globally.
```ts
import { defineFlow } from "@genkit-ai/flow"; // INCORRECT
```
You should never import `@genkit-ai/flow`, `@genkit-ai/ai` or `@genkit-ai/core`
packages directly.
## Zod and Schema Errors
- **Import Source**: ALWAYS use `import { z } from "genkit"`.
- Using `zod` directly from `zod` package may cause instance mismatches or
compatibility issues.
- **Supported Types**: Stick to basic types: scalar (`string`, `number`,
`boolean`), `object`, and `array`.
- Avoid complex Zod features unless strictly necessary and verified.
- **Descriptions**: Always use `.describe('...')` for fields in output schemas
to guide the LLM.
## Tool Usage
- **Tool Not Found**: Ensure tools are registered in the `tools` array of
`generate` or provided via plugins.
- **MCP Tools**: Use the `ServerName:tool_name` format when referencing MCP
tools.
## Handling Failures in Tool Loops
- **Don't throw away finished tool rounds.** By default `generate()` throws on a
model/tool/middleware failure or at `maxTurns`. Since `genkit` 1.43.0,
`throwOnError: false` returns the failure on the response along with
`messages` up to the last completed tool round, so you can retry without
re-running tools that already succeeded:
```ts
const opts = { model: googleAI.model('gemini-flash-latest'), tools: [getWeather], throwOnError: false };
let res = await ai.generate({ ...opts, prompt: 'What should I wear in Tokyo?' });
if (res.finishReason === 'failed' || res.finishReason === 'aborted') {
console.warn(res.error?.status, res.error?.message); // e.g. INTERNAL, tool "getWeather" failed
res = await ai.generate({ ...opts, messages: res.messages }); // safe to resend
}
```
`aborted` means the caller stopped it (abort signal, timeout, `maxTurns`);
`failed` means something broke. Errors before the request resolves (unknown
model/tool, invalid options) still throw.
- **Agents: retry a failed turn with `send({})`.** A failed agent turn throws
`AgentError` (from `genkit/beta/client`), but the chat has already adopted the
resume point. `await chat.send({})` re-runs the turn from there:
```ts
try {
await chat.send('Book the full itinerary.');
} catch (err) {
if (err instanceof AgentError) await chat.send({});
else throw err;
}
```
- **Recoverable domain errors belong in tool output.** Return
`{ ok: false, reason: '...' }` from the tool when the model can fix the input;
throw only when the system can't continue.
## Multimodal and Image Generation
- **Missing responseModalities**: When using image generation models (like
`gemini-nano-banana-2.1`), you **MUST** specify the response modalities in the
config.
```ts
config: {
responseModalities: ["TEXT", "IMAGE"]
}
```
Failure to do so will result in errors or incorrect output format.
## Audio and Speech Generation
- **Raw PCM Data vs MP3**: Some providers (e.g., Google GenAI) return raw PCM
data, while others (e.g., OpenAI) return MP3.
- **DO NOT assume MP3 format.**
- **DO NOT embed raw PCM in HTML audio tags.**
- **Action**: Run `genkit docs:search "speech audio"` to find
provider-specific conversion steps (e.g., PCM to WAV).
docs-and-cli.md 5.7 KB
# Genkit Documentation & CLI
This reference lists common tasks and workflows using the `genkit` CLI. For
authoritative command details, always run `genkit --help` or
`genkit <command> --help`.
- [Prerequisites:](#prerequisites): Lines 16-21
- [Documentation](#documentation): Lines 23-30
- [Development Workflow (recommended)](#development-workflow-recommended): Lines 32-68
- [Flow Execution (secondary)](#flow-execution-secondary): Lines 70-93
- [Evaluation](#evaluation): Lines 95-115
- [Tracing](#tracing): Lines 117-132
---
## Prerequisites:
Ensure that the CLI is on `genkit-cli` version >= 1.29.0. If not, or if an older
version (1.x < 1.29.0) is present, update the Genkit CLI version. Alternatively,
to run commands with a specific version or without global installation, prefix
them with `npx -y genkit-cli@^1.29.0`.
## Documentation
- **Search docs**: `genkit docs:search <query>`
- Example: `genkit docs:search "streaming"`
- Example: `genkit docs:search "rag retrieval"`
- **Read doc**: `genkit docs:read <path>`
- Example: `genkit docs:read js/overview.md`
- **List docs**: `genkit docs:list`
## Development Workflow (recommended)
`genkit start` unintrusively wraps any Node.js 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 your app directly
(`node`/`tsx`/`npm start`) skips trace capture, so you're debugging blind.
**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:
- **Node.js (TypeScript)**:
```bash
genkit start -- npx tsx --watch src/index.ts
```
- **Next.js**:
```bash
genkit start -- npx next dev
```
- **Without the Dev UI** (still a persistent server):
```bash
genkit start --noui -- npx tsx src/index.ts
```
`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.
For non-interactive/agent/CI use, 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), e.g.
`genkit flow:run myFlow '<input>' --non-interactive -- npx tsx src/index.ts`.
## Flow Execution (secondary)
- **Run a flow**: `genkit flow:run <flowName> '<inputJSON>' -- <run cmd>`
- Invokes a specific flow by name from the CLI. Append your run command
after `--` to spin up the runtime for this run (the command runs as-is
to register your flows): it runs once, prints a `Trace ID`, then exits,
so it's the right choice for a quick, non-interactive check that must
self-terminate (unlike `genkit start`). Note: `flow:run` runs **flows**
(`ai.defineFlow`), not agents; you can't `flow:run` an agent
(`ai.defineAgent`) directly. To verify an agent, wrap one turn in a
throwaway flow and run that. Traces for the run can be inspected with
the tracing commands below.
- **Always pass input JSON explicitly.** `flow:run` sends `undefined` when
the input is omitted and does **not** fall back to a schema
`.default()`, so a flow with a defaulted input will fail validation
unless you pass the value.
- **Simple Input**:
```bash
genkit flow:run tellJoke '"chicken"' -- npx tsx src/index.ts
```
- **Object Input**:
```bash
genkit flow:run generateStory '{"subject": "robot", "genre": "sci-fi"}' -- npx tsx src/index.ts
```
## Evaluation
- **Evaluate a flow**: `genkit eval:flow <flowName> [data] -- <run cmd>`
- Runs a flow and evaluates the output against configured evaluators. As
with `flow:run`, append your run command after `--` to spin up the
runtime for the run.
- **Example (Single Input)**:
```bash
genkit eval:flow answerQuestion '[{"testCaseId": "1", "input": {"question": "What is Genkit?"}}]' -- npx tsx src/index.ts
```
- **Example (Batch Input)**:
```bash
genkit eval:flow answerQuestion --input inputs.json -- npx tsx src/index.ts
```
- **Run Evaluation**: `genkit eval:run <dataset>`
- Evaluates a dataset against configured evaluators.
- **Example**:
```bash
genkit eval:run dataset.json --output results.json
```
## Tracing
- **Get a trace**: `genkit trace:get <traceId>`
- Retrieves detailed information for a specific trace by its ID. This is
particularly useful for debugging failed model calls, inspecting tool
execution, or analyzing the exact inputs and outputs of a specific step
in your flow.
- **Machine-readable output**: add `--format json` (e.g.
`genkit trace:get <traceId> --format json`) to get clean JSON you can
pipe into `jq` or other parsers.
- **List traces**: `genkit trace:list [options]`
- Lists recent traces. Use this to find trace IDs from recent executions.
- **Piping to parsers**: the **default** trace output is human-oriented (extra
banner/log lines, possible truncation on large traces), so don't pipe that
form directly into `jq`. Use `--format json` for clean JSON, or the Dev UI
trace viewer (`genkit start`) for complex traces.
dotprompt.md 5.8 KB
# Dotprompt (.prompt files) — Genkit JS
- [What it is](#what-it-is): Lines 16-20
- [Where files live](#where-files-live): Lines 22-35
- [File format](#file-format): Lines 37-61
- [Loading and calling a prompt](#loading-and-calling-a-prompt): Lines 63-100
- [Registering named schemas](#registering-named-schemas): Lines 102-118
- [Variants](#variants): Lines 120-127
- [Partials](#partials): Lines 129-153
- [Helpers](#helpers): Lines 155-165
- [Tools, tool-loop control, and middleware](#tools-tool-loop-control-and-middleware): Lines 167-213
- [Relationship to agents](#relationship-to-agents): Lines 215-219
---
## What it is
`.prompt` files combine YAML frontmatter (model, config, schemas, tools,
middleware) with a Handlebars template. They keep prompt logic out of your
TypeScript code and make variants and iteration easy.
## Where files live
By default Genkit loads `.prompt` files from `./prompts`. Configure with the
`promptDir` option (set to `null` to disable auto-loading):
```ts
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [googleAI()],
promptDir: './prompts', // default
});
```
## File format
`prompts/recipe.prompt`:
```
---
model: googleai/gemini-pro-latest
input:
schema:
food: string
ingredients?(array): string # ? = optional
output:
schema: Recipe # references a schema registered via ai.defineSchema
---
You are a chef famous for creative recipes.
Generate a recipe for {{food}}.
{{#if ingredients}}
Make sure to include the following ingredients:
{{list ingredients}}
{{/if}}
```
Schema fields use Picoschema (the compact form above) or you can reference a
named schema registered with `ai.defineSchema`.
## Loading and calling a prompt
`ai.prompt(name, { variant? })` returns an `ExecutablePrompt`. The returned
object is **callable** and also has `.stream()`, `.render()`, and `.asTool()`.
```ts
// Non-streaming: call it like a function with the input object.
const recipePrompt = ai.prompt('recipe');
const { output } = await recipePrompt({ food: 'banana bread' });
// With a typed output schema
const RecipeSchema = ai.defineSchema('Recipe', z.object({
title: z.string(),
steps: z.array(z.string()),
}));
const result = await ai.prompt<any, typeof RecipeSchema>('recipe')({ food: 'banana bread' });
result.output; // typed as Recipe
```
### Streaming
```ts
const storyPrompt = ai.prompt('story');
const { response, stream } = storyPrompt.stream({ subject: 'a robot' });
for await (const chunk of stream) {
console.log(chunk.text);
}
const final = await response;
```
### Render without generating
Useful for building `ai.generate` calls or LLM-judge evals:
```ts
const rendered = await ai.prompt('recipe').render({ food: 'banana bread' });
// rendered is a GenerateOptions object (messages, model, config, ...)
```
## Registering named schemas
Reference a schema by name in `.prompt` frontmatter (`input.schema` /
`output.schema`) after registering it:
```ts
import { z } from 'genkit';
const RecipeSchema = ai.defineSchema(
'Recipe',
z.object({
title: z.string().describe('recipe title'),
ingredients: z.array(z.object({ name: z.string(), quantity: z.string() })),
steps: z.array(z.string()).describe('the steps required'),
})
);
```
## Variants
Name the file `<name>.<variant>.prompt` — e.g. `recipe.robot.prompt`. Call with
the `variant` option:
```ts
await ai.prompt('recipe', { variant: 'robot' })({ food: 'oil cake' });
```
## Partials
Reusable template fragments. Name a partial file `_<name>.prompt` and include it
with `{{>name param=value}}`.
`prompts/_style.prompt`:
```
{{ role "system" }}
You should speak as if you are a {{#if personality}}{{personality}}{{else}}pirate{{/if}}.
{{role "user"}}
```
`prompts/story.prompt`:
```
---
model: googleai/gemini-pro-latest
input:
schema:
subject: string
personality?: string
---
{{>style personality=personality}}
Tell me a story about {{subject}}.
```
## Helpers
Register a function callable inside templates:
```ts
ai.defineHelper('list', (data: any) =>
Array.isArray(data) ? data.map((item) => `- ${item}`).join('\n') : ''
);
```
Then use `{{list ingredients}}` in the template.
## 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:
```
---
model: googleai/gemini-flash-latest
input:
schema:
tone: string
tools:
- getAttractions
- getFlightInfo
toolChoice: auto # auto | required | none
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. 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 — register the middleware plugin so the
name is available:
```ts
import { retry } from '@genkit-ai/middleware';
const ai = genkit({
plugins: [googleAI(), retry.plugin()],
promptDir: './prompts',
});
```
See [Using middleware](middleware.md) for the full list of built-in middleware.
## Relationship to agents
Agents (`defineAgent`) share the same dotprompt frontmatter — `system`/`prompt`,
`tools`, `maxTurns`, `returnToolRequests`, and `use`. A `.prompt` file with
`{{history}}` and tools can back an agent directly. See [Agents](agents.md).
examples.md 5.5 KB
# Genkit Examples
This reference contains minimal, reproducible examples (MREs) for common Genkit
patterns.
> **Disclaimer**: These examples use **Google AI** models (`googleAI`,
> `gemini-*`) for demonstration. The patterns apply to **any provider**. To use
> a different provider:
> 1. Search the docs for the correct plugin: `genkit docs:search "plugins"`.
> 2. Install and configure the plugin.
> 3. Swap the model reference in the code.
- [Basic Text Generation](#basic-text-generation): Lines 22-36
- [Structured Output](#structured-output): Lines 38-59
- [Streaming](#streaming): Lines 61-76
- [Advanced Configuration](#advanced-configuration): Lines 78-115
- [Multimodal Generation](#multimodal-generation): Lines 117-178
- [Embeddings](#embeddings): Lines 180-214
---
## Basic Text Generation
```ts
import { genkit } from "genkit";
import { googleAI } from "@genkit-ai/google-genai";
const ai = genkit({
plugins: [googleAI()],
});
const { text } = await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: 'Tell me a story in a pirate accent',
});
```
## Structured Output
```ts
import { z } from 'genkit';
const JokeSchema = z.object({
setup: z.string().describe('The setup of the joke'),
punchline: z.string().describe('The punchline'),
});
const response = await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: 'Tell me a joke about developers.',
output: { schema: JokeSchema },
});
// response.output is strongly typed
const joke = response.output;
if (joke) {
console.log(`${joke.setup} ... ${joke.punchline}`);
}
```
## Streaming
```ts
const { stream, response } = ai.generateStream({
model: googleAI.model('gemini-flash-latest'),
prompt: 'Tell a long story about a developer using Genkit.',
});
for await (const chunk of stream) {
console.log(chunk.text);
}
// Await the final response
const finalResponse = await response;
console.log('Complete:', finalResponse.text);
```
## Advanced Configuration
### Thinking Mode
Enable "thinking" process for complex reasoning tasks.
```ts
const response = await ai.generate({
model: googleAI.model('gemini-pro-latest'),
prompt: 'what is heavier, one kilo of steel or one kilo of feathers',
config: {
thinkingConfig: {
thinkingLevel: 'HIGH', // or 'LOW'
includeThoughts: true, // Returns thought process in response
},
},
});
```
### Google Search Grounding
Enable models to access current information via Google Search.
```ts
const response = await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: 'What are the top tech news stories this week?',
config: {
googleSearchRetrieval: true,
},
});
// Access grounding metadata (sources)
const groundingMetadata = (response.custom as any)?.candidates?.[0]?.groundingMetadata;
if (groundingMetadata) {
console.log('Sources:', groundingMetadata.groundingChunks);
}
```
## Multimodal Generation
### Image Generation / Editing
Set `responseModalities: ['TEXT', 'IMAGE']` when using image generation models.
Image settings (aspect ratio, size) go in `config.imageConfig`.
```ts
// Generate an image
const { media } = await ai.generate({
model: googleAI.model('gemini-nano-banana-2.1'),
config: { responseModalities: ['TEXT', 'IMAGE'] },
prompt: "generate a picture of a unicorn wearing a space suit on the moon",
});
// media.url contains the data URI
```
```ts
// Edit an image
const { media } = await ai.generate({
model: googleAI.model('gemini-nano-banana-2.1'),
config: { responseModalities: ['TEXT', 'IMAGE'] },
prompt: [
{ text: "change the person's outfit to a banana costume" },
{ media: { url: "https://example.com/photo.jpg" } },
],
});
```
### Speech Generation (TTS)
Generate audio from text.
```ts
import { Buffer } from 'node:buffer';
import { writeFile } from 'node:fs/promises';
const { media } = await ai.generate({
model: googleAI.model('gemini-3.8-flash-tts'),
config: {
speechConfig: {
voiceConfig: {
prebuiltVoiceConfig: { voiceName: 'Algenib' }, // Options: 'Puck', 'Charon', 'Kore', etc.
},
},
},
prompt: 'Genkit is an amazing library',
});
// gemini-3.8-flash-tts returns a complete WAV file (audio/wav) as a data URI.
// Streamed requests return raw PCM chunks unless you set
// config.audioFormat: { mimeType: 'audio/wav' }.
if (media?.url) {
const wav = Buffer.from(media.url.slice(media.url.indexOf(',') + 1), 'base64');
await writeFile('output.wav', wav);
}
```
Older preview TTS models (`gemini-2.5-*-preview-tts`,
`gemini-3.1-flash-tts-preview`)
are deprecated and return raw PCM that needs conversion to WAV. Run
`genkit docs:search "speech audio"` for conversion code.
## Embeddings
```ts
const embedder = googleAI.embedder('gemini-embedding-001');
const embeddings = await ai.embed({ embedder, content: 'The sky is blue.' });
const vector = embeddings[0].embedding; // number[]
const batch = await ai.embedMany({
embedder,
content: ['The sky is blue.', 'Grass is green.'],
});
// Optional tuning (default is 3072 dimensions)
await ai.embed({
embedder,
content: 'The sky is blue.',
options: { outputDimensionality: 768, taskType: 'RETRIEVAL_DOCUMENT' },
});
```
Common embedders: `gemini-embedding-001` (text), `gemini-embedding-2`
(multimodal: text, image, video). Plain string ids
(`embedder: 'googleai/gemini-embedding-001'`) also work.
Multimodal input is passed as a document:
```ts
const imageEmbeddings = await ai.embed({
embedder: googleAI.embedder('gemini-embedding-2'),
content: {
content: [{ media: { url: 'data:image/png;base64,...', contentType: 'image/png' } }],
},
});
```
middleware-custom.md 3.2 KB
# Building Custom Middleware
Write reusable, named middleware with `generateMiddleware`. It returns a factory
you call in the `use: [...]` array (see [using middleware](middleware.md)) —
exactly how the `@genkit-ai/middleware` package's middleware are built. The
factory can take optional Zod-validated config and gets access to the `ai`
instance.
```ts
// timing.ts
import { generateMiddleware, z } from 'genkit';
const OptionsSchema = z.object({ label: z.string().optional() });
export const timing = generateMiddleware(
{
name: 'timing',
description: 'Logs how long the model call takes.',
configSchema: OptionsSchema,
},
({ config, ai }) => {
// Runs once per generate() call. Return any of the hooks below.
return {
model: async (req, ctx, next) => {
const start = Date.now();
const res = await next(req, ctx);
console.log(`[${config?.label ?? 'timing'}] ${Date.now() - start}ms`);
return res;
},
};
}
);
```
## Register it as a plugin
Register custom middleware with Genkit via its `.plugin()` method. This is the
recommended setup — without it the middleware still works in `use: [...]`, but
it
is **not visible to the Genkit Dev UI**.
```ts
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
import { timing } from './timing.js';
export const ai = genkit({
plugins: [googleAI(), timing.plugin()],
});
// Then use the factory in `use: [...]`:
await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: 'Hi',
use: [timing({ label: 'gen' })],
});
```
## Available hooks
The instantiate callback returns a `GenerateMiddlewareDef` with any subset of:
- `generate(envelope, ctx, next)` — wrap the **whole generate action**. The
`envelope` carries `{ request, currentTurn, messageIndex }`. Use it to inject
request params, post-process the response, or catch errors across the tool
loop.
- `model(req, ctx, next)` — wrap the **underlying model call** (caching, retry,
request/response rewriting). `req` is a `GenerateRequest`.
- `tool(req, ctx, next)` — wrap **individual tool calls** (validate inputs,
cache or override tool output). `req` is a `ToolRequestPart`; return a
`ToolResponsePart | undefined`.
- `tools: ToolAction[]` — **statically inject tools** whenever the middleware is
active (how `artifacts()` / `filesystem()` add their tools).
```ts
generateMiddleware({ name: 'example' }, ({ ai }) => ({
generate: async (envelope, ctx, next) => next(envelope, ctx),
model: async (req, ctx, next) => next(req, ctx),
tool: async (req, ctx, next) => next(req, ctx),
tools: [
/* ToolAction[] */
],
}));
```
Call `next(...)` to continue the chain (optionally with a modified
request/envelope) and transform the result before returning it.
## Choosing a hook
- Transform prompt/messages or the final result across the whole turn →
`generate`.
- Cache/retry/rewrite a single model round-trip → `model`.
- Gate or memoize tool execution → `tool`.
- Make extra capabilities available to the model → `tools`.
> Reminder: register custom middleware via `.plugin()` (see above). It works in
> `use: [...]` without registering, but unregistered middleware is not visible
> to
> the Genkit Dev UI.
middleware.md 6.3 KB
# Using Middleware
Middleware wraps generation to add cross-cutting behavior — retries, fallback,
extra tools, request/response transforms, etc. You attach middleware with the
`use: [...]` array, which is supported on `ai.generate` / `ai.generateStream`,
executable prompts (`definePrompt`), and agents (`defineAgent`).
```ts
import { retry } from '@genkit-ai/middleware';
const res = await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: 'Say hello',
use: [retry({ maxRetries: 2 })],
});
```
The same array works on prompts and agents:
```ts
const myPrompt = ai.definePrompt({ name: 'p', prompt: '...', use: [retry()] });
const myAgent = ai.defineAgent({ name: 'a', system: '...', use: [retry()] });
```
Middleware is a configurable factory like `retry()` / `artifacts()` that returns
a reference for `use: [...]`. The `@genkit-ai/middleware` package ships a set of
ready-made ones (covered below); to write your own see
[building custom middleware](middleware-custom.md).
- [Register middleware as a plugin](#register-middleware-as-a-plugin): Lines 37-58
- [The @genkit-ai/middleware package](#the-genkit-aimiddleware-package): Lines 60-184
- [Built-in model middleware (in core)](#built-in-model-middleware-in-core): Lines 186-208
---
## Register middleware as a plugin
Register each middleware with Genkit via its `.plugin()` method. This is the
recommended setup — middleware still works in `use: [...]` without registering,
but **unregistered middleware is not visible to the Genkit Dev UI**.
```ts
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
import { retry, artifacts } from '@genkit-ai/middleware';
export const ai = genkit({
plugins: [googleAI(), retry.plugin(), artifacts.plugin()],
});
// Then reference the factory in `use: [...]`:
await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: 'Say hello',
use: [retry({ maxRetries: 2 })],
});
```
## The `@genkit-ai/middleware` package
```bash
npm i @genkit-ai/middleware
```
Exports eight middleware factories. Register each via `.plugin()` (above), then
call `name(options)` in `use: [...]`.
### `retry(options?)`
Retries on transient errors with exponential backoff.
```ts
import { retry } from '@genkit-ai/middleware';
retry({
maxRetries: 3, // default 3
initialDelayMs: 1000, // default 1000
maxDelayMs: 60000, // default 60000
backoffFactor: 2, // default 2
noJitter: false, // default false
// statuses defaults to UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED,
// ABORTED, INTERNAL
});
```
### `fallback(options)`
Falls back to other models when the primary fails.
```ts
import { fallback } from '@genkit-ai/middleware';
import { googleAI } from '@genkit-ai/google-genai';
fallback({
models: [googleAI.model('gemini-flash-latest')], // tried in order
// statuses defaults to UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED,
// ABORTED, INTERNAL, NOT_FOUND, UNIMPLEMENTED
isolateConfig: false, // default false - fallback inherits the request config
});
```
### `artifacts(options?)`
Adds `write_artifact` / `read_artifact` tools for session artifacts.
```ts
artifacts({ readonly: false }); // readonly true → read_artifact only
```
See [working with artifacts](agents-artifacts.md).
### `agents(options)`
Sub-agent delegation: injects a `delegate_to_<name>` tool per sub-agent, plus a
`continue_task` tool for picking up failed/aborted/finished sub-agent tasks.
`async: true` adds background delegation (requires `genkit >= 1.43.0`).
```ts
agents({ agents: ['researcher', 'coder'], maxDelegations: 5, async: true });
```
See [multi-agent orchestration](agents-multi-agent.md).
### `contextCompression(options)`
Keeps long conversations and tool loops inside a token budget
(requires `genkit >= 1.43.0`). The model gets a compressed view;
`response.messages`
keeps the full transcript, with compression state in message metadata.
```ts
import { contextCompression, resolveCompressedHistory } from '@genkit-ai/middleware';
use: [
// List AFTER context-adding middleware (filesystem, skills, artifacts, agents).
contextCompression({
maxInputTokens: 80000, // trigger
deduplicateToolResponses: { matchBy: 'name-and-input' },
toolResponses: { maxChars: 2000, preserveRecent: 2 },
summarize: { model: googleAI.model('gemini-flash-lite-latest'), preserveRecent: 6 },
// also: maxMessages, preserveRecent (4), maxToolResponseChars (400000),
// skipSummarizationThreshold, preserveOriginalMessages (true)
}),
];
const sentToModel = resolveCompressedHistory(response.messages);
```
Strategies run cheapest first: per-response hard cap, dedupe, truncate older
tool
responses, message cap, LLM summary, then dropping older messages as a last
resort.
### `filesystem(options)`
Grants the model `list_files`, `read_file`, `write_file`, and
`search_and_replace` tools, sandboxed to a root directory.
```ts
filesystem({
rootDirectory: './workspace', // required; all access is restricted to it
allowWriteAccess: false, // default false (read-only)
toolNamePrefix: '', // optional prefix for the injected tool names
});
```
### `skills(options?)`
Scans directories for skill files (frontmatter `name`/`description`), injects a
listing into the system prompt, and provides a `use_skill` tool.
```ts
skills({ skillPaths: ['skills'] }); // default ['skills']
```
### `toolApproval(options)`
Restricts tool execution to an approved list; throws a `ToolInterruptError` for
anything else (resumable via [interrupts](agents-human-in-the-loop.md)).
```ts
toolApproval({ approved: ['getWeather', 'search'] });
```
## Built-in model middleware (in core)
Some middleware ships in the `genkit` core (no extra package) — import from
`genkit/model/middleware`:
- `downloadRequestMedia({ maxBytes? })` — fetch URL media and inline it.
- `validateSupport({ name, ... })` — assert a model supports requested features.
- `simulateSystemPrompt({ preface? })` — emulate a system prompt for models
without native support.
- `augmentWithContext(options?)` — inject retrieved context documents.
- `simulateConstrainedGeneration(options?)` — emulate constrained/JSON output.
```ts
import { simulateConstrainedGeneration } from 'genkit/model/middleware';
await ai.generate({
model: someModel,
prompt: '...',
use: [simulateConstrainedGeneration()],
});
```
To write your own, see [building custom middleware](middleware-custom.md).
observability.md 5.5 KB
# Observability (Tracing, OpenTelemetry, Reflection API)
> Pluggable instrumentation, `@genkit-ai/otel`, and the reflection API settings
> require `genkit >= 1.43.0`.
- [How tracing works](#how-tracing-works): Lines 13-21
- [Export OpenTelemetry GenAI semantic conventions (@genkit-ai/otel)](#export-opentelemetry-genai-semantic-conventions-genkit-aiotel): Lines 23-81
- [Custom instrumentation](#custom-instrumentation): Lines 83-119
- [Reflection API outside dev](#reflection-api-outside-dev): Lines 121-142
---
## How tracing works
- **In dev** (`genkit start`), Genkit posts spans straight to the Developer UI's
telemetry server. No OpenTelemetry SDK is involved. Logs written with
`logger` from `genkit/logging` show up next to the span that produced them.
- **Elsewhere**, spans go through pluggable `Instrumentation` providers. The
default provider creates OpenTelemetry spans with `genkit:*` attributes.
Nothing is exported until an OTel SDK is started, directly or by a plugin
such as `enableFirebaseTelemetry()` (Genkit Monitoring).
## Export OpenTelemetry GenAI semantic conventions (`@genkit-ai/otel`)
Use this to send Genkit telemetry to any OTLP backend (Jaeger, Grafana,
Honeycomb, Datadog, ...) in the vendor-neutral `gen_ai.*` shape.
```bash
npm i @genkit-ai/otel @opentelemetry/sdk-node
```
```ts
import { googleAI } from '@genkit-ai/google-genai';
import { GenAiInstrumentation } from '@genkit-ai/otel';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { genkit } from 'genkit';
import { configureInstrumentation } from 'genkit/tracing';
// 1. The app owns the OTel SDK. With no args it reads the standard OTEL_* env
// vars (default: OTLP http/protobuf on localhost:4318).
const sdk = new NodeSDK();
sdk.start();
// 2. Route Genkit spans through the GenAI provider. Call once, before genkit().
configureInstrumentation(
new GenAiInstrumentation({
contentCapturingMode: 'SPAN_ONLY', // prompts/responses on spans; may contain PII
emitToolSpans: true, // execute_tool spans
})
);
// 3. Use Genkit as usual.
const ai = genkit({ plugins: [googleAI()] });
```
What you get: `chat <model>` client spans with `gen_ai.request.*`,
`gen_ai.usage.*`, and `gen_ai.response.finish_reasons`; optional
`execute_tool <name>` spans; a generic span per other Genkit action (tagged
`genkit.action.type`); and the `gen_ai.client.token.usage` and
`gen_ai.client.operation.duration` metrics.
Options: `contentCapturingMode` (`'NO_CONTENT'` default, `'SPAN_ONLY'`,
`'EVENT_ONLY'`, `'SPAN_AND_EVENT'`; falls back to the
`OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` env var), `captureActionIO`
(raw `genkit.input`/`genkit.output`, default `false`), `emitToolSpans` (default
`false`), `emitMetrics` (default `true`), `scopeName`, and explicit
`tracer`/`meter`/`logger`.
Gotchas:
- **Do not combine with `enableFirebaseTelemetry()` or
`enableGoogleCloudTelemetry()`.** `configureInstrumentation` replaces the
default provider, and those plugins build their metrics/logs from its
`genkit:*` attributes. Their Genkit metrics stop with no error. Pick one.
- **`EVENT_ONLY` content goes to the OTel logs signal**, not the span. Jaeger
can't show it; use `SPAN_ONLY`/`SPAN_AND_EVENT` there.
- **The Dev UI keeps working.** Under `genkit start`, its own provider always
runs first. To preview what the OTel export looks like in the Dev UI, run
`genkit start --experimental-use-otel -- <command>`.
- **No SDK, no export.** Without a started OTel SDK the provider is inert and
logs one warning.
## Custom instrumentation
Implement `Instrumentation` to send spans somewhere else. `runInNewSpan` wraps
the operation like middleware: call `next` exactly once, return its result,
rethrow its errors unchanged.
```ts
import { INVALID_SPAN_CONTEXT, trace } from '@opentelemetry/api';
import {
configureInstrumentation,
type Instrumentation,
type InstrumentationNext,
type InstrumentationSpanInfo,
} from 'genkit/tracing';
class TimingInstrumentation implements Instrumentation {
async runInNewSpan<T>(
info: InstrumentationSpanInfo,
next: InstrumentationNext<T>
): Promise<T> {
const start = performance.now();
try {
// Not OTel-based: pass a non-recording span and empty ids.
return await next(trace.wrapSpanContext(INVALID_SPAN_CONTEXT), {
traceId: '',
spanId: '',
setMetadata() {},
});
} finally {
// metadata.state is 'success' | 'error' once next settles.
console.log(info.metadata.path, info.metadata.state, performance.now() - start);
}
}
}
configureInstrumentation(new TimingInstrumentation());
```
## Reflection API outside dev
The CLI and Dev UI talk to the app through the reflection API. By default it
runs only under `GENKIT_ENV=dev` on `127.0.0.1:3100+`. To run it elsewhere
(e.g. staging), turn it on explicitly and protect it:
```bash
GENKIT_REFLECTION_ENABLED=true \
GENKIT_REFLECTION_HOST=0.0.0.0 \
GENKIT_REFLECTION_PORT=3100 \
GENKIT_REFLECTION_SECRET_TOKEN="$(openssl rand -hex 32)" \
node lib/index.js
```
- `GENKIT_REFLECTION_ENABLED`: `true` on anywhere, `false` off even under dev.
Any other value makes `genkit()` throw.
- `GENKIT_REFLECTION_SECRET_TOKEN`: every request must send it in the
`x-genkit-reflection-secret` header (`/api/__health` stays open). Without it,
anyone who can reach the port can run every flow, model, and tool.
- `genkit({ reflectionPort: 3200 })` binds exactly that port and fails if taken;
`0` lets the OS pick; unset searches upward from 3100. The env var wins over
the option, and neither turns the API on.
setup.md 4.3 KB
# Genkit JS Setup
Follow these instructions to set up Genkit in the current codebase. These
instructions are general-purpose and lack specific codebase knowledge, so use
your best judgment when following them.
0. Tell the user "I'm going to check out your workspace and set you up to use
Genkit for GenAI workflows."
1. If the current workspace is empty or is a starter template, your goal will be
to create a simple image generation flow that allows someone to generate an
image based on a prompt and selectable style. If the current workspace is not
empty, you will create a simple example flow to help get the user started.
2. Check to see if any Genkit provider plugin (such as `@genkit-ai/google-genai`
or `@genkit-ai/oai-compat` or others, may start with `genkitx-*`) is
installed.
- If not, ask the user which provider they want to use.
- **For non-Google providers**: Use `genkit docs:search "plugins"` to find
the correct package and installation instructions.
- If they have no preference, default to `@genkit-ai/google-genai` for a
quick start.
- If this is a Next.js app, install `@genkit-ai/next` as well.
3. Search the codebase for the exact string `genkit(` (remember to escape
regexes properly) which indicates that the user has already set up Genkit in
the codebase. If found, no need to set it up again; tell the user "Genkit is
already configured in this app." and exit this workflow.
4. Create an `ai` directory in the primary source directory of the project (this
may be e.g. `src` but is project-dependent). Adapt this path if your project
uses a different structure.
5. Create `{sourceDir}/ai/genkit.ts` and populate it using the example below. DO
NOT add a `next` plugin to the file, ONLY add a model provider plugin to the
plugins array:
```ts
import { genkit, z } from 'genkit';
// Import your chosen provider plugin here. Example:
import { googleAI } from '@genkit-ai/google-genai';
export const ai = genkit({
plugins: [
googleAI(), // Add your provider plugin here
],
model: googleAI.model('gemini-flash-latest'), // Set your provider's model here
});
export { z };
```
6. Create `{sourceDir}/ai/tools` and `{sourceDir}/ai/flows` directories, but
leave them empty for now.
7. Create `{sourceDir}/ai/index.ts` and populate it with the following (change
the import to match import aliases in `tsconfig.json` as needed):
```ts
import './genkit.js';
// import each created flow, tool, etc. here for use in the Genkit Dev UI
```
8. Add the `genkit-cli` to the project's `devDependencies` (e.g.
`npm install -D genkit-cli`, or the pnpm/yarn/bun equivalent) so the CLI
version is pinned per-project and works in CI, then add a `genkit:dev` script
to `package.json` that runs
`genkit start -- npx tsx --watch {sourceDir}/ai/index.ts`. This is the
recommended way to run the app during development: `genkit start` wraps your
program and captures a trace of every Genkit action (prompts, model I/O, tool
calls) while serving the Dev UI at http://localhost:4000. Running the app
directly (`tsx`/`node`/`npm start`) skips trace capture, so you're debugging
blind. DO NOT try to run the script now.
9. Tell the user "Genkit is now configured and ready for use." Let them know
they can start developing with `npm run genkit:dev` (or the pnpm/yarn/bun
equivalent), which stays running until stopped with Ctrl+C and serves the Dev
UI at http://localhost:4000. Also remind them to set appropriate env
variables (e.g. `GEMINI_API_KEY` for Google providers). Wait for the user to
prompt further before creating any specific flows.
## Next Steps and Troubleshooting
- **Documentation**: Use the [CLI](docs-and-cli.md) to access documentation
(e.g., `genkit docs:search`).
- **Building Flows**: See [examples.md](examples.md) for patterns on creating
flows, adding tools, and advanced configuration.
- **Running & Verifying**: `npm run genkit:dev` is the default dev loop
(persistent, serves the Dev UI). For a quick, non-interactive check that exits
on its own, run a single flow with
`genkit flow:run <flow> '<input>' -- npx tsx {sourceDir}/ai/index.ts` and
inspect it with `genkit trace:get <id>`. See
[docs-and-cli.md](docs-and-cli.md).
- **Troubleshooting**: If you encounter issues during setup or initialization,
check [common-errors.md](common-errors.md) for solutions.
License (Apache-2.0)
Apache-2.0
Source: google/skills
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE