agent

package module
v1.12.9 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2026 License: Apache-2.0 Imports: 24 Imported by: 2

README

go-agent

Go Version CI Status Go Reference Go Report Card

go-agent is a Go framework for building AI agents with pluggable LLM providers, memory, file context, guardrails, UTCP tool orchestration, and multi-agent coordination.

Use it when you want agent runtime pieces that stay idiomatic in Go:

  • A small agent.Agent core with Generate, GenerateWithFiles, and GenerateStream
  • Provider adapters for Gemini, OpenAI, Anthropic, Ollama, and a local dummy model
  • Short-term memory plus vector-store backed long-term memory
  • ADK modules for wiring models, memory, tools, sub-agents, CodeMode, and UTCP
  • Agent-as-tool patterns for specialist agents and hierarchical workflows
  • Input/output guardrails and checkpoint/restore support

Install

go get github.com/Protocol-Lattice/go-agent

For this repository:

git clone https://github.com/Protocol-Lattice/go-agent.git
cd go-agent
go test ./...

The module currently targets Go 1.25.0.

Quick Start

This example runs without API keys. It uses the dummy model and in-memory storage, so it is safe for tests and local wiring checks.

package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	ctx := context.Background()

	mem := memory.NewSessionMemory(
		memory.NewMemoryBankWithStore(memory.NewInMemoryStore()),
		8,
	)

	a, err := agent.New(agent.Options{
		Model:        models.NewDummyLLM("local:"),
		Memory:       mem,
		SystemPrompt: "You are concise and helpful.",
	})
	if err != nil {
		log.Fatal(err)
	}

	out, err := a.Generate(ctx, "demo-session", "Say hello in one sentence.")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(out)
}

Real Model Providers

Use models.NewLLMProvider when you want provider selection from configuration or flags.

model, err := models.NewLLMProvider(ctx, "openai", "gpt-4o-mini", "")
if err != nil {
	log.Fatal(err)
}

Supported provider names:

Provider Aliases Required environment
Gemini gemini, google GOOGLE_API_KEY or GEMINI_API_KEY
OpenAI openai OPENAI_API_KEY or OPENAI_KEY
Anthropic anthropic, claude ANTHROPIC_API_KEY
Ollama ollama optional OLLAMA_HOST, defaults to http://localhost:11434

Embeddings are selected with memory.AutoEmbedder().

Variable Purpose
ADK_EMBED_PROVIDER openai, google, gemini, ollama, claude, anthropic, or fastembed
ADK_EMBED_MODEL Provider-specific embedding model

If no embedding provider can be created, Lattice falls back to DummyEmbedder.

ADK Setup

For applications, prefer the ADK when you want dependency injection around model, memory, tools, and runtime features.

package main

import (
	"context"
	"log"

	"github.com/Protocol-Lattice/go-agent/src/adk"
	"github.com/Protocol-Lattice/go-agent/src/adk/modules"
	"github.com/Protocol-Lattice/go-agent/src/memory"
	"github.com/Protocol-Lattice/go-agent/src/models"
)

func main() {
	ctx := context.Background()
	memOpts := memory.DefaultOptions()

	kit, err := adk.New(ctx,
		adk.WithDefaultSystemPrompt("You coordinate a helpful assistant."),
		adk.WithModules(
			modules.NewModelModule("llm", func(ctx context.Context) (models.Agent, error) {
				return models.NewLLMProvider(ctx, "openai", "gpt-4o-mini", "")
			}),
			modules.InMemoryMemoryModule(8, memory.AutoEmbedder(), &memOpts),
		),
	)
	if err != nil {
		log.Fatal(err)
	}

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

	_, _ = a.Generate(ctx, "user-123", "Draft a short project update.")
}

Use direct agent.New for small programs and tests. Use adk.New once you need reusable modules, shared sessions, provider selection, or UTCP runtime wiring.

Memory

Every agent needs a *memory.SessionMemory. The session layer keeps recent conversation turns and can retrieve long-term records from a vector store.

Common backends:

