gopheragent

module
v0.48.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: Apache-2.0

README

GopherAgent — Go / Golang Agent Framework

Build production LLM agents with YAML. Ship them in Go.

Go Reference CI License

GopherAgent is a Golang multi-agent LLM framework — deterministic ReAct loops, parallel tool execution, streaming, sub-agents, and multi-model routing. Your PM writes a YAML file. Your engineer registers a Go tool. GopherAgent wires them together at runtime — no recompile, no redeploy.

# agent.yaml — your PM creates this
agent:
  name: "Customer Support"
  system_prompt: |
    You are a customer support agent. Look up orders before answering.
    Be polite and concise. Escalate billing issues to a human.
  tools_required:
    - "lookup_order"
    - "web_search"
// main.go — your engineer writes this once
catalog := builder.NewGlobalCatalog()
catalog.Register(&LookupOrderTool{db: db})
catalog.Register(webSearchTool)

loop, _, _, _ := builder.BuildFromYAML("agent.yaml", catalog, provider, nil)
loop.RunIteration(ctx, sessionKey, userMessage)

That's it. Change the YAML, get a different agent. No code changes.

Install

go get github.com/hung12ct/gopheragent

What you get

  • YAML-defined agents — file or //go:embed, with knowledge-base injection.
  • Skills with progressive disclosure — an Agent Skills loader over any io/fs.FS; descriptions sit in the prompt, full instructions load only when a skill is used.
  • Deterministic ReAct loop — dependency-aware parallel tool scheduling with <output_of:ID> refs, anti-loop detection, token-budget-aware pruning, and a prompt-cache-friendly history window with incremental compaction (WithHistoryWindow + WithCompactor) that keeps months-long sessions at a flat request size without losing the thread.
  • Streaming & HITL — SSE streaming, human approvals (durable across restarts with DeferApprovals + Resume), plan mode, and self-critique that keeps the best-scoring pass instead of the last one.
  • Honest terminals — a context_trace event says exactly which messages pruning rewrote and why; a degraded terminal reports "the artifact landed, the bookkeeping did not" instead of forcing a turn into success or failure.
  • Custom tools — one interface, schema derived from a Go struct; a middleware chain for logging, timing, rate limiting, and tracing.
  • MCP servers — pkg/tools/mcptools turns any MCP server's tools into registry tools, approval-gated by default and bounded against oversized listings, schemas and results.
  • Multi-provider — OpenAI, Anthropic, Gemini, Vertex, OpenRouter, and OpenAI-compatible backends, each in its own subpackage; multi-model routing; sampling controls.
  • Speech to text — pkg/audio transcribes with Whisper or Gemini behind one interface, ahead of the loop, so any provider can drive an audio-fed agent and a long recording is uploaded once rather than re-sent every turn.
  • Sub-agents & async — sub-agent streaming, conversation forking, background workers, first-class task tracking.
  • Cross-session memory — a post-session consolidator distills transcripts into notes the loader prepends to future sessions.
  • Observability — OpenTelemetry traces + metrics (one trace per turn, nested LLM/tool spans, GenAI-convention token metrics, W3C trace propagation), zero-cost and export-off until an endpoint is configured.
  • Audit log (experimental) — pkg/auditlog ships who-did-what records (tool runs, approvals, policy verdicts, data changes) over OTLP logs — validated, HMAC-signed and sequenced for tamper detection, blocking or batched, optionally fail-closed.
  • Evaluation — grade trajectory + answer + HITL with pkg/eval and a CI-ready gopherevals CLI.

MCP servers

pkg/tools/mcptools connects to a Model Context Protocol server over any SDK transport (stdio, streamable HTTP, in-memory) and registers its tools. It is a separate package, so programs that don't import it don't link the MCP SDK.

s, err := mcptools.Connect(ctx, &mcp.CommandTransport{Command: exec.Command("my-mcp-server")},
	mcptools.WithPrefix("fs_"))
if err != nil {
	return err
}
defer s.Close()
if err := s.RegisterAll(ctx, reg); err != nil {
	log.Printf("some MCP tools were skipped: %v", err) // the valid ones are registered
}
  • Approval by default. Every remote tool requires confirmation: configure agent.WithHITL or a PermissionAllow rule, or calls are auto-denied. Tool descriptions and results come from the server, so treat them as untrusted input that may attempt prompt injection. WithRequireApproval(false) lifts the gate; with WithSpeculativeTools remote tools may then run speculatively, and a discarded speculation's side effect still happened.
  • Prefix untrusted servers with WithPrefix so their names cannot collide with local tools.
  • One-time snapshot. Tools are listed once; list-changed notifications are ignored deliberately so the tool set (and the provider prompt cache) stays stable. Rebuild the registry yourself if you need updates.
  • Bounded. 512 tools, 64 KiB per tool definition and 256 KiB per result by default (WithLimits); for very large servers put a tools.Selector in front.

