go-llms

module
v0.3.6 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2025 License: MIT

README ΒΆ

Go-LLMs: Unified Go Library for LLM Integration

Build powerful AI applications with a clean, unified interface to multiple LLM providers. Go-LLMs provides everything you need: from simple text generation to complex multi-agent workflows with built-in tools and structured outputs.

Why Go-LLMs?

  • One Library, All Providers - Switch between OpenAI, Anthropic, Google, Ollama, and more with the same code
  • Production Readiness Mindset - Built-in error handling, rate limiting, retries, and monitoring
  • Rich Tooling - 33+ built-in tools for web, files, calculations, and data processing
  • Smart Agents - Create conversational AI that can use tools and coordinate with other agents
  • Structured Data - Get reliable, validated JSON/XML output instead of unpredictable text
  • Go Native - Designed for Go developers with clean APIs and minimal dependencies

Features

✨ Unified Provider API - OpenAI, Anthropic, Google Gemini, Vertex AI, Ollama, OpenRouter
πŸ› οΈ Built-in Tool System - Web search, file operations, calculations, APIs, and more
πŸ€– Intelligent Agents - Conversational AI with memory, tools, and workflow orchestration
πŸ“Š Structured Outputs - JSON schema validation with automatic error recovery
πŸ” Tool Discovery - Dynamic tool exploration perfect for scripting engines
🌐 Multimodal Content - Text, images, audio, video, and file support
⚑ Performance Optimized - Concurrent execution, streaming, caching

Installation

go get github.com/lexlapax/go-llms

Quick Start

Get started in 5 minutes with our interactive quickstart guide.

1. Simple AI Conversation
package main

import (
    "context"
    "fmt"
    "os"
    
    "github.com/lexlapax/go-llms/pkg/llm/provider"
    "github.com/lexlapax/go-llms/pkg/agent/core"
    "github.com/lexlapax/go-llms/pkg/llm/domain"
)

func main() {
    // Create provider
    p := provider.NewOpenAIProvider(os.Getenv("OPENAI_API_KEY"), "gpt-4")
    
    // Create agent
    agent := core.NewLLMAgent("assistant", "gpt-4", core.LLMDeps{Provider: p})
    agent.SetSystemPrompt("You are a helpful assistant.")
    
    // Chat
    state := domain.NewState()
    state.Set("user_input", "Explain quantum computing in simple terms")
    result, _ := agent.Run(context.Background(), state)
    
    fmt.Println(result.Get("response"))
}
2. Agent with Tools
// Create smart agent with built-in tools
agent := core.NewLLMAgent("smart-assistant", "gpt-4", core.LLMDeps{Provider: p})

// Add powerful tools
agent.AddTool(web.NewWebSearchTool(webAPIKey))
agent.AddTool(file.NewFileReadTool())
agent.AddTool(calculator.NewCalculatorTool())

// Agent can now search web, read files, and calculate
state := domain.NewState()
state.Set("user_input", "Search for recent Go releases and calculate days since Go 1.21")
result, _ := agent.Run(context.Background(), state)
3. Structured Data Extraction
// Define what you want
schema := &schema.Schema{
    Type: "object",
    Properties: map[string]*schema.Schema{
        "name":     {Type: "string"},
        "sentiment": {Type: "string", Enum: []interface{}{"positive", "negative", "neutral"}},
        "confidence": {Type: "number"},
    },
    Required: []string{"name", "sentiment"},
}

// Get reliable structured output
agent.SetSchema(schema)
state.Set("user_input", "Analyze this review: 'Amazing product, works perfectly!'")
result, _ := agent.Run(context.Background(), state)

// Guaranteed to match your schema
data := result.Get("structured_output")
4. Multi-Agent Workflows
// Create specialized agents
extractor := core.NewLLMAgent("extractor", "gpt-4", core.LLMDeps{Provider: p})
analyzer := core.NewLLMAgent("analyzer", "claude-3-sonnet-20240229", core.LLMDeps{Provider: claude})

// Orchestrate with workflows
workflow := workflow.NewSequentialAgent("data-pipeline", []domain.BaseAgent{
    extractor,  // First: extract data from text
    analyzer,   // Second: analyze extracted data
})

// Process data through the pipeline
state.Set("document", "Large document content...")
result, _ := workflow.Run(context.Background(), state)

Learning Resources

πŸ“– Documentation
πŸš€ Learning Paths
πŸ’‘ Examples & Tutorials

Supported Providers

OpenAI β€’ Anthropic β€’ Google Gemini β€’ Google Vertex AI β€’ Ollama β€’ OpenRouter

Provider Best For Models Setup
OpenAI General use, reliability GPT-4o, GPT-4 Turbo, GPT-4o-mini Guide
Anthropic Analysis, reasoning Claude 3.5 Sonnet, Claude 3 Opus Guide
Google Gemini Multimodal, speed Gemini 2.0 Flash Lite, Gemini Pro Guide **
Vertex AI ** Enterprise, compliance Gemini + partner models Guide
Ollama Local hosting, privacy Llama, Mistral, CodeLlama Guide
OpenRouter Model variety, cost 400+ models (68 free) Guide