Backend Constructor or module
In-memory memory.NewInMemoryStore() or modules.InMemoryMemoryModule(...)
PostgreSQL + pgvector memory.NewPostgresStore(...) or modules.InPostgresMemory(...)
Qdrant memory.NewQdrantStore(...) or modules.InQdrantMemory(...)
MongoDB memory.NewMongoStore(...) or modules.InMongoMemory(...)
Neo4j memory.NewNeo4jStore(...) or modules.InNeo4jMemory(...)

Minimal in-memory setup:

mem := memory.NewSessionMemory(
	memory.NewMemoryBankWithStore(memory.NewInMemoryStore()),
	8,
)

Persistent stores that support schema setup implement memory.SchemaInitializer.

store, err := memory.NewPostgresStore(ctx, connStr)
if err != nil {
	log.Fatal(err)
}
defer store.Close()

if err := store.CreateSchema(ctx, ""); err != nil {
	log.Fatal(err)
}

File Context

Use GenerateWithFiles when you already have file bytes in memory. Text files are included in the prompt context; supported image/video MIME types are passed through provider-specific paths where available.

files := []models.File{
	{
		Name: "notes.md",
		MIME: "text/markdown",
		Data: []byte("# Notes\nShip the README update."),
	},
}

out, err := a.GenerateWithFiles(ctx, "demo-session", "Summarize this file.", files)

Tools

Tools are small Go interfaces with a JSON-schema-like spec and an invocation function.

type EchoTool struct{}

func (EchoTool) Spec() agent.ToolSpec {
	return agent.ToolSpec{
		Name:        "echo",
		Description: "Returns the input text.",
		InputSchema: map[string]any{
			"type": "object",
			"properties": map[string]any{
				"input": map[string]any{
					"type": "string",
				},
			},
			"required": []string{"input"},
		},
	}
}

func (EchoTool) Invoke(ctx context.Context, req agent.ToolRequest) (agent.ToolResponse, error) {
	return agent.ToolResponse{Content: fmt.Sprint(req.Arguments["input"])}, nil
}

Register tools directly when constructing an agent to keep them in the agent catalog and expose them through a.Tools() or ADK tool bundles:

a, err := agent.New(agent.Options{
	Model:  model,
	Memory: mem,
	Tools:  []agent.Tool{EchoTool{}},
})

For model-selected tool execution across providers and processes, wire execution through UTCP. Agents can also be exposed as UTCP tools.

Agents As Tools

Any *agent.Agent can be wrapped as a local agent.Tool.

researcher, _ := agent.New(agent.Options{
	Model:        researcherModel,
	Memory:       researcherMemory,
	SystemPrompt: "You are a research specialist.",
})

manager, _ := agent.New(agent.Options{
	Model:        managerModel,
	Memory:       managerMemory,
	SystemPrompt: "You delegate research work.",
	Tools: []agent.Tool{
		researcher.AsTool("researcher", "Delegates research to a specialist agent."),
	},
})

You can also register an agent as a UTCP provider:

client, err := utcp.NewUTCPClient(ctx, &utcp.UtcpClientConfig{}, nil, nil)
if err != nil {
	log.Fatal(err)
}

if err := researcher.RegisterAsUTCPProvider(
	ctx,
	client,
	"agent.researcher",
	"Specialist research agent",
); err != nil {
	log.Fatal(err)
}

result, err := client.CallTool(ctx, "agent.researcher", map[string]any{
	"instruction": "Find three facts about pgvector.",
})

Guardrails

Input guardrails validate or transform user input before the model call. Output guardrails validate or repair model responses before they are returned.

inputGuardrails := &agent.InputGuardrails{
	SafetyPolicies: []agent.InputSafetyPolicy{
		agent.NewPromptInjectionDetectorPolicy(nil),
	},
	Transformers: []agent.InputTransformer{
		agent.NewPIIMaskerTransformer(true, true, false, false),
	},
}

outputPolicy, err := agent.NewRegexBlocklistPolicy([]string{
	`(?i)\bpassword\s*=`,
})
if err != nil {
	log.Fatal(err)
}

