agentic

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2026 License: MIT Imports: 14 Imported by: 0

README

agentic-go

CI Go Reference

A lightweight, type-safe Go framework for building AI agents with tool use, structured output, and multi-agent orchestration.

Features

  • Provider-agnostic -- pluggable Model interface with 9 built-in providers
  • Type-safe tools -- generic tool builders with automatic JSON Schema generation from Go structs
  • Structured output -- TypedAgent[DepsT, OutputT] returns validated typed results
  • Streaming -- first-class streaming with channel-based event delivery
  • Dependency injection -- typed dependencies passed to tool handlers via RunContext[DepsT]
  • Multi-agent -- delegate tasks between agents with Handoff
  • Deferred tools -- async execution with human-in-the-loop approval
  • History processors -- truncation, sliding window, and LLM-based summarization
  • Multi-modal -- images, audio, video, and document inputs
  • MCP support -- use tools from Model Context Protocol servers
  • Thinking tokens -- extended reasoning for Anthropic, OpenAI o-series, and Gemini
  • Output validation -- struct tag validation with automatic retry

Installation

go get github.com/regularkevvv/agentic-go

Requires Go 1.25.4 or later.

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    agentic "github.com/regularkevvv/agentic-go"
    "github.com/regularkevvv/agentic-go/provider/openai"
)

func main() {
    model, _ := openai.New("gpt-4o")
    agent := agentic.NewAgent[agentic.NoDeps]("You are a helpful assistant.", model)

    result, err := agent.Run(context.Background(), "Hello!", nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result.Output)
}

Tools

Define tools with automatic schema inference from Go types:

type GetWeatherInput struct {
    _        struct{} `tool:"Look up the current weather for a city"`
    Location string   `json:"location" description:"City name"`
    Unit     string   `json:"unit,omitempty" enum:"celsius,fahrenheit"`
}

agentic.AddTool(agent, func(input GetWeatherInput) (WeatherOutput, error) {
    return WeatherOutput{Temperature: 24, Condition: "sunny"}, nil
})

Tools with dependencies:

agentic.AddToolWithDeps(agent, func(ctx agentic.RunContext[MyDeps], input QueryInput) (QueryOutput, error) {
    rows, _ := ctx.Deps.DB.QueryContext(ctx.Ctx, input.SQL)
    return QueryOutput{Rows: rows}, nil
})

Structured Output

type Summary struct {
    Title    string   `json:"title"    validate:"required"`
    Points   []string `json:"points"   validate:"required,min=1"`
}

agent := agentic.NewTypedAgent[agentic.NoDeps, Summary](
    "Summarize the input as structured data.",
    model,
    "Return a structured summary.",
)

result, _ := agent.Run(ctx, "Summarize Go's strengths.", nil)
fmt.Println(result.Output.Title)  // typed access

Providers

Provider Import Constructor
OpenAI provider/openai openai.New("gpt-4o")
Anthropic provider/anthropic anthropic.New("claude-sonnet-4-20250514")
Google Gemini provider/gemini gemini.New("gemini-2.0-flash")
Azure OpenAI provider/azure azure.New(endpoint, deployment, apiKey)
AWS Bedrock provider/bedrock bedrock.New("us.anthropic.claude-sonnet-4-20250514-v1:0")
Together AI provider/together together.New("meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo")
OpenRouter provider/openrouter openrouter.New("anthropic/claude-sonnet-4")
Ollama provider/ollama ollama.New("llama3.1")
Grok provider/grok grok.New("grok-3")

Implement the Model interface to add your own.

Agent-to-Agent

Delegate tasks to specialized sub-agents:

researcher := agentic.NewAgent[MyDeps]("You are a research assistant.", model)
writer := agentic.NewAgent[MyDeps]("You write clear reports.", model)

// Writer can delegate research tasks
writer.AddHandoff(agentic.NewHandoff("research", "Delegate research tasks", researcher))

Deferred Tools

Tools that require human approval before execution:

tool, handler, _ := agentic.DeferredToolWithApproval(
    "delete_record", "Delete a database record",
    func(ctx context.Context, input DeleteInput) (string, error) {
        return db.Delete(input.ID)
    },
    func(ctx context.Context, call agentic.ToolUse) (bool, error) {
        return promptUser("Approve deletion of %s?", call.Input["id"]), nil
    },
)

Streaming

stream, _ := agent.RunStream(ctx, "Tell me a story.", nil)
for event := range stream.Events {
    if event.Type == agentic.StreamEventTextDelta {
        fmt.Print(event.Delta)
    }
}

History Processors

Manage context window with built-in processors:

agent := agentic.NewAgent[agentic.NoDeps]("You are helpful.", model,
    agentic.WithHistoryProcessor[agentic.NoDeps](agentic.TruncateHistory(20)),
)

// Or chain multiple processors
agentic.WithHistoryProcessor[agentic.NoDeps](agentic.ChainProcessors(
    agentic.SlidingWindowHistory(4000, tokenCounter),
    agentic.TruncateHistory(50),
))

Project Layout

agentic-go/
  agent.go            # Core agent orchestration
  agent_options.go    # Configuration options
  stream.go           # Streaming support
  typed_agent.go      # TypedAgent for structured output
  handoff.go          # Agent-to-agent delegation
  deferred.go         # Async/deferred tools
  history_processor.go # Message history transforms
  tools/              # Tool builders, registry, toolsets
  provider/           # LLM provider implementations
  internal/core/      # Shared types (Message, Tool, Model, etc.)
  mcp/                # Model Context Protocol integration
  examples/           # Runnable example programs

Examples

cp .env.example .env   # fill in your API key
go run ./examples/basic
go run ./examples/tools
go run ./examples/structured

See examples/ for details.

Contributing

See CONTRIBUTING.md for development setup, testing, and PR guidelines.

License

MIT

Documentation

Index

Constants

View Source
const (
	ToolTypeFunction          = core.ToolTypeFunction
	ToolChoiceNone            = core.ToolChoiceNone
	ToolChoiceAuto            = core.ToolChoiceAuto
	ToolChoiceRequired        = core.ToolChoiceRequired
	FinishReasonStop          = core.FinishReasonStop
	FinishReasonLength        = core.FinishReasonLength
	FinishReasonToolCalls     = core.FinishReasonToolCalls
	FinishReasonContentFilter = core.FinishReasonContentFilter
	RoleSystem                = core.RoleSystem
	RoleUser                  = core.RoleUser
	RoleAssistant             = core.RoleAssistant
	RoleTool                  = core.RoleTool
	ContentText               = core.ContentText
	ContentImageURL           = core.ContentImageURL
	ContentToolUse            = core.ContentToolUse
	ContentToolResult         = core.ContentToolResult
	ContentThinking           = core.ContentThinking
	ContentImageData          = core.ContentImageData
	ContentAudioURL           = core.ContentAudioURL
	ContentVideoURL           = core.ContentVideoURL
	ContentDocumentURL        = core.ContentDocumentURL
	ContentCachePoint         = core.ContentCachePoint
	ContentUploadedFile       = core.ContentUploadedFile
	OutputModeTool            = core.OutputModeTool
	OutputModeNative          = core.OutputModeNative
	OutputModePrompted        = core.OutputModePrompted
	OutputModeText            = core.OutputModeText
)

