Hono tutorial
In this tutorial, you’ll build Bargain Chef, a standalone Genkit backend on Hono that exposes a recipe-generating flow over HTTP. It uses two AI patterns Genkit simplifies: streaming structured output and tool calling.
What you’ll build
Section titled “What you’ll build”For each request, your server prompts Gemini to draft a recipe, and the model calls a tool to look up mock grocery sale prices so it can prefer on-sale ingredients. The server streams the recipe back field-by-field as it’s generated, so clients see progress before the full recipe is ready.
You can find the finished code on GitHub.
Prerequisites
Section titled “Prerequisites”- Node.js v20 or later
- npm
- Familiarity with Hono and TypeScript
Set up the application
Section titled “Set up the application”Create the Hono project
Section titled “Create the Hono project”npm create hono@latest my-genkit-hono -- --template nodejs --pm npm --installcd my-genkit-honoInstall packages
Section titled “Install packages”npm install genkit @genkit-ai/google-genai @genkit-ai/fetch @hono/node-servernpm install -D genkit-cli tsxpnpm add genkit @genkit-ai/google-genai @genkit-ai/fetch @hono/node-serverpnpm add -D genkit-cli tsxyarn add genkit @genkit-ai/google-genai @genkit-ai/fetch @hono/node-serveryarn add -D genkit-cli tsxbun add genkit @genkit-ai/google-genai @genkit-ai/fetch @hono/node-serverbun add -d genkit-cli tsxThese packages include:
genkit: Core Genkit SDK.@genkit-ai/google-genai: Plugin that connects Genkit to Google’s Gemini models.@genkit-ai/fetch: Provides fetch-based server integration for runtimes like Hono.@hono/node-server: Adapter that runs your Hono app on Node.js.genkit-cli: CLI tool that enables Genkit testing and observability.tsx: TypeScript runner used to start the server during development.
hono and hono/cors come from the npm create hono scaffold you ran earlier, so they aren’t in the install command above.
Configure a model API key
Section titled “Configure a model API key”This tutorial uses the Gemini API from Google AI Studio:
Get a Gemini API Key
Set the GEMINI_API_KEY environment variable to your key:
export GEMINI_API_KEY=<your API key>Create the backend
Section titled “Create the backend”The backend handles requests from clients. For each request, it prompts Gemini to draft a recipe, lets the model call a tool to look up today’s grocery sale prices, and streams the partial recipe back to the client as it’s generated.
The whole pipeline is a single Genkit flow. A flow is a special Genkit function with built-in observability, type safety, and tooling integration.
Create src/genkit/bargainChefFlow.ts:
import { googleAI } from '@genkit-ai/google-genai';import { genkit, z } from 'genkit';
const ai = genkit({ plugins: [googleAI()],});
const getIngredientsOnSale = ai.defineTool( { name: 'getIngredientsOnSale', description: 'Returns the ingredients on sale at the local grocery store, with prices. The sale set differs between weekdays and weekends.', inputSchema: z.object({ dayType: z .enum(['weekday', 'weekend']) .describe('Whether to fetch weekday or weekend sale prices.'), }), outputSchema: z.array( z.object({ name: z.string(), price: z.string(), }), ), }, async ({ dayType }) => { // Mock data: in a real app, query a pricing database. return dayType === 'weekend' ? [ { name: 'chicken breast', price: '$2.99/lb' }, { name: 'pasta', price: '$0.79' }, { name: 'canned tomatoes', price: '$0.99' }, { name: 'garlic', price: '$0.50 / head' }, { name: 'olive oil', price: '$6.99' }, ] : [ { name: 'eggs', price: '$3.49 / dozen' }, { name: 'spinach', price: '$1.99' }, { name: 'parmesan', price: '$4.99' }, { name: 'lemons', price: '$0.50 each' }, { name: 'rice', price: '$2.49' }, { name: 'butter', price: '$3.99' }, ]; },);
const RecipeSchema = z.object({ title: z.string(), description: z.string(), servings: z.number(), ingredients: z.array( z.object({ name: z.string(), quantity: z.string(), onSale: z.boolean(), }), ), steps: z.array(z.string()),});
export const bargainChefFlow = ai.defineFlow( { name: 'bargainChefFlow', inputSchema: z.object({ craving: z .string() .describe('What the user feels like eating right now.'), }), outputSchema: RecipeSchema, streamSchema: RecipeSchema.partial(), }, async ({ craving }, { sendChunk }) => { const today = new Date().toLocaleDateString('en-US', { weekday: 'long' });
const { stream, response } = ai.generateStream({ model: googleAI.model('gemini-flash-latest', { temperature: 0.7, thinkingConfig: { thinkingLevel: 'MINIMAL' }, }), prompt: `Today is ${today}. The user is craving: ${craving}.
Call the getIngredientsOnSale tool with the dayType that matches today. Saturday and Sunday are weekends; all other days are weekdays. Then propose ONE recipe that takes advantage of those deals. For each ingredient, set onSale=true if it appears in the tool's response, false otherwise.`, tools: [getIngredientsOnSale], output: { schema: RecipeSchema }, });
for await (const chunk of stream) { if (chunk.output) sendChunk(chunk.output); }
const { output } = await response; if (!output) throw new Error('Failed to generate recipe'); return output; },);The file builds the flow in four parts:
- Initialize Genkit.
genkit({ plugins: [googleAI()] })sets up the SDK and registers Gemini as the model provider. - Define a tool.
getIngredientsOnSaleis a function the model can call mid-generation. Tools let the model reach outside its training data and into your code. Here, the tool fetches live sale prices before the model finalizes the recipe. The tool’s typedinputSchemaforces the model to passdayType: 'weekday'or'weekend'. In a real app, this would query a pricing database, inventory system, or third-party API. - Describe the recipe shape.
RecipeSchemais the structure of the final response. The flow declares it asoutputSchemaso Genkit validates the model’s output against it, andRecipeSchema.partial()asstreamSchemaso fields can be absent in the in-progress chunks emitted during streaming. - Define the flow.
bargainChefFlowties everything together. It callsai.generateStream, which yields chunks as the model produces them;sendChunkforwards each chunk to the client so the response fills in field by field. After the stream completes, the flow awaitsresponseso the HTTP request still resolves with a validated recipe.
Add the server route
Section titled “Add the server route”Wire up the Genkit backend in src/index.ts. Replace the contents with the following:
import { fetchHandlers } from '@genkit-ai/fetch';import { serve } from '@hono/node-server';import { Hono } from 'hono';import { cors } from 'hono/cors';import { bargainChefFlow } from './genkit/bargainChefFlow.js';
const app = new Hono();app.use('*', cors());const handleFlow = fetchHandlers([bargainChefFlow], '/api');
app.post('/api/:flowName', async (c) => { return handleFlow(c.req.raw);});
serve( { fetch: app.fetch, port: 3780, }, (info) => { console.log(`Hono server listening on http://localhost:${info.port}`); },);fetchHandlers adapts your Genkit flows to the standard Request/Response shape that Hono passes around, so the same handler works in Node.js and other fetch-based runtimes. The cors() middleware with no options allows all origins, so any browser frontend (a Vite or Next.js dev server, for example) can call this endpoint during development. Before deploying, restrict it to the origins you actually serve (for example, cors({ origin: 'https://your-app.com' })).
Check the project layout
Section titled “Check the project layout”Verify that your project layout matches the structure below:
- package.json
- tsconfig.json
Directorysrc
Directorygenkit
- bargainChefFlow.ts
- index.ts
Optional: install the Genkit agent skills
Section titled “Optional: install the Genkit agent skills”If you’re coding with an AI assistant, install the Genkit Agent Skills so it has structured guidance on Genkit APIs, patterns, and common errors:
npx skills add genkit-ai/skillsSee Develop with AI for tool-specific installation instructions.
Run the app
Section titled “Run the app”Start the Hono server:
npx tsx --watch src/index.tspnpm dlx tsx --watch src/index.tsyarn dlx tsx --watch src/index.tsbunx tsx --watch src/index.tsYou’ll see Hono server listening on http://localhost:3780. The server is now ready to accept POST requests at /api/bargainChefFlow. Send it a craving like something warm with chicken and the recipe streams back field by field: title first, then description, then ingredients (with onSale: true on the ones the model picked from the tool), then steps.
Test and inspect the app
Section titled “Test and inspect the app”You can test the endpoint directly with curl, and you can use the Developer UI to inspect both manual runs and requests from any client.
Send a request with curl
Section titled “Send a request with curl”Use the -N flag and an Accept: text/event-stream header to consume the streamed response:
curl -N -X POST http://localhost:3780/api/bargainChefFlow \ -H "Content-Type: application/json" \ -H "Accept: text/event-stream" \ -d '{"data":{"craving":"something warm with chicken"}}'The { "data": ... } wrapper is required: Genkit’s HTTP handler reads the flow input from the request body’s data field.
The response arrives as a series of data: events. Each event contains the partial recipe accumulated so far, with fields such as title, ingredients, and steps filling in as the model generates them. The final event contains the complete, validated recipe.
Use the Developer UI
Section titled “Use the Developer UI”The Developer UI is Genkit’s local console for testing flows and inspecting execution traces. It runs alongside your backend code, gives you a visual runner for any flow in your project, and records every tool call and model invocation so you can iterate on prompts and debug tool behavior.
-
Start the Developer UI from your project root:
Terminal window npx genkit start -- tsx --watch src/index.tsTerminal window pnpm dlx genkit start -- tsx --watch src/index.tsTerminal window yarn dlx genkit start -- tsx --watch src/index.tsTerminal window bunx genkit start -- tsx --watch src/index.tsThis launches the Developer UI at
http://localhost:4000by default. -
Select
bargainChefFlowfrom the list of flows. -
Enter sample input:
{ "craving": "something warm with chicken" } -
Click Run.
You’ll see the generated recipe, with a trace that builds in real time so you can follow the flow’s progress through each tool call and model invocation.
What you built
Section titled “What you built”You now have a standalone Genkit backend on Hono that streams structured output from Gemini over HTTP, calls a tool during generation to ground the model’s response in mock sale-price data, validates input and output against schemas, and surfaces every step in a local trace UI.
Next steps
Section titled “Next steps”- Creating flows: Compose multi-step flows, branch on input, and chain model calls.
- Generating content: Swap Gemini for another provider, tune sampling parameters, and work with multimodal input.
- Connect an app framework: Add a full-stack UI that calls your flow.
- Connect a web frontend: Wire a standalone web client up to this backend.
- Deploy your app: Ship to Cloud Run, Vercel, Firebase, or your own infrastructure.
- Developer tools: Dig deeper into the Developer UI, tracing, and evaluation.