Developing with Genkit in Go

Developing with Genkit in Go

Teaches an AI coding agent to build AI features, flows, tools and agents in Go with Genkit, loading focused references for generation, streaming, prompts and deployment.

Skill files20 files

references/

SKILL.md235 lines
1
---
2
name: developing-genkit-go
3
description: >-
4
Provides guidance on developing AI-powered applications using Genkit in Go.
5
Use when the user asks to build AI features, agents, flows, or tools in Go
6
using Genkit, or when working with Genkit Go code involving generation,
7
prompts, streaming, tool calling, or model providers. Don't use for Genkit in
8
JavaScript/TypeScript, Python, or Dart.
9
metadata:
10
version: "1.0.0"
11
category: AiAndMachineLearning
12
---
13
14
# Genkit Go
15
16
Genkit Go is an AI SDK for Go that provides generation, structured output,
17
streaming, tool calling, prompts, and flows with a unified interface across
18
model providers.
19
20
## Hello World
21
22
```go
23
package main
24
25
import (
26
"context"
27
"fmt"
28
"log"
29
"net/http"
30
31
"github.com/firebase/genkit/go/ai"
32
"github.com/firebase/genkit/go/genkit"
33
"github.com/firebase/genkit/go/plugins/googlegenai"
34
"github.com/firebase/genkit/go/plugins/server"
35
)
36
37
func main() {
38
ctx := context.Background()
39
g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{}))
40
41
genkit.DefineFlow(g, "jokeFlow", func(ctx context.Context, topic string) (string, error) {
42
return genkit.GenerateText(ctx, g,
43
ai.WithModelName("googleai/gemini-flash-latest"),
44
ai.WithPrompt("Tell me a joke about %s", topic),
45
)
46
})
47
48
mux := http.NewServeMux()
49
for _, f := range genkit.ListFlows(g) {
50
mux.HandleFunc("POST /"+f.Name(), genkit.Handler(f))
51
}
52
log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux))
53
}
54
```
55
56
## Core Features
57
58
Load the appropriate reference based on what you need:
59
60
| Feature | Reference | When to load |
61
| --- | --- | --- |
62
| Initialization | [references/getting-started.md](references/getting-started.md) | Setting up `genkit.Init`, plugins, the `*Genkit` instance pattern |
63
| Generation | [references/generation.md](references/generation.md) | `Generate`, `GenerateText`, `GenerateData`, streaming, output formats, `Embed` |
64
| Prompts | [references/prompts.md](references/prompts.md) | `DefinePrompt`, `DefineDataPrompt`, `.prompt` files, schemas |
65
| Tools | [references/tools.md](references/tools.md) | `DefineTool`, `DefineResumableTool` interrupts (`Interrupted` claim, `Restart`/`Respond`, `WithResume`), `ai/tool` helpers (`tool.Interrupt`, `tool.Fail`, `tool.AttachParts`) |
66
| 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`) |
67
| Observability | [references/observability.md](references/observability.md) | OpenTelemetry export (`otelgenai`), `tracing.SetInstrumentation`, `aix.Observer`, reflection API outside dev |
68
| Flows & HTTP | [references/flows-and-http.md](references/flows-and-http.md) | `DefineFlow`, `DefineStreamingFlow`, `genkit.Handler`, HTTP serving |
69
| Model Providers | [references/providers.md](references/providers.md) | Google AI, Vertex AI, Anthropic, OpenAI-compatible, Ollama setup |
70
71
## Agents (Experimental)
72
73
Genkit Go has an **experimental** agent API for persistent, multi-turn
74
conversations (sessions, snapshots, interrupts, branching, background
75
execution).
76
It is gated: initialize with `genkit.Init(ctx, genkit.WithExperimental())` or
77
the
78
constructors panic. Server constructors come from `genkit/exp` (aliased
79
`genkitx`); types and options from `ai/exp` (aliased `aix`); session stores from
80
`ai/exp/localstore`.
81
82
- **Agent or flow?** If the task is conversational, multi-turn, or described as
83
"an agent", "assistant", or "chatbot", build it with `genkitx.DefineAgent`
84
rather than hand-rolling a `Generate` + tools loop in a flow. Reach for a
85
plain flow only for single-shot, stateless generation.
86
87
For details see:
88
89
- [Agents](references/agents.md): defining/serving an agent, running turns,
90
and client- vs server-managed state (start here).
91
- [Sessions & persistence](references/agents-sessions.md): session stores
92
(`localstore.NewInMemorySessionStore`/`NewFileSessionStore`, PostgreSQL),
93
snapshots, and the `sessionstoretest` conformance suite.
94
- [Human-in-the-loop / interrupts](references/agents-human-in-the-loop.md):
95
pausing for approval/input and resuming.
96
- [Branching](references/agents-branching.md): forking a conversation from a
97
snapshot.
98
- [Background agents](references/agents-background.md): detaching long-running
99
turns and polling.
100
- [Working with state](references/agents-state.md): typed custom session
101
state, streamed as JSON patches.
102
- [Artifacts](references/agents-artifacts.md): producing and reading named
103
deliverables.
104
- [Multi-agent orchestration](references/agents-multi-agent.md): delegating to
105
sub-agents, background delegation, `continue_task`, and remote agents
106
(`DefineRemoteAgent`).
107
- [Advanced custom agents](references/agents-custom.md): `DefineCustomAgent`
108
for full turn control.
109
- [Deploying agents](references/agents-deployment.md): serving agents over
110
HTTP with `genkit.Handler`.
111
112
## Generative UI (A2UI)
113
114
Genkit Go has an **A2UI** (Agent-to-UI) plugin
115
(`github.com/firebase/genkit/go/plugins/a2ui/exp`, imported as `a2uix`) that
116
lets an agent stream interactive UI **surfaces** (cards, lists, forms, buttons),
117
not just prose. The whole integration is the `&a2uix.Surfaces{}` model
118
middleware added via `ai.WithUse`
119
on a generate call or agent inline prompt. **Go is server-only: it has no A2UI
120
client/renderer.** Render surfaces with a JS or Dart/Flutter client that talks
121
to
122
your Go agent over HTTP (the server and clients are wire-compatible).
123
124
- [A2UI](references/a2ui.md): server middleware, options, custom catalogs, and
125
security. For the client (rendering surfaces), refer to the A2UI reference
126
in the Genkit JS or Dart skill.
127
128
## Genkit CLI (recommended)
129
130
`genkit start` unintrusively wraps any Go program that uses the Genkit library,
131
running it unchanged while capturing traces from every Genkit action so you can
132
prove tools were actually called and inspect model I/O from the terminal, even
133
for headless checks. It forwards stdio, so interactive CLI tools that rely on
134
stdin/stdout work without issues. Running the app directly (`go run .`) skips
135
trace capture, so you're debugging blind. Check install with `genkit --version`.
136
137
**Installation:**
138
```bash
139
curl -sL cli.genkit.dev | bash
140
```
141
142
**Primary pattern (default):** prefix `genkit start --` to your normal run
143
command. This collects telemetry from any Genkit code your program runs, whether
144
triggered from the dev UI, your own web server/web UI, or a plain script. Starts
145
the Developer UI (usually http://localhost:4000) for running flows, model and
146
agent playground, and browsing traces:
147
```bash
148
genkit start -- go run .
149
genkit start --noui -- go run . # same, without the Dev UI (still a persistent server)
150
genkit start -o -- go run . # also opens the browser
151
```
152
`genkit start` runs until you stop it with Ctrl+C. That is expected and correct
153
for the common cases: a server your web/mobile app calls, or an interactive CLI
154
you exit yourself. `--noui` only drops the Dev UI; it is **not** a one-shot
155
command and will not exit on its own. Do **not** use `genkit start` as a
156
blocking step in automated/non-interactive contexts; use `flow:run` (below) for
157
that.
158
159
**Non-interactive use (agents/CI):** add the global `--non-interactive` flag
160
before `--` so the CLI uses defaults and never blocks on a prompt (e.g. the
161
first-run analytics notice): `genkit start --non-interactive -- go run .` (works
162
with `flow:run` too).
163
164
**Run a flow (`flow:run`):** invoke a specific flow by name from the CLI. Append
165
your run command after `--` to spin up the runtime just for this run (the
166
command runs as-is to register your flows):
167
```bash
168
genkit flow:run myFlow '{"data": "input"}' -- go run .
169
genkit flow:run myFlow '{"data": "input"}' --stream -- go run . # with streaming
170
genkit flow:run myFlow '{"data": "input"}' --wait -- go run . # wait for completion
171
```
172
This is **self-terminating**: it runs the flow once, prints a `Trace ID`, then
173
exits, so it's the right choice for a quick, non-interactive check (unlike
174
`genkit start`). Traces for this run can be inspected using the trace commands
175
below.
176
177
**Debugging with traces:** the fastest way to see prompts, model inputs/outputs,
178
tool calls, latencies, and errors. Inspect from the terminal after any run under
179
`genkit start`:
180
```bash
181
genkit trace:list # find recent trace IDs
182
genkit trace:get <traceId> # full trace details (inputs, outputs, tool calls, errors)
183
genkit trace:get <traceId> --format json # machine-readable JSON, safe to pipe into jq or other parsers
184
```
185
186
For machine-readable output, pass `--format json` to get clean JSON you can pipe
187
into `jq` or other parsers. The **default** output is human-oriented (banner/log
188
lines, possible truncation on large traces), so don't pipe that form directly;
189
use `--format json`, grep, or the Dev UI trace viewer.
190
191
**Documentation:**
192
```bash
193
genkit docs:search "streaming" go
194
genkit docs:list go
195
genkit docs:read go/flows.md
196
```
197
198
See [references/getting-started.md](references/getting-started.md) for full CLI
199
and Developer UI details.
200
201
## Key Guidance
202
203
- **Pass `g` explicitly.** The `*Genkit` instance returned by `genkit.Init` is
204
the central registry. Pass it to all Genkit functions rather than storing it
205
as a global. This is a core pattern throughout the SDK.
206
- **Wrap AI logic in flows.** Flows give you tracing, observability, HTTP
207
deployment via `genkit.Handler`, and the ability to test from the Developer UI
208
and CLI. Any generation call worth keeping should live in a flow.
209
- **Verify with traces, not a blind run.** Running the app directly (`go run .`)
210
does not capture dev traces. See the [Genkit CLI](#genkit-cli-recommended)
211
section for how to run your app and capture traces.
212
- **Use `jsonschema:"description=..."` struct tags on output types.** The model
213
uses these descriptions to understand what each field should contain. Without
214
them, structured output quality drops significantly.
215
- **Write good tool descriptions.** The model decides which tools to call based
216
on their description string. Vague descriptions lead to missed or incorrect
217
tool calls.
218
- **Use `.prompt` files for complex prompts.** They separate prompt content from
219
Go code, support Handlebars templating, and can be iterated on without
220
recompilation. Code-defined prompts are better for simple, single-line cases.
221
- **Use `DefineResumableTool` for interrupts.** Claim paused calls with the
222
tool's `Interrupted` method and resume with `ai.WithResume`.
223
`ai.InterruptWith`, `RestartWith`/`RespondWith`, and `WithToolRestarts` are
224
deprecated; `genkitx.DefineInterruptibleTool` and `ai/exp/tool` were removed
225
in v1.14.0. See [references/tools.md](references/tools.md).
226
- **Reach for built-in middleware before writing one.** `Retry`, `Fallback`,
227
`ToolApproval`, `Filesystem`, `Skills`, and `SoftToolErrors` cover the common
228
cross-cutting needs and compose with each other via `ai.WithUse`. See
229
[references/middleware.md](references/middleware.md). When you do write custom
230
middleware, allocate per-call state in closures captured by `New`, and guard
231
anything that `WrapTool` mutates because tools may run concurrently.
232
- **Look up the latest model IDs.** Model names change frequently. Check
233
provider documentation for current model IDs rather than relying on hardcoded
234
names. See [references/providers.md](references/providers.md).
235

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…