Domain constants (from core)

View Source
const (
	StreamEventTextDelta     = core.StreamEventTextDelta
	StreamEventToolCallStart = core.StreamEventToolCallStart
	StreamEventToolCallDelta = core.StreamEventToolCallDelta
	StreamEventToolResult    = core.StreamEventToolResult
	StreamEventDone          = core.StreamEventDone
	StreamEventError         = core.StreamEventError
	StreamEventThinkingDelta = core.StreamEventThinkingDelta
)

Stream event constants

View Source
const (
	DeferredPending  = agentictool.DeferredPending
	DeferredApproved = agentictool.DeferredApproved
	DeferredRejected = agentictool.DeferredRejected
	DeferredTimedOut = agentictool.DeferredTimedOut
)

Deferred status constants

View Source
const DefaultPromptedTemplate = `` /* 140-byte string literal not displayed */

DefaultPromptedTemplate is the default template for prompted output. The {schema} placeholder is replaced with the JSON schema.

Variables

This section is empty.

Functions

func AutoTool

func AutoTool[TInput any, TOutput any](
	handler func(input TInput) (TOutput, error),
	opts ...AutoToolOption,
) (Tool, ToolHandler, error)

func AutoToolWithDeps

func AutoToolWithDeps[TInput any, TOutput any, DepsT any](
	handler func(ctx RunContext[DepsT], input TInput) (TOutput, error),
	opts ...AutoToolOption,
) (Tool, ToolHandler, error)

func DeferredTool

func DeferredTool[TInput any, TOutput any](
	name, description string,
	handler func(ctx context.Context, input TInput) (<-chan TOutput, error),
	opts ...DeferredToolOption,
) (Tool, ToolHandler, error)

func DeferredToolWithApproval

func DeferredToolWithApproval[TInput any, TOutput any](
	name, description string,
	handler func(ctx context.Context, input TInput) (TOutput, error),
	approvalFn ApprovalFunc,
	opts ...DeferredToolOption,
) (Tool, ToolHandler, error)

func FormatToolResult

func FormatToolResult(result interface{}) string

func IntPtr

func IntPtr(v int) *int

IntPtr is a helper to create *int values for UsageLimits fields.

Example:

limits := agentic.UsageLimits{
    MaxRequests:    agentic.IntPtr(10),
    MaxTotalTokens: agentic.IntPtr(50000),
}

func IsModelRetry

func IsModelRetry(err error) bool

IsModelRetry checks if an error is a ModelRetry.

func IsUsageLimitExceeded

func IsUsageLimitExceeded(err error) bool

IsUsageLimitExceeded checks if an error is a UsageLimitExceededError.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if an error is a ValidationError.

func MustAutoTool

func MustAutoTool[TInput any, TOutput any](
	handler func(input TInput) (TOutput, error),
	opts ...AutoToolOption,
) (Tool, ToolHandler)

func MustAutoToolWithDeps

func MustAutoToolWithDeps[TInput any, TOutput any, DepsT any](
	handler func(ctx RunContext[DepsT], input TInput) (TOutput, error),
	opts ...AutoToolOption,
) (Tool, ToolHandler)

func MustDeferredTool

func MustDeferredTool[TInput any, TOutput any](
	name, description string,
	handler func(ctx context.Context, input TInput) (<-chan TOutput, error),
	opts ...DeferredToolOption,
) (Tool, ToolHandler)

func MustDeferredToolWithApproval

func MustDeferredToolWithApproval[TInput any, TOutput any](
	name, description string,
	handler func(ctx context.Context, input TInput) (TOutput, error),
	approvalFn ApprovalFunc,
	opts ...DeferredToolOption,
) (Tool, ToolHandler)

func MustToolPlain

func MustToolPlain[TInput any, TOutput any](
	name, description string,
	handler func(input TInput) (TOutput, error),
	opts ...ToolOption,
) (Tool, ToolHandler)

func MustToolWithDeps

func MustToolWithDeps[TInput any, TOutput any, DepsT any](
	name, description string,
	handler func(ctx RunContext[DepsT], input TInput) (TOutput, error),
	opts ...ToolOption,
) (Tool, ToolHandler)

func RegisterToolset

func RegisterToolset(registry ToolRegistry, set Toolset) error

func ToolPlain

func ToolPlain[TInput any, TOutput any](
	name, description string,
	handler func(input TInput) (TOutput, error),
	opts ...ToolOption,
) (Tool, ToolHandler, error)

func ToolWithDeps

func ToolWithDeps[TInput any, TOutput any, DepsT any](
	name, description string,
	handler func(ctx RunContext[DepsT], input TInput) (TOutput, error),
	opts ...ToolOption,
) (Tool, ToolHandler, error)

func ValidateStruct

func ValidateStruct(v any) error

ValidateStruct validates a struct using `validate` struct tags. Returns a *ValidationError with human-readable messages if validation fails, or nil if validation passes (or the value has no validate tags).

This is used automatically by ToolOutputSpec when parsing structured output, but can also be called directly.

Types

type Agent

type Agent[DepsT any] struct {
	// contains filtered or unexported fields
}

Agent orchestrates LLM interactions with tools and structured output. DepsT is the type of user-provided dependencies accessible in tool handlers and dynamic prompts. Use NoDeps when you do not inject dependencies.

func AddTool

func AddTool[DepsT any, TInput any, TOutput any](
	agent *Agent[DepsT],
	handler func(input TInput) (TOutput, error),
	opts ...AutoToolOption,
) *Agent[DepsT]

AddTool registers a plain auto-tool on an agent.

func AddToolWithDeps

func AddToolWithDeps[DepsT any, TInput any, TOutput any](
	agent *Agent[DepsT],
	handler func(ctx RunContext[DepsT], input TInput) (TOutput, error),
	opts ...AutoToolOption,
) *Agent[DepsT]

AddToolWithDeps registers a deps-aware auto-tool on an agent.

func NewAgent

func NewAgent[DepsT any](systemPrompt string, model Model, opts ...AgentOption[DepsT]) *Agent[DepsT]

NewAgent creates a new agent with a static system prompt.

Example:

agent := agentic.NewAgent[NoDeps]("You are a helpful assistant", model)

func NewAgentDynamic

func NewAgentDynamic[DepsT any](promptFn func(ctx RunContext[DepsT]) (string, error), model Model, opts ...AgentOption[DepsT]) *Agent[DepsT]

NewAgentDynamic creates an agent with a dynamic system prompt function. The function is called at the start of each Run to generate the system prompt.

func (*Agent[DepsT]) AddAutoTool

func (a *Agent[DepsT]) AddAutoTool(tool Tool, handler ToolHandler) *Agent[DepsT]

