agent

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package agent provides the agent definition and builder API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildAll

func BuildAll(ctx context.Context, fc *FileConfig, opts ...BuildOption) (map[string]*Agent, error)

BuildAll constructs all agents from a FileConfig. BuildOptions (e.g. WithToolHandler) apply to every agent built.

func CompressToolCalls added in v0.3.0

func CompressToolCalls(messages []model.Message, maxCalls int) []model.Message

CompressToolCalls removes older tool call/result pairs from message history, keeping only the most recent maxCalls pairs. System messages and non-tool messages are always preserved.

func ExtractReasoningParts added in v0.3.0

func ExtractReasoningParts(content string) map[string]string

ExtractReasoningParts parses a reflection-style response into components.

func ReadStoredResult added in v0.3.0

func ReadStoredResult(ctx context.Context, store storage.Storage, sessionID, key string) (string, error)

ReadStoredResult retrieves a previously evicted tool result from storage.

Types

type Agent

type Agent struct {
	ID          string
	Name        string
	Description string
	UserID      string

	// Core components
	Model   model.Provider
	Tools   *tool.Registry
	Skills  *skill.Registry
	Memory  *memory.Store
	Storage storage.Storage
	Graph   *graph.CompiledGraph

	// Enhancements
	Knowledge      knowledge.Knowledge
	MemoryManager  *memory.Manager
	Hooks          hooks.Chain
	Guardrails     *guardrails.Engine
	Broker         *stream.Broker          // SSE broker for real-time event streaming
	Tracer         *chronostrace.Collector // execution tracer for span-based observability
	SessionState   map[string]any          // persistent cross-turn state
	OutputSchema   map[string]any          // JSON Schema for structured output
	NumHistoryRuns int                     // number of past runs to inject into context
	ContextCfg     ContextConfig           // context window management and summarization

	// System prompt and instructions
	SystemPrompt   string
	Instructions   []string
	InstructionsFn func(ctx context.Context, state map[string]any) []string
	Examples       []Example

	// Reasoning and iteration control
	Reasoning      ReasoningStrategy
	ReasoningModel model.Provider // separate, more capable model for reasoning steps
	Debug          bool           // when set, logs detailed execution info
	MaxIterations  int            // max tool-calling loop iterations; 0 = default (25)

	// MCP servers
	MCPClients []*mcp.Client

	// Multi-agent
	SubAgents              []*Agent
	MaxConcurrentSubAgents int
	Capabilities           []string // advertised capabilities for the protocol bus
}

Agent is the top-level agent definition.

func BuildAgent

func BuildAgent(ctx context.Context, cfg *AgentConfig, opts ...BuildOption) (*Agent, error)

BuildAgent constructs a fully-wired *Agent from an AgentConfig.

func (*Agent) Chat

func (a *Agent) Chat(ctx context.Context, userMessage string) (*model.ChatResponse, error)

Chat sends a single user message to the agent's model and returns the response. This is a convenience method for agents that have a model but no graph.

func (*Agent) ChatWithSession

func (a *Agent) ChatWithSession(ctx context.Context, sessionID, userMessage string) (*model.ChatResponse, error)

ChatWithSession sends a message within a persistent, multi-turn session. When the conversation approaches the model's context window limit, older messages are automatically summarized to stay within budget.

func (*Agent) CloseMCP added in v0.3.0

func (a *Agent) CloseMCP()

CloseMCP disconnects all MCP server connections.

func (*Agent) ConnectMCP added in v0.3.0

func (a *Agent) ConnectMCP(ctx context.Context) error

ConnectMCP connects all configured MCP servers and registers their tools in the agent's tool registry. Call after Build.

func (*Agent) Execute

func (a *Agent) Execute(ctx context.Context, task string) (string, error)

Execute runs the agent on a text task and returns the text response. Unlike Run, Execute works with just a model — no graph or storage needed. This is the primary entry point for team-based orchestration where agents are lightweight task executors.

func (*Agent) Resume

func (a *Agent) Resume(ctx context.Context, sessionID string) (*graph.RunState, error)

Resume continues a paused session.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, input map[string]any) (*graph.RunState, error)