** Untested integration

See our provider comparison guide for detailed feature matrices.

What's New

v0.3.6 (Latest) - Production-Ready Documentation πŸ“š

Comprehensive documentation and quality assurance improvements:

  • Complete Godoc Coverage - Enhanced 300+ Go files with comprehensive documentation
  • Documentation Automation - Automated validation, link fixing, and content consistency
  • Structural Reorganization - 95+ documentation files with proper navigation and learning paths
  • Enhanced User Experience - Complete user guide with visual diagrams and task-oriented guides
  • API Consistency - Updated 750+ code examples to current v0.3.5+ standards
  • Technical Reference - Advanced tool patterns, integration guides, and architectural documentation
v0.3.5 - Complete Scripting Engine Support πŸš€

Comprehensive bridge integration for go-llmspell and other scripting engines:

  • Schema Repositories with versioning and persistence
  • Enhanced Error Handling with serializable errors and recovery strategies
  • Event System with serialization, filtering, and replay capabilities
  • Tool Discovery with metadata-first exploration (33+ built-in tools)
  • Workflow Serialization with templates and script-based execution
  • Testing Infrastructure with mocks, fixtures, and comprehensive scenarios

Full release history in CHANGELOG.md.

Architecture

Go-LLMs uses a clean, modular architecture designed for reliability and extensibility:

Architecture Overview

pkg/
β”œβ”€β”€ llm/         # Provider implementations and domain types
β”œβ”€β”€ agent/       # Intelligent agents, tools, workflows, events
β”œβ”€β”€ schema/      # JSON Schema validation and type conversion  
β”œβ”€β”€ structured/  # Output parsing with error recovery
β”œβ”€β”€ errors/      # Serializable error system with recovery
└── testutils/   # Comprehensive testing infrastructure

Design Principles:

  • Unified Interfaces - Same API across all providers and components
  • Fail-Safe Defaults - Graceful degradation and automatic error recovery
  • Type Safety - Strong typing with schema validation throughout
  • Performance First - Concurrent execution, streaming, and efficient state management
  • Bridge Friendly - JSON-serializable types for scripting engine integration

Get Started

# Install
go get github.com/lexlapax/go-llms

# Try the quickstart
export OPENAI_API_KEY="your-key-here"
go run docs/user-guide/getting-started/quickstart.go

Choose your path:

Community & Support

Status

βœ… Actively Maintained - Regular updates and improvements
βœ… Comprehensive Testing - 280+ tests with >85% coverage
βœ… Complete Documentation - User guides, API docs, examples
βœ… Bridge Compatible - Ready for scripting engine integration

License: MIT - see LICENSE for details

Directories ΒΆ

