agent

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ProviderOpenAI    = "openai"
	ProviderAnthropic = "anthropic"
	ProviderOllama    = "ollama"
	ProviderGoogle    = "google"
	ProviderXAI       = "xai"
	ProviderGroq      = "groq"
)

Provider constants for supported LLM providers.

Variables

This section is empty.

Functions

func ContextWithEventCh

func ContextWithEventCh(ctx context.Context, ch chan<- ReactEvent) context.Context

ContextWithEventCh injects an event channel into the context.

func DetectProvider

func DetectProvider(model string) string

DetectProvider infers the provider from the model name. This follows well-known model naming conventions.

func EventChFromContext

func EventChFromContext(ctx context.Context) chan<- ReactEvent

EventChFromContext extracts the event channel from context, if any.

func InitModel

func InitModel(cfg ModelConfig) (llms.Model, error)

InitModel creates an llms.Model from the given config. This is the universal model factory that routes to the correct provider.

func IsAnthropicModel

func IsAnthropicModel(model string) bool

IsAnthropicModel returns true if the model string refers to an Anthropic Claude model.

func IsReasoningModel

func IsReasoningModel(model string) bool

IsReasoningModel returns true if the model is known to support reasoning/thinking tokens.

func NewVFSTools

func NewVFSTools(b Backend) []interface{}

NewVFSTools creates all VFS tools for a given backend.

func NormalizeToolSchema

func NormalizeToolSchema(params map[string]any) map[string]any

NormalizeToolSchema ensures a tool parameter schema is valid for Anthropic's API. Anthropic requires:

  • Parameters must be a JSON Schema object with "type": "object"
  • Properties must be a dict, not null
  • Required must be an array (can be empty)

This is the Go equivalent of the Zod v4 schema normalization issue — different providers serialize schemas differently, and Anthropic is the strictest.

func ParseModelString

func ParseModelString(s string) (provider, model string)

ParseModelString splits a "provider:model" string into provider and model. If no provider prefix, returns empty provider (will be auto-detected).

Examples:

"gpt-4.1"                            → ("", "gpt-4.1")
"openai:gpt-4.1"                     → ("openai", "gpt-4.1")
"anthropic:claude-sonnet-4-5-20250929" → ("anthropic", "claude-sonnet-4-5-20250929")
"ollama:llama3"                       → ("ollama", "llama3")
"google:gemini-2.5-flash"             → ("google", "gemini-2.5-flash")

func SanitizeContentForAnthropic

func SanitizeContentForAnthropic(content string) string

SanitizeContentForAnthropic ensures message content follows Anthropic's rules:

  • System messages must be plain strings, not arrays
  • Tool results must have non-empty content
  • Empty text blocks should be removed from multi-part messages

func SanitizeToolCallInput

func SanitizeToolCallInput(input string) string

SanitizeToolCallInput fixes the known Anthropic issue where tool call input is returned as an empty string "" instead of an empty object "{}". This happens when a tool has no required parameters.

func TaskToolDef

func TaskToolDef(subAgents []AgentConfig) llms.Tool

TaskToolDef returns the llms.Tool definition for the task tool. This is used when building tool definitions for the parent agent's LLM call.

Types

type AgentConfig

type AgentConfig struct {
	// Identity
	Name        string // unique name: "orchestrator", "researcher", "coder"
	Description string // shown to parent agent for routing decisions

	// Prompt — REQUIRED. User's base prompt. Gets concatenated with governance prompts.
	// Final prompt = [governance base] + [governance tool usage] + [Prompt] + [loaded skills] + [sub-agent descriptions]
	Prompt string

	// Model configuration — supports "provider:model" format (e.g. "anthropic:claude-sonnet-4-5-20250929")
	// If Provider is empty, it is auto-detected from Model string.
	Provider    string  // explicit provider: "openai", "anthropic", "ollama", "google" (optional)
	Model       string  // model name or "provider:model" format
	APIKey      string  // provider API key (falls back to env vars if empty)
	BaseURL     string  // optional custom API base URL
	Temperature float64 // 0.0 - 1.0

	// Capabilities
	Tools   []tools.Tool // langchaingo standard tool interface
	Skills  []Skill      // loaded skill definitions (constructed, not paths)
	MaxIter int          // max ReAct loop iterations (0 = default 25)

	// Recursive — sub-agents use the SAME struct
	SubAgents []AgentConfig

	// Infrastructure (typically set at top-level, inherited downward)
	Middleware []Middleware
	Backend    Backend
	Store      Store
	Governance *Governance // nil = use package defaults

	// Flexible key-value config per agent
	Config map[string]any
}

