Dev.to AI 🤖 Ai 👁 0 📖 12 min read

Go AI Agent Framework With Retries, Budgets and Human Approval

One of my team's main projects has an AI-heavy backend written in Go. I work mostly in Python, where agent frameworks are mature, so I know what the Go side was missing: an agent that's a normal value inside the service,

Go AI Agent Framework With Retries, Budgets and Human Approval

One of my team's main projects has an AI-heavy backend written in Go. I work mostly in Python, where agent frameworks are mature, so I know what the Go side was missing: an agent that's a normal value inside the service, not a Python process reached over a queue. The loop itself takes an afternoon. Deciding what happens at each place it can break is what became Golem, an open-source Go AI agent framework.

This post is about that second part: bad tool calls, provider errors, loops, cost and human sign-off, and where each one lands in a run. It also covers how Golem compares with the other Go options and when you should pick something else. It describes v1.2.0, released on 16 November 2026.

What breaks once the agent loop is running?

The loop is short. The model reads a conversation, asks for a tool, you run it, you feed the result back and repeat until the model answers. Each step then fails in its own way:

  • The provider returns a 429 or a 503 halfway through a run.
  • The model calls a tool with arguments that don't match your schema.
  • The model returns JSON that is almost the shape you asked for.
  • The model asks for the same tool call again and again.
  • A tool needs a person to approve it before anything irreversible happens.
  • A run dies on turn six and you lose the first five turns.

Python has good answers to several of these. Pydantic AI showed that an agent can have typed dependencies and validated output, and I used it as a reference. But copying Python mechanisms into Go would have given me something un-Go-like: decorators are awkward, runtime validation hides what the compiler could check, and exceptions as control flow don't suit a language that returns errors. So the question I started from was what an agent should look like if you begin with Go's strengths.

What is Golem?

Golem is an open-source Go library for building agents. The repository started on 16 August 2026, and v1.0.0 on 25 October 2026 froze the API under a rule written down in ADR 0041: semantic versioning, additive changes only below v2, checked by an API diff against the previous tag.

The short version:

  • Agents are generic: Agent[Deps, Output]. Dependencies and the final output are real types.
  • The module has no dependencies outside the standard library, and needs Go 1.26 or newer.
  • Adapters cover OpenAI, Anthropic, Google Gemini, AWS Bedrock, Azure OpenAI, and local models through Ollama or LM Studio.
  • An MCP client works over stdio and streamable HTTP, and an MCP server exposes one agent as a tool.
  • Retries, fallback models, self-correction, usage limits, loop detection, streaming and run events are built in.
  • A deterministic fake model lets you test agents offline.
  • It ships with 39 guides, every example runs offline, and statement coverage is 81.6%.
go get github.com/abubakarsiddik31/golem

The layering is plain. Your service owns the dependencies, the core owns the run, and everything that touches the outside world sits behind a small interface.

Your Go service calls the golem core, which talks to two ports: model.Model, implemented by provider adapters, and tool.Tool, implemented by MCP servers and common tools. The core imports only the standard library

Why build agents in Go at all?

Agent work is mostly waiting on a network, so it's fair to ask whether the language matters. I think it does once the agent leaves the notebook. An agent service holds many conversations at once, calls tools concurrently, streams tokens to clients and has to shut down cleanly. Goroutines, context.Context and a single static binary fit that shape. A deployed agent can be one small container image with no interpreter, no virtualenv and no dependency tree to audit.

The compiler is the second reason. When a tool depends on a database handle and a tenant ID, I want the compiler to tell me if I pass the wrong one. In Golem that's a type parameter, not a convention.

What does a first agent look like?

This is the smallest working agent, from the README:

client, err := openai.New(openai.Config{
    APIKey: os.Getenv("OPENAI_API_KEY"),
    Model:  "gpt-4o-mini",
})
if err != nil {
    panic(err)
}

agent, err := golem.New[struct{}, string](client,
    golem.DecodeFunc[string](func(_ context.Context, r model.Response) (string, error) {
        return r.Message.Content, nil
    }),
)
if err != nil {
    panic(err)
}

result, err := agent.Run(context.Background(), golem.RunContext[struct{}]{}, "Why is Go ideal for AI agents?")
fmt.Println(result.Output)
fmt.Printf("Tokens: %d input, %d output\n", result.Usage.InputTokens, result.Usage.OutputTokens)

You build the agent once with golem.New and run it many times. It needs a model and an output decoder, and the decoder is the line where untrusted model text becomes a value your program is willing to use. Everything else is an option function. The result carries the typed output, the full normalized conversation and cumulative token usage.

How do typed tools and dependencies work?

Most agent bugs I've seen live in tools. A tool needs a database, an HTTP client or a user identity, and frameworks often solve that with globals or closures, which makes tools hard to test. In Golem a tool is a typed value, and its Exec function receives the run's dependency value directly:

