agentloop

package
v0.0.14 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const BasePrompt = `` /* 1503-byte string literal not displayed */

BasePrompt is the base system prompt for the agent.

Variables

This section is empty.

Functions

func ArrayParam

func ArrayParam(desc string, elemInfo *schema.ParameterInfo, required bool) *schema.ParameterInfo

ArrayParam creates an array parameter with element info.

func BoolParam

func BoolParam(desc string, required bool) *schema.ParameterInfo

BoolParam creates a boolean parameter.

func BuildPreloadedSkills

func BuildPreloadedSkills(efs embed.FS, baseDirs ...string) map[string]string

BuildPreloadedSkills builds a PreloadedSkills map from an embedded filesystem. The baseDirs are the root directories within the embedded FS to start from. File paths in the returned map will be relative to the baseDir and prefixed with '/'.

Example:

//go:embed skills/*
var skillsFS embed.FS

preloaded := BuildPreloadedSkills(skillsFS, "skills")
// Returns: map[string]string{
//   "/skills/web-research/SKILL.md": "...",
//   "/skills/code-analysis/SKILL.md": "...",
// }

Multiple base dirs:

preloaded := BuildPreloadedSkills(skillsFS, "skills", "templates")

func BuildPreloadedSkillsWithFilter

func BuildPreloadedSkillsWithFilter(efs embed.FS, filter func(path string) bool, baseDirs ...string) map[string]string

BuildPreloadedSkillsWithFilter builds a PreloadedSkills map from an embedded filesystem with a custom filter function. The filter function receives the file path and should return true if the file should be included in the result.

Example:

//go:embed skills/*
var skillsFS embed.FS

// Only include SKILL.md files
preloaded := BuildPreloadedSkillsWithFilter(skillsFS, func(path string) bool {
    return strings.HasSuffix(path, "SKILL.md")
}, "skills")

Multiple base dirs:

preloaded := BuildPreloadedSkillsWithFilter(skillsFS, func(path string) bool {
    return strings.HasSuffix(path, "SKILL.md")
}, "skills", "templates")

func GetCurrentTime

func GetCurrentTime(timezone float64) string

GetCurrentTime returns the current time formatted for display.

func IntParam

func IntParam(desc string, required bool) *schema.ParameterInfo

IntParam creates an integer parameter.

func NumberParam

func NumberParam(desc string, required bool) *schema.ParameterInfo

NumberParam creates a number parameter.

func ObjectParam

func ObjectParam(desc string, subParams map[string]*schema.ParameterInfo, required bool) *schema.ParameterInfo

ObjectParam creates an object parameter with sub-parameters.

func StringParam

func StringParam(desc string, required bool) *schema.ParameterInfo

StringParam creates a string parameter.

func StringParamEnum

func StringParamEnum(desc string, enumValues []string, required bool) *schema.ParameterInfo

StringParamEnum creates a string parameter with enum values.

func WithEnableFileTool

func WithEnableFileTool(v bool) func(o *BuiltinToolsOption)

WithEnableFileTool enables or disables the built-in file tools (read_file, write_file, edit_file, list_directory, glob, add_artifact).

Types

type AddArtifactArgs