Run starts a new execution session for this agent.

type AgentConfig

type AgentConfig struct {
	ID          string `yaml:"id"`
	Name        string `yaml:"name"`
	Description string `yaml:"description,omitempty"`
	UserID      string `yaml:"user_id,omitempty"`

	Model        ModelConfig   `yaml:"model"`
	Storage      StorageConfig `yaml:"storage,omitempty"`
	System       string        `yaml:"system_prompt,omitempty"`
	Instructions []string      `yaml:"instructions,omitempty"`
	Tools        []ToolConfig  `yaml:"tools,omitempty"`
	Capabilities []string      `yaml:"capabilities,omitempty"`

	// MCPServers lists Model Context Protocol servers whose tools are
	// registered with the agent when ConnectMCP is called after Build.
	MCPServers []mcp.ServerConfig `yaml:"mcp_servers,omitempty"`

	OutputSchema   map[string]any `yaml:"output_schema,omitempty"`
	NumHistoryRuns int            `yaml:"num_history_runs,omitempty"`
	Stream         bool           `yaml:"stream,omitempty"`
	Context        ContextYAML    `yaml:"context,omitempty"`

	// Team nesting: an agent config can reference sub-agents by ID
	SubAgents []string `yaml:"sub_agents,omitempty"`
}

AgentConfig is the YAML-serializable definition of a single agent.

type BuildOption added in v0.5.0

type BuildOption func(*buildOptions)

BuildOption configures BuildAgent/BuildAll. Options are applied per call, so nothing leaks between builds.

func WithToolHandler added in v0.5.0

func WithToolHandler(name string, factory ToolHandlerFactory) BuildOption

WithToolHandler binds a config tool name to a factory that builds its runtime handler for this build. When the agent being built declares a custom tool whose name matches, the factory supplies the real handler. An empty name or nil factory is ignored. Pass it to BuildAgent/BuildAll:

agent.BuildAgent(ctx, cfg, agent.WithToolHandler("word_count", factory))

type Builder

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

Builder provides a fluent API for constructing agents.

func New

func New(id, name string) *Builder

New creates a new agent builder.

func (*Builder) AddCapability

func (b *Builder) AddCapability(capability string) *Builder

func (*Builder) AddExample added in v0.3.0

func (b *Builder) AddExample(input, output string) *Builder

func (*Builder) AddHook

func (b *Builder) AddHook(h hooks.Hook) *Builder

func (*Builder) AddInputGuardrail

func (b *Builder) AddInputGuardrail(name string, g guardrails.Guardrail) *Builder

func (*Builder) AddInstruction

func (b *Builder) AddInstruction(instruction string) *Builder

func (*Builder) AddMCPServer added in v0.3.0

func (b *Builder) AddMCPServer(cfg mcp.ServerConfig) *Builder

func (*Builder) AddOutputGuardrail

func (b *Builder) AddOutputGuardrail(name string, g guardrails.Guardrail) *Builder

func (*Builder) AddSkill

func (b *Builder) AddSkill(s *skill.Skill) *Builder

func (*Builder) AddSubAgent

func (b *Builder) AddSubAgent(sub *Agent) *Builder

func (*Builder) AddTool

func (b *Builder) AddTool(def *tool.Definition) *Builder

func (*Builder) AddToolkit added in v0.3.0

func (b *Builder) AddToolkit(tk *tool.Toolkit) *Builder

func (*Builder) Build

func (b *Builder) Build() (*Agent, error)

Build compiles the graph (if set) and returns the agent.

func (*Builder) Description

func (b *Builder) Description(d string) *Builder

func (*Builder) WithBroker

func (b *Builder) WithBroker(br *stream.Broker) *Builder

func (*Builder) WithContextConfig

func (b *Builder) WithContextConfig(cfg ContextConfig) *Builder

func (*Builder) WithDebug added in v0.3.0

func (b *Builder) WithDebug(debug bool) *Builder

func (*Builder) WithGraph

func (b *Builder) WithGraph(g *graph.StateGraph) *Builder

func (*Builder) WithHistoryRuns

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

func (*Builder) WithInstructionsFn added in v0.3.0

func (b *Builder) WithInstructionsFn(fn func(ctx context.Context, state map[string]any) []string) *Builder

func (*Builder) WithKnowledge

func (b *Builder) WithKnowledge(k knowledge.Knowledge) *Builder

func (*Builder) WithMaxIterations added in v0.3.0

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

func (*Builder) WithMemory

func (b *Builder) WithMemory(m *memory.Store) *Builder

func (*Builder) WithMemoryManager

func (b *Builder) WithMemoryManager(m *memory.Manager) *Builder

func (*Builder) WithModel

func (b *Builder) WithModel(p model.Provider) *Builder

func (*Builder) WithOutputSchema

func (b *Builder) WithOutputSchema(s map[string]any) *Builder

func (*Builder) WithReasoning added in v0.3.0

func (b *Builder) WithReasoning(strategy ReasoningStrategy) *Builder

WithReasoning configures the agent's reasoning strategy.

func (*Builder) WithReasoningModel added in v0.3.0

func (b *Builder) WithReasoningModel(p model.Provider) *Builder

func (*Builder) WithStorage

func (b *Builder) WithStorage(s storage.Storage) *Builder

func (*Builder) WithSystemPrompt

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

func (*Builder) WithTracer

func (b *Builder) WithTracer(t *chronostrace.Collector) *Builder

func (*Builder) WithUserID

func (b *Builder) WithUserID(id string) *Builder

type ChatSession

type ChatSession struct {
	ID       string          `json:"id"`
	AgentID  string          `json:"agent_id"`
	Messages []model.Message `json:"messages"`
	Summary  string          `json:"summary"`
	// contains filtered or unexported fields
}

ChatSession manages multi-turn conversation state with automatic context-window summarization.

type ContextConfig

type ContextConfig struct {
	MaxContextTokens        int     `json:"max_context_tokens" yaml:"max_tokens"`                 // override model default; 0 = use model default
	SummarizeThreshold      float64 `json:"summarize_threshold" yaml:"summarize_threshold"`       // fraction of context window to trigger summarization (default 0.8)
	PreserveRecentTurns     int     `json:"preserve_recent_turns" yaml:"preserve_recent_turns"`   // number of recent user/assistant pairs to keep (default 5)
	MaxToolResultTokens     int     `json:"max_tool_result_tokens" yaml:"max_tool_result_tokens"` // max tokens for tool result before eviction (default 20000)
	MaxToolCallsFromHistory int     `json:"max_tool_calls_from_history" yaml:"max_tool_calls"`    // max tool call pairs to keep in history
}

ContextConfig controls context window management and automatic summarization.

type ContextYAML

type ContextYAML struct {
	MaxTokens           int     `yaml:"max_tokens,omitempty"`
	SummarizeThreshold  float64 `yaml:"summarize_threshold,omitempty"`
	PreserveRecentTurns int     `yaml:"preserve_recent_turns,omitempty"`
}

ContextYAML is the YAML-serializable form of ContextConfig.

type EvictionResult added in v0.3.0

type EvictionResult struct {
	StorageKey string `json:"storage_key"`
	Preview    string `json:"preview"`
	FullSize   int    `json:"full_size"`
}

EvictionResult holds the outcome of evicting a large tool result.

func EvictLargeResult added in v0.3.0

func EvictLargeResult(ctx context.Context, store storage.Storage, sessionID, toolName string, result any) (*EvictionResult, error)

EvictLargeResult stores a large tool result in storage and returns a truncated preview with a reference key. The agent can re-read the full result using the read_stored_result built-in tool.

type Example added in v0.3.0

type Example struct {
	Input  string `json:"input"`
	Output string `json:"output"`
}

Example represents a few-shot learning example.

type FileConfig

type FileConfig struct {
	Agents []AgentConfig `yaml:"agents"`
	Teams  []TeamConfig  `yaml:"teams,omitempty"`

	// Defaults applied to all agents unless overridden
	Defaults *AgentConfig `yaml:"defaults,omitempty"`
}

FileConfig is the top-level structure of a Chronos YAML config file. Supports both a single agent and a list of agents, plus optional teams.

func LoadFile