AddAutoTool registers a tool and handler created via auto-registration. This is a convenience method — pass the results of AutoTool or MustAutoTool.

Example:

agent.AddAutoTool(agentic.MustAutoTool(func(input GetWeatherInput) (WeatherOutput, error) {
    return WeatherOutput{Temperature: 72.0}, nil
}))

func (*Agent[DepsT]) AddHandoff

func (a *Agent[DepsT]) AddHandoff(h *Handoff[DepsT]) *Agent[DepsT]

AddHandoff registers another agent as a delegatable tool. The parent agent can call this tool to delegate work to the sub-agent.

func (*Agent[DepsT]) AddTool

func (a *Agent[DepsT]) AddTool(tool Tool, handler ToolHandler) *Agent[DepsT]

AddTool adds a tool and its handler to the agent. If no registry exists, one is created automatically.

func (*Agent[DepsT]) AddToolset

func (a *Agent[DepsT]) AddToolset(set Toolset) *Agent[DepsT]

func (*Agent[DepsT]) Run

func (a *Agent[DepsT]) Run(ctx context.Context, prompt string, deps *DepsT, opts ...RunOption) (*RunResult, error)

Run executes the agent with the given instruction and returns the result.

The agent loop:

  1. Builds messages (system prompt + history + user instruction)
  2. Sends request to the model
  3. If the model returns tool calls, executes them and loops
  4. If a tool returns ModelRetry, sends the error back and retries
  5. Returns when the model produces a final text response or max iterations is hit

func (*Agent[DepsT]) RunStream

func (a *Agent[DepsT]) RunStream(ctx context.Context, prompt string, deps *DepsT, opts ...RunOption) (*StreamResult, error)

RunStream executes the agent with streaming. If the model implements StreamModel, true token-by-token streaming is used. Otherwise, it falls back to wrapping Run() and emitting the result as events.

func (*Agent[DepsT]) SetOutputToolNames

func (a *Agent[DepsT]) SetOutputToolNames(names map[string]bool) *Agent[DepsT]

SetOutputToolNames sets the names of tools that signal structured output completion. When an output tool is called, the agent stops the loop and returns the result.

func (*Agent[DepsT]) SetRegistry

func (a *Agent[DepsT]) SetRegistry(registry ToolRegistry) *Agent[DepsT]

SetRegistry sets the tool registry for the agent.

type AgentOption

type AgentOption[DepsT any] func(*agentConfig[DepsT])

AgentOption configures an Agent at creation time.

func WithEndStrategy

func WithEndStrategy[DepsT any](strategy EndStrategy) AgentOption[DepsT]

WithEndStrategy sets when the agent considers a run complete.

func WithHandoffs

func WithHandoffs[DepsT any](handoffs ...*Handoff[DepsT]) AgentOption[DepsT]

WithHandoffs registers handoffs at agent creation time. Each handoff is registered as a tool on the agent.

func WithHistoryProcessor

func WithHistoryProcessor[DepsT any](p HistoryProcessor) AgentOption[DepsT]

WithHistoryProcessor sets a processor to transform messages before each LLM request. The processor only affects what's sent to the model — RunResult retains the full unprocessed history.

func WithMaxIterations

func WithMaxIterations[DepsT any](maxIter int) AgentOption[DepsT]

WithMaxIterations sets the maximum number of tool execution iterations.

func WithMaxTokens

func WithMaxTokens[DepsT any](maxTokens int) AgentOption[DepsT]

WithMaxTokens sets the maximum number of tokens to generate.

func WithMaxValidationRetries

func WithMaxValidationRetries[DepsT any](n int) AgentOption[DepsT]

WithMaxValidationRetries sets the maximum number of validation retry attempts. Default is 3. After this many failed validations, the last error is returned.

func WithOutputValidator

func WithOutputValidator[DepsT any](v OutputValidator[DepsT]) AgentOption[DepsT]

WithOutputValidator adds an output validator to the agent. Multiple validators can be added — all must pass for output to be accepted.

func WithOutputValidatorFunc

func WithOutputValidatorFunc[DepsT any](fn func(ctx RunContext[DepsT], output string) error) AgentOption[DepsT]

WithOutputValidatorFunc adds a function-based output validator.

Example:

agentic.WithOutputValidatorFunc[NoDeps](func(ctx agentic.RunContext[NoDeps], output string) error {
    if !strings.Contains(output, "answer") {
        return agentic.NewValidationError("Response must contain the word 'answer'")
    }
    return nil
})

func WithRetries

func WithRetries[DepsT any](config RetryConfig) AgentOption[DepsT]

WithRetries sets the retry configuration.

func WithSystemPrompts

func WithSystemPrompts[DepsT any](prompts ...SystemPrompt[DepsT]) AgentOption[DepsT]

WithSystemPrompts sets multiple system prompts (static and/or dynamic) for the agent. Prompts are resolved and concatenated (joined with "\n\n") at the start of each run. This replaces any system prompt set via NewAgent or NewAgentDynamic.

Example:

agent := agentic.NewAgent[MyDeps]("", model,
    agentic.WithSystemPrompts[MyDeps](
        agentic.StaticPrompt[MyDeps]("You are a helpful assistant."),
        agentic.DynamicPrompt[MyDeps](func(ctx agentic.RunContext[MyDeps]) (string, error) {
            return fmt.Sprintf("The user's name is %s", ctx.Deps.Name), nil
        }),
    ),
)

func WithTemperature

func WithTemperature[DepsT any](temp float64) AgentOption[DepsT]

WithTemperature sets the sampling temperature (0.0 to 2.0).

func WithThinking

func WithThinking[DepsT any](config ThinkingConfig) AgentOption[DepsT]

WithThinking enables thinking/reasoning tokens for the agent. For Anthropic models, this enables extended thinking with the specified budget. For OpenAI o1/o3 models, this maps to reasoning_effort.

Example:

agent := agentic.NewAgent[NoDeps]("prompt", model,
    agentic.WithThinking[NoDeps](agentic.ThinkingConfig{
        Enabled:      true,
        BudgetTokens: 10000,
    }),
)

func WithToolChoice

func WithToolChoice[DepsT any](choice ToolChoice) AgentOption[DepsT]

WithToolChoice sets how the agent should use tools.

func WithToolPrepare

func WithToolPrepare[DepsT any](fn ToolPrepareFunc[DepsT]) AgentOption[DepsT]

WithToolPrepare registers a function to customize tools before each LLM request.

func WithTopP

func WithTopP[DepsT any](topP float64) AgentOption[DepsT]

WithTopP sets the nucleus sampling parameter (0.0 to 1.0).

func WithUsageLimits

func WithUsageLimits[DepsT any](limits UsageLimits) AgentOption[DepsT]

WithUsageLimits sets usage limits for all runs of this agent. Limits are enforced during the agent run loop — before each LLM request, after each response, and before tool call execution.

Example:

agent := agentic.NewAgent[NoDeps]("prompt", model,
    agentic.WithUsageLimits[NoDeps](agentic.UsageLimits{
        MaxRequests:    intPtr(10),
        MaxTotalTokens: intPtr(50000),
    }),
)

type ApprovalFunc

type ApprovalFunc = agentictool.ApprovalFunc

type AudioURL

type AudioURL = core.AudioURL

type AutoToolOption

type AutoToolOption = agentictool.AutoToolOption

func AutoToolDescription

func AutoToolDescription(desc string) AutoToolOption

func AutoToolName

func AutoToolName(name string) AutoToolOption

type CachePoint

type CachePoint = core.CachePoint

type ChatRequest

type ChatRequest = core.ChatRequest

type ChatResponse

type ChatResponse = core.ChatResponse

type Choice

type Choice = core.Choice

type ContentType

type ContentType = core.ContentType

type DeferredStatus

type DeferredStatus = agentictool.DeferredStatus

Deferred tool types (from tool/)

type DeferredToolOption

type DeferredToolOption = agentictool.DeferredToolOption

func WithApproval

func WithApproval(fn ApprovalFunc) DeferredToolOption

func WithDeferredTimeout

func WithDeferredTimeout(d time.Duration) DeferredToolOption

type DeferredToolResult

type DeferredToolResult = agentictool.DeferredToolResult

type DepsToolHandler

type DepsToolHandler[TInput any, TOutput any, DepsT any] = agentictool.DepsToolHandler[TInput, TOutput, DepsT]

type DocumentURL

type DocumentURL = core.DocumentURL

type EndStrategy

type EndStrategy int

EndStrategy controls when the agent considers a run complete when multiple tool calls are returned in a single response.

const (
	// EndStrategyExhaustive (default) processes all tool calls in a response
	// before checking for completion.
	EndStrategyExhaustive EndStrategy = iota

	// EndStrategyEarly stops the run as soon as an output tool result
	// is produced, even if other tool calls are pending.
	EndStrategyEarly
)

type FinishReason

type FinishReason = core.FinishReason

type FuncToolset

type FuncToolset = agentictool.FuncToolset

func NewToolset

func NewToolset() *FuncToolset

type Function

type Function = core.Function

type Handoff

type Handoff[DepsT any] struct {
	// contains filtered or unexported fields
}

Handoff represents a delegation target — another agent that can handle specific tasks. Handoffs are registered as regular tools on the parent agent, making them composable with all existing features (retry, validation, etc.).

func NewHandoff

func NewHandoff[DepsT any](name, description string, agent *Agent[DepsT], opts ...HandoffOption) *Handoff[DepsT]

NewHandoff creates a handoff target from an existing agent.

type HandoffInputFilter

type HandoffInputFilter int

HandoffInputFilter controls what context is passed to the sub-agent.

const (
	// HandoffFullHistory passes the full conversation history to the sub-agent.
	HandoffFullHistory HandoffInputFilter = iota
	// HandoffLastMessage passes only the tool call input as the user prompt.
	HandoffLastMessage
	// HandoffSummary summarizes the conversation before passing to the sub-agent.
	HandoffSummary
)

type HandoffOption

type HandoffOption func(*handoffConfig)

HandoffOption configures handoff behavior.

func WithHandoffFilter

func WithHandoffFilter(filter HandoffInputFilter) HandoffOption

WithHandoffFilter sets the input filter for the sub-agent.

func WithHandoffMaxTokens

func WithHandoffMaxTokens(n int) HandoffOption

WithHandoffMaxTokens overrides max tokens for the sub-agent run.

func WithHandoffSystemPrompt

func WithHandoffSystemPrompt(prompt string) HandoffOption

WithHandoffSystemPrompt prepends context to the sub-agent's system prompt.

type HistoryProcessor

type HistoryProcessor interface {
	Process(ctx context.Context, messages []Message) ([]Message, error)
}

HistoryProcessor transforms the message history before it's sent to the model. The processor affects only what's sent to the model — the agent's internal message list remains complete for RunResult.AllMessages().

func ChainProcessors

func ChainProcessors(processors ...HistoryProcessor) HistoryProcessor

ChainProcessors applies multiple processors in sequence. Each processor receives the output of the previous one.

func SlidingWindowHistory

func SlidingWindowHistory(maxTokens int, tokenCounter func(Message) int) HistoryProcessor

SlidingWindowHistory keeps a sliding window of messages within a token budget. The system prompt is always preserved. tokenCounter estimates the token count for a single message.

func SummarizeHistory

func SummarizeHistory(model Model, maxMessages int) HistoryProcessor

SummarizeHistory uses an LLM to summarize older messages when the history exceeds maxMessages. The summary replaces older messages as a single user message. The most recent maxMessages are always preserved verbatim.

func TruncateHistory

func TruncateHistory(maxMessages int) HistoryProcessor

TruncateHistory keeps the system prompt (if any) plus the last maxMessages messages.

type HistoryProcessorFunc

type HistoryProcessorFunc func(ctx context.Context, messages []Message) ([]Message, error)

HistoryProcessorFunc is a function adapter for HistoryProcessor.

func (HistoryProcessorFunc) Process

func (f HistoryProcessorFunc) Process(ctx context.Context, messages []Message) ([]Message, error)

type ImageData

type ImageData = core.ImageData

type ImageURL

type ImageURL = core.ImageURL

type JSONSchemaFormat

type JSONSchemaFormat = core.JSONSchemaFormat

type MaxIterationsError

type MaxIterationsError struct {
	MaxIterations int
}

MaxIterationsError is returned when the agent hits the maximum iteration limit.

func (*MaxIterationsError) Error

func (e *MaxIterationsError) Error() string

type Message

type Message = core.Message

func NewImageDataMessage

func NewImageDataMessage(text string, data []byte, mediaType string) Message

NewImageDataMessage creates a user message with text and inline image data.

func NewImageFileMessage

func NewImageFileMessage(text string, filePath string) (Message, error)

NewImageFileMessage creates a user message with text and an image loaded from a file. The media type is inferred from the file extension.

func NewImageURLMessage

func NewImageURLMessage(text string, imageURL string, detail ...string) Message

NewImageURLMessage creates a user message with text and an image URL.

func NewMultiPartMessage

func NewMultiPartMessage(parts ...Part) Message

NewMultiPartMessage creates a user message with multiple content parts.

func NewTextMessage

func NewTextMessage(role MessageRole, text string) Message

func NewToolResultMessage

func NewToolResultMessage(toolUseID string, content string, isError bool) Message

func NewToolUseMessage

func NewToolUseMessage(toolUses ...ToolUse) Message

type MessageHistory

type MessageHistory struct {
	Messages []Message `json:"messages"`
}

MessageHistory is a serializable conversation history that can be saved, loaded, and used to resume conversations.

func LoadHistory

func LoadHistory(data []byte) (*MessageHistory, error)

LoadHistory deserializes a MessageHistory from JSON bytes.

func NewHistory

func NewHistory(messages ...Message) *MessageHistory

NewHistory creates a new MessageHistory from the given messages.

func (*MessageHistory) SaveJSON

