Installation
Install as Agent Plugin
Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install developing-genkit-go@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin developing-genkit-go v1.0.0 follows the Agent Plugins spec.
Install with the gh extension
gh skills-hub install developing-genkit-go Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/developing-genkit-go/ Extract the ZIP to .github/skills/ in your repo. The folder name must match developing-genkit-go for Copilot to auto-discover it.
Skill Files (20)
SKILL.md 11.2 KB
---
name: developing-genkit-go
description: >-
Provides guidance on developing AI-powered applications using Genkit in Go.
Use when the user asks to build AI features, agents, flows, or tools in Go
using Genkit, or when working with Genkit Go code involving generation,
prompts, streaming, tool calling, or model providers. Don't use for Genkit in
JavaScript/TypeScript, Python, or Dart.
metadata:
version: "1.0.0"
category: AiAndMachineLearning
---
# 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
```go
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](references/getting-started.md) | Setting up `genkit.Init`, plugins, the `*Genkit` instance pattern |
| Generation | [references/generation.md](references/generation.md) | `Generate`, `GenerateText`, `GenerateData`, streaming, output formats, `Embed` |
| Prompts | [references/prompts.md](references/prompts.md) | `DefinePrompt`, `DefineDataPrompt`, `.prompt` files, schemas |
| Tools | [references/tools.md](references/tools.md) | `DefineTool`, `DefineResumableTool` interrupts (`Interrupted` claim, `Restart`/`Respond`, `WithResume`), `ai/tool` helpers (`tool.Interrupt`, `tool.Fail`, `tool.AttachParts`) |
| Middleware | [references/middleware.md](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](references/observability.md) | OpenTelemetry export (`otelgenai`), `tracing.SetInstrumentation`, `aix.Observer`, reflection API outside dev |
| Flows & HTTP | [references/flows-and-http.md](references/flows-and-http.md) | `DefineFlow`, `DefineStreamingFlow`, `genkit.Handler`, HTTP serving |
| Model Providers | [references/providers.md](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.DefineAgent`
rather than hand-rolling a `Generate` + tools loop in a flow. Reach for a
plain flow only for single-shot, stateless generation.
For details see:
- [Agents](references/agents.md): defining/serving an agent, running turns,
and client- vs server-managed state (start here).
- [Sessions & persistence](references/agents-sessions.md): session stores
(`localstore.NewInMemorySessionStore`/`NewFileSessionStore`, PostgreSQL),
snapshots, and the `sessionstoretest` conformance suite.
- [Human-in-the-loop / interrupts](references/agents-human-in-the-loop.md):
pausing for approval/input and resuming.
- [Branching](references/agents-branching.md): forking a conversation from a
snapshot.
- [Background agents](references/agents-background.md): detaching long-running
turns and polling.
- [Working with state](references/agents-state.md): typed custom session
state, streamed as JSON patches.
- [Artifacts](references/agents-artifacts.md): producing and reading named
deliverables.
- [Multi-agent orchestration](references/agents-multi-agent.md): delegating to
sub-agents, background delegation, `continue_task`, and remote agents
(`DefineRemoteAgent`).
- [Advanced custom agents](references/agents-custom.md): `DefineCustomAgent`
for full turn control.
- [Deploying agents](references/agents-deployment.md): 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](references/a2ui.md): 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:**
```bash
curl -sL cli.genkit.dev | bash
```
**Primary 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:
```bash
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 browser
```
`genkit 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):
```bash
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 completion
```
This 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`:
```bash
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 parsers
```
For 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:**
```bash
genkit docs:search "streaming" go
genkit docs:list go
genkit docs:read go/flows.md
```
See [references/getting-started.md](references/getting-started.md) for full CLI
and Developer UI details.
## Key Guidance
- **Pass `g` explicitly.** The `*Genkit` instance returned by `genkit.Init` is
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](#genkit-cli-recommended)
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 `.prompt` files 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 `DefineResumableTool` for interrupts.** Claim paused calls with the
tool's `Interrupted` method and resume with `ai.WithResume`.
`ai.InterruptWith`, `RestartWith`/`RespondWith`, and `WithToolRestarts` are
deprecated; `genkitx.DefineInterruptibleTool` and `ai/exp/tool` were removed
in v1.14.0. See [references/tools.md](references/tools.md).
- **Reach for built-in middleware before writing one.** `Retry`, `Fallback`,
`ToolApproval`, `Filesystem`, `Skills`, and `SoftToolErrors` cover the common
cross-cutting needs and compose with each other via `ai.WithUse`. See
[references/middleware.md](references/middleware.md). When you do write custom
middleware, allocate per-call state in closures captured by `New`, and guard
anything that `WrapTool` mutates 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](references/providers.md).
references/
a2ui.md 12.3 KB
# A2UI (Agent-to-UI) generative UI
The A2UI plugin (`github.com/firebase/genkit/go/plugins/a2ui/exp`, imported as
`a2uix`) brings [A2UI](https://a2ui.org/), a transport-agnostic, JSON-based
streaming UI protocol, to Genkit Go agents. The plugin is in preview: it lives
under the `.../a2ui/exp` import path (package `exp`, aliased `a2uix` following
`aix` and `genkitx`) and its APIs may change in any minor version release.
A2UI builds on the experimental agent API
(`genkit.Init(ctx, genkit.WithExperimental())`). Read [Agents](agents.md)
first if you have not.
An A2UI-enabled agent streams more than prose. It streams interactive UI
**surfaces** (cards, lists, forms, buttons) that a client renders incrementally
as the model responds. The entire Go integration is a single model middleware:
add `&a2uix.Surfaces{}` to a generate/agent's `ai.WithUse` and nothing else
changes.
- [Go is server-only: bring your own client](#go-is-server-only-bring-your-own-client): Lines 28-53
- [Server: add the a2ui middleware](#server-add-the-a2ui-middleware): Lines 55-120
- [Serve the agent over HTTP](#serve-the-agent-over-http): Lines 122-173
- [Custom catalogs](#custom-catalogs): Lines 175-234
- [Security and the trust boundary](#security-and-the-trust-boundary): Lines 236-257
- [How it works](#how-it-works): Lines 259-278
---
## Go is server-only: bring your own client
**Go has no A2UI client/renderer.** The Go plugin is the server half: it injects
catalog capabilities into the prompt and rewrites the model's a2ui blocks into
a2ui data parts on the stream. To actually render surfaces in a browser or app,
use a JS or Dart/Flutter client that talks to your Go agent over HTTP. The Go
server and the JS/Dart client are wire-compatible (same `application/a2ui+json`
data parts, same catalog ids), so mix and match freely.
For the client half, refer to the A2UI reference in the Genkit **JS** or
**Dart**
skill (the `a2ui.md` reference in `developing-genkit-js` /
`developing-genkit-dart`).
Read their client sections and ignore their server/`a2ui()` middleware sections
(that is the JS/Dart server, replaced by the Go server below):
- **JS**: browser rendering with an `@a2ui/*` renderer (Lit/React/Angular) plus
the `@genkit-ai/a2ui/client` helpers (`remoteAgent`, `a2uiEnvelopesFromParts`,
`actionToMessage`).
- **Dart/Flutter**: rendering with the
[`genui`](https://pub.dev/packages/genui) package plus the
`package:genkit_a2ui/client.dart` helpers.
The client points `remoteAgent` at the Go endpoint (for example
`remoteAgent({ url: '/api/uiAgent' })`), and the client's renderer registers a
catalog under the **same catalog id** the Go server advertises.
## Server: add the `a2ui` middleware
Add `&a2uix.Surfaces{}` to the generate call (or agent inline prompt) via
`ai.WithUse`. That is the whole server-side setup. Registering `&a2uix.A2UI{}`
in `genkit.Init` is **optional**: it only surfaces the middleware and catalogs
in
the Dev UI. The middleware works via `ai.WithUse` regardless.
```go
import (
"context"
"github.com/firebase/genkit/go/ai"
aix "github.com/firebase/genkit/go/ai/exp"
"github.com/firebase/genkit/go/ai/exp/localstore"
"github.com/firebase/genkit/go/genkit"
genkitx "github.com/firebase/genkit/go/genkit/exp"
a2uix "github.com/firebase/genkit/go/plugins/a2ui/exp"
"github.com/firebase/genkit/go/plugins/googlegenai"
)
ctx := context.Background()
// &a2uix.A2UI{} is optional (Dev UI only); the middleware works without it.
g := genkit.Init(ctx,
genkit.WithPlugins(&googlegenai.GoogleAI{}, &a2uix.A2UI{}),
genkit.WithExperimental(),
)
uiAgent := genkitx.DefineAgent(g, "uiAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem(
"You help users. Render an A2UI surface whenever a result is " +
"clearer shown than told (weather, comparisons, lists, forms). " +
"Keep prose brief; put the substance in the UI."),
ai.WithUse(&a2uix.Surfaces{}), // defaults to the bundled basic catalog
},
// Server-managed state: the client just passes a session id (remoteAgent
// handles that), history lives in the store.
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()),
)
```
It works identically on a one-shot `genkit.Generate`:
```go
resp, err := genkit.Generate(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Show me the weather in Tokyo"),
ai.WithUse(&a2uix.Surfaces{}),
)
```
### Middleware ordering
A2UI keeps per-turn streaming state (a stream parser and its minted surface ids)
for the model call it wraps. Place any retrying/fallback middleware (which
re-invokes the model) **outside** A2UI so each attempt gets a fresh A2UI turn.
`ai.WithUse(A, B)` means A wraps B:
```go
ai.WithUse(
&middleware.Retry{MaxRetries: 5}, // outer: fresh A2UI turn per attempt
&a2uix.Surfaces{}, // inner
)
```
## Serve the agent over HTTP
Serve the agent with `genkit.Handler` (see
[Deploying agents](agents-deployment.md)).
A server-managed agent exposes three endpoints the `remoteAgent` client expects:
the turn endpoint plus its `/getSnapshot` and `/abort` companions.
```go
mux := http.NewServeMux()
mux.HandleFunc("POST /api/uiAgent", genkit.Handler(uiAgent))
mux.HandleFunc("POST /api/uiAgent/getSnapshot", genkit.Handler(uiAgent.GetSnapshotAction()))
mux.HandleFunc("POST /api/uiAgent/waitForSnapshot", genkit.Handler(uiAgent.WaitForSnapshotAction()))
mux.HandleFunc("POST /api/uiAgent/abort", genkit.Handler(uiAgent.AbortAction()))
log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux))
```
If the browser is served from a different origin than the agent (for example a
Vite dev server on `:5173`), wrap the entire router/mux with permissive CORS
middleware (as shown in
[Deploying agents](agents-deployment.md#cors-for-browser-clients))
so that preflight OPTIONS requests are handled automatically without needing to
register duplicate bare paths. Behind a same-origin proxy (for example Vite
preview),
CORS is a no-op.
You can also drive the agent directly with curl:
```bash
curl -N -X POST 'http://localhost:8080/api/uiAgent?stream=true' \
-H "Content-Type: application/json" \
-d '{"data": {"message": {"role": "user", "content": [{"text": "What is the weather in Tokyo?"}]}}}'
```
### Config options
`&a2uix.Surfaces{}` fields (all optional):
| Field | Default | Description |
| -------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `Catalog` | nil | Inline `*a2uix.Catalog`. Wins over `CatalogID`, but is not serialized, so prefer `CatalogID` + `LoadCatalog`. |
| `CatalogID` | `a2uix.DefaultCatalogID` (`"basic"`) | Id of a catalog registered with `a2uix.LoadCatalog`. Resolved from the registry at call time. |
| `Instructions` | `a2uix.InstructionsSystem` | Where catalog capabilities are injected. `a2uix.InstructionsNone` injects nothing (supply your own). |
| `Validate` | `a2uix.ValidateWarn` | `ValidateWarn` logs and drops bad blocks; `ValidateStrict` returns an error; `ValidateOff` skips checking. |
| `SurfaceID` | fresh UUID | Surface-id policy. Set a fixed string to reuse one id per surface; empty mints a fresh UUID per surface. |
| `Version` | `a2uix.DefaultVersion` (`"v0.9"`) | Protocol version stamped on envelopes. Validated against `a2uix.SupportedVersions`. |
Use `Validate: a2uix.ValidateStrict` during development to fail fast on
malformed
JSON or components outside the catalog. See
[Security](#security-and-the-trust-boundary)
for what strict does and does not check.
## Custom catalogs
The `CatalogID` is a **catalog id** resolved from the Genkit registry. The
bundled basic catalog (`a2uix.BasicCatalog()`, id `a2uix.BasicCatalogID`,
mirroring
`@a2ui/web_core`'s basic catalog) is the default and needs no registration. A
catalog describes the components the model may emit:
- `ID`: globally-unique URI (also used as `catalogId` on `createSurface`).
- `Components`: each an `a2uix.CatalogComponent` with `Name` (matches the
renderer
type), `Description` (one-line summary), and `Props` (a compact, model-facing
text description of the component's props, kept as plain text to minimize
prompt tokens).
Register a catalog with `a2uix.LoadCatalog`, then reference it by id. Start from
the basic catalog and add your own component:
```go
import a2uix "github.com/firebase/genkit/go/plugins/a2ui/exp"
weatherCatalog := a2uix.BasicCatalog()
weatherCatalog.ID = "https://my-app.org/catalogs/weather.json"
weatherCatalog.Components = append(weatherCatalog.Components, a2uix.CatalogComponent{
Name: "Gauge",
Description: "A circular gauge visualizing a single numeric value.",
Props: "value: number or { path } binding (required); min?: number; max?: number; label?: string; unit?: string.",
})
if err := a2uix.LoadCatalog(g, weatherCatalog); err != nil {
log.Fatalf("loading catalog: %v", err)
}
uiAgent := genkitx.DefineAgent(g, "uiAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithUse(&a2uix.Surfaces{
CatalogID: weatherCatalog.ID,
Validate: a2uix.ValidateStrict,
}),
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()),
)
```
You can also load a catalog from a JSON file with
`a2uix.LoadCatalogFile(g, "./my-catalog.json")` (an object with an `id` string
and
a `components` array). To surface the bundled basic catalog in the Dev UI
alongside custom ones, call `a2uix.RegisterBasicCatalog(g)` (optional; the
middleware falls back to it either way). `LoadCatalog` is idempotent per id.
The **client must register a matching renderer under the same catalog id**, and
each component `Name` must match on both sides. Otherwise the model emits a
component the client cannot render. See the A2UI reference in the JS or Dart
skill for how to register a custom component (a genui `CatalogItem` in Dart, an
`@a2ui/*` renderer in JS). Catalogs live in the registry under value type
`a2uix.CatalogValueType`
(`"a2ui-catalog"`); the Dev UI lists them at
`GET /api/values?type=a2ui-catalog`.
## Security and the trust boundary
Generative UI moves model output into the client UI, so treat every surface an
agent emits as **untrusted input**. `Validate` (including `ValidateStrict`)
checks
envelope structure and component *type names* against the catalog only. It does
**not** validate component props or data-model values: model-controlled values
such as an `Image`'s url or a `Text`'s inline Markdown pass through untouched.
`ValidateStrict` is a well-formedness check, not a security boundary.
- **The client renderer/catalog owns prop sanitization.** Whatever renders a
surface is responsible for escaping and sanitizing prop values before they
reach the UI.
- **Restrict remote sources at the host.** On the web, serve the client with a
Content Security Policy that limits `img-src` and other fetch directives to
origins you trust.
- **Do not put secrets in the data model.** Anything bound into a surface's data
model can be echoed back through an action's `context`.
For server-side control over props (for example, allow-listing image hosts), add
your own model middleware after `&a2uix.Surfaces{}` to inspect and rewrite the
emitted a2ui parts.
## How it works
A2UI rides on its own part channel: a Genkit `data` part with mime type
`application/a2ui+json` (`a2uix.A2UIMimeType`) whose data is
`{ "envelopes": [...] }`. On each model call, `&a2uix.Surfaces{}`:
1. Sanitizes inbound a2ui parts (a surface action sent back as the next turn, or
replayed history) into model-readable text, so a model that does not
understand the a2ui mime type can still reason about prior surfaces and user
actions.
2. Injects the catalog's capabilities into the system prompt (unless
`Instructions: a2uix.InstructionsNone`).
3. Intercepts the model output (streamed chunks and the final message).
4. Extracts `a2ui` fenced code blocks from the model's text.
5. Validates them against the catalog (per `Validate`).
6. Rewrites them into canonical a2ui data parts.
For a complete, runnable example (a Go backend plus a Vite + Lit web frontend),
see `go/samples/basic-middleware/a2ui` in the Genkit repo (it serves the same
agent the JS `a2ui` testapp's web UI talks to).
agents-artifacts.md 4.2 KB
# Working with Artifacts (Experimental)
> **Experimental / preview API.** The `Artifacts` middleware comes from
> `plugins/middleware/exp`; the `Artifact` type from `ai/exp`. Read
> [agents.md](agents.md) first.
**Artifacts** are named, content-bearing deliverables an agent produces during a
session — files, reports, code, etc. They live in the session (deduplicated by
name) and are returned on `out.Artifacts`.
```go
import (
aix "github.com/firebase/genkit/go/ai/exp"
middlewarex "github.com/firebase/genkit/go/plugins/middleware/exp"
)
```
- [Give the model artifact tools](#give-the-model-artifact-tools): Lines 25-69
- [The Artifact shape](#the-artifact-shape): Lines 71-82
- [Programmatic access (inside tools and custom agents)](#programmatic-access-inside-tools-and-custom-agents): Lines 84-112
- [Sharing artifacts across agents](#sharing-artifacts-across-agents): Lines 114-131
---
## Give the model artifact tools
The `middlewarex.Artifacts` middleware (see [using middleware](middleware.md))
adds `read_artifact` and `write_artifact` tools and injects an `<artifacts>`
listing (names + sizes, not full content) into the system prompt each turn. No
custom tool code needed. Attach it via the `ai.WithUse` prompt option.
```go
workspaceAgent := genkitx.DefineAgent[any](g, "workspaceAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem(`You are a code generation assistant. Use write_artifact to create
files (pass the filename as "name" and the full content as "content"). Use
read_artifact to review or modify a previously created file.`),
ai.WithUse(&middlewarex.Artifacts{}),
},
)
```
No session store is needed to produce artifacts — they are returned on
`out.Artifacts` either way (this agent is
[client-managed](agents.md#client-managed-vs-server-managed-state),
hence the explicit `[any]` type parameter). Add a store (e.g.
`localstore.NewFileSessionStore`) only when artifacts should persist across
turns
or sessions. See [sessions](agents-sessions.md).
Run it; artifacts are produced via the tool and returned in the output:
```go
out, _ := workspaceAgent.RunText(ctx, "Write poem.txt with a poem about Genkit")
for _, a := range out.Artifacts {
fmt.Println(a.Name)
}
```
`middlewarex.Artifacts` option:
- `Readonly` (default `false`): when `true`, only `read_artifact` is provided —
the model can read but not create/update artifacts. Useful on an orchestrator
that should review (but not produce) sub-agent artifacts.
```go
ai.WithUse(&middlewarex.Artifacts{Readonly: true})
```
## The `Artifact` shape
```go
// An artifact's content lives in Parts (text/media parts). Metadata is optional.
artifact := &aix.Artifact{
Name: "poem.txt",
Parts: []*ai.Part{ai.NewTextPart("Roses are red…")},
Metadata: map[string]any{"source": "workspaceAgent"}, // optional
}
```
Writing the same `Name` again **replaces** the artifact (dedup by name).
## Programmatic access (inside tools and custom agents)
Use the session's artifact store. `aix.ArtifactStoreFromContext(ctx)` returns a
`State`-agnostic view (so tools don't need to know the agent's `State` type), or
`nil` when there is no active session.
```go
store := aix.ArtifactStoreFromContext(ctx)
if store == nil {
// not inside an agent session
}
// Read all artifacts:
for _, a := range store.Artifacts() {
if a.Name == "poem.txt" {
// ...
}
}
// Create / replace artifacts:
store.AddArtifacts(&aix.Artifact{
Name: "notes.md",
Parts: []*ai.Part{ai.NewTextPart("# Notes")},
})
```
From a [custom agent](agents-custom.md) you can also stream an artifact to the
client with `resp.SendArtifact(a)`, which forwards it and adds it to the session
in one call.
## Sharing artifacts across agents
In [multi-agent orchestration](agents-multi-agent.md), set the `Agents`
middleware's `ArtifactStrategy: middlewarex.ArtifactStrategySession` so
sub-agent
artifacts are merged into the parent session (namespaced by invocation ID), and
add `&middlewarex.Artifacts{Readonly: true}` to the orchestrator so it can
`read_artifact` them:
```go
ai.WithUse(
&middlewarex.Agents{
Agents: []aix.AgentRef{{Name: "researcher"}, {Name: "coder"}},
ArtifactStrategy: middlewarex.ArtifactStrategySession,
},
&middlewarex.Artifacts{Readonly: true},
)
```
agents-background.md 5.7 KB
# Background Agents / Detaching (Experimental)
> **Experimental / preview API.** Detaching **requires a
> [session store](agents-sessions.md)** that also implements
> `aix.SnapshotSubscriber` (both `localstore` stores do) — the server needs
> somewhere to write the result and a way to observe an abort. Read
> [agents.md](agents.md) first.
Detaching runs a turn in the background: the server writes a `pending` snapshot
and returns its `SnapshotID` **immediately**, keeps processing, then rewrites
the
snapshot to a terminal status (`completed` / `failed` / `aborted`). A reader
waits on the snapshot (or polls it) and can `Abort` in the meantime.
- [Define the agent (store required)](#define-the-agent-store-required): Lines 24-34
- [Detach a turn](#detach-a-turn): Lines 36-55
- [Wait (or poll)](#wait-or-poll): Lines 57-82
- [Abort and resume](#abort-and-resume): Lines 84-110
- [Serve detach over HTTP](#serve-detach-over-http): Lines 112-131
- [Status values (aix.SnapshotStatus)](#status-values-aixsnapshotstatus): Lines 133-146
---
## Define the agent (store required)
```go
backgroundAgent := genkitx.DefineAgent(g, "backgroundAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are a senior research analyst. Produce a comprehensive markdown report."),
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()), // REQUIRED for detach
)
```
## Detach a turn
`RunDetached` sends one input, returns once the server has accepted the work,
and hands back a `*aix.DetachedTask[State]`. Store its snapshot ID;
`agent.Task(snapshotID)` rebuilds the same handle in any process later.
```go
task, err := backgroundAgent.RunDetached(ctx, &aix.AgentInput{
Message: ai.NewUserTextMessage("Write a report on renewable energy trends"),
})
if err != nil {
log.Fatal(err) // the work never started
}
snapshotID := task.SnapshotID() // pending; save this
```
On a live connection, send an input with `Detach: true` (or call `conn.Detach()`
mid-turn); the output has `FinishReason == aix.AgentFinishReasonDetached` and
the
pending `SnapshotID`.
## Wait (or poll)
```go
waitCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
snap, err := task.Wait(waitCtx) // blocks until settled; no polling loop needed
if err != nil {
log.Fatal(err) // the wait itself failed (unknown snapshot, ctx done)
}
switch snap.Status {
case aix.SnapshotStatusCompleted:
msgs := snap.State.Messages
fmt.Println(msgs[len(msgs)-1].Text())
case aix.SnapshotStatusFailed, aix.SnapshotStatusAborted:
// Resume points: State holds the turns that finished (see below).
case aix.SnapshotStatusExpired:
// The worker died (heartbeat stale). Resume from snap.ParentID and resend.
}
```
`task.Poll(ctx)` does one read instead. `agent.WaitForSnapshot(ctx, id)` waits
on
a bare snapshot ID. Pass `aix.WithMetadataOnly()` to `Poll` / `GetSnapshot` to
read status without loading `State`. `Wait` returns the snapshot for every
outcome; a non-nil error means the wait could not proceed.
## Abort and resume
```go
status, err := task.Abort(ctx) // or backgroundAgent.Abort(ctx, snapshotID)
```
An abort flips `pending` to `aborting` (so `Abort` answers `aborting` for a run
still going), the worker winds down, then the row settles. Check what `Wait`
returns rather than assuming `aborted`: a turn that finished anyway settles
`completed`, and one that broke first settles `failed`.
`failed` and `aborted` snapshots are **resume points**: they hold the
conversation up to the last completed turn. Send an input with no payload to
re-run the turn, or a new message to change course:
```go
snap, _ := task.Wait(ctx)
if snap.Status == aix.SnapshotStatusAborted || snap.Status == aix.SnapshotStatusFailed {
out, err := backgroundAgent.Run(ctx, &aix.AgentInput{},
aix.WithSnapshotID[any](snap.SnapshotID))
// ...
}
```
Detached work runs in the process that started it; it is not durable
execution. On `SIGTERM`, abort pending snapshots and wait for them to settle so
callers find resumable `aborted` rows instead of `expired` ones.
## Serve detach over HTTP
A remote client drives the same story over HTTP: send `{"detach": true, ...}` as
the turn input, then wait on the `waitForSnapshot` companion (or poll
`getSnapshot`) and hit `abort`. Expose the companions next to the agent:
```go
mux.HandleFunc("POST /api/backgroundAgent", genkit.Handler(backgroundAgent))
mux.HandleFunc("POST /api/backgroundAgent/getSnapshot", genkit.Handler(backgroundAgent.GetSnapshotAction()))
mux.HandleFunc("POST /api/backgroundAgent/waitForSnapshot", genkit.Handler(backgroundAgent.WaitForSnapshotAction()))
mux.HandleFunc("POST /api/backgroundAgent/abort", genkit.Handler(backgroundAgent.AbortAction()))
```
One `waitForSnapshot` request holds for at most `aix.WithMaxSnapshotWait`
(default
25s), then answers with the row as it stands (`pending`/`aborting`); a direct
HTTP client must loop until settled. `aix.AgentHandle` (local or
`genkitx.DefineRemoteAgent`) does that for you. `AbortAction()` is non-nil only
when the store implements `aix.SnapshotSubscriber`. See
[deployment](agents-deployment.md).
## Status values (`aix.SnapshotStatus`)
- `SnapshotStatusPending`: still processing.
- `SnapshotStatusAborting`: abort requested; the worker is winding down. Not
terminal: `Wait` keeps waiting.
- `SnapshotStatusCompleted`: finished successfully; read the result from
`snap.State.Messages`.
- `SnapshotStatusFailed`: a turn broke; details on `snap.Error`, completed
turns in `snap.State`. Resumable.
- `SnapshotStatusAborted`: stopped by the caller; `snap.State` holds the turns
that finished. Resumable.
- `SnapshotStatusExpired`: the background worker stopped responding (its
heartbeat went stale, e.g. a server restart). Computed on read, never
persisted; terminal — the task can never complete.
agents-branching.md 3.9 KB
# Agent Branching (Experimental)
> **Experimental / preview API.** Requires a [session store](agents-sessions.md)
> so snapshots are persistent. Read [agents.md](agents.md) first.
A `SnapshotID` is an **immutable checkpoint**, like a git commit. You can fork
as
many independent timelines as you want from the same snapshot — each turn from a
snapshot creates a new, independent snapshot; the original is unchanged.
To branch, run a turn resuming from an earlier snapshot via
`aix.WithSnapshotID(id)`.
- [Branch from a checkpoint](#branch-from-a-checkpoint): Lines 21-49
- ["Pick a variant"](#pick-a-variant): Lines 51-79
- [Resume by session vs. by snapshot](#resume-by-session-vs-by-snapshot): Lines 81-86
- [Restore history from a snapshot](#restore-history-from-a-snapshot): Lines 88-111
---
## Branch from a checkpoint
```go
assistant := genkitx.DefineAgent(g, "assistant",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are a helpful assistant."),
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()),
)
root, _ := assistant.RunText(ctx, "Hello!")
checkpoint := root.SnapshotID // branch point
// Branch A - forks from `checkpoint`.
a1, _ := assistant.RunText(ctx, "My name is Bob.", aix.WithSnapshotID(checkpoint))
a2, _ := assistant.RunText(ctx, "What is my name?", aix.WithSnapshotID(a1.SnapshotID)) // -> Bob
// Branch B - forks from the SAME `checkpoint`, fully independent.
b1, _ := assistant.RunText(ctx, "My name is John.", aix.WithSnapshotID(checkpoint))
b2, _ := assistant.RunText(ctx, "What is my name?", aix.WithSnapshotID(b1.SnapshotID)) // -> John
_ = a2
_ = b2
```
Each turn returns a fresh `SnapshotID`; the two branches never share one past
the
common `checkpoint`.
## "Pick a variant"
A common pattern: generate two variants from the same checkpoint in parallel,
let the user pick one, and continue from the chosen snapshot.
```go
func twoVariants(ctx context.Context, agent *aix.Agent[any], checkpoint, text string) (a, b *aix.AgentOutput[any], err error) {
var wg sync.WaitGroup
var errA, errB error
wg.Add(2)
go func() { defer wg.Done(); a, errA = agent.RunText(ctx, text, aix.WithSnapshotID(checkpoint)) }()
go func() { defer wg.Done(); b, errB = agent.RunText(ctx, text, aix.WithSnapshotID(checkpoint)) }()
wg.Wait()
if errA != nil {
return nil, nil, errA
}
if errB != nil {
return nil, nil, errB
}
return a, b, nil // a.SnapshotID != b.SnapshotID; both branch from the same point
}
// When the user picks a variant, its SnapshotID becomes the new branch point:
// checkpoint = chosen.SnapshotID
```
When no branch point exists yet (the very first turn), start a fresh session by
omitting the invocation option, then use the returned `SnapshotID` as the branch
point going forward.
## Resume by session vs. by snapshot
- `aix.WithSnapshotID(id)` — fork from an **exact** checkpoint (branching).
- `aix.WithSessionID(id)` — continue the session's **latest** snapshot. If
history was forked, the most recently created branch wins; use
`WithSnapshotID` when you need a specific branch.
## Restore history from a snapshot
Use `Agent.GetSnapshot` to read a snapshot's state without starting a turn —
handy for restoring a UI after a reload (e.g. a `SnapshotID` stored in the URL).
```go
snap, err := assistant.GetSnapshot(ctx, snapshotID)
if err != nil {
log.Fatal(err)
}
for _, m := range snap.State.Messages {
if m.Role == ai.RoleUser || m.Role == ai.RoleModel {
fmt.Printf("%s: %s\n", m.Role, m.Text())
}
}
```
Over HTTP, expose `Agent.GetSnapshotAction()` so a remote client can fetch
snapshots (see [agents.md](agents.md#serve-an-agent-over-http)).
> Abandoned branches simply remain in the store as immutable snapshots; nothing
> is overwritten when you branch. (A `FileSessionStore` configured with
> `WithMaxPersistedChainLength` prunes only along a single chain's parent links,
> so sibling branches are retained independently.)
agents-custom.md 7.1 KB
# Advanced Custom Agents — `DefineCustomAgent` (Experimental)
> **Experimental / preview API.** `genkitx.DefineCustomAgent` comes from
> `genkit/exp`. Read [agents.md](agents.md) and [agent state](agents-state.md)
> first.
`DefineAgent` runs a single prompt + tool loop. When you need **full control of
the turn** — multiple sequential model calls, custom logic between them, manual
message/state management, or custom progress streaming — use
`genkitx.DefineCustomAgent`. You provide the function that runs the turn loop.
- [When to use it](#when-to-use-it): Lines 20-30
- [Signature](#signature): Lines 32-71
- [Example: multi-step research agent](#example-multi-step-research-agent): Lines 73-162
- [Custom status streaming](#custom-status-streaming): Lines 164-194
- [Notes](#notes): Lines 196-209
---
## When to use it
Reach for `DefineCustomAgent` when a turn needs to:
- make **multiple model calls** with your own orchestration between them;
- run **multi-step workflows** (decompose → research → synthesize);
- **manually manage** messages and custom state;
- **stream custom status** updates to the client mid-turn.
Otherwise prefer `DefineAgent` (simpler; custom state still works — see
[agent state](agents-state.md)).
## Signature
```go
func DefineCustomAgent[State any](
g *genkit.Genkit,
name string,
fn aix.AgentFunc[State],
opts ...aix.AgentOption[State],
) *aix.Agent[State]
// where:
type AgentFunc[State any] = func(ctx context.Context, resp aix.Responder, sess *aix.SessionRunner[State]) (*aix.AgentResult, error)
```
Your `fn` receives:
- `resp aix.Responder` — the output channel to the client.
`resp.SendModelChunk(chunk)`
streams generation tokens; `resp.SendArtifact(a)` streams (and records) an
artifact. Sends are fire-and-forget.
- `sess *aix.SessionRunner[State]` — the session plus turn-loop control. Call
`sess.Run(ctx, perTurn)` to enter the loop; it blocks per turn until the
client
sends the next input.
Key `sess` methods:
- `sess.Run(ctx, func(ctx, input *aix.AgentInput) (*aix.TurnResult, error))` —
runs the turn loop. The incoming `input.Message` is added to the session
before
your callback runs, so `sess.Messages()` includes it. Return a
`*aix.TurnResult`
to report the finish reason (or `nil` to report none).
- `sess.Messages()` / `sess.AddMessages(...)` / `sess.SetMessages(...)` — read
and
write conversation history.
- `sess.UpdateCustom(fn)` — mutate typed custom state; auto-streams a
`CustomPatch` chunk (see [state](agents-state.md)).
- `sess.Result()` — build an `*aix.AgentResult` from the current session (last
message + artifacts), a convenience for the return value.
## Example: multi-step research agent
```go
type ResearchState struct {
Status string `json:"status,omitempty"` // live progress shown to the client
SubQuestions []string `json:"subQuestions"`
SubAnswers []QA `json:"subAnswers"`
}
type QA struct {
Question string `json:"question"`
Answer string `json:"answer"`
}
researchAgent := genkitx.DefineCustomAgent(g, "researchAgent",
func(ctx context.Context, resp aix.Responder, sess *aix.SessionRunner[ResearchState]) (*aix.AgentResult, error) {
var lastMessage *ai.Message
err := sess.Run(ctx, func(ctx context.Context, input *aix.AgentInput) (*aix.TurnResult, error) {
userText := input.Message.Text()
// Step 1: decompose. Mutating custom state auto-emits a CustomPatch
// chunk so the client's tracked state stays live.
sess.UpdateCustom(func(s ResearchState) ResearchState {
s.Status = "Decomposing question…"
return s
})
subQs, _, err := genkit.GenerateData[[]string](ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Break this into 2-3 sub-questions (JSON array): %q", userText),
)
if err != nil {
return nil, err
}
sess.UpdateCustom(func(s ResearchState) ResearchState {
s.SubQuestions, s.SubAnswers = *subQs, nil
return s
})
// Step 2: research each sub-question.
var answers []QA
for i, q := range *subQs {
sess.UpdateCustom(func(s ResearchState) ResearchState {
s.Status = fmt.Sprintf("Researching (%d/%d)", i+1, len(*subQs))
return s
})
a, err := genkit.GenerateText(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt(q),
)
if err != nil {
return nil, err
}
answers = append(answers, QA{Question: q, Answer: a})
}
sess.UpdateCustom(func(s ResearchState) ResearchState {
s.SubAnswers, s.Status = answers, "Synthesizing…"
return s
})
// Step 3: synthesize and STREAM the final answer to the client.
var reason aix.AgentFinishReason
for result, err := range genkit.GenerateStream(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Synthesize a unified answer from: %v", answers),
) {
if err != nil {
return nil, err
}
if result.Done {
lastMessage = result.Response.Message
reason = aix.AgentFinishReason(result.Response.FinishReason)
sess.AddMessages(lastMessage) // record the final response in history
} else {
resp.SendModelChunk(result.Chunk) // stream model output to the client
}
}
sess.UpdateCustom(func(s ResearchState) ResearchState { s.Status = "Done"; return s })
// Report how the turn ended; the framework forwards it on TurnEnd and
// persists it on the snapshot.
return &aix.TurnResult{FinishReason: reason}, nil
})
if err != nil {
return nil, err
}
return sess.Result(), nil
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[ResearchState]()),
)
```
## Custom status streaming
Calling `sess.UpdateCustom(...)` during the turn automatically emits a
`CustomPatch` chunk, so a connection's tracked [custom state](agents-state.md)
(e.g. the `Status` field) stays live **mid-stream** without extra wiring. Stream
model output separately with `resp.SendModelChunk(chunk)`.
Run a custom agent exactly like a regular one:
```go
conn, _ := researchAgent.Connect(ctx,
aix.WithState(&aix.SessionState[ResearchState]{}),
)
_ = conn.SendText("Impacts of electric vehicles?")
for chunk, err := range conn.Receive() {
if err != nil {
log.Fatal(err)
}
if chunk.ModelChunk != nil {
fmt.Print(chunk.ModelChunk.Text()) // model output
}
if len(chunk.CustomPatch) > 0 {
cur, _ := conn.Custom()
fmt.Println("status:", cur.Status) // live progress
}
if chunk.TurnEnd != nil {
break
}
}
out, _ := conn.Output()
```
## Notes
- **Per-turn metadata.** Inside the `sess.Run` callback,
`aix.TurnContextFromContext(ctx)` returns the turn's `SnapshotID`,
`ParentSnapshotID`, and `TurnIndex` — reserved before the turn runs, so you
can
name external resources (e.g. a git worktree) after the snapshot up front.
- **Validate untrusted resume.** If you accept `input.Resume` from untrusted
callers, call
`aix.ValidateResumeAgainstHistory(input.Resume, sess.Messages())`
before forwarding it to the model (the prompt-backed loop does this for you).
- **Recovering from a failed turn.** If your callback returns an error, `Run`
records the failure and stops; you may call `Run` again to keep processing, or
return the error to resolve the invocation as a failed `AgentOutput`.
agents-deployment.md 7.1 KB
# Deploying / Serving Agents over HTTP (Experimental)
> **Experimental / preview API.** Uses `genkit.Handler` and the agent's
> companion
> actions. Read [agents.md](agents.md) first.
An agent is an `api.BidiAction`, so `genkit.Handler(agent)` serves it as a
standard HTTP action — **one turn per request**. Most agents also expose two
companion actions:
- `agent.GetSnapshotAction()` — read a snapshot's state. Needed for
[snapshot restore](agents-branching.md) and [background](agents-background.md)
polling. `nil` for a client-managed agent (no store).
- `agent.AbortAction()` — cancel a [background](agents-background.md) turn.
`nil` unless the store implements `aix.SnapshotSubscriber` (both `localstore`
stores do).
- [Request/response shape](#requestresponse-shape): Lines 27-44
- [Serve with the built-in route layout (recommended)](#serve-with-the-built-in-route-layout-recommended): Lines 46-77
- [A reusable helper for several agents (manual wiring)](#a-reusable-helper-for-several-agents-manual-wiring): Lines 79-125
- [CORS for browser clients](#cors-for-browser-clients): Lines 127-154
- [Registering agents](#registering-agents): Lines 156-163
- [Verifying locally](#verifying-locally): Lines 165-188
---
## Request/response shape
The handler accepts `{"data": <AgentInput>, "init": <AgentInit>}`:
- `data` — the turn's `aix.AgentInput` (message, resume, or `detach`). Required
for one-shot (non-streaming) requests.
- `init` — the session source: `{"sessionId": ...}` or `{"snapshotId": ...}` for
server-managed agents, `{"state": ...}` for client-managed ones. Omit for a
fresh conversation.
Responses come back as `{"result": <AgentOutput>}`. Stream chunks (`modelChunk`,
`turnEnd`, then the final `result`) by either setting
`Accept: text/event-stream`
or adding `?stream=true` to the URL — the handler honors both. Turn-tier
failures
return **200** with a failed `AgentOutput` (so the caller keeps its last-good
state); init-tier failures (a rejected session source) are hard HTTP errors
(400/404).
## Serve with the built-in route layout (recommended)
`genkit/exp` ships a default HTTP layout so you don't hand-wire companions.
`genkitx.AllAgentRoutes(g)` returns a `[]genkitx.Route` covering every
registered
agent; `genkitx.AgentRoutes(agent)` does one agent. Each `Route` exposes
`Pattern()` (a `"METHOD /path"` string for `http.ServeMux`) and
`Handler(opts...)` (builds the `genkit.Handler`, passing any `HandlerOption`s).
The layout follows each agent's capabilities, mounting under `/agents`:
```go
mux := http.NewServeMux()
for _, route := range genkitx.AllAgentRoutes(g) {
mux.HandleFunc(route.Pattern(), route.Handler())
}
log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux))
```
This produces, per agent:
```
POST /agents/<name> one turn per request
POST /agents/<name>/getSnapshot read a snapshot (store-backed agents)
POST /agents/<name>/abort abort background work (abortable stores)
```
Companion routes are omitted for capabilities an agent lacks: a client-managed
agent contributes only its turn route. To serve specific agents instead of all
of them, use `genkitx.AgentRoutes(agent)`; to expose flows,
`genkitx.AllFlowRoutes(g)` / `genkitx.FlowRoutes(flow)`. Mix them by
concatenating the route slices. Any router works the same way (Gin, Chi, Echo):
read `Pattern()` and serve `Handler()`.
## A reusable helper for several agents (manual wiring)
If you'd rather wire routes by hand (a custom path scheme, extra middleware per
route, a `/api`-style prefix), mount the agent and pluck its companions off the
typed value. A small helper keeps companion wiring consistent.
```go
func exposeAgent[State any](mux *http.ServeMux, agent *aix.Agent[State]) {
base := "/api/" + agent.Name()
mux.HandleFunc("POST "+base, genkit.Handler(agent))
if snap := agent.GetSnapshotAction(); snap != nil {
mux.HandleFunc("POST "+base+"/getSnapshot", genkit.Handler(snap))
}
if abort := agent.AbortAction(); abort != nil {
mux.HandleFunc("POST "+base+"/abort", genkit.Handler(abort))
}
}
mux := http.NewServeMux()
exposeAgent(mux, weatherAgent) // plain chat: no companions registered
exposeAgent(mux, branchingAgent) // has a store: getSnapshot registered
exposeAgent(mux, backgroundAgent) // store + subscriber: getSnapshot + abort
log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux))
```
To mount every agent generically, `genkitx.ListAgents(g)` returns every
registered agent (companions are typed on the concrete `*aix.Agent[State]`, so
from `ListAgents` you serve the run action directly and pluck companions off the
typed value where you have it):
```go
for _, a := range genkitx.ListAgents(g) {
mux.HandleFunc("POST /api/"+a.Name(), genkit.Handler(a))
}
```
For most deployments prefer the built-in route layout above
(`genkitx.AllAgentRoutes`), which wires companions for you.
Which companions to enable:
| Agent capability | `getSnapshot` | `abort` |
| ----------------------------------------- | ------------- | ------- |
| Plain chat (client- or server-state) | – | – |
| Snapshot restore / [branching](agents-branching.md) | ✓ | – |
| [Background](agents-background.md) / detach | ✓ | ✓ |
## CORS for browser clients
A browser calling a different origin (e.g. a Vite dev server) needs CORS.
Streaming uses Server-Sent Events, so allow the `Accept` header and handle
preflight.
```go
func withCORS(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Accept")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
h.ServeHTTP(w, r)
})
}
```
`server.Start` takes a `*http.ServeMux`, so wrap the mux with
`http.ListenAndServe`
(which accepts any `http.Handler`) to apply CORS around every route:
```go
log.Fatal(http.ListenAndServe("127.0.0.1:8080", withCORS(mux)))
```
## Registering agents
Agents register with Genkit when their `genkitx.DefineAgent` (or
`DefineCustomAgent` / `DefinePromptAgent`) call runs, so make sure the code that
defines them executes during startup. Keep a reference to the returned
`*aix.Agent[State]` to reach `RunText`, `GetSnapshot`, `Abort`, and the
companion
actions from your own code.
## Verifying locally
Run under the Genkit CLI so turns are traced, and drive the endpoint with
`curl`:
```bash
genkit start -- go run .
```
```bash
# One-shot turn:
curl -s localhost:8080/api/weatherAgent \
-H 'Content-Type: application/json' \
-d '{"data":{"message":{"role":"user","content":[{"text":"Weather in Tokyo?"}]}}}'
# Resume a server-managed session:
curl -s localhost:8080/api/weatherAgent \
-H 'Content-Type: application/json' \
-d '{"data":{"message":{"role":"user","content":[{"text":"And Paris?"}]}},"init":{"sessionId":"<id>"}}'
```
You can also exercise an agent from the CLI by wrapping one turn in a throwaway
flow and using `genkit flow:run` (see
[agents.md](agents.md#verify-an-agent-from-the-cli-flowrun)).
agents-human-in-the-loop.md 7.7 KB
# Agent Human-in-the-Loop / Interrupts (Experimental)
> **Experimental / preview API.** Read [agents.md](agents.md) first. The
> resumable tool API below requires Genkit Go v1.14.0+.
An **interrupt** pauses an agent mid-turn and hands control back to your code
(or
a human), e.g. to approve a sensitive action, collect missing input, or confirm
a plan. Internally it's a **tool call used as control flow**: the interrupting
tool does not produce a normal result; it pauses the turn. You then **resume**
from the exact point it paused.
Interrupts are **orthogonal to persistence**: they work the same whether the
agent uses a [session store](agents-sessions.md) or
[client-managed state](agents.md#client-managed-vs-server-managed-state). The
paused turn just needs to be carried back into the resume: with a store the
session/snapshot ID does it; without one you round-trip the state blob.
The tool side is identical to plain `Generate` (see [tools.md](tools.md)):
`genkit.DefineResumableTool`, `tool.Interrupt`, and the claim through the tool's
`Interrupted` method. Only the delivery differs: an agent takes the resume parts
in an `aix.ToolResume` via `conn.SendResume` or `AgentInput.Resume`.
- [Define a resumable tool](#define-a-resumable-tool): Lines 31-102
- [Detect, claim, and resume (streaming connection)](#detect-claim-and-resume-streaming-connection): Lines 104-167
- [Single-turn resume with Run](#single-turn-resume-with-run): Lines 169-192
- [Notes and gotchas](#notes-and-gotchas): Lines 194-213
---
## Define a resumable tool
`genkit.DefineResumableTool[In, Out, Res]` defines a tool that can pause by
returning `tool.Interrupt(ctx, data)`. `Res` is what the caller sends back; it
arrives as the `*Res` parameter, `nil` on the first call.
```go
import (
"context"
"fmt"
"github.com/firebase/genkit/go/ai"
aix "github.com/firebase/genkit/go/ai/exp"
"github.com/firebase/genkit/go/ai/exp/localstore"
"github.com/firebase/genkit/go/ai/tool"
"github.com/firebase/genkit/go/genkit"
genkitx "github.com/firebase/genkit/go/genkit/exp"
)
type TransferInput struct {
Amount float64 `json:"amount"`
ToAccount string `json:"toAccount"`
}
type TransferOutput struct {
Success bool `json:"success"`
TransactionID string `json:"transactionId,omitempty"`
}
// ApprovalAsk is the data the tool pauses with.
type ApprovalAsk struct {
Details string `json:"details"`
}
// ApprovalReply is the resume type the caller answers with.
type ApprovalReply struct {
Approved bool `json:"approved"`
Feedback string `json:"feedback,omitempty"`
}
transferMoney := genkit.DefineResumableTool(g, "transferMoney",
"Transfer money to a specified account, pausing for user approval.",
func(ctx context.Context, in TransferInput, reply *ApprovalReply) (TransferOutput, error) {
if reply == nil {
// First call: pause and surface the request to the caller.
return TransferOutput{}, tool.Interrupt(ctx, ApprovalAsk{
Details: fmt.Sprintf("Transfer $%.2f to %s", in.Amount, in.ToAccount),
})
}
if !reply.Approved {
return TransferOutput{Success: false}, nil
}
return TransferOutput{Success: true, TransactionID: "txn-123"}, nil
},
)
bankingAgent := genkitx.DefineAgent(g, "bankingAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are a banking assistant. Use transferMoney to move funds; it will pause for user approval."),
ai.WithTools(transferMoney),
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()),
)
```
`tool.Interrupt` data must serialize to a JSON object (a struct or map) or be
`nil`. The resume type must be a struct or map too.
Returning an ordinary Go `error` from the tool is different: it **fails the
turn** rather than pausing it (wrapped as `ai.ErrToolFailed`). Return
`tool.Fail(ctx, err)` instead when the model should see the error and retry; see
[tools.md](tools.md#errors-the-model-can-fix).
## Detect, claim, and resume (streaming connection)
Collect interrupt parts from the stream with `chunk.ModelChunk.Interrupts()`,
claim each with the tool's `Interrupted` method (it decodes the input to `In`),
read the pause data with `ai.InterruptAs[T]`, and resume with `aix.ToolResume`.
```go
conn, err := bankingAgent.Connect(ctx)
if err != nil {
return err
}
_ = conn.SendText("Transfer $500 to my savings account.")
var interrupts []*ai.Part
for chunk, err := range conn.Receive() {
if err != nil {
return err
}
if chunk.ModelChunk != nil {
interrupts = append(interrupts, chunk.ModelChunk.Interrupts()...)
}
if chunk.TurnEnd != nil {
break
}
}
var restart []*ai.Part
for _, part := range interrupts {
call, ok := transferMoney.Interrupted(part)
if !ok {
return fmt.Errorf("no handler for interrupt from tool %q", part.ToolRequest.Name)
}
ask, _ := ai.InterruptAs[ApprovalAsk](part)
fmt.Println(ask.Details, call.Input.Amount) // show this to the human
restart = append(restart, call.Restart(ApprovalReply{Approved: true}))
}
// Resume the same connection, then receive the continuation.
_ = conn.SendResume(&aix.ToolResume{Restart: restart})
for chunk, err := range conn.Receive() {
if err != nil {
return err
}
if chunk.ModelChunk != nil {
fmt.Print(chunk.ModelChunk.Text())
}
if chunk.TurnEnd != nil {
break
}
}
out, _ := conn.Output()
```
### Respond vs. Restart
| Verb | Goes in | Effect |
| --- | --- | --- |
| `call.Restart(res)` | `aix.ToolResume{Restart: ...}` | Re-runs the tool with the typed resume value. |
| `call.RestartWithInput(in, res)` | `aix.ToolResume{Restart: ...}` | Re-runs it with revised input. |
| `call.Respond(out)` | `aix.ToolResume{Respond: ...}` | Supplies the tool's output; the tool does not run again. |
Both lists may appear in one payload. The claim already type-checked the part,
so
the verbs return no error.
## Single-turn resume with `Run`
You don't need a persistent connection. Detect the interrupt on one `Run`, then
resume with another `Run` carrying the `Resume` payload plus the session source.
```go
out, _ := bankingAgent.RunText(ctx, "Transfer $500 to savings.")
if out.FinishReason == aix.AgentFinishReasonInterrupted {
var restart []*ai.Part
for _, part := range out.Message.Content {
if call, ok := transferMoney.Interrupted(part); ok {
restart = append(restart, call.Restart(ApprovalReply{Approved: true}))
}
}
out, _ = bankingAgent.Run(ctx,
&aix.AgentInput{Resume: &aix.ToolResume{Restart: restart}},
aix.WithSessionID[any](out.SessionID), // server-managed: carry the paused turn back
)
}
fmt.Println(out.Message.Text())
```
For a client-managed agent, pass `aix.WithState(out.State)` instead of
`WithSessionID`. Over HTTP the same object rides in `data.resume`.
## Notes and gotchas
- **No store required.** Interrupts work with a
[session store](agents-sessions.md)
or [client-managed state](agents.md#client-managed-vs-server-managed-state).
- **Build resume parts from the claim.** The framework validates every entry
against the most recent model response (name/ref must match). Hand-rolled
parts, or parts from an earlier turn, are rejected.
- **Answer every interrupt** in the turn, or the resume fails.
- **Resumable snapshots.** `completed`, `failed`, and `aborted` snapshots resume
(failed/aborted ones hold the conversation up to the last completed tool
round).
`pending` and `aborting` ones are rejected until they settle.
- **Re-pausing.** After resuming, the turn may interrupt again; loop until the
finish reason is no longer `aix.AgentFinishReasonInterrupted`.
- **`ToolApproval` middleware.** To gate arbitrary tools (rather than writing a
resumable tool by hand), `plugins/middleware`'s `ToolApproval` holds any tool
call outside an allowlist. Claim holds with
`middleware.ToolApprovalInterrupted`.
See [middleware](middleware.md).
agents-multi-agent.md 9.9 KB
# Multi-Agent Orchestration / Sub-Agents (Experimental)
> **Experimental / preview API.** Sub-agent delegation uses the `Agents`
> middleware from `plugins/middleware/exp`. Read [agents.md](agents.md) first.
A common pattern is an **orchestrator** agent that delegates tasks to
specialized
**sub-agents** (e.g. a `researcher` and a `coder`). The `middlewarex.Agents`
middleware injects one delegation tool per sub-agent (`delegate_to_<name>`),
appends a `<sub-agents>` block to the orchestrator's system prompt, and — when
the
model calls a delegation tool — runs the sub-agent with the task and returns its
response as the tool result.
```go
import (
aix "github.com/firebase/genkit/go/ai/exp"
middlewarex "github.com/firebase/genkit/go/plugins/middleware/exp"
"github.com/firebase/genkit/go/plugins/middleware" // Retry, etc.
)
```
- [1. Define the sub-agents](#1-define-the-sub-agents): Lines 34-58
- [2. Wire up the orchestrator](#2-wire-up-the-orchestrator): Lines 60-98
- [middlewarex.Agents fields](#middlewarexagents-fields): Lines 100-119
- [Background delegation (Async: true)](#background-delegation-async-true): Lines 121-160
- [Continuing a task (continue_task)](#continuing-a-task-continue_task): Lines 162-179
- [Delegating to a remote agent](#delegating-to-a-remote-agent): Lines 181-204
- [Sharing artifacts between agents](#sharing-artifacts-between-agents): Lines 206-220
- [Combining with retries](#combining-with-retries): Lines 222-245
---
## 1. Define the sub-agents
Give each sub-agent a description via `aix.WithDescription` — it's
auto-discovered and shown to the orchestrator so the model knows when to
delegate.
```go
researcher := genkitx.DefineAgent(g, "researcher",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are a thorough research assistant. Save findings with write_artifact."),
ai.WithUse(&middleware.Retry{}, &middlewarex.Artifacts{}),
},
aix.WithDescription[any]("A thorough research assistant that provides well-sourced answers."),
)
coder := genkitx.DefineAgent(g, "coder",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are an expert programmer. Save code with write_artifact."),
ai.WithUse(&middlewarex.Artifacts{}, &middleware.Retry{}),
},
aix.WithDescription[any]("An expert programmer that writes clean, well-commented code."),
)
```
## 2. Wire up the orchestrator
Add `&middlewarex.Agents{...}` to the orchestrator's `ai.WithUse`. Reference
each
sub-agent by `aix.AgentRef` — a bare `{Name: ...}` (description auto-discovered
from the registry) or `agent.Ref()` (captures the agent's name and description).
```go
orchestrator := genkitx.DefineAgent(g, "orchestrator",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem(`You are a helpful project assistant. Analyze the request and
delegate to the appropriate sub-agent. If it needs research AND code, call them
sequentially, then synthesize a final answer.`),
ai.WithUse(
&middlewarex.Agents{
Agents: []aix.AgentRef{
{Name: "researcher"}, // by name (description auto-discovered)
coder.Ref(), // by instance (carries its description)
},
MaxDelegations: 5, // guard rail against runaway loops
HistoryLength: 4, // forward the last N user/model messages as context
ArtifactStrategy: middlewarex.ArtifactStrategySession, // see "Sharing artifacts" below
},
&middlewarex.Artifacts{Readonly: true}, // read sub-agent artifacts via read_artifact
&middleware.Retry{},
),
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()),
)
```
Run it like any other agent:
```go
out, _ := orchestrator.RunText(ctx,
"Research the best sorting algorithms, then write a Go quicksort.")
fmt.Println(out.Message.Text())
```
## `middlewarex.Agents` fields
- `Agents` (required): sub-agent references (`[]aix.AgentRef`). Each is a bare
`{Name: ...}` (description auto-discovered) or `agent.Ref()` (explicit).
- `ToolPrefix` (`*string`): prefix for generated delegation tool names. `nil`
defaults to `"delegate_to"` (tools become `delegate_to_<agent>`); a pointer to
the empty string uses bare agent names.
- `MaxDelegations` (`int`): cap on delegations per generate call. `0` means
unlimited. Prevents runaway loops.
- `HistoryLength` (`int`): number of recent user/model messages forwarded to a
sub-agent as context. `0` sends only the task description. History is
forwarded
only to **client-managed** sub-agents (no session store); server-managed
sub-agents receive only the task.
- `ArtifactStrategy` (`middlewarex.ArtifactStrategy`): `ArtifactStrategyInline`
(default) or `ArtifactStrategySession` — see below. The type and its constants
live in `plugins/middleware/exp` alongside the `Agents` middleware.
- `Async` (`bool`): enables background delegation (see below).
- `MaxWaitSeconds` (`int`): caps one `wait_for_background_tasks` call, whatever
timeout the model asks for. `0` lets the model decide.
## Background delegation (`Async: true`)
> Requires Genkit Go v1.14.0+.
By default a delegation blocks the orchestrator's turn. With `Async: true`, each
delegation tool accepts `background: true` and returns a task ID immediately,
and three tools are added:
- `check_background_tasks({taskIds})`: current status, no waiting.
- `wait_for_background_tasks({taskIds, timeoutSeconds, waitFor})`: blocks until
they settle (`waitFor: "first"` returns on the first one).
- `abort_background_tasks({taskIds})`: stops tasks no longer needed.
**The sub-agent needs a session store** (with detach support). Background work
is tracked by a pending snapshot.
```go
researcher := genkitx.DefineAgent(g, "researcher",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("Research one question and answer in a few sentences."),
},
aix.WithDescription[any]("Researches one question."),
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()), // required for background
)
orchestrator := genkitx.DefineAgent(g, "orchestrator",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem(`Give each part of a question to the researcher IN THE BACKGROUND
("background": true), then collect the answers with wait_for_background_tasks.`),
ai.WithUse(&middlewarex.Agents{
Agents: []aix.AgentRef{researcher.Ref()},
Async: true,
}),
ai.WithMaxTurns(10), // background work adds tool rounds
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()),
)
```
## Continuing a task (`continue_task`)
> Requires Genkit Go v1.14.0+.
A delegation to a store-backed sub-agent returns a `taskId` and a settled
`status` even when synchronous. The
`continue_task({taskId, instructions, background})`
tool picks it up:
- **failed / aborted**: continues from the last saved progress (finished tool
calls are not repeated); `instructions` steer the retry.
- **completed**: follow-up `instructions` in the sub-agent's own session.
- **expired**: fences the dead worker, then continues from the parent snapshot.
- **interrupted**: refused (no way to answer the interrupt from here).
Task IDs are scoped to the conversation: the tools accept only IDs this call or
its history minted. Two `Agents` instances in one call need distinct
`ToolPrefix` values.
## Delegating to a remote agent
> Requires Genkit Go v1.14.0+.
Any agent another Genkit app serves over HTTP (Go, JS, or Dart) can be a
sub-agent. Register it with `genkitx.DefineRemoteAgent`; the orchestrator code
is the same as for a local agent, background delegation included:
```go
researcher := genkitx.DefineRemoteAgent(g, "researcher", "https://research.internal/agents/researcher",
aix.WithDescription[any]("Researches one question and answers in a few sentences."),
aix.WithAgentMetadata(&aix.AgentMetadata{
StateManagement: aix.AgentStateManagementServer, // remote keeps its own session
Abortable: true, // its store can stop background work
}),
// aix.WithHTTPClient(idTokenClient), aix.WithHeaders(fn), aix.WithRouteURLs(...)
)
```
`researcher.Ref()` then goes in `Agents` as usual. The handle
(`*aix.AgentHandle`)
also runs the remote agent directly (`Run`, `RunText`, `RunDetached`, `Task`,
`WaitForSnapshot`, `Abort`). The remote server needs a session store for
background tasks and `continue_task`.
## Sharing artifacts between agents
Sub-agents can produce [artifacts](agents-artifacts.md). `ArtifactStrategy`
controls how they reach the orchestrator:
- `middlewarex.ArtifactStrategyInline` (default): artifact content is included
in
the delegation tool result (so the model sees it directly) **and** merged into
the parent session.
- `middlewarex.ArtifactStrategySession`: artifacts are merged into the parent
session only; the tool result lists artifact names, not content. Pair it with
`&middlewarex.Artifacts{}` on the orchestrator so it can `read_artifact` on
demand (the pattern above). Merged artifacts are namespaced by an invocation
ID
(`<agentName>_<n>/<name>`) and tagged with their source agent.
## Combining with retries
`plugins/middleware`'s `Retry` (and `Fallback`) attach the same way via
`ai.WithUse` on an agent, and pair well with delegation:
```go
ai.WithUse(&middleware.Retry{
MaxRetries: 3, // default 3
InitialDelayMs: 1000, // default 1000
MaxDelayMs: 60000, // default 60000
BackoffFactor: 2, // default 2
})
```
See [using middleware](middleware.md) for the full catalog (`Retry`, `Fallback`,
`ToolApproval`, `Filesystem`, `Skills`, `SoftToolErrors`, `ContextCompression`,
`Budget`). A `Budget` on the orchestrator also counts in-process sub-agents, so
delegation cannot spend around the cap.
> Note: a sub-agent failure is reported back to the orchestrator as the
> delegation tool's output, with a task ID to `continue_task` it. A sub-agent
> [interrupt](agents-human-in-the-loop.md) is reported the same way but cannot
> be
> continued, so delegate self-contained tasks.
agents-sessions.md 8.8 KB
# Agent Sessions & Persistence (Experimental)
> **Experimental / preview API.** Session stores come from
> `ai/exp/localstore`. Read [agents.md](agents.md) for the basics first.
When an agent has a `SessionStore` (via `aix.WithSessionStore`), the **server**
owns the session history. Each turn produces an immutable **snapshot**; the
snapshot chain carries conversation state forward. A store also enables
[branching](agents-branching.md) and
[background execution](agents-background.md).
(Interrupts work with or without a store — see
[human-in-the-loop](agents-human-in-the-loop.md).)
- [Pick a store](#pick-a-store): Lines 24-104
- [Turns persist automatically](#turns-persist-automatically): Lines 106-116
- [Resume a conversation](#resume-a-conversation): Lines 118-140
- [Read a snapshot without running a turn](#read-a-snapshot-without-running-a-turn): Lines 142-160
- [Typed session state](#typed-session-state): Lines 162-190
- [Interrupts (human-in-the-loop)](#interrupts-human-in-the-loop): Lines 192-198
- [Implementing a custom SessionStore](#implementing-a-custom-sessionstore): Lines 200-247
---
## Pick a store
`ai/exp/localstore` ships two single-process stores. Both are generic over the
custom-state type `State` (use `any` when you have no typed custom state).
```go
import "github.com/firebase/genkit/go/ai/exp/localstore"
// In-memory: great for tests/dev; lost on restart.
memStore := localstore.NewInMemorySessionStore[any]()
// File-backed: snapshots persisted as <dir>/<prefix>/<snapshotId>.json
// (the prefix defaults to "global"). Returns an error if dir can't be created.
fileStore, err := localstore.NewFileSessionStore[any]("./.snapshots")
if err != nil {
log.Fatal(err)
}
```
`localstore` is for local development, tests, and single-instance apps. For
multi-instance production, use the Firestore or PostgreSQL store, or implement
`aix.SessionStore` against your own database (see below).
### PostgreSQL store (experimental)
> Requires Genkit Go v1.14.0+.
`plugins/postgresql/exp` adds a session store with cross-process abort of
detached runs (`LISTEN`/`NOTIFY`), metadata-only reads, and per-tenant prefixes.
It shares the pool of the registered PostgreSQL plugin:
```go
import (
"github.com/firebase/genkit/go/plugins/postgresql"
pgexp "github.com/firebase/genkit/go/plugins/postgresql/exp"
)
engine, err := postgresql.NewPostgresEngine(ctx,
postgresql.WithCloudSQLInstance("my-project", "us-central1", "my-instance"),
postgresql.WithDatabase("my-database"))
if err != nil {
log.Fatal(err)
}
g := genkit.Init(ctx,
genkit.WithExperimental(),
genkit.WithPlugins(&postgresql.Postgres{Engine: engine}))
store, err := pgexp.NewPostgresSessionStore[ChatState](ctx, g,
pgexp.WithSnapshotPathPrefix(tenantFromContext))
```
Note: since v1.14.0, `PostgresEngine.Close` no longer closes a pool passed with
`postgresql.WithPool`; close it yourself.
`NewFileSessionStore` options:
- `localstore.WithMaxPersistedChainLength(n)`: keep only the newest `n`
snapshots in a chain (each save prunes older ancestors). `n >= 1`.
- `localstore.WithSnapshotPathPrefix(fn)`: derive a per-call subdirectory from
context to isolate snapshots per tenant (e.g. `"org-42/user-7"`).
- `localstore.WithPollInterval(d)`: how often the store re-reads subscribed
snapshot files to observe cross-process status changes (default 2s). This is
what lets one process abort a detached turn another process is running.
```go
pruning, err := localstore.NewFileSessionStore[any]("./.snapshots",
localstore.WithMaxPersistedChainLength(3),
)
```
Attach a store to the agent with `aix.WithSessionStore`:
```go
logbookAgent := genkitx.DefineAgent(g, "logbookAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are a personal logbook assistant."),
},
aix.WithSessionStore(fileStore),
)
```
## Turns persist automatically
Each turn writes a snapshot chained off the previous one. The turn's snapshot ID
is on `out.SnapshotID`; the conversation's stable ID is on `out.SessionID`.
```go
out1, _ := logbookAgent.RunText(ctx, "Log this: I started studying Genkit today.")
out2, _ := logbookAgent.RunText(ctx, "What did I study today?",
aix.WithSessionID(out1.SessionID)) // remembers turn 1
fmt.Println(out1.SnapshotID, out2.SnapshotID)
```
## Resume a conversation
Two ways to resume a server-managed conversation:
- `aix.WithSessionID(id)` — resume the session's **latest** snapshot. Use it
when you track the conversation, not individual snapshots.
- `aix.WithSnapshotID(id)` — resume a **specific** snapshot (see
[branching](agents-branching.md)).
```go
// Continue from the session's latest snapshot:
out, _ := logbookAgent.RunText(ctx, "Add another note.",
aix.WithSessionID(sessionID))
// Or continue from an exact checkpoint:
out, _ = logbookAgent.RunText(ctx, "Add another note.",
aix.WithSnapshotID(snapshotID))
```
Resume is rejected if the latest snapshot is a failed, aborted, or pending dead
end (a pending tip means a detached invocation is still running — wait for it or
abort it). `aix.WithState` is for client-managed agents only and is mutually
exclusive with `WithSessionID` / `WithSnapshotID`.
## Read a snapshot without running a turn
`Agent.GetSnapshot` / `Agent.GetLatestSnapshot` fetch a stored snapshot
(applying
any configured `aix.WithStateTransform`). Handy for restoring a UI after a
reload. They return `FAILED_PRECONDITION` on a client-managed agent (no store).
```go
snap, err := logbookAgent.GetSnapshot(ctx, snapshotID)
if err != nil {
log.Fatal(err)
}
fmt.Println(snap.Status) // aix.SnapshotStatusCompleted, ...
for _, m := range snap.State.Messages {
fmt.Println(m.Role, m.Text())
}
latest, _ := logbookAgent.GetLatestSnapshot(ctx, sessionID)
```
## Typed session state
Parameterize the store (and agent) with a struct to attach typed **custom
state**. State is validated (via JSON) when a snapshot is loaded. See
[working with state](agents-state.md) for reading and mutating it inside tools.
```go
type Profile struct {
Name string `json:"name"`
Tier string `json:"tier"` // "free" | "pro"
}
profileAgent := genkitx.DefineAgent(g, "profileAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("Greet the user by name and tailor answers to their tier."),
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[Profile]()),
)
// Seed custom state on the first turn (client-managed here for illustration;
// with a store you would seed via WithState on a fresh session).
out, _ := profileAgent.Run(ctx,
&aix.AgentInput{Message: ai.NewUserTextMessage("Hello")},
aix.WithState(&aix.SessionState[Profile]{
Custom: Profile{Name: "Ada", Tier: "pro"},
}),
)
```
## Interrupts (human-in-the-loop)
Interrupts pause a turn so a human can approve or provide input, then resume
from
the exact pause point. They work with a store or with client-managed state
(persistence is orthogonal). See
[Human-in-the-loop / interrupts](agents-human-in-the-loop.md).
## Implementing a custom `SessionStore`
For production, implement `aix.SessionStore` (which is `aix.SnapshotReader` +
`aix.SnapshotWriter`) against your database. Add `aix.SnapshotSubscriber` to
support [background/detach](agents-background.md) aborts.
```go
type SnapshotReader[State any] interface {
GetSnapshot(ctx context.Context, snapshotID string) (*SessionSnapshot[State], error)
GetLatestSnapshot(ctx context.Context, sessionID string) (*SessionSnapshot[State], error)
}
type SnapshotWriter[State any] interface {
// Atomically read the row at id (nil if absent), apply fn, and persist the
// result. fn must be pure (it may be retried). Returning (nil, nil) skips
// the write. The store owns identity (SnapshotID); the caller owns
// timestamps and Status. An empty id means "mint a fresh one".
SaveSnapshot(ctx context.Context, snapshotID string,
fn func(existing *SessionSnapshot[State]) (*SessionSnapshot[State], error),
) (*SessionSnapshot[State], error)
}
// Optional: enables detach/abort by observing status changes without polling.
type SnapshotSubscriber interface {
OnSnapshotStatusChange(ctx context.Context, snapshotID string) <-chan SnapshotStatus
}
```
Contract notes: preserve `SessionID` across rewrites (a row's session never
changes); default an empty `Status` to `SnapshotStatusCompleted`; keep
`CreatedAt`/`UpdatedAt` caller-managed (persist them verbatim, never stamp
them);
`GetLatestSnapshot` returns the greatest-`CreatedAt` row, ties broken by
`SnapshotID`. See the `localstore` implementations for a reference.
**Prove it with the conformance suite** (v1.14.0+). `ai/exp/sessionstoretest`
checks a store against the contract the agent runtime relies on; the bundled
stores all run it:
```go
import "github.com/firebase/genkit/go/ai/exp/sessionstoretest"
func TestMyStore(t *testing.T) {
sessionstoretest.Run(t, func(t *testing.T) aix.SessionStore[MyState] {
return newEmptyStore(t)
}, nil) // or &sessionstoretest.Options[MyState]{Reopen: ..., Scoped: ...}
}
```
agents-state.md 5.1 KB
# Working with Agent State (Experimental)
> **Experimental / preview API.** Read [agents.md](agents.md) first.
Beyond message history, an agent session can hold typed **custom state** — your
own structured data (a task list, a workflow status, counters, etc.). Tools read
and mutate it during a turn, and every mutation is streamed to a connected
client
as a JSON Patch so the client's view stays live.
- [Declare the state shape](#declare-the-state-shape): Lines 20-46
- [Read and mutate state inside tools](#read-and-mutate-state-inside-tools): Lines 48-91
- [Seed and read state](#seed-and-read-state): Lines 93-110
- [Live state on a connection](#live-state-on-a-connection): Lines 112-141
- [Prompt templating with state](#prompt-templating-with-state): Lines 143-151
- [Custom status streaming from a custom agent](#custom-status-streaming-from-a-custom-agent): Lines 153-158
---
## Declare the state shape
The custom-state type is the `State` type parameter of the agent (and its
store).
It lives under `Custom` of `aix.SessionState[State]`.
```go
type TaskItem struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
type TaskState struct {
Tasks []TaskItem `json:"tasks"`
NextID int `json:"nextId"`
}
taskAgent := genkitx.DefineAgent(g, "taskAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You manage the user's task list. Use the tools to modify it."),
ai.WithTools(addTask), // defined below
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[TaskState]()),
)
```
## Read and mutate state inside tools
Inside a tool, get the live session from context with
`aix.SessionFromContext[State](ctx)`, then read with `session.Custom()` and
mutate with `session.UpdateCustom(fn)`. `UpdateCustom` takes
`func(State) State` and writes the result back atomically. When the session is
driven by an agent invocation, the mutation is automatically streamed to the
client as an `AgentStreamChunk.CustomPatch`.
```go
type AddTaskInput struct {
Title string `json:"title"`
}
addTask := genkit.DefineTool(g, "addTask",
"Add a new task. Returns the created task.",
func(ctx *ai.ToolContext, in AddTaskInput) (TaskItem, error) {
session := aix.SessionFromContext[TaskState](ctx.Context)
if session == nil {
return TaskItem{}, fmt.Errorf("addTask must run inside an agent session")
}
var created TaskItem
session.UpdateCustom(func(s TaskState) TaskState {
if s.NextID == 0 {
s.NextID = 1
}
created = TaskItem{ID: s.NextID, Title: in.Title, Done: false}
s.Tasks = append(s.Tasks, created)
s.NextID++
return s
})
return created, nil
},
)
```
`aix.SessionFromContext[State]` returns `nil` outside an active session (or when
the `State` type does not match), so guard against it. Note the tool's context
is
`ctx.Context` (the `*ai.ToolContext` embeds the standard `context.Context`).
> Do not call other `Session` methods (or send on a `Responder`) from inside the
> `UpdateCustom` callback: it runs while the session lock is held and would
> deadlock.
## Seed and read state
Seed initial custom state with `aix.WithState` on the first turn. For a
server-managed agent, later turns resume with `aix.WithSessionID` and the state
is loaded from the snapshot.
```go
out, _ := taskAgent.Run(ctx,
&aix.AgentInput{Message: ai.NewUserTextMessage("Add a task: buy groceries")},
aix.WithState(&aix.SessionState[TaskState]{
Custom: TaskState{Tasks: nil, NextID: 1},
}),
)
// For a client-managed agent, the final state is on out.State:
if out.State != nil {
fmt.Printf("%+v\n", out.State.Custom)
}
```
## Live state on a connection
A connection tracks custom state as it streams: each `Receive()`d chunk carries
a
`CustomPatch` (an RFC 6902 JSON Patch delta), which the connection applies to an
internal copy. Read it any time with `conn.Custom()`.
```go
conn, _ := taskAgent.Connect(ctx,
aix.WithState(&aix.SessionState[TaskState]{Custom: TaskState{NextID: 1}}),
)
_ = conn.SendText("Add buy groceries, then mark it done")
for chunk, err := range conn.Receive() {
if err != nil {
log.Fatal(err)
}
if len(chunk.CustomPatch) > 0 {
cur, _ := conn.Custom() // TaskState reflecting deltas so far
fmt.Printf("live: %+v\n", cur)
}
if chunk.TurnEnd != nil {
break
}
}
```
The first `CustomPatch` of each turn is a whole-document replace (re-basing the
client); later patches are incremental diffs. The authoritative final state is
on
`out.State` (client-managed) or the turn-end snapshot (server-managed).
## Prompt templating with state
Inside a prompt template, the session's custom state is available as
`{{@state}}`,
evaluated fresh at render time so the template always sees the latest values.
```go
ai.WithSystem("The user's current task list: {{json @state.tasks}}. Help them manage it."),
```
## Custom status streaming from a custom agent
For live mid-turn progress (a `status` field that updates as a long turn runs),
mutate custom state from a [custom agent](agents-custom.md): every
`UpdateCustom` emits a `CustomPatch` chunk automatically, so the connection's
`Custom()` stays live without extra wiring.
agents.md 13.7 KB
# Agents (Experimental)
> **Experimental / preview API.** Agents live in the `genkit/exp` and `ai/exp`
> packages and are gated behind an opt-in. Initialize Genkit with
> `genkit.WithExperimental()` or the constructors panic. Import paths and
> signatures may change in any minor release.
An **agent** is a persistent, multi-turn conversation primitive built on top of
prompts + tools. Compared to a bare `genkit.Generate` loop, an agent adds:
- **Sessions**: multi-turn history tracked as immutable **snapshots**.
- **State**: typed session state (messages + custom data + artifacts).
- **Interrupts**: human-in-the-loop pause/resume.
- **Branching**: fork a conversation from any snapshot.
- **Detaching**: run a turn in the background and poll for the result.
Read the file for the level you need:
- This file: defining an agent, running it, serving it, and **client-managed
state** (no store).
- [Sessions & persistence](agents-sessions.md): `SessionStore`,
`localstore.NewInMemorySessionStore`, `localstore.NewFileSessionStore`.
- [Human-in-the-loop / interrupts](agents-human-in-the-loop.md): pausing for
approval/input and resuming.
- [Branching](agents-branching.md): forking a conversation from a snapshot.
- [Background agents](agents-background.md): detaching long-running turns and
polling.
- [Working with state](agents-state.md): typed custom session state and streamed
patches.
- [Artifacts](agents-artifacts.md): producing/reading named deliverables.
- [Multi-agent orchestration](agents-multi-agent.md): delegating to sub-agents.
- [Advanced custom agents](agents-custom.md): `DefineCustomAgent` for full turn
control.
- [Deploying agents](agents-deployment.md): serving agents over HTTP.
- [Packages and import aliases](#packages-and-import-aliases): Lines 48-65
- [Setup](#setup): Lines 67-78
- [Define an agent](#define-an-agent): Lines 80-177
- [Agents and middleware go hand in hand](#agents-and-middleware-go-hand-in-hand): Lines 179-204
- [Run an agent (single turn)](#run-an-agent-single-turn): Lines 206-234
- [Chat with an agent (multi-turn)](#chat-with-an-agent-multi-turn): Lines 236-279
- [Verify an agent from the CLI (flow:run)](#verify-an-agent-from-the-cli-flowrun): Lines 281-296
- [Serve an agent over HTTP](#serve-an-agent-over-http): Lines 298-339
- [Client-managed vs server-managed state](#client-managed-vs-server-managed-state): Lines 341-381
---
## Packages and import aliases
Agents span a few packages. These aliases are used throughout the agent docs:
```go
import (
"github.com/firebase/genkit/go/ai"
aix "github.com/firebase/genkit/go/ai/exp" // types: Agent, Session, options, AgentInput/Output
"github.com/firebase/genkit/go/ai/exp/localstore" // session stores
"github.com/firebase/genkit/go/genkit"
genkitx "github.com/firebase/genkit/go/genkit/exp" // constructors: DefineAgent, DefineCustomAgent, ...
)
```
`genkitx` (genkit/exp) holds the registry-aware constructors you call.
`aix` (ai/exp) holds the types, options, and the returned `*aix.Agent[State]`.
Both packages are named `exp`, which is why the docs alias them `genkitx` and
`aix`.
## Setup
```go
ctx := context.Background()
g := genkit.Init(ctx,
genkit.WithExperimental(), // REQUIRED: opts into the genkit/exp surface
genkit.WithPlugins(&googlegenai.GoogleAI{}),
)
```
Without `genkit.WithExperimental()`, `genkitx.DefineAgent` (and every other
`genkit/exp` constructor) panics with a message pointing you at the fix.
## Define an agent
`genkitx.DefineAgent` combines an inline prompt + tools + (optional) session
store into a single registered action. The prompt is an `aix.InlinePrompt` — a
slice of `ai.PromptOption` values, the same options you would pass to
`genkit.DefinePrompt`.
```go
type WeatherInput struct {
City string `json:"city"`
}
type WeatherOutput struct {
TempC float64 `json:"tempC"`
Summary string `json:"summary"`
}
getWeather := genkit.DefineTool(g, "getWeather",
"Look up the current weather for a city.",
func(ctx *ai.ToolContext, in WeatherInput) (WeatherOutput, error) {
return WeatherOutput{TempC: 21, Summary: "Sunny"}, nil
},
)
weatherAgent := genkitx.DefineAgent(g, "weatherAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are a helpful weather assistant. Use the getWeather tool. Be concise."),
ai.WithTools(getWeather),
},
// A session store is optional. Omit it for client-managed state (see below).
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()),
)
```
The `State` type parameter is inferred from the typed options (here
`aix.WithSessionStore(...[any]())` makes `State = any`). For a
**client-managed**
agent with no typed option, pass `State` explicitly:
`genkitx.DefineAgent[any](g, "name", prompt)`.
Constructor choices:
- `genkitx.DefineAgent` — inline prompt (the common case, above).
- `genkitx.DefinePromptAgent` — back the agent with a prompt already in the
registry (e.g. a `.prompt` file). By default it uses the prompt registered
under the agent's own name; use `aix.WithNamedPrompt` to point at another.
- `genkitx.DefineCustomAgent` — full control over the turn loop. See
[advanced custom agents](agents-custom.md).
### Backing an agent with a `.prompt` file
`genkitx.DefinePromptAgent` pairs an agent with a prompt from the registry — for
example a `.prompt` file loaded at startup — so prompt authors can tune the
model, config, template, and default input without touching the Go wiring. With
no source option it defaults to the prompt registered under the agent's own
name.
```prompt
---
# prompts/chef.prompt
model: googleai/gemini-flash-latest
input:
schema: ChatPromptInput
default:
personality: a Michelin-starred chef who loves explaining technique
---
You are {{personality}}. Keep every answer very brief, a few sentences at most.
```
If the `.prompt` frontmatter references a schema by name, register that Go type
with `genkit.DefineSchemasFor` **before** defining the agent (the prompt is
rendered at definition time):
```go
type ChatPromptInput struct {
Personality string `json:"personality"`
}
genkit.DefineSchemasFor(g, ChatPromptInput{}) // resolve "ChatPromptInput" in the .prompt
chef := genkitx.DefinePromptAgent(g, "chef", // loads prompts/chef.prompt by name
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()),
aix.WithDescription[any]("Michelin-starred chef"),
)
```
To supply an input from code, or to back several agents with one shared prompt,
add `aix.WithNamedPrompt(name, input)`.
Common agent options (all from `aix`):
- `aix.WithSessionStore(store)`: server-side snapshot persistence. See
[sessions](agents-sessions.md).
- `aix.WithDescription[State](desc)`: human-readable description (shown in the
Dev UI; used by [sub-agent delegation](agents-multi-agent.md)).
- `aix.WithStateTransform[State](fn)`: rewrite state on its way out to a client
(e.g. PII redaction).
- `aix.WithStreamTransform[State](fn)`: rewrite stream chunks on their way out.
## Agents and middleware go hand in hand
Agents and [middleware](middleware.md) are built for each other: the
`ai.WithUse(...)` prompt option layers in behavior without writing it yourself.
Most agent capabilities — sub-agent delegation, artifacts, retries, fallback,
tool approval — are just middleware you drop in.
```go
weatherAgent := genkitx.DefineAgent(g, "weatherAgent",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are a helpful weather assistant."),
ai.WithTools(getWeather),
ai.WithUse(
&middleware.Retry{}, // plugins/middleware: retry transient model errors
&middlewarex.Artifacts{}, // plugins/middleware/exp: read_artifact / write_artifact
),
},
aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()),
)
```
`plugins/middleware` provides `Retry`, `Fallback`, `ToolApproval`, `Filesystem`,
and `Skills`. `plugins/middleware/exp` (aliased `middlewarex`) adds the
agent-specific `Agents` (sub-agent delegation) and `Artifacts` middleware. See
[using middleware](middleware.md) and [multi-agent](agents-multi-agent.md).
## Run an agent (single turn)
`Agent.RunText` and `Agent.Run` run one turn and return the final
`*aix.AgentOutput[State]`.
```go
out, err := weatherAgent.RunText(ctx, "Weather in Tokyo?")
if err != nil {
log.Fatal(err)
}
fmt.Println(out.Message.Text())
fmt.Println(out.SnapshotID) // immutable checkpoint id for this turn (server-managed only)
fmt.Println(out.FinishReason) // e.g. aix.AgentFinishReasonStop
```
`Run` takes an `*aix.AgentInput` when you need more than user text (a full
message, a resume payload, or a detach signal):
```go
out, err := weatherAgent.Run(ctx, &aix.AgentInput{
Message: ai.NewUserTextMessage("Weather in Tokyo?"),
})
```
In-band failures (a failed turn) resolve as a failed `AgentOutput`
(`out.FinishReason == aix.AgentFinishReasonFailed`, `out.Error` populated), not
a
Go `error`. A returned `error` means the invocation never started (e.g. a
rejected session source).
## Chat with an agent (multi-turn)
`Agent.Connect` opens a bidirectional streaming session. A single connection
carries state forward automatically across turns. Send input, iterate
`Receive()` until a `TurnEnd`, then send the next input.
```go
conn, err := weatherAgent.Connect(ctx)
if err != nil {
log.Fatal(err)
}
// Turn 1 (streaming):
_ = conn.SendText("Weather in Tokyo?")
for chunk, err := range conn.Receive() {
if err != nil {
log.Fatal(err)
}
if chunk.ModelChunk != nil {
fmt.Print(chunk.ModelChunk.Text())
}
if chunk.TurnEnd != nil {
break // turn done; safe to send the next input
}
}
// Turn 2 - history is carried automatically on the same connection:
_ = conn.SendText("What about Paris?")
for chunk, err := range conn.Receive() {
if err != nil {
log.Fatal(err)
}
if chunk.TurnEnd != nil {
break
}
}
out, err := conn.Output() // finalize; closes input and drains remaining chunks
```
Connection helpers: `SendText`, `SendMessage`, `Send` (raw `*aix.AgentInput`),
`SendResume` (see [interrupts](agents-human-in-the-loop.md)), `Detach` (see
[background](agents-background.md)), `Receive` (chunk iterator), `Custom`
(live custom state, see [state](agents-state.md)), `Output`, and `Close`.
## Verify an agent from the CLI (`flow:run`)
`genkit flow:run` runs **flows**, not agents, so you can't `flow:run` an agent
directly. To exercise an agent from the CLI (a quick, self-terminating check),
wrap one turn in a throwaway flow and run that:
```go
genkit.DefineFlow(g, "tryWeatherAgent", func(ctx context.Context, message string) (string, error) {
out, err := weatherAgent.RunText(ctx, message)
if err != nil {
return "", err
}
return out.Message.Text(), nil
})
// genkit flow:run tryWeatherAgent '"Weather in Tokyo?"' -- go run .
```
## Serve an agent over HTTP
An agent is an `api.BidiAction`, so `genkit.Handler` serves it one turn per
request. Optionally serve its companion actions for snapshot lookup
(`GetSnapshotAction`) and background aborts (`AbortAction`); both are `nil` for
a
client-managed agent (no store).
```go
mux := http.NewServeMux()
mux.HandleFunc("POST /api/weatherAgent", genkit.Handler(weatherAgent))
// Optional companions (needed for snapshot restore / branching / background):
if snap := weatherAgent.GetSnapshotAction(); snap != nil {
mux.HandleFunc("POST /api/weatherAgent/getSnapshot", genkit.Handler(snap))
}
if abort := weatherAgent.AbortAction(); abort != nil {
mux.HandleFunc("POST /api/weatherAgent/abort", genkit.Handler(abort))
}
log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux))
```
The request body is `{"data": <AgentInput>, "init": <AgentInit>}`. `data`
carries
the turn's input; `init` carries the session source (see below). Set
`Accept: text/event-stream` (or add `?stream=true`) to stream chunks.
Rather than wiring companions by hand, `genkit/exp` ships a default HTTP layout:
`genkitx.AllAgentRoutes(g)` returns a route per registered agent (mounted under
`/agents/<name>`, with `getSnapshot` / `abort` added for capable agents), which
you range over onto a mux:
```go
for _, route := range genkitx.AllAgentRoutes(g) {
mux.HandleFunc(route.Pattern(), route.Handler())
}
```
For serving multiple agents, the route helpers, CORS headers for browser
clients,
and companion routing, see [Deploying agents](agents-deployment.md).
## Client-managed vs server-managed state
**Server-managed** (a `SessionStore` is configured): the server owns history as
snapshots. Resume with `aix.WithSessionID` (latest snapshot of a session) or
`aix.WithSnapshotID` (a specific snapshot). Over HTTP, `init` carries
`{"sessionId": ...}` or `{"snapshotId": ...}`.
```go
out1, _ := weatherAgent.RunText(ctx, "Weather in London?")
out2, _ := weatherAgent.RunText(ctx, "Is it sunny in Tokyo?",
aix.WithSessionID(out1.SessionID)) // resumes the conversation
```
**Client-managed** (no store): the server is stateless and the caller owns the
session state blob (messages + custom + artifacts). Round-trip it via
`aix.WithState` / `out.State`. Over HTTP, `init` carries `{"state": ...}`.
```go
statelessAgent := genkitx.DefineAgent[any](g, "weatherAgentStateless",
aix.InlinePrompt{
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are a helpful weather assistant. Be concise."),
ai.WithTools(getWeather),
},
)
// First turn: start fresh; the framework mints a SessionID inside the state.
out1, _ := statelessAgent.RunText(ctx, "Weather in London?")
// Next turn: pass the returned state back to resume.
out2, _ := statelessAgent.Run(ctx,
&aix.AgentInput{Message: ai.NewUserTextMessage("And Tokyo?")},
aix.WithState(out1.State),
)
fmt.Println(out2.State) // updated blob to carry forward again
```
Use client-managed state when you don't want server-side storage. Use a
[session store](agents-sessions.md) when the server should own history, or when
you need branching or background execution.
([Interrupts](agents-human-in-the-loop.md) work either way.)
flows-and-http.md 4.6 KB
# Flows & HTTP
- [DefineFlow](#defineflow): Lines 10-29
- [DefineStreamingFlow](#definestreamingflow): Lines 31-101
- [Named Sub-Steps](#named-sub-steps): Lines 103-125
- [HTTP Handlers](#http-handlers): Lines 127-192
---
## DefineFlow
Wrap AI logic in a flow for observability, tracing, and HTTP deployment.
```go
jokeFlow := 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),
)
},
)
```
### Running a Flow Directly
```go
result, err := jokeFlow.Run(ctx, "cats")
```
## DefineStreamingFlow
Flows that stream chunks back to the caller. Two common patterns:
### Pattern 1: Passthrough Streaming
Pass the stream callback directly through to `WithStreaming`. The callback type
is `ai.ModelStreamCallback` =
`func(context.Context, *ai.ModelResponseChunk) error`:
```go
genkit.DefineStreamingFlow(g, "streamingJokeFlow",
func(ctx context.Context, topic string, sendChunk ai.ModelStreamCallback) (string, error) {
resp, err := genkit.Generate(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Tell me a long joke about %s", topic),
ai.WithStreaming(sendChunk), // passthrough
)
if err != nil {
return "", err
}
return resp.Text(), nil
},
)
```
### Pattern 2: Manual String Streaming
Use `core.StreamCallback[string]` to stream extracted text:
```go
genkit.DefineStreamingFlow(g, "streamingJokeFlow",
func(ctx context.Context, topic string, sendChunk core.StreamCallback[string]) (string, error) {
stream := genkit.GenerateStream(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Tell me a long joke about %s", topic),
)
for result, err := range stream {
if err != nil {
return "", err
}
if result.Done {
return result.Response.Text(), nil
}
sendChunk(ctx, result.Chunk.Text())
}
return "", nil
},
)
```
### Typed Streaming Flows
Use `core.StreamCallback[T]` with `GenerateDataStream` for typed chunks:
```go
genkit.DefineStreamingFlow(g, "structuredStream",
func(ctx context.Context, input JokeRequest, sendChunk core.StreamCallback[*Joke]) (*Joke, error) {
stream := genkit.GenerateDataStream[*Joke](ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Tell me a joke about %s", input.Topic),
)
for result, err := range stream {
if err != nil { return nil, err }
if result.Done { return result.Output, nil }
sendChunk(ctx, result.Chunk)
}
return nil, nil
},
)
```
## Named Sub-Steps
Use `core.Run` inside a flow for traced sub-steps:
```go
genkit.DefineFlow(g, "pipeline",
func(ctx context.Context, input string) (string, error) {
subject, err := core.Run(ctx, "extract-subject", func() (string, error) {
return genkit.GenerateText(ctx, g,
ai.WithPrompt("Extract the subject from: %s", input),
)
})
if err != nil { return "", err }
joke, err := core.Run(ctx, "generate-joke", func() (string, error) {
return genkit.GenerateText(ctx, g,
ai.WithPrompt("Tell me a joke about %s", subject),
)
})
return joke, err
},
)
```
## HTTP Handlers
### genkit.Handler
Convert any flow into an `http.HandlerFunc`:
```go
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))
```
### Request/Response Format
**Non-streaming request:**
```bash
curl -X POST http://localhost:8080/jokeFlow \
-H "Content-Type: application/json" \
-d '{"data": "bananas"}'
```
Response: `{"result": "Why did the banana go to the doctor?..."}`
**Streaming request:**
```bash
curl -N -X POST http://localhost:8080/streamingJokeFlow \
-H "Content-Type: application/json" \
-d '{"data": "bananas"}'
```
Streaming responses use Server-Sent Events (SSE) format.
### genkit.HandlerFunc
For frameworks that expect error-returning handlers:
```go
handler := genkit.HandlerFunc(myFlow)
// handler is func(http.ResponseWriter, *http.Request) error
```
### Context Providers
Inject request context (e.g., auth headers) into flow execution:
```go
mux.HandleFunc("POST /myFlow", genkit.Handler(myFlow,
genkit.WithContextProviders(func(ctx context.Context, rd core.RequestData) (api.ActionContext, error) {
// rd.Headers contains HTTP headers
return api.ActionContext{"userId": rd.Headers.Get("X-User-Id")}, nil
}),
))
```
### ListFlows
Get all registered flows for dynamic route setup:
```go
flows := genkit.ListFlows(g) // []api.Action
for _, f := range flows {
fmt.Println(f.Name())
}
```
generation.md 5.6 KB
# Generation
- [GenerateText](#generatetext): Lines 13-22
- [Generate](#generate): Lines 24-37
- [GenerateData (Structured Output)](#generatedata-structured-output): Lines 39-54
- [Streaming](#streaming): Lines 56-115
- [Common Options](#common-options): Lines 117-133
- [Output Formats](#output-formats): Lines 135-187
- [Embeddings](#embeddings): Lines 189-224
---
## GenerateText
Simplest form. Returns a string.
```go
text, err := genkit.GenerateText(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Tell me a joke about %s", topic),
)
```
## Generate
Returns a full `*ModelResponse` with metadata, usage stats, and history.
```go
resp, err := genkit.Generate(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithSystem("You are a helpful assistant."),
ai.WithPrompt("Explain %s", topic),
)
fmt.Println(resp.Text()) // concatenated text
fmt.Println(resp.FinishReason) // ai.FinishReasonStop, etc.
fmt.Println(resp.Usage) // token counts
```
## GenerateData (Structured Output)
Returns a typed Go value parsed from the model's JSON output.
```go
type Joke struct {
Setup string `json:"setup" jsonschema:"description=The setup of the joke"`
Punchline string `json:"punchline" jsonschema:"description=The punchline"`
}
joke, resp, err := genkit.GenerateData[Joke](ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Tell me a joke about %s", topic),
)
// joke is *Joke, resp is *ModelResponse
```
## Streaming
### GenerateStream
Returns an iterator. Each value has `.Done`, `.Chunk`, and `.Response`.
```go
stream := genkit.GenerateStream(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Tell me a long story about %s", topic),
)
for result, err := range stream {
if err != nil {
return err
}
if result.Done {
finalText := result.Response.Text()
break
}
fmt.Print(result.Chunk.Text()) // incremental text
}
```
### GenerateDataStream (Structured Streaming)
Streams typed partial objects as they arrive.
```go
stream := genkit.GenerateDataStream[Joke](ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Tell me a joke about %s", topic),
)
for result, err := range stream {
if err != nil {
return err
}
if result.Done {
finalJoke := result.Output // *Joke
break
}
partialJoke := result.Chunk // *Joke (partial)
}
```
### Callback-Based Streaming
Use `ai.WithStreaming` with `Generate` for callback-style streaming. The
callback receives `*ai.ModelResponseChunk`:
```go
resp, err := genkit.Generate(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Tell me a story"),
ai.WithStreaming(func(ctx context.Context, chunk *ai.ModelResponseChunk) error {
fmt.Print(chunk.Text()) // extract text from chunk
return nil
}),
)
// resp contains the final complete response
```
## Common Options
```go
// Model selection
ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)) // model reference
ai.WithModelName("googleai/gemini-flash-latest") // by name string
// Content
ai.WithPrompt("Tell me about %s", topic) // user message (supports fmt verbs)
ai.WithSystem("You are a pirate.") // system instructions
ai.WithMessages(msg1, msg2) // conversation history
ai.WithDocs(doc1, doc2) // context documents
ai.WithTextDocs("context 1", "context 2") // context as strings
// Model config (provider-specific)
ai.WithConfig(map[string]any{"temperature": 0.7})
```
## Output Formats
Control how the model structures its output.
### By Go Type
```go
// Automatically uses JSON format and instructs model to match the type
ai.WithOutputType(MyStruct{})
```
### By Format String
```go
ai.WithOutputFormat(ai.OutputFormatJSON) // single JSON object
ai.WithOutputFormat(ai.OutputFormatJSONL) // JSON Lines (one object per line)
ai.WithOutputFormat(ai.OutputFormatArray) // JSON array
ai.WithOutputFormat(ai.OutputFormatEnum) // constrained enum value
ai.WithOutputFormat(ai.OutputFormatText) // plain text (default)
```
### Enum Output
```go
type Color string
const (
Red Color = "red"
Green Color = "green"
Blue Color = "blue"
)
text, err := genkit.GenerateText(ctx, g,
ai.WithPrompt("What color is the sky?"),
ai.WithOutputEnums(Red, Green, Blue),
)
```
### Custom Output Instructions
```go
ai.WithOutputInstructions("Return a JSON object with fields: name (string), age (number)")
```
### Combining Format + Schema
```go
// JSONL with a typed schema (useful for streaming lists)
genkit.DefinePrompt(g, "characters",
ai.WithPrompt("Generate 5 story characters"),
ai.WithOutputType([]StoryCharacter{}),
ai.WithOutputFormat(ai.OutputFormatJSONL),
)
```
## Embeddings
```go
res, err := genkit.Embed(ctx, g,
ai.WithEmbedderName("googleai/gemini-embedding-001"),
ai.WithTextDocs("The sky is blue.", "Grass is green."), // one embedding per doc
)
if err != nil {
return err
}
vector := res.Embeddings[0].Embedding // []float32
// Optional tuning (default is 3072 dimensions)
res, err = genkit.Embed(ctx, g,
ai.WithEmbedderName("googleai/gemini-embedding-001"),
ai.WithTextDocs("The sky is blue."),
ai.WithConfig(&genai.EmbedContentConfig{
OutputDimensionality: genai.Ptr[int32](768),
TaskType: "RETRIEVAL_DOCUMENT",
}),
)
```
Common embedders: `googleai/gemini-embedding-001` (text),
`googleai/gemini-embedding-2` (multimodal: text, image, video).
Multimodal input goes in a document's media parts:
```go
res, err := genkit.Embed(ctx, g,
ai.WithEmbedderName("googleai/gemini-embedding-2"),
ai.WithDocs(&ai.Document{Content: []*ai.Part{
ai.NewMediaPart("image/png", "data:image/png;base64,..."),
}}),
)
```
getting-started.md 3.6 KB
# Getting Started
- [Project Setup](#project-setup): Lines 10-27
- [Initialization](#initialization): Lines 29-95
- [Genkit CLI](#genkit-cli): Lines 97-144
- [Import Paths](#import-paths): Lines 146-155
---
## Project Setup
```bash
mkdir my-genkit-app && cd my-genkit-app
go mod init my-genkit-app
go get github.com/firebase/genkit/go@latest
```
Provider plugins ship in the same module under `plugins/`, so they don't need to
be fetched separately. Just import the ones you want and run `go mod tidy`
afterwards. The available plugins include:
- `plugins/googlegenai` for Google AI and Vertex AI
- `plugins/anthropic` for Anthropic Claude
- `plugins/compat_oai` for OpenAI-compatible APIs (OpenAI, Groq, xAI, etc.)
- `plugins/ollama` for local Ollama models
- `plugins/middleware` for the built-in middleware bundle (`Retry`, `Fallback`,
`ToolApproval`, `Filesystem`, `Skills`)
## Initialization
Every Genkit app starts with `genkit.Init`, which returns a `*Genkit` instance:
```go
import (
"context"
"github.com/firebase/genkit/go/genkit"
"github.com/firebase/genkit/go/plugins/googlegenai"
)
ctx := context.Background()
g := genkit.Init(ctx,
genkit.WithPlugins(&googlegenai.GoogleAI{}),
)
```
### The `*Genkit` Instance
The `*Genkit` value `g` is the central registry. Pass it to every Genkit
function:
```go
// Defining resources
genkit.DefineFlow(g, "myFlow", ...)
genkit.DefineTool(g, "myTool", ...)
genkit.DefinePrompt(g, "myPrompt", ...)
// Generating content
genkit.GenerateText(ctx, g, ...)
genkit.Generate(ctx, g, ...)
```
Do not store `g` in a global variable. Pass it explicitly through your call
chain.
### Init Options
```go
g := genkit.Init(ctx,
// Register one or more plugins
genkit.WithPlugins(&googlegenai.GoogleAI{}, &anthropic.Anthropic{}),
// Set a default model (used when no model is specified)
genkit.WithDefaultModel("googleai/gemini-flash-latest"),
// Set directory for .prompt files (default: "prompts")
genkit.WithPromptDir("my-prompts"),
// Or embed prompts using Go's embed package
// genkit.WithPromptFS(promptsFS),
)
```
### Embedding Prompts
Use `go:embed` to bundle `.prompt` files into the binary:
```go
//go:embed prompts
var promptsFS embed.FS
g := genkit.Init(ctx,
genkit.WithPlugins(&googlegenai.GoogleAI{}),
genkit.WithPromptFS(promptsFS),
)
```
## Genkit CLI
The Genkit CLI provides a local Developer UI for running flows, tracing
executions, and inspecting model interactions.
**Install:**
```bash
curl -sL cli.genkit.dev | bash
```
**Verify:**
```bash
genkit --version
```
### Developer UI
Start your app with the Developer UI attached:
```bash
genkit start -- go run .
```
This launches:
- Your app (with tracing enabled)
- The Developer UI at `http://localhost:4000`
- A telemetry API at `http://localhost:4033`
Add `-o` to auto-open the UI in your browser:
```bash
genkit start -o -- go run .
```
The Developer UI lets you:
- Run and test flows interactively
- View traces for each generation call (inputs, outputs, latency, token usage)
- Inspect prompt rendering and tool calls
- Debug multi-step flows with per-step trace data
### Without the CLI
Set `GENKIT_ENV=dev` to enable the reflection API without the CLI:
```bash
GENKIT_ENV=dev go run .
```
## Import Paths
```go
import (
"github.com/firebase/genkit/go/genkit" // Core: Init, Generate*, DefineFlow, etc.
"github.com/firebase/genkit/go/ai" // Types: WithModel, WithPrompt, Message, Part, etc.
"github.com/firebase/genkit/go/core" // Low-level: Run (sub-steps), Flow types
"github.com/firebase/genkit/go/plugins/server" // server.Start for HTTP
)
```
middleware.md 20.6 KB
# 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](#the-mental-model): Lines 24-52
- [When each hook fires](#when-each-hook-fires): Lines 54-70
- [Composition order](#composition-order): Lines 72-87
- [Per-call state](#per-call-state): Lines 89-141
- [Plugin-level state](#plugin-level-state): Lines 143-184
- [Composition with WithUse](#composition-with-withuse): Lines 186-202
- [Inline middleware](#inline-middleware): Lines 204-222
- [Application-owned middleware](#application-owned-middleware): Lines 224-240
- [Built-in middleware](#built-in-middleware): Lines 242-456
- [Practical patterns](#practical-patterns): Lines 458-551
- [Migration note](#migration-note): Lines 553-558
- [See also](#see-also): Lines 560-566
---
## The mental model
A middleware is a config struct that implements two methods:
```go
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.
```go
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:
```go
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.
```go
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:
```go
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:
```go
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
```go
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`:
```go
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:
```go
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:
```go
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`.
```go
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`.
```go
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`.
```go
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:
```go
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:
```go
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.
```go
ai.WithUse(&middleware.SoftToolErrors{}) // every tool
ai.WithUse(&middleware.SoftToolErrors{Tools: []string{"search"}}) // only these
```
For a tool you own, return `tool.Fail(ctx, err)` for just the errors the model
can fix. See [tools.md](tools.md#errors-the-model-can-fix).
### `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.
```go
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.
```go
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`.
```go
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.
```go
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`:
```go
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):
```go
return &ai.Hooks{
Tools: []ai.Tool{myTool},
WrapTool: myInterceptor, // intercepts both myTool and any user-supplied tools
}, nil
```
Duplicate 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.)
```go
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:
```go
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.md`](tools.md) for tool definition, interrupt/restart machinery used
by `ToolApproval`.
- Sample sources under `go/samples/basic-middleware/`: `retry-fallback`,
`filesystem`, `skills`.
- The `plugins/middleware` package source for reference implementations.
observability.md 4.7 KB
# Observability (Tracing, OpenTelemetry, Reflection API)
> Pluggable instrumentation, `otelgenai`, and the reflection API settings
> require Genkit Go v1.14.0+.
- [How tracing works](#how-tracing-works): Lines 13-27
- [Export OpenTelemetry GenAI semantic conventions (otelgenai)](#export-opentelemetry-genai-semantic-conventions-otelgenai): Lines 29-72
- [Custom instrumentation](#custom-instrumentation): Lines 74-94
- [Reflection API outside dev](#reflection-api-outside-dev): Lines 96-117
---
## How tracing works
- **In dev** (`genkit start`), Genkit posts spans straight to the Developer UI's
telemetry server; no OpenTelemetry SDK is on that path. The Dev UI shows
Genkit spans only: spans you write through OTel directly (`otelhttp`,
`trace.SpanFromContext(ctx)`) go to your OTel backend, not the Dev UI.
- **Elsewhere**, spans go through pluggable instrumentation providers. The
default, `&tracing.OTelInstrumentation{}`, creates OTel spans with `genkit:*`
attributes on the `TracerProvider` you register. Genkit installs none itself,
so nothing leaves the process until you (or a plugin such as Firebase)
register
one.
- Write span metadata with `tracing.SetSpanMetadata`. The old
`tracing.TracerProvider`, `tracing.Tracer`, and `WriteTelemetry*` helpers are
deprecated.
## Export OpenTelemetry GenAI semantic conventions (`otelgenai`)
Sends Genkit telemetry to any OTLP backend in the vendor-neutral `gen_ai.*`
shape (`chat <model>` spans, token usage and duration metrics).
```bash
go get github.com/firebase/genkit/go/plugins/otelgenai
go get go.opentelemetry.io/contrib/exporters/autoexport
```
```go
import (
"github.com/firebase/genkit/go/core/tracing"
"github.com/firebase/genkit/go/plugins/otelgenai"
)
// 1. The app owns the OTel SDK: register TracerProvider / MeterProvider /
// LoggerProvider (e.g. with autoexport), and defer their Shutdown.
// 2. Set the GenAI instrumentation before genkit.Init:
tracing.SetInstrumentation(otelgenai.New(&otelgenai.Options{
ContentCapturingMode: otelgenai.SpanOnly, // default NoContent; may contain PII
EmitToolSpans: true,
}))
g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{}))
```
`otelgenai.Options`: `ContentCapturingMode` (`NoContent`, `SpanOnly`,
`EventOnly`, `SpanAndEvent`; falls back to
`OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT`), `CaptureActionIO`,
`EmitToolSpans`, `DisableMetrics`, `ScopeName`, and explicit
`TracerProvider`/`MeterProvider`/`LoggerProvider` (default: the globals). Pass
`nil` for the defaults.
Gotchas:
- **It replaces the default encoding.** To export both, list both:
`tracing.SetInstrumentation(&tracing.OTelInstrumentation{},
otelgenai.New(nil))`.
- **Do not use it alone with the Firebase or Google Cloud telemetry plugins.**
They build metrics/logs from the `genkit:*` attributes; without
`OTelInstrumentation` in the list their Genkit metrics stop.
- **`EventOnly` content goes to the OTel logs signal**, which trace-only
backends like Jaeger can't show.
- Runnable sample: `go/samples/otel-genai` (Jaeger + collector, no Docker).
## Custom instrumentation
Implement `tracing.Instrumentation` (`StartSpan` returns a `tracing.Span` with
`TraceInfo`, `SetMetadata`, and `End`). Genkit owns the run, so a provider
observes it but cannot skip or repeat it. Return a nil `Span` to ignore a span.
Scope providers to one context (one request, one agent run) with
`tracing.WithInstrumentation(ctx, providers...)`. `aix.Observer` is a ready-made
scoped provider that reports each model call, typed; the `Budget` middleware is
built on it:
```go
ctx = tracing.WithInstrumentation(ctx, aix.Observer{
ModelDone: func(ctx context.Context, call *aix.ModelCall) {
if u := call.Response.Usage; u != nil {
meter.Add(tenant, call.Model, u)
}
},
})
out, err := supportAgent.RunText(ctx, msg)
```
## Reflection API outside dev
The CLI and Dev UI talk to the app through the reflection API. By default it
runs only under `GENKIT_ENV=dev` on `127.0.0.1:3100+`. To run it elsewhere
(e.g. staging), turn it on explicitly and protect it:
```bash
GENKIT_REFLECTION_ENABLED=true \
GENKIT_REFLECTION_HOST=0.0.0.0 \
GENKIT_REFLECTION_PORT=3100 \
GENKIT_REFLECTION_SECRET_TOKEN="$(openssl rand -hex 32)" \
./server
```
- `GENKIT_REFLECTION_ENABLED`: `true` on anywhere, `false` off even under dev.
Any other value makes `genkit.Init` panic.
- `GENKIT_REFLECTION_SECRET_TOKEN`: every request must send it in the
`x-genkit-reflection-secret` header (`/api/__health` stays open). Without it,
anyone who can reach the port can run every flow, model, and tool.
- `genkit.WithReflectionPort(3200)` binds exactly that port (panics if taken);
`0` lets the OS pick. The env var wins over the option, and neither turns the
API on.
prompts.md 7.3 KB
# Prompts
- [DefinePrompt](#defineprompt): Lines 10-53
- [DefineDataPrompt (Typed Input/Output)](#definedataprompt-typed-inputoutput): Lines 55-94
- [.prompt Files (Dotprompt)](#prompt-files-dotprompt): Lines 96-278
- [Schemas](#schemas): Lines 280-323
---
## DefinePrompt
Define a reusable prompt in code with a default model and template.
```go
jokePrompt := genkit.DefinePrompt(g, "joke",
ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)),
ai.WithInputType(JokeRequest{Topic: "example"}),
ai.WithPrompt("Tell me a joke about {{topic}}."),
)
```
### Execute
```go
resp, err := jokePrompt.Execute(ctx,
ai.WithInput(map[string]any{"topic": "cats"}),
)
fmt.Println(resp.Text())
```
### ExecuteStream
```go
stream := jokePrompt.ExecuteStream(ctx,
ai.WithInput(map[string]any{"topic": "cats"}),
)
for result, err := range stream {
if err != nil { return err }
if result.Done { break }
fmt.Print(result.Chunk.Text())
}
```
### Override Options at Execution
```go
resp, err := jokePrompt.Execute(ctx,
ai.WithInput(map[string]any{"topic": "cats"}),
ai.WithModelName("googleai/gemini-pro-latest"), // override model
ai.WithConfig(map[string]any{"temperature": 0.9}),
ai.WithTools(myTool),
)
```
## DefineDataPrompt (Typed Input/Output)
Strongly-typed prompts with Go generics.
```go
type JokeRequest struct {
Topic string `json:"topic"`
}
type Joke struct {
Setup string `json:"setup" jsonschema:"description=The setup"`
Punchline string `json:"punchline" jsonschema:"description=The punchline"`
}
jokePrompt := genkit.DefineDataPrompt[JokeRequest, *Joke](g, "structured-joke",
ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", nil)),
ai.WithPrompt("Tell me a joke about {{topic}}."),
)
```
### Execute (typed)
```go
joke, resp, err := jokePrompt.Execute(ctx, JokeRequest{Topic: "cats"})
// joke is *Joke, resp is *ModelResponse
```
### ExecuteStream (typed)
```go
stream := jokePrompt.ExecuteStream(ctx, JokeRequest{Topic: "cats"})
for result, err := range stream {
if err != nil { return err }
if result.Done {
finalJoke := result.Output // *Joke
break
}
fmt.Print(result.Chunk) // partial *Joke
}
```
## .prompt Files (Dotprompt)
Define prompts in separate files with YAML frontmatter and Handlebars templates.
### Basic .prompt File
`prompts/joke.prompt`:
```
---
model: googleai/gemini-flash-latest
input:
schema:
topic: string
---
Tell me a joke about {{topic}}.
```
### Load and Use
```go
// LookupPrompt returns Prompt (untyped: map[string]any input, string output)
jokePrompt := genkit.LookupPrompt(g, "joke")
resp, err := jokePrompt.Execute(ctx,
ai.WithInput(map[string]any{"topic": "cats"}),
)
```
### Typed .prompt File
`prompts/structured-joke.prompt`:
```
---
model: googleai/gemini-flash-latest
config:
thinkingConfig:
thinkingBudget: 0
input:
schema: JokeRequest
output:
format: json
schema: Joke
---
Tell me a joke about {{topic}}.
```
Register Go types so the .prompt file can reference them by name:
```go
genkit.DefineSchemaFor[JokeRequest](g)
genkit.DefineSchemaFor[Joke](g)
jokePrompt := genkit.LookupDataPrompt[JokeRequest, *Joke](g, "structured-joke")
joke, resp, err := jokePrompt.Execute(ctx, JokeRequest{Topic: "cats"})
```
### LoadPrompt (Explicit Path)
```go
prompt := genkit.LoadPrompt(g, "./prompts/countries.prompt", "countries")
resp, err := prompt.Execute(ctx)
```
### .prompt File Features
**Multi-message prompts with roles:**
```
---
model: googleai/gemini-flash-latest
input:
schema:
question: string
---
{{ role "system" }}
You are a helpful assistant.
{{ role "user" }}
{{question}}
```
**Media in prompts:**
```
---
model: googleai/gemini-flash-latest
input:
schema:
videoUrl: string
contentType: string
---
{{ role "user" }}
Summarize this video:
{{media url=videoUrl contentType=contentType}}
```
**Conditionals and loops:**
```
---
input:
schema:
topic: string
dietaryRestrictions?(array): string
---
Write a recipe about {{topic}}.
{{#if dietaryRestrictions}}
Dietary restrictions: {{#each dietaryRestrictions}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}.
{{/if}}
```
**Inline schema in .prompt file:**
```
---
model: googleai/gemini-flash-latest
input:
schema:
topic: string
style?: string
output:
format: json
schema:
title: string
body: string
tags(array): string
---
Write an article about {{topic}}.
{{#if style}}Write in a {{style}} style.{{/if}}
```
**Tools, tool-loop control, and middleware:**
`.prompt` frontmatter can also configure tool calling and attach middleware, so
an agent-style prompt can be fully described in the file:
```
---
model: googleai/gemini-flash-latest
input:
schema:
tone: string
tools:
- getAttractions
- getFlightInfo
toolChoice: auto # auto | required | none
maxTurns: 20 # max tool-call loop iterations (WithMaxTurns)
returnToolRequests: false # return tool requests instead of running them (WithReturnToolRequests)
use:
- name: genkit-middleware/retry
config:
maxRetries: 2
- genkit-middleware/fallback # bare string = middleware name, no config
---
{{role "system"}}
You are a friendly trip planning assistant. Keep your tone {{tone}}.
{{history}}
```
Field mapping:
| Frontmatter | Option | Notes |
| --- | --- | --- |
| `tools` | `WithTools` | list of registered tool names (strings) |
| `toolChoice` | `WithToolChoice` | `auto`, `required`, or `none` |
| `maxTurns` | `WithMaxTurns` | integer |
| `returnToolRequests` | `WithReturnToolRequests` | boolean |
| `use` | `WithUse` | list of middleware refs |
`use` entries are resolved by name against middleware registered on the
`*Genkit`
instance. Each entry is either a bare string (the middleware name) or a map with
`name` and optional `config`. Register the built-in middleware plugin so names
like `genkit-middleware/retry` resolve:
```go
import "github.com/firebase/genkit/go/plugins/middleware"
g := genkit.Init(ctx, genkit.WithPlugins(
&googlegenai.GoogleAI{},
&middleware.Middleware{}, // registers genkit-middleware/{retry,fallback,filesystem,skills,toolApproval}
))
```
Available named middleware: `genkit-middleware/retry`,
`genkit-middleware/fallback`,
`genkit-middleware/filesystem`, `genkit-middleware/skills`,
`genkit-middleware/toolApproval`. See [references/middleware.md](middleware.md).
## Schemas
### DefineSchemaFor (from Go type)
Registers a Go struct as a named schema for use in `.prompt` files.
```go
genkit.DefineSchemaFor[JokeRequest](g)
genkit.DefineSchemaFor[Joke](g)
```
The schema name matches the Go type name. Use `jsonschema` struct tags for
metadata:
```go
type Recipe struct {
Title string `json:"title" jsonschema:"description=The recipe title"`
Difficulty string `json:"difficulty" jsonschema:"enum=easy,enum=medium,enum=hard"`
Ingredients []Ingredient `json:"ingredients"`
Steps []string `json:"steps"`
}
type Ingredient struct {
Name string `json:"name"`
Amount float64 `json:"amount"`
Unit string `json:"unit"`
}
```
### DefineSchema (manual JSON Schema)
```go
genkit.DefineSchema(g, "Recipe", map[string]any{
"type": "object",
"properties": map[string]any{
"title": map[string]any{"type": "string"},
"ingredients": map[string]any{
"type": "array",
"items": map[string]any{"type": "object"},
},
},
"required": []string{"title", "ingredients"},
})
```
providers.md 4.0 KB
# Model Providers
- [Google AI (Gemini)](#google-ai-gemini): Lines 12-38
- [Vertex AI](#vertex-ai): Lines 40-58
- [Anthropic (Claude)](#anthropic-claude): Lines 60-90
- [OpenAI-Compatible (compat_oai)](#openai-compatible-compat_oai): Lines 92-116
- [Ollama (Local Models)](#ollama-local-models): Lines 118-145
- [Multiple Providers](#multiple-providers): Lines 147-170
---
## Google AI (Gemini)
```go
import "github.com/firebase/genkit/go/plugins/googlegenai"
g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{}))
```
**Env var:** `GEMINI_API_KEY` or `GOOGLE_API_KEY`
Model names follow the format `googleai/<model-id>`. Look up the latest model
IDs at https://ai.google.dev/gemini-api/docs/models.
```go
// By name string
ai.WithModelName("googleai/gemini-flash-latest")
// Model ref with provider-specific config
ai.WithModel(googlegenai.ModelRef("googleai/gemini-flash-latest", &genai.GenerateContentConfig{
ThinkingConfig: &genai.ThinkingConfig{
ThinkingBudget: genai.Ptr[int32](0), // disable thinking
},
}))
// Lookup a model instance
m := googlegenai.GoogleAIModel(g, "gemini-flash-latest")
```
## Vertex AI
```go
import "github.com/firebase/genkit/go/plugins/googlegenai"
g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.VertexAI{}))
```
**Env vars:** `GOOGLE_CLOUD_PROJECT`, `GOOGLE_CLOUD_LOCATION` (or
`GOOGLE_CLOUD_REGION`)
Uses Application Default Credentials (`gcloud auth application-default login`).
Model names follow the format `vertexai/<model-id>`. Same model IDs as Google
AI.
```go
ai.WithModelName("vertexai/gemini-flash-latest")
```
## Anthropic (Claude)
```go
import (
"github.com/anthropics/anthropic-sdk-go" // Anthropic SDK types
ant "github.com/firebase/genkit/go/plugins/anthropic" // Genkit plugin
)
g := genkit.Init(ctx, genkit.WithPlugins(&ant.Anthropic{}))
```
**Env var:** `ANTHROPIC_API_KEY`
Model names follow the format `anthropic/<model-id>`. Look up the latest model
IDs at https://docs.anthropic.com/en/docs/about-claude/models.
```go
// By name
ai.WithModelName("anthropic/claude-sonnet-4-6")
// With provider-specific config (uses Anthropic SDK types via ai.WithConfig)
ai.WithConfig(&anthropic.MessageNewParams{
Temperature: anthropic.Float(1.0),
MaxTokens: *anthropic.IntPtr(2000),
Thinking: anthropic.ThinkingConfigParamUnion{
OfEnabled: &anthropic.ThinkingConfigEnabledParam{
BudgetTokens: *anthropic.IntPtr(1024),
},
},
})
```
## OpenAI-Compatible (compat_oai)
Works with any OpenAI-compatible API: OpenAI, DeepSeek, xAI, etc.
```go
import "github.com/firebase/genkit/go/plugins/compat_oai"
openaiPlugin := &compat_oai.OpenAICompatible{
Provider: "openai", // unique identifier
APIKey: os.Getenv("OPENAI_API_KEY"),
// BaseURL: "https://custom-endpoint/v1", // for non-OpenAI providers
}
g := genkit.Init(ctx, genkit.WithPlugins(openaiPlugin))
```
Define models explicitly (not auto-discovered):
```go
model := openaiPlugin.DefineModel("openai", "gpt-4o", compat_oai.ModelOptions{})
```
Use with:
```go
ai.WithModel(model)
```
## Ollama (Local Models)
```go
import "github.com/firebase/genkit/go/plugins/ollama"
ollamaPlugin := &ollama.Ollama{
ServerAddress: "http://localhost:11434",
Timeout: 60, // seconds
}
g := genkit.Init(ctx, genkit.WithPlugins(ollamaPlugin))
```
Define models explicitly:
```go
model := ollamaPlugin.DefineModel(g,
ollama.ModelDefinition{
Name: "llama3.1",
Type: "chat", // or "generate"
},
nil, // optional *ModelOptions
)
```
Use with:
```go
ai.WithModel(model)
```
## Multiple Providers
Register multiple plugins in a single Genkit instance:
```go
g := genkit.Init(ctx,
genkit.WithPlugins(
&googlegenai.GoogleAI{},
&ant.Anthropic{},
),
genkit.WithDefaultModel("googleai/gemini-flash-latest"),
)
// Use different models per call
text1, _ := genkit.GenerateText(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("Hello from Gemini"),
)
text2, _ := genkit.GenerateText(ctx, g,
ai.WithModelName("anthropic/claude-sonnet-4-6"),
ai.WithPrompt("Hello from Claude"),
)
```
tools.md 8.6 KB
# Tools
- [DefineTool](#definetool): Lines 10-31
- [Using Tools in Generation](#using-tools-in-generation): Lines 33-61
- [Tool runtime helpers (ai/tool)](#tool-runtime-helpers-aitool): Lines 63-116
- [Tool interrupts (DefineResumableTool)](#tool-interrupts-defineresumabletool): Lines 118-262
---
## DefineTool
Define a tool the model can call during generation.
```go
type WeatherInput struct {
Location string `json:"location" jsonschema:"description=City name"`
}
type WeatherOutput struct {
Temperature float64 `json:"temperature"`
Conditions string `json:"conditions"`
}
weatherTool := genkit.DefineTool(g, "getWeather",
"Gets the current weather for a location.",
func(ctx *ai.ToolContext, input WeatherInput) (WeatherOutput, error) {
// Call your weather API
return WeatherOutput{Temperature: 72, Conditions: "sunny"}, nil
},
)
```
## Using Tools in Generation
Pass tools to `Generate`, `GenerateText`, or prompts:
```go
resp, err := genkit.Generate(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt("What's the weather in San Francisco?"),
ai.WithTools(weatherTool),
)
// The model calls the tool automatically and incorporates the result
fmt.Println(resp.Text())
```
### Tool Choice
```go
ai.WithToolChoice(ai.ToolChoiceAuto) // model decides (default)
ai.WithToolChoice(ai.ToolChoiceRequired) // model must use a tool
ai.WithToolChoice(ai.ToolChoiceNone) // model cannot use tools
```
### Max Turns
Limit how many tool-call round trips the model can make:
```go
ai.WithMaxTurns(3) // default is 5
```
## Tool runtime helpers (`ai/tool`)
> Requires Genkit Go v1.14.0+.
Package `github.com/firebase/genkit/go/ai/tool` holds the verbs a tool (or a
`WrapTool` hook) calls. They take a `context.Context`, so they work from
`DefineTool` too (`*ai.ToolContext` embeds the context).
| Function | Use |
| --- | --- |
| `tool.Interrupt(ctx, data)` | Pause the call for the caller (see below). |
| `tool.Fail(ctx, err)` | Hand this error to the model as the tool's output so it can fix its input, instead of stopping the loop. |
| `tool.AttachParts(ctx, parts...)` | Attach media (images, etc.) to the result while keeping the tool's own output type. Replaces multipart tools. |
| `tool.SendChunk(ctx, chunk)` | Stream progress from a tool (set `Role: ai.RoleTool`). |
| `tool.OriginalInput[In](ctx)` | On a restart with revised input, the input the tool was first called with. |
| `tool.ResumeData[T](ctx)` | Read a resume payload untyped (for `WrapTool` hooks). |
```go
import "github.com/firebase/genkit/go/ai/tool"
screenshot := genkit.DefineTool(g, "screenshot", "Takes a screenshot of a page.",
func(ctx *ai.ToolContext, in PageInput) (*PageInfo, error) {
info, png, err := capture(ctx, in.URL)
if err != nil {
return nil, err
}
tool.AttachParts(ctx, ai.NewMediaPart("image/png", png)) // a data: URL
return info, nil // still *PageInfo, so the model sees the real output schema
})
```
`genkit.DefineMultipartTool` / `ai.MultipartToolResponse` are deprecated; use
`tool.AttachParts`.
### Errors the model can fix
By default a tool error stops the loop with `ai.ErrToolFailed`. Return
`tool.Fail` for errors the model can correct:
```go
query := genkit.DefineTool(g, "query", "Runs a read-only SQL query.",
func(ctx *ai.ToolContext, in QueryInput) ([]string, error) {
rows, err := runQuery(ctx, in.SQL)
if errors.Is(err, errSyntax) {
return nil, tool.Fail(ctx, err) // the model reads the error and fixes the query
}
return rows, err // a lost connection still stops the loop
})
```
For tools you don't own (e.g. MCP tools), `&middleware.SoftToolErrors{}`
(optionally `Tools: []string{"search"}`) returns every tool error to the model.
See [middleware](middleware.md). A tool that panics fails with the message
`tool panicked` instead of crashing the process.
## Tool interrupts (`DefineResumableTool`)
Pause a tool call to get human input, then resume. Use
`genkit.DefineResumableTool`, whose third type parameter is the **resume type**:
what the caller answers with. The tool receives it as a pointer that is `nil` on
the first call.
> **Do not use** the deprecated `ai.InterruptWith`, `ToolContext.Interrupt`,
> `RestartWith`/`RespondWith`, `WithToolRestarts`/`WithToolResponses`,
> `ai.ResumedValue`, `IsResumed`, or `ai.OriginalInputAs`. The experimental
> `genkitx.DefineInterruptibleTool` and `ai/exp/tool` package were removed in
> v1.14.0.
### Define a resumable tool
```go
import (
"context"
"github.com/firebase/genkit/go/ai/tool"
"github.com/firebase/genkit/go/genkit"
)
type TransferInput struct {
ToAccount string `json:"toAccount"`
Amount float64 `json:"amount"`
}
type TransferOutput struct {
Status string `json:"status"`
}
// TransferInterrupt is extra data the tool reports when it pauses.
type TransferInterrupt struct {
Reason string `json:"reason"`
}
// Confirmation is the resume type. Must be a struct or map (a JSON object).
type Confirmation struct {
Approved bool `json:"approved"`
}
transferMoney := genkit.DefineResumableTool(g, "transferMoney",
"Transfers money to another account.",
func(ctx context.Context, in TransferInput, confirm *Confirmation) (*TransferOutput, error) {
if confirm == nil && in.Amount > approvalLimit {
// First call: pause. Data must serialize to a JSON object (or be nil).
return nil, tool.Interrupt(ctx, TransferInterrupt{Reason: "over_limit"})
}
if confirm != nil && !confirm.Approved {
return &TransferOutput{Status: "declined"}, nil
}
// ... perform the transfer
return &TransferOutput{Status: "completed"}, nil
},
)
```
`DefineResumableTool` returns `*ai.ResumableToolAction[In, Out, Res]`.
### Handle interrupts
A paused generation returns `(resp, nil)` with `resp.FinishReason ==
ai.FinishReasonInterrupted`. Claim each part in `resp.Interrupts()` with the
tool's `Interrupted` method. The claim matches the part to the tool and decodes
its input, so the verbs after it cannot fail:
| Verb | Effect |
| --- | --- |
| `call.Restart(resume)` | Run the tool again with the typed resume value. |
| `call.RestartWithInput(input, resume)` | Run it again with revised input (history records the revised request). |
| `call.Respond(output)` | Answer with the tool's output; the tool does not run again. |
```go
const maxRounds = 5
resp, err := genkit.Generate(ctx, g,
ai.WithModelName("googleai/gemini-flash-latest"),
ai.WithPrompt(userRequest),
ai.WithTools(transferMoney),
)
if err != nil {
return err
}
for round := 0; round < maxRounds && resp.FinishReason == ai.FinishReasonInterrupted; round++ {
var parts []*ai.Part
for _, part := range resp.Interrupts() {
call, ok := transferMoney.Interrupted(part)
if !ok {
return fmt.Errorf("no handler for interrupt from tool %q", part.ToolRequest.Name)
}
meta, _ := ai.InterruptAs[TransferInterrupt](part) // the data the tool paused with
log.Println("paused:", meta.Reason)
approved := askUser(call.Input.Amount, call.Input.ToAccount) // call.Input is TransferInput
parts = append(parts, call.Restart(Confirmation{Approved: approved}))
}
// The full history, the same tools, and every interrupt answered.
resp, err = genkit.Generate(ctx, g,
ai.WithMessages(resp.History()...),
ai.WithTools(transferMoney),
ai.WithResume(parts...),
)
if err != nil {
return err
}
}
fmt.Println(resp.Text())
```
Rules:
- **Answer every interrupt** in the turn with exactly one part. Missing one
fails
with `ai.ErrUnresolvedToolRequest`; passing `resp.Interrupts()` back as is
(still paused) fails with `INVALID_ARGUMENT`. The whole resume is checked
before any tool runs.
- **Several resumable tools?** Try each tool's `Interrupted` on the part; it
reports false for other tools' interrupts.
- **A resume can pause again.** It returns `(resp, nil)` with `FinishReason`
interrupted, so loop as above.
- **Middleware holds** (e.g. `ToolApproval`) are not the tool's interrupt: claim
them with `middleware.ToolApprovalInterrupted(part)`. See
[middleware](middleware.md).
- **Generic handlers** that only hold the part can build the same parts with
`part.ToToolRestart(resume)`, `part.ToToolRestartWithInput(input, resume)`,
and `part.ToToolResponse(output)`. These return an error, since nothing was
type-checked by a claim.
### Read the original input after a revised restart
```go
if orig, ok := tool.OriginalInput[TransferInput](ctx); ok {
log.Printf("adjusted from $%.2f to $%.2f", orig.Amount, in.Amount)
}
```
`tool.OriginalInput` reports false on a first call and on a restart that kept
the
input.
Agents use the same tool and claim; only the delivery differs
(`aix.ToolResume`).
See [agents-human-in-the-loop.md](agents-human-in-the-loop.md).
License (Apache-2.0)
Apache-2.0
Source: google/skills
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE