agent

package
v1.19.1 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package agent implements the agentic tool-use loop for multi-step reasoning.

Stability: alpha

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatToolResult

func FormatToolResult(result ToolResult) string

FormatToolResult serialises a ToolResult as a JSON string suitable for injection back into the model context.

Types

type AgentSession

type AgentSession struct {
	Steps       []AgentStep
	Finished    bool
	FinalOutput string
	TotalTokens int
	StopReason  string
}

AgentSession records the full result of a RunLoop invocation.

type AgentStep

type AgentStep struct {
	StepNum     int
	ModelOutput string
	ToolCalls   []ToolCall
	ToolResults []ToolResult
	TokensUsed  int
}

AgentStep records one iteration of the agentic loop.

type EarningsEvent

type EarningsEvent struct {
	Symbol       string `json:"symbol"`
	Date         string `json:"date"`
	EstimatedEPS string `json:"estimated_eps"`
}

EarningsEvent represents a scheduled earnings release.

type FunctionCallParser

type FunctionCallParser struct{}

FunctionCallParser scans model output text for embedded JSON tool-call objects and extracts them into structured ToolCall values.

func NewFunctionCallParser

func NewFunctionCallParser() *FunctionCallParser

NewFunctionCallParser creates a new FunctionCallParser.

func (*FunctionCallParser) Parse

func (p *FunctionCallParser) Parse(text string) ParsedResponse

Parse scans text for JSON objects matching tool-call patterns and extracts them as ToolCall values. Two patterns are recognised:

{"name": "...", "arguments": {...}}
{"tool": "...", "parameters": {...}}

Extracted JSON blocks are removed from the text. If no valid tool calls are found, HasToolCalls is false and Text contains the original input.

type MarketDataProvider

type MarketDataProvider interface {
	GetMarketData(symbol string) (MarketQuote, error)
	GetOrderBook(symbol string, depth int) (OrderBook, error)
	GetPortfolio(accountID string) (Portfolio, error)
	GetEarningsCalendar(startDate, endDate string) ([]EarningsEvent, error)
	SearchNews(query string, limit int) ([]NewsArticle, error)
}

MarketDataProvider supplies market data, order books, portfolios, earnings calendars, and news to the agentic tool set.

type MarketQuote

type MarketQuote struct {
	Symbol    string  `json:"symbol"`
	Price     float64 `json:"price"`
	Bid       float64 `json:"bid"`
	Ask       float64 `json:"ask"`
	Volume    int64   `json:"volume"`
	Timestamp string  `json:"timestamp"`
}

MarketQuote holds a price quote for a single symbol.

type MarketToolSet

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

MarketToolSet holds the dependencies for market-related agent tools.

func NewMarketToolSet

func NewMarketToolSet(provider MarketDataProvider, risk RiskApprover) *MarketToolSet

NewMarketToolSet creates a new MarketToolSet.

func (*MarketToolSet) RegisterAll

func (m *MarketToolSet) RegisterAll(reg *ToolRegistry) error

RegisterAll registers all market tools into the given registry.

type NewsArticle

type NewsArticle struct {
	Title     string `json:"title"`
	Source    string `json:"source"`
	URL       string `json:"url"`
	Summary   string `json:"summary"`
	Published string `json:"published"`
}

NewsArticle is a single news search result.

type OrderBook

type OrderBook struct {
	Symbol string           `json:"symbol"`
	Bids   []OrderBookEntry `json:"bids"`
	Asks   []OrderBookEntry `json:"asks"`
}

OrderBook represents the bids and asks for a symbol.

type OrderBookEntry

type OrderBookEntry struct {
	Price    float64 `json:"price"`
	Quantity float64 `json:"quantity"`
}

OrderBookEntry represents a single level in an order book.

type OrderRequest

type OrderRequest struct {
	Symbol   string  `json:"symbol"`
	Side     string  `json:"side"`
	Quantity float64 `json:"quantity"`
	Price    float64 `json:"price"`
}