func (h *MessageHistory) SaveJSON() ([]byte, error)

SaveJSON serializes the MessageHistory to JSON bytes.

func (*MessageHistory) ToRunOption

func (h *MessageHistory) ToRunOption() RunOption

ToRunOption converts the history into a RunOption that provides the messages as conversation history for a new run.

type MessageRole

type MessageRole = core.MessageRole

type Model

type Model = core.Model

type ModelRetry

type ModelRetry struct {
	Message string
}

ModelRetry is a sentinel error that tools can return to request a retry. When a tool returns this error, the error message is sent back to the LLM as a tool error, and the agent re-enters the loop (up to MaxRetries).

func Retry

func Retry(msg string) *ModelRetry

Retry creates a ModelRetry error. Use this in tool handlers to tell the agent to send the error back to the model and try again.

Example:

func(input SearchInput) (SearchOutput, error) {
    results := search(input.Query)
    if len(results) == 0 {
        return SearchOutput{}, agentic.Retry("No results found, try a different query")
    }
    return SearchOutput{Results: results}, nil
}

func Retryf

func Retryf(format string, args ...interface{}) *ModelRetry

Retryf creates a ModelRetry error with a formatted message.

func (*ModelRetry) Error

func (e *ModelRetry) Error() string

type NativeOutputSpec

type NativeOutputSpec[T any] struct {
	// contains filtered or unexported fields
}

NativeOutputSpec uses the model's native JSON schema output (response_format) for structured output. This is supported by OpenAI (json_schema) and Anthropic (output_config) on newer models.

The model is instructed via the API to produce JSON conforming to the schema of type T. No tool call is needed — the model returns JSON directly.

Example:

type MovieReview struct {
    Title   string  `json:"title"   description:"Movie title"`
    Rating  float64 `json:"rating"  description:"Rating from 1-10"`
    Summary string  `json:"summary" description:"Brief review"`
}

output := agentic.NewNativeOutput[MovieReview]("movie_review", "A structured movie review")

func NewNativeOutput

func NewNativeOutput[T any](name, description string) *NativeOutputSpec[T]

NewNativeOutput creates a NativeOutputSpec that uses native JSON schema output. The name identifies the schema (used in the API request). The description explains what the output represents.

func (*NativeOutputSpec[T]) Mode

func (s *NativeOutputSpec[T]) Mode() OutputMode

Mode returns the output mode for this spec.

func (*NativeOutputSpec[T]) Parse

func (s *NativeOutputSpec[T]) Parse(msg Message) (any, error)

Parse extracts the typed output from the assistant message text (JSON).

func (*NativeOutputSpec[T]) ResponseFormat

func (s *NativeOutputSpec[T]) ResponseFormat() *ResponseFormat

ResponseFormat returns the ResponseFormat to include in the ChatRequest.

func (*NativeOutputSpec[T]) Tools

func (s *NativeOutputSpec[T]) Tools() []Tool

Tools returns nil — native output does not use tools.

func (*NativeOutputSpec[T]) WithStrict

func (s *NativeOutputSpec[T]) WithStrict(strict bool) *NativeOutputSpec[T]

WithStrict sets whether to enforce strict schema adherence. Default is true.

type NoDeps added in v0.2.0

type NoDeps = core.NoDeps

NoDeps is the empty dependency type for agents and tools without dependency injection. It implements json.Marshaler (always JSON null). See package core.

type OutputMode

type OutputMode = core.OutputMode

type OutputModeSpec

type OutputModeSpec interface {
	OutputSpec
	Mode() OutputMode
}

OutputModeSpec is implemented by output specs that carry an output mode. This is used by the agent to determine how to configure the request.

type OutputSpec

type OutputSpec interface {
	// Tools returns any additional tools needed for output extraction.
	// For example, ToolOutputSpec adds a hidden "final_result" tool.
	Tools() []Tool

	// Parse extracts the typed output from the agent response.
	// It receives the final assistant message and returns the parsed output.
	Parse(msg Message) (any, error)
}

OutputSpec defines how to extract structured output from the LLM response. The default (nil) extracts plain text.

type OutputValidator

type OutputValidator[DepsT any] interface {
	Validate(ctx RunContext[DepsT], output string) error
}

OutputValidator validates agent text output and can request retries. When validation fails, the error message is sent back to the model and the agent re-enters the loop (up to maxValidationRetries).

For structured output, prefer using `validate` struct tags instead — they are applied automatically. Use OutputValidator for custom logic on the raw text response.

type OutputValidatorFunc

type OutputValidatorFunc[DepsT any] func(ctx RunContext[DepsT], output string) error

OutputValidatorFunc is a function adapter for OutputValidator.

Example:

agentic.WithOutputValidatorFunc[NoDeps](func(ctx agentic.RunContext[NoDeps], output string) error {
    if !strings.Contains(output, "ANSWER:") {
        return agentic.NewValidationError("Response must contain 'ANSWER:'")
    }
    return nil
})

func (OutputValidatorFunc[DepsT]) Validate

func (f OutputValidatorFunc[DepsT]) Validate(ctx RunContext[DepsT], output string) error

Validate implements OutputValidator.

type Part

type Part = core.Part

func AudioURLPart

func AudioURLPart(url string, format ...string) Part

AudioURLPart creates an audio-from-URL content part.

func CachePointPart

func CachePointPart(ttl ...string) Part

CachePointPart creates a cache point marker. When inserted into message content, it signals the provider to cache all content preceding this point. TTL can be "5m" (default) or "1h". Supported by: Anthropic, Amazon Bedrock. Silently ignored by other providers.

func DocumentURLPart

func DocumentURLPart(url string, mediaType ...string) Part

DocumentURLPart creates a document-from-URL content part (e.g. PDF).

func ImageDataPart

func ImageDataPart(data []byte, mediaType string) Part

ImageDataPart creates an inline base64-encoded image content part.

func ImageURLPart

func ImageURLPart(url string, detail ...string) Part

ImageURLPart creates an image-from-URL content part. Optional detail parameter controls image processing fidelity ("auto", "low", "high").

func TextPart

func TextPart(text string) Part

TextPart creates a text content part.

func UploadedFilePart

func UploadedFilePart(fileID string, providerName string) Part

UploadedFilePart creates a reference to a file uploaded to a provider's file storage. The fileID is the provider-specific identifier returned by the provider's upload API. The providerName identifies which provider hosts the file (e.g. "anthropic", "openai").

func VideoURLPart

func VideoURLPart(url string) Part

VideoURLPart creates a video-from-URL content part.

type PlainToolHandler

type PlainToolHandler[TInput any, TOutput any] = agentictool.PlainToolHandler[TInput, TOutput]

type PromptedOutputSpec

type PromptedOutputSpec[T any] struct {
	// contains filtered or unexported fields
}

PromptedOutputSpec instructs the model via the system prompt to output JSON conforming to a schema. The model receives the schema as text instructions and optionally uses the provider's JSON object mode (response_format: json_object) to ensure valid JSON output.

This is useful for providers/models that don't support native JSON schema output but do support JSON object mode.

Example:

output := agentic.NewPromptedOutput[MovieReview]()

func NewPromptedOutput

func NewPromptedOutput[T any]() *PromptedOutputSpec[T]

NewPromptedOutput creates a PromptedOutputSpec.

func (*PromptedOutputSpec[T]) Mode

func (s *PromptedOutputSpec[T]) Mode() OutputMode

Mode returns the output mode for this spec.

func (*PromptedOutputSpec[T]) Parse

func (s *PromptedOutputSpec[T]) Parse(msg Message) (any, error)

Parse extracts the typed output from the assistant message text (JSON).

func (*PromptedOutputSpec[T]) ResponseFormat

func (s *PromptedOutputSpec[T]) ResponseFormat() *ResponseFormat

ResponseFormat returns a json_object response format hint for providers that support it.

func (*PromptedOutputSpec[T]) SystemPromptSuffix

func (s *PromptedOutputSpec[T]) SystemPromptSuffix() string

SystemPromptSuffix returns the text to append to the system prompt with the JSON schema instructions.

func (*PromptedOutputSpec[T]) Tools

func (s *PromptedOutputSpec[T]) Tools() []Tool

Tools returns nil — prompted output does not use tools.

func (*PromptedOutputSpec[T]) WithTemplate

func (s *PromptedOutputSpec[T]) WithTemplate(template string) *PromptedOutputSpec[T]

WithTemplate sets a custom template. Use {schema} as a placeholder for the JSON schema.

type RequestUsage

type RequestUsage = core.RequestUsage

type ResponseFormat

type ResponseFormat = core.ResponseFormat

type ResponseFormatSpec

type ResponseFormatSpec interface {
	ResponseFormat() *ResponseFormat
}

ResponseFormatSpec is implemented by output specs that need a response_format in the ChatRequest (NativeOutputSpec and PromptedOutputSpec).

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retries when a tool returns ModelRetry.
	MaxRetries int
}

RetryConfig controls retry behavior for the agent.

type RunContext

type RunContext[DepsT any] = core.RunContext[DepsT]

type RunOption

type RunOption func(*runOptions)

RunOption configures a single Run call.

func WithMessages

func WithMessages(messages ...Message) RunOption

WithMessages provides initial conversation history for the run.

func WithRunEndStrategy

func WithRunEndStrategy(strategy EndStrategy) RunOption

WithRunEndStrategy overrides the agent's end strategy for this run.

func WithRunHistoryProcessor

func WithRunHistoryProcessor(p HistoryProcessor) RunOption

WithRunHistoryProcessor overrides the history processor for a single run.

func WithRunMaxIterations

func WithRunMaxIterations(maxIter int) RunOption

WithRunMaxIterations overrides the agent's max iterations for this run.

func WithRunMaxTokens

func WithRunMaxTokens(maxTokens int) RunOption

WithRunMaxTokens overrides the agent's max tokens for this run.

func WithRunTemperature

func WithRunTemperature(temp float64) RunOption

WithRunTemperature overrides the agent's temperature for this run.

func WithRunToolChoice

func WithRunToolChoice(choice ToolChoice) RunOption

WithRunToolChoice overrides the agent's tool choice for this run.

func WithRunUsageLimits

func WithRunUsageLimits(limits UsageLimits) RunOption

WithRunUsageLimits overrides the agent's usage limits for this run.

type RunResult

type RunResult struct {
	// Output is the final text response from the agent.
	Output string

	// Messages is the complete conversation history including tool interactions.
	Messages []Message

	// ToolCalls contains all tool calls made during the run.
	ToolCalls []ToolUse

	// ToolResults contains all tool results from executed tools.
	ToolResults []ToolExecutionResult

	// FinishReason indicates why the agent stopped.
	FinishReason FinishReason

	// Usage contains cumulative token usage for the entire run.
	Usage Usage

	// Retries is the number of retries that occurred.
	Retries int
	// contains filtered or unexported fields
}

RunResult contains the result of an agent run.

func (*RunResult) AllMessages

func (r *RunResult) AllMessages() []Message

AllMessages returns the complete conversation history including any messages provided as history and all new messages from this run.

func (*RunResult) History

func (r *RunResult) History() *MessageHistory

History returns a serializable MessageHistory from this result, containing all messages from the conversation.

func (*RunResult) NewMessages

func (r *RunResult) NewMessages() []Message

NewMessages returns only the messages generated during this run, excluding any messages that were provided as conversation history.

type StreamEvent

type StreamEvent = core.StreamEvent

type StreamEventType

type StreamEventType = core.StreamEventType

type StreamModel

type StreamModel = core.StreamModel

type StreamResult

type StreamResult = core.StreamResult

func NewStreamResult

func NewStreamResult(ch <-chan StreamEvent) *StreamResult

type SystemPrompt

type SystemPrompt[DepsT any] struct {
	// contains filtered or unexported fields
}

SystemPrompt represents one segment of a system prompt. An agent can have multiple system prompts (static and/or dynamic) that are concatenated at the start of each run.

func DynamicPrompt

func DynamicPrompt[DepsT any](fn func(ctx RunContext[DepsT]) (string, error)) SystemPrompt[DepsT]

DynamicPrompt creates a dynamic system prompt segment that is evaluated at the start of each run.

Example:

prompt := agentic.DynamicPrompt[MyDeps](func(ctx agentic.RunContext[MyDeps]) (string, error) {
    return fmt.Sprintf("The user's name is %s", ctx.Deps.Name), nil
})

func StaticPrompt

func StaticPrompt[DepsT any](text string) SystemPrompt[DepsT]

StaticPrompt creates a static system prompt segment.

Example:

prompt := agentic.StaticPrompt[NoDeps]("You are a helpful assistant")

func (SystemPrompt[DepsT]) Resolve

func (sp SystemPrompt[DepsT]) Resolve(ctx RunContext[DepsT]) (string, error)

Resolve evaluates the prompt segment, returning the text. For static prompts, it returns the text directly. For dynamic prompts, it calls the function with the given RunContext.

type SystemPromptAppender

type SystemPromptAppender interface {
	SystemPromptSuffix() string
}

SystemPromptAppender is implemented by output specs that need to append instructions to the system prompt (PromptedOutputSpec).

type TextOutputSpec

type TextOutputSpec struct{}

TextOutputSpec is the default output spec — extracts text content.

func (*TextOutputSpec) Parse

func (s *TextOutputSpec) Parse(msg Message) (any, error)

func (*TextOutputSpec) Tools

func (s *TextOutputSpec) Tools() []Tool

type TextProcessorOutputSpec

type TextProcessorOutputSpec[T any] struct {
	// contains filtered or unexported fields
}

TextProcessorOutputSpec uses a custom function to convert raw text output into a typed result. The model returns plain text, and the processor function transforms it into the desired output type.

Example:

output := agentic.NewTextProcessorOutput(func(text string) (int, error) {
    return strconv.Atoi(strings.TrimSpace(text))
})