a, err := agent.New(agent.Options{
	Model:           model,
	Memory:          mem,
	InputGuardrails: inputGuardrails,
	Guardrails: &agent.OutputGuardrails{
		SafetyPolicies: []agent.SafetyPolicy{outputPolicy},
	},
})

See cmd/example/guardrails for a complete runnable example.

Checkpoint And Restore

Checkpointing serializes the agent system prompt, short-term memory, shared-space memberships, and timestamp.

data, err := a.Checkpoint()
if err != nil {
	log.Fatal(err)
}

restored, err := agent.New(agent.Options{
	Model:  model,
	Memory: freshMemory,
})
if err != nil {
	log.Fatal(err)
}

if err := restored.Restore(data); err != nil {
	log.Fatal(err)
}

See cmd/example/checkpoint for a disk-backed example.

CodeMode

Lattice can integrate with UTCP CodeMode and chain execution:

  • adk.WithUTCP(client) makes remote/discovered UTCP tools available to the agent.
  • adk.WithCodeModeUtcp(client, model) enables Go-code tool orchestration through CodeMode.
  • Agent.AllowUnsafeTools must be enabled before codemode.run_code can execute.

Use these features only in trusted environments. CodeMode executes generated Go snippets through the configured UTCP runtime.

Examples

No-key examples:

go run ./cmd/example/composability
go run ./cmd/example/guardrails
go run ./cmd/example/checkpoint

Provider-backed examples:

# Requires GOOGLE_API_KEY or GEMINI_API_KEY by default.
go run ./cmd/example/codemode

# Requires provider credentials and a Qdrant instance unless flags are changed.
go run ./cmd/app -provider openai -model gpt-4o-mini -message "Summarize this project"

# Requires provider credentials and PostgreSQL + pgvector unless flags are changed.
go run ./cmd/example -provider openai -model gpt-4o-mini -message "Summarize this project"

Specialized workflows:

Path Demonstrates
cmd/example/agent_as_tool Registering an agent as a UTCP tool
cmd/example/agent_as_utcp_codemode Orchestrating agent tools through CodeMode
cmd/example/codemode_utcp_workflow Analyst/writer/reviewer workflow
cmd/example/autonomous_agent Configurable multi-agent coordinator
cmd/example/autonomous_cron Autonomous periodic task pattern
cmd/example/claw_cron Task store, permission gateway, and specialist agents
cmd/codemode CodeMode CLI wiring

Repository Layout

