types

package
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Cache-related constants
	DefaultCacheSize    = 100             // default tool cache size
	CacheExpirationTime = 5 * time.Minute // cache expiration time
	// Execution-related constants
	DefaultChannelBuffer = 50   // default channel buffer size
	MaxTruncationLength  = 2048 // maximum truncation length
	MinChannelBuffer     = 10   // minimum channel buffer size
	// Performance-related constants
	DefaultBufferPoolSize = 1024                   // default buffer pool size (1KB)
	IterationDelay        = 100 * time.Millisecond // inter-iteration delay
)

Constant definitions

View Source
const (
	ContextKeyTemperature         = "temperature"
	ContextKeyMaxTokens           = "max_tokens"
	ContextKeyTopP                = "top_p"
	ContextKeyMaxCompletionTokens = "max_completion_tokens"
)

Context keys

View Source
const ToolErrorMaxLen = 400

Variables

View Source
var BufferPool = sync.Pool{
	New: func() interface{} {
		return make([]byte, 0, DefaultBufferPoolSize)
	},
}

BufferPool for reusing byte buffers to reduce GC pressure

Functions

func FormatToolResult added in v1.6.13

func FormatToolResult(result interface{}) string

FormatToolResult formats tool execution result to string Uses JSON marshaling for better representation of complex data structures

func NormalizeToolError added in v1.7.0

func NormalizeToolError(err error, maxLen int) string

func SanitizeToolResult added in v1.7.0

func SanitizeToolResult(result interface{}, maxTextLen int) interface{}

func SerializeMessageParts added in v1.6.14

func SerializeMessageParts(parts []MessagePart) (string, error)

SerializeMessageParts serializes message parts to JSON string

func TruncateString added in v1.6.13

func TruncateString(s string, maxLen int) string

TruncateString truncates a string to the specified length

func TruncateToolResult added in v1.7.0

func TruncateToolResult(content string, maxLen int, writeDir string) (display string, truncated bool, filePath string)

Types

type ActionMetadata

type ActionMetadata struct {
	ItemIndex int `json:"itemIndex"`
}

ActionMetadata action metadata

type ActionResponse

type ActionResponse struct {
	Action *ToolAction `json:"action"`
	Data   interface{} `json:"data"`
	Error  string      `json:"error,omitempty"`
}

ActionResponse action response

type AgentConfig

type AgentConfig struct {
	MaxIterations            int                                                      `json:"maxIterations"`
	SystemMessage            string                                                   `json:"systemMessage"`
	ChatMessageRole          string                                                   `json:"chatMessageRole,omitempty"`
	Temperature              float32                                                  `json:"temperature"`                   // 温度参数 (0.0-1.0)
	MaxTokens                int                                                      `json:"maxTokens,omitempty"`           // 最大token数
	MaxCompletionTokens      int                                                      `json:"maxCompletionTokens,omitempty"` // 最大完成token数
	TopP                     float32                                                  `json:"topP"`                          // Top P采样
	FrequencyPenalty         float32                                                  `json:"frequencyPenalty"`              // 频率惩罚
	PresencePenalty          float32                                                  `json:"presencePenalty"`               // 存在惩罚
	StopSequences            []string                                                 `json:"stopSequences"`                 // 停止序列
	Timeout                  time.Duration                                            `json:"timeout"`                       // 超时时间
	ToolExecutionTimeout     time.Duration                                            `json:"toolExecutionTimeout"`          // 工具执行超时时间
	RetryAttempts            int                                                      `json:"retryAttempts"`                 // 重试次数
	RetryDelay               time.Duration                                            `json:"retryDelay"`                    // 重试延迟
	EnableToolRetry          bool                                                     `json:"enableToolRetry"`               // 启用工具重试
	MaxHistoryMessages       int                                                      `json:"maxHistoryMessages"`            // 最大历史消息数
	EnableMemoryCompress     bool                                                     `json:"enableMemoryCompress"`          // 启用记忆压缩
	MemoryCompressThreshold  int                                                      `json:"memoryCompressThreshold"`       // 记忆压缩阈值(消息数量)
	MemoryCompressRatio      float32                                                  `json:"memoryCompressRatio"`           // 记忆压缩比例(0.0-1.0)
	LogSilent                bool                                                     `json:"logSilent"`                     // 是否静默日志
	LogFile                  string                                                   `json:"logFile"`                       // 日志文件路径,为空则输出到终端
	DoomLoopThreshold        int                                                      `json:"doomLoopThreshold"`             // 同一 tool+同一参数连续出现次数阈值,0 表示关闭
	OnDoomLoop               func(toolName string, input map[string]interface{}) bool `json:"-"`                             // 检测到 doom loop 时回调,返回 false 则终止迭代
	MaxToolCallsPerIteration int                                                      `json:"maxToolCallsPerIteration"`      // 单轮最大 tool 调用数,0 表示不限制
	ToolResultWriteDir       string                                                   `json:"toolResultWriteDir"`            // 工具大结果落盘目录,为空则仅内存截断
	DefaultToolResultMaxLen  int                                                      `json:"defaultToolResultMaxLen"`       // 工具结果默认截断长度,0 表示用 types.MaxTruncationLength
	ToolErrorMaxLen          int                                                      `json:"toolErrorMaxLen"`               // 工具错误信息截断长度,0 表示用 types.ToolErrorMaxLen
}