type Database struct {
    Users map[int]string
}

getUser := tool.MustNew(tool.Tool[Database]{
    Name:        "get_user",
    Description: "Look up a user name by their ID.",
    Schema: json.RawMessage(`{
        "type": "object",
        "properties": {"id": {"type": "integer"}},
        "required": ["id"]
    }`),
    Exec: func(ctx context.Context, db Database, args json.RawMessage) (tool.Result, error) {
        var input struct {
            ID int `json:"id"`
        }
        if err := json.Unmarshal(args, &input); err != nil {
            return tool.Result{}, err
        }
        name, ok := db.Users[input.ID]
        if !ok {
            return tool.Text("User not found"), nil
        }
        return tool.Text(name), nil
    },
})

agent, err := golem.New[Database, string](client, decoder,
    golem.WithTools[Database, string](getUser),
)

result, err := agent.Run(ctx, golem.RunContext[Database]{Deps: Database{Users: map[int]string{42: "Alice"}}}, "Who is user 42?")

The schema is written by hand and the arguments arrive as raw JSON. That's deliberate. Arguments are untrusted model output, and I'd rather you see the validation than have reflection do it somewhere you can't read. It costs a few more lines per tool, and in return a tool's behavior is visible in the file where it's defined.

What happens when a run goes wrong?

A Golem run is a transparent loop, and each failure has a named place to land.

One Golem run: a prompt becomes a request, goes to the model and a usage check, then either runs tools and loops back or decodes a typed result. Tools and decoders can retry, fail, defer or cancel, and any step can end in a RunError that keeps the partial evidence

How does an agent correct bad output?

When the model returns bad output or bad tool arguments, the cheapest fix is often to say what was wrong and ask again. A decoder or tool does that by returning an error that wraps *model.ModelRetry:

if input.N <= 0 {
    return "", &model.ModelRetry{Err: fmt.Errorf("n must be positive, got %d", input.N)}
}

The run feeds that message back to the model. Self-correction is opt-in, with separate budgets from WithOutputRetries and WithToolRetries, so a model can't argue with your validator forever. With no budget, the same error fails the run at a named stage with its cause intact. A failure the model should simply see, like a missing file, is &tool.Failed{Reason}: the model gets the reason as a tool result and no retry budget is spent.

How do you survive provider errors?

Transient provider errors (408, 429, 5xx and transport faults) are retried with WithMaxAttempts. The default is one attempt, so retries are opt-in. Backoff starts at 500 ms, doubles and caps at 30 seconds unless you supply your own. Tool and decode failures are never retried by this mechanism, since they aren't transport problems.

When retrying isn't enough, model.NewFallback(primary, backup) tries models in order. For streams there's one rule: a fallback only happens before the first fragment is forwarded, because after the caller has seen output, switching models would replay it.

How do you stop a runaway agent?

Two limits cover it. golem.UsageLimit bounds input, output and total tokens, model requests and tool calls, and a dollar cost if you supply a price table with WithPrice. Token counts come from the provider's reported usage, so a token limit only trips when the provider reports usage, while requests and tool calls are counted by the run itself. Pricing is yours to supply, because I don't want to ship a table that goes stale between releases, and the library says plainly that the cost estimate is only as good as your rates and isn't a billing guarantee.

The second limit is loop detection, added in v1.2.0 (ADR 0051). WithLoopDetection(maxRepeats) counts calls to the same tool with canonically equal arguments across the whole run, and fails the run before the offending call executes. That ordering is the point: a model that polls a tool can't repeat a side effect while you wait for the check. WithLoopPolicy adds checks for repeated results, alternating A-B calls and repeated final text, with a choice between stopping the run and nudging the model.

Oversized tool output is the quieter cost. WithToolOutputLimit caps a tool result before it enters the conversation, keeps the head and tail, and appends a marker with the original size (ADR 0050).

What do you keep when a run fails?

When a run fails on turn six, you still want turns one to five. Golem attaches them to the error as RunError.Partial: the conversation through the last completed turn, the usage so far and the counts of requests and tool executions. Pass Partial.Messages to RunWithHistory to resume instead of starting over, which matters when the run has already spent real money.

How does an agent wait for a person?

Some tools shouldn't run without sign-off: deleting files, moving money, sending email. A tool defers by returning an error wrapping *tool.Deferred, of kind tool.DeferApproval or tool.DeferExternal. The other tool calls in that batch execute, and Run returns successfully with Result.Pending listing what's waiting. No further model call happens.

You resume with RunWithDeferredResults, passing the paused conversation and a decision for each pending call. Approved calls run, denied calls tell the model it was denied, and external results are inserted as given. Because a pause is a returned value, you can store it, show it in a UI and resume it hours later from another process. The reasoning behind that boundary is in the case for keeping meaningful actions with people.