AgentConfig is the recursive configuration for any agent — top-level or sub-agent. The same struct is used at every level of the hierarchy.

func (AgentConfig) Defaults

func (cfg AgentConfig) Defaults() AgentConfig

Defaults returns a copy of cfg with zero values replaced by sensible defaults.

type AnthropicSanitizeMiddleware

type AnthropicSanitizeMiddleware struct {
	BaseMiddleware
}

AnthropicSanitizeMiddleware fixes known Anthropic/Claude API quirks:

  1. tool_use.input: "" → {} — Claude sometimes returns empty string instead of empty object for tool calls with no parameters. Anthropic API rejects this with "messages.N.content.N.tool_use.input: Input should be a valid dictionary"

  2. Empty content blocks — Claude occasionally produces empty text blocks alongside tool_use blocks, which can cause issues on subsequent API calls.

  3. Tool parameter schema normalization — ensures all tool parameters have proper JSON Schema format with "type": "object" wrapper, which is required by Anthropic but optional for OpenAI.

This middleware should be added automatically when an Anthropic model is detected.

func NewAnthropicSanitizeMiddleware

func NewAnthropicSanitizeMiddleware() *AnthropicSanitizeMiddleware

func (*AnthropicSanitizeMiddleware) AfterToolCall

func (m *AnthropicSanitizeMiddleware) AfterToolCall(ctx *ToolCallContext) error

AfterToolCall sanitizes tool output before it's sent back to Claude. Ensures the output is never empty (Claude rejects empty tool results).

func (*AnthropicSanitizeMiddleware) Name

type App

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

App is the top-level agent runtime. It wires together the orchestrator agent, sub-agents, VFS backend, middleware, store, and governance prompts. If a Store is provided (or defaulted to in-memory), conversation history is managed automatically via threads.

func New

func New(cfg AgentConfig, apiKey string) (*App, error)

New creates a new agent application from the given config. The config is recursive: the top-level agent and all sub-agents use the same AgentConfig struct. If Store is nil, an in-memory store is created automatically.

func (*App) Config

func (a *App) Config() AgentConfig

Config returns the resolved agent config.

func (*App) CreateThread

func (a *App) CreateThread(ctx context.Context, cfg ThreadConfig) (string, error)

CreateThread creates a new conversation thread. If cfg.ThreadID is empty, a UUID is generated. If cfg.UserID is set, it's stored in metadata["user_id"].

func (*App) DeleteThread

func (a *App) DeleteThread(ctx context.Context, threadID string) error

DeleteThread removes a thread.

func (*App) GetLatestCheckpoint

func (a *App) GetLatestCheckpoint(ctx context.Context, threadID string) (*protocol.Checkpoint, error)

GetLatestCheckpoint returns the most recent checkpoint for a thread.

func (*App) GetThread

func (a *App) GetThread(ctx context.Context, threadID string) (*protocol.Thread, error)

GetThread returns a thread with its full message history.

func (*App) ListCheckpoints

func (a *App) ListCheckpoints(ctx context.Context, threadID string, limit int) ([]*protocol.Checkpoint, error)

ListCheckpoints returns checkpoints for a thread (newest first).

func (*App) ListThreads

func (a *App) ListThreads(ctx context.Context, userID string, limit, offset int) ([]*protocol.Thread, error)

ListThreads returns threads for a given user.

func (*App) Process

func (a *App) Process(ctx context.Context, input string) (string, error)

Process runs a single input through the agent (stateless, no history).

func (*App) ProcessWithHistory

func (a *App) ProcessWithHistory(ctx context.Context, input string, history []llms.MessageContent) (*ReactResult, error)

