agent

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package agent provides a convenience layer for building AI agents.

This package is the "Laravel layer" - syntactic sugar that makes building agents as simple as possible while retaining full power.

Quick start (1 line):

agent.Run("You are a helpful assistant.")

Query and get response:

response, err := agent.Query(ctx, "What is 2+2?")

Typed responses:

type Answer struct {
    Result int    `json:"result"`
    Reason string `json:"reason"`
}
answer, err := agent.QueryAs[Answer](ctx, "What is 2+2?")

Fluent builder:

agent.New("assistant").
    Model("opus").
    System("You are helpful.").
    MaxTurns(10).
    Run()

Index

Constants

View Source
const (
	// DefaultModel is the default model used when none is specified.
	DefaultModel = "claude-sonnet-4-20250514"

	// ModelOpus is the most capable model.
	ModelOpus = "claude-opus-4-20250514"

	// ModelSonnet is the balanced model (default).
	ModelSonnet = "claude-sonnet-4-20250514"

	// ModelHaiku is the fastest model.
	ModelHaiku = "claude-haiku-3-5-20241022"
)

Model shortcuts

Variables

View Source
var (
	// ProviderAnthropic is the default Anthropic API.
	ProviderAnthropic = &Provider{
		Name:  "anthropic",
		Model: ModelOpus,
	}

	// ProviderZAI is Z.AI's Claude-compatible API.
	ProviderZAI = &Provider{
		Name:       "zai",
		BaseURL:    "https://api.z.ai/api/anthropic",
		AuthEnvVar: "ZAI_API_KEY",
		Model:      "GLM-4.7",
	}

	// ProviderSynthetic is Synthetic.new's API.
	ProviderSynthetic = &Provider{
		Name:       "synthetic",
		BaseURL:    "https://api.synthetic.new/anthropic",
		AuthEnvVar: "SYNTHETIC_API_KEY",
		Model:      "hf:zai-org/GLM-4.7",
	}
)

Common providers with sensible defaults.

Functions

func AsyncTool

func AsyncTool(name, description string, fn func(context.Context, string) error) *tools.Tool

AsyncTool creates a tool that runs asynchronously and returns immediately. The handler runs in a goroutine and results can be retrieved later.

Example:

downloadTool := agent.AsyncTool("download", "Download a file",
    func(ctx context.Context, url string) error {
        return downloadFile(url)
    },
)

func ExpandModel

func ExpandModel(m string) string

ExpandModel converts a short model name to its full ID. Returns the input unchanged if not a known shortcut.

Example:

ExpandModel("opus")  // "claude-opus-4-20250514"
ExpandModel("sonnet") // "claude-sonnet-4-20250514"
ExpandModel("claude-3-opus") // "claude-3-opus" (unchanged)

func ExtractJSON

func ExtractJSON[T any](response string) (*T, error)

ExtractJSON extracts and parses the first JSON object from an LLM response. Handles common LLM quirks: markdown code blocks, leading text, trailing text.

Example:

type Result struct {
    Answer string `json:"answer"`
}
result, err := agent.ExtractJSON[Result](response)

func ExtractJSONArray

func ExtractJSONArray[T any](response string) ([]T, error)

ExtractJSONArray extracts and parses the first JSON array from an LLM response. Handles common LLM quirks: markdown code blocks, leading text, streaming duplicates.

Example:

type Item struct {
    Name string `json:"name"`
}
items, err := agent.ExtractJSONArray[Item](response)

func ExtractMarkdown

func ExtractMarkdown(content string) string

