Genkit AI Framework

1.32.0 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up Genkit with the Google GenAI plugin, define type-safe input/output schemas using Zod, and create a simple AI flow that generates a structured recipe based on user input, ready for local execution and deployment.

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();

view raw JSON →