type AddArtifactArgs struct {
	Path     string            `json:"path"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

type AddTodoArgs

type AddTodoArgs struct {
	Todos []TodoItemInput `json:"todos"`
}

type Agent

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

Agent is a ReAct (Reasoning + Acting) agent that can process tasks using tools and skills. The graph is compiled once and can be reused across multiple Execute calls for efficiency. Each Execute call receives fresh skills and backend via taskInput, allowing for stateful backends. Capabilities:

  • Tool calling with automatic backend injection
  • Skills system with progressive disclosure
  • Token-aware message pruning
  • Tool result eviction for large outputs

func NewAgent

func NewAgent(config AgentConfig) (*Agent, error)

NewAgent creates a new ReAct agent.

func (*Agent) Execute

func (a *Agent) Execute(rail flow.Rail, req AgentRequest) (TaskOutput, error)

Execute runs the agent with the given request.

type AgentConfig

type AgentConfig struct {
	// Name is an optional identifier for the agent used in logs.
	// If empty, defaults to "AgentLoop".
	Name string

	// Model is the LLM model to use.
	Model model.ToolCallingChatModel

	// MaxRunSteps limits the maximum number of ReAct rounds (tool-call cycles) the agent may execute.
	// Each round corresponds to one tool-calling iteration; the value is multiplied by 5 internally
	// to derive the actual Eino graph step budget (1 round ≈ 4 graph steps, ×5 includes a safety margin).
	// If 0 or negative, the step budget is determined automatically by Eino (node count + 10).
	MaxRunSteps int

	// Language specifies the language for agent responses.
	// If empty, defaults to "English".
	Language string

	// LogOnStart controls whether the agent logs when it starts processing.
	// If nil, defaults to true.
	LogOnStart *bool

	// LogOnEnd controls whether the agent logs token stats when it finishes.
	// If nil, defaults to true.
	LogOnEnd *bool

	// LogInputs controls whether the agent logs input messages to the model.
	// If nil, defaults to false.
	LogInputs *bool

	// LogOutputs controls whether the agent logs model output content.
	// If nil, defaults to true.
	LogOutputs *bool

	// Skills is a list of skill paths to load.
	// Skills are loaded from the backend and injected into the system prompt.
	Skills []string

	// PreloadedSkills is a map of file paths to content that will be written to the backend
	// before loading skills. This is useful for predefining skills when using TmpFileStore.
	// Example: {"/skills/web-research/SKILL.md": "# Web Research\n\n..."}
	//
	// See [BuildPreloadedSkills], [BuildPreloadedSkillsWithFilter]
	PreloadedSkills map[string]string

	// Tools is a list of custom tools to add to the built-in tools.
	// Built-in tools are always registered; this field adds additional tools.
	//
	// Create custom tools using helper functions:
	//   - [NewToolFunc] - for simple tools with map-based arguments
	//   - [NewCtxAwareToolFunc] - for tools needing AgentContext (Store, Todos)
	//   - [NewTypedToolFunc] - for tools with typed struct arguments
	//   - [NewTypedCtxAwareToolFunc] - for tools with typed arguments and AgentContext
	Tools []Tool

	// TaskPrompt is the main task prompt for the agent.
	TaskPrompt string

	// SystemPrompt is an optional custom system prompt.
	// If provided, it will be prepended to the base system prompt.
	SystemPrompt string

	// BackendFactory is a factory function that creates a fresh FileStore for each execution.
	// If nil, a new TmpFileStore will be created for each execution.
	// This allows stateful backends to be created fresh per execution.
	BackendFactory func() FileStore

	// Timezone is the timezone offset in hours for time display (default: 0, UTC).
	Timezone float64

	// MaxTokens is the maximum number of tokens allowed in the conversation history.
	// When exceeded, old messages will be pruned (except system messages).
	// If 0 or negative, no token limit is enforced.
	// Default: 0 (no limit)
	MaxTokens int

	// TokenizerModelName is the name of the model used for token counting.
	// This is used to select the appropriate tiktoken encoding (e.g., cl100k_base for gpt-3.5-turbo, o200k_base for gpt-4o).
	// If empty, defaults to "gpt-3.5-turbo".
	// Common values: "gpt-3.5-turbo", "gpt-4", "gpt-4o", "qwen-plus", "deepseek-chat"
	TokenizerModelName string

	// EvictToolResultsThreshold is the maximum token count for tool results before eviction.
	// Tool results exceeding this threshold are evicted to the filesystem and replaced with a reference.
	// If 0 or negative, no eviction is performed.
	// Default: 0 (no eviction)
	// Recommended: 1000-2000 tokens for most use cases
	EvictToolResultsThreshold int

	// EvictToolResultsKeepPreview is the number of tokens to keep as a preview in the reference message.
	// Allows the agent to see context without loading the full content.
	// If 0, no preview is kept (only metadata).
	// Default: 0 (no preview)
	EvictToolResultsKeepPreview int

	// EnableFileTool enables the built-in file tools: read_file, write_file, edit_file,
	// list_directory, glob, and add_artifact. When false, these tools are not registered.
	// Default: false
	EnableFileTool bool
}

AgentConfig is the configuration for creating an agent.

type AgentContext

type AgentContext struct {
	Store     FileStore
	Todos     *TodoManager
	Artifacts *ArtifactManager
}

type AgentRequest

type AgentRequest struct {
	UserInput           string
	PreloadBackendFiles func(store FileStore) error                       // Optional callback to preload files into the backend before execution
	ArtifactCallback    func(store FileStore, artifacts []Artifact) error // Optional callback for artifacts
}

AgentRequest represents a request to execute an agent

type Artifact

type Artifact struct {
	Path        string            // Backend file path
	SizeInBytes int64             // File size in bytes
	Meta        map[string]string // Additional metadata (title, url, etc.)
}

Artifact represents a discovered or created artifact during agent execution

type ArtifactManager

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

ArtifactManager manages artifacts collected during agent execution.

func NewArtifactManager

func NewArtifactManager() *ArtifactManager

NewArtifactManager creates a new artifact manager.

func (*ArtifactManager) AddArtifact

func (am *ArtifactManager) AddArtifact(artifact Artifact) error

AddArtifact adds a new artifact.

func (*ArtifactManager) GetArtifacts

func (am *ArtifactManager) GetArtifacts() []Artifact

GetArtifacts returns all artifacts (alias for ListArtifacts).

func (*ArtifactManager) ListArtifacts

func (am *ArtifactManager) ListArtifacts() []Artifact

ListArtifacts returns all artifacts.

type BuiltinToolsOption

type BuiltinToolsOption struct {
	// EnableFileTool enables the file-related tools: read_file, write_file, edit_file,
	// list_directory, glob, and add_artifact. Default: false.
	EnableFileTool bool
}

BuiltinToolsOption configures which built-in tools are registered.

type DeleteTodoArgs

type DeleteTodoArgs struct {
	IDs []string `json:"ids"`
}

type EditFileArgs

type EditFileArgs struct {
	Path       string `json:"path"`
	OldString  string `json:"old_string"`
	NewString  string `json:"new_string"`
	ReplaceAll bool   `json:"replace_all,omitempty"`
}

type FileInfo

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

FileInfo represents file metadata.

type FileStore

type FileStore interface {
	// ReadFile reads a file from the backend.
	ReadFile(ctx context.Context, path string) ([]byte, error)

	// WriteFile writes content to a file in the backend.
	WriteFile(ctx context.Context, path string, content []byte) error

	// ListDirectory lists files and directories in a path.
	ListDirectory(ctx context.Context, path string) ([]FileInfo, error)

	// FileExists checks if a file exists.
	FileExists(ctx context.Context, path string) (bool, error)

	// DeleteFile deletes a file.
	DeleteFile(ctx context.Context, path string) error
}

FileStore defines the interface for file operations. This abstraction allows different storage backends (filesystem, in-memory, etc.)

type GlobArgs

type GlobArgs struct {
	Pattern string `json:"pattern"`
}

type ListDirectoryArgs

type ListDirectoryArgs struct {
	Path string `json:"path"`
}

type PromptBuilder

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

PromptBuilder builds the system prompt for the agent.

func NewPromptBuilder

func NewPromptBuilder() *PromptBuilder

NewPromptBuilder creates a new prompt builder.

func (*PromptBuilder) Build

func (pb *PromptBuilder) Build(ctx context.Context) (*schema.Message, error)

Build builds the system prompt.

func (*PromptBuilder) WithCurrentTime

func (pb *PromptBuilder) WithCurrentTime(time string) *PromptBuilder

WithCurrentTime sets the current time.

func (*PromptBuilder) WithCustomPrompt

func (pb *PromptBuilder) WithCustomPrompt(prompt string) *PromptBuilder

WithCustomPrompt sets a custom prompt that will be prepended to the base prompt.

func (*PromptBuilder) WithLanguage

func (pb *PromptBuilder) WithLanguage(language string) *PromptBuilder

WithLanguage sets the language for the agent.

func (*PromptBuilder) WithSkills

func (pb *PromptBuilder) WithSkills(skills *Skills) *PromptBuilder

WithSkills sets the skills middleware.

func (*PromptBuilder) WithTaskPrompt

func (pb *PromptBuilder) WithTaskPrompt(prompt string) *PromptBuilder

WithTaskPrompt sets a task prompt that provides task-specific guidance.

type ReadFileArgs

type ReadFileArgs struct {
	Path   string `json:"path"`
	Offset int    `json:"offset,omitempty"`
	Limit  int    `json:"limit,omitempty"`
}

type SelfInvokeTool

type SelfInvokeTool interface {
	ExecuteJson(ctx context.Context, jsonArg string) (string, error)
}

type SessionAware

type SessionAware interface {
	// OnSessionStart is called when an agent session begins, before any file operations.
	// Implementations should perform any initialisation here (e.g. creating a tmp directory).
	OnSessionStart(rail flow.Rail) error

	// OnSessionEnd is called when an agent session ends.
	// Implementations should release resources here (e.g. removing the tmp directory).
	OnSessionEnd(rail flow.Rail) error
}

SessionAware is implemented by FileStore backends that need lifecycle management tied to an agent session.

type Skill

type Skill struct {
	Metadata SkillMetadata
	Path     string
	Content  string // The markdown content (excluding YAML frontmatter)
}

Skill represents a loaded skill with its metadata and content.

func LoadSkill

func LoadSkill(path string, content []byte) (*Skill, error)

LoadSkill loads a skill from markdown content with YAML frontmatter. Format: --- name: skill-name description: skill description --- # Skill Content

func (*Skill) FormatForPrompt

func (s *Skill) FormatForPrompt() string

FormatForPrompt formats the skill for injection into the system prompt.

func (*Skill) FormatMetadataOnly

func (s *Skill) FormatMetadataOnly() string

FormatMetadataOnly formats only the skill metadata for progressive disclosure. This is used in the system prompt to show available skills without loading full content.

type SkillLoader

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

SkillLoader loads skills from a backend.

func NewSkillLoader

func NewSkillLoader(backend FileStore) *SkillLoader

NewSkillLoader creates a new skill loader.

func (*SkillLoader) LoadFromSource

func (l *SkillLoader) LoadFromSource(ctx context.Context, source string) (SkillsMap, error)

LoadFromSource loads skills from a single source directory.

func (*SkillLoader) LoadFromSources

func (l *SkillLoader) LoadFromSources(ctx context.Context, sources []string) (SkillsMap, error)

LoadFromSources loads skills from multiple sources. Sources are paths to skill directories (e.g., "/skills/user/", "/skills/project/"). Each source directory should contain skill subdirectories with SKILL.md files. Later sources override earlier sources for skills with the same name.

func (*SkillLoader) LoadSkillFile

func (l *SkillLoader) LoadSkillFile(ctx context.Context, path string) (*Skill, error)

LoadSkillFile loads a single skill from a SKILL.md file.

type SkillMetadata

type SkillMetadata struct {
	Name         string   `yaml:"name"`
	Description  string   `yaml:"description"`
	License      string   `yaml:"license,omitempty"`
	Compatible   string   `yaml:"compatibility,omitempty"`
	Metadata     string   `yaml:"metadata,omitempty"`
	AllowedTools []string `yaml:"allowed_tools,omitempty"`
}

SkillMetadata represents the metadata of a skill from YAML frontmatter.

type Skills

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

Skills injects loaded skills into the system prompt.

func NewSkills

func NewSkills(backend FileStore) *Skills

NewSkills creates a new skills manager.

func (*Skills) GetSkills

func (s *Skills) GetSkills() SkillsMap

GetSkills returns the loaded skills map.

func (*Skills) InjectMetadata

func (s *Skills) InjectMetadata(basePrompt string) string

InjectMetadata injects only skill metadata for progressive disclosure. The LLM is instructed to read full skill content on-demand using tools.

func (*Skills) Load

func (s *Skills) Load(ctx context.Context, sources []string) error

Load loads skills from the configured sources.

type SkillsMap

type SkillsMap map[string]*Skill

SkillsMap is a collection of skills keyed by name.

func (SkillsMap) Add

func (sm SkillsMap) Add(skill *Skill)

Add adds a skill to the map, overwriting if it exists.

func (SkillsMap) FormatMetadata

func (sm SkillsMap) FormatMetadata() string

FormatMetadata formats all skills with only metadata for progressive disclosure.

func (SkillsMap) Get

func (sm SkillsMap) Get(name string) (*Skill, bool)

Get retrieves a skill by name.

func (SkillsMap) List

func (sm SkillsMap) List() []*Skill

List returns all skills in the map.

type TaskOutput

type TaskOutput struct {
	Response  string     // Main response (research report)
	Artifacts []Artifact // Artifacts collected during execution
}

TaskOutput represents the output from an agent execution

type TmpFileStore

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

TmpFileStore is a tmp-file-backed FileStore implementation. Each session gets its own tmp directory; all files written during the session are stored as individual tmp files inside that directory. The tmp directory is created lazily on the first WriteFile call, so calling OnSessionStart is optional. Call OnSessionEnd when the session is done to clean up.

func NewTmpFileStore

func NewTmpFileStore() *TmpFileStore

NewTmpFileStore creates a new TmpFileStore. The underlying tmp directory is created lazily on the first WriteFile call.

func (*TmpFileStore) DeleteFile

func (b *TmpFileStore) DeleteFile(ctx context.Context, path string) error

DeleteFile removes a file entry and its underlying tmp file.

func (*TmpFileStore) FileExists

func (b *TmpFileStore) FileExists(ctx context.Context, path string) (bool, error)

FileExists checks whether a file or directory exists.

func (*TmpFileStore) ListDirectory

func (b *TmpFileStore) ListDirectory(ctx context.Context, path string) ([]FileInfo, error)

ListDirectory lists direct children of the given path.

func (*TmpFileStore) OnSessionEnd

func (b *TmpFileStore) OnSessionEnd(rail flow.Rail) error

OnSessionEnd removes the session tmp directory and all files inside it.

func (*TmpFileStore) OnSessionStart

func (b *TmpFileStore) OnSessionStart(rail flow.Rail) error

OnSessionStart creates the session tmp directory. This is optional — the directory is also created lazily on the first WriteFile call. Calling OnSessionStart explicitly is idempotent: a second call is a no-op.

func (*TmpFileStore) ReadFile

func (b *TmpFileStore) ReadFile(ctx context.Context, path string) ([]byte, error)

ReadFile reads a file from the tmp-file-backed store.

func (*TmpFileStore) WriteFile

func (b *TmpFileStore) WriteFile(ctx context.Context, path string, content []byte) error

WriteFile writes content to a new tmp file inside the session directory. The session tmp directory is created lazily on the first call if OnSessionStart has not been called explicitly.

type TodoItem

type TodoItem struct {
	ID          string `json:"id"`
	Task        string `json:"task"`
	Status      string `json:"status"` // "pending", "completed"
	Description string `json:"description,omitempty"`
}

TodoItem represents a task in the todo list.

type TodoItemInput

type TodoItemInput struct {
	Task        string `json:"task"`
	Description string `json:"description,omitempty"`
}

type TodoManager

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

TodoManager manages the todo list for the agent.

func NewTodoManager

func NewTodoManager() *TodoManager

NewTodoManager creates a new todo manager.

func (*TodoManager) AddTodo

func (tm *TodoManager) AddTodo(task, description string) (string, error)

AddTodo adds a new todo item.

func (*TodoManager) AddTodos

func (tm *TodoManager) AddTodos(todos []TodoItem) ([]string, error)

AddTodos adds multiple todo items atomically.

func (*TodoManager) ClearCompleted

func (tm *TodoManager) ClearCompleted()

ClearCompleted removes all completed todos.

func (*TodoManager) DeleteTodo

func (tm *TodoManager) DeleteTodo(id string) error

DeleteTodo deletes a todo item.

func (*TodoManager) DeleteTodos

func (tm *TodoManager) DeleteTodos(ids []string) error

DeleteTodos deletes multiple todo items atomically.

func (*TodoManager) Format

func (tm *TodoManager) Format() string

Format returns a formatted string representation of all todos.

func (*TodoManager) FromState

func (tm *TodoManager) FromState(todos []TodoItem)

FromState restores the todos from state.

func (*TodoManager) GetTodo

func (tm *TodoManager) GetTodo(id string) (TodoItem, bool)

GetTodo returns a specific todo item.

func (*TodoManager) ListTodos

func (tm *TodoManager) ListTodos() []TodoItem

ListTodos returns all todo items.

func (*TodoManager) ToState

func (tm *TodoManager) ToState() []TodoItem

ToState returns the todos as a slice for state persistence.

func (*TodoManager) UpdateTodoStatus

func (tm *TodoManager) UpdateTodoStatus(id, status string) error

UpdateTodoStatus updates the status of a todo item.

type Tokenizer

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

Tokenizer manages tiktoken encodings for token counting. It caches encodings to avoid repeated initialization.

func NewTokenizer

func NewTokenizer(model string) (*Tokenizer, error)

NewTokenizer creates a new tokenizer for the specified model. If model is empty, defaults to "gpt-3.5-turbo" (cl100k_base encoding).

func (*Tokenizer) CountMessageTokens

func (t *Tokenizer) CountMessageTokens(msg *schema.Message) int

CountMessageTokens returns the token count for a message. This follows OpenAI's token counting methodology for chat messages. See: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb

func (*Tokenizer) CountMessagesTokens

func (t *Tokenizer) CountMessagesTokens(messages []*schema.Message) int

CountMessagesTokens returns the total token count for a slice of messages. Includes the 3 token priming for assistant reply.

func (*Tokenizer) CountTokens

func (t *Tokenizer) CountTokens(text string) int

CountTokens returns the exact token count for the given text.

func (*Tokenizer) PruneMessagesToTokenLimit

func (t *Tokenizer) PruneMessagesToTokenLimit(messages []*schema.Message, maxTokens int) []*schema.Message

PruneMessagesToTokenLimit prunes messages to fit within the token limit. It preserves system messages and the most recent messages. Returns the pruned slice of messages.

type Tool

type Tool interface {
	// Name returns the name of the tool.
	Name() string

	// Description returns a description of the tool.
	Description() string

	// Parameters returns the JSON schema for the tool parameters.
	Parameters() map[string]*schema.ParameterInfo

	// Execute executes the tool with the given arguments.
	Execute(ctx context.Context, args map[string]interface{}) (string, error)
}

Tool represents a tool that can be used by the agent.

func NewCtxAwareToolFunc

func NewCtxAwareToolFunc(
	name string,
	description string,
	parameters map[string]*schema.ParameterInfo,
	execute func(ctx context.Context, agentCtx AgentContext, args map[string]interface{}) (string, error),
) Tool

NewCtxAwareToolFunc creates a tool that needs access to AgentContext (Store and Todos). The AgentContext is automatically injected via context by the agent loop.

Parameters should be built using the typed helper functions:

  • StringParam(desc, required) - for string parameters
  • IntParam(desc, required) - for integer parameters
  • NumberParam(desc, required) - for numeric parameters
  • BoolParam(desc, required) - for boolean parameters
  • ArrayParam(desc, elemInfo, required) - for array parameters
  • ObjectParam(desc, subParams, required) - for object parameters

Example:

NewCtxAwareToolFunc(
    "read_file",
    "Read file content",
    map[string]*schema.ParameterInfo{
        "path": StringParam("The absolute path to the file to read", true),
    },
    func(ctx context.Context, agentCtx AgentContext, args map[string]interface{}) (string, error) {
        path := cast.ToString(args["path"])
        content, err := agentCtx.Store.ReadFile(ctx, path)
        return string(content), err
    },
)

func NewThinkTool

func NewThinkTool() Tool

NewThinkTool creates a think tool for strategic reflection on research progress and decision-making. This tool is not included in the built-in tools by default, but can be added by users if needed. Use this tool after each search to analyze results and plan next steps systematically. This creates a deliberate pause in the research workflow for quality decision-making.

When to use: - After receiving search results: What key information did I find? - Before deciding next steps: Do I have enough to answer comprehensively? - When assessing research gaps: What specific information am I still missing? - Before concluding research: Can I provide a complete answer now?

Reflection should address: 1. Analysis of current findings - What concrete information have I gathered? 2. Gap assessment - What crucial information is still missing? 3. Quality evaluation - Do I have sufficient evidence/examples for a good answer? 4. Strategic decision - Should I continue searching or provide my answer?

Example:

agent := agentloop.NewAgent(agentloop.AgentConfig{
    Model: chatModel,
    Tools: []agentloop.Tool{agentloop.NewThinkTool()},
})

func NewToolFunc

func NewToolFunc(
	name string,
	description string,
	parameters map[string]*schema.ParameterInfo,
	execute func(ctx context.Context, args map[string]interface{}) (string, error),
) Tool

NewToolFunc creates a new function-based tool.

Parameters should be built using the typed helper functions:

  • StringParam(desc, required) - for string parameters
  • IntParam(desc, required) - for integer parameters
  • NumberParam(desc, required) - for numeric parameters
  • BoolParam(desc, required) - for boolean parameters
  • ArrayParam(desc, elemInfo, required) - for array parameters
  • ObjectParam(desc, subParams, required) - for object parameters

Example:

NewToolFunc(
    "finish_tool",
    "Call this tool when you have completed the task",
    map[string]*schema.ParameterInfo{
        "response": StringParam("Your final answer to the task", false),
    },
    func(ctx context.Context, args map[string]interface{}) (string, error) {
        response := cast.ToString(args["response"])
        return response, nil
    },
)

func NewTypedCtxAwareToolFunc

func NewTypedCtxAwareToolFunc[T any](
	name string,
	description string,
	parameters map[string]*schema.ParameterInfo,
	execute func(ctx context.Context, agentCtx AgentContext, args T) (string, error),
) Tool

NewTypedCtxAwareToolFunc creates a tool that accepts typed arguments and has AgentContext access. The execute function receives a struct of type T instead of a map.

Parameters should be built using the typed helper functions:

  • StringParam(desc, required) - for string parameters
  • IntParam(desc, required) - for integer parameters
  • NumberParam(desc, required) - for numeric parameters
  • BoolParam(desc, required) - for boolean parameters
  • ArrayParam(desc, elemInfo, required) - for array parameters
  • ObjectParam(desc, subParams, required) - for object parameters

Example:

type ReadFileArgs struct {
    Path   string `json:"path"`
    Offset int    `json:"offset"`
    Limit  int    `json:"limit"`
}

NewTypedCtxAwareToolFunc(
    "read_file",
    "Read file content",
    map[string]*schema.ParameterInfo{
        "path":   StringParam("The absolute path to the file to read", true),
        "offset": IntParam("Optional: Line number to start reading from", false),
        "limit":  IntParam("Optional: Maximum number of lines to read", false),
    },
    func(ctx context.Context, agentCtx AgentContext, args ReadFileArgs) (string, error) {
        // args is already typed as ReadFileArgs
        // No need for cast.ToString or cast.ToInt
        content, err := agentCtx.Store.ReadFile(ctx, args.Path)
        return string(content), err
    },
)

func NewTypedToolFunc

func NewTypedToolFunc[T any](
	name string,
	description string,
	parameters map[string]*schema.ParameterInfo,
	execute func(ctx context.Context, args T) (string, error),
) Tool

NewTypedToolFunc creates a tool that accepts typed arguments via JSON deserialization. The execute function receives a struct of type T instead of a map.

Parameters should be built using the typed helper functions:

  • StringParam(desc, required) - for string parameters
  • IntParam(desc, required) - for integer parameters
  • NumberParam(desc, required) - for numeric parameters
  • BoolParam(desc, required) - for boolean parameters
  • ArrayParam(desc, elemInfo, required) - for array parameters
  • ObjectParam(desc, subParams, required) - for object parameters

Example:

type ReadFileArgs struct {
    Path   string `json:"path"`
    Offset int    `json:"offset"`
    Limit  int    `json:"limit"`
}

NewTypedToolFunc(
    "read_file",
    "Read file content",
    map[string]*schema.ParameterInfo{
        "path":   StringParam("The absolute path to the file to read", true),
        "offset": IntParam("Optional: Line number to start reading from", false),
        "limit":  IntParam("Optional: Maximum number of lines to read", false),
    },
    func(ctx context.Context, args ReadFileArgs) (string, error) {
        // args is already typed as ReadFileArgs
        // No need for cast.ToString or cast.ToInt
        return "file content", nil
    },
)

type ToolFunc

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

ToolFunc is a function-based tool implementation.

func (*ToolFunc) Description

func (t *ToolFunc) Description() string

Description returns the description of the tool.

func (*ToolFunc) Execute

func (t *ToolFunc) Execute(ctx context.Context, args map[string]interface{}) (string, error)

Execute executes the tool with the given arguments.

func (*ToolFunc) Name

func (t *ToolFunc) Name() string

Name returns the name of the tool.

func (*ToolFunc) Parameters

func (t *ToolFunc) Parameters() map[string]*schema.ParameterInfo

Parameters returns the JSON schema for the tool parameters.

type ToolRegistry

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

Registry manages tool registration and retrieval.

func BuiltinTools

func BuiltinTools(ops ...func(o *BuiltinToolsOption)) *ToolRegistry

BuiltinTools returns the built-in tools configured by the provided options. By default (no options), no tools are registered; use WithEnableFileTool to opt in.

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewRegistry creates a new tool registry.

func (*ToolRegistry) Get

func (r *ToolRegistry) Get(name string) (Tool, bool)

Get retrieves a tool by name.

func (*ToolRegistry) List

func (r *ToolRegistry) List() []Tool

List returns all registered tools.

func (*ToolRegistry) Merge

func (r *ToolRegistry) Merge(other *ToolRegistry)

Merge merges another registry into this one.

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(tool Tool)

Register registers a tool in the registry.

func (*ToolRegistry) ToEinoTools

func (r *ToolRegistry) ToEinoTools() []tool.BaseTool

ToEinoTools converts the registry to Eino tool instances.

type TypedCtxAwareToolFunc

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

TypedCtxAwareToolFunc is a tool that accepts typed arguments and has AgentContext access.

func (*TypedCtxAwareToolFunc[T]) Description

func (t *TypedCtxAwareToolFunc[T]) Description() string

Description returns the description of the tool.

func (*TypedCtxAwareToolFunc[T]) Execute

func (t *TypedCtxAwareToolFunc[T]) Execute(ctx context.Context, args map[string]interface{}) (string, error)

Execute executes the tool with the given arguments (untyped).

func (*TypedCtxAwareToolFunc[T]) ExecuteJson

func (t *TypedCtxAwareToolFunc[T]) ExecuteJson(ctx context.Context, jsonArg string) (string, error)

ExecuteJson executes the tool with JSON arguments.

func (*TypedCtxAwareToolFunc[T]) Name

func (t *TypedCtxAwareToolFunc[T]) Name() string

Name returns the name of the tool.

func (*TypedCtxAwareToolFunc[T]) Parameters

func (t *TypedCtxAwareToolFunc[T]) Parameters() map[string]*schema.ParameterInfo

Parameters returns the JSON schema for the tool parameters.

type TypedToolFunc

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

TypedToolFunc is a tool that accepts typed arguments via JSON deserialization.

func (*TypedToolFunc[T]) Description

func (t *TypedToolFunc[T]) Description() string

Description returns the description of the tool.

func (*TypedToolFunc[T]) Execute

func (t *TypedToolFunc[T]) Execute(ctx context.Context, args map[string]interface{}) (string, error)

Execute executes the tool with the given arguments (untyped).

func (*TypedToolFunc[T]) ExecuteJson

func (t *TypedToolFunc[T]) ExecuteJson(ctx context.Context, jsonArg string) (string, error)

ExecuteJson executes the tool with JSON arguments.

func (*TypedToolFunc[T]) Name

func (t *TypedToolFunc[T]) Name() string

Name returns the name of the tool.

func (*TypedToolFunc[T]) Parameters

func (t *TypedToolFunc[T]) Parameters() map[string]*schema.ParameterInfo

Parameters returns the JSON schema for the tool parameters.

type UpdateTodoArgs

type UpdateTodoArgs struct {
	ID     string `json:"id,omitempty"`
	Status string `json:"status,omitempty"`
}

type WriteFileArgs

type WriteFileArgs struct {
	Path    string `json:"path"`
	Content string `json:"content"`
}

Jump to

Keyboard shortcuts

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