Index of every page on this site: llms.txt
All skills
genkit-ai avatar

/developing-genkit-js

@d12c988
by Genkitgenkit-ai/skills40 stars
13
Run it yourself

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.

Use this Skill: https://skilld.dev/gh/genkit-ai/skills/developing-genkit-js

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesmiddleware.md

≈1.6k tokens on demand. Your agent reads this file only when SKILL.md points to it.

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).

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:

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.


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.

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

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.

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.

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.

artifacts({ readonly: false }); // readonly true → read_artifact only

See working with artifacts.

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).

agents({ agents: ['researcher', 'coder'], maxDelegations: 5, async: true });

See multi-agent orchestration.

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.

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.

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.

skills({ skillPaths: ['skills'] }); // default ['skills']

toolApproval(options)

Restricts tool execution to an approved list; throws a ToolInterruptError for anything else (resumable via interrupts).

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.
import { simulateConstrainedGeneration } from 'genkit/model/middleware';

await ai.generate({
  model: someModel,
  prompt: '...',
  use: [simulateConstrainedGeneration()],
});

To write your own, see building custom middleware.

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts13d5 checks · Risk SAFE
  • Gen Agent Trust Hub14d

    The skill is a comprehensive development guide for the Genkit JS framework. It provides technical instructions, code examples, and troubleshooting steps. All referenced tools and packages are official or standard industry dependencies. No security risks were identified.

  • Socket13d

    No alerts

  • Snyk14d

    Risk: LOW · No issues

  • Runlayer8mo

    6 files scanned · No issues

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at d12c988. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated 2 weeks ago
metadata
{
  "version": "1.0.0",
  "category": "AiAndMachineLearning"
}
  • TypeScript
  • genkit
  • nodejs
  • ai-agents
  • flows
  • llm
  • google-ai
  • openai
  • anthropic

README badge

README badge for genkit-ai/skills/developing-genkit-js

Develop AI-powered applications using Genkit in Node.js and TypeScript, including flows, tools, and multi-model integrations. Covers Genkit CLI setup, flow definition with schema validation, provider selection (Google AI, OpenAI, Anthropic, Ollama), and error troubleshooting for version 1.29.0 and later.

Generated from the current SKILL.md.

What Genkit CLI version does this skill require?
Minimum CLI version 1.29.0. Verify with `genkit --version` and upgrade with `npm install -g genkit-cli@^1.29.0` if needed.
Does this skill cover pre-1.0 Genkit or older versions?
No. Genkit went through a major breaking API change. This skill assumes v1.x (1.29.0+) and will not reliably handle pre-1.0 code or deprecated APIs.
What AI providers does this skill support?
Genkit is provider-agnostic and supports Google AI, OpenAI, Anthropic, Ollama, and others. The skill defaults to Google AI if no provider is specified.
How should I troubleshoot Genkit errors?
Always read the Common Errors reference first to identify known patterns and their fixes. Use `genkit docs:search` only if the error is not documented there.
Does this skill work with Next.js, Firebase, or Express?
Yes. The skill detects your framework via package.json and adapts the implementation to framework-specific patterns like @genkit-ai/next or @genkit-ai/firebase.

Generated from the current SKILL.md. These answers refresh after source changes.