Developing Genkit Go
GoogleOfficialPublished by Google
- Skill
- Tool integration
- Software development
- Apache-2.0
- Medium risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
Genkit Go is an AI SDK that provides a unified interface for integrating generative AI into Go applications. It supports features such as model generation, structured output, streaming, tool calling, and complex agent workflows. The framework is designed for observability and testing, offering a CLI for tracing and a developer UI for inspecting model interactions. It includes experimental support for multi-turn agents, persistent sessions, and generative UI (A2UI) surfaces.
What it does
- Provides a unified interface for interacting with various AI model providers.
- Enables the creation of flows for structured, observable AI logic.
- Supports experimental multi-turn agent development with session persistence.
- Offers middleware for common tasks like retries, fallbacks, and artifact management.
- Includes a CLI tool for capturing traces, debugging, and running flows.
- Facilitates generative UI integration via A2UI middleware.
When to use it
- When building AI features, chatbots, or agents within a Go codebase.
- When you need to integrate multiple AI model providers with a consistent API.
- When you require observability, tracing, and structured testing for AI logic.
- When developing conversational interfaces that require state management or human-in-the-loop capabilities.
Advantages
- Unified API across different model providers.
- Strong observability through integrated tracing and CLI tools.
- Separation of concerns between AI logic and application code via flows.
- Extensible middleware system for common AI patterns.
- Experimental support for advanced agent features like branching and artifacts.
Usage examples
- “How do I define a simple flow in Genkit Go?”
- You use genkit.DefineFlow to wrap your AI logic, which automatically enables tracing and HTTP deployment capabilities.
- “How can I debug my AI model calls in the terminal?”
- Use the Genkit CLI by running 'genkit start -- go run .' to capture traces and inspect model I/O in the Developer UI.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/google/developing-genkit-go/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip developing-genkit-go.zip -d .agents/skills
Documentation by Google
Genkit Go
Genkit Go is an AI SDK for Go that provides generation, structured output, streaming, tool calling, prompts, and flows with a unified interface across model providers.
Hello World
package main
import (
"context"
"fmt"
"log"
"net/http"
"github.com/firebase/genkit/go/ai"
"github.com/firebase/genkit/go/genkit"
"github.com/firebase/genkit/go/plugins/googlegenai"
"github.com/firebase/genkit/go/plugins/server"
)
func main() {
ctx := context.Background()
g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{}))
genkit.DefineFlow(g, "jokeFlow", func(ctx context.Context, topic string) (string, error) {
return genkit.GenerateText(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Tell me a joke about %s", topic),
)
})
mux := http.NewServeMux()
for _, f := range genkit.ListFlows(g) {
mux.HandleFunc("POST /"+f.Name(), genkit.Handler(f))
}
log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux))
}Core Features
Load the appropriate reference based on what you need:
| Feature | Reference | When to load |
|---|---|---|
| Initialization | references/getting-started.md | Setting up genkit.Init, plugins, the *Genkit instance pattern |
| Generation | references/generation.md | Generate, GenerateText, GenerateData, streaming, output formats, Embed |
| Prompts | references/prompts.md | DefinePrompt, DefineDataPrompt, .prompt files, schemas |
| Tools | references/tools.md | DefineTool, DefineResumableTool interrupts (Interrupted claim, Restart/Respond, WithResume), ai/tool helpers (tool.Interrupt, tool.Fail, tool.AttachParts) |
| Middleware | references/middleware.md | ai.Middleware, ai.WithUse, Hooks (Generate/Model/Tool), built-ins (Retry, Fallback, ToolApproval, Filesystem, Skills, SoftToolErrors, ContextCompression, Budget) |
| Observability | references/observability.md | OpenTelemetry export (otelgenai), tracing.SetInstrumentation, aix.Observer, reflection API outside dev |
| Flows & HTTP | references/flows-and-http.md | DefineFlow, DefineStreamingFlow, genkit.Handler, HTTP serving |
| Model Providers | references/providers.md | Google AI, Vertex AI, Anthropic, OpenAI-compatible, Ollama setup |
Agents (Experimental)
Genkit Go has an experimental agent API for persistent, multi-turn
conversations (sessions, snapshots, interrupts, branching, background execution).
It is gated: initialize with genkit.Init(ctx, genkit.WithExperimental()) or the
constructors panic. Server constructors come from genkit/exp (aliased
genkitx); types and options from ai/exp (aliased aix); session stores from
ai/exp/localstore.
Agent or flow? If the task is conversational, multi-turn, or described as "an agent", "assistant", or "chatbot", build it with
genkitx.DefineAgentrather than hand-rolling aGenerate+ tools loop in a flow. Reach for a plain flow only for single-shot, stateless generation.
For details see:
Agents: defining/serving an agent, running turns, and client- vs server-managed state (start here).
Sessions & persistence: session stores (
localstore.NewInMemorySessionStore/NewFileSessionStore, PostgreSQL), snapshots, and thesessionstoretestconformance suite.Human-in-the-loop / interrupts: pausing for approval/input and resuming.
Branching: forking a conversation from a snapshot.
Background agents: detaching long-running turns and polling.
Working with state: typed custom session state, streamed as JSON patches.
Artifacts: producing and reading named deliverables.
Multi-agent orchestration: delegating to sub-agents, background delegation,
continue_task, and remote agents (DefineRemoteAgent).Advanced custom agents:
DefineCustomAgentfor full turn control.Deploying agents: serving agents over HTTP with
genkit.Handler.
Generative UI (A2UI)
Genkit Go has an A2UI (Agent-to-UI) plugin
(github.com/firebase/genkit/go/plugins/a2ui/exp, imported as a2uix) that
lets an agent stream interactive UI surfaces (cards, lists, forms, buttons),
not just prose. The whole integration is the &a2uix.Surfaces{} model
middleware added via ai.WithUse
on a generate call or agent inline prompt. Go is server-only: it has no A2UI
client/renderer. Render surfaces with a JS or Dart/Flutter client that talks to
your Go agent over HTTP (the server and clients are wire-compatible).
A2UI: server middleware, options, custom catalogs, and security. For the client (rendering surfaces), refer to the A2UI reference in the Genkit JS or Dart skill.
Genkit CLI (recommended)
genkit start unintrusively wraps any Go program that uses the Genkit library, running it unchanged while capturing traces from every Genkit action so you can prove tools were actually called and inspect model I/O from the terminal, even for headless checks. It forwards stdio, so interactive CLI tools that rely on stdin/stdout work without issues. Running the app directly (go run .) skips trace capture, so you're debugging blind. Check install with genkit --version.
Installation:
curl -sL cli.genkit.dev | bashPrimary pattern (default): prefix genkit start -- to your normal run command. This collects telemetry from any Genkit code your program runs, whether triggered from the dev UI, your own web server/web UI, or a plain script. Starts the Developer UI (usually http://localhost:4000) for running flows, model and agent playground, and browsing traces:
genkit start -- go run .
genkit start --noui -- go run . # same, without the Dev UI (still a persistent server)
genkit start -o -- go run . # also opens the browsergenkit start runs until you stop it with Ctrl+C. That is expected and correct for the common cases: a server your web/mobile app calls, or an interactive CLI you exit yourself. --noui only drops the Dev UI; it is not a one-shot command and will not exit on its own. Do not use genkit start as a blocking step in automated/non-interactive contexts; use flow:run (below) for that.
Non-interactive use (agents/CI): add the global --non-interactive flag before -- so the CLI uses defaults and never blocks on a prompt (e.g. the first-run analytics notice): genkit start --non-interactive -- go run . (works with flow:run too).
Run a flow (flow:run): invoke a specific flow by name from the CLI. Append your run command after -- to spin up the runtime just for this run (the command runs as-is to register your flows):
genkit flow:run myFlow '{"data": "input"}' -- go run .
genkit flow:run myFlow '{"data": "input"}' --stream -- go run . # with streaming
genkit flow:run myFlow '{"data": "input"}' --wait -- go run . # wait for completionThis is self-terminating: it runs the flow once, prints a Trace ID, then exits, so it's the right choice for a quick, non-interactive check (unlike genkit start). Traces for this run can be inspected using the trace commands below.
Debugging with traces: the fastest way to see prompts, model inputs/outputs, tool calls, latencies, and errors. Inspect from the terminal after any run under genkit start:
genkit trace:list # find recent trace IDs
genkit trace:get <traceId> # full trace details (inputs, outputs, tool calls, errors)
genkit trace:get <traceId> --format json # machine-readable JSON, safe to pipe into jq or other parsersFor machine-readable output, pass --format json to get clean JSON you can pipe into jq or other parsers. The default output is human-oriented (banner/log lines, possible truncation on large traces), so don't pipe that form directly; use --format json, grep, or the Dev UI trace viewer.
Documentation:
genkit docs:search "streaming" go
genkit docs:list go
genkit docs:read go/flows.mdSee references/getting-started.md for full CLI and Developer UI details.
Key Guidance
Pass
gexplicitly. The*Genkitinstance returned bygenkit.Initis the central registry. Pass it to all Genkit functions rather than storing it as a global. This is a core pattern throughout the SDK.Wrap AI logic in flows. Flows give you tracing, observability, HTTP deployment via
genkit.Handler, and the ability to test from the Developer UI and CLI. Any generation call worth keeping should live in a flow.Verify with traces, not a blind run. Running the app directly (
go run .) does not capture dev traces. See the Genkit CLI section for how to run your app and capture traces.Use
jsonschema:"description=..."struct tags on output types. The model uses these descriptions to understand what each field should contain. Without them, structured output quality drops significantly.Write good tool descriptions. The model decides which tools to call based on their description string. Vague descriptions lead to missed or incorrect tool calls.
Use
.promptfiles for complex prompts. They separate prompt content from Go code, support Handlebars templating, and can be iterated on without recompilation. Code-defined prompts are better for simple, single-line cases.Use
DefineResumableToolfor interrupts. Claim paused calls with the tool'sInterruptedmethod and resume withai.WithResume.ai.InterruptWith,RestartWith/RespondWith, andWithToolRestartsare deprecated;genkitx.DefineInterruptibleToolandai/exp/toolwere removed in v1.14.0. See references/tools.md.Reach for built-in middleware before writing one.
Retry,Fallback,ToolApproval,Filesystem,Skills, andSoftToolErrorscover the common cross-cutting needs and compose with each other viaai.WithUse. See references/middleware.md. When you do write custom middleware, allocate per-call state in closures captured byNew, and guard anything thatWrapToolmutates because tools may run concurrently.Look up the latest model IDs. Model names change frequently. Check provider documentation for current model IDs rather than relying on hardcoded names. See references/providers.md.
Files
- ATTRIBUTION.mdAdded by AutoGineer858 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md11.0 KiB
- references/a2ui.md11.9 KiB
- references/agents-artifacts.md3.9 KiB
- references/agents-background.md5.3 KiB
- references/agents-branching.md3.6 KiB
- references/agents-custom.md6.8 KiB
- references/agents-deployment.md6.6 KiB
- references/agents-human-in-the-loop.md7.3 KiB
- references/agents-multi-agent.md9.3 KiB
- references/agents-sessions.md8.3 KiB
- references/agents-state.md4.6 KiB
- references/agents.md13.0 KiB
- references/flows-and-http.md4.4 KiB
- references/generation.md5.3 KiB
- references/getting-started.md3.4 KiB
- references/middleware.md19.9 KiB
- references/observability.md4.3 KiB
- references/prompts.md7.0 KiB
- references/providers.md3.6 KiB
- references/tools.md8.3 KiB
references/middleware.md
Middleware
Middleware wraps Generate calls to add cross-cutting behavior (retries, logging, fallback, gating, sandboxed tools) without touching the flow that uses it. Middleware composes, so a single Generate call can stack several behaviors. Built-ins ship in the plugins/middleware package; custom middleware is just a Go struct with two methods.
The mental model
A middleware is a config struct that implements two methods:
type Middleware interface {
Name() string // stable, registered identifier
New(ctx context.Context) (*Hooks, error) // produces a per-call hook bundle
}The same struct value the user passes to ai.WithUse is the value the runtime calls New on. There is no separate factory parameter and no embedded base type. Per-call state goes in closures captured by New. Plugin-level state goes on unexported fields of the struct.
New is invoked once per Generate call. The returned *Hooks is reused across every iteration of the tool loop within that call.
type Hooks struct {
Tools []Tool // injected for this call
WrapGenerate func(ctx, *GenerateParams, GenerateNext) ... // tool-loop iteration
WrapModel func(ctx, *ModelParams, ModelNext) ... // model API call
WrapTool func(ctx, *ToolParams, ToolNext) ... // tool execution
}A nil hook is a pass-through. Implement only what the middleware needs.
When each hook fires
A Generate call executes a tool loop: model produces output, any tool calls execute, results feed back into a new model call, repeat until the model stops. The hooks fire at three different layers of this loop:
| Hook | Fires | Sees |
|---|---|---|
WrapGenerate | Once per tool-loop iteration. N tool turns means N+1 invocations. | The accumulated ModelRequest, the iteration index, the streaming callback, and MessageIndex (the next streamed-message slot). |
WrapModel | Once per actual model API call, inside the iteration. | The ModelRequest about to go to the model and the streaming callback. |
WrapTool | Once per tool execution. May run concurrently for parallel tool calls in the same iteration. | The ToolRequest and the resolved Tool. |
WrapGenerate is the right place for logic that needs to see the whole conversation (rewrites, system-prompt injection, message accumulation). WrapModel is the right place for logic about the model call itself (retry, fallback, caching). WrapTool is the right place for logic about a single tool execution (approval, sandboxing, logging).
Composition order
ai.WithUse(A, B, C) expands to A { B { C { actual } } } at call time. Each layer's next continuation runs the next inner layer:
ai.WithUse(
&middleware.Retry{MaxRetries: 3}, // outer: retries the whole inner stack
&middleware.Fallback{Models: ...}, // inner: tries fallback models on failure
)
// effective chain: Retry { Fallback { model } }Order matters. Retry outside Fallback retries the entire fallback cascade as a unit. Swapped, you'd retry the primary first and only fall back after exhausting retries.
Per-call state
State that should be shared across the hooks of a single Generate call lives in closures captured by New. Each Generate call gets a fresh Hooks bundle, so nothing leaks between calls.
type Counter struct{}
func (Counter) Name() string { return "mine/counter" }
func (Counter) New(ctx context.Context) (*ai.Hooks, error) {
var modelCalls int
return &ai.Hooks{
WrapModel: func(ctx context.Context, p *ai.ModelParams, next ai.ModelNext) (*ai.ModelResponse, error) {
modelCalls++
return next(ctx, p)
},
WrapGenerate: func(ctx context.Context, p *ai.GenerateParams, next ai.GenerateNext) (*ai.ModelResponse, error) {
// The same modelCalls variable is visible here because both closures
// capture it from the enclosing New scope.
resp, err := next(ctx, p)
if err == nil {
log.Printf("iteration %d: %d model calls so far", p.Iteration, modelCalls)
}
return resp, err
},
}, nil
}WrapTool may be invoked concurrently for parallel tool calls in the same iteration. Any state it mutates must be guarded:
func (Counter) New(ctx context.Context) (*ai.Hooks, error) {
var (
mu sync.Mutex
toolCalls int
)
return &ai.Hooks{
WrapTool: func(ctx context.Context, p *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error) {
mu.Lock()
toolCalls++
mu.Unlock()
return next(ctx, p)
},
}, nil
}WrapGenerate and WrapModel are not called concurrently within a single Generate call.
Plugin-level state
When a middleware needs resources its config can't carry as JSON (an HTTP client, a database handle, a logger), put them on unexported fields of the config struct. The plugin sets them on a prototype, and ai.NewMiddleware captures that prototype in a closure that value-copies it across JSON-dispatched invocations:
type Logger struct {
Prefix string `json:"prefix,omitempty"`
out io.Writer // unexported; preserved across JSON dispatch via value-copy
}
func (Logger) Name() string { return "mine/logger" }
func (l Logger) New(ctx context.Context) (*ai.Hooks, error) {
return &ai.Hooks{
WrapModel: func(ctx context.Context, p *ai.ModelParams, next ai.ModelNext) (*ai.ModelResponse, error) {
start := time.Now()
resp, err := next(ctx, p)
fmt.Fprintf(l.out, "%s model call took %s\n", l.Prefix, time.Since(start))
return resp, err
},
}, nil
}
type LoggerPlugin struct{ Out io.Writer }
func (p *LoggerPlugin) Name() string { return "logger" }
func (p *LoggerPlugin) Init(ctx context.Context) []api.Action { return nil }
func (p *LoggerPlugin) Middlewares(ctx context.Context) ([]*ai.MiddlewareDesc, error) {
return []*ai.MiddlewareDesc{
ai.NewMiddleware("logs model call latency", Logger{out: p.Out}),
}, nil
}The Dev UI and other-runtime callers send JSON config; the prototype's value copy preserves out (unexported, not in JSON) while Prefix is overridden by the unmarshaled config.
Composition with WithUse
response, _ := genkit.Generate(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Explain quantum computing."),
ai.WithUse(
Logger{Prefix: "[trace]"},
&middleware.Retry{MaxRetries: 3},
),
)No registration is required for pure-Go use. WithUse calls each value's New directly on a fast path; the registry is only consulted for JSON-dispatched calls (Dev UI or cross-runtime). Registration is what makes a middleware visible to the Dev UI and addressable by name.
Inline middleware
For ad-hoc middleware that does not need Dev UI visibility or a named type, use ai.MiddlewareFunc:
ai.WithUse(ai.MiddlewareFunc(func(ctx context.Context) (*ai.Hooks, error) {
return &ai.Hooks{
WrapModel: func(ctx context.Context, p *ai.ModelParams, next ai.ModelNext) (*ai.ModelResponse, error) {
log.Printf("model call: %s", p.Request.Messages[len(p.Request.Messages)-1].Text())
return next(ctx, p)
},
}, nil
}))The adapter satisfies Middleware with a placeholder Name() of "inline". Inline middleware is resolved on the fast path and never touches the registry, so the placeholder name is fine.
Application-owned middleware
Use genkit.DefineMiddleware to register a middleware your application owns directly. Registration surfaces it in the Dev UI and lets cross-runtime callers reference it by name:
genkit.DefineMiddleware(g, "logs model call latency", Logger{out: os.Stderr})
// Lookup by name (mostly for inspection / cross-runtime dispatch).
desc := genkit.LookupMiddleware(g, "mine/logger")For application code, DefineMiddleware is the typical entry point. For plugin authors, ai.NewMiddleware (no registration) plus MiddlewarePlugin.Middlewares() is the typical entry point. genkit.Init registers the returned descriptors automatically.
Built-in middleware
The plugins/middleware package bundles six production-ready implementations (Retry, Fallback, ToolApproval, Filesystem, Skills, SoftToolErrors); the experimental plugins/middleware/exp package (imported as middlewarex) adds ContextCompression, Budget, Agents, and Artifacts. Register the plugin once during Init to make them visible to the Dev UI:
import "github.com/firebase/genkit/go/plugins/middleware"
g := genkit.Init(ctx, genkit.WithPlugins(
&googlegenai.GoogleAI{},
&middleware.Middleware{},
))Retry
Retries failed model API calls with exponential backoff and jitter. Hooks WrapModel.
ai.WithUse(&middleware.Retry{
MaxRetries: 3, // default 3
InitialDelayMs: 1000, // default 1000
MaxDelayMs: 60000, // default 60000
BackoffFactor: 2, // default 2
NoJitter: false, // default false
// Statuses (default: UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, ABORTED, INTERNAL)
// Statuses: []core.StatusName{core.UNAVAILABLE, core.RESOURCE_EXHAUSTED},
})Non-GenkitError errors (network, parse, etc.) are always retried. GenkitError errors are retried only if their status is in Statuses. The backoff respects ctx.Done(): a canceled context aborts the retry loop with the last error.
Fallback
Tries alternative models when the primary fails with a fallback-eligible status. Hooks WrapModel.
ai.WithUse(&middleware.Fallback{
Models: []ai.ModelRef{
googlegenai.ModelRef("googleai/gemini-flash-latest", nil),
googlegenai.ModelRef("vertexai/gemini-flash-latest", nil),
},
// default Statuses: UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED,
// ABORTED, INTERNAL, NOT_FOUND, UNIMPLEMENTED
})Each fallback model uses its own ModelRef.Config() verbatim; the original request's config is not inherited. Compose with Retry outside to retry the whole cascade, or inside to retry just the primary before falling back.
ToolApproval
Holds any tool call not in the allow list, exposing approval as a human-in-the-loop step. Hooks WrapTool.
approval := ai.WithUse(&middleware.ToolApproval{
AllowedTools: []string{"lookup", "search"}, // anything else is held
})Claim holds with middleware.ToolApprovalInterrupted (not the tool's own Interrupted) and answer with a typed middleware.ToolCallDecision. Keep the same middleware on the resume call:
var parts []*ai.Part
for _, part := range resp.Interrupts() {
if call, ok := middleware.ToolApprovalInterrupted(part); ok {
decision := middleware.ToolCallDecision{Approved: confirm(part.ToolRequest.Name, call.Input)}
if !decision.Approved {
decision.Reason = "the user declined" // the model sees this as the tool's error
}
parts = append(parts, call.Restart(decision))
}
}
resp, err = genkit.Generate(ctx, g,
ai.WithMessages(resp.History()...),
ai.WithTools(writeFile),
approval,
ai.WithResume(parts...),
)Silence never approves: any restart without Approved: true refuses the call, and the model receives the refusal as a tool error and continues. Answer a hold with Restart, not Respond.
Judge model. Let a model decide calls the allowlist does not cover (auto-approval). It answers allow, deny (the model sees the denial), or ask (held for you), and fails closed:
ai.WithUse(&middleware.ToolApproval{
AllowedTools: []string{"list_files"},
Judge: googlegenai.ModelRef("googleai/gemini-flash-lite-latest", nil),
JudgePolicy: "Never allow deleting anything outside build/.",
})SoftToolErrors
Returns tool errors to the model as the tool's output ({"error": "..."}) instead of stopping the loop, so the model can fix its input. Useful for tools you don't own, like MCP tools. Interrupts and cancellation still stop the loop.
ai.WithUse(&middleware.SoftToolErrors{}) // every tool
ai.WithUse(&middleware.SoftToolErrors{Tools: []string{"search"}}) // only theseFor a tool you own, return tool.Fail(ctx, err) for just the errors the model can fix. See tools.md.
ContextCompression (experimental, middlewarex)
Keeps long chats and tool loops inside a context budget. The model receives a compressed view; resp.History() keeps every original message, with compression state in metadata.
import middlewarex "github.com/firebase/genkit/go/plugins/middleware/exp"
ai.WithUse(
&middlewarex.ContextCompression{
MaxInputTokens: 80_000,
DedupeToolResponses: &middlewarex.CompressionDedupe{},
TruncateToolResponses: &middlewarex.CompressionToolTruncation{MaxChars: 2000},
Summarize: &middlewarex.CompressionSummarizer{
Model: googlegenai.ModelRef("googleai/gemini-flash-lite-latest", nil),
},
// also: MaxMessages, PreserveRecent (4), MaxToolResponseChars (400000),
// SkipSummarizationThreshold, ReplaceHistory
},
&middleware.Retry{}, // inside compression, so a retry resends the compressed view
)List it after context-adding middleware (Skills, Filesystem, Agents, Artifacts) and before Retry/Fallback. middlewarex.ResolveCompressedHistory(msgs) returns what the model received. Set MaxInputTokens well above a typical first turn.
Budget (experimental, middlewarex)
Caps what a run (or an agent session) may spend. Each non-zero field of Limit (an ai.GenerationUsage) is a cap; Custom is capped key by key.
resp, err := genkit.Generate(ctx, g,
ai.WithPrompt("Research the topic and summarize it."),
ai.WithTools(search),
ai.WithUse(&middlewarex.Budget{Limit: ai.GenerationUsage{
TotalTokens: 200_000,
Custom: map[string]float64{"cost": 0.50},
}}),
)
if errors.Is(err, ai.ErrBudgetExceeded) {
log.Println(resp.FinishReason) // aborted; resp.History() keeps the rounds that ran
}Checked before each model call, so a run can go over by one turn. Subagents count toward the run. Scope: middlewarex.BudgetScopeSession caps the whole agent session (needs a session store). Interrupt: true pauses instead of stopping; claim with middlewarex.BudgetInterrupted(part) and restart with middlewarex.BudgetDecision{Approved: true}.
Every run reports usage: resp.Usage is the last model call, resp.TotalUsage sums every call in the run (nested ones included). Agents report TurnEnd.Usage, out.Usage, and out.State.Usage (session total).
Filesystem
Grants the model scoped file access under a single root directory via list_files, read_file, plus write_file and search_and_replace when writes are enabled. Hooks WrapGenerate and WrapTool and contributes Tools.
ai.WithUse(&middleware.Filesystem{
RootDir: "./workspace",
AllowWriteAccess: true,
ToolNamePrefix: "", // set distinct prefixes if attaching multiple Filesystem middlewares
})Path safety is enforced by os.Root (Go 1.25+), which rejects any path resolving outside the root, including via .., absolute paths, or symlinks. read_file returns its content as a queued user message on the next turn (not as the tool's direct output) so binary types like images can be inlined as media parts.
Skills
Exposes a local library of SKILL.md files as loadable system instructions. Hooks WrapGenerate and contributes a use_skill tool.
ai.WithUse(&middleware.Skills{SkillPaths: []string{"skills"}}) // default: ["skills"]A skill is a directory containing SKILL.md, optionally with YAML frontmatter (name, description). The middleware injects a system prompt listing available skills, and the model calls use_skill("name") to pull the skill body into the conversation on demand. Heavier persona instructions stay off the hot path until actually loaded.
Practical patterns
Streaming-aware middleware
If your WrapGenerate or WrapModel hook emits its own messages (injected user content, system updates), use the streaming callback and the MessageIndex cursor in GenerateParams:
WrapGenerate: func(ctx context.Context, p *ai.GenerateParams, next ai.GenerateNext) (*ai.ModelResponse, error) {
if p.Callback != nil {
_ = p.Callback(ctx, &ai.ModelResponseChunk{
Role: ai.RoleUser,
Index: p.MessageIndex,
Content: []*ai.Part{ai.NewTextPart("[injected context]")},
})
p.MessageIndex++ // advance so downstream middleware and the model see the shifted index
}
p.Request.Messages = append(p.Request.Messages, ai.NewUserMessage(ai.NewTextPart("[injected context]")))
return next(ctx, p)
},Filesystem does this to deliver read_file content to the model while preserving streamed-chunk ordering.
Adding tools from middleware
Hooks.Tools registers extra tools for the duration of the call without the user wiring them through ai.WithTools. Useful when the middleware's hooks and tools work as a pair (e.g., Filesystem's read/write tools, Skills's use_skill tool):
return &ai.Hooks{
Tools: []ai.Tool{myTool},
WrapTool: myInterceptor, // intercepts both myTool and any user-supplied tools
}, nilDuplicate tool names across user-supplied tools and middleware-contributed tools error out at call setup; the call won't run.
Interrupting from WrapTool
A WrapTool hook pauses a call with tool.Interrupt(ctx, data) (from github.com/firebase/genkit/go/ai/tool), reads its answer on the restart with tool.ResumeData[T](ctx), and skips calls it already let through with tool.Released(ctx). (ai.NewToolInterruptError was removed in v1.14.0.)
WrapTool: func(ctx context.Context, p *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error) {
if shouldGate(p.Tool.Name()) && !tool.Released(ctx) {
if d, ok := tool.ResumeData[MyDecision](ctx); ok {
if !d.Approved {
return nil, errors.New("declined")
}
return next(ctx, p)
}
return nil, tool.Interrupt(ctx, map[string]any{"message": "needs approval"})
}
return next(ctx, p)
},Export a typed claim for your hold by wrapping ai.MiddlewareInterrupted[Res](name, part), as ToolApprovalInterrupted does. ToolApproval uses this pattern.
Modifying the request safely
p.Request is the live request for the iteration. Mutating it in place affects later layers. If the change should be visible only to the inner layer, copy first:
WrapModel: func(ctx context.Context, p *ai.ModelParams, next ai.ModelNext) (*ai.ModelResponse, error) {
req := *p.Request
req.Messages = append([]*ai.Message(nil), p.Request.Messages...)
req.Messages = append(req.Messages, extraSystemMessage)
p.Request = &req
return next(ctx, p)
},Skills.injectSkillsPrompt shows the same pattern for ModelRequest cloning.
Idempotent re-injection across iterations
WrapGenerate runs once per tool-loop iteration. If you inject content into the request, you'll inject it on every iteration unless you mark and detect what you've already added. Skills tags its system prompt part with metadata (skills-instructions: true) and refreshes that one part in place rather than appending a new one each turn.
Migration note
The legacy ai.ModelMiddleware / ai.WithMiddleware API is preserved and marked deprecated. Prefer ai.Middleware / ai.WithUse, which adds WrapGenerate and WrapTool hooks plus Hooks.Tools for dynamically injected tools.
See also
tools.mdfor tool definition, interrupt/restart machinery used byToolApproval.Sample sources under
go/samples/basic-middleware/:retry-fallback,filesystem,skills.The
plugins/middlewarepackage source for reference implementations.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
What our scanner noticed· Medium risk
- Downloads piped into a shell
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Publisher
- Google (Official)
- Source
- google/skills · skills/cloud/developing-genkit-go · commit 2194d3b
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Google.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download developing-genkit-go.zip