ProcessWithHistory runs input with explicit conversation history.

func (*App) ProcessWithHistoryAndEvents

func (a *App) ProcessWithHistoryAndEvents(ctx context.Context, input string, history []llms.MessageContent, eventCh chan<- ReactEvent) (*ReactResult, error)

ProcessWithHistoryAndEvents runs input with explicit history and emits streaming events.

func (*App) Send

func (a *App) Send(ctx context.Context, threadID, input string) (*ReactResult, error)

Send sends a message on an existing thread. It loads conversation history from the store, runs the agent, appends both user and assistant messages, and saves a checkpoint with parent chain.

func (*App) SendWithEvents

func (a *App) SendWithEvents(ctx context.Context, threadID, input string, eventCh chan<- ReactEvent) (*ReactResult, error)

SendWithEvents is like Send but emits streaming events.

func (*App) Store

func (a *App) Store() Store

Store returns the underlying store for advanced usage.

type Backend

type Backend interface {
	afero.Fs
	Grep(pattern, path string) ([]GrepMatch, error)
	Summarize(path string) (string, error) // LLM-powered file summary
}

Backend is the VFS interface agents use for persistent context. Built on top of afero.Fs with agent-specific extensions.

func CompositeBackendFrom

func CompositeBackendFrom(routes ...CompositeRoute) Backend

CompositeBackendFrom creates a backend that routes operations based on path prefix. The first matching route wins. Unmatched paths go to the default (first route).

func DiskBackend

func DiskBackend(dir string) Backend

DiskBackend returns a real filesystem backend rooted at dir. For CLI / development use. Use with caution in production.

func MemoryBackend

func MemoryBackend() Backend

MemoryBackend returns an in-memory afero filesystem. Fast, ephemeral — persists within a thread via checkpoints.

func ReadOnlyBackend

func ReadOnlyBackend(inner Backend) Backend

ReadOnlyBackend wraps a backend to prevent writes. Useful for mounting skills directories.

type BaseMiddleware

type BaseMiddleware struct{}

BaseMiddleware provides no-op defaults for all Middleware methods. Embed this in your middleware to only override what you need.

func (BaseMiddleware) AfterInvoke

func (BaseMiddleware) AfterInvoke(*InvokeContext) error

func (BaseMiddleware) AfterToolCall

func (BaseMiddleware) AfterToolCall(*ToolCallContext) error

func (BaseMiddleware) BeforeInvoke

func (BaseMiddleware) BeforeInvoke(*InvokeContext) error

func (BaseMiddleware) BeforeToolCall

func (BaseMiddleware) BeforeToolCall(*ToolCallContext) error

func (BaseMiddleware) Init

func (BaseMiddleware) Init(map[string]any) error

func (BaseMiddleware) SystemPrompt

func (BaseMiddleware) SystemPrompt() string

func (BaseMiddleware) Tools

func (BaseMiddleware) Tools() []ToolDef

type CompositeRoute

type CompositeRoute struct {
	Prefix  string
	Backend Backend
}

CompositeRoute maps a path prefix to a backend.

func Route

func Route(prefix string, b Backend) CompositeRoute

Route is a shorthand for CompositeRoute.

type EditFileTool

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

EditFileTool performs find-and-replace in a file.

func NewEditFileTool

func NewEditFileTool(b Backend) *EditFileTool

func (*EditFileTool) Call

func (t *EditFileTool) Call(ctx context.Context, input string) (string, error)

func (*EditFileTool) Description

func (t *EditFileTool) Description() string

func (*EditFileTool) Name

func (t *EditFileTool) Name() string

type GlobTool

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

GlobTool finds files matching a pattern.

func NewGlobTool

func NewGlobTool(b Backend) *GlobTool

func (*GlobTool) Call

func (t *GlobTool) Call(ctx context.Context, input string) (string, error)

func (*GlobTool) Description

func (t *GlobTool) Description() string

func (*GlobTool) Name

func (t *GlobTool) Name() string

type Governance

type Governance struct {
	Base              string // always prepended
	ToolUsage         string // when agent has tools
	ContextManagement string // when VFS backend is available
	Planning          string // when agent has sub-agents
	Aggregation       string // for result synthesis
	SubAgentDefault   string // default sub-agent governance
}

