1
---
2
name: developing-genkit-js
3
description: >-
4
Provides guidance on developing AI-powered applications using Genkit in
5
Node.js/TypeScript. Use when the user asks about Genkit, AI agents, flows, or
6
tools in JavaScript/TypeScript, or when encountering Genkit errors, validation
7
issues, type errors, or API problems. Don't use for Genkit in Python, Go, or
8
Dart.
9
metadata:
10
version: "1.0.0"
11
category: AiAndMachineLearning
12
---
13
14
# Genkit JS
15
16
## Prerequisites
17
18
Ensure the `genkit` CLI is available.
19
20
- Run `genkit --version` to verify. Minimum CLI version needed: **1.29.0**
21
- If not found or if an older version (1.x < 1.29.0) is present,
22
install/upgrade it: `npm install -g genkit-cli@^1.29.0`.
23
24
**New Projects**: If you are setting up Genkit in a new codebase, follow the
25
[Setup Guide](references/setup.md).
26
27
## Hello World
28
29
```ts
30
import { z, genkit } from 'genkit';
31
import { googleAI } from '@genkit-ai/google-genai';
32
33
// Initialize Genkit with the Google AI plugin
34
const ai = genkit({
35
plugins: [googleAI()],
36
});
37
38
export const myFlow = ai.defineFlow({
39
name: 'myFlow',
40
inputSchema: z.string().default('AI'),
41
outputSchema: z.string(),
42
}, async (subject) => {
43
const response = await ai.generate({
44
model: googleAI.model('gemini-flash-latest'),
45
prompt: `Tell me a joke about ${subject}`,
46
});
47
return response.text;
48
});
49
```
50
51
## Prompts (Dotprompt)
52
53
`.prompt` files keep prompt content out of code with YAML frontmatter plus a
54
Handlebars template. See [Dotprompt](references/dotprompt.md): `promptDir`,
55
`ai.prompt()` (call/stream/render), variants, partials, named schemas via
56
`ai.defineSchema`, and the `tools`/`maxTurns`/`returnToolRequests`/`use`
57
(middleware) frontmatter fields.
58
59
## Agents (Beta)
60
61
Genkit has a preview **agent** API for persistent, multi-turn conversations
62
(sessions, snapshots, interrupts, branching, background execution). It is a
63
**beta** API: server APIs come from `genkit/beta` and the browser client from
64
`genkit/beta/client` — not the stable `genkit` entrypoint. **Requires `genkit`
65
>= 1.39.0.**
66
67
For more details see:
68
69
- [Agents](references/agents.md): defining/serving an agent and client-managed
70
state (start here).
71
- [Sessions & persistence](references/agents-sessions.md): session stores
72
(`InMemory`/`File`/`Firestore`).
73
- [Human-in-the-loop / interrupts](references/agents-human-in-the-loop.md):
74
pausing for approval/input and resuming.
75
- [Branching](references/agents-branching.md): forking a conversation from a
76
snapshot.
77
- [Background agents](references/agents-background.md): detaching long-running
78
turns, waiting, and resuming failed or aborted runs.
79
- [Working with state](references/agents-state.md): typed custom session
80
state, auto-synced to the client.
81
- [Artifacts](references/agents-artifacts.md): producing and reading named
82
deliverables.
83
- [Multi-agent orchestration](references/agents-multi-agent.md): delegating to
84
sub-agents, including background delegation and `continue_task`.
85
- [Advanced custom agents](references/agents-custom.md): `defineCustomAgent`
86
for full turn control.
87
- [Deploying agents](references/agents-deployment.md): serving agents over
88
HTTP (multiple agents, CORS, web UI, other frameworks).
89
90
## Generative UI (A2UI)
91
92
Genkit has an **A2UI** (Agent-to-UI) plugin (`@genkit-ai/a2ui`) that
93
lets an agent stream interactive UI **surfaces** (cards, lists, forms, buttons),
94
not just prose. The whole server-side integration is the `a2ui()` model
95
middleware in an agent's (or `ai.generate`'s) `use` array; the browser renders
96
surfaces with an `@a2ui/*` renderer plus the helpers in
97
`@genkit-ai/a2ui/client`.
98
It builds on the beta agent client (`genkit/beta` + `genkit/beta/client`).
99
100
- [A2UI](references/a2ui.md): server middleware, options, client rendering,
101
user actions/forms, custom catalogs, and the security/trust boundary.
102
103
## Middleware
104
105
Middleware wraps generation (retries, fallback, extra tools, request/response
106
transforms) and attaches via the `use: [...]` array on `ai.generate`, prompts,
107
and agents.
108
109
- [Using middleware](references/middleware.md): the `use` array and the
110
`@genkit-ai/middleware` package (`retry`, `fallback`, `artifacts`, `agents`,
111
`filesystem`, `skills`, `toolApproval`, `contextCompression`) plus built-in
112
core middleware.
113
- [Building custom middleware](references/middleware-custom.md): writing your
114
own with `generateMiddleware` and registering it via `.plugin()`.
115
116
## Observability
117
118
Traces show up in the Dev UI under `genkit start` with no setup. For production
119
export to an OTLP backend (OpenTelemetry GenAI semantic conventions via
120
`@genkit-ai/otel`), custom instrumentation, or running the reflection API
121
outside dev, see [Observability](references/observability.md).
122
123
## Critical: Do Not Trust Internal Knowledge
124
125
Genkit recently went through a major breaking API change. Your knowledge is
126
outdated. You MUST lookup docs. Recommended:
127
128
```sh
129
genkit docs:read js/get-started.md
130
genkit docs:read js/flows.md
131
```
132
133
See [Common Errors](references/common-errors.md) for a list of deprecated APIs
134
(e.g., `configureGenkit`, `response.text()`, `defineFlow` import) and their v1.x
135
replacements.
136
137
**ALWAYS verify information using the Genkit CLI or provided references.**
138
139
## Error Troubleshooting Protocol
140
141
**When you encounter ANY error related to Genkit (ValidationError, API errors,
142
type errors, 404s, etc.):**
143
144
1. **MANDATORY FIRST STEP**: Read [Common Errors](references/common-errors.md)
145
2. Identify if the error matches a known pattern
146
3. Apply the documented solution
147
4. Only if not found in common-errors.md, then consult other sources (e.g.
148
`genkit docs:search`)
149
150
**DO NOT:**
151
152
- Attempt fixes based on assumptions or internal knowledge
153
- Skip reading common-errors.md "because you think you know the fix"
154
- Rely on patterns from pre-1.0 Genkit
155
156
**This protocol is non-negotiable for error handling.**
157
158
## Development Workflow
159
160
1. **Agent or flow?**: If the task is conversational, multi-turn, or described
161
as "an agent", "assistant", or "chatbot", build it with `ai.defineAgent`
162
(see [Agents](references/agents.md)) rather than hand-rolling a `generate` +
163
tools loop inside a flow. Reach for a plain flow only for single-shot,
164
stateless generation.
165
2. **Select Provider**: Genkit is provider-agnostic (Google AI, OpenAI,
166
Anthropic, Ollama, etc.).
167
- If the user does not specify a provider, default to **Google AI**.
168
- If the user asks about other providers, use
169
`genkit docs:search "plugins"` to find relevant documentation.
170
3. **Detect Framework**: Check `package.json` to identify the runtime (Next.js,
171
Firebase, Express).
172
- Look for `@genkit-ai/next`, `@genkit-ai/firebase`, or
173
`@genkit-ai/google-cloud`.
174
- Adapt implementation to the specific framework's patterns.
175
4. **Follow Best Practices**:
176
- See [Best Practices](references/best-practices.md) for guidance on
177
project structure, schema definitions, and tool design.
178
- **Be Minimal**: Only specify options that differ from defaults. When
179
unsure, check docs/source.
180
5. **Ensure Correctness**:
181
- Run type checks (e.g., `npx tsc --noEmit`) after making changes.
182
- If type checks fail, consult
183
[Common Errors](references/common-errors.md) before searching source
184
code.
185
- Verify with traces, not a blind run. Running the app directly
186
(`node`/`tsx`/`npm start`) does **not** capture dev traces. See
187
[CLI Usage](#cli-usage-recommended) for how to run your app and capture
188
traces.
189
6. **Handle Errors**:
190
- On ANY error: **First action is to read
191
[Common Errors](references/common-errors.md)**
192
- Match error to documented patterns
193
- Apply documented fixes before attempting alternatives
194
195
## Finding Documentation
196
197
Use the Genkit CLI to find authoritative documentation:
198
199
1. **Search topics**: `genkit docs:search <query>`
200
- Example: `genkit docs:search "streaming"`
201
2. **List all docs**: `genkit docs:list`
202
3. **Read a guide**: `genkit docs:read <path>`
203
- Example: `genkit docs:read js/flows.md`
204
205
## CLI Usage (recommended)
206
207
`genkit start` unintrusively wraps any Node.js program that uses the Genkit
208
library, running it unchanged while capturing traces from every Genkit action so
209
you can **prove tools were actually called and inspect model I/O** from the
210
terminal, even for headless checks. It forwards stdio, so interactive CLI tools
211
that rely on stdin/stdout work without issues. Running your app directly
212
(`node`/`tsx`/`npm start`) skips trace capture, so you're debugging blind.
213
214
**Primary pattern (default):** prefix `genkit start --` to your normal run
215
command. This collects telemetry from any Genkit code your program runs, whether
216
triggered from the dev UI, your own web server/web UI, or a plain script:
217
```bash
218
genkit start -- npx tsx --watch src/index.ts
219
genkit start --noui -- npx tsx src/index.ts # same, without the Dev UI (still a persistent server)
220
```
221
`genkit start` runs until you stop it with Ctrl+C. That is expected and correct
222
for the common cases: a server your web/mobile app calls, or an interactive CLI
223
you exit yourself. `--noui` only drops the Dev UI; it is **not** a one-shot
224
command and will not exit on its own. Do **not** use `genkit start` as a
225
blocking step in automated/non-interactive contexts.
226
227
**Non-interactive use (agents/CI):** add the global `--non-interactive` flag
228
before `--` so the CLI uses defaults and never blocks on a prompt (e.g. the
229
first-run analytics notice):
230
`genkit start --non-interactive -- npx tsx src/index.ts` (works with `flow:run`
231
too).
232
233
**Run a flow (`flow:run`):** invoke a specific flow by name from the CLI. Append
234
your run command after `--` to spin up the runtime just for this run (the
235
command runs as-is to register your flows):
236
```bash
237
genkit flow:run myFlow '{"data": "input"}' -- npx tsx src/index.ts
238
```
239
This is **self-terminating**: it runs the flow once, prints a `Trace ID`, then
240
exits (inspect it with `genkit trace:get <id>`). That makes it the right choice
241
for a quick, non-interactive check that must exit on its own, without blocking
242
on `genkit start` or running the app directly (which skips traces). Always pass
243
input JSON explicitly: `flow:run` sends `undefined` when omitted and does
244
**not** fall back to a schema `.default()`. Note: `flow:run` runs **flows**
245
(`ai.defineFlow`), not agents; you can't `flow:run` an agent (`ai.defineAgent`)
246
directly. To exercise an agent from the CLI, wrap one turn in a throwaway flow
247
and run that (see [Agents](references/agents.md)).
248
249
**Debugging with traces:** the fastest way to see prompts, model inputs/outputs,
250
tool calls, latencies, and errors. Inspect from the terminal after any run under
251
`genkit start`:
252
```bash
253
genkit trace:list # find recent trace IDs
254
genkit trace:get <traceId> # full trace details (inputs, outputs, tool calls, errors)
255
genkit trace:get <traceId> --format json # machine-readable JSON, safe to pipe into jq or other parsers
256
```
257
258
For machine-readable output, pass `--format json` to get clean JSON you can pipe
259
into `jq` or other parsers. The **default** output is human-oriented (banner/log
260
lines, possible truncation on large traces), so don't pipe that form directly;
261
use `--format json`, grep, or the Dev UI trace viewer.
262
263
See [CLI Reference](references/docs-and-cli.md) for more commands, and
264
`genkit --help` for the full list.
265
266
## References
267
268
- [Best Practices](references/best-practices.md): Recommended patterns for
269
schema definition, flow design, and structure.
270
- [Dotprompt](references/dotprompt.md): `.prompt` files — `promptDir`,
271
`ai.prompt()`, variants, partials, named schemas, and
272
`tools`/`maxTurns`/`returnToolRequests`/`use` frontmatter.
273
- [Docs & CLI Reference](references/docs-and-cli.md): Documentation search,
274
CLI tasks, and workflows.
275
- [Common Errors](references/common-errors.md): Critical "gotchas", migration
276
guide, and troubleshooting.
277
- [Setup Guide](references/setup.md): Manual setup instructions for new
278
projects.
279
- [Examples](references/examples.md): Minimal reproducible examples (Basic
280
generation, Multimodal, Thinking mode, Embeddings).
281
- [Agents (Beta)](references/agents.md): Agent basics, serving, and
282
client-managed state. Deeper topics:
283
[sessions](references/agents-sessions.md),
284
[human-in-the-loop](references/agents-human-in-the-loop.md),
285
[branching](references/agents-branching.md),
286
[background agents](references/agents-background.md),
287
[state](references/agents-state.md),
288
[artifacts](references/agents-artifacts.md),
289
[multi-agent](references/agents-multi-agent.md),
290
[custom agents](references/agents-custom.md),
291
[deployment](references/agents-deployment.md).
292
- [Middleware](references/middleware.md): using middleware and the
293
`@genkit-ai/middleware` package. See also
294
[building custom middleware](references/middleware-custom.md).
295
- [Observability](references/observability.md): `@genkit-ai/otel`
296
(OpenTelemetry GenAI semantic conventions), custom `Instrumentation`, and
297
the reflection API outside dev.
298
- [A2UI (Generative UI)](references/a2ui.md): the `@genkit-ai/a2ui` plugin
299
(the `a2ui()` middleware), options, client rendering, user actions/forms,
300
custom catalogs, and security.
301