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.
Hello World
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: 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: defining/serving an agent and client-managed state (start here).
- Sessions & persistence: session stores (
InMemory/File/Firestore).
- Human-in-the-loop / interrupts: pausing for approval/input and resuming.
- Branching: forking a conversation from a snapshot.
- Background agents: detaching long-running turns and polling.
- Working with state: typed custom session state, auto-synced to the client.
- Artifacts: producing and reading named deliverables.
- Multi-agent orchestration: delegating to sub-agents.
- Advanced custom agents:
defineCustomAgent for full turn control.
- Deploying agents: serving agents over HTTP (multiple agents, CORS, web UI, other frameworks).
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: the
use array and the @genkit-ai/middleware package (retry, fallback, artifacts, agents, filesystem, skills, toolApproval) plus built-in core middleware.
- Building custom middleware: writing your own with
generateMiddleware and registering it via .plugin().
Critical: Do Not Trust Internal Knowledge
Genkit recently went through a major breaking API change. Your knowledge is outdated. You MUST lookup docs. Recommended:
genkit docs:read js/get-started.md
genkit docs:read js/flows.md
See Common Errors 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.):
- MANDATORY FIRST STEP: Read Common Errors
- Identify if the error matches a known pattern
- Apply the documented solution
- 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
- 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.
- 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.
- Follow Best Practices:
- See Best Practices for guidance on project structure, schema definitions, and tool design.
- Be Minimal: Only specify options that differ from defaults. When unsure, check docs/source.
- Ensure Correctness:
- Run type checks (e.g.,
npx tsc --noEmit) after making changes.
- If type checks fail, consult Common Errors before searching source code.
- Handle Errors:
- On ANY error: First action is to read Common Errors
- Match error to documented patterns
- Apply documented fixes before attempting alternatives
Finding Documentation
Use the Genkit CLI to find authoritative documentation:
- Search topics:
genkit docs:search <query>
- Example:
genkit docs:search "streaming"
- List all docs:
genkit docs:list
- Read a guide:
genkit docs:read <path>
- Example:
genkit docs:read js/flows.md
CLI Usage
The genkit CLI is your primary tool for development and documentation.
- See CLI Reference for common tasks, workflows, and command usage.
- Use
genkit --help for a full list of commands.
References
- Best Practices: Recommended patterns for schema definition, flow design, and structure.
- Dotprompt:
.prompt files — promptDir, ai.prompt(), variants, partials, named schemas, and tools/maxTurns/returnToolRequests/use frontmatter.
- Docs & CLI Reference: Documentation search, CLI tasks, and workflows.
- Common Errors: Critical "gotchas", migration guide, and troubleshooting.
- Setup Guide: Manual setup instructions for new projects.
- Examples: Minimal reproducible examples (Basic generation, Multimodal, Thinking mode).
- Agents (Beta): Agent basics, serving, and client-managed state. Deeper topics: sessions, human-in-the-loop, branching, background agents, state, artifacts, multi-agent, custom agents, deployment.
- Middleware: using middleware and the
@genkit-ai/middleware package. See also building custom middleware.
1---2name: developing-genkit-js3description: Develop 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.4---56# Genkit JS78## Prerequisites910Ensure the `genkit` CLI is available.11- Run `genkit --version` to verify. Minimum CLI version needed: **1.29.0**12- 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`.1314**New Projects**: If you are setting up Genkit in a new codebase, follow the [Setup Guide](references/setup.md).1516## Hello World1718```ts19import { z, genkit } from 'genkit';20import { googleAI } from '@genkit-ai/google-genai';2122// Initialize Genkit with the Google AI plugin23const ai = genkit({24 plugins: [googleAI()],25});2627export const myFlow = ai.defineFlow({28 name: 'myFlow',29 inputSchema: z.string().default('AI'),30 outputSchema: z.string(),31}, async (subject) => {32 const response = await ai.generate({33 model: googleAI.model('gemini-flash-latest'),34 prompt: `Tell me a joke about ${subject}`,35 });36 return response.text;37});38```3940## Prompts (Dotprompt)4142`.prompt` files keep prompt content out of code with YAML frontmatter plus a43Handlebars template. See [Dotprompt](references/dotprompt.md): `promptDir`,44`ai.prompt()` (call/stream/render), variants, partials, named schemas via45`ai.defineSchema`, and the `tools`/`maxTurns`/`returnToolRequests`/`use`46(middleware) frontmatter fields.4748## Agents (Beta)4950Genkit has a preview **agent** API for persistent, multi-turn conversations51(sessions, snapshots, interrupts, branching, background execution). It is a52**beta** API: server APIs come from `genkit/beta` and the browser client from53`genkit/beta/client` — not the stable `genkit` entrypoint. **Requires `genkit`54>= 1.39.0.**5556For more details see:5758- [Agents](references/agents.md): defining/serving an agent and client-managed state (start here).59- [Sessions & persistence](references/agents-sessions.md): session stores (`InMemory`/`File`/`Firestore`).60- [Human-in-the-loop / interrupts](references/agents-human-in-the-loop.md): pausing for approval/input and resuming.61- [Branching](references/agents-branching.md): forking a conversation from a snapshot.62- [Background agents](references/agents-background.md): detaching long-running turns and polling.63- [Working with state](references/agents-state.md): typed custom session state, auto-synced to the client.64- [Artifacts](references/agents-artifacts.md): producing and reading named deliverables.65- [Multi-agent orchestration](references/agents-multi-agent.md): delegating to sub-agents.66- [Advanced custom agents](references/agents-custom.md): `defineCustomAgent` for full turn control.67- [Deploying agents](references/agents-deployment.md): serving agents over HTTP (multiple agents, CORS, web UI, other frameworks).6869## Middleware7071Middleware wraps generation (retries, fallback, extra tools, request/response72transforms) and attaches via the `use: [...]` array on `ai.generate`, prompts,73and agents.7475- [Using middleware](references/middleware.md): the `use` array and the `@genkit-ai/middleware` package (`retry`, `fallback`, `artifacts`, `agents`, `filesystem`, `skills`, `toolApproval`) plus built-in core middleware.76- [Building custom middleware](references/middleware-custom.md): writing your own with `generateMiddleware` and registering it via `.plugin()`.7778## Critical: Do Not Trust Internal Knowledge7980Genkit recently went through a major breaking API change. Your knowledge is outdated. You MUST lookup docs. Recommended:8182```sh83genkit docs:read js/get-started.md84genkit docs:read js/flows.md85```8687See [Common Errors](references/common-errors.md) for a list of deprecated APIs (e.g., `configureGenkit`, `response.text()`, `defineFlow` import) and their v1.x replacements.8889**ALWAYS verify information using the Genkit CLI or provided references.**9091## Error Troubleshooting Protocol9293**When you encounter ANY error related to Genkit (ValidationError, API errors, type errors, 404s, etc.):**94951. **MANDATORY FIRST STEP**: Read [Common Errors](references/common-errors.md)962. Identify if the error matches a known pattern973. Apply the documented solution984. Only if not found in common-errors.md, then consult other sources (e.g. `genkit docs:search`)99100**DO NOT:**101- Attempt fixes based on assumptions or internal knowledge102- Skip reading common-errors.md "because you think you know the fix"103- Rely on patterns from pre-1.0 Genkit104105**This protocol is non-negotiable for error handling.**106107## Development Workflow1081091. **Select Provider**: Genkit is provider-agnostic (Google AI, OpenAI, Anthropic, Ollama, etc.).110 - If the user does not specify a provider, default to **Google AI**.111 - If the user asks about other providers, use `genkit docs:search "plugins"` to find relevant documentation.1122. **Detect Framework**: Check `package.json` to identify the runtime (Next.js, Firebase, Express).113 - Look for `@genkit-ai/next`, `@genkit-ai/firebase`, or `@genkit-ai/google-cloud`.114 - Adapt implementation to the specific framework's patterns.1153. **Follow Best Practices**:116 - See [Best Practices](references/best-practices.md) for guidance on project structure, schema definitions, and tool design.117 - **Be Minimal**: Only specify options that differ from defaults. When unsure, check docs/source.1184. **Ensure Correctness**:119 - Run type checks (e.g., `npx tsc --noEmit`) after making changes.120 - If type checks fail, consult [Common Errors](references/common-errors.md) before searching source code.1215. **Handle Errors**:122 - On ANY error: **First action is to read [Common Errors](references/common-errors.md)**123 - Match error to documented patterns124 - Apply documented fixes before attempting alternatives125126## Finding Documentation127128Use the Genkit CLI to find authoritative documentation:1291301. **Search topics**: `genkit docs:search <query>`131 - Example: `genkit docs:search "streaming"`1322. **List all docs**: `genkit docs:list`1333. **Read a guide**: `genkit docs:read <path>`134 - Example: `genkit docs:read js/flows.md`135136## CLI Usage137138The `genkit` CLI is your primary tool for development and documentation.139- See [CLI Reference](references/docs-and-cli.md) for common tasks, workflows, and command usage.140- Use `genkit --help` for a full list of commands.141142## References143144- [Best Practices](references/best-practices.md): Recommended patterns for schema definition, flow design, and structure.145- [Dotprompt](references/dotprompt.md): `.prompt` files — `promptDir`, `ai.prompt()`, variants, partials, named schemas, and `tools`/`maxTurns`/`returnToolRequests`/`use` frontmatter.146- [Docs & CLI Reference](references/docs-and-cli.md): Documentation search, CLI tasks, and workflows.147- [Common Errors](references/common-errors.md): Critical "gotchas", migration guide, and troubleshooting.148- [Setup Guide](references/setup.md): Manual setup instructions for new projects.149- [Examples](references/examples.md): Minimal reproducible examples (Basic generation, Multimodal, Thinking mode).150- [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).151- [Middleware](references/middleware.md): using middleware and the `@genkit-ai/middleware` package. See also [building custom middleware](references/middleware-custom.md).