Governance holds the system prompts that govern agent behavior. These are concatenated BEFORE the user's Prompt field.

func DefaultGovernance

func DefaultGovernance() *Governance

DefaultGovernance loads the embedded governance prompts shipped with the package.

func GovernanceFromDir

func GovernanceFromDir(dir string) *Governance

GovernanceFromDir loads governance prompts from a directory on disk.

func (*Governance) BuildSystemPrompt

func (g *Governance) BuildSystemPrompt(cfg AgentConfig, middlewarePrompt string) string

BuildSystemPrompt assembles the final system prompt for an agent.

func (*Governance) Override

func (g *Governance) Override(name, content string) *Governance

Override returns a copy with the named prompt replaced.

type GrepMatch

type GrepMatch struct {
	Path string `json:"path"`
	Line int    `json:"line"`
	Text string `json:"text"`
}

GrepMatch represents a single grep result.

type GrepTool

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

GrepTool searches for a pattern in files.

func NewGrepTool

func NewGrepTool(b Backend) *GrepTool

func (*GrepTool) Call

func (t *GrepTool) Call(ctx context.Context, input string) (string, error)

func (*GrepTool) Description

func (t *GrepTool) Description() string

func (*GrepTool) Name

func (t *GrepTool) Name() string

type InvokeContext

type InvokeContext struct {
	AgentName string
	Iteration int
	ThreadID  string
	RunID     string
	Input     string
	Output    string
	Metadata  map[string]any
	Stop      bool // middleware can set this to halt execution
}

InvokeContext is passed through the middleware chain on every LLM call.

type LoggingMiddleware

type LoggingMiddleware struct {
	BaseMiddleware
	// contains filtered or unexported fields
}

LoggingMiddleware logs every invoke and tool call with timing information.

func NewLoggingMiddleware

func NewLoggingMiddleware() *LoggingMiddleware

func (*LoggingMiddleware) AfterInvoke

func (m *LoggingMiddleware) AfterInvoke(ctx *InvokeContext) error

func (*LoggingMiddleware) AfterToolCall

func (m *LoggingMiddleware) AfterToolCall(ctx *ToolCallContext) error

func (*LoggingMiddleware) BeforeInvoke

func (m *LoggingMiddleware) BeforeInvoke(ctx *InvokeContext) error

func (*LoggingMiddleware) BeforeToolCall

func (m *LoggingMiddleware) BeforeToolCall(ctx *ToolCallContext) error

func (*LoggingMiddleware) Name

func (m *LoggingMiddleware) Name() string

type LsTool

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

LsTool lists files and directories at a given path.

func NewLsTool

func NewLsTool(b Backend) *LsTool

func (*LsTool) Call

func (t *LsTool) Call(ctx context.Context, input string) (string, error)

func (*LsTool) Description

func (t *LsTool) Description() string

func (*LsTool) Name

func (t *LsTool) Name() string

type Middleware

type Middleware interface {
	Name() string
	Init(cfg map[string]any) error
	BeforeInvoke(ctx *InvokeContext) error
	AfterInvoke(ctx *InvokeContext) error
	BeforeToolCall(ctx *ToolCallContext) error
	AfterToolCall(ctx *ToolCallContext) error
	Tools() []ToolDef     // middleware can inject its own tools
	SystemPrompt() string // appended to the agent's system prompt
}

Middleware intercepts agent execution at key points. Implement only the hooks you need — all methods have no-op defaults via BaseMiddleware.

type MiddlewareChain

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

MiddlewareChain runs a slice of middleware in order.

func NewMiddlewareChain

func NewMiddlewareChain(mws ...Middleware) *MiddlewareChain

func (*MiddlewareChain) CollectExecutableTools

func (c *MiddlewareChain) CollectExecutableTools() []tools.Tool

CollectExecutableTools gathers executable tool implementations from middleware that implement the ToolProvider interface.

func (*MiddlewareChain) CollectSystemPrompts

func (c *MiddlewareChain) CollectSystemPrompts() string

