runtime

package module
v0.6.6 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2025 License: Apache-2.0 Imports: 15 Imported by: 2

README

ChatGPT Image 25 paź 2025 o 16_36_32

Go Version CI Status Go Reference Go Report Card

Lattice helps you build AI agents in Go with clean abstractions for LLMs, tool calling, retrieval-augmented memory, and multi-agent coordination. Focus on your domain logic while Lattice handles the orchestration plumbing.

Why Lattice?

Building production AI agents requires more than just LLM calls. You need:

  • Pluggable LLM providers that swap without rewriting logic
  • Tool calling that works across different model APIs
  • Memory systems that remember context across conversations
  • Multi-agent coordination for complex workflows
  • Testing infrastructure that doesn't hit external APIs

Lattice provides all of this with idiomatic Go interfaces and minimal dependencies.

Features

  • 🧩 Modular Architecture – Compose agents from reusable modules with declarative configuration
  • 🤖 Multi-Agent Support – Coordinate specialist agents through a shared catalog and delegation system
  • 🔧 Rich Tooling – Implement the Tool interface once, use everywhere automatically
  • 🧠 Smart Memory – RAG-powered memory with importance scoring, MMR retrieval, and automatic pruning
  • 🔌 Model Agnostic – Adapters for Gemini, Anthropic, Ollama, or bring your own
  • 📡 UTCP Ready – First-class Universal Tool Calling Protocol support

Quick Start

Installation

git clone https://github.com/Protocol-Lattice/go-agent.git
cd lattice-agent
go mod download

Basic Usage

package main

import (
	"context"
	"flag"
	"log"

	"github.com/Protocol-Lattice/go-agent/src/adk"
	adkmodules "github.com/Protocol-Lattice/go-agent/src/adk/modules"
	"github.com/Protocol-Lattice/go-agent"
	"github.com/Protocol-Lattice/go-agent/src/subagents"

	"github.com/Protocol-Lattice/go-agent/src/memory"
	"github.com/Protocol-Lattice/go-agent/src/memory/engine"
	"github.com/Protocol-Lattice/go-agent/src/models"
	"github.com/Protocol-Lattice/go-agent/src/tools"
)

func main() {
	qdrantURL := flag.String("qdrant-url", "http://localhost:6333", "Qdrant base URL")
	qdrantCollection := flag.String("qdrant-collection", "adk_memories", "Qdrant collection name")
	flag.Parse()
	ctx := context.Background()

	// --- Shared runtime
	researcherModel, err := models.NewGeminiLLM(ctx, "gemini-2.5-pro", "Research summary:")
	if err != nil {
		log.Fatalf("create researcher model: %v", err)
	}
	memOpts := engine.DefaultOptions()

	adkAgent, err := adk.New(ctx,
		adk.WithDefaultSystemPrompt("You orchestrate a helpful assistant team."),
		adk.WithSubAgents(subagents.NewResearcher(researcherModel)),
		adk.WithModules(
			adkmodules.NewModelModule("gemini-model", func(_ context.Context) (models.Agent, error) {
				return models.NewGeminiLLM(ctx, "gemini-2.5-pro", "Swarm orchestration:")
			}),
			adkmodules.InQdrantMemory(100000, *qdrantURL, *qdrantCollection, memory.AutoEmbedder(), &memOpts),
			adkmodules.NewToolModule("essentials", adkmodules.StaticToolProvider([]agent.Tool{&tools.EchoTool{}}, nil)),
		),
	)
	if err != nil {
		log.Fatal(err)
	}

	agent, err := adkAgent.BuildAgent(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// Use the agent
	resp, err := agent.Generate(ctx, "SessionID", "What is pgvector")
	if err != nil {
		log.Fatal(err)
	}

	log.Println(resp)
}

Running Examples

# Interactive CLI demo
go run cmd/demo/main.go

# Multi-agent coordination
go run cmd/team/main.go

# Quick start example
go run cmd/quickstart/main.go

Project Structure

lattice-agent/
├── cmd/
│   ├── demo/          # Interactive CLI with tools, delegation, and memory
│   ├── quickstart/    # Minimal getting-started example
│   └── team/          # Multi-agent coordination demos
├── pkg/
│   ├── adk/           # Agent Development Kit and module system
│   ├── memory/        # Memory engine and vector store adapters
│   ├── models/        # LLM provider adapters (Gemini, Ollama, Anthropic)
│   ├── subagents/     # Pre-built specialist agent personas
├── └── tools/         # Built-in tools (echo, calculator, time, etc.)

Configuration

Environment Variables

Variable Description Required
GOOGLE_API_KEY Gemini API credentials For Gemini models
GEMINI_API_KEY Alternative to GOOGLE_API_KEY For Gemini models
DATABASE_URL PostgreSQL connection string For persistent memory
ADK_EMBED_PROVIDER Embedding provider override No (defaults to Gemini)

Example Configuration

export GOOGLE_API_KEY="your-api-key-here"
export DATABASE_URL="postgres://user:pass@localhost:5432/lattice?sslmode=disable"
export ADK_EMBED_PROVIDER="gemini"

Core Concepts

Memory Engine

Lattice includes a sophisticated memory system with retrieval-augmented generation (RAG):

store := memory.NewInMemoryStore() // or PostgreSQL/Qdrant
engine := memory.NewEngine(store, memory.Options{}).
    WithEmbedder(yourEmbedder)

sessionMemory := memory.NewSessionMemory(
    memory.NewMemoryBankWithStore(store), 
    8, // context window size
).WithEngine(engine)

Features:

  • Importance Scoring – Automatically weights memories by relevance
  • MMR Retrieval – Maximal Marginal Relevance for diverse results
  • Auto-Pruning – Removes stale or low-value memories
  • Multiple Backends – In-memory, PostgreSQL+pgvector,mongodb, neo4j or Qdrant

Tool System

Create custom tools by implementing a simple interface:

package tools

import (
        "context"
        "fmt"
        "strings"

        "github.com/Protocol-Lattice/go-agent"
)

// EchoTool repeats the provided input. Useful for testing tool wiring.
type EchoTool struct{}

func (e *EchoTool) Spec() agent.ToolSpec {
        return agent.ToolSpec{
                Name:        "echo",
                Description: "Echoes the provided text back to the caller.",
                InputSchema: map[string]any{
                        "type": "object",
                        "properties": map[string]any{
                                "input": map[string]any{
                                        "type":        "string",
                                        "description": "Text to echo back.",
                                },
                        },
                        "required": []any{"input"},
                },
        }
}

func (e *EchoTool) Invoke(_ context.Context, req agent.ToolRequest) (agent.ToolResponse, error) {
        raw := req.Arguments["input"]
        if raw == nil {
                return agent.ToolResponse{Content: ""}, nil
        }
        return agent.ToolResponse{Content: strings.TrimSpace(fmt.Sprint(raw))}, nil
}

Register tools with the module system and they're automatically available to all agents.

Multi-Agent Coordination

Use Shared Spaces to coordinate multiple agents with shared memory

Perfect for:

  • Team-based workflows where agents need shared context
  • Complex tasks requiring specialist coordination
  • Projects with explicit access control requirements

Development

Running Tests

# Run all tests
go test ./...

# Run with coverage
go test -cover ./...

# Run specific package tests
go test ./pkg/memory/...

Code Style

We follow standard Go conventions:

  • Use gofmt for formatting
  • Follow Effective Go guidelines
  • Add tests for new features
  • Update documentation when adding capabilities

Adding New Components

New LLM Provider:

  1. Implement the models.LLM interface in pkg/models/
  2. Add provider-specific configuration
  3. Update documentation and examples

New Tool:

  1. Implement agent.Tool interface in pkg/tools/
  2. Register with the tool module system
  3. Add tests and usage examples

New Memory Backend:

  1. Implement memory.VectorStore interface
  2. Add migration scripts if needed
  3. Update configuration documentation

Prerequisites

  • Go 1.22+ (1.25 recommended)
  • PostgreSQL 15+ with pgvector extension (optional, for persistent memory)
  • API Keys for your chosen LLM provider

PostgreSQL Setup (Optional)

For persistent memory with vector search:

CREATE EXTENSION IF NOT EXISTS vector;

The memory module handles schema migrations automatically.

Troubleshooting

Common Issues

Missing pgvector extension

ERROR: type "vector" does not exist

Solution: Run CREATE EXTENSION vector; in your PostgreSQL database.

API key errors

ERROR: authentication failed

Solution: Verify your API key is correctly set in the environment where you run the application.

Tool not found

ERROR: tool "xyz" not registered

Solution: Ensure tool names are unique and properly registered in your tool catalog.

Getting Help

Contributing

We welcome contributions! Here's how to get started:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes with tests
  4. Update documentation
  5. Submit a pull request

Please ensure:

  • Tests pass (go test ./...)
  • Code is formatted (gofmt)
  • Documentation is updated
  • Commit messages are clear

License

This project is licensed under the Apache 2.0 License.

Acknowledgments


Star us on GitHub if you find Lattice useful! ⭐

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Agent

type Agent struct {
	UTCPClient utcp.UtcpClientInterface

	Shared *memory.SharedSession
	// contains filtered or unexported fields
}

Agent orchestrates model calls, memory, tools, and sub-agents.

func New

func New(opts Options) (*Agent, error)

New creates an Agent with the provided options.

func (*Agent) EnsureSpaceGrants

func (a *Agent) EnsureSpaceGrants(sessionID string, spaces []string)

EnsureSpaceGrants gives the provided sessionID writer access to each space. This mirrors how tests set up spaces: mem.Spaces.Grant(space, session, role, ttl).

func (*Agent) Flush

func (a *Agent) Flush(ctx context.Context, sessionID string) error

Flush persists session memory into the long-term store.

func (*Agent) Generate

func (a *Agent) Generate(ctx context.Context, sessionID, userInput string) (string, error)

Generate processes a user message, optionally invoking tools or sub-agents.

func (*Agent) GenerateWithFiles

func (a *Agent) GenerateWithFiles(
	ctx context.Context,
	sessionID string,
	userInput string,
	files []models.File,
) (string, error)

GenerateWithFiles sends the user message plus in-memory files to the model without ingesting them into long-term memory. Use this when you already have file bytes (e.g., uploaded via API) and want the model to consider them ephemerally for this turn only.

func (*Agent) RetrieveAttachmentFiles

func (a *Agent) RetrieveAttachmentFiles(ctx context.Context, sessionID string, limit int) ([]models.File, error)

RetrieveAttachmentFiles returns attachment files stored for the session. It reconstructs the original bytes from base64-encoded metadata, making it suitable for binary assets such as images and videos.

func (*Agent) Save

func (agent *Agent) Save(ctx context.Context, role, content string)

Save stores a conversation turn into all shared spaces. role should be "user" or "agent".

func (*Agent) SessionMemory

func (a *Agent) SessionMemory() *memory.SessionMemory

SessionMemory exposes the underlying session memory (useful for advanced setup/tests).

func (*Agent) SetSharedSpaces

func (a *Agent) SetSharedSpaces(shared *memory.SharedSession)

func (*Agent) SubAgents

func (a *Agent) SubAgents() []SubAgent

SubAgents returns all registered sub-agents in deterministic order.

func (*Agent) ToolSpecs

func (a *Agent) ToolSpecs() []ToolSpec

ToolSpecs returns the registered tool specifications in deterministic order.

func (*Agent) Tools

func (a *Agent) Tools() []Tool

Tools returns the registered tools in deterministic order.

type Options

type Options struct {
	Model             models.Agent
	Memory            *memory.SessionMemory
	SystemPrompt      string
	ContextLimit      int
	Tools             []Tool
	SubAgents         []SubAgent
	ToolCatalog       ToolCatalog
	SubAgentDirectory SubAgentDirectory
	UTCPClient        utcp.UtcpClientInterface

	Shared *memory.SharedSession
}

Options configure a new Agent.

type QueryType

type QueryType int
const (
	QueryComplex QueryType = iota
	QueryShortFactoid
	QueryMath
)

type StaticSubAgentDirectory

type StaticSubAgentDirectory struct {
	// contains filtered or unexported fields
}

StaticSubAgentDirectory is the default SubAgentDirectory implementation.

func NewStaticSubAgentDirectory

func NewStaticSubAgentDirectory(subagents []SubAgent) *StaticSubAgentDirectory

NewStaticSubAgentDirectory constructs a directory from the provided sub-agents.

func (*StaticSubAgentDirectory) All

func (d *StaticSubAgentDirectory) All() []SubAgent

All returns the registered sub-agents in registration order.

func (*StaticSubAgentDirectory) Lookup

func (d *StaticSubAgentDirectory) Lookup(name string) (SubAgent, bool)

Lookup retrieves a sub-agent by name.

func (*StaticSubAgentDirectory) Register

func (d *StaticSubAgentDirectory) Register(subAgent SubAgent) error

Register adds a sub-agent to the directory. Duplicate names return an error.

type StaticToolCatalog

type StaticToolCatalog struct {
	// contains filtered or unexported fields
}

StaticToolCatalog is the default in-memory implementation of ToolCatalog used by the runtime.

func NewStaticToolCatalog

func NewStaticToolCatalog(tools []Tool) *StaticToolCatalog

NewStaticToolCatalog constructs a catalog seeded with the provided tools.

func (*StaticToolCatalog) Lookup

func (c *StaticToolCatalog) Lookup(name string) (Tool, ToolSpec, bool)

Lookup returns the tool and its specification if present.

func (*StaticToolCatalog) Register

func (c *StaticToolCatalog) Register(tool Tool) error

Register adds a tool to the catalog using a lower-cased key. Duplicate names return an error.

func (*StaticToolCatalog) Specs

func (c *StaticToolCatalog) Specs() []ToolSpec

Specs returns a snapshot of the tool specifications in registration order.

func (*StaticToolCatalog) Tools

func (c *StaticToolCatalog) Tools() []Tool

Tools returns the registered tools in order.

type SubAgent

type SubAgent interface {
	Name() string
	Description() string
	Run(ctx context.Context, input string) (string, error)
}

SubAgent represents a specialist agent that can be delegated work.

type SubAgentDirectory

type SubAgentDirectory interface {
	Register(subAgent SubAgent) error
	Lookup(name string) (SubAgent, bool)
	All() []SubAgent
}

SubAgentDirectory stores sub-agents by name while preserving insertion order.

type Tool

type Tool interface {
	Spec() ToolSpec
	Invoke(ctx context.Context, req ToolRequest) (ToolResponse, error)
}

Tool exposes structured metadata and an invocation handler.

type ToolCatalog

type ToolCatalog interface {
	Register(tool Tool) error
	Lookup(name string) (Tool, ToolSpec, bool)
	Specs() []ToolSpec
	Tools() []Tool
}

ToolCatalog maintains an ordered set of tools and provides lookup by name.

type ToolRequest

type ToolRequest struct {
	SessionID string
	Arguments map[string]any
}

ToolRequest captures an invocation request for a tool.

type ToolResponse

type ToolResponse struct {
	Content  string
	Metadata map[string]string
}

ToolResponse represents the structured response returned by a tool.

type ToolSpec

type ToolSpec struct {
	Name        string           `json:"name"`
	Description string           `json:"description"`
	InputSchema map[string]any   `json:"input_schema"`
	Examples    []map[string]any `json:"examples,omitempty"`
}

ToolSpec describes how the agent should present a tool to the model.

Directories

Path Synopsis
cmd
app command
main.go — fixed agent-mode with provider flag Runs your Agent with optional file context using GenerateWithFiles.
main.go — fixed agent-mode with provider flag Runs your Agent with optional file context using GenerateWithFiles.
example command
main.go — fixed agent-mode with provider flag, Postgres memory + CreateSchema Runs your Agent with optional file context using GenerateWithFiles.
main.go — fixed agent-mode with provider flag, Postgres memory + CreateSchema Runs your Agent with optional file context using GenerateWithFiles.
quickstart command
main.go — guided swarm quickstart wiring ADK agents into the CLI.
main.go — guided swarm quickstart wiring ADK agents into the CLI.
team command
main.go — multi-agent swarm orchestrator with shared memory spaces.
main.go — multi-agent swarm orchestrator with shared memory spaces.
src
adk

Jump to

Keyboard shortcuts

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