OrderRequest is the input for SubmitOrder.

type OrderResponse

type OrderResponse struct {
	OrderID  string `json:"order_id"`
	Status   string `json:"status"`
	Message  string `json:"message,omitempty"`
	Approved bool   `json:"approved"`
}

OrderResponse is the result of a submitted order.

type ParsedResponse

type ParsedResponse struct {
	Text         string
	ToolCalls    []ToolCall
	HasToolCalls bool
}

ParsedResponse holds the result of parsing model output for tool calls.

type Portfolio

type Portfolio struct {
	AccountID string              `json:"account_id"`
	Cash      float64             `json:"cash"`
	Positions []PortfolioPosition `json:"positions"`
}

Portfolio represents account holdings.

type PortfolioPosition

type PortfolioPosition struct {
	Symbol   string  `json:"symbol"`
	Quantity float64 `json:"quantity"`
	AvgCost  float64 `json:"avg_cost"`
	Current  float64 `json:"current"`
}

PortfolioPosition is a single holding in a portfolio.

type RiskApprover

type RiskApprover interface {
	Approve(symbol string, side string, quantity float64, price float64) (bool, string, error)
}

RiskApprover evaluates whether an order should be permitted.

type Supervisor

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

Supervisor orchestrates the agentic tool-use loop: generate output, parse for tool calls, execute tools, and repeat until completion.

func NewSupervisor

func NewSupervisor(cfg SupervisorConfig, registry *ToolRegistry, parser *FunctionCallParser) *Supervisor

NewSupervisor creates a Supervisor with the given configuration, tool registry, and function-call parser.

func (*Supervisor) RunLoop

func (s *Supervisor) RunLoop(
	ctx context.Context,
	generateFn func(ctx context.Context, history []string) (string, error),
	initialPrompt string,
) (*AgentSession, error)

RunLoop drives the full agentic loop. It calls generateFn repeatedly, parsing each output for tool calls and executing them until one of:

  • the model produces no tool calls (StopReason "no_tools")
  • MaxSteps is reached (StopReason "max_steps")
  • a tool returns an error and StopOnToolError is true (StopReason "tool_error")
  • MaxTokens is exceeded (StopReason "max_tokens")

func (*Supervisor) RunStep

func (s *Supervisor) RunStep(ctx context.Context, modelOutput string) (*AgentStep, bool, error)

RunStep processes a single model output: parses it for tool calls, executes any found tools via the registry, and returns the resulting step. The boolean return indicates whether the loop should finish (true when no tool calls were found).

type SupervisorConfig

type SupervisorConfig struct {
	MaxSteps        int
	MaxTokens       int
	StopOnToolError bool
}

SupervisorConfig controls the behavior of the agentic loop.

type ToolCall

type ToolCall struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
}

ToolCall represents a request from a model to invoke a tool.

type ToolDef

type ToolDef struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Parameters  json.RawMessage `json:"parameters"`
}

ToolDef describes a tool that can be invoked by an agent.

type ToolRegistry

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

ToolRegistry maps tool names to their definitions and handler functions.

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates an empty ToolRegistry.

func (*ToolRegistry) Call

func (r *ToolRegistry) Call(call ToolCall) (result ToolResult)

Call invokes the handler for the named tool. If the tool is not found, or if the handler returns an error or panics, the result has IsError set to true.

func (*ToolRegistry) Get

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

Get looks up a tool definition by name.

func (*ToolRegistry) List

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

List returns all registered tool definitions sorted by name.

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(def ToolDef, fn func(args json.RawMessage) (string, error)) error

Register adds a tool to the registry. It returns an error if the name is empty or already registered.

type ToolResult

type ToolResult struct {
	CallID  string `json:"call_id"`
	Output  string `json:"output"`
	IsError bool   `json:"is_error,omitempty"`
}

ToolResult is the outcome of executing a ToolCall.

Jump to

Keyboard shortcuts

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