.
|-- agent.go                 # Core Agent runtime
|-- agent_stream.go          # Streaming responses
|-- agent_tool.go            # Agent-as-tool and UTCP provider adapters
|-- input_guardrails.go      # Input validation and transforms
|-- safety_policies.go       # Output safety policies
|-- catalog.go               # Tool and sub-agent registries
|-- src/
|   |-- adk/                 # Agent Development Kit and modules
|   |-- cache/               # LRU cache utilities
|   |-- concurrent/          # Worker pool helpers
|   |-- helpers/             # Small CLI/config helpers
|   |-- memory/              # Session memory, engine, stores, embedders
|   |-- models/              # LLM provider adapters
|   |-- subagents/           # Built-in specialist agents
|   `-- swarm/               # Multi-agent coordination primitives
`-- cmd/
    |-- app/                 # Qdrant-backed CLI
    |-- codemode/            # CodeMode CLI
    `-- example/             # Runnable examples

Development

# Run all tests.
go test ./...

# Run one package.
go test ./src/memory/engine

# Run one test.
go test ./... -run TestCheckpoint

# Format changed Go files.
gofmt -w path/to/file.go

FastEmbed support is behind the fastembed build tag:

go test -tags fastembed ./src/memory/embed

Adding Components

Add a model provider by implementing src/models.Agent:

type Agent interface {
	Generate(context.Context, string) (any, error)
	GenerateWithFiles(context.Context, string, []File) (any, error)
	GenerateStream(context.Context, string) (<-chan StreamChunk, error)
}

Add a memory backend by implementing memory.VectorStore. Add memory.SchemaInitializer if the backend needs schema/bootstrap support.

Add a tool by implementing agent.Tool, then register it through agent.Options, an ADK tool provider, or a UTCP provider depending on how it should be discovered and executed.

Troubleshooting

Missing API Key

Provider constructors fail when required keys are missing. Set the matching environment variable or use models.NewDummyLLM for local tests.

No Long-Term Memory Results

Check that the session uses a store-backed MemoryBank, an embedder is configured, and records have been flushed or stored through the memory engine.

PostgreSQL Vector Errors

For pgvector-backed memory, enable the extension:

CREATE EXTENSION IF NOT EXISTS vector;

Then run the store schema initializer:

_ = store.CreateSchema(ctx, "")
Tool Not Found

Confirm the tool name exactly matches the registered UTCP tool name. Fully qualified names such as agent.researcher are preferred when multiple providers expose similar tools.

License

See LICENSE.

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
	CodeMode *codemode.CodeModeUTCP

	AllowUnsafeTools bool
	Guardrails       *OutputGuardrails
	InputGuardrails  *InputGuardrails
	// 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) AsTool added in v1.0.9

func (a *Agent) AsTool(name, description string) Tool

AsTool returns a Tool representation of the Agent.

func (*Agent) AsUTCPTool added in v1.10.0

func (a *Agent) AsUTCPTool(name, description string) tools.Tool

AsUTCPTool exposes the agent as a UTCP tool with an in-process handler. The tool accepts: - instruction (required): user query for the agent - session_id (optional): custom session id; defaults to a namespaced value derived from the tool name

func (*Agent) Checkpoint added in v1.10.3

func (a *Agent) Checkpoint() ([]byte, error)

Checkpoint serializes the agent's current state (system prompt and short-term memory) to a byte slice. This can be saved to disk or a database to pause the agent.

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) (any, error)

func (*Agent) GenerateStream added in v1.10.6

func (a *Agent) GenerateStream(ctx context.Context, sessionID, userInput string) (<-chan models.StreamChunk, error)

GenerateStream provides a streaming interface for the agent's generation process. It follows the same logic as Generate but returns a channel of chunks.

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. GenerateWithFiles runs the full orchestration pipeline (direct tool → subagent → CodeMode → UTCP tool loop) before falling back to a file-aware model call. Files are forwarded to the planner so tools can be selected with attachment context, but tool execution still uses the normal UTCP arguments.

func (*Agent) RegisterAsUTCPProvider added in v1.10.0

func (a *Agent) RegisterAsUTCPProvider(ctx context.Context, client utcp.UtcpClientInterface, name, description string) error

RegisterAsUTCPProvider registers the agent as a UTCP tool on the provided client. It installs a lightweight in-process transport under the "text" provider type to route CallTool invocations directly to the agent's Generate method.

func (*Agent) Restore added in v1.10.3

func (a *Agent) Restore(data []byte) error

Restore rehydrates the agent's state from a checkpoint. It restores the system prompt and short-term memory.

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() []tools.Tool

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 AgentState added in v1.10.3

type AgentState struct {
	SystemPrompt string                          `json:"system_prompt"`
	ShortTerm    map[string][]model.MemoryRecord `json:"short_term"`
	JoinedSpaces []string                        `json:"joined_spaces,omitempty"`
	Timestamp    time.Time                       `json:"timestamp"`
}

AgentState represents the serializable state of an agent for checkpointing.

type AgentToolAdapter added in v1.0.9

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

AgentToolAdapter adapts an Agent to the Tool interface.

func (*AgentToolAdapter) Invoke added in v1.0.9

func (*AgentToolAdapter) Spec added in v1.0.9

func (t *AgentToolAdapter) Spec() ToolSpec

type FormatEnforcer added in v1.11.0

type FormatEnforcer interface {
	Enforce(ctx context.Context, response string) (string, error)
}

FormatEnforcer defines an interface for validating or repairing the format of LLM responses.

type InputGuardrails added in v1.11.4

type InputGuardrails struct {
	SafetyPolicies []InputSafetyPolicy
	Transformers   []InputTransformer
}

InputGuardrails holds the input safety policies and transformers.

func (*InputGuardrails) ValidateAndTransform added in v1.11.4

func (g *InputGuardrails) ValidateAndTransform(ctx context.Context, input string) (string, error)

ValidateAndTransform applies safety checks and transformers to the input.

type InputSafetyPolicy added in v1.11.4

type InputSafetyPolicy interface {
	Validate(ctx context.Context, input string) error
}

InputSafetyPolicy defines an interface for validating LLM inputs.

type InputTransformer added in v1.11.4

type InputTransformer interface {
	Transform(ctx context.Context, input string) (string, error)
}

InputTransformer defines an interface for modifying or sanitizing LLM inputs.

type LLMEvaluatorInputPolicy added in v1.11.4

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

LLMEvaluatorInputPolicy uses a secondary language model to evaluate the safety of the proposed input query.

func NewLLMEvaluatorInputPolicy added in v1.11.4

func NewLLMEvaluatorInputPolicy(model models.Agent, promptTemplate string) *LLMEvaluatorInputPolicy

NewLLMEvaluatorInputPolicy creates a new input safety policy that uses an LLM to evaluate inputs. If promptTemplate is empty, a default evaluation prompt is used.

func (*LLMEvaluatorInputPolicy) Validate added in v1.11.4

func (p *LLMEvaluatorInputPolicy) Validate(ctx context.Context, input string) error

Validate sends the input to the evaluating LLM and checks its verdict.

type LLMEvaluatorPolicy added in v1.11.1

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

LLMEvaluatorPolicy uses a secondary language model to evaluate the safety of the proposed response.

func NewLLMEvaluatorPolicy added in v1.11.1

func NewLLMEvaluatorPolicy(model models.Agent, promptTemplate string) *LLMEvaluatorPolicy

NewLLMEvaluatorPolicy creates a new safety policy that uses an LLM to evaluate responses. If promptTemplate is empty, a default evaluation prompt is used.

func (*LLMEvaluatorPolicy) Validate added in v1.11.1

func (p *LLMEvaluatorPolicy) Validate(ctx context.Context, response string) error

Validate sends the response to the evaluating LLM and checks its verdict.

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
	CodeMode          *codemode.CodeModeUTCP
	Shared            *memory.SharedSession
	AllowUnsafeTools  bool
	Guardrails        *OutputGuardrails
	InputGuardrails   *InputGuardrails
}

Options configure a new Agent.

type OutputGuardrails added in v1.11.0

type OutputGuardrails struct {
	SafetyPolicies  []SafetyPolicy
	FormatEnforcers []FormatEnforcer
}

OutputGuardrails holds the policy engines and formatting rules.

func (*OutputGuardrails) ValidateAndRepair added in v1.11.0

func (g *OutputGuardrails) ValidateAndRepair(ctx context.Context, response string) (string, error)

ValidateAndRepair applies safety checks and format enforcing to the response.

type PIIMaskerTransformer added in v1.11.4

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

PIIMaskerTransformer automatically detects personal data and replaces it with generic descriptors like [EMAIL] or [PHONE].

func NewPIIMaskerTransformer added in v1.11.4

func NewPIIMaskerTransformer(maskEmail, maskPhone, maskSSN, maskCards bool) *PIIMaskerTransformer

NewPIIMaskerTransformer creates a new PII masker transformer configuring the categories to mask.

func (*PIIMaskerTransformer) Transform added in v1.11.4

func (t *PIIMaskerTransformer) Transform(ctx context.Context, input string) (string, error)

Transform processes the input string and masks matches for selected categories.

type PromptInjectionDetectorPolicy added in v1.11.4

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

PromptInjectionDetectorPolicy scans the user query for common phrases associated with prompt injection attacks (heuristics).

func NewPromptInjectionDetectorPolicy added in v1.11.4

func NewPromptInjectionDetectorPolicy(customPatterns []string) *PromptInjectionDetectorPolicy

NewPromptInjectionDetectorPolicy creates a new injection detector policy. If customPatterns is provided, they are converted to lowercase and appended to the default patterns list.

func (*PromptInjectionDetectorPolicy) Validate added in v1.11.4

func (p *PromptInjectionDetectorPolicy) Validate(ctx context.Context, input string) error

Validate checks the input for potential prompt injection attempts.

type QueryType

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

type RegexBlocklistPolicy added in v1.11.1

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

RegexBlocklistPolicy enforces that a configurable list of regular expressions are not matched within the LLM output.

func NewRegexBlocklistPolicy added in v1.11.1

func NewRegexBlocklistPolicy(patterns []string) (*RegexBlocklistPolicy, error)

NewRegexBlocklistPolicy creates a new policy with the given string regex patterns. It returns an error if any of the patterns fail to compile.

func (*RegexBlocklistPolicy) Validate added in v1.11.1

func (p *RegexBlocklistPolicy) Validate(ctx context.Context, response string) error

Validate checks the response against all configured regex patterns.

type RegexInputBlocklistPolicy added in v1.11.4

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

RegexInputBlocklistPolicy validates that the input does not match a configurable list of regular expression patterns.

func NewRegexInputBlocklistPolicy added in v1.11.4

func NewRegexInputBlocklistPolicy(patterns []string) (*RegexInputBlocklistPolicy, error)

NewRegexInputBlocklistPolicy creates a new policy with the given string regex patterns. It returns an error if any of the patterns fail to compile.

func (*RegexInputBlocklistPolicy) Validate added in v1.11.4

func (p *RegexInputBlocklistPolicy) Validate(ctx context.Context, input string) error

Validate checks the input against all configured regex patterns.

type RegexInputReplaceTransformer added in v1.11.4

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

RegexInputReplaceTransformer replaces occurrences of a regular expression pattern with a specified replacement string.

func NewRegexInputReplaceTransformer added in v1.11.4

func NewRegexInputReplaceTransformer(pattern string, replacement string) (*RegexInputReplaceTransformer, error)

NewRegexInputReplaceTransformer creates a new regex replace transformer.

func (*RegexInputReplaceTransformer) Transform added in v1.11.4

func (t *RegexInputReplaceTransformer) Transform(ctx context.Context, input string) (string, error)

Transform replaces all matched patterns in the input with the replacement string.

type SafetyPolicy added in v1.11.0

type SafetyPolicy interface {
	Validate(ctx context.Context, response string) error
}

SafetyPolicy defines an interface for validating LLM responses.

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 SubAgentTool added in v1.0.9

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

SubAgentTool adapts a SubAgent to the Tool interface.

func (*SubAgentTool) Invoke added in v1.0.9

func (t *SubAgentTool) Invoke(ctx context.Context, req ToolRequest) (ToolResponse, error)

func (*SubAgentTool) Spec added in v1.0.9

func (t *SubAgentTool) Spec() ToolSpec

type Tool

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

Tool exposes structured metadata and an invocation handler.

func NewAgentTool added in v1.0.9

func NewAgentTool(name, description string, agent *Agent) Tool

NewAgentTool creates a new tool that wraps an Agent.

func NewSubAgentTool added in v1.0.9

func NewSubAgentTool(sa SubAgent) Tool

NewSubAgentTool creates a new tool that wraps a SubAgent.

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 ToolChoice added in v0.7.5

type ToolChoice struct {
	UseTool     bool           `json:"use_tool"`
	ToolName    string         `json:"tool_name"`
	Arguments   map[string]any `json:"arguments"`
	Reason      string         `json:"reason"`
	Answer      string         `json:"answer"`
	FinalAnswer string         `json:"final_answer"`
}

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.
codemode command
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.
gateway command
cmd/gateway — HTTP gateway that exposes a go-agent as a REST API.
cmd/gateway — HTTP gateway that exposes a go-agent as a REST API.
src
adk

Jump to

Keyboard shortcuts

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