Documentation

Guide Use it for
Getting started Install, the YAML builder, persistent sessions
Tools Built-in tools, writing custom tools, middleware
Skills Progressive disclosure — catalog in the prompt, instructions on demand
Permissions & HITL Confirmation gates, permission DSL, autonomous approvals
Providers Providers, multi-model routing, sampling, multimodal
Observability OpenTelemetry traces & metrics, collectors, debugging a conversation
Audit log Who-did-what audit events over OTLP: setup, agent integration, event schema
Evaluation Grade an agent with pkg/eval + gopherevals

Full API reference: pkg.go.dev.

Examples

Example What it shows
examples/demo Full chat UI — web research, memory sidebar, Python execution, live HITL, SSE streaming, OTLP export
examples/agent_eval Agent evaluation — trajectory + answer + judge graders, JUnit/Markdown reports, CI gate
examples/creative_studio AI Creative Director — DALL-E 3 images + Veo 2 video clips generated inline
examples/media_chat Media Q&A — upload image/video/doc, native multimodal history, multi-turn references
examples/hitl_server Human-in-the-loop approvals over HTTP (async bridge)
examples/mcp_client MCP server tools in a registry — in-process server, prefixing, HITL-gated agent calls
examples/yaml_agents Multiple YAML-defined agents sharing a catalog, plus a skills-driven assistant
cd examples/demo
printf "LLM_PROVIDER=openai\nOPENAI_API_KEY=sk-...\n" > .env
go run .
# open http://localhost:8888

License

Apache 2.0

Directories