CollectSystemPrompts gathers all system prompt additions from middleware.

func (*MiddlewareChain) CollectTools

func (c *MiddlewareChain) CollectTools() []ToolDef

CollectTools gathers all tools injected by middleware.

func (*MiddlewareChain) RunAfterInvoke

func (c *MiddlewareChain) RunAfterInvoke(ctx *InvokeContext) error

func (*MiddlewareChain) RunAfterToolCall

func (c *MiddlewareChain) RunAfterToolCall(ctx *ToolCallContext) error

func (*MiddlewareChain) RunBeforeInvoke

func (c *MiddlewareChain) RunBeforeInvoke(ctx *InvokeContext) error

func (*MiddlewareChain) RunBeforeToolCall

func (c *MiddlewareChain) RunBeforeToolCall(ctx *ToolCallContext) error

type ModelConfig

type ModelConfig struct {
	Provider string // "openai", "anthropic", "ollama", "google" — auto-detected if empty
	Model    string // model name, or "provider:model" format (e.g. "anthropic:claude-sonnet-4-5-20250929")
	APIKey   string // provider API key — falls back to env vars if empty
	BaseURL  string // custom base URL (useful for proxies, Azure, local endpoints)

	// Provider-specific options
	OllamaServerURL string         // Ollama server URL (default: http://localhost:11434)
	Options         map[string]any // additional provider-specific options
}

ModelConfig holds provider-agnostic model configuration. It supports both explicit provider setting and the "provider:model" shorthand.

type ReactEvent

type ReactEvent struct {
	Type      ReactEventType
	Agent     string
	Iteration int
	ToolName  string
	ToolInput string
	Content   string // LLM output or tool output
}

ReactEvent is emitted during the ReAct loop for streaming.

type ReactEventType

type ReactEventType string

ReactEventType identifies the kind of streaming event.

const (
	EventIterationStart ReactEventType = "iteration_start"
	EventLLMResponse    ReactEventType = "llm_response"
	EventToolStart      ReactEventType = "tool_start"
	EventToolEnd        ReactEventType = "tool_end"
	EventFinalAnswer    ReactEventType = "final_answer"
)

type ReactExecutor

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

ReactExecutor runs the ReAct (Reasoning + Acting) loop for a single agent. It sends messages to the LLM, handles tool calls, and loops until the LLM produces a final text answer or MaxIter is reached.

func NewReactExecutor

func NewReactExecutor(cfg AgentConfig, apiKey string) (*ReactExecutor, error)

NewReactExecutor creates an executor for the given agent config. The apiKey parameter is a fallback — cfg.APIKey takes precedence if set.

func (*ReactExecutor) Run

func (r *ReactExecutor) Run(ctx context.Context, input string, history []llms.MessageContent) (*ReactResult, error)

Run executes the ReAct loop with the given input and optional conversation history.

func (*ReactExecutor) RunWithEvents

func (r *ReactExecutor) RunWithEvents(ctx context.Context, input string, history []llms.MessageContent, eventCh chan<- ReactEvent) (*ReactResult, error)

RunWithEvents executes the ReAct loop and emits streaming events to the channel. Events are emitted for each iteration start, LLM response, tool start/end, and final answer.

type ReactResult

type ReactResult struct {
	Output     string
	ToolCalls  int
	Iterations int
	Duration   time.Duration
}

ReactResult is the output of a ReAct execution loop.

type ReadFileTool

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

ReadFileTool reads file content with optional offset/limit.

func NewReadFileTool

func NewReadFileTool(b Backend) *ReadFileTool

func (*ReadFileTool) Call

func (t *ReadFileTool) Call(ctx context.Context, input string) (string, error)

func (*ReadFileTool) Description

func (t *ReadFileTool) Description() string

func (*ReadFileTool) Name

func (t *ReadFileTool) Name() string

type Skill

type Skill struct {
	Name         string         `yaml:"name"`
	Description  string         `yaml:"description"`
	Instructions string         `yaml:"-"` // the markdown body after frontmatter
	AllowedTools []string       `yaml:"allowed-tools"`
	Metadata     map[string]any `yaml:"metadata"`
}

