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-state.md

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

Working with Agent State (Beta)

Beta / preview API. Read agents.md first.

Beyond message history, an agent session can hold typed custom state — your own structured data (a task list, a workflow status, counters, etc.). Tools read and mutate it during a turn, and it is automatically synced to the remoteAgent client.


Declare the state shape

Pass a stateSchema (Zod) to defineAgent. State is inferred from it and validated when a snapshot is loaded.

import { z } from 'genkit';
import { ai } from './genkit.js';

const TaskItem = z.object({
  id: z.number(),
  title: z.string(),
  done: z.boolean(),
});

const TaskState = z.object({
  tasks: z.array(TaskItem),
  nextId: z.number(),
});

export const taskAgent = ai.defineAgent({
  name: 'taskAgent',
  stateSchema: TaskState,
  system: 'You manage the user\'s task list. Use the tools to modify it.',
  tools: [
    /* addTask, toggleTask, removeTask - below */
  ],
});

Read and mutate state inside tools

Tools call ai.currentSession<S>() to access the live session, then session.getCustom() / session.updateCustom(mutator). updateCustom takes (custom?: S) => S and returns the new state.

type TaskState = z.infer<typeof TaskState>;

const addTask = ai.defineTool(
  {
    name: 'addTask',
    description: 'Add a new task. Returns the created task.',
    inputSchema: z.object({ title: z.string() }),
    outputSchema: z.object({
      id: z.number(),
      title: z.string(),
      done: z.boolean(),
    }),
  },
  async (input) => {
    const session = ai.currentSession<TaskState>();
    let created!: { id: number; title: string; done: boolean };
    session.updateCustom((state) => {
      const s = state ?? { tasks: [], nextId: 1 };
      created = { id: s.nextId, title: input.title, done: false };
      s.tasks.push(created);
      s.nextId++;
      return s;
    });
    return created;
  }
);

ai.currentSession() throws if called outside an active session (e.g. a tool invoked without a running agent turn), so only use it inside agent tools.

Seed and read state (server-side)

Seed initial custom state when opening a chat. The state argument is a SessionState<S>: custom data goes under .custom (alongside messages and artifacts).

const chat = taskAgent.chat({
  state: {
    custom: { tasks: [], nextId: 1 },
    messages: [],
    artifacts: [],
  },
});

const res = await chat.send('Add a task: buy groceries');
console.log(res.state); // res.state returns the custom state directly

Auto-sync to the remoteAgent client

When you talk to the agent over HTTP, the remoteAgent client tracks custom state for you. Parameterize the client with your state type, seed it the same way (state.custom), and after a turn read it off chat.state.

Important: on the client, custom fields are flattened directly onto chat.state (e.g. chat.state.tasks) — not under chat.state.custom.

import { remoteAgent, type AgentChat } from 'genkit/beta/client';

interface TaskState {
  tasks: { id: number; title: string; done: boolean }[];
  nextId: number;
}

const agent = remoteAgent<TaskState>({ url: '/api/taskAgent' });
const chat: AgentChat<TaskState> = agent.chat({
  state: { custom: { tasks: [], nextId: 1 }, messages: [], artifacts: [] },
});

const turn = chat.sendStream('Add buy groceries, then mark it done');
for await (const chunk of turn.stream) {
  /* render chunk.text */
}
await turn.response;

// Custom state is flattened onto chat.state:
console.log(chat.state?.tasks);

There is no onStateChange subscription — state updates ride on the streamed chunks. Read the authoritative state from chat.state after await turn.response. (For live mid-stream status updates from a custom agent, see advanced custom agents, which emit customPatch chunks as state changes.)

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.