Developing Genkit JS
GoogleOfficialPublished by Google
- Skill
- Tool integration
- Software development
- Apache-2.0
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
Genkit is a framework for building AI-powered applications in Node.js and TypeScript. This skill provides guidance on using Genkit to define flows, create persistent agents, manage prompts with Dotprompt, and integrate generative UI (A2UI). It emphasizes a strict troubleshooting protocol for handling errors and recommends using the Genkit CLI for development, tracing, and debugging.
What it does
- Defines AI flows and persistent multi-turn agents.
- Manages prompts using Dotprompt files with YAML frontmatter.
- Integrates generative UI surfaces via the A2UI plugin.
- Provides middleware for retries, fallbacks, and artifact management.
- Captures traces and observability data via the Genkit CLI.
- Supports troubleshooting through a mandatory common-errors review protocol.
When to use it
- When building AI agents or conversational assistants in Node.js/TypeScript.
- When you need to implement multi-turn sessions, human-in-the-loop, or background execution.
- When you need to separate prompt logic from application code.
- When you encounter Genkit-related errors, validation issues, or API problems.
- When you need to inspect model I/O and tool calls via traces.
Advantages
- Provider-agnostic design supports various AI models.
- Built-in observability and trace capture via the CLI.
- Structured approach to agent state and persistence.
- Separation of concerns through middleware and Dotprompt.
- Interactive UI capabilities via A2UI.
Usage examples
- “How do I define a simple flow in Genkit?”
- The agent provides a code snippet using ai.defineFlow with inputSchema and outputSchema, demonstrating how to call ai.generate.
- “I am getting a validation error in my Genkit agent. What should I do?”
- The agent instructs you to first check references/common-errors.md to identify if the error matches a known pattern before attempting any other fix.
- “How can I run my Genkit app and see traces?”
- The agent explains how to use 'genkit start -- npx tsx src/index.ts' to capture telemetry and inspect traces in the Dev UI.
- “How do I add generative UI to my agent?”
- The agent explains installing @genkit-ai/a2ui and adding the a2ui() middleware to the agent's use array.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/google/developing-genkit-js/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip developing-genkit-js.zip -d .agents/skills
Documentation by Google
Genkit JS
Prerequisites
Ensure the genkit CLI is available.
Run
genkit --versionto verify. Minimum CLI version needed: 1.29.0If 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, waiting, and resuming failed or aborted runs.
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, including background delegation and
continue_task.Advanced custom agents:
defineCustomAgentfor full turn control.Deploying agents: 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: 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: the
usearray and the@genkit-ai/middlewarepackage (retry,fallback,artifacts,agents,filesystem,skills,toolApproval,contextCompression) plus built-in core middleware.Building custom middleware: writing your own with
generateMiddlewareand 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.
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.mdSee 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
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) rather than hand-rolling agenerate+ tools loop inside a flow. Reach for a plain flow only for single-shot, stateless generation.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.jsonto 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.
Verify with traces, not a blind run. Running the app directly (
node/tsx/npm start) does not capture dev traces. See CLI Usage for how to run your app and capture traces.
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:listRead 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:
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):
genkit flow:run myFlow '{"data": "input"}' -- npx tsx src/index.tsThis 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).
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:
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 parsersFor 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 for more commands, and genkit --help for the full list.
References
Best Practices: Recommended patterns for schema definition, flow design, and structure.
Dotprompt:
.promptfiles —promptDir,ai.prompt(), variants, partials, named schemas, andtools/maxTurns/returnToolRequests/usefrontmatter.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, Embeddings).
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/middlewarepackage. See also building custom middleware.Observability:
@genkit-ai/otel(OpenTelemetry GenAI semantic conventions), customInstrumentation, and the reflection API outside dev.A2UI (Generative UI): the
@genkit-ai/a2uiplugin (thea2ui()middleware), options, client rendering, user actions/forms, custom catalogs, and security.
Files
- ATTRIBUTION.mdAdded by AutoGineer858 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md12.8 KiB
- references/a2ui.md11.9 KiB
- references/agents-artifacts.md3.3 KiB
- references/agents-background.md5.2 KiB
- references/agents-branching.md3.2 KiB
- references/agents-custom.md5.0 KiB
- references/agents-deployment.md6.0 KiB
- references/agents-human-in-the-loop.md6.4 KiB
- references/agents-multi-agent.md7.8 KiB
- references/agents-sessions.md5.0 KiB
- references/agents-state.md3.9 KiB
- references/agents.md10.0 KiB
- references/best-practices.md1.7 KiB
- references/common-errors.md6.4 KiB
- references/docs-and-cli.md5.3 KiB
- references/dotprompt.md5.2 KiB
- references/examples.md5.2 KiB
- references/middleware-custom.md3.2 KiB
- references/middleware.md6.1 KiB
- references/observability.md5.2 KiB
- references/setup.md4.2 KiB
references/a2ui.md
A2UI (Agent-to-UI) generative UI
The @genkit-ai/a2ui plugin brings
A2UI, a transport-agnostic, JSON-based streaming UI protocol, to Genkit agents.
A2UI builds on the agent client, so it uses the agent APIs:
genkit/betaon the server andgenkit/beta/clientin the browser. Read Agents 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
npm i @genkit-ai/a2uiTo render surfaces in the browser you also need a renderer. A2UI ships renderers
for @a2ui/lit,
@a2ui/react, and
@a2ui/angular. The examples here
use Lit:
npm i @a2ui/lit @a2ui/web_core @a2ui/markdown-it lit @lit/contextServer: 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: [...] }).
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:
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); 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:
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
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.
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 turnremoteAgent 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:
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:
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:
Bind each input's
valueto a data-model path ({ "path": "/email" }).Echo those same paths in the submit
Button'saction.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).Textheadingvariants render as Markdown; without a renderer, headings show as literal##.The Material Symbols Outlined font. The
Iconcomponent renders names as font ligatures; without the font, icon names show as literal text. Load it in your 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:
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 ascatalogIdoncreateSurface).components[]: each withname(matches the renderer type),description(one-line summary), andprops(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:
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):
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-srcand 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():
Injects the catalog's capabilities into the system prompt (unless
instructions: 'none').Intercepts the model output (streamed chunks and the final message).
Extracts
a2uifenced code blocks from the model's text.Validates them against the catalog (per
validate).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.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Publisher
- Google (Official)
- Source
- google/skills · skills/cloud/developing-genkit-js · commit 2194d3b
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Google.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download developing-genkit-js.zip