gopheragent

module
v0.34.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 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 (multiagent) 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.

Installation

go get github.com/hung12ct/gopheragent

The YAML Builder

Engineers register tools into a catalog; PMs wire agents with YAML.

catalog := builder.NewGlobalCatalog()
catalog.Register(&CheckInventoryTool{})
catalog.Register(builtin.NewReadURLTool())
webSearch, _ := builtin.NewWebSearchTool("")
catalog.Register(webSearch)

provider, _ := openai.New("", "gpt-4o") // pkg/llm/openai
loop, _, _, _ := builder.BuildFromYAML("agent.yaml", catalog, provider, nil)
resp, _ := loop.RunIteration(ctx, "session_1", "Do we have iPhone 16 in stock?")

More YAML agent patterns (customer support, data analyst, content writer, multi-agent SQL hub) live in examples/yaml_agents.

Built-in Tools

Import github.com/hung12ct/gopheragent/pkg/tools/builtin:

Tool Constructor Description
Web search NewWebSearchTool(apiKey) Internet search via Tavily API
Read URL NewReadURLTool() Fetch and parse any web page to plain text; SSRF-protected
Show media NewShowMediaTool() Embed images or videos inline in streaming UIs
HTTP request NewHTTPRequestTool() Call JSON APIs and webhooks; SSRF-protected + host allowlist
File read NewFileReadTool(root) Read local files; path-traversal-safe root sandbox
Media analyze NewMediaAnalyzeTool(analyzer) Describe images or videos via any multimodal model
Memory set/get/delete/list NewMemorySetTool(store) etc. Agent-curated key/value facts; survives context pruning
Task tracking (create/update/list) RegisterTaskTools(registry, store) Structured planning scratchpad with enum status (pending/in_progress/completed)
Code interpreter NewCodeInterpreterTool() Execute Python or Node snippets; output-capped, timeout-bounded
SQL agent NewSQLAgentTool(db, schema, sm, provider) Natural language → read-only SQL; DML-proof + self-consistency
Generate image NewGenerateImageTool(apiKey, model) DALL-E 3 image generation; returns inline markdown embed
Generate video NewGenerateVideoTool(apiKey, model) Veo 2 video generation (5–8 s); inline <video> result

Writing Custom Tools

Implement the tools.Tool interface — one struct, five methods. Use tools.SchemaFor[T]() to derive the JSON schema from a Go struct:

type CheckInventoryArgs struct {
    ProductName string `json:"product_name" description:"Product to check"`
}

type CheckInventoryTool struct{ db *sql.DB }

func (t *CheckInventoryTool) Name() string        { return "check_inventory" }
func (t *CheckInventoryTool) Description() string { return "Check product stock" }
func (t *CheckInventoryTool) ParametersSchema() tools.ToolSchema {
    return tools.SchemaFor[CheckInventoryArgs]()
}
func (t *CheckInventoryTool) RequiresConfirmation() bool { return false }
func (t *CheckInventoryTool) Execute(ctx context.Context, argsJSON string) (string, error) {
    var args CheckInventoryArgs
    _ = json.Unmarshal([]byte(argsJSON), &args)
    return `{"in_stock": 250}`, nil
}

Supported tags: json, description, enum, required. See pkg/tools/schema.go for the full type list.

Permission Flow

When a tool returns RequiresConfirmation() = true, the loop denies the call unless one of:

  • A loop.ConfirmHITL hook returns true (human approves), or
  • A loop.Permissions rule returns PermissionAllow (policy auto-approves).

With neither, the call is denied and the model receives a directive "permission gate" message telling it to ask the user for approval.

For autonomous agents (no human reviewer), pre-approve trusted tools:

loop.Permissions = agent.NewPermissionRuleSet().
    Allow("call_sql_agent").     // bypass HITL for this tool
    Deny("dangerous_tool")       // deny-over-allow ordering

Or opt the tool out of confirmation entirely at the source:

sqlTool := builtin.NewSQLAgentTool(db, "", sm, provider).
    WithRequiresConfirmation(false)

Native Multimodal Input

Conversation history accepts typed MediaParts — images go straight into the LLM request on OpenAI, Anthropic, and Gemini, no base64 round-trip per turn. See examples/media_chat.

Production-Ready Features

Full API on pkg.go.dev.

