Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyMessageToolPersist(m *Message, s string) error
- func FormatToolResult(result interface{}) string
- func MarshalMessageToolPersist(m Message) (string, error)
- func NormalizeToolError(err error, maxLen int) string
- func SanitizeToolResult(result interface{}, maxTextLen int) interface{}
- func SerializeMessageParts(parts []MessagePart) (string, error)
- func TruncateString(s string, maxLen int) string
- func TruncateToolResult(content string, maxLen int, writeDir string) (display string, truncated bool, filePath string)
- type ActionMetadata
- type ActionResponse
- type AgentConfig
- type AgentInput
- type AgentResult
- type EngineRequest
- type EngineResponse
- type ImageDataPart
- type ImageURLPart
- type LLMProvider
- type LangChainToolWrapper
- type MemoryProvider
- type Message
- type MessagePart
- type ModelMetadata
- type OutputParser
- type ReasoningMessage
- type RequestResponseMetadata
- type StreamEvent
- type StreamMessage
- type StreamResult
- type TextPart
- type Tool
- type ToolAction
- type ToolActionStep
- type ToolCacheEntry
- type ToolCall
- type ToolCallData
- type ToolCallRequest
- type ToolCallback
- type ToolCallbackFunc
- func (f *ToolCallbackFunc) OnToolCall(toolName string, toolCallID string, input map[string]interface{})
- func (f *ToolCallbackFunc) OnToolError(toolName string, toolCallID string, err error)
- func (f *ToolCallbackFunc) OnToolInputEnd(toolName string, toolCallID string, input map[string]interface{})
- func (f *ToolCallbackFunc) OnToolInputStart(toolName string, toolCallID string, input map[string]interface{})
- func (f *ToolCallbackFunc) OnToolResult(toolName string, toolCallID string, output interface{})
- type ToolEvent
- type ToolFunction
- type ToolMetadata
- type Usage
Constants ¶
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
const ( ToolStatePending = "pending" ToolStateRunning = "running" ToolStateCompleted = "completed" ToolStateError = "error" ToolEmptyResultMessage = "Tool executed successfully but returned no result" )
Tool state constants (aligned with OpenCode)
const ( StreamEventToolCall = "tool_call" StreamEventToolInputStart = "tool_input_start" StreamEventToolInputEnd = "tool_input_end" StreamEventToolResult = "tool_result" StreamEventToolError = "tool_error" )
StreamResult tool event types
const ( ContextKeyTemperature = "temperature" ContextKeyMaxTokens = "max_tokens" ContextKeyTopP = "top_p" ContextKeyMaxCompletionTokens = "max_completion_tokens" ContextKeyReasoningEffort = "reasoning_effort" )
Context keys
const ToolErrorMaxLen = 400
Variables ¶
var BufferPool = sync.Pool{ New: func() interface{} { return make([]byte, 0, DefaultBufferPoolSize) }, }
BufferPool for reusing byte buffers to reduce GC pressure
Functions ¶
func ApplyMessageToolPersist ¶ added in v1.8.7
ApplyMessageToolPersist restores ToolCalls and ToolCallID from storage.
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 MarshalMessageToolPersist ¶ added in v1.8.7
MarshalMessageToolPersist JSON for DB/redis; empty string if no tool fields.
func NormalizeToolError ¶ added in v1.7.0
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
TruncateString truncates a string to the specified length
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"`
MaxTokens int `json:"maxTokens,omitempty"`
MaxCompletionTokens int `json:"maxCompletionTokens,omitempty"`
TopP float32 `json:"topP"`
FrequencyPenalty float32 `json:"frequencyPenalty"`
PresencePenalty float32 `json:"presencePenalty"`
StopSequences []string `json:"stopSequences"`
Timeout time.Duration `json:"timeout"`
ToolExecutionTimeout time.Duration `json:"toolExecutionTimeout"`
ToolTimeouts map[string]time.Duration `json:"toolTimeouts"`
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"` // message count incl. each assistant + tool row from tool rounds
MemoryCompressRatio float32 `json:"memoryCompressRatio"`
LogSilent bool `json:"logSilent"`
LogFile string `json:"logFile"`
DoomLoopThreshold int `json:"doomLoopThreshold"`
OnDoomLoop func(toolName string, input map[string]interface{}) bool `json:"-"`
ToolTimeoutCalculator func(toolName string, input map[string]interface{}) time.Duration `json:"-"`
MaxToolCallsPerIteration int `json:"maxToolCallsPerIteration"`
ToolResultWriteDir string `json:"toolResultWriteDir"`
DefaultToolResultMaxLen int `json:"defaultToolResultMaxLen"`
ToolErrorMaxLen int `json:"toolErrorMaxLen"`
ReasoningEffort string `json:"reasoningEffort"`
}
AgentConfig agent configuration
func NewAgentConfig ¶
func NewAgentConfig() *AgentConfig
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 ¶
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) 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
func MessagesFromToolSteps ¶ added in v1.8.7
func MessagesFromToolSteps(assistantContent string, steps []ToolCallData) []Message
MessagesFromToolSteps builds assistant (with tool_calls) and tool messages for one model turn.
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 ReasoningMessage ¶ added in v1.8.0
type ReasoningMessage struct {
Content string `json:"content"`
Reasoning string `json:"reasoning,omitempty"`
}
ReasoningMessage represents a message with reasoning/thinking content
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", "reasoning"
Content string `json:"content,omitempty"`
Reasoning string `json:"reasoning,omitempty"` // Thinking/reasoning content
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
// Tool event fields
ToolEvent *ToolEvent
}
StreamResult streaming result
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 ToolCallback ¶ added in v1.7.3
type ToolCallback interface {
OnToolCall(toolName string, toolCallID string, input map[string]interface{})
OnToolInputStart(toolName string, toolCallID string, input map[string]interface{})
OnToolInputEnd(toolName string, toolCallID string, input map[string]interface{})
OnToolResult(toolName string, toolCallID string, output interface{})
OnToolError(toolName string, toolCallID string, err error)
}
ToolCallback is an interface for receiving tool execution events in real-time
type ToolCallbackFunc ¶ added in v1.7.3
type ToolCallbackFunc struct {
// contains filtered or unexported fields
}
ToolCallbackFunc is a functional adapter for ToolCallback
func (*ToolCallbackFunc) OnToolCall ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolCall(toolName string, toolCallID string, input map[string]interface{})
func (*ToolCallbackFunc) OnToolError ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolError(toolName string, toolCallID string, err error)
func (*ToolCallbackFunc) OnToolInputEnd ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolInputEnd(toolName string, toolCallID string, input map[string]interface{})
func (*ToolCallbackFunc) OnToolInputStart ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolInputStart(toolName string, toolCallID string, input map[string]interface{})
func (*ToolCallbackFunc) OnToolResult ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolResult(toolName string, toolCallID string, output interface{})
type ToolEvent ¶ added in v1.7.3
type ToolEvent struct {
Event string // Event type: tool_call, tool_input_start, tool_input_end, tool_result, tool_error
ToolName string // Tool name
ToolCallID string // Tool call ID
State string // State: pending, running, completed, error
Input map[string]interface{} // Tool input arguments
Output interface{} // Tool execution result
Error string // Error message if failed
Duration time.Duration // Execution duration
}
ToolEvent represents a tool execution lifecycle event
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"`
ReasoningTokens int `json:"reasoning_tokens,omitempty"` // Thinking tokens (o1, o3 series etc.)
CachedTokens int `json:"cached_tokens,omitempty"` // Cache read tokens
}
Usage token usage information