func LoadFile(path string) (*FileConfig, error)

LoadFile parses a YAML config file and returns all agent configs. Searches in order: given path, .chronos/agents.yaml, ~/.chronos/agents.yaml.

func (*FileConfig) FindAgent

func (fc *FileConfig) FindAgent(idOrName string) (*AgentConfig, error)

FindAgent looks up an agent by ID or name (case-insensitive) within a FileConfig.

func (*FileConfig) FindTeam

func (fc *FileConfig) FindTeam(id string) (*TeamConfig, error)

FindTeam looks up a team by ID (case-insensitive) within a FileConfig.

type ModelConfig

type ModelConfig struct {
	Provider   string `yaml:"provider"`          // openai, anthropic, gemini, mistral, ollama, azure, groq, together, deepseek, openrouter, fireworks, perplexity, anyscale, compatible
	Model      string `yaml:"model,omitempty"`   // model ID, e.g. "gpt-4o", "claude-sonnet-4-6"
	APIKey     string `yaml:"api_key,omitempty"` // literal or ${ENV_VAR}
	BaseURL    string `yaml:"base_url,omitempty"`
	OrgID      string `yaml:"org_id,omitempty"`
	TimeoutSec int    `yaml:"timeout_sec,omitempty"`

	// Azure-specific
	Endpoint   string `yaml:"endpoint,omitempty"`
	Deployment string `yaml:"deployment,omitempty"`
	APIVersion string `yaml:"api_version,omitempty"`
}

ModelConfig describes which model provider and settings to use.

type ReasoningStrategy added in v0.3.0

type ReasoningStrategy int

ReasoningStrategy defines the chain-of-thought approach.

const (
	ReasoningNone       ReasoningStrategy = iota
	ReasoningCoT                          // chain-of-thought: "Let's think step by step"
	ReasoningReflection                   // think, then critique
)

type StorageConfig

type StorageConfig struct {
	Backend string `yaml:"backend,omitempty"` // sqlite, postgres (default: sqlite)
	DSN     string `yaml:"dsn,omitempty"`     // connection string or file path

	// Connection-pool tuning for the SQL backends (sqlite, postgres). A zero
	// value leaves the adapter's built-in default in place.
	MaxOpenConns       int `yaml:"max_open_conns,omitempty"`
	MaxIdleConns       int `yaml:"max_idle_conns,omitempty"`
	ConnMaxLifetimeSec int `yaml:"conn_max_lifetime_sec,omitempty"`
}

StorageConfig describes the backing store.

type TeamConfig

type TeamConfig struct {
	ID             string   `yaml:"id"`
	Name           string   `yaml:"name"`
	Strategy       string   `yaml:"strategy"`                  // sequential, parallel, router, coordinator
	Agents         []string `yaml:"agents"`                    // agent IDs (order matters for sequential)
	Coordinator    string   `yaml:"coordinator,omitempty"`     // agent ID to use as coordinator
	MaxConcurrency int      `yaml:"max_concurrency,omitempty"` // for parallel strategy
	MaxIterations  int      `yaml:"max_iterations,omitempty"`  // for coordinator strategy
	ErrorStrategy  string   `yaml:"error_strategy,omitempty"`  // fail_fast, collect, best_effort
}

TeamConfig defines a multi-agent team in YAML.

type ToolConfig

type ToolConfig struct {
	Name        string         `yaml:"name"`
	Description string         `yaml:"description"`
	Parameters  map[string]any `yaml:"parameters,omitempty"` // JSON Schema
}

ToolConfig describes a tool to register on the agent.

type ToolHandlerFactory added in v0.5.0

type ToolHandlerFactory func(tc ToolConfig) (tool.Handler, error)

ToolHandlerFactory constructs the runtime handler for a config-declared custom tool. It receives the ToolConfig (name, description, JSON-Schema parameters) so the factory can honor the declared contract, and returns the tool.Handler that executes the tool. A non-nil error aborts agent build.

Bind a YAML tool name to a real handler by passing WithToolHandler to BuildAgent/BuildAll, so config-built agents execute working tools instead of no-op placeholders.

Jump to

Keyboard shortcuts

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