AgentConfig agent configuration

func NewAgentConfig

func NewAgentConfig() *AgentConfig

NewAgentConfig creates a new agent configuration with reasonable defaults

type AgentInput added in v1.6.13

type AgentInput struct {
	Text  string        `json:"text,omitempty"`
	Parts []MessagePart `json:"parts,omitempty"`
}

AgentInput agent execution input

func ConvertToAgentInput added in v1.6.13

func ConvertToAgentInput(input interface{}) (AgentInput, error)

ConvertToAgentInput converts input to AgentInput Supports string and AgentInput types

func NewAgentInput added in v1.6.13

func NewAgentInput(text string) AgentInput

NewAgentInput creates a new agent input with text

func NewAgentInputWithParts added in v1.6.13

func NewAgentInputWithParts(parts []MessagePart) AgentInput

NewAgentInputWithParts creates a new agent input with message parts

func (AgentInput) String added in v1.6.13

func (i AgentInput) String() string

String returns the string representation of the input

func (AgentInput) ToMessage added in v1.6.13

func (i AgentInput) ToMessage(role string) Message

ToMessage converts AgentInput to Message

type AgentResult added in v1.6.13

type AgentResult struct {
	Output            string            `json:"output"`
	ToolCalls         []ToolCallRequest `json:"tool_calls"`
	IntermediateSteps []ToolCallData    `json:"intermediate_steps"`
	Usage             Usage             `json:"usage"`
}

==================== Data Structures and Type Definitions ==================== AgentResult agent execution result

type EngineRequest

type EngineRequest struct {
	Actions  []ToolAction            `json:"actions"`
	Metadata RequestResponseMetadata `json:"metadata"`
}

EngineRequest engine request

type EngineResponse

type EngineResponse struct {
	ActionResponses []ActionResponse        `json:"actionResponses"`
	Metadata        RequestResponseMetadata `json:"metadata"`
}

EngineResponse engine response

type ImageDataPart

type ImageDataPart struct {
	Data     []byte `json:"data"`
	MIMEType string `json:"mime_type"`
}

ImageDataPart image data part

type ImageURLPart

type ImageURLPart struct {
	URL    string `json:"url"`
	Detail string `json:"detail,omitempty"` // "low", "high", "auto"
}

ImageURLPart image URL part

type LLMProvider

type LLMProvider interface {
	// Basic chat functionality
	Chat(ctx context.Context, messages []Message) (Message, error)
	ChatStream(ctx context.Context, messages []Message) (<-chan StreamMessage, error)

	// Tool call support
	ChatWithTools(ctx context.Context, messages []Message, tools []Tool) (Message, error)
	ChatWithToolsStream(ctx context.Context, messages []Message, tools []Tool) (<-chan StreamMessage, error)

	// Model information
	GetModelName() string
	GetModelMetadata() ModelMetadata
}

LLMProvider defines LLM provider interface

type LangChainToolWrapper

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

LangChainToolWrapper LangChain tool wrapper

func NewLangChainToolWrapper

func NewLangChainToolWrapper(tool Tool) *LangChainToolWrapper

NewLangChainToolWrapper creates a new LangChain tool wrapper

func (*LangChainToolWrapper) Call

func (w *LangChainToolWrapper) Call(ctx context.Context, input string) (string, error)

Call invokes the tool (LangChain interface)

func (*LangChainToolWrapper) Description

func (w *LangChainToolWrapper) Description() string

Description returns tool description

func (*LangChainToolWrapper) Name

func (w *LangChainToolWrapper) Name() string

Name returns tool name

type MemoryProvider

type MemoryProvider interface {
	// Load memory variables
	LoadMemoryVariables(ctx context.Context) (map[string]interface{}, error)

	// Save context
	SaveContext(ctx context.Context, input, output map[string]interface{}) error

	// Clear memory
	Clear(ctx context.Context) error

	// Get chat history
	GetChatHistory(ctx context.Context) ([]Message, error)

	// Compress memory (optional, for memory compression)
	CompressMemory(ctx context.Context, llm LLMProvider, maxMessages int) error
}

MemoryProvider memory system interface

type Message

type Message struct {
	Role       string        `json:"role"` // "system", "user", "assistant", "tool"
	Content    string        `json:"content"`
	Name       string        `json:"name,omitempty"`
	ToolCalls  []ToolCall    `json:"tool_calls,omitempty"`
	ToolCallID string        `json:"tool_call_id,omitempty"`
	Parts      []MessagePart `json:"parts,omitempty"` // Multi-modal content support
	Usage      Usage         `json:"usage,omitempty"` // Token usage information
}

Message message structure

type MessagePart

