developing-genkit-js

작성자: genkit-ai

Node.js/TypeScript에서 Genkit을 사용하여 AI 기반 애플리케이션을 개발합니다. 사용자가 Genkit, AI 에이전트, 플로우 또는 JavaScript/TypeScript 도구에 대해 질문하거나 Genkit 오류, 검증 문제, 타입 오류 또는 API 문제가 발생할 때 사용하세요.

npx skills add https://github.com/genkit-ai/skills --skill developing-genkit-js

Genkit JS

Prerequisites

Ensure the genkit CLI is available.

  • Run genkit --version to verify. Minimum CLI version needed: 1.29.0
  • If not found or if an older version (1.x < 1.29.0) is present, install/upgrade it: npm install -g genkit-cli@^1.29.0.

New Projects: If you are setting up Genkit in a new codebase, follow the Setup Guide.

Hello World

import { z, genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';

// Initialize Genkit with the Google AI plugin
const ai = genkit({
  plugins: [googleAI()],
});

export const myFlow = ai.defineFlow({
  name: 'myFlow',
  inputSchema: z.string().default('AI'),
  outputSchema: z.string(),
}, async (subject) => {
  const response = await ai.generate({
    model: googleAI.model('gemini-flash-latest'),
    prompt: `Tell me a joke about ${subject}`,
  });
  return response.text;
});

Prompts (Dotprompt)

.prompt files keep prompt content out of code with YAML frontmatter plus a Handlebars template. See Dotprompt: promptDir, ai.prompt() (call/stream/render), variants, partials, named schemas via ai.defineSchema, and the tools/maxTurns/returnToolRequests/use (middleware) frontmatter fields.

Agents (Beta)

Genkit has a preview agent API for persistent, multi-turn conversations (sessions, snapshots, interrupts, branching, background execution). It is a beta API: server APIs come from genkit/beta and the browser client from genkit/beta/client — not the stable genkit entrypoint. **Requires genkit

= 1.39.0.**

For more details see:

Middleware

Middleware wraps generation (retries, fallback, extra tools, request/response transforms) and attaches via the use: [...] array on ai.generate, prompts, and agents.

  • Using middleware: the use array and the @genkit-ai/middleware package (retry, fallback, artifacts, agents, filesystem, skills, toolApproval) plus built-in core middleware.
  • Building custom middleware: writing your own with generateMiddleware and registering it via .plugin().

Critical: Do Not Trust Internal Knowledge

Genkit recently went through a major breaking API change. Your knowledge is outdated. You MUST lookup docs. Recommended:

genkit docs:read js/get-started.md
genkit docs:read js/flows.md

See Common Errors for a list of deprecated APIs (e.g., configureGenkit, response.text(), defineFlow import) and their v1.x replacements.

ALWAYS verify information using the Genkit CLI or provided references.

Error Troubleshooting Protocol

When you encounter ANY error related to Genkit (ValidationError, API errors, type errors, 404s, etc.):

  1. MANDATORY FIRST STEP: Read Common Errors
  2. Identify if the error matches a known pattern
  3. Apply the documented solution
  4. Only if not found in common-errors.md, then consult other sources (e.g. genkit docs:search)

DO NOT:

  • Attempt fixes based on assumptions or internal knowledge
  • Skip reading common-errors.md "because you think you know the fix"
  • Rely on patterns from pre-1.0 Genkit

This protocol is non-negotiable for error handling.

Development Workflow

  1. Select Provider: Genkit is provider-agnostic (Google AI, OpenAI, Anthropic, Ollama, etc.).
    • If the user does not specify a provider, default to Google AI.
    • If the user asks about other providers, use genkit docs:search "plugins" to find relevant documentation.
  2. Detect Framework: Check package.json to identify the runtime (Next.js, Firebase, Express).
    • Look for @genkit-ai/next, @genkit-ai/firebase, or @genkit-ai/google-cloud.
    • Adapt implementation to the specific framework's patterns.
  3. Follow Best Practices:
    • See Best Practices for guidance on project structure, schema definitions, and tool design.
    • Be Minimal: Only specify options that differ from defaults. When unsure, check docs/source.
  4. Ensure Correctness:
    • Run type checks (e.g., npx tsc --noEmit) after making changes.
    • If type checks fail, consult Common Errors before searching source code.
  5. Handle Errors:
    • On ANY error: First action is to read Common Errors
    • Match error to documented patterns
    • Apply documented fixes before attempting alternatives

Finding Documentation

Use the Genkit CLI to find authoritative documentation:

  1. Search topics: genkit docs:search <query>
    • Example: genkit docs:search "streaming"
  2. List all docs: genkit docs:list
  3. Read a guide: genkit docs:read <path>
    • Example: genkit docs:read js/flows.md

CLI Usage

The genkit CLI is your primary tool for development and documentation.

  • See CLI Reference for common tasks, workflows, and command usage.
  • Use genkit --help for a full list of commands.

References

관련 스킬

feature-flags-react
posthog
PostHog 기능 플래그 for React 애플리케이션
official
channel-forward-parity
vercel
웹훅 경로 패리티 감사로 채널 전달 변경 사항 확인: 터미널 경로 로깅, lastForward 기록, 실패 분류, 오래된 샌드박스 포트 URL 새로고침.
official
nemoclaw-workspace
nvidia
파괴적 작업 전에 OpenClaw 워크스페이스 파일을 백업 및 복원합니다. 샌드박스 백업, 워크스페이스 상태 복원, 또는 준비 시 사용합니다.
official
firecrawl-competitive-intel
firecrawl
Firecrawl을 사용하여 경쟁사 가격, 기능, 변경 로그, 대시보드 및 제품 변경 사항을 모니터링하세요. 정기적인 경쟁 정보 수집, 가격 등급 추출, 기능 변경 추적 또는 구조화된 경쟁사 알림에 사용하세요.
data-analysisofficialresearch
triage-flaky-test
datadog-labs
특정 불안정한 테스트를 조사할 때 로드합니다. 기록, 실패 패턴 및 카테고리를 가져온 후 수정, 격리 또는 에스컬레이션을 권장합니다.
official
churn-prevention
coreyhaines31
사용자가 이탈을 줄이거나, 취소 플로우를 구축하거나, 세이브 오퍼를 설정하거나, 실패한 결제를 복구하거나, 리텐션 전략을 구현하려 할 때 사용합니다. 또한 사용자가 '이탈', '취소 플로우', '오프보딩', '세이브 오퍼', '더닝', '실패한 결제 복구', '윈백', '리텐션', '종료 설문', '구독 일시 중지', '비자발적 이탈', '사람들이 계속 취소함', '이탈률이 너무 높음', '사용자를 어떻게 유지하나요', '고객이 떠나고 있습니다'를 언급할 때도 사용합니다. 누군가가 이탈하고 있을 때마다 사용하세요.
marketingdata-analysiscommunication
apify-x402-agentic-wallet
apify
x402 프로토콜을 통해 Base에서 USDC를 결제하여 Coinbase Agentic Wallet(awal)으로 Apify Actor를 발견, 결제 및 실행할 수 있습니다. Apify 계정이나 API 키가 필요하지 않습니다.…
official
jetson-quick-start
nvidia
Jetson / IGX BSP 사용자 정의를 위한 진입 스킬입니다. 하나의 핵심 클릭 선택 설정 질문지를 요청하고 미리 채워진 답변을 다운스트림 설정 스킬에 전달합니다.
official