Path Synopsis
cmd
gopherevals command
Command gopherevals runs a GopherAgent eval suite against an agent and writes reports for CI.
Command gopherevals runs a GopherAgent eval suite against an agent and writes reports for CI.
examples
creative_studio command
Creative Studio — a multi-modal AI creative director that generates images and short videos from natural-language descriptions.
Creative Studio — a multi-modal AI creative director that generates images and short videos from natural-language descriptions.
demo command
hitl_server command
Package main is a reference HITL (Human-In-The-Loop) server built on GopherAgent.
Package main is a reference HITL (Human-In-The-Loop) server built on GopherAgent.
mcp_client command
Command mcp_client connects an in-process MCP server to a tool registry with pkg/tools/mcptools.
Command mcp_client connects an in-process MCP server to a tool registry with pkg/tools/mcptools.
media_chat command
media_chat demonstrates native multimodal input: uploaded images are injected into the conversation history as MediaParts and become directly visible to the LLM — no tool call, no separate vision API, no base64 round-trip each turn.
media_chat demonstrates native multimodal input: uploaded images are injected into the conversation history as MediaParts and become directly visible to the LLM — no tool call, no separate vision API, no base64 round-trip each turn.
memory_demo command
Command memory_demo shows GopherAgent's cross-session memory in action.
Command memory_demo shows GopherAgent's cross-session memory in action.
internal
latewire
Package latewire catches the one way the one-call Instrument helpers fail silently: something attached to the loop after Instrument ran.
Package latewire catches the one way the one-call Instrument helpers fail silently: something attached to the loop after Instrument ran.
pkg
agent
Package agent provides the core orchestration loop for GopherAgent.
Package agent provides the core orchestration loop for GopherAgent.
agentmetrics
Package agentmetrics exposes a Prometheus / OpenMetrics HTTP handler for a gopheragent BudgetTracker.
Package agentmetrics exposes a Prometheus / OpenMetrics HTTP handler for a gopheragent BudgetTracker.
audio
Package audio defines provider-neutral types for speech-to-text.
Package audio defines provider-neutral types for speech-to-text.
auditlog
Package auditlog records who did what — tool executions, human approvals, policy decisions, data and configuration changes — as structured audit events shipped over OTLP logs, so the collector infrastructure already running for traces and metrics carries the audit trail too.
Package auditlog records who did what — tool executions, human approvals, policy decisions, data and configuration changes — as structured audit events shipped over OTLP logs, so the collector infrastructure already running for traces and metrics carries the audit trail too.
builder
Package builder provides YAML-driven agent configuration and a global tool catalog.
Package builder provides YAML-driven agent configuration and a global tool catalog.
cache
Package cache provides a trigram-based similarity LRU cache for deduplicating tool results.
Package cache provides a trigram-based similarity LRU cache for deduplicating tool results.
eval
Package eval is an evaluation harness for GopherAgent agents.
Package eval is an evaluation harness for GopherAgent agents.
history
Package history defines conversation storage types and session backends.
Package history defines conversation storage types and session backends.
history/historyfake
Package historyfake provides a test-friendly SessionManager fake for consumers writing agent-integration tests without standing up a real session backend.
Package historyfake provides a test-friendly SessionManager fake for consumers writing agent-integration tests without standing up a real session backend.
llm
Package llm hosts provider-neutral LLM utilities — currently the rule-based RouterProvider for multi-model selection — and the per-provider subpackages.
Package llm hosts provider-neutral LLM utilities — currently the rule-based RouterProvider for multi-model selection — and the per-provider subpackages.
llm/anthropic
Package anthropic implements agent.LLMProvider for Anthropic's Claude models via the Messages API, including prompt caching, adaptive thinking, and native structured output.
Package anthropic implements agent.LLMProvider for Anthropic's Claude models via the Messages API, including prompt caching, adaptive thinking, and native structured output.
llm/gemini
Package gemini implements agent.LLMProvider for Google Gemini — both the public Gemini API and Vertex AI — plus the Gemini-backed embedder and multimodal media analyzer.
Package gemini implements agent.LLMProvider for Google Gemini — both the public Gemini API and Vertex AI — plus the Gemini-backed embedder and multimodal media analyzer.
llm/llmfake
Package llmfake provides in-tree fakes for the agent.LLMProvider interface, mirroring pkg/history/historyfake for the session layer.
Package llmfake provides in-tree fakes for the agent.LLMProvider interface, mirroring pkg/history/historyfake for the session layer.
llm/openai
Package openai implements agent.LLMProvider for the OpenAI Chat Completions API and any OpenAI-compatible endpoint (Ollama, Groq, Together AI, vLLM, ...), plus the OpenAI-backed embedder, vision analyzer, and history summary provider.
Package openai implements agent.LLMProvider for the OpenAI Chat Completions API and any OpenAI-compatible endpoint (Ollama, Groq, Together AI, vLLM, ...), plus the OpenAI-backed embedder, vision analyzer, and history summary provider.
memory
Package memory provides cross-session note persistence so agents can learn between sessions without retraining.
Package memory provides cross-session note persistence so agents can learn between sessions without retraining.
skills
Package skills implements progressive disclosure of agent instructions, following the Agent Skills format (https://agentskills.io).
Package skills implements progressive disclosure of agent instructions, following the Agent Skills format (https://agentskills.io).
telemetry
Package telemetry provides OpenTelemetry integration for GopherAgent via the EventHandler system.
Package telemetry provides OpenTelemetry integration for GopherAgent via the EventHandler system.
telemetry/otelllm
Package otelllm provides an OpenTelemetry instrumenting decorator for any agent.LLMProvider.
Package otelllm provides an OpenTelemetry instrumenting decorator for any agent.LLMProvider.
telemetry/otelsetup
Package otelsetup wires an OpenTelemetry OTLP pipeline for gopheragent with a single call.
Package otelsetup wires an OpenTelemetry OTLP pipeline for gopheragent with a single call.
telemetry/oteltools
Package oteltools provides an OpenTelemetry tools.Middleware that traces each tool execution and records latency and error metrics.
Package oteltools provides an OpenTelemetry tools.Middleware that traces each tool execution and records latency and error metrics.
telemetry/semconv
Package semconv holds the OpenTelemetry attribute keys and metric names shared by the gopheragent instrumentation packages (otelllm, oteltools, and the agent loop).
Package semconv holds the OpenTelemetry attribute keys and metric names shared by the gopheragent instrumentation packages (otelllm, oteltools, and the agent loop).
telemetry/spanattr
Package spanattr carries request-scoped span attributes — tenant, user, feature flag, request ID — on a context.Context, so every span started under that ctx (agent run, iteration, chat, execute_tool, sub-agent runs) can be stamped with them without threading values through each instrumentation layer.
Package spanattr carries request-scoped span attributes — tenant, user, feature flag, request ID — on a context.Context, so every span started under that ctx (agent run, iteration, chat, execute_tool, sub-agent runs) can be stamped with them without threading values through each instrumentation layer.
tools
Package tools defines the Tool interface and extension utilities.
Package tools defines the Tool interface and extension utilities.
tools/mcptools
Package mcptools adapts the tools of a Model Context Protocol (MCP) server into tools.Tool values an agent loop can call.
Package mcptools adapts the tools of a Model Context Protocol (MCP) server into tools.Tool values an agent loop can call.
tools/toolsfake
Package toolsfake provides a configurable tools.Tool fake for agent tests.
Package toolsfake provides a configurable tools.Tool fake for agent tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL