Genkit AI Framework
Genkit is an open-source AI framework developed by Google (initially from Firebase) designed to streamline the building, deployment, and monitoring of AI-powered applications. The JavaScript/TypeScript SDK is currently at a stable production-ready version, `1.32.0`, with frequent minor and patch releases, often introducing new model support and features (e.g., `1.33.0-rc.0` is a recent release candidate). Genkit offers a unified interface for integrating with a wide array of generative AI model providers, including Google AI (Gemini, Imagen), Vertex AI, Anthropic, OpenAI, and local models via Ollama. Its key differentiators include a code-centric approach to defining AI flows, built-in observability with automatic tracing and logging, structured output generation with Zod schema validation, tool calling, Retrieval-Augmented Generation (RAG) capabilities, and comprehensive local development tools like a CLI and a web-based Developer UI for interactive testing and debugging. It aims to simplify the development lifecycle of complex AI applications and supports flexible deployment to various environments.
Common errors
-
Error: Cannot find module '@genkit-ai/google-genai' or its corresponding type declarations.
cause The `@genkit-ai/google-genai` package has not been installed in the project.fixInstall the package using npm: `npm install @genkit-ai/google-genai`. -
Error: Genkit configuration error: GOOGLE_API_KEY environment variable is not set.
cause The `apiKey` for the `googleGenai` plugin (or other model plugins) is missing, often due to a forgotten environment variable.fixSet the `GOOGLE_API_KEY` environment variable in your shell (`export GOOGLE_API_KEY='your-key'`), in a `.env` file, or pass it directly in the `googleGenai` plugin configuration. -
ZodError: [ { "code": "invalid_type", "expected": "string", "received": "number", "path": [ "mainIngredient" ], "message": "Expected string, received number" } ]cause Input provided to a Genkit flow (or model with structured input) does not conform to its defined Zod schema.fixReview the `inputSchema` definition for the flow or model. Ensure the data passed to the flow or model's `generate` call strictly matches the expected types and structure.
Warnings
- deprecated The `@genkit-ai/googleai` and `@genkit-ai/vertexai` packages for model plugins are deprecated. Users should migrate to `@genkit-ai/google-genai` for all Google Generative AI models (Gemini, Imagen, etc.).
- deprecated Some specific Imagen and Veo models within the Google GenAI plugin have been deprecated. Users relying on these models may experience errors or reduced functionality.
- breaking Genkit JavaScript SDK updated its core TypeScript dependency to `5.9.3`. Projects using older TypeScript versions might encounter compilation issues or type mismatches.
- gotcha The introduction of `generate middleware` and the new `@genkit-ai/middleware` package in v1.33.0-rc.0 signifies a new pattern for modifying `generate()` calls. Existing custom middleware or direct manipulation of generation context might need to be refactored.
Install
-
npm install genkit -
yarn add genkit -
pnpm add genkit
Imports
- configureGenkit
const configureGenkit = require('genkit').configureGenkitimport { configureGenkit } from 'genkit' - defineFlow
import { defineFlow } from '@genkit-ai/core'import { defineFlow } from 'genkit' - googleGenai
import { googleAI } from '@genkit-ai/googleai'import { googleGenai } from '@genkit-ai/google-genai'
Quickstart
import { configureGenkit, defineFlow, generate } from 'genkit';
import { googleGenai } from '@genkit-ai/google-genai';
import * as z from 'zod';
// Ensure you have `npm install genkit @genkit-ai/google-genai zod`
// And set GOOGLE_API_KEY as an environment variable (e.g., in .env or your shell)
// e.g., export GOOGLE_API_KEY='your-api-key'
// Configure Genkit with a plugin for Google Generative AI
configureGenkit({
plugins: [
googleGenai({
apiKey: process.env.GOOGLE_API_KEY ?? '',
}),
],
logLevel: 'debug',
enableTracingAndMetrics: true,
});
// Define input and output schemas using Zod for type safety
const RecipeInputSchema = z.object({
mainIngredient: z.string().describe('The primary ingredient for the recipe.'),
dietaryRestrictions: z.string().optional().describe('Any dietary restrictions (e.g., vegetarian, gluten-free).'),
});
const RecipeOutputSchema = z.object({
title: z.string().describe('The title of the recipe.'),
ingredients: z.array(z.string()).describe('List of ingredients.'),
instructions: z.array(z.string()).describe('Step-by-step cooking instructions.'),
prepTimeMinutes: z.number().int().positive().describe('Preparation time in minutes.'),
});
// Define a Genkit flow to generate a recipe
export const recipeGeneratorFlow = defineFlow(
{
name: 'recipeGenerator',
inputSchema: RecipeInputSchema,
outputSchema: RecipeOutputSchema,
description: 'Generates a recipe based on a main ingredient and dietary restrictions.',
},
async ({ mainIngredient, dietaryRestrictions }) => {
const prompt = `Create a detailed recipe with ${mainIngredient} as the main ingredient.`;
const restrictionsPrompt = dietaryRestrictions ? ` It must be ${dietaryRestrictions}.` : '';
const fullPrompt = prompt + restrictionsPrompt + ` Respond in JSON format strictly following the provided schema.`;
const response = await generate({
model: googleGenai.model('gemini-1.5-flash'), // Use a suitable Gemini model
prompt: fullPrompt,
output: { schema: RecipeOutputSchema },
config: { temperature: 0.7 },
});
if (!response.output) {
throw new Error('Failed to generate recipe output.');
}
return response.output;
}
);
// To run this flow in development, you would typically use 'genkit start'
// and interact via the Developer UI at http://localhost:4000/ or make HTTP calls.
// Example of direct execution (for testing or serverless functions):
async function runExample() {
console.log('Running recipeGeneratorFlow...');
try {
const recipe = await recipeGeneratorFlow({
mainIngredient: 'chicken',
dietaryRestrictions: 'low-carb'
});
console.log('Generated Recipe:', JSON.stringify(recipe, null, 2));
} catch (error) {
console.error('Flow failed:', error);
}
}
runExample();