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.

referencesagents-custom.md

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

Advanced Custom Agents — defineCustomAgent (Beta)

Beta / preview API. ai.defineCustomAgent comes from genkit/beta. Read agents.md and agent state 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

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

Signature

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

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 (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:

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;

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.