ExtractMarkdown removes markdown code block wrappers from LLM responses. Handles ```markdown, ```json, and bare ``` wrappers.

Example:

clean := agent.ExtractMarkdown(response)

func Final

func Final(results []StepResult) string

Final returns the final output from a list of step results.

func Must

func Must[T any](val T, err error) T

Must wraps a (T, error) return and panics on error. Useful for scripts where error handling is verbose.

Example:

response := agent.Must(agent.Query(ctx, "Hello"))

func MustExtractJSON

func MustExtractJSON[T any](response string) *T

MustExtractJSON extracts JSON or panics. Use for tests and scripts.

func MustExtractJSONArray

func MustExtractJSONArray[T any](response string) []T

MustExtractJSONArray extracts JSON array or panics. Use for tests and scripts.

func ProviderEnv

func ProviderEnv(p *Provider) map[string]string

ProviderEnv returns environment variables for non-Anthropic providers. Pass to WithClientEnv() when creating a client.

Example:

client, err := agent.NewClient(ctx,
    agent.WithClientModel(agent.ProviderZAI.Model),
    agent.WithClientEnv(agent.ProviderEnv(agent.ProviderZAI)),
)

func Providers

func Providers() map[string]*Provider

Providers returns a map of all built-in providers by name.

func Query

func Query(ctx context.Context, prompt string, opts ...Option) (string, error)

Query sends a single prompt and returns the response. For scripts and one-shot tasks.

Example:

response, err := agent.Query(ctx, "Explain goroutines in one sentence.")

func QueryAs

func QueryAs[T any](ctx context.Context, prompt string, opts ...any) (*T, error)

QueryAs sends a prompt and returns a typed response. The response is parsed as JSON into the type T.

When validation rules are provided via WithValidation(), QueryAs automatically retries up to WithMaxRetries() times (default 3), feeding validation errors back to the LLM for self-correction.

Example (basic):

type Summary struct {
    Title  string   `json:"title"`
    Points []string `json:"points"`
}
summary, err := agent.QueryAs[Summary](ctx, "Summarize this article...")

Example (with validation):

type User struct {
    Age int `json:"age"`
}
user, err := agent.QueryAs[User](ctx, prompt,
    agent.WithValidation(validation.Range("age", 18, 150)),
    agent.WithMaxRetries(3),
)

func QueryJSON

func QueryJSON[T any](c *SimpleClient, ctx context.Context, prompt string) (*T, error)

QueryJSON sends a prompt and parses the response as JSON.

Example:

type Result struct {
    Value int `json:"value"`
}
result, err := c.QueryJSON[Result](ctx, "What is 2+2? Reply as JSON.")

func QueryJSONArray

func QueryJSONArray[T any](c *SimpleClient, ctx context.Context, prompt string) ([]T, error)

QueryJSONArray sends a prompt and parses the response as a JSON array.

func Run

func Run(systemPrompt string, opts ...Option) error

Run starts an interactive agent with the given system prompt. This is the simplest possible entry point.

Example:

agent.Run("You are a helpful coding assistant.")

func SchemaFor

func SchemaFor[T any]() map[string]any

SchemaFor generates a JSON Schema from a Go type using reflection. Supports structs, slices, maps, and primitive types.

Example:

type Response struct {
    Name  string   `json:"name"`
    Count int      `json:"count"`
    Tags  []string `json:"tags"`
}
schema := agent.SchemaFor[Response]()

func SimplePrompt

func SimplePrompt(template string, input string) string

SimplePrompt formats a prompt with a single input placeholder. Convenience for the common case of "template with one %s".

Example:

prompt := agent.SimplePrompt("Summarize:\n\n%s", text)

func SimpleTool

func SimpleTool(name, description string, fn func(string) (string, error)) *tools.Tool

SimpleTool creates a tool with a single string input and output. Perfect for simple transformations or queries.

Example:

reverseTool := agent.SimpleTool("reverse", "Reverse a string",
    func(s string) (string, error) {
        runes := []rune(s)
        for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
            runes[i], runes[j] = runes[j], runes[i]
        }
        return string(runes), nil
    },
)

func State added in v0.6.0

func State[T any](ctx context.Context) *T

State retrieves typed session state from context. Returns nil if no state was set or type doesn't match.

Example:

type Session struct {
    TargetFile string
}

findTool := agent.Tool("find", "Find file", func(ctx context.Context, in FindInput) (string, error) {
    state := agent.State[Session](ctx)
    state.TargetFile = in.Path
    return "Found", nil
})

func Stream

func Stream(ctx context.Context, prompt string, handler func(chunk string), opts ...Option) error

Stream sends a prompt and streams the response chunks.

Example:

err := agent.Stream(ctx, "Write a poem about Go.", func(chunk string) {
    fmt.Print(chunk)
})

func Tool

func Tool[I, O any](name, description string, fn func(context.Context, I) (O, error)) *tools.Tool

Tool creates a type-safe tool with schema inferred from the input type. The input type's JSON schema is automatically generated from struct tags.

Example:

type SearchInput struct {
    Query string `json:"query" desc:"Search query" required:"true"`
    Limit int    `json:"limit" desc:"Max results" max:"100"`
}

type SearchOutput struct {
    Results []string `json:"results"`
}

searchTool := agent.Tool("search", "Search the web",
    func(ctx context.Context, in SearchInput) (SearchOutput, error) {
        results := doSearch(in.Query, in.Limit)
        return SearchOutput{Results: results}, nil
    },
)

func ToolWithSchema

func ToolWithSchema(name, description string, schema map[string]any, fn tools.Handler) *tools.Tool

ToolWithSchema creates a tool with an explicit schema. Use when you need precise control over the schema.

Example:

calcTool := agent.ToolWithSchema("calc", "Calculate expression",
    map[string]any{
        "type": "object",
        "properties": map[string]any{
            "expression": map[string]any{
                "type": "string",
                "pattern": "^[0-9+\\-*/()\\s]+$",
            },
        },
        "required": []string{"expression"},
    },
    func(ctx context.Context, input map[string]any) (any, error) {
        expr := input["expression"].(string)
        return evaluate(expr), nil
    },
)

Types

type Approval

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

Approval represents the result of a permission check.

func Allow

func Allow() Approval

Allow creates an approval that allows the action.

func Deny

func Deny(reason string) Approval

Deny creates an approval that blocks the action.

type Builder

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

Builder provides a fluent interface for configuring agents.

func New

func New(name string) *Builder

New creates a new agent builder with the given name.

Example:

agent.New("code-reviewer").
    Model("opus").
    System("You review code for bugs.").
    Run()

func (*Builder) AlsoAccess

func (b *Builder) AlsoAccess(paths ...string) *Builder

AlsoAccess adds additional directories the agent can access.

func (*Builder) AppendSystem

func (b *Builder) AppendSystem(prompt string) *Builder

AppendSystem appends to the system prompt.

func (*Builder) Apply

func (b *Builder) Apply(opts ...Option) *Builder

Apply applies multiple options at once.

func (*Builder) Beta

func (b *Builder) Beta(features ...string) *Builder

Beta enables experimental beta features.

func (*Builder) BlockTools

func (b *Builder) BlockTools(tools ...string) *Builder

BlockTools prevents the agent from using specific tools (blacklist).

func (*Builder) Budget

func (b *Builder) Budget(usd float64) *Builder

Budget sets a spending limit in USD.

func (*Builder) ClaudeCodeTools

func (b *Builder) ClaudeCodeTools() *Builder

ClaudeCodeTools enables standard Claude Code tools.

func (*Builder) Context

func (b *Builder) Context(files ...string) *Builder

Context adds files to the agent's context.

func (*Builder) Continue

func (b *Builder) Continue() *Builder

Continue resumes the most recent session.

func (*Builder) Env

func (b *Builder) Env(vars map[string]string) *Builder

Env sets environment variables for the agent subprocess.

func (*Builder) Fallback

func (b *Builder) Fallback(m string) *Builder

Fallback sets a fallback model if primary is unavailable.

func (*Builder) Fork

func (b *Builder) Fork(sessionID string) *Builder

Fork creates a branched conversation from a session.

func (*Builder) MaxThinking

func (b *Builder) MaxThinking(tokens int) *Builder

MaxThinking limits thinking tokens.

func (*Builder) MaxTurns

func (b *Builder) MaxTurns(n int) *Builder

MaxTurns limits the number of conversation turns.

func (*Builder) Model

func (b *Builder) Model(m string) *Builder

Model sets the AI model. Accepts shortcuts: "opus", "sonnet", "haiku".

Example:

agent.New("app").Model("opus")        // claude-opus-4-20250514
agent.New("app").Model("sonnet")      // claude-sonnet-4-20250514
agent.New("app").Model("haiku")       // claude-haiku-3-5-20241022

func (*Builder) OnPostToolUse

func (b *Builder) OnPostToolUse(fn func(tool string, result any)) *Builder

OnPostToolUse registers a hook called after each tool use.

func (*Builder) OnPreToolUse

func (b *Builder) OnPreToolUse(fn func(tool string, input map[string]any) bool) *Builder

OnPreToolUse registers a hook called before each tool use. Return false to block the tool call.

func (*Builder) OnSessionEnd

func (b *Builder) OnSessionEnd(fn func(sessionID string)) *Builder

OnSessionEnd registers a hook called when a session ends.

func (*Builder) OnSessionStart

func (b *Builder) OnSessionStart(fn func(sessionID string)) *Builder

OnSessionStart registers a hook called when a session starts.

func (*Builder) OnlyTools

func (b *Builder) OnlyTools(tools ...string) *Builder

OnlyTools restricts the agent to specific tools (whitelist).

func (*Builder) OutputSchema

func (b *Builder) OutputSchema(schema map[string]any) *Builder

OutputSchema sets a JSON schema for structured output.

func (*Builder) PermissionMode

func (b *Builder) PermissionMode(mode PermissionMode) *Builder

PermissionMode sets how permissions are handled.

func (*Builder) Query

func (b *Builder) Query(ctx context.Context, prompt string) (string, error)

Query sends a prompt and returns the response.

func (*Builder) QueryResponse added in v0.5.0

func (b *Builder) QueryResponse(ctx context.Context, prompt string) (*Response, error)

QueryResponse sends a prompt and returns a rich response with metadata.

func (*Builder) RequireApproval

func (b *Builder) RequireApproval(fn func(tool string, input map[string]any) Approval) *Builder

RequireApproval sets a callback for runtime tool approval.

func (*Builder) Resume

func (b *Builder) Resume(sessionID string) *Builder

Resume continues a previous session.

func (*Builder) Run

func (b *Builder) Run() error

Run starts the agent interactively.

func (*Builder) SDKOption

func (b *Builder) SDKOption(opt claude.ClientOption) *Builder

SDKOption adds a raw SDK option for advanced use cases.

func (*Builder) State added in v0.6.0

func (b *Builder) State(state any) *Builder

State sets session state that tools can access via agent.State[T](ctx). The state pointer is shared across all tool invocations.

Example:

type Session struct { Files []string }
session := &Session{}
agent.New("finder").State(session).Tool(findTool).Run()

func (*Builder) Stream

func (b *Builder) Stream(ctx context.Context, prompt string, handler func(chunk string)) error

Stream sends a prompt and streams the response.

func (*Builder) StreamPartial

func (b *Builder) StreamPartial() *Builder

StreamPartial includes partial/incomplete messages in streams.

func (*Builder) String

func (b *Builder) String() string

Print utility for debugging builder state

func (*Builder) System

func (b *Builder) System(prompt string) *Builder

System sets the system prompt.

func (*Builder) Timeout

func (b *Builder) Timeout(d time.Duration) *Builder

Timeout sets the operation timeout.

func (*Builder) Tool

func (b *Builder) Tool(t *tools.Tool) *Builder

Tool adds a tool to the agent.

func (*Builder) TrackFiles

func (b *Builder) TrackFiles() *Builder

TrackFiles enables file change tracking for rollback.

func (*Builder) User

func (b *Builder) User(userID string) *Builder

User sets a user identifier for multi-tenant tracking.

func (*Builder) Version

func (b *Builder) Version(v string) *Builder

Version sets the agent version.

func (*Builder) WorkDir

func (b *Builder) WorkDir(path string) *Builder

WorkDir sets the working directory.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures a SimpleClient.

func WithClientEnv

func WithClientEnv(env map[string]string) ClientOption

WithClientEnv sets environment variables (for provider config).

func WithClientModel

func WithClientModel(m string) ClientOption

WithClientModel sets the model for the client.

func WithClientRetry

func WithClientRetry() ClientOption

WithClientRetry enables retry with exponential backoff.

func WithClientSystem

func WithClientSystem(prompt string) ClientOption

WithClientSystem sets the system prompt.

type Option

type Option func(*Builder)

Option is a functional option for configuring builders.

func WithBudget

func WithBudget(usd float64) Option

WithBudget sets a spending limit.

func WithContext

func WithContext(files ...string) Option

WithContext adds context files.

func WithEnv

func WithEnv(vars map[string]string) Option

WithEnv sets environment variables.

func WithMaxTurns

func WithMaxTurns(n int) Option

WithMaxTurns limits conversation turns.

func WithModel

func WithModel(m string) Option

WithModel sets the AI model.

func WithState added in v0.6.0

func WithState[T any](state *T) Option

WithState sets session state that tools can access via State[T](ctx). The state pointer is shared across all tool invocations in a session.

Example:

type Session struct {
    Files []string
}

session := &Session{}
agent.Run("Help me find files",
    agent.WithState(session),
    agent.WithTool(findTool),
)
// After run, session.Files contains found files

func WithSystem

func WithSystem(prompt string) Option

WithSystem sets the system prompt.

func WithTool

func WithTool(t *tools.Tool) Option

WithTool adds a tool.

func WithWorkDir

func WithWorkDir(path string) Option

WithWorkDir sets the working directory.

type PermissionMode

type PermissionMode string

Permission modes

const (
	// PermissionDefault asks for permission on each action.
	PermissionDefault PermissionMode = "default"

	// PermissionAcceptEdits auto-accepts file edits.
	PermissionAcceptEdits PermissionMode = "acceptEdits"

	// PermissionBypass skips all permission checks.
	PermissionBypass PermissionMode = "bypassPermissions"

	// PermissionPlan enables plan mode.
	PermissionPlan PermissionMode = "plan"
)

type Pipeline

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

Pipeline chains multiple LLM calls, passing output from each step as input to the next. This is common in spec (5-layer snowflake) and learn (extract → filter → format).

Example:

result, err := agent.NewPipeline(client).
    Step("extract", extractPrompt).
    Step("refine", refinePrompt).
    Step("polish", polishPrompt).
    Run(ctx, input)

func NewPipeline

func NewPipeline(client *SimpleClient) *Pipeline

NewPipeline creates a new pipeline with the given client.

func (*Pipeline) OnError

func (p *Pipeline) OnError(handler func(name string, err error) (fallback string, skip bool)) *Pipeline

OnError sets an error handler for all steps. The handler can return a fallback value and whether to skip to next step. If skip is false and fallback is empty, the error propagates.

Example:

pipeline.OnError(func(name string, err error) (string, bool) {
    log.Printf("Step %s failed: %v", name, err)
    return "", true // Skip failed step, continue with previous output
})

func (*Pipeline) OnProgress

func (p *Pipeline) OnProgress(fn func(name string, stepNum, total int)) *Pipeline

OnProgress sets a callback for step progress.

Example:

pipeline.OnProgress(func(name string, step, total int) {
    fmt.Printf("Step %d/%d: %s\n", step, total, name)
})

func (*Pipeline) Run

func (p *Pipeline) Run(ctx context.Context, input string) (string, error)

Run executes the pipeline with the given initial input. Each step receives the output of the previous step as input.

func (*Pipeline) RunWithResults

func (p *Pipeline) RunWithResults(ctx context.Context, input string) ([]StepResult, error)

RunWithResults executes the pipeline and returns all intermediate results.

func (*Pipeline) Step

func (p *Pipeline) Step(name, template string) *Pipeline

Step adds a step with a static prompt template. Use %s as placeholder for the input from the previous step.

Example:

pipeline.Step("extract", "Extract key points from:\n\n%s")

func (*Pipeline) StepFunc

func (p *Pipeline) StepFunc(name string, builder func(input string) string) *Pipeline

StepFunc adds a step with a dynamic prompt builder. Use when the prompt needs complex construction.

Example:

pipeline.StepFunc("analyze", func(input string) string {
    return fmt.Sprintf("Analyze this code:\n```\n%s\n```", input)
})

func (*Pipeline) StepWithPost

func (p *Pipeline) StepWithPost(name, template string, post func(string) string) *Pipeline

StepWithPost adds a step with output post-processing. The post function transforms the LLM output before passing to the next step.

Example:

pipeline.StepWithPost("extract", template, agent.ExtractMarkdown)

type PromptRegistry

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

PromptRegistry manages prompt templates with embed + runtime override support. Priority: runtime (~/.config/<app>/prompts/) > embedded > error

Example:

//go:embed prompts/*.prompt
var promptsFS embed.FS

prompts := agent.NewPromptRegistry("myapp", promptsFS)
text, err := prompts.Render("extraction", map[string]any{"input": data})

func NewPromptRegistry

func NewPromptRegistry(appName string, embedded embed.FS) *PromptRegistry

NewPromptRegistry creates a prompt registry. appName is used for runtime config path: ~/.config/<appName>/prompts/ embedded is the embed.FS containing *.prompt files.

func (*PromptRegistry) Format

func (r *PromptRegistry) Format(name string, args ...any) (string, error)

Format is a simpler alternative using fmt.Sprintf. Use when templates are overkill.

Example:

text, err := prompts.Format("simple", userInput)

func (*PromptRegistry) List

func (r *PromptRegistry) List() []string

List returns all available prompt names.

func (*PromptRegistry) Load

func (r *PromptRegistry) Load(name string) (string, error)

Load retrieves a prompt template by name (without .prompt extension). Checks runtime directory first, then embedded.

func (*PromptRegistry) MustFormat

func (r *PromptRegistry) MustFormat(name string, args ...any) string

MustFormat formats a prompt or panics.

func (*PromptRegistry) MustLoad

func (r *PromptRegistry) MustLoad(name string) string

MustLoad loads a prompt or panics. Use during init.

func (*PromptRegistry) MustRender

func (r *PromptRegistry) MustRender(name string, data any) string

MustRender renders a prompt or panics.

func (*PromptRegistry) Render

func (r *PromptRegistry) Render(name string, data any) (string, error)

Render loads a prompt and executes it as a Go template.

Example:

text, err := prompts.Render("extraction", map[string]any{
    "input": userInput,
    "maxItems": 10,
})

type Provider

type Provider struct {
	Name       string // Display name
	BaseURL    string // API base URL (empty = default)
	AuthEnvVar string // Environment variable for auth token
	Model      string // Default model for this provider
}

Provider represents an LLM API provider configuration. Use for multi-provider support (Anthropic, Z.AI, Synthetic, etc.)

func GetProvider

func GetProvider(name string) *Provider

GetProvider returns a provider by name, or nil if not found.

type QueryOption added in v0.6.0

type QueryOption func(*queryOptions)

QueryOption configures QueryAs behavior.

func WithMaxRetries added in v0.6.0

func WithMaxRetries(n int) QueryOption

WithMaxRetries sets the maximum number of retry attempts when validation fails. Default is 3. Set to 0 for no retries.

Example:

user, err := agent.QueryAs[User](ctx, prompt,
    agent.WithValidation(validation.Required("name")),
    agent.WithMaxRetries(5),
)

func WithValidation added in v0.6.0

func WithValidation(rules ...validation.Rule) QueryOption

WithValidation adds validation rules to check the parsed response. If validation fails, the error is fed back to the LLM for retry.

Example:

type User struct {
    Age int `json:"age"`
}

user, err := agent.QueryAs[User](ctx, prompt,
    agent.WithValidation(validation.Range("age", 18, 150)),
)

type Response added in v0.5.0

type Response struct {
	// Content is the raw text response
	Content string

	// Usage contains token consumption details
	Usage *TokenUsage

	// ToolCalls lists tools that were invoked during this response
	ToolCalls []ToolCall

	// Model is the model that generated this response
	Model string

	// SessionID for conversation continuity
	SessionID string
}

Response wraps an agent response with metadata and helper methods.

func QueryResponse added in v0.5.0

func QueryResponse(ctx context.Context, prompt string, opts ...Option) (*Response, error)

QueryResponse sends a prompt and returns a rich response with metadata.

Example:

resp, err := agent.QueryResponse(ctx, "What is 2+2?")
if err != nil {
    log.Fatal(err)
}
fmt.Println(resp.Content)
if resp.Usage != nil {
    fmt.Printf("Tokens: %d\n", resp.Usage.TotalTokens)
}

func (*Response) Bytes added in v0.5.0

func (r *Response) Bytes() []byte

Bytes returns content as byte slice.

func (*Response) Contains added in v0.5.0

func (r *Response) Contains(s string) bool

Contains checks if content contains substring.

func (*Response) HasToolCalls added in v0.5.0

func (r *Response) HasToolCalls() bool

HasToolCalls returns true if any tools were called.

func (*Response) IsEmpty added in v0.5.0

func (r *Response) IsEmpty() bool

IsEmpty returns true if content is empty or whitespace only.

func (*Response) JSON added in v0.5.0

func (r *Response) JSON(v any) error

JSON unmarshals the content into the provided value.

func (*Response) Lines added in v0.5.0

func (r *Response) Lines() []string

Lines returns content split by newlines.

func (*Response) SaveTo added in v0.5.0

func (r *Response) SaveTo(path string) error

SaveTo writes the content to a file.

func (*Response) String added in v0.5.0

func (r *Response) String() string

String returns the content (implements fmt.Stringer).

func (*Response) ToolCallsByName added in v0.5.0

func (r *Response) ToolCallsByName(name string) []ToolCall

ToolCallsByName returns tool calls matching the given name.

type SimpleClient

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

SimpleClient provides direct LLM access without the full app.App machinery. Use for pipeline tools, scripts, and batch processing.

func NewClient

func NewClient(ctx context.Context, opts ...ClientOption) (*SimpleClient, error)

NewClient creates a SimpleClient for direct LLM queries. This is lighter weight than app.New() - no CLI, no tools, just queries.

Example:

c, err := agent.NewClient(ctx,
    agent.WithClientModel("opus"),
    agent.WithClientSystem("You are helpful."),
    agent.WithClientRetry(),
)
defer c.Close()
response, err := c.Query(ctx, "Hello")

func (*SimpleClient) Close

func (c *SimpleClient) Close() error

Close releases resources.

func (*SimpleClient) Model

func (c *SimpleClient) Model() string

Model returns the model being used.

func (*SimpleClient) Query

func (c *SimpleClient) Query(ctx context.Context, prompt string) (string, error)

Query sends a prompt and returns the response.

type StepResult

type StepResult struct {
	Name    string
	Input   string
	Output  string
	Error   error
	Skipped bool
}

StepResult holds the result of a single pipeline step.

type TokenUsage added in v0.5.0

type TokenUsage struct {
	InputTokens  int
	OutputTokens int
	TotalTokens  int
	// CostUSD is estimated cost (optional, may be 0)
	CostUSD float64
}

TokenUsage tracks token consumption.

type ToolCall added in v0.5.0

type ToolCall struct {
	Name   string
	Input  map[string]any
	Output any
	Error  error
}

ToolCall records a tool invocation.

Jump to

Keyboard shortcuts

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