Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

gollm

> AI 编程
Open source

Unified Go interface for Language Model (LLM) providers. Simplifies LLM integration with flexible prompt management and common task functions.

671 stars0 likes0 views
WebsiteGitHub

About

Unified Go interface for Language Model (LLM) providers. Simplifies LLM integration with flexible prompt management and common task functions.

gollm - Go Large Language Model

gollm is a Go package designed to help you build your own AI golems. Just as the mystical golem of legend was brought to life with sacred words, gollm empowers you to breathe life into your AI creations using the power of Large Language Models (LLMs). This package simplifies and streamlines interactions with various LLM providers, offering a unified, flexible, and powerful interface for AI engineers and developers to craft their own digital servants.

Documentation

Table of Contents

  • Key Features
  • Real-World Applications
  • Installation
  • Quick Start
    • Basic Usage
  • Quick Reference
    • LLM Creation and Configuration
    • Prompt Creation
    • Generate Response
    • Chain of Thought
    • Prompt Optimization
    • Model Comparison
  • Advanced Usage
    • Prompt Engineering
    • Pre-built Functions (Chain of Thought)
    • Working with Examples
    • Prompt Templates
    • Structured Output (JSON Output Validation)
    • Prompt Optimizer
    • Model Comparison
    • Memory Retention
    • Structured Messages and Caching
  • Best Practices
  • Examples and Tutorials
  • Project Status
  • Philosophy
  • Contributing
  • License

Key Features

  • Unified API for Multiple LLM Providers: Interact seamlessly with various providers, including OpenAI, Anthropic, Groq, Ollama, and OpenRouter. Easily switch between models like GPT-4, Claude, and Llama-3.1.
  • Easy Provider and Model Switching: Configure preferred providers and models with simple options.
  • Flexible Configuration Options: Customize using environment variables, code-based configuration, or configuration files.
  • Advanced Prompt Engineering: Craft sophisticated instructions to guide your AI's responses effectively.
  • Prompt Optimizer: Automatically refine and improve your prompts for better results, with support for custom metrics and different rating systems.
  • Memory Retention: Maintain context across multiple interactions for more coherent conversations.
  • Structured Output and Validation: Ensure outputs are consistent and reliable with JSON schema generation and validation.
  • Provider Comparison Tools: Test performance across different LLM providers and models for the same task.
  • High-Level AI Functions: Use pre-built functions like ChainOfThought for complex reasoning tasks.
  • Robust Error Handling and Retries: Built-in retry mechanisms to handle API rate limits and transient errors.
  • Extensible Architecture: Easily expand support for new LLM providers and features.

Supported Providers

gollm works with a variety of LLM providers:

  • OpenAI: GPT-4o, GPT-4, GPT-3.5 Turbo
  • Anthropic: Claude 3 (Opus, Sonnet, Haiku), Claude 2.1
  • Groq: Llama-3, Mixtral models with high-speed inference
  • Ollama: Local models support (Llama-3, Mistral, etc.)
  • Mistral: Mistral Large, Mistral Medium
  • OpenRouter: Access to multiple providers through a single API with:
    • Model fallback capabilities
    • Auto-routing between models
    • Prompt caching
    • Reasoning tokens
    • Provider routing preferences

Real-World Applications

gollm can handle a wide range of AI-powered tasks, including:

  • Content Creation Workflows: Generate research summaries, article ideas, and refined paragraphs.
  • Complex Reasoning Tasks: Use the ChainOfThought function to analyze complex problems step-by-step.
  • Structured Data Generation: Create and validate complex data structures with customizable JSON schemas.
  • Model Performance Analysis: Compare different models' performance for specific tasks.
  • Prompt Optimization: Automatically improve prompts for various tasks.
  • Mixture of Agents: Combine responses from multiple LLM providers.

Installation

bash
go get github.com/teilomillet/gollm

Quick Start

Basic Usage

…

Quick Reference

Here's a quick reference guide for the most commonly used functions and options in the gollm package:

LLM Creation and Configuration

…

Prompt Creation

go
prompt := gollm.NewPrompt("Your prompt text here",
    gollm.WithContext("Additional context"),
    gollm.WithDirectives("Be concise", "Use examples"),
    gollm.WithOutput("Expected output format"),
    gollm.WithMaxLength(300),
)

Generate Response

go
response, err := llm.Generate(ctx, prompt)

Chain of Thought

go
response, err := tools.ChainOfThought(ctx, llm, "Your question here")

Prompt Optimization

go
optimizer := optimizer.NewPromptOptimizer(llm, initialPrompt, taskDescription,
    optimizer.WithCustomMetrics(/* custom metrics */),
    optimizer.WithRatingSystem("numerical"),
    optimizer.WithThreshold(0.8),
)
optimizedPrompt, err := optimizer.OptimizePrompt(ctx)

Model Comparison

go
results, err := tools.CompareModels(ctx, promptText, validateFunc, configs...)