func NewTextProcessorOutput

func NewTextProcessorOutput[T any](processor func(string) (T, error)) *TextProcessorOutputSpec[T]

NewTextProcessorOutput creates a TextProcessorOutputSpec with the given processor function.

func (*TextProcessorOutputSpec[T]) Mode

func (s *TextProcessorOutputSpec[T]) Mode() OutputMode

Mode returns the output mode for this spec.

func (*TextProcessorOutputSpec[T]) Parse

func (s *TextProcessorOutputSpec[T]) Parse(msg Message) (any, error)

Parse extracts text from the message and runs it through the processor function.

func (*TextProcessorOutputSpec[T]) Tools

func (s *TextProcessorOutputSpec[T]) Tools() []Tool

Tools returns nil — text processor output does not use tools.

type ThinkingBlock

type ThinkingBlock = core.ThinkingBlock

type ThinkingConfig

type ThinkingConfig = core.ThinkingConfig

type Tool

type Tool = core.Tool

func MustNewToolFromStruct

func MustNewToolFromStruct(name, description string, input interface{}) Tool

func NewToolFromStruct

func NewToolFromStruct(name, description string, input interface{}) (Tool, error)

type ToolChoice

type ToolChoice = core.ToolChoice

type ToolConfig

type ToolConfig = core.ToolConfig

type ToolExecutionResult

type ToolExecutionResult = core.ToolExecutionResult

type ToolHandler

type ToolHandler = core.ToolHandler

type ToolOption

type ToolOption = agentictool.ToolOption

func WithToolMaxRetries

func WithToolMaxRetries(n int) ToolOption

WithToolMaxRetries sets the max retry count for a specific tool.

type ToolOutputSpec

type ToolOutputSpec[T any] struct {
	// contains filtered or unexported fields
}

ToolOutputSpec uses a designated tool call for structured output. The LLM is instructed to call a tool whose input IS the structured output. This is the most reliable way to get structured output across all providers.

func NewToolOutput

func NewToolOutput[T any](description string) *ToolOutputSpec[T]

NewToolOutput creates a ToolOutputSpec that extracts structured output via a tool call. The type T defines the output schema. The LLM will be given a tool with this schema and instructed to call it with the final result.

Use `validate` struct tags to enforce constraints on the output. If the LLM produces invalid output, the validation error is sent back to the model for automatic retry. See https://github.com/go-playground/validator for all available tags.

Example:

type MovieReview struct {
    Title   string  `json:"title"   validate:"required,min=1"                  description:"Movie title"`
    Rating  float64 `json:"rating"  validate:"required,min=1,max=10"           description:"Rating from 1-10"`
    Genre   string  `json:"genre"   validate:"required,oneof=action comedy drama" description:"Movie genre"`
    Summary string  `json:"summary" validate:"required,min=10"                 description:"Brief review"`
}

output := agentic.NewToolOutput[MovieReview]("Review a movie and provide structured feedback")

func (*ToolOutputSpec[T]) Parse

func (s *ToolOutputSpec[T]) Parse(msg Message) (any, error)

func (*ToolOutputSpec[T]) Tools

func (s *ToolOutputSpec[T]) Tools() []Tool

type ToolPrepareFunc

type ToolPrepareFunc[DepsT any] func(ctx RunContext[DepsT], tools []Tool) ([]Tool, error)

ToolPrepareFunc is called before each LLM request to customize the tool set. It receives the current RunContext and the full list of registered tools, and returns the (possibly filtered/modified) tools to send to the model.

type ToolRegistry

type ToolRegistry = agentictool.ToolRegistry

func NewRegistry

func NewRegistry() ToolRegistry

type ToolResult

type ToolResult = core.ToolResult

type ToolType

type ToolType = core.ToolType

type ToolUse

type ToolUse = core.ToolUse

type Toolset

type Toolset = agentictool.Toolset

func CombineToolsets

func CombineToolsets(sets ...Toolset) Toolset

func FilterToolset

func FilterToolset(set Toolset, predicate func(toolName string) bool) Toolset

func PrefixToolset

func PrefixToolset(set Toolset, prefix string) Toolset

type TypedAgent

type TypedAgent[DepsT any, OutputT any] struct {
	// contains filtered or unexported fields
}

TypedAgent is an agent that returns typed structured output. It wraps Agent[DepsT] with an OutputSpec to provide a clean, type-safe API.

By default it uses tool-based output (ToolOutputSpec), but it also supports native JSON schema output (NativeOutputSpec), prompted output (PromptedOutputSpec), and text processor output (TextProcessorOutputSpec).

Use NewTypedAgent to create one:

type MovieReview struct {
    Title   string  `json:"title"   validate:"required"         description:"Movie title"`
    Rating  float64 `json:"rating"  validate:"required,min=1,max=10" description:"Rating 1-10"`
    Summary string  `json:"summary" validate:"required,min=10"  description:"Brief review"`
}

agent := agentic.NewTypedAgent[NoDeps, MovieReview](
    "You review movies.",
    model,
    "Provide a structured movie review",
)
result, err := agent.Run(ctx, "Review The Matrix", nil)
fmt.Println(result.Output.Title)  // "The Matrix"

func AddToolToTyped

func AddToolToTyped[DepsT any, OutputT any, TInput any, TOutput any](
	agent *TypedAgent[DepsT, OutputT],
	handler func(input TInput) (TOutput, error),
	opts ...AutoToolOption,
) *TypedAgent[DepsT, OutputT]

AddToolToTyped registers a plain auto-tool on a TypedAgent.

func NewTypedAgent

func NewTypedAgent[DepsT any, OutputT any](
	systemPrompt string,
	model Model,
	outputDescription string,
	opts ...AgentOption[DepsT],
) *TypedAgent[DepsT, OutputT]

NewTypedAgent creates an agent that returns typed structured output using tool-based output. The outputDescription tells the LLM what to produce (e.g., "Provide a movie review").

Example:

agent := agentic.NewTypedAgent[NoDeps, MovieReview](
    "You are a movie critic.",
    model,
    "Provide a structured movie review",
    agentic.WithMaxTokens[NoDeps](500),
)

func NewTypedAgentDynamic

func NewTypedAgentDynamic[DepsT any, OutputT any](
	promptFn func(ctx RunContext[DepsT]) (string, error),
	model Model,
	outputDescription string,
	opts ...AgentOption[DepsT],
) *TypedAgent[DepsT, OutputT]

NewTypedAgentDynamic creates a typed agent with a dynamic system prompt.

func NewTypedAgentWithMode

func NewTypedAgentWithMode[DepsT any, OutputT any](
	systemPrompt string,
	model Model,
	outputSpec OutputSpec,
	opts ...AgentOption[DepsT],
) *TypedAgent[DepsT, OutputT]

NewTypedAgentWithMode creates an agent that returns typed structured output using the specified output mode spec.

Supported output specs:

  • *ToolOutputSpec[T] (tool-based, default)
  • *NativeOutputSpec[T] (native JSON schema via response_format)
  • *PromptedOutputSpec[T] (schema in system prompt + JSON mode)
  • *TextProcessorOutputSpec[T] (custom text→output function)