Runtime

  • Streaming (SSE), HITL approvals, plan mode, self-critique (Reflect)
  • Dependency-aware parallel tool scheduling with <output_of:ID> refs
  • Sub-agent streaming, conversation forking, first-class task tracking

Cost & performance

  • Structured output / JSON mode across OpenAI, Anthropic, Gemini
  • Anthropic prompt-cache hints, speculative tool execution
  • Per-session token budget, thinking budget, tool RAG (50+ tools)
  • Multi-model routing (llm.RouterProvider)

Reliability

  • Exponential-backoff retry, structured errors (errors.Is / errors.As)
  • Structured tool-error hints for better LLM recovery
  • Session TTL + auto cleanup, SSRF-hardened HTTP tools

Ops

  • OpenTelemetry tracing, Prometheus via BudgetTracker.MetricsHandler()
  • Custom event sinks (OnEvent), tool middleware chain

Extensibility

  • YAML-driven agents (file or //go:embed) + knowledge base injection
  • Permission DSL (Allow / Deny glob patterns)
  • Typed event payloads, bounded async workers
  • Cross-session memory (pkg/memory): post-session Consolidator distills transcripts into notes that the loader prepends to future sessions — agents learn between conversations without retraining

Supported Providers

Each provider lives in its own subpackage, so a binary that uses one vendor does not statically link the other vendors' SDKs:

Provider Import Constructor Models
OpenAI pkg/llm/openai openai.New(key, model) gpt-4o, gpt-4o-mini, o1, ...
Anthropic pkg/llm/anthropic anthropic.New(key, model) claude-sonnet, claude-opus, ...
Google Gemini pkg/llm/gemini gemini.New(key, model) gemini-2.5-flash, gemini-2.5-pro, ...
Vertex AI (Gemini) pkg/llm/gemini gemini.NewVertex(project, location, model) Vertex-hosted Gemini via ADC
OpenAI-compatible pkg/llm/openai openai.NewCompat(key, model, baseURL) Ollama, Groq, vLLM, Together, ...

All providers auto-discover API keys from environment variables when key is "".

Every constructor accepts sampling options for reproducible runs — WithTemperature(t), WithTopP(p), and WithSeed(n) (OpenAI and Gemini only; the Anthropic API has no seed parameter, so temperature 0 there is best-effort, not bit-exact). Unset options keep each provider's defaults.

Evaluation

pkg/eval evaluates an agent against a suite of tasks: it checks the tool-call trajectory (which tools ran, in what order, with what arguments), the final answer (contains / regex / exact, or an LLM-as-judge with an "unknown" escape hatch and N-sample majority vote), whether a human-in-the-loop approval gate fired for a dangerous tool (or, with NoHITL, that a safe request did not trip one), and reports cost, tokens, and latency. Tasks can be multi-turn conversations, run over N trials with pass@k / pass^k, and are matched with five trajectory modes (strict, in-order, unordered, subset, superset).

Run it two ways:

// Inside go test — deterministic with a scripted provider, no API keys.
eval.RunT(t, &eval.Runner{NewTarget: factory}, suite)
# In CI — YAML suite against a real agent; exits non-zero below threshold.
go run ./cmd/gopherevals -suite suite.yaml -agent agent.yaml -junit eval.xml -threshold 0.9

Reports emit as JSON, JUnit XML (rendered natively by GitHub Actions), and Markdown. Capture transcripts once with -save-transcripts and re-grade them against a revised rubric via -from-transcripts without re-running the agent. See examples/agent_eval.

Examples

Example What it shows
examples/demo Full chat UI — web research, memory sidebar, Python execution, live HITL, SSE streaming
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/yaml_agents Multiple YAML-defined agents sharing a catalog
cd examples/demo
echo "LLM_PROVIDER=openai\nOPENAI_API_KEY=sk-..." > .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.
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.
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.
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, extended thinking, and structured output (synthesized-tool JSON mode).
Package anthropic implements agent.LLMProvider for Anthropic's Claude models via the Messages API, including prompt caching, extended thinking, and structured output (synthesized-tool JSON mode).
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.
telemetry
Package telemetry provides OpenTelemetry integration for GopherAgent via the EventHandler system.
Package telemetry provides OpenTelemetry integration for GopherAgent via the EventHandler system.
tools
Package tools defines the Tool interface and extension utilities.
Package tools defines the Tool interface and extension utilities.
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