type MessagePart interface {
	// contains filtered or unexported methods
}

MessagePart message part interface

func DeserializeMessageParts added in v1.6.14

func DeserializeMessageParts(data string) ([]MessagePart, error)

DeserializeMessageParts deserializes JSON string to message parts

type ModelMetadata

type ModelMetadata struct {
	Name      string                 `json:"name"`
	Version   string                 `json:"version"`
	MaxTokens int                    `json:"maxTokens"`
	Tools     []Tool                 `json:"tools,omitempty"`
	Extra     map[string]interface{} `json:"extra,omitempty"`
}

ModelMetadata model metadata

type OutputParser

type OutputParser interface {
	Parse(output string) (interface{}, error)
	GetFormatInstructions() string
}

OutputParser output parser interface

type RequestResponseMetadata

type RequestResponseMetadata struct {
	ItemIndex        int            `json:"itemIndex,omitempty"`
	PreviousRequests []ToolCallData `json:"previousRequests,omitempty"`
	IterationCount   int            `json:"iterationCount,omitempty"`
}

RequestResponseMetadata request response metadata

type StreamEvent

type StreamEvent struct {
	Type       string      `json:"type"`
	Content    string      `json:"content,omitempty"`
	ToolResult interface{} `json:"toolResult,omitempty"`
	EventName  string      `json:"eventName,omitempty"`
	Data       interface{} `json:"data,omitempty"`
}

StreamEvent stream event

type StreamMessage

type StreamMessage struct {
	Type      string     `json:"type"` // "chunk", "end", "error", "tool_calls"
	Content   string     `json:"content,omitempty"`
	Error     string     `json:"error,omitempty"`
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	Usage     *Usage     `json:"usage,omitempty"`
}

StreamMessage streaming message

type StreamResult added in v1.6.13

type StreamResult struct {
	Type    string
	Content string
	Result  *AgentResult
	Error   error
}

StreamResult streaming result

type TextPart

type TextPart struct {
	Text string `json:"text"`
}

TextPart text content part

type Tool

type Tool interface {
	// Tool basic information
	Name() string
	Description() string
	Schema() map[string]interface{}

	// Tool execution
	Execute(ctx context.Context, input map[string]interface{}) (interface{}, error)

	// Tool metadata
	Metadata() ToolMetadata
}

Tool defines tool interface

type ToolAction

type ToolAction struct {
	NodeName string                 `json:"nodeName"`
	Input    map[string]interface{} `json:"input"`
	Type     string                 `json:"type"`
	ID       string                 `json:"id"`
	Metadata ActionMetadata         `json:"metadata"`
}

ToolAction tool action

type ToolActionStep

type ToolActionStep struct {
	Tool       string      `json:"tool"`
	ToolInput  interface{} `json:"toolInput"`
	Log        interface{} `json:"log"`
	ToolCallID interface{} `json:"toolCallId"`
	Type       interface{} `json:"type"`
}

ToolActionStep tool action step

type ToolCacheEntry added in v1.6.13

type ToolCacheEntry struct {
	Result    interface{}
	Err       error
	Timestamp time.Time
	Prev      *ToolCacheEntry
	Next      *ToolCacheEntry
	Key       string
}

ToolCacheEntry tool cache entry with LRU support

type ToolCall

type ToolCall struct {
	ID       string       `json:"id"`
	Type     string       `json:"type"`
	Function ToolFunction `json:"function"`
}

ToolCall tool call

type ToolCallData

type ToolCallData struct {
	Action      ToolActionStep `json:"action"`
	Observation string         `json:"observation"`
}

ToolCallData tool call data

type ToolCallRequest

type ToolCallRequest struct {
	Tool       string                 `json:"tool"`
	ToolInput  map[string]interface{} `json:"toolInput"`
	ToolCallID string                 `json:"toolCallId"`
	Type       string                 `json:"type,omitempty"`
	Log        string                 `json:"log,omitempty"`
	MessageLog []interface{}          `json:"messageLog,omitempty"`
}

ToolCallRequest tool call request

type ToolFunction

type ToolFunction struct {
	Name      string                 `json:"name"`
	Arguments map[string]interface{} `json:"arguments"`
}

ToolFunction tool function

type ToolMetadata

type ToolMetadata struct {
	SourceNodeName      string                 `json:"sourceNodeName"`
	IsFromToolkit       bool                   `json:"isFromToolkit"`
	ToolType            string                 `json:"toolType"`                      // "mcp","http","builtin"
	Priority            int                    `json:"priority,omitempty"`            // 优先级,数字越大优先级越高
	Dependencies        []string               `json:"dependencies,omitempty"`        // 依赖的工具名称列表
	MaxTruncationLength int                    `json:"maxTruncationLength,omitempty"` // 工具结果截断长度,0表示使用默认值
	Extra               map[string]interface{} `json:"extra,omitempty"`
}

ToolMetadata tool metadata

type Usage added in v1.6.10

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Usage token usage information

Jump to

Keyboard shortcuts

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