Example with native output:

agent := agentic.NewTypedAgentWithMode[NoDeps, MovieReview](
    "You are a movie critic.",
    model,
    agentic.NewNativeOutput[MovieReview]("movie_review", "A structured movie review"),
)

func (*TypedAgent[DepsT, OutputT]) AddAutoTool

func (ta *TypedAgent[DepsT, OutputT]) AddAutoTool(tool Tool, handler ToolHandler) *TypedAgent[DepsT, OutputT]

AddAutoTool adds an auto-registered tool to the typed agent.

func (*TypedAgent[DepsT, OutputT]) AddTool

func (ta *TypedAgent[DepsT, OutputT]) AddTool(tool Tool, handler ToolHandler) *TypedAgent[DepsT, OutputT]

AddTool adds a tool to the typed agent.

func (*TypedAgent[DepsT, OutputT]) AddToolset

func (ta *TypedAgent[DepsT, OutputT]) AddToolset(set Toolset) *TypedAgent[DepsT, OutputT]

AddToolset adds a toolset to the typed agent.

func (*TypedAgent[DepsT, OutputT]) Run

func (ta *TypedAgent[DepsT, OutputT]) Run(
	ctx context.Context,
	prompt string,
	deps *DepsT,
	opts ...RunOption,
) (*TypedRunResult[OutputT], error)

Run executes the typed agent and returns structured output.

func (*TypedAgent[DepsT, OutputT]) SetRegistry

func (ta *TypedAgent[DepsT, OutputT]) SetRegistry(registry ToolRegistry) *TypedAgent[DepsT, OutputT]

SetRegistry sets the tool registry for the typed agent.

type TypedOutputValidator

type TypedOutputValidator[DepsT any, OutputT any] interface {
	ValidateTyped(ctx RunContext[DepsT], output OutputT) error
}

TypedOutputValidator validates typed structured output. Use this for programmatic validation that goes beyond what struct tags can express.

type TypedOutputValidatorFunc

type TypedOutputValidatorFunc[DepsT any, OutputT any] func(ctx RunContext[DepsT], output OutputT) error

TypedOutputValidatorFunc is a function adapter for TypedOutputValidator.

func (TypedOutputValidatorFunc[DepsT, OutputT]) ValidateTyped

func (f TypedOutputValidatorFunc[DepsT, OutputT]) ValidateTyped(ctx RunContext[DepsT], output OutputT) error

ValidateTyped implements TypedOutputValidator.

type TypedRunResult

type TypedRunResult[OutputT any] struct {
	Output       OutputT
	Messages     []Message
	ToolCalls    []ToolUse
	ToolResults  []ToolExecutionResult
	FinishReason FinishReason
	Usage        Usage
	Retries      int
}

TypedRunResult is like RunResult but with typed output.

type UploadedFile

type UploadedFile = core.UploadedFile

type Usage

type Usage = core.Usage

type UsageLimitExceededError

type UsageLimitExceededError struct {
	// LimitName describes which limit was exceeded (e.g., "request_tokens", "requests").
	LimitName string
	// Current is the current value at the time the limit was exceeded.
	Current int
	// Max is the configured limit that was exceeded.
	Max int
}

UsageLimitExceededError is returned when a usage limit is hit during an agent run.

func (*UsageLimitExceededError) Error

func (e *UsageLimitExceededError) Error() string

type UsageLimits

type UsageLimits struct {
	// MaxRequestTokens caps the total prompt (input) tokens across all requests.
	MaxRequestTokens *int
	// MaxResponseTokens caps the total completion (output) tokens across all requests.
	MaxResponseTokens *int
	// MaxTotalTokens caps the combined (prompt + completion) tokens across all requests.
	MaxTotalTokens *int
	// MaxRequests caps the number of LLM API requests in a single run.
	// Default is 50 when UsageLimits is set (via DefaultUsageLimits).
	MaxRequests *int
	// MaxToolCalls caps the number of successful tool call executions in a single run.
	MaxToolCalls *int
}

UsageLimits defines caps on token and request usage for an agent run. All fields are pointers — nil means "no limit".

func DefaultUsageLimits

func DefaultUsageLimits() UsageLimits

DefaultUsageLimits returns UsageLimits with only the request limit set (50), matching pydantic-ai's default behavior.

type ValidationError

type ValidationError struct {
	Message string
}

ValidationError signals output validation failed and the model should retry. Return this from a validator to have the agent send the message back to the model and request a new response.

func NewValidationError

func NewValidationError(msg string) *ValidationError

NewValidationError creates a ValidationError with the given message.

func NewValidationErrorf

func NewValidationErrorf(format string, args ...interface{}) *ValidationError

NewValidationErrorf creates a ValidationError with a formatted message.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type VideoURL

type VideoURL = core.VideoURL

Directories

Path Synopsis
examples
basic command
Example: basic agent with no tools.
Example: basic agent with no tools.
internal/envutil
Package envutil provides shared helpers for example programs.
Package envutil provides shared helpers for example programs.
structured command
Example: typed agent with structured output and validation.
Example: typed agent with structured output and validation.
tools command
Example: agent with auto-registered tool.
Example: agent with auto-registered tool.
internal
Package mcp provides Model Context Protocol (MCP) client integration for agentic-go.
Package mcp provides Model Context Protocol (MCP) client integration for agentic-go.
provider
anthropic
Package anthropic provides an Anthropic Model implementation for agentic-go.
Package anthropic provides an Anthropic Model implementation for agentic-go.
azure
Package azure provides an Azure OpenAI Model implementation for agentic-go.
Package azure provides an Azure OpenAI Model implementation for agentic-go.
bedrock
Package bedrock provides an AWS Bedrock Model implementation for agentic-go.
Package bedrock provides an AWS Bedrock Model implementation for agentic-go.
gemini
Package gemini provides a Google Gemini Model implementation for agentic-go.
Package gemini provides a Google Gemini Model implementation for agentic-go.
grok
Package grok provides a Grok (xAI) Model implementation for agentic-go.
Package grok provides a Grok (xAI) Model implementation for agentic-go.
ollama
Package ollama provides an Ollama Model implementation for agentic-go.
Package ollama provides an Ollama Model implementation for agentic-go.
openai
Package openai provides an OpenAI Model implementation for agentic-go.
Package openai provides an OpenAI Model implementation for agentic-go.
openrouter
Package openrouter provides an OpenRouter Model implementation for agentic-go.
Package openrouter provides an OpenRouter Model implementation for agentic-go.
together
Package together provides a Together AI Model implementation for agentic-go.
Package together provides a Together AI Model implementation for agentic-go.
Package tool provides tool definitions, handlers, registries, and toolsets for building LLM-callable tools in agentic-go agents.
Package tool provides tool definitions, handlers, registries, and toolsets for building LLM-callable tools in agentic-go agents.

Jump to

Keyboard shortcuts

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