Skill is a loaded, ready-to-use capability definition. Skills are constructed via factory functions, not raw paths.

func NewSkill

func NewSkill(name, description, instructions string) Skill

NewSkill creates a skill inline from code.

func SkillFromBackend

func SkillFromBackend(backend afero.Fs, path string) (Skill, error)

SkillFromBackend loads a SKILL.md from a VFS backend.

func SkillFromEmbed

func SkillFromEmbed(fsys embed.FS, path string) (Skill, error)

SkillFromEmbed loads a SKILL.md from an embedded filesystem.

func SkillFromFile

func SkillFromFile(path string) (Skill, error)

SkillFromFile loads a SKILL.md from the local filesystem.

func SkillsFromDir

func SkillsFromDir(dir string) ([]Skill, error)

SkillsFromDir loads all SKILL.md files under a directory on disk.

func (Skill) String

func (s Skill) String() string

String returns the full skill content for prompt injection.

type Store

type Store interface {
	// Threads
	CreateThread(ctx context.Context, t *protocol.Thread) error
	GetThread(ctx context.Context, id string) (*protocol.Thread, error)
	DeleteThread(ctx context.Context, id string) error
	SetThreadStatus(ctx context.Context, id string, status protocol.ThreadStatus) error
	AppendMessage(ctx context.Context, threadID string, msg protocol.Message) error
	SearchThreads(ctx context.Context, userID string, limit, offset int) ([]*protocol.Thread, error)

	// Checkpoints
	SaveCheckpoint(ctx context.Context, cp *protocol.Checkpoint) error
	GetLatestCheckpoint(ctx context.Context, threadID string) (*protocol.Checkpoint, error)
	ListCheckpoints(ctx context.Context, threadID string, limit int, before string) ([]*protocol.Checkpoint, error)

	// Runs
	CreateRun(ctx context.Context, r *protocol.Run) error
	GetRun(ctx context.Context, id string) (*protocol.Run, error)
	UpdateRun(ctx context.Context, r *protocol.Run) error
}

Store is the persistence interface for threads, runs, checkpoints. Both MemoryStore and MongoStore implement this.

type SummarizationMiddleware

type SummarizationMiddleware struct {
	BaseMiddleware
	// contains filtered or unexported fields
}

SummarizationMiddleware tracks iteration count and signals when context should be summarized to prevent context window overflow.

func NewSummarizationMiddleware

func NewSummarizationMiddleware(cfg SummarizeConfig) *SummarizationMiddleware

func (*SummarizationMiddleware) AfterInvoke

func (m *SummarizationMiddleware) AfterInvoke(ctx *InvokeContext) error

func (*SummarizationMiddleware) IterationCount

func (m *SummarizationMiddleware) IterationCount() int64

IterationCount returns the current iteration count.

func (*SummarizationMiddleware) Name

func (m *SummarizationMiddleware) Name() string

func (*SummarizationMiddleware) Reset

func (m *SummarizationMiddleware) Reset()

Reset resets the iteration counter.

func (*SummarizationMiddleware) ShouldSummarize

func (m *SummarizationMiddleware) ShouldSummarize() bool

ShouldSummarize returns true when context should be compacted.

func (*SummarizationMiddleware) SystemPrompt

func (m *SummarizationMiddleware) SystemPrompt() string

type SummarizeConfig

type SummarizeConfig struct {
	TriggerAfterMessages int // summarize after this many iterations (default 20)
	MaxContextTokens     int // approximate token limit before summarization (default 50000)
}

SummarizeConfig controls when context summarization triggers.

type TaskTool

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

TaskTool is the tool that allows an agent to spawn sub-agents. This is the core of the recursive architecture — agents delegate work by calling task(description, subagent_type).

func NewTaskTool

func NewTaskTool(subAgents []AgentConfig, apiKey string, sharedBackend Backend) (*TaskTool, error)

NewTaskTool creates a task tool from sub-agent configs. Each sub-agent gets its own ReactExecutor with its own model/tools/skills.

func (*TaskTool) Call

func (t *TaskTool) Call(ctx context.Context, input string) (string, error)

func (*TaskTool) Description

func (t *TaskTool) Description() string

