goagent

module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2025 License: Apache-2.0

README

GoAgent - AI Agent Framework for Go

Go Version Build License Documentation Downloads Go Report Card Go Reference Deepwiki

GoAgent is a comprehensive, production-ready AI agent framework for Go, inspired by LangChain. It provides agents, tools, memory, LLM abstraction, and orchestration capabilities with enterprise-grade features like distributed tracing, persistent storage, and multi-agent coordination.

Features

  • Intelligent Agents - Autonomous agents with reasoning capabilities and tool execution
  • High Performance - Hot path optimization with InvokeFast reducing latency by 4-6%
  • Flexible Architecture - 4-layer modular design with clear separation of concerns
  • LLM Abstraction - Support for multiple LLM providers (OpenAI, Anthropic Claude, Cohere, HuggingFace, Gemini, DeepSeek)
  • Memory Management - Conversation history, case-based reasoning, and vector storage
  • Tool System - Extensible tool registry with parallel execution and dependency management
  • State Management - Thread-safe state with checkpointing and persistence
  • Observability - OpenTelemetry integration with distributed tracing
  • Enterprise Ready - Redis, PostgreSQL support, NATS messaging, and high availability

Quick Start

Installation
go get github.com/kart-io/goagent
Basic Example
package main

import (
    "context"
    "log"

    "github.com/kart-io/goagent/builder"
    "github.com/kart-io/goagent/llm"
)

func main() {
    // Create LLM client
    llmClient := llm.NewOpenAIClient("your-api-key")

    // Build agent with fluent API
    agent, err := builder.NewAgentBuilder(llmClient).
        WithSystemPrompt("You are a helpful assistant").
        WithMaxIterations(10).
        WithTimeout(30 * time.Second).
        Build()

    if err != nil {
        log.Fatal(err)
    }

    // Execute agent
    result, err := agent.Execute(context.Background(), "Analyze the latest sales data")
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Result: %v", result)
}
Using Pre-configured Agents
// Create a RAG agent for document Q&A
ragAgent, err := builder.RAGAgent(llmClient, vectorStore)

// Create an analysis agent (low temperature, high precision)
analysisAgent, err := builder.AnalysisAgent(llmClient, dataSource)

// Create a monitoring agent (long-running, periodic checks)
monitoringAgent, err := builder.MonitoringAgent(llmClient, 30*time.Second)

Architecture

GoAgent follows a 4-layer architecture for maintainability and scalability:

Layer 1: Foundation     - Interfaces, errors, cache, utilities
Layer 2: Business Logic - Core, LLM, memory, storage, observability
Layer 3: Implementation - Agents, tools, middleware, parsers
Layer 4: Examples       - Usage examples and tests

See Architecture Documentation for details.

Core Components

Agents

Autonomous entities that can reason, use tools, and make decisions.

type Agent interface {
    Execute(ctx context.Context, input *AgentInput) (*AgentOutput, error)
    Name() string
    Description() string
    Capabilities() []string
}
Tools

Extensible functions that agents can call to interact with external systems.

type Tool interface {
    Name() string
    Description() string
    Execute(ctx context.Context, input map[string]interface{}) (interface{}, error)
}
Memory

Persistent storage for conversations, cases, and application state.

type Manager interface {
    AddConversation(ctx context.Context, conv *Conversation) error
    GetConversationHistory(ctx context.Context, sessionID string, limit int) ([]*Conversation, error)
    SearchSimilarCases(ctx context.Context, query string, limit int) ([]*Case, error)
}
Builder

Fluent API for constructing agents with complex configurations.

agent := builder.NewAgentBuilder(llmClient).
    WithSystemPrompt("You are an expert analyst").
    WithTools(searchTool, calcTool).
    WithMemory(memoryManager).
    WithMiddleware(loggingMW, cacheMW).
    Build()

Advanced Features

State Management & Checkpointing
// Create checkpointer for session persistence
checkpointer := core.NewRedisCheckpointer(redisClient, "agent:")

agent := builder.NewAgentBuilder(llmClient).
    WithCheckpointer(checkpointer).
    WithConfig(&builder.AgentConfig{EnableAutoSave: true}).
    Build()
Distributed Tracing
// Initialize OpenTelemetry
provider := observability.NewTelemetryProvider(&observability.TelemetryConfig{
    ServiceName: "my-agent",
    OTLPEndpoint: "localhost:4317",
})