Path Synopsis
cmd
examples/errors-serialization command
Package main demonstrates enhanced error handling features
Package main demonstrates enhanced error handling features
examples/schema-generator command
Example demonstrating schema generation
Example demonstrating schema generation
examples/schema-repository command
Example demonstrating schema repository usage
Example demonstrating schema repository usage
examples/simple command
internal
toolgen command
pkg
agent/builtins
ABOUTME: Built-in tools and agents providing out-of-the-box functionality.
ABOUTME: Built-in tools and agents providing out-of-the-box functionality.
agent/builtins/agents
ABOUTME: Pre-configured agents for common tasks and use cases.
ABOUTME: Pre-configured agents for common tasks and use cases.
agent/builtins/tools/data
ABOUTME: Data processing tools for JSON, XML, CSV, and general transformations.
ABOUTME: Data processing tools for JSON, XML, CSV, and general transformations.
agent/builtins/tools/datetime
ABOUTME: Date and time manipulation tools for parsing, formatting, and calculations.
ABOUTME: Date and time manipulation tools for parsing, formatting, and calculations.
agent/builtins/tools/feed
ABOUTME: RSS/Atom feed processing tools for fetching, parsing, and filtering.
ABOUTME: RSS/Atom feed processing tools for fetching, parsing, and filtering.
agent/builtins/tools/file
ABOUTME: File system operations including read, write, search, and management.
ABOUTME: File system operations including read, write, search, and management.
agent/builtins/tools/math
ABOUTME: Mathematical computation tool supporting expressions and functions.
ABOUTME: Mathematical computation tool supporting expressions and functions.
agent/builtins/tools/system
ABOUTME: System interaction tools for environment, process, and command execution.
ABOUTME: System interaction tools for environment, process, and command execution.
agent/builtins/tools/web
ABOUTME: Web interaction tools for HTTP requests, scraping, and API clients.
ABOUTME: Web interaction tools for HTTP requests, scraping, and API clients.
agent/core
ABOUTME: Core agent implementation providing base functionality for LLM agents.
ABOUTME: Core agent implementation providing base functionality for LLM agents.
agent/domain
Package domain defines the core domain models and interfaces for agents.
Package domain defines the core domain models and interfaces for agents.
agent/events
ABOUTME: Event system for agents with bus, storage, filtering, and serialization.
ABOUTME: Event system for agents with bus, storage, filtering, and serialization.
agent/tools
Package tools provides implementations of agent tools.
Package tools provides implementations of agent tools.
agent/utils
ABOUTME: Utility functions for agent state manipulation and event handling.
ABOUTME: Utility functions for agent state manipulation and event handling.
agent/workflow
ABOUTME: Workflow orchestration patterns for complex agent task execution.
ABOUTME: Workflow orchestration patterns for complex agent task execution.
docs
ABOUTME: Documentation generation for tools and APIs in multiple formats.
ABOUTME: Documentation generation for tools and APIs in multiple formats.
errors
ABOUTME: Enhanced error handling with serialization and recovery strategies.
ABOUTME: Enhanced error handling with serialization and recovery strategies.
internal/debug
ABOUTME: Internal debugging utilities for development and troubleshooting.
ABOUTME: Internal debugging utilities for development and troubleshooting.
llm/domain
Package domain defines the core types and interfaces for LLM interactions.
Package domain defines the core types and interfaces for LLM interactions.
llm/outputs
ABOUTME: Output parsing and validation for LLM responses in various formats.
ABOUTME: Output parsing and validation for LLM responses in various formats.
llm/provider
Package provider implements LLM provider integrations for OpenAI, Anthropic, Google, and others.
Package provider implements LLM provider integrations for OpenAI, Anthropic, Google, and others.
schema/adapter/reflection
ABOUTME: Reflection-based schema generation from Go types and structs.
ABOUTME: Reflection-based schema generation from Go types and structs.
schema/domain
Package domain defines types and interfaces for JSON schema validation and generation.
Package domain defines types and interfaces for JSON schema validation and generation.
schema/generator
ABOUTME: Schema generation utilities for creating JSON schemas programmatically.
ABOUTME: Schema generation utilities for creating JSON schemas programmatically.
schema/repository
ABOUTME: Schema storage and retrieval with file-based and memory repositories.
ABOUTME: Schema storage and retrieval with file-based and memory repositories.
schema/validation
ABOUTME: JSON schema validation with type coercion and custom validators.
ABOUTME: JSON schema validation with type coercion and custom validators.
structured/domain
Package domain defines core types and interfaces for structured LLM outputs.
Package domain defines core types and interfaces for structured LLM outputs.
structured/processor
ABOUTME: Structured output processing for LLMs with prompt enhancement.
ABOUTME: Structured output processing for LLMs with prompt enhancement.
testutils
Package testutils provides a comprehensive testing infrastructure for the go-llms project.
Package testutils provides a comprehensive testing infrastructure for the go-llms project.
testutils/fixtures
Package fixtures provides test data and utilities for testing LLM integrations.
Package fixtures provides test data and utilities for testing LLM integrations.
testutils/helpers
ABOUTME: Test helper utilities for common testing patterns and operations.
ABOUTME: Test helper utilities for common testing patterns and operations.
testutils/mocks
ABOUTME: Mock implementations for testing LLM providers, agents, and tools.
ABOUTME: Mock implementations for testing LLM providers, agents, and tools.
testutils/scenario
ABOUTME: Scenario-based testing framework for complex interaction patterns.
ABOUTME: Scenario-based testing framework for complex interaction patterns.
util/auth
ABOUTME: Authentication utilities for API access with multiple auth methods.
ABOUTME: Authentication utilities for API access with multiple auth methods.
util/json
ABOUTME: JSON manipulation utilities with schema support and streaming.
ABOUTME: JSON manipulation utilities with schema support and streaming.
util/llmutil
ABOUTME: LLM-specific utilities for provider management and configuration.
ABOUTME: LLM-specific utilities for provider management and configuration.
util/llmutil/modelinfo
ABOUTME: Model information package providing LLM inventory and capability discovery.
ABOUTME: Model information package providing LLM inventory and capability discovery.
util/llmutil/modelinfo/cache
ABOUTME: File-based caching for model inventory with save, load, and validation utilities.
ABOUTME: File-based caching for model inventory with save, load, and validation utilities.
util/llmutil/modelinfo/domain
ABOUTME: Core domain types for model inventory including capabilities and pricing.
ABOUTME: Core domain types for model inventory including capabilities and pricing.
util/llmutil/modelinfo/fetchers
ABOUTME: Provider-specific fetchers for retrieving model information from LLM APIs.
ABOUTME: Provider-specific fetchers for retrieving model information from LLM APIs.
util/llmutil/modelinfo/service
ABOUTME: Service layer for aggregating model information from multiple providers.
ABOUTME: Service layer for aggregating model information from multiple providers.
util/metrics
ABOUTME: Metrics collection and reporting for monitoring system performance.
ABOUTME: Metrics collection and reporting for monitoring system performance.
util/profiling
ABOUTME: Performance profiling utilities for CPU, memory, and trace analysis.
ABOUTME: Performance profiling utilities for CPU, memory, and trace analysis.
util/types
ABOUTME: Type conversion and registration system for dynamic type handling.
ABOUTME: Type conversion and registration system for dynamic type handling.
tests

Jump to

Keyboard shortcuts

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