Advanced Usage

The gollm package offers a range of advanced features to enhance your AI applications:

Prompt Engineering

Create sophisticated prompts to guide the AI's responses:

go
prompt := gollm.NewPrompt(
    "Explain the concept of recursion in programming",
    gollm.WithDirectives(
        "Be concise and clear", 
        "Include code examples in multiple languages",
        "Provide a practical example.",
    ),
    gollm.WithContext("This is for a beginner programmer who is just starting to learn."),
    gollm.WithOutput("Structure your response with sections: Definition, Example, Pitfalls, Best Practices."),
    gollm.WithMaxLength(1000),
)

Provider-Specific Features

OpenRouter Special Features

OpenRouter provides access to multiple LLM providers with additional capabilities:

…

Pre-built Functions (Chain of Thought)

Use the ChainOfThought function for step-by-step reasoning:

go
question := "What is the result of 15 * 7 + 22?"
response, err := tools.ChainOfThought(ctx, llm, question)
if err != nil {
    log.Fatalf("Failed to perform chain of thought: %v", err)
}
fmt.Printf("Chain of Thought:\n%s\n", response)

Working with Examples

Load examples directly from files:

go
examples, err := utils.ReadExamplesFromFile("examples.txt")
if err != nil {
    log.Fatalf("Failed to read examples: %v", err)
}

prompt := gollm.NewPrompt("Generate a similar example:",
    gollm.WithExamples(examples...),
)

response, err := llm.Generate(ctx, prompt)
if err != nil {
    log.Fatalf("Failed to generate example: %v", err)
}
fmt.Printf("Generated Example:\n%s\n", response)

Prompt Templates

Create reusable prompt templates for consistent prompt generation:

…

Structured Output (JSON Output Validation)

Ensure your LLM outputs are in a valid JSON format:

go
prompt := gollm.NewPrompt("Analyze the pros and cons of remote work.",
    gollm.WithOutput("Respond in JSON format with 'topic', 'pros', 'cons', and 'conclusion' fields."),
)

response, err := llm.Generate(ctx, prompt, gollm.WithJSONSchemaValidation())
if err != nil {
    log.Fatalf("Failed to generate valid analysis: %v", err)
}

var result AnalysisResult
if err := json.Unmarshal([]byte(response), &result); err != nil {
    log.Fatalf("Failed to parse response: %v", err)
}

fmt.Printf("Analysis: %+v\n", result)

Prompt Optimizer

Use the PromptOptimizer to automatically refine and improve your prompts:

…

Model Comparison

Compare responses from different LLM providers or models:

…

Memory Retention

Enable memory to maintain context across multiple interactions:

…

Structured Messages and Caching

When using memory with LLMs, gollm preserves each message as a separate structured object (enabled by default). This approach:

  • Maintains conversation structure for better LLM understanding
  • Enables API-level caching (especially with Anthropic's prompt caching)
  • Reduces token costs by allowing providers to cache repeated context

Basic Usage (Automatic)

Structured messages are enabled by default when you use SetMemory():

go
llm, err := gollm.NewLLM(
    gollm.SetProvider("anthropic"),
    gollm.SetModel("claude-3-5-sonnet-20241022"),
    gollm.SetAPIKey(os.Getenv("ANTHROPIC_API_KEY")),
    gollm.SetMemory(4096), // Structured messages enabled by default
)

Cache Control with Anthropic

For fine-grained control over caching, you can add messages with explicit cache control:

go
// Add a message with cache control
// "ephemeral" caching is recommended for most use cases
llm.AddStructuredMessage("user", "Here is a long document to analyze...", "ephemeral")

// Generate - subsequent requests with the same context will use cached tokens
response, err := llm.Generate(ctx, gollm.NewPrompt("Summarize the key points"))

Managing Memory

go
// Check if memory is enabled
if llm.HasMemory() {
    // Get current conversation history
    messages := llm.GetMemory()

    // Add a message manually
    llm.AddToMemory("user", "Remember this context")

    // Clear conversation history
    llm.ClearMemory()
}

Switching Between Modes

You can toggle between structured and flattened message modes:

go
// Use structured messages (default, recommended for caching)
llm.SetUseStructuredMessages(true)

// Or use flattened prompt (legacy mode, combines all messages into one)
llm.SetUseStructuredMessages(false)

See the examples/caching_structured/ directory for a complete working example.

Best Practices

  1. Prompt Engineering:

    • Use NewPrompt() with options like WithContext(), WithDirectives(), and WithOutput() to create well-structured prompts.
    • Example:
      go
      prompt := gollm.NewPrompt("Your main prompt here",
          gollm.WithContext("Provide relevant context"),
          gollm.WithDirectives("Be concise", "Use examples"),
          gollm.WithOutput("Specify expected output format"),
      )
  2. Utilize Prompt Templates:

    • For consistent prompt generation, create and use `

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Goaianthropicdspygenai

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.