Get started with Genkit
This guide shows you how to get started with Genkit in your preferred language and test it in the Developer UI.
Prerequisites
Section titled βPrerequisitesβBefore you begin, make sure your environment meets these requirements:
- Node.js v20 or later
- npm
This guide assumes youβre already familiar with building Node.js applications.
- Go 1.24 or later (Download and install)
This guide assumes youβre already familiar with building Go applications.
- Python 3.10 or later (Download and install)
Set up your project
Section titled βSet up your projectβCreate a new Node.js project and configure TypeScript:
mkdir my-genkit-appcd my-genkit-appnpm init -y
# Set up your source directorymkdir srctouch src/index.ts
# Install and configure TypeScriptnpm install -D typescript tsxnpx tsc --init
This sets up your project structure and a TypeScript entry point at src/index.ts
.
Initialize a new Go project directory:
mkdir genkit-intro && cd genkit-intro
go mod init example/genkit-intro
Create a main.go
file for your application entry point.
Create a new project directory and set up a virtual environment:
mkdir genkit-intro && cd genkit-intro
(Recommended) Create a Python virtual environment:
python3 -m venv .
Activate the virtual environment if necessary:
source bin/activate # for bash
Install Genkit packages
Section titled βInstall Genkit packagesβFirst, install the Genkit CLI. This gives you access to local developer tools, including the Developer UI:
curl -sL cli.genkit.dev | bash
First, install the Genkit CLI globally. This gives you access to local developer tools, including the Developer UI:
npm install -g genkit-cli
Then, add the following packages to your project:
npm install genkit @genkit-ai/google-genai
genkit
provides Genkit core capabilities.@genkit-ai/google-genai
provides access to the Google AI Gemini models.
Then, install the Genkit package for Go:
go get github.com/firebase/genkit/go
This provides Genkit core capabilities and access to Google AI Gemini models.
Then, install the required Python packages:
pip3 install genkitpip3 install genkit-plugin-google-genai
Or create a requirements.txt
file:
genkitgenkit-plugin-google-genai
and run:
pip3 install -r requirements.txt
Configure your model API key
Section titled βConfigure your model API keyβGenkit can work with multiple model providers. This guide uses the Gemini API, which offers a generous free tier and doesnβt require a credit card to get started.
To use it, youβll need an API key from Google AI Studio:
Get a Gemini API Key
Once you have a key, set the GEMINI_API_KEY
environment variable:
export GEMINI_API_KEY=<your API key>
Create your first application
Section titled βCreate your first applicationβA flow is a special Genkit function with built-in observability, type safety, and tooling integration.
Update src/index.ts
with the following:
import { googleAI } from '@genkit-ai/google-genai';import { genkit, z } from 'genkit';
// Initialize Genkit with the Google AI pluginconst ai = genkit({ plugins: [googleAI()], model: googleAI.model('gemini-2.5-flash', { temperature: 0.8, }),});
// Define input schemaconst RecipeInputSchema = z.object({ ingredient: z.string().describe('Main ingredient or cuisine type'), dietaryRestrictions: z.string().optional().describe('Any dietary restrictions'),});
// Define output schemaconst RecipeSchema = z.object({ title: z.string(), description: z.string(), prepTime: z.string(), cookTime: z.string(), servings: z.number(), ingredients: z.array(z.string()), instructions: z.array(z.string()), tips: z.array(z.string()).optional(),});
// Define a recipe generator flowexport const recipeGeneratorFlow = ai.defineFlow( { name: 'recipeGeneratorFlow', inputSchema: RecipeInputSchema, outputSchema: RecipeSchema, }, async (input) => { // Create a prompt based on the input const prompt = `Create a recipe with the following requirements: Main ingredient: ${input.ingredient} Dietary restrictions: ${input.dietaryRestrictions || 'none'}`;
// Generate structured recipe data using the same schema const { output } = await ai.generate({ prompt, output: { schema: RecipeSchema }, });
if (!output) throw new Error('Failed to generate recipe');
return output; },);
// Run the flowasync function main() { const recipe = await recipeGeneratorFlow({ ingredient: 'avocado', dietaryRestrictions: 'vegetarian', });
console.log(recipe);}
main().catch(console.error);
This code sample:
- Defines reusable input and output schemas with Zod
- Configures the
gemini-2.5-flash
model with temperature settings - Defines a Genkit flow to generate a structured recipe based on your input
- Runs the flow with a sample input and prints the result
Create a main.go
file with the following sample code:
package main
import ( "context" "encoding/json" "fmt" "log"
"github.com/firebase/genkit/go/ai" "github.com/firebase/genkit/go/genkit" "github.com/firebase/genkit/go/plugins/googlegenai")
// Define input schematype RecipeInput struct { Ingredient string `json:"ingredient" jsonschema:"description=Main ingredient or cuisine type"` DietaryRestrictions string `json:"dietaryRestrictions,omitempty" jsonschema:"description=Any dietary restrictions"`}
// Define output schematype Recipe struct { Title string `json:"title"` Description string `json:"description"` PrepTime string `json:"prepTime"` CookTime string `json:"cookTime"` Servings int `json:"servings"` Ingredients []string `json:"ingredients"` Instructions []string `json:"instructions"` Tips []string `json:"tips,omitempty"`}
func main() { ctx := context.Background()
// Initialize Genkit with the Google AI plugin g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{}), genkit.WithDefaultModel("googleai/gemini-2.5-flash"), )
// Define a recipe generator flow recipeGeneratorFlow := genkit.DefineFlow(g, "recipeGeneratorFlow", func(ctx context.Context, input *RecipeInput) (*Recipe, error) { // Create a prompt based on the input dietaryRestrictions := input.DietaryRestrictions if dietaryRestrictions == "" { dietaryRestrictions = "none" }
prompt := fmt.Sprintf(`Create a recipe with the following requirements: Main ingredient: %s Dietary restrictions: %s`, input.Ingredient, dietaryRestrictions)
// Generate structured recipe data using the same schema recipe, _, err := genkit.GenerateData[Recipe](ctx, g, ai.WithPrompt(prompt), ) if err != nil { return nil, fmt.Errorf("failed to generate recipe: %w", err) }
return recipe, nil })
// Run the flow recipe, err := recipeGeneratorFlow.Run(ctx, &RecipeInput{ Ingredient: "avocado", DietaryRestrictions: "vegetarian", }) if err != nil { log.Fatalf("could not generate recipe: %v", err) }
// Print the structured recipe recipeJSON, _ := json.MarshalIndent(recipe, "", " ") fmt.Println(string(recipeJSON))}
This code sample:
- Defines reusable input and output schemas using Go structs with JSON schema tags
- Configures the
gemini-2.5-flash
model as the default - Defines a Genkit flow to generate a structured recipe based on your input
- Runs the flow with a sample input and prints the structured result
Create a main.py
file:
import jsonfrom typing import Optionalfrom pydantic import BaseModel, Fieldfrom genkit.ai import Genkitfrom genkit.plugins.google_genai import GoogleAI
# Initialize Genkit with the Google AI pluginai = Genkit( plugins=[GoogleAI()], model='googleai/gemini-2.5-flash',)
# Define input schemaclass RecipeInput(BaseModel): ingredient: str = Field(description='Main ingredient or cuisine type') dietary_restrictions: Optional[str] = Field(default=None, description='Any dietary restrictions')
# Define output schemaclass Recipe(BaseModel): title: str description: str prep_time: str cook_time: str servings: int ingredients: list[str] instructions: list[str]
# Define a recipe generator flow@ai.flow()async def recipe_generator_flow(input_data: RecipeInput) -> Recipe: # Create a prompt based on the input dietary_restrictions = input_data.dietary_restrictions or 'none'
prompt = f"""Create a recipe with the following requirements: Main ingredient: {input_data.ingredient} Dietary restrictions: {dietary_restrictions}"""
# Generate structured recipe data using the same schema result = await ai.generate( prompt=prompt, output_schema=Recipe, )
if not result.output: raise ValueError('Failed to generate recipe')
return result.output
async def main() -> None: # Run the flow recipe = await recipe_generator_flow(RecipeInput( ingredient='avocado', dietary_restrictions='vegetarian' ))
# Print the structured recipe print(json.dumps(recipe, indent=2))
ai.run_main(main())
This code sample:
- Defines reusable input and output schemas with Pydantic
- Configures the
gemini-2.5-flash
model as the default - Defines a Genkit flow to generate a structured recipe based on your input
- Runs the flow with a sample input and prints the structured result
Why use flows?
Section titled βWhy use flows?β- Type-safe inputs and outputs: Define clear schemas for your data
- Integrates with the Developer UI: Test and debug flows visually
- Easy deployment as APIs: Deploy flows as HTTP endpoints
- Built-in tracing and observability: Monitor performance and debug issues
Run your application
Section titled βRun your applicationβRun your application to see it in action:
npx tsx src/index.ts
You should see a structured recipe output in your console.
Run your application to see it in action:
go run .
You should see a structured recipe output in JSON format.
Run your app (Genkit apps are just regular Python applications):
python3 main.py
You should see a structured recipe output in JSON format.
Test in the Developer UI
Section titled βTest in the Developer UIβThe Developer UI is a local tool for testing and inspecting Genkit components, like flows, with a visual interface.
Start the Developer UI
Section titled βStart the Developer UIβThe Genkit CLI is required to run the Developer UI. If you followed the installation steps above, you already have it installed.
Run the following command from your project root:
genkit start -- npx tsx --watch src/index.ts
This starts your app and launches the Developer UI at http://localhost:4000
by default.
Optional: Add an npm script
Section titled βOptional: Add an npm scriptβTo make starting the Developer UI easier, add the following to your package.json
scripts:
"scripts": { "genkit:ui": "genkit start -- npx tsx --watch src/index.ts"}
Then run it with:
npm run genkit:ui
Run the following command from your project root:
genkit start -- go run .
This starts your app and launches the Developer UI at http://localhost:4000
by default.
To inspect your app with Genkit Dev UI, run:
genkit start -- python3 main.py
The command will print the Dev UI URL:
Genkit Developer UI: http://localhost:4000
Run and inspect flows
Section titled βRun and inspect flowsβIn the Developer UI:
-
Select your recipe generator flow from the list of flows:
-recipeGeneratorFlow
-recipe_generator_flow
-
Enter sample input:
{ "ingredient": "avocado", "dietaryRestrictions": "vegetarian"}
{ "ingredient": "avocado", "dietary_restrictions": "vegetarian"}
- Click Run
Youβll see the generated recipe as structured output, along with a visual trace of the AI generation process for debugging and optimization.
Next steps
Section titled βNext stepsβNow that youβve created and tested your first Genkit application, explore more features to build powerful AI-driven applications:
- Developer tools: Set up your local workflow with the Genkit CLI and Dev UI.
- Generating content: Use Genkitβs unified generation API to work with multimodal and structured output across supported models.
- Creating flows: Learn about streaming flows, schema customization, deployment options, and more.
- Tool calling: Enable your AI models to interact with external systems and APIs.
- Managing prompts with Dotprompt: Define flexible prompt templates using
.prompt
files or code.