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

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

Agent Sessions & Persistence (Beta)

Beta / preview API. Session stores are imported from genkit/beta (InMemorySessionStore, FileSessionStore) and @genkit-ai/google-cloud/beta (FirestoreSessionStore). See agents.md for the basics first.

When an agent has a store, the server owns the session history. Each turn produces an immutable snapshot; the snapshot chain is what carries conversation state forward. A store also enables branching and background execution. (Interrupts work with or without a store — see human-in-the-loop.)


Pick a store

import { InMemorySessionStore, FileSessionStore } from 'genkit/beta';

// In-memory: great for tests/dev; lost on restart.
const memStore = new InMemorySessionStore();

// File-backed: snapshots persisted under <dir>/global/<snapshotId>.json
const fileStore = new FileSessionStore('./.snapshots');

// File store with chain pruning - keep only the last N snapshots in a chain.
const pruning = new FileSessionStore('./.snapshots', {
  maxPersistedChainLength: 3,
});

Attach it to the agent:

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

export const logbookAgent = ai.defineAgent({
  name: 'logbookAgent',
  system: 'You are a personal logbook assistant.',
  store: fileStore,
});

A single chat persists to the store and threads the snapshot forward automatically:

const chat = logbookAgent.chat();
const res1 = await chat.send('Log this: I started studying Genkit today.');
const res2 = await chat.send('What did I study today?'); // remembers turn 1
console.log(res1.snapshotId, res2.snapshotId);

Resume a prior conversation by snapshot id:

// Continue an existing session from its latest snapshot.
const resumed = logbookAgent.chat({ snapshotId: res2.snapshotId });
await resumed.send('Add another note.');

Typed session state

Use stateSchema to attach typed custom state to the session. State is inferred from the schema and validated when a snapshot is loaded.

import { z } from 'genkit';

const Profile = z.object({ name: z.string(), tier: z.enum(['free', 'pro']) });

export const profileAgent = ai.defineAgent({
  name: 'profileAgent',
  system: 'Greet the user by name and tailor answers to their tier.',
  store: new InMemorySessionStore<z.infer<typeof Profile>>(),
  stateSchema: Profile,
});

// Seed custom state when opening the chat. Custom state lives under `.custom`
// of the `SessionState` (that's what `stateSchema` validates).
const chat = profileAgent.chat({
  state: { custom: { name: 'Ada', tier: 'pro' } },
});

Interrupts (human-in-the-loop)

Interrupts pause a turn so a human can approve/provide input, then resume from the exact pause point. They work with a store or with client-managed state (persistence is orthogonal). See the dedicated reference: Human-in-the-loop / interrupts.

Firestore session store (scalable, Beta)

For production, FirestoreSessionStore (from @genkit-ai/google-cloud/beta) persists each turn as an incremental JSON Patch diff anchored to periodic sharded checkpoints — no single document approaches Firestore's 1 MiB limit, and reads/writes per turn are bounded by checkpointInterval rather than total session length (scales to long-lived chat/coding agents).

import { genkit } from 'genkit/beta';
import { FirestoreSessionStore } from '@genkit-ai/google-cloud/beta';

const ai = genkit({ plugins: [/* ... */] });

const myAgent = ai.defineAgent({
  name: 'myAgent',
  system: 'You are a helpful assistant.',
  // Defaults to a new Firestore() using Application Default Credentials.
  store: new FirestoreSessionStore(),
});

Options:

  • db: explicit Firestore instance (defaults to a new Firestore(), honoring FIRESTORE_EMULATOR_HOST).
  • collection: snapshot collection (default "genkit-sessions"). Companion collections "<collection>-pointers" and "<collection>-shards" are derived.
  • checkpointInterval: turns between full-state checkpoints (default 25). Lower for small, read-heavy state; raise for large per-turn state.
  • shardSize: max bytes per shard/diff document (default 512 KiB).

On Firebase, @genkit-ai/firebase re-exports this store with Firebase app setup (a firebaseApp option). See its README.

Implementing a custom SessionStore

import type { SessionStore } from 'genkit/beta';

// S is the custom state type.
const store: SessionStore<MyState> = {
  // Load a snapshot by snapshotId OR sessionId (exactly one).
  async getSnapshot(opts) {
    /* ... */ return undefined;
  },
  // Atomically read → mutate → persist. Returns the snapshotId used,
  // or null when the mutator returns null.
  async saveSnapshot(snapshotId, mutator, options) {
    /* ... */ return snapshotId ?? 'new-id';
  },
  // Optional: subscribe to snapshot state changes (used by background agents).
  onSnapshotStateChange(snapshotId, callback, options) {
    return () => {}; // unsubscribe
  },
};

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.