// Traces are automatically propagated across agent calls
Multi-Agent Communication
// NATS-based distributed communication
comm := multiagent.NewNATSCommunicator("agent-1", natsConn, tracer)

// Send message to another agent
message := &multiagent.AgentMessage{
    From: "agent-1",
    To: "agent-2",
    Type: multiagent.MessageTypeRequest,
    Payload: map[string]interface{}{"task": "analyze"},
}
comm.Send(ctx, "agent-2", message)
Parallel Tool Execution
// Execute multiple tools concurrently
executor := tools.NewToolExecutor(tools.ToolExecutorConfig{
    MaxConcurrency: 10,
    Timeout: 30 * time.Second,
})

results, err := executor.ExecuteParallel(ctx, []tools.ToolCall{
    {Tool: searchTool, Input: map[string]interface{}{"query": "Go"}},
    {Tool: calcTool, Input: map[string]interface{}{"expr": "2+2"}},
})

Documentation

See DOCUMENTATION_INDEX.md for a complete guide.

Examples

Explore working examples in the examples/ directory:

  • Basic - Simple agent creation and execution
  • Advanced - Complex workflows with state management
  • Integration - Multi-component systems
  • Streaming - Real-time streaming responses
  • Observability - Tracing and metrics
  • Multi-agent - Agent-to-agent communication

Run an example:

go run examples/basic/01-simple-agent/main.go

Performance

Core Performance Metrics
  • Builder Construction: ~100μs/op
  • Agent Execution: ~1ms/op (excluding LLM calls)
  • Middleware Overhead: <5%
  • Parallel Tool Execution: Linear scaling to 100+ concurrent calls
  • Cache Hit Rate: >90% with LRU caching
  • OpenTelemetry Overhead: <2% at 10% sampling
InvokeFast Optimization 🚀

GoAgent provides InvokeFast, a hot path optimization that bypasses callbacks and middleware for internal calls:

Performance Gains (ReActAgent benchmarks on Intel i7-14700KF):

  • Latency: 4-6% faster execution (1494ns → 1399ns per call)
  • Memory: 5-8% reduction in allocations
  • Chain Calls (10x): 4.4% faster (15508ns → 14825ns)

Automatic Optimization:

  • ChainableAgent automatically uses InvokeFast for internal calls
  • SupervisorAgent optimizes sub-agent coordination
  • ExecutorAgent optimizes wrapped agent execution
  • Zero code changes required for existing applications

Use Cases:

  • Multi-agent systems with nested calls
  • High-frequency reasoning loops (ReAct)
  • Chain compositions with multiple agents
  • Performance-critical production workloads

See InvokeFast Optimization Guide for implementation details and benchmarks.

Benchmarking Your Agents
import "testing"

func BenchmarkYourAgent(b *testing.B) {
    agent := createYourAgent()
    ctx := context.Background()
    input := &core.AgentInput{Task: "test"}

    b.Run("Standard", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            _, _ = agent.Invoke(ctx, input)
        }
    })

    b.Run("Optimized", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            _, _ = agent.InvokeFast(ctx, input)
        }
    })
}

See Test Coverage Report for detailed benchmarks.

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Development Setup
# Clone repository
git clone https://github.com/kart-io/goagent.git
cd goagent

# Install dependencies
go mod download

# Run tests
go test ./...

# Run linter
golangci-lint run

# Run examples
go run examples/basic/01-simple-agent/main.go
Code Quality
  • Minimum test coverage: 80%
  • All public APIs must have documentation
  • Follow import layering rules
  • Run verification: ./verify_imports.sh

Roadmap

  • Additional LLM providers (Anthropic Claude, Cohere, Hugging Face)
  • Production vector database integration (Qdrant, Milvus, Pinecone)
  • Graphical workflow designer
  • Enhanced monitoring dashboard
  • Agent versioning and A/B testing
  • Performance optimizations (connection pooling, batch processing)

See archived roadmaps for historical planning.

Design Principles

  1. Interface First - Clear interfaces supporting multiple implementations
  2. Composability - Components can be flexibly combined and extended
  3. Type Safety - Strong typing to catch errors at compile time
  4. Context Aware - All operations support context.Context
  5. Observability - Built-in tracing, metrics, and logging
  6. Ease of Use - Sensible defaults and fluent APIs

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Support

Acknowledgments

GoAgent is inspired by:


Status: Production Ready Version: 1.0 Go Version: 1.25.0+ Last Updated: 2025-11-15

Directories

Path Synopsis
cot
got
pot
sot
tot
Package core provides the lifecycle manager implementation.
Package core provides the lifecycle manager implementation.
state
Package state provides type-safe state management with schema validation.
Package state provides type-safe state management with schema validation.
examples
advanced command
advanced/react command
basic/02-tools command
basic/08-deepseek-agent command
Package main demonstrates using DeepSeek LLM provider with GoAgent
Package main demonstrates using DeepSeek LLM provider with GoAgent
basic/09-deepseek-simple command
Package main demonstrates a simple DeepSeek agent implementation
Package main demonstrates a simple DeepSeek agent implementation
basic/09-deepseek-simple/invokefast command
Package main demonstrates DeepSeek usage with GoAgent's InvokeFast optimization
Package main demonstrates DeepSeek usage with GoAgent's InvokeFast optimization
basic/10-object-pooling command
Package main demonstrates the usage of GoAgent's object pooling for GC pressure reduction
Package main demonstrates the usage of GoAgent's object pooling for GC pressure reduction
basic/11-deepseek-with-builder command
Package main demonstrates using DeepSeek LLM with AgentBuilder
Package main demonstrates using DeepSeek LLM with AgentBuilder
basic/12-deepseek-simple command
Package main demonstrates simplified DeepSeek Agent usage
Package main demonstrates simplified DeepSeek Agent usage
basic/13-simple-builder-deepseek command
Package main 演示使用简化的 Builder API 构建 DeepSeek Agent
Package main 演示使用简化的 Builder API 构建 DeepSeek Agent
basic/14-reasoning-agents command
Package main 演示使用 builder 包快速创建各种推理型 Agent
Package main 演示使用 builder 包快速创建各种推理型 Agent
basic/15-simple-builder-kimi command
Package main 演示使用简化的 Builder API 构建 Kimi Agent
Package main 演示使用简化的 Builder API 构建 Kimi Agent
basic/16-pdf-rag command
Package main 演示使用 PDF 文档构建 RAG(检索增强生成)系统
Package main 演示使用 PDF 文档构建 RAG(检索增强生成)系统
basic/17-vertexai-rag command
Package main 演示使用 Vertex AI(Gemini)构建 RAG 系统
Package main 演示使用 Vertex AI(Gemini)构建 RAG 系统
builder/advanced command
Advanced API 示例 展示 Builder API 的 Advanced 层级(30+ 个方法,覆盖 100% 使用场景)
Advanced API 示例 展示 Builder API 的 Advanced 层级(30+ 个方法,覆盖 100% 使用场景)
builder/core command
Core API 示例 展示 Builder API 的 Core 层级(15-20 个方法,覆盖 95% 使用场景)
Core API 示例 展示 Builder API 的 Core 层级(15-20 个方法,覆盖 95% 使用场景)
builder/simple command
Simple API 示例 展示 Builder API 的 Simple 层级(5-8 个方法,覆盖 80% 使用场景)
Simple API 示例 展示 Builder API 的 Simple 层级(5-8 个方法,覆盖 80% 使用场景)
comprehensive command
Package main 综合示例 - GoAgent 框架组件完整性验证
Package main 综合示例 - GoAgent 框架组件完整性验证
error_handling command
generator/basic command
llm/advanced command
Package main 演示 LLM 包的高级用法
Package main 演示 LLM 包的高级用法
llm/anthropic command
llm/cohere command
llm/huggingface command
llm/kimi command
multiagent/01-basic-system command
Package main 演示 MultiAgentSystem 的基本用法 本示例展示如何创建多智能体系统、注册 Agent、发送消息和执行协作任务
Package main 演示 MultiAgentSystem 的基本用法 本示例展示如何创建多智能体系统、注册 Agent、发送消息和执行协作任务
multiagent/02-collaboration-types command
Package main 演示不同的多智能体协作类型 本示例展示五种协作模式:并行、顺序、分层、共识、管道
Package main 演示不同的多智能体协作类型 本示例展示五种协作模式:并行、顺序、分层、共识、管道
multiagent/03-team-management command
Package main 演示多智能体团队管理功能 本示例展示如何创建团队、分配角色、管理团队成员
Package main 演示多智能体团队管理功能 本示例展示如何创建团队、分配角色、管理团队成员
multiagent/04-specialized-agents command
Package main 演示专业化 Agent 的使用 本示例展示 SpecializedAgent 和 NegotiatingAgent 的高级用法
Package main 演示专业化 Agent 的使用 本示例展示 SpecializedAgent 和 NegotiatingAgent 的高级用法
multiagent/05-llm-collaborative-agents command
Package main 演示使用 LLM 的多智能体协作系统 本示例展示如何创建具有 LLM 推理能力的协作 Agent
Package main 演示使用 LLM 的多智能体协作系统 本示例展示如何创建具有 LLM 推理能力的协作 Agent
multiagent/06-llm-tool-calling command
Package main 演示如何在 MultiAgent 系统中使用 LLM 调用工具
Package main 演示如何在 MultiAgent 系统中使用 LLM 调用工具
multiagent/07-multiagent-llm-stream command
Package main 演示多智能体系统中使用 LLM 流式响应
Package main 演示多智能体系统中使用 LLM 流式响应
multiagent/08-multiagent-tool-registry command
Package main 演示多智能体系统中使用工具注册表
Package main 演示多智能体系统中使用工具注册表
multiagent/09-multiagent-with-middleware command
Package main 演示多智能体系统中使用工具中间件
Package main 演示多智能体系统中使用工具中间件
multiagent/10-multiagent-integrated command
Package main 演示多智能体系统综合使用 LLM、工具注册表、中间件和记忆
Package main 演示多智能体系统综合使用 LLM、工具注册表、中间件和记忆
multiagent/11-planning-multiagent command
Package main 演示多智能体系统与规划模块的集成使用
Package main 演示多智能体系统与规划模块的集成使用
multiagent/common
Package common 提供 multiagent 示例的公共组件
Package common 提供 multiagent 示例的公共组件
performance command
Package main demonstrates InvokeFast performance optimization
Package main demonstrates InvokeFast performance optimization
planning command
Package main 演示 Planning 包的使用
Package main 演示 Planning 包的使用
rag command
tools/middleware command
Package main 演示中间件与可观测性功能
Package main 演示中间件与可观测性功能
tools/registry command
Package main 演示工具注册表和执行器的使用
Package main 演示工具注册表和执行器的使用
translate command
Package interfaces defines core constants used across all layers of the GoAgent framework.
Package interfaces defines core constants used across all layers of the GoAgent framework.
llm
mcp
Package memory provides enhanced memory capabilities for agents
Package memory provides enhanced memory capabilities for agents
Package multiagent provides multi-agent collaboration capabilities
Package multiagent provides multi-agent collaboration capabilities
Package options 提供各种组件的配置选项
Package options 提供各种组件的配置选项
Package parsers defines constants used for parsing agent outputs, particularly for ReAct (Reasoning and Acting) pattern and other reasoning frameworks.
Package parsers defines constants used for parsing agent outputs, particularly for ReAct (Reasoning and Acting) pattern and other reasoning frameworks.
Package planning provides task decomposition and strategy planning capabilities for agents.
Package planning provides task decomposition and strategy planning capabilities for agents.
Package prompt provides prompt engineering and management capabilities
Package prompt provides prompt engineering and management capabilities
Package reflection provides self-evaluation and improvement capabilities for agents
Package reflection provides self-evaluation and improvement capabilities for agents
examples/basic command
Package store defines constants used for storage and persistence systems.
Package store defines constants used for storage and persistence systems.
adapters
Package adapters provides example usage of store adapters
Package adapters provides example usage of store adapters
adapters/example command
Package main demonstrates real-world usage of store adapters with common options
Package main demonstrates real-world usage of store adapters with common options
plugingen
Package plugingen provides code generation tools for type-safe plugin boundaries.
Package plugingen provides code generation tools for type-safe plugin boundaries.
plugingen/cmd/plugingen command
plugingen is a command-line tool for generating type-safe Go code from plugin schemas.
plugingen is a command-line tool for generating type-safe Go code from plugin schemas.
httpclient
Package httpclient 提供统一的 HTTP 客户端管理
Package httpclient 提供统一的 HTTP 客户端管理

Jump to

Keyboard shortcuts

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