func (*TaskTool) Name

func (t *TaskTool) Name() string

func (*TaskTool) ToolDefinition

func (t *TaskTool) ToolDefinition() llms.Tool

ToolDefinition implements ToolDefiner — returns the proper JSON schema with description + subagent_type parameters instead of generic __arg1.

type ThreadConfig

type ThreadConfig struct {
	ThreadID string                 // explicit thread ID (auto-generated if empty)
	UserID   string                 // user identifier, stored in metadata
	Metadata map[string]interface{} // additional metadata
}

ThreadConfig configures a new thread.

type TodoItem

type TodoItem struct {
	ID      string `json:"id"`
	Content string `json:"content"`
	Status  string `json:"status"` // "pending", "in_progress", "completed"
}

TodoItem represents a single task in the agent's plan.

type TodoListMiddleware

type TodoListMiddleware struct {
	BaseMiddleware
	// contains filtered or unexported fields
}

TodoListMiddleware provides agents with a write_todos tool for planning.

func NewTodoListMiddleware

func NewTodoListMiddleware() *TodoListMiddleware

func (*TodoListMiddleware) ExecutableTools

func (m *TodoListMiddleware) ExecutableTools() []tools.Tool

ExecutableTools implements ToolProvider — returns the executable write_todos tool.

func (*TodoListMiddleware) GetTodos

func (m *TodoListMiddleware) GetTodos() []TodoItem

GetTodos returns a copy of the current todo list.

func (*TodoListMiddleware) Name

func (m *TodoListMiddleware) Name() string

func (*TodoListMiddleware) SystemPrompt

func (m *TodoListMiddleware) SystemPrompt() string

func (*TodoListMiddleware) Tools

func (m *TodoListMiddleware) Tools() []ToolDef

type ToolCallContext

type ToolCallContext struct {
	InvokeContext
	ToolName   string
	ToolInput  string
	ToolOutput string
}

ToolCallContext is passed through the middleware chain on every tool invocation.

type ToolDef

type ToolDef = llms.Tool

ToolDef is a function definition that middleware can inject into an agent's tool set. This is the langchaingo standard llms.Tool — we alias it for convenience.

func NewToolDef

func NewToolDef(name, description string, params map[string]any) ToolDef

NewToolDef creates a standard tool definition from name, description, and JSON Schema parameters.

type ToolDefiner

type ToolDefiner interface {
	ToolDefinition() llms.Tool
}

ToolDefiner is implemented by tools that provide their own JSON schema for LLM function calling, instead of the default __arg1 string pattern. TaskTool implements this to expose description + subagent_type parameters.

type ToolProvider

type ToolProvider interface {
	ExecutableTools() []tools.Tool
}

ToolProvider is an optional interface that middleware can implement to supply executable tool implementations alongside their ToolDef schemas.

type VFSFileInfo

type VFSFileInfo struct {
	Path       string    `json:"path"`
	IsDir      bool      `json:"is_dir"`
	Size       int64     `json:"size"`
	ModifiedAt time.Time `json:"modified_at"`
}

FileInfo is a simplified file metadata struct for tool responses.

type WriteFileTool

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

WriteFileTool writes content to a file, creating parent dirs as needed.

func NewWriteFileTool

func NewWriteFileTool(b Backend) *WriteFileTool

func (*WriteFileTool) Call

func (t *WriteFileTool) Call(ctx context.Context, input string) (string, error)

func (*WriteFileTool) Description

func (t *WriteFileTool) Description() string

func (*WriteFileTool) Name

func (t *WriteFileTool) Name() string

type WriteTodosTool

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

WriteTodosTool is the langchaingo tools.Tool implementation for the todo list.

func NewWriteTodosTool

func NewWriteTodosTool(mw *TodoListMiddleware) *WriteTodosTool

func (*WriteTodosTool) Call

func (t *WriteTodosTool) Call(_ context.Context, input string) (string, error)

func (*WriteTodosTool) Description

func (t *WriteTodosTool) Description() string

func (*WriteTodosTool) Name

func (t *WriteTodosTool) Name() string

Jump to

Keyboard shortcuts

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