goagent

module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 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
error_handling command
generator/basic command
llm/kimi command
option_demo/llm command
performance command
Package main demonstrates InvokeFast performance optimization
Package main demonstrates InvokeFast performance optimization
rag command
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
examples command
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