Documentation
¶
Overview ¶
Package agent provides conversation context management for multi-turn dialogues. This module maintains state across conversation turns to enable handling of refinements like "change it to 3pm" without re-specifying the full context.
Package agent provides error classification for intelligent retry logic. This system categorizes errors into transient (retryable), permanent (non-retryable), and conflict (special handling) types to improve agent reliability.
Package agent provides error recovery mechanisms for AI agents. This system automatically attempts to recover from certain error types by modifying inputs and retrying, improving user experience.
Note: ErrorRecovery instances are designed to be created per-request or shared as immutable configurations. Use WithTimezone to create a new instance with different settings rather than modifying existing ones.
Index ¶
- Constants
- Variables
- func BuildSystemPrompt(workDir, sessionID string, userID int32, deviceContext string) stringdeprecated
- func ConversationIDToSessionID(conversationID int64) stringdeprecated
- func ExtractIntent(route ChatRouteType) string
- func GetActionHint(err error) string
- func GetRetryDelay(err error) time.Duration
- func IsMissingCapability(err error) bool
- func IsRecoverableError(err error) bool
- func IsTransientError(err error) bool
- func ParseInabilityReport(report string) (capability, reason string)
- func SendPhaseChange(callback SafeCallbackFunc, phase ProcessingPhase, estimatedSeconds int)
- func SendProgress(callback SafeCallbackFunc, percent int, estimatedSeconds int)
- func ShouldRetry(err error) bool
- type Agent
- type AgentConfig
- type AgentSessionStatsForStoragedeprecated
- type AgentStats
- type AssistantMessagedeprecated
- type BaseParrot
- func (b *BaseParrot) Finalize() *NormalSessionStats
- func (b *BaseParrot) GetSessionStats() *NormalSessionStats
- func (b *BaseParrot) RecordAgentStats(agentStats *AgentStats)
- func (b *BaseParrot) Reset(agentType string)
- func (b *BaseParrot) TrackLLMCall(stats *ai.LLMCallStats, model string)
- func (b *BaseParrot) TrackToolCall(toolName string)
- type BaseTool
- type CCRunnerdeprecated
- type CCRunnerConfigdeprecated
- type CCSessionManagerdeprecated
- type CacheEntry
- type CacheStats
- type Callback
- type ChatRouteResult
- type ChatRouteType
- type ChatRouter
- func (r *ChatRouter) Route(ctx context.Context, input string) (*ChatRouteResult, error)
- func (r *ChatRouter) RouteAndExecute(ctx context.Context, input string, sessionCtx *ConversationContext) (*ChatRouteResult, error)
- func (r *ChatRouter) RouteWithContext(ctx context.Context, input string, sessionCtx *ConversationContext) (*ChatRouteResult, error)
- type ChatRouterWithMetadata
- type ClassifiedError
- type ConflictError
- type ContentBlockdeprecated
- type ContextStore
- type ContextSummary
- type ConversationContext
- func (c *ConversationContext) AddTurn(userInput, agentOutput string, toolCalls []ToolCallRecord)
- func (c *ConversationContext) Clear()
- func (c *ConversationContext) GetExtension(key string) any
- func (c *ConversationContext) GetLastNTurns(n int) []ConversationTurn
- func (c *ConversationContext) GetLastRoute() (ChatRouteType, bool)
- func (c *ConversationContext) GetLastTurn() *ConversationTurn
- func (c *ConversationContext) GetSummary() ContextSummary
- func (c *ConversationContext) SetExtension(key string, value any)
- func (c *ConversationContext) SetLastRoute(routeType ChatRouteType)
- func (c *ConversationContext) ToHistoryPrompt() string
- func (c *ConversationContext) ToJSON() (string, error)
- type ConversationTurn
- type DangerBlockEventdeprecated
- type DangerDetectordeprecated
- type DangerLeveldeprecated
- type ErrorClass
- type ErrorRecovery
- func (r *ErrorRecovery) ExecuteWithRecovery(ctx context.Context, executor ExecutorFunc, input string) (string, error)
- func (r *ErrorRecovery) ExecuteWithRecoveryDetailed(ctx context.Context, executor ExecutorFunc, input string) RecoveryResult
- func (r *ErrorRecovery) WithTimezone(tz string) *ErrorRecovery
- type EventCallbackdeprecated
- type EventMetadeprecated
- type EventWithMetadeprecated
- type ExecutorFunc
- type ExpertRegistryInterface
- type GenericCache
- type HandoffResult
- type IntentClassifier
- type IntentKeywordProvider
- type LRUCache
- type MissingCapability
- type NativeTool
- type NormalSessionStats
- type ParrotAgent
- type ParrotError
- type ParrotSelfCognition
- type ParrotStreamAdapter
- type PhaseChangeEventdeprecated
- type ProcessingPhasedeprecated
- type ProgressEventdeprecated
- type RecoveryResult
- type RoutingConfig
- type SafeCallbackFuncdeprecated
- type Sessiondeprecated
- type SessionManagerdeprecated
- type SessionStatsdeprecated
- type SessionStatsDatadeprecated
- type SessionStatsProvider
- type SessionStatusdeprecated
- type SimpleHandoffHandler
- type SimpleHandoffRequest
- type SimpleHandoverResult
- type StreamMessagedeprecated
- type TaskIntentdeprecated
- type Tool
- type ToolCallRecord
- type ToolOption
- type ToolRegistry
- type ToolResult
- type ToolWithSchema
- type UsageStatsdeprecated
Constants ¶
const ( // SessionStatus constants SessionStatusStarting = runner.SessionStatusStarting SessionStatusReady = runner.SessionStatusReady SessionStatusBusy = runner.SessionStatusBusy SessionStatusDead = runner.SessionStatusDead // DangerLevel constants DangerLevelCritical = runner.DangerLevelCritical DangerLevelHigh = runner.DangerLevelHigh DangerLevelModerate = runner.DangerLevelModerate // ProcessingPhase constants PhaseAnalyzing = runner.PhaseAnalyzing PhasePlanning = runner.PhasePlanning PhaseRetrieving = runner.PhaseRetrieving PhaseSynthesizing = runner.PhaseSynthesizing // Event type constants EventTypePhaseChange = runner.EventTypePhaseChange EventTypeProgress = runner.EventTypeProgress EventTypeThinking = runner.EventTypeThinking EventTypeToolUse = runner.EventTypeToolUse EventTypeToolResult = runner.EventTypeToolResult EventTypeAnswer = runner.EventTypeAnswer EventTypeError = runner.EventTypeError EventTypeSessionStats = "session_stats" // Session statistics event )
Constants for backward compatibility
const ( EventToolUse = "tool_use" EventToolResult = "tool_result" EventAnswer = "answer" )
Event constants for callbacks.
const MaxTurnsPerSession = 10
MaxTurnsPerSession is the maximum number of conversation turns to keep in memory. This prevents unbounded memory growth in long conversations.
Variables ¶
var ( ErrInvalidTimeFormat = errors.New("invalid time format") ErrToolNotFound = errors.New("tool not found") ErrParseError = errors.New("parse error") ErrNetworkError = errors.New("network error") ErrScheduleConflict = errors.New("schedule conflict") ErrInvalidInput = errors.New("invalid input") )
Base error definitions for agent errors
Functions ¶
func BuildSystemPrompt
deprecated
func ConversationIDToSessionID
deprecated
func ExtractIntent ¶ added in v0.100.1
func ExtractIntent(route ChatRouteType) string
ExtractIntent extracts the intent from route type for metadata storage. This is a standalone function to avoid DRY violation between packages.
func GetActionHint ¶
GetActionHint returns the suggested action for handling the error.
func GetRetryDelay ¶
GetRetryDelay returns the suggested delay before retry, or 0 if not retryable.
func IsMissingCapability ¶ added in v0.100.0
IsMissingCapability checks if an error is a MissingCapability error.
func IsRecoverableError ¶
IsRecoverableError returns true if the error is a known type that can be recovered from. This is distinct from retry logic - it indicates whether the error type itself is fixable (e.g., invalid time format can be corrected) vs. a system-level issue.
func IsTransientError ¶
IsTransientError returns true if the error is temporary and may resolve on retry. This maps network and service availability issues.
func ParseInabilityReport ¶ added in v0.100.1
ParseInabilityReport parses the INABILITY_REPORTED message to extract capability and reason. This is a public function to avoid DRY violation between packages. Format: "INABILITY_REPORTED: <capability> - <reason> (suggested_agent: <agent>)"
func SendPhaseChange ¶
func SendPhaseChange(callback SafeCallbackFunc, phase ProcessingPhase, estimatedSeconds int)
SendPhaseChange sends a phase_change event to notify the frontend of processing progress. SendPhaseChange 发送 phase_change 事件以通知前端处理进度。
func SendProgress ¶
func SendProgress(callback SafeCallbackFunc, percent int, estimatedSeconds int)
SendProgress sends a progress event with the current percentage. SendProgress 发送带有当前百分比的进度事件。
func ShouldRetry ¶
ShouldRetry returns true if the error warrants a retry attempt.
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent is a lightweight, framework-less AI agent. It uses native LLM tool calling without LangChainGo.
func NewAgent ¶
func NewAgent(llm ai.LLMService, config AgentConfig, tools []ToolWithSchema) *Agent
NewAgent creates a new Agent with the given configuration.
func (*Agent) GetStats ¶
func (a *Agent) GetStats() AgentStats
GetStats returns a snapshot of the accumulated stats.
func (*Agent) ResetStats ¶
func (a *Agent) ResetStats()
ResetStats clears all accumulated statistics.
type AgentConfig ¶
type AgentConfig struct {
// Name identifies this agent.
Name string
// SystemPrompt is the base system prompt for the LLM.
SystemPrompt string
// MaxIterations is the maximum number of tool-calling loops.
MaxIterations int
}
AgentConfig holds configuration for creating a new Agent.
type AgentSessionStatsForStorage
deprecated
type AgentSessionStatsForStorage = runner.AgentSessionStatsForStorage
AgentSessionStatsForStorage is an alias for runner.AgentSessionStatsForStorage.
Deprecated: Use runner.AgentSessionStatsForStorage directly.
type AgentStats ¶
type AgentStats struct {
LLMCallCount int
PromptTokens int
CompletionTokens int
TotalCacheRead int
TotalCacheWrite int
ToolCallCount int
// contains filtered or unexported fields
}
AgentStats accumulates statistics for agent execution. AgentStats 累积代理执行的统计数据。
func (*AgentStats) GetSnapshot ¶
func (s *AgentStats) GetSnapshot() AgentStats
GetSnapshot returns a copy of the current stats.
func (*AgentStats) RecordLLMCall ¶
func (s *AgentStats) RecordLLMCall(stats *ai.LLMCallStats)
RecordLLMCall records a single LLM call with its statistics.
func (*AgentStats) RecordToolCall ¶
func (s *AgentStats) RecordToolCall()
RecordToolCall records a tool invocation.
type AssistantMessage
deprecated
type AssistantMessage = runner.AssistantMessage
AssistantMessage is an alias for runner.AssistantMessage.
Deprecated: Use runner.AssistantMessage directly.
type BaseParrot ¶
type BaseParrot struct {
// contains filtered or unexported fields
}
BaseParrot provides common statistics accumulation functionality for all normal mode agents. UniversalParrot and other agents embed BaseParrot to track LLM call statistics.
BaseParrot is thread-safe and uses a mutex to protect the stats state.
BaseParrot 为所有普通模式代理提供通用的统计累积功能。 UniversalParrot 和其他代理嵌入 BaseParrot 以跟踪其执行会话期间的 LLM 调用统计。
BaseParrot 是线程安全的,使用互斥锁保护统计状态。
func NewBaseParrot ¶
func NewBaseParrot(agentType string) *BaseParrot
NewBaseParrot creates a new BaseParrot with initialized stats. NewBaseParrot 创建一个具有初始化统计数据的 BaseParrot。
func (*BaseParrot) Finalize ¶
func (b *BaseParrot) Finalize() *NormalSessionStats
Finalize marks the session as complete and returns the final stats. Finalize 标记会话完成并返回最终统计数据。
func (*BaseParrot) GetSessionStats ¶
func (b *BaseParrot) GetSessionStats() *NormalSessionStats
GetSessionStats returns a copy of the current session stats. GetSessionStats 返回当前会话统计的副本。
func (*BaseParrot) RecordAgentStats ¶
func (b *BaseParrot) RecordAgentStats(agentStats *AgentStats)
RecordAgentStats transfers accumulated stats from the Agent framework to BaseParrot. This is used by agents (e.g., SchedulerAgentV2) that embed both Agent and BaseParrot to ensure stats from the Agent's LLM calls are captured in the session stats.
Note: agentStats should be a snapshot (e.g., from Agent.GetStats()) which is safe to pass.
RecordAgentStats 将 Agent 框架的累积统计数据传输到 BaseParrot。 这被同时嵌入 Agent 和 BaseParrot 的代理(例如 SchedulerAgentV2)使用, 以确保来自 Agent LLM 调用的统计数据被捕获到会话统计中。
func (*BaseParrot) Reset ¶
func (b *BaseParrot) Reset(agentType string)
Reset clears the current stats and starts a new session. Reset 清除当前统计数据并开始新会话。
func (*BaseParrot) TrackLLMCall ¶
func (b *BaseParrot) TrackLLMCall(stats *ai.LLMCallStats, model string)
TrackLLMCall records statistics from a single LLM call. It accumulates tokens, timing, and cost information into the session stats.
TrackLLMCall 记录单次 LLM 调用的统计信息。 它将 tokens、时间和成本信息累积到会话统计中。
func (*BaseParrot) TrackToolCall ¶
func (b *BaseParrot) TrackToolCall(toolName string)
TrackToolCall records a tool invocation. TrackToolCall 记录工具调用。
type BaseTool ¶
type BaseTool struct {
// contains filtered or unexported fields
}
BaseTool provides a reusable base implementation for tools. BaseTool 为工具提供可复用的基础实现。
func NewBaseTool ¶
func NewBaseTool( name string, description string, execute func(ctx context.Context, input string) (string, error), opts ...ToolOption, ) *BaseTool
NewBaseTool creates a new BaseTool. NewBaseTool 创建一个新的 BaseTool。
Parameters:
- name: The name of the tool
- description: A description of what the tool does
- execute: The function to execute when the tool is run
- opts: Optional configuration functions
Example:
tool := NewBaseTool(
"my_tool",
"Does something useful",
func(ctx context.Context, input string) (string, error) {
return "result", nil
},
WithTimeout(30*time.Second),
)
func (*BaseTool) Description ¶
Description returns the description of the tool. Description 返回工具描述。
type CCRunner
deprecated
CCRunner is an alias for runner.CCRunner.
Deprecated: Use runner.CCRunner directly.
type CCRunnerConfig
deprecated
type CCSessionManager
deprecated
type CCSessionManager = runner.CCSessionManager
CCSessionManager is an alias for runner.CCSessionManager.
Deprecated: Use runner.CCSessionManager directly.
func NewCCSessionManager
deprecated
func NewCCSessionManager(logger *slog.Logger, timeout time.Duration) *CCSessionManager
NewCCSessionManager creates a new session manager.
Deprecated: Use runner.NewCCSessionManager directly.
type CacheEntry ¶
type CacheEntry struct {
Value interface{} `json:"value"`
Key string `json:"key"`
ExpiresAt int64 `json:"expires_at"`
SizeBytes int `json:"size_bytes"`
AccessTime int64 `json:"access_time"`
}
CacheEntry represents a cached value with metadata. CacheEntry 表示带有元数据的缓存值。
type CacheStats ¶
type CacheStats struct {
Size int `json:"size"`
MaxEntries int `json:"max_entries"`
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
HitRate float64 `json:"hit_rate"`
}
CacheStats represents cache statistics. CacheStats 表示缓存统计信息。
type Callback ¶
type Callback func(event string, data interface{})
Callback is called during agent execution for events. Updated to accept interface{} for structured event data (EventWithMeta).
type ChatRouteResult ¶
type ChatRouteResult struct {
Route ChatRouteType `json:"route"`
Method string `json:"method"`
Confidence float64 `json:"confidence"`
NeedsOrchestration bool `json:"needs_orchestration"`
// Handoff indicates whether a handoff occurred during sticky route execution.
Handoff bool `json:"handoff"`
// HandoffResult contains the result of a handoff operation (if Handoff is true).
HandoffResult *HandoffResult `json:"handoff_result,omitempty"`
// ExecutionResult contains the result of expert execution (if not handoff).
ExecutionResult string `json:"execution_result,omitempty"`
}
ChatRouteResult represents the routing classification result.
type ChatRouteType ¶
type ChatRouteType string
ChatRouteType represents the type of chat routing.
const ( // RouteTypeMemo routes to Memo Parrot (灰灰) for memo search and retrieval. // Implemented by UniversalParrot with memo.yaml configuration. RouteTypeMemo ChatRouteType = "memo" // RouteTypeSchedule routes to Schedule Parrot (时巧) for schedule management. // Implemented by UniversalParrot with schedule.yaml configuration. RouteTypeSchedule ChatRouteType = "schedule" // RouteTypeGeneral routes to General Parrot for pure LLM tasks. // Implemented by UniversalParrot with general.yaml configuration. // Use for: summarization, translation, rewriting, Q&A without tools. RouteTypeGeneral ChatRouteType = "general" )
type ChatRouter ¶
type ChatRouter struct {
// contains filtered or unexported fields
}
ChatRouter routes user input to the appropriate Parrot agent. It is a thin adapter over routing.Service (two-layer: cache -> rule).
func NewChatRouter ¶
func NewChatRouter(routerSvc *routerpkg.Service) *ChatRouter
NewChatRouter creates a new chat router. routerSvc is required and provides the two-layer routing (cache -> rule).
func NewChatRouterWithHandoff ¶ added in v0.100.0
func NewChatRouterWithHandoff(routerSvc *routerpkg.Service, handoffHandler SimpleHandoffHandler, expertRegistry ExpertRegistryInterface) *ChatRouter
NewChatRouterWithHandoff creates a new chat router with handoff support. routerSvc is required and provides the two-layer routing. handoffHandler is optional - when provided, enables handoff on MissingCapability errors. expertRegistry is required when handoffHandler is provided.
func (*ChatRouter) Route ¶
func (r *ChatRouter) Route(ctx context.Context, input string) (*ChatRouteResult, error)
Route determines the appropriate Parrot agent for the user input. Delegates to routing.Service which implements: cache → rule → history → LLM.
func (*ChatRouter) RouteAndExecute ¶ added in v0.100.0
func (r *ChatRouter) RouteAndExecute(ctx context.Context, input string, sessionCtx *ConversationContext) (*ChatRouteResult, error)
RouteAndExecute determines the appropriate Parrot agent and executes it for sticky routes. This method is used when the user wants to execute the expert directly with handoff support. It handles MissingCapability errors by triggering handoff to another expert.
func (*ChatRouter) RouteWithContext ¶
func (r *ChatRouter) RouteWithContext(ctx context.Context, input string, sessionCtx *ConversationContext) (*ChatRouteResult, error)
RouteWithContext determines the appropriate Parrot agent with session context support. If the input is a short confirmation (e.g., "OK", "好的"), it reuses the last route for intent stickiness, enabling seamless multi-turn conversations (Issue #163).
type ChatRouterWithMetadata ¶ added in v0.100.0
type ChatRouterWithMetadata struct {
*ChatRouter // Embed original router
// contains filtered or unexported fields
}
ChatRouterWithMetadata extends ChatRouter with metadata-based sticky routing. This implements the "Stateful Routing" principle from context-engineering.md: routing decisions are based on persisted database state (AIBlock.Metadata), not just in-memory session state.
func NewChatRouterWithMetadata ¶ added in v0.100.0
func NewChatRouterWithMetadata( baseRouter *ChatRouter, metadataMgr *ctxpkg.MetadataManager, ) *ChatRouterWithMetadata
NewChatRouterWithMetadata creates a new chat router with metadata support.
func NewChatRouterWithMetadataAndKeywords ¶ added in v0.100.1
func NewChatRouterWithMetadataAndKeywords( baseRouter *ChatRouter, metadataMgr *ctxpkg.MetadataManager, keywordProvider IntentKeywordProvider, ) *ChatRouterWithMetadata
NewChatRouterWithMetadataAndKeywords creates a new chat router with metadata and keyword provider.
func (*ChatRouterWithMetadata) InvalidateStickyCache ¶ added in v0.100.0
func (r *ChatRouterWithMetadata) InvalidateStickyCache(conversationID int32)
InvalidateStickyCache invalidates the sticky cache for a conversation. Call this when the conversation context changes significantly.
func (*ChatRouterWithMetadata) RouteWithContextWithMetadata ¶ added in v0.100.0
func (r *ChatRouterWithMetadata) RouteWithContextWithMetadata( ctx context.Context, input string, sessionCtx *ConversationContext, conversationID int32, blockID int64, ) (*ChatRouteResult, error)
RouteWithContextWithMetadata routes with metadata-based sticky routing. This method extends the base routing with: 1. Metadata-based sticky state (persistent across sessions) 2. Confidence-based sticky window decay
type ClassifiedError ¶
type ClassifiedError struct {
Original error
ActionHint string
Class ErrorClass
RetryAfter time.Duration
}
ClassifiedError wraps an error with its classification and retry guidance.
func ClassifyError ¶
func ClassifyError(err error) *ClassifiedError
ClassifyError analyzes an error and determines its class and retry strategy.
func (*ClassifiedError) Error ¶
func (c *ClassifiedError) Error() string
Error returns a formatted error message.
func (*ClassifiedError) IsConflict ¶
func (c *ClassifiedError) IsConflict() bool
IsConflict returns true if the error is a conflict.
func (*ClassifiedError) IsPermanent ¶
func (c *ClassifiedError) IsPermanent() bool
IsPermanent returns true if the error is non-retryable.
func (*ClassifiedError) IsTransient ¶
func (c *ClassifiedError) IsTransient() bool
IsTransient returns true if the error is temporary and should be retried.
func (*ClassifiedError) Unwrap ¶
func (c *ClassifiedError) Unwrap() error
Unwrap returns the original error for errors.Is/As.
type ConflictError ¶ added in v0.100.0
ConflictError is an interface for detecting schedule conflict errors. This follows DIP (Dependency Inversion Principle) - the AI layer depends on an abstraction, not concrete implementations in server/store packages.
type ContentBlock
deprecated
type ContentBlock = runner.ContentBlock
ContentBlock is an alias for runner.ContentBlock.
Deprecated: Use runner.ContentBlock directly.
type ContextStore ¶
type ContextStore struct {
// contains filtered or unexported fields
}
ContextStore manages conversation contexts for multiple sessions.
func NewContextStore ¶
func NewContextStore() *ContextStore
NewContextStore creates a new context store.
func (*ContextStore) CleanupOld ¶
func (s *ContextStore) CleanupOld(maxAge time.Duration) int
CleanupOld removes contexts older than the specified duration.
func (*ContextStore) Delete ¶
func (s *ContextStore) Delete(sessionID string)
Delete removes a conversation context.
func (*ContextStore) Get ¶
func (s *ContextStore) Get(sessionID string) *ConversationContext
Get retrieves a conversation context if it exists.
func (*ContextStore) GetOrCreate ¶
func (s *ContextStore) GetOrCreate(sessionID string, userID int32, timezone string) *ConversationContext
GetOrCreate retrieves or creates a conversation context.
type ContextSummary ¶
type ContextSummary struct {
CreatedAt time.Time
UpdatedAt time.Time
SessionID string
TurnCount int
UserID int32
}
ContextSummary provides a quick overview of the context state.
type ConversationContext ¶
type ConversationContext struct {
CreatedAt time.Time
UpdatedAt time.Time
SessionID string
Timezone string
Turns []ConversationTurn
UserID int32
// RouteSticky: Intent stickiness for short confirmations (Issue #163)
LastRouteType ChatRouteType // Last successful route type
LastRouteTime time.Time // When the last route was made
// Extensions stores domain-specific state (e.g., schedule context).
// Use type-safe getters/setters from domain packages.
Extensions map[string]any
// contains filtered or unexported fields
}
ConversationContext maintains state across conversation turns.
func NewConversationContext ¶
func NewConversationContext(sessionID string, userID int32, timezone string) *ConversationContext
NewConversationContext creates a new conversation context.
func (*ConversationContext) AddTurn ¶
func (c *ConversationContext) AddTurn(userInput, agentOutput string, toolCalls []ToolCallRecord)
AddTurn adds a new turn to the conversation history.
func (*ConversationContext) Clear ¶
func (c *ConversationContext) Clear()
Clear resets the conversation context.
func (*ConversationContext) GetExtension ¶ added in v0.100.0
func (c *ConversationContext) GetExtension(key string) any
GetExtension retrieves a domain-specific extension by key.
func (*ConversationContext) GetLastNTurns ¶
func (c *ConversationContext) GetLastNTurns(n int) []ConversationTurn
GetLastNTurns returns the last N conversation turns.
func (*ConversationContext) GetLastRoute ¶
func (c *ConversationContext) GetLastRoute() (ChatRouteType, bool)
GetLastRoute returns the last route type and whether it's within the sticky window.
func (*ConversationContext) GetLastTurn ¶
func (c *ConversationContext) GetLastTurn() *ConversationTurn
GetLastTurn returns a copy of the most recent conversation turn.
func (*ConversationContext) GetSummary ¶
func (c *ConversationContext) GetSummary() ContextSummary
GetSummary returns a summary of the conversation context.
func (*ConversationContext) SetExtension ¶ added in v0.100.0
func (c *ConversationContext) SetExtension(key string, value any)
SetExtension stores a domain-specific extension by key.
func (*ConversationContext) SetLastRoute ¶
func (c *ConversationContext) SetLastRoute(routeType ChatRouteType)
SetLastRoute sets the last successful route for intent stickiness (Issue #163).
func (*ConversationContext) ToHistoryPrompt ¶
func (c *ConversationContext) ToHistoryPrompt() string
ToHistoryPrompt converts the conversation history to a string format suitable for LLM context. It formats turns as "User: ...\nAssistant: ..." and optionally includes tool usage summaries.
func (*ConversationContext) ToJSON ¶
func (c *ConversationContext) ToJSON() (string, error)
ToJSON exports the conversation context to JSON for persistence.
type ConversationTurn ¶
type ConversationTurn struct {
Timestamp time.Time
UserInput string
AgentOutput string
ToolCalls []ToolCallRecord
}
ConversationTurn represents a single turn in the conversation.
type DangerBlockEvent
deprecated
type DangerBlockEvent = runner.DangerBlockEvent
DangerBlockEvent is an alias for runner.DangerBlockEvent.
Deprecated: Use runner.DangerBlockEvent directly.
type DangerDetector
deprecated
DangerDetector is an alias for runner.Detector.
Deprecated: Use runner.Detector directly.
func NewDangerDetector
deprecated
func NewDangerDetector(logger *slog.Logger) *DangerDetector
NewDangerDetector creates a new danger detector.
Deprecated: Use runner.NewDetector directly.
type DangerLevel
deprecated
type DangerLevel = runner.DangerLevel
DangerLevel is an alias for runner.DangerLevel.
Deprecated: Use runner.DangerLevel directly.
type ErrorClass ¶
type ErrorClass int
ErrorClass represents the category of error for retry decisions.
const ( // Examples: network timeout, temporary service unavailability. ErrorClassTransient ErrorClass = iota // Examples: validation failures, permission denied, invalid input. ErrorClassPermanent // Examples: schedule overlap, duplicate booking. ErrorClassConflict )
func (ErrorClass) String ¶
func (e ErrorClass) String() string
String returns the string representation of ErrorClass.
type ErrorRecovery ¶
type ErrorRecovery struct {
// contains filtered or unexported fields
}
ErrorRecovery provides automatic error recovery for agent executions. It attempts to recover from certain error types by modifying inputs and retrying. This struct is safe for concurrent use as long as configuration is not modified after creation. Use WithTimezone to create new instances with different settings.
func NewErrorRecovery ¶
func NewErrorRecovery(timeService aitime.TimeService) *ErrorRecovery
NewErrorRecovery creates a new ErrorRecovery instance.
func (*ErrorRecovery) ExecuteWithRecovery ¶
func (r *ErrorRecovery) ExecuteWithRecovery( ctx context.Context, executor ExecutorFunc, input string, ) (string, error)
ExecuteWithRecovery executes the given function with automatic error recovery. If the execution fails with a recoverable error, it attempts to fix the input and retry once.
Returns:
- On success: (result, nil)
- On failure: (user-friendly message, original error)
Use ExecuteWithRecoveryDetailed if you need more detailed execution information.
func (*ErrorRecovery) ExecuteWithRecoveryDetailed ¶
func (r *ErrorRecovery) ExecuteWithRecoveryDetailed( ctx context.Context, executor ExecutorFunc, input string, ) RecoveryResult
ExecuteWithRecoveryDetailed executes with recovery and returns detailed result. This is the recommended method when you need to programmatically distinguish between successful results and error messages.
func (*ErrorRecovery) WithTimezone ¶
func (r *ErrorRecovery) WithTimezone(tz string) *ErrorRecovery
WithTimezone returns a new ErrorRecovery instance with the specified timezone. This method is safe for concurrent use as it creates a new instance.
type EventCallback
deprecated
type EventCallback = runner.EventCallback
EventCallback is an alias for runner.EventCallback.
Deprecated: Use runner.EventCallback directly.
type EventWithMeta
deprecated
type EventWithMeta = runner.EventWithMeta
EventWithMeta is an alias for runner.EventWithMeta.
Deprecated: Use runner.EventWithMeta directly.
func NewEventWithMeta
deprecated
func NewEventWithMeta(eventType, eventData string, meta *EventMeta) *EventWithMeta
NewEventWithMeta creates a new EventWithMeta.
Deprecated: Use runner.NewEventWithMeta directly.
type ExecutorFunc ¶
ExecutorFunc is the function signature for agent executors.
type ExpertRegistryInterface ¶ added in v0.100.0
type ExpertRegistryInterface interface {
ExecuteExpert(ctx context.Context, expertName string, input string, callback func(eventType string, eventData string) error) error
}
ExpertRegistryInterface defines the interface for accessing expert agents.
type GenericCache ¶
type GenericCache[T any] struct { // contains filtered or unexported fields }
GenericCache is a generic type-safe cache wrapper. GenericCache 是泛型类型安全的缓存包装器。
func NewGenericCache ¶
func NewGenericCache[T any](maxEntries int, ttl time.Duration) *GenericCache[T]
NewGenericCache creates a new generic cache. NewGenericCache 创建一个新的泛型缓存。
func (*GenericCache[T]) Clear ¶
func (g *GenericCache[T]) Clear()
Clear removes all entries from the generic cache. Clear 从泛型缓存中移除所有条目。
func (*GenericCache[T]) Delete ¶
func (g *GenericCache[T]) Delete(key string)
Delete removes a key from the generic cache. Delete 从泛型缓存中删除键。
func (*GenericCache[T]) Get ¶
func (g *GenericCache[T]) Get(key string) (T, bool)
Get retrieves a value from the generic cache. Get 从泛型缓存中检索值。
func (*GenericCache[T]) Set ¶
func (g *GenericCache[T]) Set(key string, value T)
Set stores a value in the generic cache. Set 在泛型缓存中存储值。
func (*GenericCache[T]) Size ¶
func (g *GenericCache[T]) Size() int
Size returns the current number of entries in the generic cache. Size 返回泛型缓存中的当前条目数。
func (*GenericCache[T]) Stats ¶
func (g *GenericCache[T]) Stats() CacheStats
Stats returns cache statistics for the generic cache. Stats 返回泛型缓存的缓存统计信息。
type HandoffResult ¶ added in v0.100.0
type HandoffResult struct {
// Success indicates whether the handoff was successful.
Success bool `json:"success"`
// FromExpert is the original expert that could not handle the request.
FromExpert string `json:"from_expert"`
// ToExpert is the expert that took over (if successful).
ToExpert string `json:"to_expert,omitempty"`
// Error is the error message if handoff failed.
Error string `json:"error,omitempty"`
// FallbackMessage is a user-friendly message when handoff fails.
FallbackMessage string `json:"fallback_message,omitempty"`
}
HandoffResult contains the result of a handoff operation from ChatRouter.
type IntentClassifier ¶
type IntentClassifier struct {
// contains filtered or unexported fields
}
- Batch tasks (IntentBatchCreate) → Plan-Execute mode.
func NewIntentClassifier ¶
func NewIntentClassifier() *IntentClassifier
NewIntentClassifier creates a new IntentClassifier with default patterns.
func (*IntentClassifier) Classify ¶
func (ic *IntentClassifier) Classify(input string) TaskIntent
Classify determines the intent of the user input. Handles negation patterns (e.g., "不要创建", "不是今天").
func (*IntentClassifier) ClassifyAndRoute ¶
func (ic *IntentClassifier) ClassifyAndRoute(input string) (TaskIntent, bool)
ClassifyAndRoute is a convenience method that classifies and returns the execution mode.
func (*IntentClassifier) ShouldUsePlanExecute ¶
func (ic *IntentClassifier) ShouldUsePlanExecute(intent TaskIntent) bool
ShouldUsePlanExecute returns true if the intent should use Plan-Execute mode.
type IntentKeywordProvider ¶ added in v0.100.1
type IntentKeywordProvider interface {
// GetIntentKeywords returns a map of intent names to their related keywords.
GetIntentKeywords() map[string][]string
}
IntentKeywordProvider defines the interface for providing intent keywords for sticky routing. This enables dynamic loading of keywords from expert configurations.
type LRUCache ¶
type LRUCache struct {
// contains filtered or unexported fields
}
LRUCache is a thread-safe LRU (Least Recently Used) cache with TTL support. LRUCache 是一个线程安全的 LRU(最近最少使用)缓存,支持 TTL。
func NewLRUCache ¶
NewLRUCache creates a new LRUCache. NewLRUCache 创建一个新的 LRUCache。
Parameters:
- maxEntries: Maximum number of entries in the cache (must be > 0)
- ttl: Time-to-live for cache entries (0 = no expiration)
Example:
// Create a cache with max 100 entries and 5 minute TTL cache := NewLRUCache(100, 5*time.Minute)
func (*LRUCache) Clear ¶
func (c *LRUCache) Clear()
Clear removes all entries from the cache. Clear 从缓存中移除所有条目。
func (*LRUCache) Get ¶
Get retrieves a value from the cache. Get 从缓存中检索值。
Returns:
- value: The cached value (or nil if not found/expired)
- found: Whether the value was found and not expired
func (*LRUCache) Set ¶
Set stores a value in the cache. Set 在缓存中存储值。
If the key already exists, the value is updated and the entry is moved to the front. If the cache is full, the least recently used entry is evicted.
func (*LRUCache) Stats ¶
func (c *LRUCache) Stats() CacheStats
Stats returns cache statistics. Stats 返回缓存统计信息。
type MissingCapability ¶ added in v0.100.0
type MissingCapability struct {
// Expert is the name of the expert that cannot handle the request.
Expert string
// MissingCapabilities lists the capabilities that the expert lacks.
MissingCapabilities []string
// OriginalError is the original error message from the expert.
OriginalError error
// Suggestion is an optional hint about which expert might help.
Suggestion string
}
MissingCapability represents an error when an expert lacks the required capability.
func NewMissingCapability ¶ added in v0.100.0
func NewMissingCapability(expert string, missingCaps []string, originalErr error) *MissingCapability
NewMissingCapability creates a new MissingCapability error.
func (*MissingCapability) Error ¶ added in v0.100.0
func (e *MissingCapability) Error() string
Error returns a sanitized error message.
func (*MissingCapability) Unwrap ¶ added in v0.100.0
func (e *MissingCapability) Unwrap() error
Unwrap returns the original error for errors.Is/As.
type NativeTool ¶
type NativeTool struct {
// contains filtered or unexported fields
}
NativeTool implements ToolWithSchema with direct function execution.
func (*NativeTool) Description ¶
func (t *NativeTool) Description() string
Description returns the tool description.
func (*NativeTool) Parameters ¶
func (t *NativeTool) Parameters() map[string]interface{}
Parameters returns the JSON Schema for parameters.
type NormalSessionStats ¶
type NormalSessionStats struct {
// Session identification
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
AgentType string `json:"agent_type"`
ModelUsed string `json:"model_used"`
// Token usage (accumulated across all LLM calls)
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
CacheReadTokens int `json:"cache_read_tokens,omitempty"`
CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
// Timing (milliseconds)
ThinkingDurationMs int64 `json:"thinking_duration_ms"` // Time to first token (avg)
GenerationDurationMs int64 `json:"generation_duration_ms"` // Content generation time (total)
TotalDurationMs int64 `json:"total_duration_ms"` // Wall-clock time
// Tool usage
ToolCallCount int `json:"tool_call_count"`
ToolDurationMs int64 `json:"tool_duration_ms"` // Total tool execution time
FilesModified int32 `json:"files_modified,omitempty"` // Number of files modified
FilePaths []string `json:"file_paths,omitempty"` // List of file paths modified
ToolsUsed []string `json:"tools_used,omitempty"`
// Cost estimation (in milli-cents: 1/1000 of a US cent, or 1/100000 USD)
// For DeepSeek: $0.14/M input, $0.28/M output = 0.014¢/1K input, 0.028¢/1K output
TotalCostMilliCents int64 `json:"total_cost_milli_cents"`
// contains filtered or unexported fields
}
NormalSessionStats represents the accumulated statistics for a single agent session in normal mode. A session may consist of multiple LLM calls (e.g., ReAct loops with tool calls). NormalSessionStats 表示普通模式下单个代理会话的累积统计数据。 一个会话可能包含多次 LLM 调用(例如,带有工具调用的 ReAct 循环)。
func (*NormalSessionStats) GetStatsSnapshot ¶
func (s *NormalSessionStats) GetStatsSnapshot() *NormalSessionStats
GetStatsSnapshot returns a thread-safe snapshot of the current statistics. GetStatsSnapshot 返回当前统计数据的线程安全快照。
type ParrotAgent ¶
type ParrotAgent interface {
// Name returns the parrot's name (e.g., "memo", "schedule", "amazing", "geek", "evolution").
Name() string
// Execute processes the user input and streams events via callback.
// history is optional - pass nil if no conversation history is needed.
// history 是可选的 - 如果不需要对话历史,传 nil。
Execute(ctx context.Context, userInput string, history []string, callback EventCallback) error
// SelfDescribe returns the parrot's metacognitive information.
SelfDescribe() *ParrotSelfCognition
// GetSessionStats returns the session statistics.
// Returns nil if stats are not available.
GetSessionStats() *NormalSessionStats
}
ParrotAgent is the interface that all parrot agents must implement. ParrotAgent 是所有鹦鹉代理必须实现的接口。
type ParrotError ¶
ParrotError represents an error that occurred during parrot execution. ParrotError 表示鹦鹉执行期间发生的错误。
func NewParrotError ¶
func NewParrotError(parrotName, operation string, err error) *ParrotError
NewParrotError creates a new ParrotError. NewParrotError 创建一个新的 ParrotError.
func (*ParrotError) Unwrap ¶
func (e *ParrotError) Unwrap() error
Unwrap returns the underlying error.
type ParrotSelfCognition ¶
type ParrotSelfCognition struct {
Name string `json:"name"`
Emoji string `json:"emoji"`
Title string `json:"title"`
Personality []string `json:"personality"`
Capabilities []string `json:"capabilities"`
CapabilityTriggers map[string][]string `json:"capability_triggers,omitempty"` // Capability -> Triggers/Keywords
Limitations []string `json:"limitations"`
WorkingStyle string `json:"working_style"`
// Routing configuration for Layer 2 rule matching.
// 路由配置,用于 Layer 2 规则匹配。
Routing *RoutingConfig `json:"routing,omitempty" yaml:"routing,omitempty"`
}
ParrotSelfCognition represents the metacognitive information about a parrot agent. ParrotSelfCognition 表示鹦鹉代理的元认知信息。
type ParrotStreamAdapter ¶
type ParrotStreamAdapter struct {
// contains filtered or unexported fields
}
ParrotStreamAdapter is an adapter that converts event callbacks to the format expected by the streaming response handler. ParrotStreamAdapter 是一个适配器,将事件回调转换为流响应处理器期望的格式。
func NewParrotStreamAdapter ¶
func NewParrotStreamAdapter(send func(eventType string, eventData any) error) *ParrotStreamAdapter
NewParrotStreamAdapter creates a new stream adapter from a send function. NewParrotStreamAdapter 从发送函数创建新的流适配器。
type PhaseChangeEvent
deprecated
type PhaseChangeEvent = runner.PhaseChangeEvent
PhaseChangeEvent is an alias for runner.PhaseChangeEvent.
Deprecated: Use runner.PhaseChangeEvent directly.
type ProcessingPhase
deprecated
type ProcessingPhase = runner.ProcessingPhase
ProcessingPhase is an alias for runner.ProcessingPhase.
Deprecated: Use runner.ProcessingPhase directly.
type ProgressEvent
deprecated
type ProgressEvent = runner.ProgressEvent
ProgressEvent is an alias for runner.ProgressEvent.
Deprecated: Use runner.ProgressEvent directly.
type RecoveryResult ¶
RecoveryResult contains the result of an execution with recovery.
type RoutingConfig ¶ added in v0.100.0
type RoutingConfig struct {
// Keywords are simple keyword triggers.
// 简单关键词触发器。
Keywords []string `json:"keywords,omitempty" yaml:"keywords,omitempty"`
// Patterns are regex patterns for more complex matching.
// 正则表达式模式,用于更复杂的匹配。
Patterns []string `json:"patterns,omitempty" yaml:"patterns,omitempty"`
// Excludes are patterns that should NOT route to this agent.
// 排除规则:匹配这些模式时不路由到此代理。
Excludes []string `json:"excludes,omitempty" yaml:"excludes,omitempty"`
// Priority determines routing priority when multiple agents match.
// 优先级:多个代理匹配时的优先级(数值越大优先级越高)。
Priority int `json:"priority,omitempty" yaml:"priority,omitempty"`
// SemanticExamples are example sentences for Layer 3 semantic routing.
// 这些示例会在启动时预计算为 embedding 向量。
// 当 Layer 2 规则匹配失败时,使用向量相似度进行匹配。
SemanticExamples []string `json:"semantic_examples,omitempty" yaml:"semantic_examples,omitempty"`
}
RoutingConfig represents routing configuration for an expert agent. RoutingConfig 表示专家代理的路由配置,用于 Layer 2 规则匹配。
type SafeCallbackFunc
deprecated
type SafeCallbackFunc = runner.SafeCallbackFunc
SafeCallbackFunc is an alias for runner.SafeCallbackFunc.
Deprecated: Use runner.SafeCallbackFunc directly.
func SafeCallback
deprecated
func SafeCallback(callback EventCallback) SafeCallbackFunc
SafeCallback wraps an EventCallback to log errors instead of propagating them.
Deprecated: Use runner.SafeCallback directly.
type SessionManager
deprecated
type SessionManager = runner.SessionManager
SessionManager is an alias for runner.SessionManager.
Deprecated: Use runner.SessionManager directly.
type SessionStats
deprecated
type SessionStats = runner.SessionStats
SessionStats is an alias for runner.SessionStats.
Deprecated: Use runner.SessionStats directly.
type SessionStatsData
deprecated
type SessionStatsData = runner.SessionStatsData
SessionStatsData is an alias for runner.SessionStatsData.
Deprecated: Use runner.SessionStatsData directly.
type SessionStatsProvider ¶
type SessionStatsProvider interface {
GetSessionStats() *SessionStats
}
SessionStatsProvider is the interface for agents that provide session statistics. SessionStatsProvider 是提供会话统计信息的代理接口。
This interface is implemented by GeekParrot and EvolutionParrot which have direct access to CCRunner's SessionStats.
type SessionStatus
deprecated
type SessionStatus = runner.SessionStatus
SessionStatus is an alias for runner.SessionStatus.
Deprecated: Use runner.SessionStatus directly.
type SimpleHandoffHandler ¶ added in v0.100.0
type SimpleHandoffHandler interface {
// HandleSimpleHandoff processes a simplified handoff request.
HandleSimpleHandoff(req SimpleHandoffRequest) SimpleHandoverResult
}
SimpleHandoffHandler is a simple interface for handling handoff between experts. This avoids circular imports by using interface{} and type assertions.
type SimpleHandoffRequest ¶ added in v0.100.0
type SimpleHandoffRequest struct {
TaskID string
Agent string
Input string
Capacity string
Reason string
}
SimpleHandoffRequest is a simplified request for handoff.
type SimpleHandoverResult ¶ added in v0.100.0
type SimpleHandoverResult struct {
Success bool
FromExpert string
ToExpert string
NewTaskInput string
Error string
FallbackMessage string
}
SimpleHandoverResult is a simplified result for handoff.
type StreamMessage
deprecated
type StreamMessage = runner.StreamMessage
StreamMessage is an alias for runner.StreamMessage.
Deprecated: Use runner.StreamMessage directly.
type TaskIntent
deprecated
TaskIntent represents the type of task across all agents. This is a type alias to routing.Intent for backward compatibility.
Deprecated: Use routing.Intent directly for new code.
const ( // Schedule-related intents. IntentSimpleCreate TaskIntent = routing.IntentScheduleCreate // 创建单个日程 IntentSimpleQuery TaskIntent = routing.IntentScheduleQuery // 查询日程/空闲 IntentSimpleUpdate TaskIntent = routing.IntentScheduleUpdate // 修改/删除日程 IntentBatchCreate TaskIntent = routing.IntentBatchSchedule // 重复日程 IntentConflictResolve TaskIntent = "schedule_conflict" // 处理冲突 (not in routing yet) // Memo-related intents. IntentMemoSearch TaskIntent = routing.IntentMemoSearch // 搜索笔记 IntentMemoCreate TaskIntent = routing.IntentMemoCreate // 创建笔记 // Legacy aliases for backward compatibility. IntentScheduleQuery TaskIntent = routing.IntentScheduleQuery IntentScheduleCreate TaskIntent = routing.IntentScheduleCreate IntentScheduleUpdate TaskIntent = routing.IntentScheduleUpdate IntentBatchSchedule TaskIntent = routing.IntentBatchSchedule )
Intent constants - aliases to routing.Intent constants for backward compatibility.
type Tool ¶
type Tool interface {
// Name returns the name of the tool.
Name() string
// Description returns a description of what the tool does.
Description() string
// Run executes the tool with the given input.
// Run 使用给定的输入执行工具。
Run(ctx context.Context, input string) (string, error)
}
Tool is the interface for agent tools. Tool 是代理工具的接口。
type ToolCallRecord ¶
type ToolCallRecord struct {
Timestamp time.Time
Tool string
Input string
Output string
Duration time.Duration
Success bool
}
ToolCallRecord records a tool invocation.
type ToolOption ¶
type ToolOption func(*BaseTool)
ToolOption is a function that configures a BaseTool. ToolOption 是配置 BaseTool 的函数。
func WithTimeout ¶
func WithTimeout(timeout time.Duration) ToolOption
WithTimeout sets a timeout for tool execution. WithTimeout 设置工具执行的超时时间。
func WithValidator ¶
func WithValidator(validator func(input string) error) ToolOption
WithValidator sets a custom input validator. WithValidator 设置自定义输入验证器。
type ToolRegistry ¶
type ToolRegistry struct {
// contains filtered or unexported fields
}
ToolRegistry manages a collection of tools. ToolRegistry 管理工具集合。
func NewToolRegistry ¶
func NewToolRegistry() *ToolRegistry
NewToolRegistry creates a new ToolRegistry. NewToolRegistry 创建一个新的 ToolRegistry。
func (*ToolRegistry) Count ¶
func (r *ToolRegistry) Count() int
Count returns the number of registered tools. Count 返回已注册工具的数量。
func (*ToolRegistry) Describe ¶
func (r *ToolRegistry) Describe() string
Describe returns a description string for all tools. Describe 返回所有工具的描述字符串。
func (*ToolRegistry) Get ¶
func (r *ToolRegistry) Get(name string) (Tool, bool)
Get retrieves a tool by name. Get 按名称获取工具。
func (*ToolRegistry) List ¶
func (r *ToolRegistry) List() []string
List returns all registered tool names. List 返回所有已注册的工具名称。
func (*ToolRegistry) Register ¶
func (r *ToolRegistry) Register(tool Tool) error
Register adds a tool to the registry. Register 向注册表添加工具。
type ToolResult ¶
type ToolResult struct {
Name string `json:"name"`
Input string `json:"input"`
Output string `json:"output"`
Error string `json:"error"`
Duration time.Duration `json:"duration"`
Timestamp int64 `json:"timestamp"`
Success bool `json:"success"`
}
ToolResult represents the result of a tool execution. ToolResult 表示工具执行的结果。
func NewToolResult ¶
func NewToolResult(name, input, output string, duration time.Duration, err error) *ToolResult
NewToolResult creates a new ToolResult. NewToolResult 创建一个新的 ToolResult。
type ToolWithSchema ¶
type ToolWithSchema interface {
Tool
// Parameters returns the JSON Schema for the tool's input parameters.
Parameters() map[string]interface{}
}
ToolWithSchema extends the Tool interface to include JSON Schema definition. This is needed for the new Agent framework to provide tool definitions to the LLM.
func NewNativeTool ¶
func NewNativeTool( name string, description string, execute func(ctx context.Context, input string) (string, error), parameters map[string]interface{}, ) ToolWithSchema
NewNativeTool creates a new NativeTool.
func ToolFromLegacy ¶
func ToolFromLegacy( name, description string, runFunc func(ctx context.Context, input string) (string, error), inputTypeFunc func() map[string]interface{}, ) ToolWithSchema
ToolFromLegacy creates a ToolWithSchema from a tool that has InputType() method. This adapts existing tools like ScheduleQueryTool to the new framework.
type UsageStats
deprecated
type UsageStats = runner.UsageStats
UsageStats is an alias for runner.UsageStats.
Deprecated: Use runner.UsageStats directly.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package events provides event callback types for the agent system.
|
Package events provides event callback types for the agent system. |
|
Package orchestrator implements the Orchestrator-Workers pattern for multi-agent coordination.
|
Package orchestrator implements the Orchestrator-Workers pattern for multi-agent coordination. |
|
Package registry provides metrics collection for UniversalParrot.
|
Package registry provides metrics collection for UniversalParrot. |
|
Package tools provides tool-level result caching for AI agents.
|
Package tools provides tool-level result caching for AI agents. |
|
schedule
Package schedule provides thin tool adapters for schedule operations.
|
Package schedule provides thin tool adapters for schedule operations. |
|
Package universal provides configuration loading for UniversalParrot.
|
Package universal provides configuration loading for UniversalParrot. |