Can a Go agent use MCP?

The Model Context Protocol is now the usual way to expose tools to agents, so Golem includes a client. mcp.NewStdio starts a server as a subprocess, mcp.NewHTTP connects to a remote endpoint, and mcp.AsTools turns the server's tool list into ordinary tool.Tool values with the server's own schema. A server error flagged as isError comes back as a correctable ModelRetry, and protocol or transport failures fail the run instead of being quietly corrected.

The guide says one thing I agree with: don't reach for MCP when a typed Go tool is one function away. A subprocess speaking JSON-RPC has more moving parts than a function call.

How do you test an agent without a model?

Agent tests are usually flaky (a real provider) or meaningless (mocked HTTP). Golem ships testmodel, a scripted in-memory model that plays back the responses you queue and records the exact request the agent sent:

client := testmodel.New().Respond(
    model.Response{Message: model.Message{Role: model.RoleAssistant, Content: "pong"}},
)
agent, _ := golem.New[struct{}, string](client, decoder)
result, err := agent.Run(context.Background(), golem.RunContext[struct{}]{}, "ping")

You can assert on the normalized request, the ordered messages in Result.Messages and which stage failed, with no network, keys or sleeps. The repository's CI runs its suite with the race detector, plus a fuzz target on the message JSON format.

How does it compare with other Go agent frameworks?

I compared Golem with the three other Go options I'd look at: langchaingo, Eino and Genkit for Go. I read each repository's source tree and go.mod on 27 November 2026. Dependency counts are the non-indirect lines in the require block, so they're approximate, and frameworks move fast, so check upstream before you depend on a detail.

Golem langchaingo Eino Genkit (Go)
Direct dependencies 0 About 60 About 10 About 40
License MIT MIT Apache-2.0 Apache-2.0
MCP client In the core module Not in the repository Separate eino-ext module Plugin in the repository, client and server
Pause for human approval tool.Deferred, resumable Not found Interrupt and resume in adk Tool approval middleware
Retry and model fallback Built into the run Not found Retry and failover in adk Retry and fallback middleware
Design centre One explicit agent loop with typed dependencies LangChain-style chains and agents Graph and workflow composition Flows with OpenTelemetry tracing

Two things stand out. Golem is the only one with no dependencies outside the standard library, and the only one where a tool receives a typed dependency value for the run. I haven't found an equivalent of RunContext[Deps] in the others, but I haven't audited every API, so read that as what I found, not a proof.

The other half is that Golem is not alone on the guardrails. Genkit's Go module ships MCP, retry, fallback and tool approval as plugins and middleware, and Eino's adk package has retry, failover and interrupt-and-resume. Only langchaingo lacks them in the repositories I read. The Golem README understated Genkit on this.

The others are ahead in other places. Eino's graph model is more expressive than Golem's linear loop for branching, parallel and multi-agent pipelines, and it has more community components. langchaingo covers more providers and vector stores. Genkit has first-party Google tooling and tight Gemini integration. What Golem offers is a smaller surface: one runtime for a single agent inside a service, with the controls in the core module instead of in add-on packages.

When should you pick something else?

Pick Golem if you want agents inside a Go service, typed dependencies, a module with nothing else to audit and tests that run offline. Pick something else if your agent is mostly prompt experimentation, if you need a graph engine for complicated multi-agent pipelines, or if you need a large catalog of prebuilt integrations today. Python is still ahead on that last one, and I won't pretend otherwise. Golem also has no evaluation harness and no durable workflow engine, and v1.0.0 lists both as non-goals.

Herbie, a self-hosted chat and workflow app I built, runs its Go backend on Golem. I don't have production numbers to publish yet, so everything above is design reasoning plus what the repository's tests and examples show.

The documentation site has a guide for each feature, and examples/ has runnable programs for nearly all of them, several with no API key.

Issues and pull requests are welcome. If you try it and something feels un-Go-like, I want to hear about it.

Frequently asked questions

What is Golem?
Golem is an open-source AI agent framework for Go. It provides typed agents, tools with dependency injection, structured output, MCP support, and controls like retries, usage limits, loop detection and human approval.

Does Golem have external dependencies?
No. It uses only the Go standard library.

Which LLM providers does it support?
OpenAI, Anthropic, Google Gemini, AWS Bedrock, Azure OpenAI, and local models through Ollama, LM Studio or any OpenAI-compatible endpoint.

Can I test agents without calling an API?
Yes. The testmodel package gives you a deterministic fake model, and the examples run offline.

Does it support MCP?
Yes. The mcp package is a client for stdio and streamable HTTP servers, and mcpserver exposes an agent as an MCP tool.

Originally published at abubakar-siddik.com.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.