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

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

Background Agents / Detaching (Beta)

Beta / preview API. Detaching requires a session store — the server needs somewhere to write the result when background work finishes. Read agents.md first.

Detaching runs a turn in the background: the server saves a pending snapshot and returns a snapshotId immediately, keeps processing, then updates the snapshot to a terminal status (completed / failed / aborted / expired). The client polls for completion and can abort.


Define the agent (store required)

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

export const backgroundAgent = ai.defineAgent({
  name: 'backgroundAgent',
  system:
    'You are a senior research analyst. Produce a comprehensive markdown report.',
  store: new InMemorySessionStore(), // REQUIRED for detach
});

Expose its companion actions so the client can poll/abort (see agents.md):

app.post('/api/backgroundAgent', expressHandler(backgroundAgent));
app.post(
  '/api/backgroundAgent/getSnapshot',
  expressHandler(backgroundAgent.getSnapshotDataAction)
);
app.post(
  // Optional (genkit >= 1.43.0): lets remoteAgent's task.wait() block on the
  // server in one request instead of polling getSnapshot.
  '/api/backgroundAgent/waitForSnapshot',
  expressHandler(backgroundAgent.waitForSnapshotAction)
);
app.post(
  '/api/backgroundAgent/abort',
  expressHandler(backgroundAgent.abortAgentAction)
);

Server-side: detach and wait

chat.detach(message) returns a DetachedTask carrying the snapshotId. task.wait() blocks until a terminal state and resolves with the final snapshot. The wait happens next to the store, so there is no polling loop on your side.

const chat = backgroundAgent.chat();
const task = await chat.detach('Write a report on renewable energy trends');
console.log(task.snapshotId); // available immediately

// Bound the wait with an abort signal; the task keeps running if it fires.
const snapshot = await task.wait({ abortSignal: AbortSignal.timeout(60_000) });
console.log(snapshot.status); // 'completed' | 'failed' | 'aborted' | 'expired'

Without a DetachedTask handle, backgroundAgent.waitForSnapshot(snapshotId) does the same from a stored ID.

Resume a failed or aborted task

Requires genkit >= 1.43.0. Earlier versions only resumed completed snapshots.

failed and aborted snapshots hold the conversation up to the last completed tool round, so they are resume points. send({}) (no message, no resume) re-runs the turn without repeating finished tool calls:

const snap = await task.wait();
if (snap.status === 'failed' || snap.status === 'aborted') {
  const retry = await backgroundAgent.loadChat({ snapshotId: snap.snapshotId });
  await retry.send({}); // or retry.send('Try again, but skip X.')
}

Client-side: detach, poll, and abort

On the client (genkit/beta/client), task.poll() yields snapshots until a terminal status; task.abort() cancels the background work.

import { remoteAgent, type DetachedTask } from 'genkit/beta/client';
import type { MessageData, Part } from 'genkit/beta';

const agent = remoteAgent({ url: '/api/backgroundAgent' });

// Submit - resolves immediately with a handle.
const task: DetachedTask = await agent.chat().detach('Quantum computing impact');
console.log(task.snapshotId);

// Poll until a terminal status.
for await (const snap of task.poll({ intervalMs: 2000 })) {
  if (snap.status === 'completed') {
    const messages: MessageData[] = snap.state?.messages ?? [];
    const lastModel = messages.filter((m) => m.role === 'model').at(-1);
    const text = (lastModel?.content ?? [])
      .filter((p: Part) => p.text)
      .map((p: Part) => p.text)
      .join('');
    console.log(text);
    break;
  } else if (snap.status === 'failed') {
    throw new Error('Background task failed on the server.');
  } else if (snap.status === 'aborted') {
    break;
  } else if (snap.status === 'expired') {
    // Worker stopped sending heartbeats (e.g. the server restarted) so the
    // task can never complete - treat as terminal.
    break;
  }
  // 'pending' → keep polling
}

// Abort an in-flight task at any time:
await task.abort();

Status values

  • pending: still processing.
  • aborting: abort() was called; the worker is winding down. Not terminal: wait() keeps waiting until it settles as aborted.
  • completed: completed successfully (read the result from snapshot.state.messages).
  • failed: error during processing. Resumable (see above).
  • aborted: stopped by the caller. Carries the state the run had committed; resumable.
  • expired: the background worker stopped responding (e.g. server restart); terminal, the task can never complete.

Pass metadataOnly: true in the getSnapshot request body to read status without loading the conversation state.

Equivalent low-level wire protocol: the client sends { detach: true } with the message; poll hits the agent's getSnapshot action, wait hits waitForSnapshot (falling back to polling getSnapshot when it is not mounted), and abort hits the abort action. remoteAgent wraps all of this for you.

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.