Documentation
¶
Overview ¶
Package interfaces defines core constants used across all layers of the GoAgent framework. These constants are foundational and can be imported by any layer without violating the import layering rules (Layer 1 - Foundation).
Package interfaces provides canonical interface definitions for the agent framework.
All concrete implementations should reference these interfaces to ensure type compatibility across packages. This package serves as the single source of truth for all shared interfaces.
Key Interfaces:
- Agent: Autonomous agent interface
- Runnable: Base execution interface
- Tool: Tool execution interface
- VectorStore: Vector storage and search
- MemoryManager: Memory management
- Checkpointer: State checkpointing
- Store: Key-value storage
Package interfaces defines field name constants used across the GoAgent framework. These constants provide standardized field names for JSON serialization, map keys, and data structure access patterns.
Package interfaces defines HTTP-related constants used across the GoAgent framework. These constants provide standardized HTTP methods, headers, content types, and status codes.
Package interfaces provides lifecycle management interfaces.
This file defines unified lifecycle management for all GoAgent components:
- Tools, Agents, Middleware, and Plugins all implement common lifecycle hooks
- Enables proper initialization, graceful shutdown, and health monitoring
- Supports dependency ordering and coordinated startup/shutdown
Package interfaces defines status and state constants used across the GoAgent framework. These constants provide standardized status values for execution states, task states, and operation outcomes.
Index ¶
- Constants
- type Agent
- type Case
- type Checkpoint
- type CheckpointMetadata
- type Checkpointer
- type Conversation
- type ConversationMemory
- type DependencyAware
- type Document
- type HealthState
- type HealthStatus
- type Input
- type Lifecycle
- type LifecycleAware
- type LifecycleManager
- type LifecycleState
- type MemoryManager
- type Message
- type Output
- type Plan
- type ProgramCode
- type ReasoningChunk
- type ReasoningInput
- type ReasoningOutput
- type ReasoningPattern
- type ReasoningStep
- type ReasoningStrategy
- type ReasoningToolCall
- type Reloadable
- type Runnable
- type SkeletonPoint
- type State
- type Step
- type Store
- type StreamChunk
- type ThoughtNode
- type TokenUsage
- type Tool
- type ToolCall
- type ToolExecutor
- type ToolInput
- type ToolOutput
- type ToolResult
- type ValidatableTool
- type VectorStore
Constants ¶
const ( // RoleSystem represents system-level instructions or configuration messages RoleSystem = "system" // RoleUser represents messages from the end user RoleUser = "user" // RoleAssistant represents messages from the AI assistant RoleAssistant = "assistant" // RoleFunction represents function/tool call results RoleFunction = "function" // RoleTool represents tool execution messages RoleTool = "tool" )
Message Roles define the role of a message in a conversation. These constants are used across LLM interactions, memory systems, and agent communications.
const ( // KeyKey represents a generic key identifier KeyKey = "key" // KeyValue represents a generic value KeyValue = "value" // KeyMetadata represents metadata information KeyMetadata = "metadata" // KeyAttributes represents additional attributes KeyAttributes = "attributes" // KeyContext represents contextual information KeyContext = "context" // KeyConfig represents configuration data KeyConfig = "config" // KeyOptions represents options or settings KeyOptions = "options" )
Generic Context Keys are commonly used keys for context values across the framework.
const ( // SeparatorComma is a comma separator SeparatorComma = "," // SeparatorColon is a colon separator SeparatorColon = ":" // SeparatorNewline is a newline separator SeparatorNewline = "\n" // SeparatorSpace is a space separator SeparatorSpace = " " // SeparatorDash is a dash separator SeparatorDash = "-" // SeparatorUnderscore is an underscore separator SeparatorUnderscore = "_" )
Common Separators and Delimiters
const ( // EmptyString represents an empty string EmptyString = "" // DefaultString represents a default string value DefaultString = "default" // UnknownString represents an unknown value UnknownString = "unknown" // NoneString represents no value NoneString = "none" )
Common String Values
const ( // StringTrue represents boolean true as a string StringTrue = "true" // StringFalse represents boolean false as a string StringFalse = "false" )
Boolean String Representations
const ( // FieldID represents a unique identifier FieldID = "id" // FieldName represents a name field FieldName = "name" // FieldDescription represents a description field FieldDescription = "description" // FieldType represents a type field FieldType = "type" // FieldVersion represents a version field FieldVersion = "version" // FieldTimestamp represents a timestamp field FieldTimestamp = "timestamp" // FieldCreatedAt represents a creation time field FieldCreatedAt = "created_at" // FieldUpdatedAt represents an update time field FieldUpdatedAt = "updated_at" // FieldDeletedAt represents a deletion time field FieldDeletedAt = "deleted_at" )
Common Field Names define frequently used field identifiers across the framework.
const ( // FieldInput represents input data FieldInput = "input" // FieldOutput represents output data FieldOutput = "output" // FieldResult represents a result value FieldResult = "result" // FieldData represents generic data FieldData = "data" // FieldMessage represents a message field FieldMessage = "message" // FieldError represents an error field FieldError = "error" // FieldErrors represents multiple errors FieldErrors = "errors" // FieldStatus represents a status field FieldStatus = "status" // FieldCode represents a code field (status code, error code, etc.) FieldCode = "code" // FieldSuccess represents a success indicator FieldSuccess = "success" // FieldResponse represents a response field FieldResponse = "response" // FieldRequest represents a request field FieldRequest = "request" )
Request and Response Fields define data exchange field names.
const ( // FieldURL represents a URL field FieldURL = "url" // FieldMethod represents an HTTP method field FieldMethod = "method" // FieldHeaders represents HTTP headers FieldHeaders = "headers" // FieldBody represents a request/response body FieldBody = "body" // FieldStatusCode represents an HTTP status code FieldStatusCode = "status_code" // FieldQuery represents query parameters FieldQuery = "query" // FieldParams represents path parameters FieldParams = "params" // FieldPath represents a URL path FieldPath = "path" // FieldHost represents a host field FieldHost = "host" // FieldPort represents a port field FieldPort = "port" // FieldScheme represents a URL scheme (http/https) FieldScheme = "scheme" )
HTTP Request Fields define HTTP-specific field names.
const ( // FieldSessionID represents a session identifier FieldSessionID = "session_id" // FieldThreadID represents a thread identifier FieldThreadID = "thread_id" // FieldConversationID represents a conversation identifier FieldConversationID = "conversation_id" // FieldUserID represents a user identifier FieldUserID = "user_id" // FieldAgentID represents an agent identifier FieldAgentID = "agent_id" // FieldToolID represents a tool identifier FieldToolID = "tool_id" // FieldNamespace represents a namespace field FieldNamespace = "namespace" // FieldAgentName represents an agent name FieldAgentName = "agent_name" // FieldToolName represents a tool name FieldToolName = "tool_name" // FieldModel represents an LLM model name FieldModel = "model" // FieldProvider represents an LLM provider name FieldProvider = "provider" // FieldEndpoint represents an API endpoint FieldEndpoint = "endpoint" // FieldOperation represents an operation name FieldOperation = "operation" // FieldComponent represents a component name FieldComponent = "component" // FieldService represents a service name FieldService = "service" )
Context and Session Fields define context-specific field names.
const ( // FieldDuration represents a duration measurement FieldDuration = "duration" // FieldLatency represents latency measurement FieldLatency = "latency" // FieldCount represents a count value FieldCount = "count" // FieldTotal represents a total value FieldTotal = "total" // FieldAverage represents an average value FieldAverage = "average" // FieldMin represents a minimum value FieldMin = "min" // FieldMax represents a maximum value FieldMax = "max" // FieldRate represents a rate value FieldRate = "rate" // FieldPercentage represents a percentage value FieldPercentage = "percentage" // FieldSize represents a size measurement FieldSize = "size" // FieldBytes represents a bytes count FieldBytes = "bytes" )
Metrics and Performance Fields define measurement-related field names.
const ( // FieldTimeout represents a timeout value FieldTimeout = "timeout" // FieldRetry represents a retry count FieldRetry = "retry" // FieldMaxRetries represents maximum retry attempts FieldMaxRetries = "max_retries" // FieldInterval represents an interval duration FieldInterval = "interval" // FieldDelay represents a delay duration FieldDelay = "delay" // FieldBatchSize represents a batch size value FieldBatchSize = "batch_size" // FieldPageSize represents a page size for pagination FieldPageSize = "page_size" // FieldPage represents a page number FieldPage = "page" // FieldLimit represents a limit value FieldLimit = "limit" // FieldOffset represents an offset value FieldOffset = "offset" // FieldSort represents a sort field FieldSort = "sort" // FieldOrder represents a sort order FieldOrder = "order" // FieldFilter represents a filter field FieldFilter = "filter" )
Configuration and Settings Fields define configuration-related field names.
const ( // FieldFunction represents a function name FieldFunction = "function" // FieldArguments represents function arguments FieldArguments = "arguments" // FieldParameters represents function parameters FieldParameters = "parameters" // FieldReturn represents a return value FieldReturn = "return" // FieldCallback represents a callback function FieldCallback = "callback" // FieldSchema represents a schema definition FieldSchema = "schema" // FieldProperties represents object properties FieldProperties = "properties" // FieldRequired represents required fields FieldRequired = "required" )
Tool and Function Fields define tool execution-related field names.
const ( // FieldState represents a state value FieldState = "state" // FieldCheckpoint represents a checkpoint identifier FieldCheckpoint = "checkpoint" // FieldSnapshot represents a snapshot value FieldSnapshot = "snapshot" // FieldHistory represents historical data FieldHistory = "history" // FieldPrevious represents a previous value FieldPrevious = "previous" // FieldCurrent represents a current value FieldCurrent = "current" // FieldNext represents a next value FieldNext = "next" )
State and Checkpoint Fields define state management field names.
const ( // FieldContent represents content data FieldContent = "content" // FieldText represents text content FieldText = "text" // FieldTitle represents a title field FieldTitle = "title" // FieldSubtitle represents a subtitle field FieldSubtitle = "subtitle" // FieldAuthor represents an author field FieldAuthor = "author" // FieldSource represents a source field FieldSource = "source" // FieldFormat represents a format field FieldFormat = "format" // FieldEncoding represents an encoding field FieldEncoding = "encoding" // FieldLanguage represents a language field FieldLanguage = "language" // FieldTags represents tags or labels FieldTags = "tags" // FieldCategories represents categories FieldCategories = "categories" )
Content and Media Fields define content-related field names.
const ( // MethodGet represents the HTTP GET method MethodGet = "GET" // MethodPost represents the HTTP POST method MethodPost = "POST" // MethodPut represents the HTTP PUT method MethodPut = "PUT" // MethodDelete represents the HTTP DELETE method MethodDelete = "DELETE" // MethodPatch represents the HTTP PATCH method MethodPatch = "PATCH" // MethodHead represents the HTTP HEAD method MethodHead = "HEAD" // MethodOptions represents the HTTP OPTIONS method MethodOptions = "OPTIONS" // MethodConnect represents the HTTP CONNECT method MethodConnect = "CONNECT" // MethodTrace represents the HTTP TRACE method MethodTrace = "TRACE" )
HTTP Methods define standard HTTP request methods.
const ( // ContentTypeJSON represents JSON content type ContentTypeJSON = "application/json" // ContentTypeText represents plain text content type ContentTypeText = "text/plain" // ContentTypeHTML represents HTML content type ContentTypeHTML = "text/html" // ContentTypeXML represents XML content type ContentTypeXML = "application/xml" // ContentTypeForm represents URL-encoded form data ContentTypeForm = "application/x-www-form-urlencoded" // ContentTypeMultipart represents multipart form data ContentTypeMultipart = "multipart/form-data" // ContentTypeEventStream represents server-sent events stream ContentTypeEventStream = "text/event-stream" // ContentTypeOctetStream represents binary data ContentTypeOctetStream = "application/octet-stream" )
Content Types define standard MIME types for HTTP requests and responses.
const ( // HeaderContentType represents the Content-Type header HeaderContentType = "Content-Type" // HeaderAccept represents the Accept header HeaderAccept = "Accept" // HeaderAuthorization represents the Authorization header HeaderAuthorization = "Authorization" // HeaderUserAgent represents the User-Agent header HeaderUserAgent = "User-Agent" // HeaderAcceptEncoding represents the Accept-Encoding header HeaderAcceptEncoding = "Accept-Encoding" // HeaderContentEncoding represents the Content-Encoding header HeaderContentEncoding = "Content-Encoding" // HeaderCacheControl represents the Cache-Control header HeaderCacheControl = "Cache-Control" // HeaderConnection represents the Connection header HeaderConnection = "Connection" // HeaderCookie represents the Cookie header HeaderCookie = "Cookie" // HeaderSetCookie represents the Set-Cookie header HeaderSetCookie = "Set-Cookie" // HeaderLocation represents the Location header HeaderLocation = "Location" // HeaderReferer represents the Referer header HeaderReferer = "Referer" // HeaderXForwardedFor represents the X-Forwarded-For header HeaderXForwardedFor = "X-Forwarded-For" // HeaderXRealIP represents the X-Real-IP header HeaderXRealIP = "X-Real-IP" )
HTTP Headers define standard HTTP header names.
const ( // StatusCodeOK represents HTTP 200 OK StatusCodeOK = 200 // StatusCodeCreated represents HTTP 201 Created StatusCodeCreated = 201 // StatusCodeAccepted represents HTTP 202 Accepted StatusCodeAccepted = 202 // StatusCodeNoContent represents HTTP 204 No Content StatusCodeNoContent = 204 // StatusCodeBadRequest represents HTTP 400 Bad Request StatusCodeBadRequest = 400 StatusCodeUnauthorized = 401 // StatusCodeForbidden represents HTTP 403 Forbidden StatusCodeForbidden = 403 // StatusCodeNotFound represents HTTP 404 Not Found StatusCodeNotFound = 404 // StatusCodeMethodNotAllowed represents HTTP 405 Method Not Allowed StatusCodeMethodNotAllowed = 405 // StatusCodeTimeout represents HTTP 408 Request Timeout StatusCodeTimeout = 408 // StatusCodeConflict represents HTTP 409 Conflict StatusCodeConflict = 409 // StatusCodeTooManyRequests represents HTTP 429 Too Many Requests StatusCodeTooManyRequests = 429 // StatusCodeInternalServerError represents HTTP 500 Internal Server Error StatusCodeInternalServerError = 500 // StatusCodeBadGateway represents HTTP 502 Bad Gateway StatusCodeBadGateway = 502 StatusCodeServiceUnavailable = 503 // StatusCodeGatewayTimeout represents HTTP 504 Gateway Timeout StatusCodeGatewayTimeout = 504 )
HTTP Status Code Ranges
const ( // PathAPIV1 represents the base path for API v1 PathAPIV1 = "/api/v1" // PathAPIV1Agents represents the agents endpoint PathAPIV1Agents = "/api/v1/agents" // PathAPIV1Tools represents the tools endpoint PathAPIV1Tools = "/api/v1/tools" // PathHealth represents the health check endpoint PathHealth = "/health" // PathHealthz represents an alternative health check endpoint PathHealthz = "/healthz" // PathMetrics represents the metrics endpoint PathMetrics = "/metrics" // PathStatus represents the status endpoint PathStatus = "/status" // PathReady represents the readiness endpoint PathReady = "/ready" )
API Paths define common API endpoint paths.
const ( // ProtocolHTTP10 represents HTTP/1.0 ProtocolHTTP10 = "HTTP/1.0" // ProtocolHTTP11 represents HTTP/1.1 ProtocolHTTP11 = "HTTP/1.1" // ProtocolHTTP2 represents HTTP/2 ProtocolHTTP2 = "HTTP/2" )
HTTP Protocol Versions
const ( // CharsetUTF8 represents UTF-8 character encoding CharsetUTF8 = "charset=utf-8" // Bearer represents the Bearer authentication scheme Bearer = "Bearer" // Basic represents the Basic authentication scheme Basic = "Basic" )
Common HTTP Values
const ( // StatusSuccess indicates successful completion StatusSuccess = "success" // StatusFailed indicates a failure occurred StatusFailed = "failed" // StatusError indicates an error occurred StatusError = "error" // StatusPending indicates the operation is pending StatusPending = "pending" // StatusInProgress indicates the operation is currently in progress StatusInProgress = "in_progress" // StatusCompleted indicates the operation has completed StatusCompleted = "completed" // StatusCanceled indicates the operation was canceled StatusCanceled = "canceled" // StatusTimeout indicates the operation timed out StatusTimeout = "timeout" // StatusRetrying indicates the operation is being retried StatusRetrying = "retrying" // StatusSkipped indicates the operation was skipped StatusSkipped = "skipped" // StatusPartial indicates partial completion StatusPartial = "partial" )
Execution Status defines the outcome of an execution or operation.
const ( // TaskStateQueued indicates the task is queued TaskStateQueued = "queued" // TaskStateRunning indicates the task is running TaskStateRunning = "running" // TaskStatePaused indicates the task is paused TaskStatePaused = "paused" // TaskStateWaiting indicates the task is waiting TaskStateWaiting = "waiting" // TaskStateBlocked indicates the task is blocked TaskStateBlocked = "blocked" // TaskStateFinished indicates the task is finished TaskStateFinished = "finished" // TaskStateAborted indicates the task was aborted TaskStateAborted = "aborted" )
Task States define the lifecycle states of a task or workflow step.
const ( // AgentStateIdle indicates the agent is idle AgentStateIdle = "idle" // AgentStateActive indicates the agent is active AgentStateActive = "active" // AgentStateBusy indicates the agent is busy AgentStateBusy = "busy" // AgentStateProcessing indicates the agent is processing AgentStateProcessing = "processing" // AgentStateThinking indicates the agent is in reasoning/thinking phase AgentStateThinking = "thinking" // AgentStateExecuting indicates the agent is executing an action AgentStateExecuting = "executing" // AgentStateWaitingForInput indicates the agent is waiting for input AgentStateWaitingForInput = "waiting_for_input" // AgentStateStopped indicates the agent has stopped AgentStateStopped = "stopped" AgentStateUnavailable = "unavailable" )
Agent States define the operational states of an agent.
const ( // ConnectionStateConnected indicates a successful connection ConnectionStateConnected = "connected" // ConnectionStateDisconnected indicates disconnection ConnectionStateDisconnected = "disconnected" // ConnectionStateConnecting indicates connection in progress ConnectionStateConnecting = "connecting" // ConnectionStateReconnecting indicates reconnection attempt ConnectionStateReconnecting = "reconnecting" // ConnectionStateClosing indicates connection is closing ConnectionStateClosing = "closing" // ConnectionStateClosed indicates connection is closed ConnectionStateClosed = "closed" )
Connection States define network or service connection states.
const ( // HealthStateHealthy indicates healthy state HealthStateHealthy = "healthy" // HealthStateUnhealthy indicates unhealthy state HealthStateUnhealthy = "unhealthy" // HealthStateDegraded indicates degraded performance HealthStateDegraded = "degraded" // HealthStateUnknown indicates unknown health state HealthStateUnknown = "unknown" )
Health States define health check status values.
const ( // AvailabilityStateAvailable indicates service is available AvailabilityStateAvailable = "available" AvailabilityStateUnavailable = "unavailable" // AvailabilityStatePartiallyAvailable indicates partial availability AvailabilityStatePartiallyAvailable = "partially_available" // AvailabilityStateMaintenance indicates maintenance mode AvailabilityStateMaintenance = "maintenance" )
Availability States define service availability status.
const ( // PriorityLow indicates low priority PriorityLow = "low" // PriorityNormal indicates normal priority PriorityNormal = "normal" // PriorityMedium indicates medium priority PriorityMedium = "medium" // PriorityHigh indicates high priority PriorityHigh = "high" // PriorityCritical indicates critical priority PriorityCritical = "critical" // PriorityUrgent indicates urgent priority PriorityUrgent = "urgent" )
Priority Levels define priority classifications.
const ( // SeverityInfo indicates informational severity SeverityInfo = "info" // SeverityDebug indicates debug severity SeverityDebug = "debug" // SeverityWarning indicates warning severity SeverityWarning = "warning" // SeverityError indicates error severity SeverityError = "error" // SeverityFatal indicates fatal severity SeverityFatal = "fatal" )
Severity Levels define issue severity classifications.
const ( // ModeSync indicates synchronous mode ModeSync = "sync" // ModeAsync indicates asynchronous mode ModeAsync = "async" // ModeStreaming indicates streaming mode ModeStreaming = "streaming" // ModeBatch indicates batch mode ModeBatch = "batch" // ModeParallel indicates parallel execution mode ModeParallel = "parallel" // ModeSequential indicates sequential execution mode ModeSequential = "sequential" )
Operation Modes define how an operation should be executed.
const ( // ValidationStateValid indicates valid state ValidationStateValid = "valid" // ValidationStateInvalid indicates invalid state ValidationStateInvalid = "invalid" // ValidationStateUnvalidated indicates not yet validated ValidationStateUnvalidated = "unvalidated" )
Validation States define validation outcomes.
const ( // PermissionStateAllowed indicates permission is granted PermissionStateAllowed = "allowed" // PermissionStateDenied indicates permission is denied PermissionStateDenied = "denied" // PermissionStateRestricted indicates restricted access PermissionStateRestricted = "restricted" )
Permission States define authorization states.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Agent ¶
type Agent interface {
Runnable
// Name 返回智能体的标识符
Name() string
// Description 返回智能体的功能描述
Description() string
// Capabilities 返回智能体的能力列表
// 描述智能体可以执行的任务或操作
// 示例:["search", "analyze", "summarize"]
Capabilities() []string
// Plan 为给定输入生成执行计划
// 这是可选的,如果智能体不支持规划可能返回 nil
Plan(ctx context.Context, input *Input) (*Plan, error)
}
Agent 表示可以处理输入并产生输出的自主智能体
所有智能体实现(react、executor、specialized)都应实现此接口 这是规范定义,其他所有引用都应使用类型别名
Agent 接口扩展了 Runnable 并添加了智能体特定的方法用于:
- 识别智能体(Name、Description、Capabilities)
- 生成执行计划
实现:
- core.BaseAgent - 基础实现,支持 Runnable
- agents/executor.ExecutorAgent - 工具执行智能体
- agents/react.ReactAgent - ReAct 推理智能体
- agents/specialized.SpecializedAgent - 领域特定智能体
type Case ¶
type Case struct {
// ID is a unique identifier for this case.
//
// May be auto-generated by the storage implementation.
ID string `json:"id"`
// Title is a brief summary of the case.
//
// Should be descriptive but concise (1-2 sentences).
Title string `json:"title"`
// Description provides more detail about the case.
//
// This can be a longer explanation of the context and scenario.
Description string `json:"description"`
// Problem describes the issue that was encountered.
//
// This should be detailed enough to match similar future problems.
Problem string `json:"problem"`
// Solution describes how the problem was resolved.
//
// This should include actionable steps and outcomes.
Solution string `json:"solution"`
// Category groups related cases.
//
// Examples: "infrastructure", "security", "performance", "bug-fix"
Category string `json:"category"`
// Tags are keywords for filtering and searching.
//
// Examples: ["database", "timeout", "postgres"]
Tags []string `json:"tags,omitempty"`
// Embedding is the semantic vector representation of this case.
//
// This is used for similarity search. Typically computed by
// embedding the concatenation of Title + Problem + Solution.
//
// The dimension should match the embedding model being used
// (e.g., 1536 for OpenAI text-embedding-ada-002).
Embedding []float64 `json:"embedding,omitempty"`
// Similarity is the similarity score (0.0-1.0) when this case
// is returned from a search.
//
// Only populated in search results. Higher values indicate
// greater similarity to the query.
//
// Not persisted in storage.
Similarity float64 `json:"similarity,omitempty"`
// CreatedAt is when the case was first added.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the case was last modified.
//
// Useful for tracking case evolution and versioning.
UpdatedAt time.Time `json:"updated_at"`
// Metadata contains additional information about the case.
//
// Optional. May include:
// - source: Where this case came from
// - author: Who created the case
// - success_rate: How often this solution works
// - related_cases: IDs of related cases
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Case represents a stored case for reasoning.
Cases capture problem-solution pairs that can be used for case-based reasoning. Each case includes semantic embeddings for similarity search.
type Checkpoint ¶
type Checkpoint struct {
// ID is the unique checkpoint identifier.
// Format: "ckpt-{uuid}" or implementation-specific format
ID string `json:"id"`
// ThreadID is the thread/session identifier.
// All checkpoints with the same ThreadID belong to the same conversation.
ThreadID string `json:"thread_id"`
// State is the agent state at checkpoint time.
// Contains all data needed to resume execution from this point.
State State `json:"state"`
// Metadata contains additional checkpoint information.
// Common metadata keys:
// - "agent_name": Name of the agent that created the checkpoint
// - "checkpoint_reason": Why this checkpoint was created (e.g., "user_request", "step_complete")
// - "parent_checkpoint_id": ID of the previous checkpoint (for history traversal)
// - "tags": Array of tags for categorization
Metadata map[string]interface{} `json:"metadata,omitempty"`
// CreatedAt is when the checkpoint was created.
CreatedAt time.Time `json:"created_at"`
}
Checkpoint represents a saved state snapshot.
A checkpoint captures the complete state of an agent at a point in time, including conversation history, tool outputs, and intermediate results.
Thread-based organization allows multiple independent conversation threads with separate state management.
type CheckpointMetadata ¶
type CheckpointMetadata struct {
// ID is the unique checkpoint identifier.
ID string `json:"id"`
// ThreadID is the thread/session identifier.
ThreadID string `json:"thread_id"`
// CreatedAt is when the checkpoint was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the checkpoint was last updated.
UpdatedAt time.Time `json:"updated_at"`
// Metadata holds additional checkpoint information.
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Size is the approximate size in bytes of the checkpoint data.
// Useful for storage management and cleanup decisions.
Size int64 `json:"size"`
}
CheckpointMetadata contains checkpoint summary information.
Provides lightweight checkpoint information without loading the full state, useful for listing and browsing checkpoints.
type Checkpointer ¶
type Checkpointer interface {
// SaveCheckpoint persists a checkpoint.
//
// The checkpoint contains the complete agent state at a point in time,
// allowing resumption of execution from that state.
//
// Parameters:
// - ctx: Context for cancellation and deadlines
// - checkpoint: The checkpoint to save (must have ID and ThreadID)
//
// Returns:
// - error: SaveError if persistence fails
SaveCheckpoint(ctx context.Context, checkpoint *Checkpoint) error
// LoadCheckpoint retrieves a checkpoint by ID.
//
// Returns the complete checkpoint including state and metadata.
//
// Parameters:
// - ctx: Context for cancellation and deadlines
// - checkpointID: The unique checkpoint identifier
//
// Returns:
// - *Checkpoint: The loaded checkpoint
// - error: NotFoundError if checkpoint doesn't exist, LoadError for other failures
LoadCheckpoint(ctx context.Context, checkpointID string) (*Checkpoint, error)
// ListCheckpoints lists checkpoints for a thread.
//
// Returns metadata for the most recent checkpoints, useful for:
// - Displaying checkpoint history to users
// - Finding the latest checkpoint to resume from
// - Analyzing checkpoint patterns
//
// Parameters:
// - ctx: Context for cancellation and deadlines
// - threadID: The thread/session identifier
// - limit: Maximum number of checkpoints to return (0 = all)
//
// Returns:
// - []*CheckpointMetadata: List of checkpoint metadata, ordered by creation time (newest first)
// - error: QueryError if listing fails
ListCheckpoints(ctx context.Context, threadID string, limit int) ([]*CheckpointMetadata, error)
// DeleteCheckpoint removes a checkpoint.
//
// Permanently deletes a checkpoint and its associated state.
// This operation cannot be undone.
//
// Parameters:
// - ctx: Context for cancellation and deadlines
// - checkpointID: The unique checkpoint identifier
//
// Returns:
// - error: DeleteError if removal fails (not an error if checkpoint doesn't exist)
DeleteCheckpoint(ctx context.Context, checkpointID string) error
}
Checkpointer is the canonical interface for saving/loading agent state.
This interface provides session state persistence for multi-turn conversations, resuming interrupted workflows, and A/B testing different conversation paths.
Implementations:
- checkpoint.MemoryCheckpointer (core/checkpoint/memory.go)
- checkpoint.RedisCheckpointer (core/checkpoint/redis.go)
- checkpoint.DistributedCheckpointer (core/checkpoint/distributed.go)
Inspired by LangChain's Checkpointer pattern, it enables:
- Thread-based conversation continuity
- Checkpoint history management
- State persistence and recovery
Example usage:
checkpointer := checkpoint.NewMemoryCheckpointer()
// Save agent state
cp := &interfaces.Checkpoint{
ID: "ckpt-001",
ThreadID: "thread-123",
State: agentState,
}
err := checkpointer.SaveCheckpoint(ctx, cp)
// Load agent state
loaded, err := checkpointer.LoadCheckpoint(ctx, "ckpt-001")
// List checkpoints for a thread
metadata, err := checkpointer.ListCheckpoints(ctx, "thread-123", 10)
type Conversation ¶
type Conversation struct {
// ID is a unique identifier for this conversation turn.
//
// May be auto-generated by the storage implementation.
ID string `json:"id"`
// SessionID groups related conversation turns.
//
// All conversations with the same SessionID are part of the
// same dialogue session.
SessionID string `json:"session_id"`
// Role indicates who sent the message.
//
// Common values:
// - "user": Message from the user
// - "assistant": Message from the AI agent
// - "system": System message (e.g., instructions)
Role string `json:"role"`
// Content is the message content.
//
// This is typically text, but may include formatted content
// depending on the implementation.
Content string `json:"content"`
// Timestamp is when the conversation occurred.
//
// Used for ordering and filtering conversations.
Timestamp time.Time `json:"timestamp"`
// Metadata contains additional context about the conversation.
//
// Optional. May include:
// - model: Which LLM model generated the response
// - tokens: Token count for this turn
// - language: Detected language
// - sentiment: Sentiment analysis results
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Conversation represents a conversation turn.
A conversation captures a single message in a multi-turn dialogue, including the role (user/assistant/system), content, and metadata.
type ConversationMemory ¶
type ConversationMemory interface {
// Add adds a conversation to storage.
Add(ctx context.Context, conv *Conversation) error
// Get retrieves conversation history.
Get(ctx context.Context, sessionID string, limit int) ([]*Conversation, error)
// Clear clears conversation history for a session.
Clear(ctx context.Context, sessionID string) error
// Count returns the number of conversations in a session.
Count(ctx context.Context, sessionID string) (int, error)
}
ConversationMemory is an optional specialized interface for conversation storage.
Implementations that need fine-grained control over conversation memory can implement this interface in addition to MemoryManager.
This interface is used internally by some memory implementations but is not required for basic MemoryManager usage.
type DependencyAware ¶
type DependencyAware interface {
// Dependencies returns the names of components this component depends on.
// The LifecycleManager will ensure dependencies are started first.
Dependencies() []string
}
DependencyAware is implemented by components that depend on other components.
type Document ¶
type Document struct {
// ID is the unique identifier for the document.
//
// If not provided when creating a document, implementations should
// generate a unique ID automatically.
ID string `json:"id"`
// PageContent is the main text content of the document.
//
// This is the primary searchable text that embeddings are generated from.
PageContent string `json:"page_content"`
// Metadata contains additional structured information about the document.
//
// Common metadata fields:
// - "source": Document source (file path, URL, etc.)
// - "title": Document title
// - "author": Document author
// - "created_at": Creation timestamp
// - "tags": Document tags/categories
//
// Metadata can be used for filtering and enriching search results.
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Embedding is the vector representation of the document.
//
// This field may be nil if embeddings haven't been generated yet.
// VectorStore implementations should generate embeddings if missing.
Embedding []float64 `json:"embedding,omitempty"`
// Score represents the similarity or relevance score.
//
// This field is populated by search operations:
// - SimilaritySearch: Cosine similarity (typically 0.0 to 1.0)
// - Reranking: Relevance score from reranker
// - BM25: BM25 score
//
// Higher scores indicate better matches.
Score float64 `json:"score,omitempty"`
}
Document represents a document with optional vector embedding.
This is the canonical document type used throughout the agent framework for retrieval, RAG, and memory systems.
Previously defined in:
- retrieval/document.go
- retrieval/vector_store.go (inline)
func (*Document) GetMetadata ¶
GetMetadata retrieves a metadata value by key.
func (*Document) SetMetadata ¶
SetMetadata sets a metadata value.
type HealthState ¶
type HealthState string
HealthState represents the health state of a component.
const ( // HealthHealthy - Component is fully operational HealthHealthy HealthState = "healthy" // HealthDegraded - Component is operational but with reduced capability HealthDegraded HealthState = "degraded" // HealthUnhealthy - Component is not operational HealthUnhealthy HealthState = "unhealthy" // HealthUnknown - Health status cannot be determined HealthUnknown HealthState = "unknown" )
type HealthStatus ¶
type HealthStatus struct {
// State is the overall health state
State HealthState `json:"state"`
// Message provides additional context about the health state
Message string `json:"message,omitempty"`
// Details contains component-specific health information
Details map[string]interface{} `json:"details,omitempty"`
// LastChecked is when this status was determined
LastChecked time.Time `json:"last_checked"`
// ComponentName identifies the component
ComponentName string `json:"component_name,omitempty"`
}
HealthStatus represents the health of a component.
func NewDegradedStatus ¶
func NewDegradedStatus(reason string) HealthStatus
NewDegradedStatus creates a degraded status with a reason.
func NewHealthStatus ¶
func NewHealthStatus(state HealthState, message string) HealthStatus
NewHealthStatus creates a new HealthStatus with the given state.
func NewHealthyStatus ¶
func NewHealthyStatus() HealthStatus
NewHealthyStatus creates a healthy status.
func NewUnhealthyStatus ¶
func NewUnhealthyStatus(err error) HealthStatus
NewUnhealthyStatus creates an unhealthy status with an error message.
func (HealthStatus) IsHealthy ¶
func (h HealthStatus) IsHealthy() bool
IsHealthy returns true if the status indicates healthy operation.
func (HealthStatus) IsOperational ¶
func (h HealthStatus) IsOperational() bool
IsOperational returns true if the component can serve requests.
type Input ¶
type Input struct {
// Messages 是对话历史或输入消息
Messages []Message `json:"messages"`
// State 是持久状态数据
// 可以存储任意键值对用于状态管理
State State `json:"state"`
// Config 包含运行时配置选项
// 可以包括模型设置、工具设置等
Config map[string]interface{} `json:"config,omitempty"`
}
Input 表示 runnable 的标准化输入
Input 提供了一个灵活的结构来向 runnable 传递数据:
- Messages: 用于基于 LLM 处理的对话历史
- State: 持久状态数据
- Config: 运行时配置选项
type Lifecycle ¶
type Lifecycle interface {
// Init initializes the component with configuration.
// This is called once before Start and should set up resources.
// Config can be nil if no configuration is needed.
Init(ctx context.Context, config interface{}) error
// Start begins the component's active operation.
// Called after Init succeeds. Component should be ready to serve.
Start(ctx context.Context) error
// Stop gracefully stops the component.
// Should release resources and complete pending operations.
// Context may have a deadline for forced shutdown.
Stop(ctx context.Context) error
// HealthCheck returns the component's current health status.
// Should be non-blocking and return quickly.
HealthCheck(ctx context.Context) HealthStatus
}
Lifecycle defines the standard lifecycle hooks for all managed components.
Components implementing this interface can be managed by the LifecycleManager for coordinated startup, shutdown, and health monitoring.
Lifecycle phases:
- Init - Initialize resources (one-time setup)
- Start - Begin active operation
- Running - Normal operation (HealthCheck monitors)
- Stop - Graceful shutdown
type LifecycleAware ¶
type LifecycleAware interface {
// OnInit is called during initialization
OnInit(ctx context.Context) error
// OnShutdown is called during shutdown
OnShutdown(ctx context.Context) error
}
LifecycleAware is implemented by components that need lifecycle notifications but don't implement the full Lifecycle interface.
type LifecycleManager ¶
type LifecycleManager interface {
// Register adds a component to be managed.
// Name must be unique. Priority determines startup/shutdown order.
Register(name string, component Lifecycle, priority int) error
// Unregister removes a component from management.
Unregister(name string) error
// InitAll initializes all registered components in priority order.
InitAll(ctx context.Context) error
// StartAll starts all initialized components in priority order.
StartAll(ctx context.Context) error
// StopAll stops all running components in reverse priority order.
StopAll(ctx context.Context) error
// HealthCheckAll returns aggregated health of all components.
HealthCheckAll(ctx context.Context) map[string]HealthStatus
// GetState returns the current state of a component.
GetState(name string) (LifecycleState, error)
// WaitForShutdown blocks until all components are stopped.
WaitForShutdown(ctx context.Context) error
}
LifecycleManager manages the lifecycle of multiple components.
type LifecycleState ¶
type LifecycleState string
LifecycleState represents the current state of a lifecycle-managed component.
const ( // StateUninitialized - Component has not been initialized StateUninitialized LifecycleState = "uninitialized" // StateInitialized - Init() has completed successfully StateInitialized LifecycleState = "initialized" // StateStarting - Start() is in progress StateStarting LifecycleState = "starting" // StateRunning - Component is running normally StateRunning LifecycleState = "running" // StateStopping - Stop() is in progress StateStopping LifecycleState = "stopping" // StateStopped - Component has stopped StateStopped LifecycleState = "stopped" // StateFailed - Component encountered a fatal error StateFailed LifecycleState = "failed" )
type MemoryManager ¶
type MemoryManager interface {
// AddConversation stores a conversation turn.
//
// This is used to maintain conversation history for context-aware
// agent interactions. Each conversation turn is associated with
// a session ID for grouping related conversations.
//
// Example:
// conv := &Conversation{
// SessionID: "session-123",
// Role: "user",
// Content: "Hello, how are you?",
// Timestamp: time.Now(),
// }
// err := manager.AddConversation(ctx, conv)
AddConversation(ctx context.Context, conv *Conversation) error
// GetConversationHistory retrieves conversation history for a session.
//
// Returns the most recent conversations up to the specified limit.
// Conversations are typically returned in chronological order.
//
// Parameters:
// - sessionID: The session identifier
// - limit: Maximum number of conversations to return (0 or negative for all)
//
// Returns:
// - Conversation slice (may be empty if no history exists)
// - Error if retrieval fails
GetConversationHistory(ctx context.Context, sessionID string, limit int) ([]*Conversation, error)
// ClearConversation removes conversation history for a session.
//
// This is useful for starting fresh conversations or implementing
// privacy features like "forget this conversation".
//
// Parameters:
// - sessionID: The session identifier to clear
//
// Returns:
// - Error if clearing fails (returns nil if session doesn't exist)
ClearConversation(ctx context.Context, sessionID string) error
// AddCase stores a case for case-based reasoning.
//
// Cases are examples of problems and solutions that agents can
// reference when handling similar situations. This supports
// learning from past experiences.
//
// The case's embedding vector should be pre-computed and included
// in the Case struct for efficient similarity search.
//
// Example:
// case := &Case{
// Title: "Database connection timeout",
// Problem: "App fails to connect to database",
// Solution: "Increase connection timeout to 30s",
// Category: "infrastructure",
// Tags: []string{"database", "timeout"},
// Embedding: embeddings, // Pre-computed vector
// }
// err := manager.AddCase(ctx, case)
AddCase(ctx context.Context, caseMemory *Case) error
// SearchSimilarCases finds similar cases using semantic search.
//
// This uses vector similarity (typically cosine similarity) to find
// cases that are semantically similar to the query. The query is
// embedded and compared against stored case embeddings.
//
// Parameters:
// - query: Natural language query describing the problem
// - limit: Maximum number of similar cases to return
//
// Returns:
// - Case slice ordered by similarity (highest first)
// - Each case includes a Similarity score (0.0-1.0)
// - Error if search fails
//
// Example:
// cases, err := manager.SearchSimilarCases(ctx, "database timeout issue", 3)
// for _, c := range cases {
// fmt.Printf("Similar case (%.2f): %s\n", c.Similarity, c.Title)
// }
SearchSimilarCases(ctx context.Context, query string, limit int) ([]*Case, error)
// Store persists arbitrary key-value data.
//
// This provides a general-purpose storage mechanism for agent state
// or other data that doesn't fit into conversation or case memory.
//
// The value will be serialized internally, so it must be serializable.
//
// Parameters:
// - key: Unique identifier for the data
// - value: Data to store (must be serializable)
//
// Returns:
// - Error if storage fails
Store(ctx context.Context, key string, value interface{}) error
// Retrieve fetches stored data by key.
//
// Returns the stored value or an error if the key doesn't exist.
// The caller is responsible for type assertion.
//
// Parameters:
// - key: The key to retrieve
//
// Returns:
// - The stored value (requires type assertion)
// - Error if key doesn't exist or retrieval fails
//
// Example:
// val, err := manager.Retrieve(ctx, "user_preferences")
// if err != nil {
// // Handle error
// }
// prefs, ok := val.(map[string]interface{})
Retrieve(ctx context.Context, key string) (interface{}, error)
// Delete removes stored data by key.
//
// This is idempotent - deleting a non-existent key is not an error.
//
// Parameters:
// - key: The key to delete
//
// Returns:
// - Error if deletion fails (returns nil if key doesn't exist)
Delete(ctx context.Context, key string) error
// Clear removes all memory.
//
// This is a destructive operation that clears:
// - All conversation history
// - All cases
// - All key-value storage
//
// Use with caution! This is typically used for:
// - Testing and development
// - Complete system resets
// - Data privacy compliance (e.g., GDPR right to be forgotten)
//
// Returns:
// - Error if clearing fails
Clear(ctx context.Context) error
}
MemoryManager is the canonical interface for agent memory management.
This interface provides a unified abstraction for managing different types of memory (conversation history, case-based reasoning, key-value storage).
Implementation locations:
- memory.DefaultManager - Default implementation with conversation and case memory
- memory.MemoryVectorStore - Vector-based memory store
Previously defined in: memory/manager.go as Manager This is now the single source of truth.
See: memory/manager.go for concrete implementations
type Message ¶
type Message struct {
// Role 标识消息发送者(user、assistant、system、function)
Role string `json:"role"`
// Content 是消息的文本内容
Content string `json:"content"`
// Name 是发送者的可选名称(用于函数/工具消息)
Name string `json:"name,omitempty"`
}
Message 表示对话中的单条消息
消息用于:
- 聊天历史
- LLM 交互
- 智能体通信
Role 字段指示消息发送者:
- "user": 用户输入
- "assistant": AI/智能体响应
- "system": 系统指令
- "function": 函数/工具输出
type Output ¶
type Output struct {
// Messages 是生成或修改的消息
Messages []Message `json:"messages"`
// State 是更新的状态数据
State State `json:"state"`
// Metadata 包含关于执行的额外信息
// 可以包括时序、模型信息、工具调用等
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Output 表示 runnable 的标准化输出
Output 提供了一个结构化的方式来返回结果:
- Messages: 生成或修改的消息
- State: 更新的状态数据
- Metadata: 关于执行的额外信息
type Plan ¶
type Plan struct {
// Steps 是要执行的有序动作列表
Steps []Step `json:"steps"`
// Metadata 包含规划元数据(置信度、推理等)
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Plan 表示智能体的执行计划
Plan 描述智能体为完成任务将采取的步骤:
- Steps: 有序的动作列表
- Metadata: 规划元数据(置信度、推理等)
计划由 Agent.Plan() 生成,用于:
- 透明性(显示智能体将要做什么)
- 验证(检查计划是否可接受)
- 优化(在执行前修改计划)
type ProgramCode ¶
type ProgramCode struct {
// Language of the code (e.g., "python", "javascript")
Language string `json:"language"`
// Code content
Code string `json:"code"`
// ExecutionResult after running the code
ExecutionResult interface{} `json:"execution_result,omitempty"`
// Error if execution failed
Error string `json:"error,omitempty"`
}
ProgramCode represents generated code in Program-of-Thought pattern.
type ReasoningChunk ¶
type ReasoningChunk struct {
// Step is a partial or complete reasoning step
Step *ReasoningStep `json:"step,omitempty"`
// PartialAnswer is incremental answer content
PartialAnswer string `json:"partial_answer,omitempty"`
// Done indicates if reasoning is complete
Done bool `json:"done"`
// Error if something went wrong
Error error `json:"error,omitempty"`
}
ReasoningChunk represents a streaming chunk of reasoning output.
type ReasoningInput ¶
type ReasoningInput struct {
// Query is the main question or task to reason about
Query string `json:"query"`
// Context provides additional information for reasoning
Context map[string]interface{} `json:"context,omitempty"`
// Tools available for the reasoning process
Tools []Tool `json:"tools,omitempty"`
// Config contains pattern-specific configuration
Config map[string]interface{} `json:"config,omitempty"`
// History of previous reasoning steps (for iterative patterns)
History []ReasoningStep `json:"history,omitempty"`
}
ReasoningInput represents input for a reasoning pattern.
type ReasoningOutput ¶
type ReasoningOutput struct {
// Answer is the final answer or conclusion
Answer string `json:"answer"`
// Steps contains the reasoning steps taken
Steps []ReasoningStep `json:"steps"`
// Confidence score (0-1) in the answer
Confidence float64 `json:"confidence,omitempty"`
// Metadata contains pattern-specific output data
Metadata map[string]interface{} `json:"metadata,omitempty"`
// ToolCalls made during reasoning
ToolCalls []ReasoningToolCall `json:"tool_calls,omitempty"`
}
ReasoningOutput represents the output from a reasoning pattern.
type ReasoningPattern ¶
type ReasoningPattern interface {
// Name returns the name of the reasoning pattern.
Name() string
// Description returns a description of the reasoning pattern.
Description() string
// Process executes the reasoning pattern on the given input.
Process(ctx context.Context, input *ReasoningInput) (*ReasoningOutput, error)
// Stream processes with streaming support for incremental results.
Stream(ctx context.Context, input *ReasoningInput) (<-chan *ReasoningChunk, error)
}
ReasoningPattern defines the interface for different reasoning strategies.
This interface allows agents to implement various reasoning patterns such as: - Chain-of-Thought (CoT): Linear step-by-step reasoning - Tree-of-Thought (ToT): Tree-based search with multiple reasoning paths - Graph-of-Thought (GoT): Graph-based reasoning with complex dependencies - Program-of-Thought (PoT): Code generation and execution for reasoning - Skeleton-of-Thought (SoT): Parallel reasoning with skeleton structure - Meta-CoT/Self-Ask: Self-questioning and meta-reasoning
type ReasoningStep ¶
type ReasoningStep struct {
// StepID uniquely identifies this step
StepID string `json:"step_id"`
// Type of reasoning step (e.g., "thought", "action", "observation", "branch")
Type string `json:"type"`
// Content of the reasoning step
Content string `json:"content"`
// Score or evaluation of this step (for search-based patterns)
Score float64 `json:"score,omitempty"`
// ParentID links to the parent step (for tree/graph patterns)
ParentID string `json:"parent_id,omitempty"`
// ChildrenIDs links to child steps (for tree/graph patterns)
ChildrenIDs []string `json:"children_ids,omitempty"`
// Metadata for step-specific data
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ReasoningStep represents a single step in the reasoning process.
type ReasoningStrategy ¶
type ReasoningStrategy string
ReasoningStrategy defines different strategies for reasoning patterns.
const ( // StrategyDepthFirst uses depth-first search for tree/graph patterns StrategyDepthFirst ReasoningStrategy = "depth_first" // StrategyBreadthFirst uses breadth-first search for tree/graph patterns StrategyBreadthFirst ReasoningStrategy = "breadth_first" // StrategyBeamSearch uses beam search with limited candidates StrategyBeamSearch ReasoningStrategy = "beam_search" // StrategyMonteCarlo uses Monte Carlo Tree Search StrategyMonteCarlo ReasoningStrategy = "monte_carlo" // StrategyGreedy uses greedy selection at each step StrategyGreedy ReasoningStrategy = "greedy" )
type ReasoningToolCall ¶
type ReasoningToolCall struct {
// ToolName identifies the tool
ToolName string `json:"tool_name"`
// Input parameters for the tool
Input map[string]interface{} `json:"input"`
// Output from the tool execution
Output interface{} `json:"output,omitempty"`
// Error if tool execution failed
Error string `json:"error,omitempty"`
// ReasoningStepID links this call to a specific reasoning step
ReasoningStepID string `json:"reasoning_step_id,omitempty"`
}
ReasoningToolCall represents a tool invocation during reasoning. This extends the basic ToolCall with reasoning-specific fields.
type Reloadable ¶
type Reloadable interface {
// Reload reloads configuration without stopping the component.
// Returns error if reload fails (component continues with old config).
Reload(ctx context.Context, config interface{}) error
}
Reloadable is implemented by components that support configuration reload without restart.
type Runnable ¶
type Runnable interface {
// Invoke 使用给定输入执行 runnable
// 这是用于同步处理的主要执行方法
//
// 参数:
// - ctx: 用于取消和超时控制的上下文
// - input: runnable 的输入数据
//
// 返回:
// - output: 执行结果
// - error: 执行失败时的错误
Invoke(ctx context.Context, input *Input) (*Output, error)
// Stream 使用流式输出支持执行
// 允许在输出可用时进行处理
//
// 参数:
// - ctx: 用于取消和超时控制的上下文
// - input: runnable 的输入数据
//
// 返回:
// - chan: 流式数据块通道
// - error: 流设置失败时的错误
Stream(ctx context.Context, input *Input) (<-chan *StreamChunk, error)
}
Runnable 表示可以使用输入调用并产生输出的任何组件
这是由智能体、链和工具实现的基础接口 它提供核心执行能力,包括:
- 同步执行(Invoke)
- 流式执行(Stream)
Runnable 接口通过标准执行模式启用组件的组合和链接 ¶
实现:
- core.BaseRunnable - 基础实现,支持回调
- core.BaseAgent - 智能体特定实现
- core.Chain - Runnable 链
type SkeletonPoint ¶
type SkeletonPoint struct {
// ID uniquely identifies this skeleton point
ID string `json:"id"`
// Question or sub-problem to solve
Question string `json:"question"`
// Answer to this skeleton point
Answer string `json:"answer,omitempty"`
// Dependencies on other skeleton points
Dependencies []string `json:"dependencies,omitempty"`
// Status of this point ("pending", "processing", "completed")
Status string `json:"status"`
}
SkeletonPoint represents a point in the Skeleton-of-Thought pattern.
type State ¶
type State map[string]interface{}
State 表示可持久化的智能体状态
State 是灵活的键值存储,用于:
- 智能体记忆
- 对话上下文
- 中间结果
- 配置数据
使用检查点功能时,State 在调用之间保持不变
type Step ¶
type Step struct {
// Action 是要执行的动作(例如 "search"、"analyze"、"format")
Action string `json:"action"`
// Input 包含动作的参数
Input map[string]interface{} `json:"input"`
// ToolName 是要调用的工具(如果这是工具调用步骤)
ToolName string `json:"tool_name,omitempty"`
}
Step 表示执行计划中的单个步骤
每个步骤描述:
- Action: 要做什么
- Input: 动作的参数
- ToolName: 要调用的工具(如果适用)
type Store ¶
type Store interface {
// Get retrieves a value by key.
//
// Returns:
// - The stored value
// - An error if the key doesn't exist or retrieval fails
Get(ctx context.Context, key string) (interface{}, error)
// Set stores a key-value pair.
//
// If the key already exists, its value is replaced.
Set(ctx context.Context, key string, value interface{}) error
// Delete removes a key and its associated value.
//
// Returns no error if the key doesn't exist (idempotent operation).
Delete(ctx context.Context, key string) error
// Clear removes all keys from the store.
//
// Use with caution - this operation is typically irreversible.
Clear(ctx context.Context) error
}
Store is the canonical interface for general key-value storage.
This interface provides a simplified, context-aware key-value store suitable for agent state, user preferences, and general persistence.
Implementations: memory.MemoryStore, postgres.PostgresStore, redis.RedisStore
The interface is intentionally simple to allow easy implementation across different storage backends.
type StreamChunk ¶
type StreamChunk struct {
// Content 是数据块内容(可以是部分输出)
Content string `json:"content"`
// Metadata 包含关于数据块的上下文信息
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Done 指示这是否是最后一个数据块
Done bool `json:"done"`
}
StreamChunk 表示流式输出的数据块
StreamChunk 允许增量处理输出:
- Content: 部分或完整输出
- Metadata: 上下文信息
- Done: 指示流完成的标志
type ThoughtNode ¶
type ThoughtNode struct {
// ID uniquely identifies this node
ID string `json:"id"`
// Thought content at this node
Thought string `json:"thought"`
// Score or evaluation of this thought
Score float64 `json:"score"`
// State at this node (for stateful reasoning)
State map[string]interface{} `json:"state,omitempty"`
// Parent node reference
Parent *ThoughtNode `json:"-"`
// Children nodes
Children []*ThoughtNode `json:"-"`
// Visited flag for graph traversal
Visited bool `json:"visited"`
// Depth in the tree/graph
Depth int `json:"depth"`
}
ThoughtNode represents a node in tree/graph-based reasoning patterns.
type TokenUsage ¶
type TokenUsage struct {
// PromptTokens is the number of tokens in the input/prompt.
PromptTokens int `json:"prompt_tokens"`
// CompletionTokens is the number of tokens in the generated output.
CompletionTokens int `json:"completion_tokens"`
// TotalTokens is the total number of tokens used.
// Usually equals PromptTokens + CompletionTokens.
TotalTokens int `json:"total_tokens"`
// CachedTokens is the number of tokens served from cache (if applicable).
// Not all LLM providers support this field.
CachedTokens int `json:"cached_tokens,omitempty"`
}
TokenUsage represents detailed token usage statistics for LLM calls.
TokenUsage tracks the number of tokens consumed by LLM API calls:
- PromptTokens: Tokens in the input/prompt
- CompletionTokens: Tokens in the generated output
- TotalTokens: Total tokens used (PromptTokens + CompletionTokens)
- CachedTokens: Tokens served from cache (if applicable)
This information is useful for:
- Cost tracking and budgeting
- Performance monitoring
- Usage analytics
- Rate limit management
func (*TokenUsage) Add ¶
func (t *TokenUsage) Add(other *TokenUsage)
Add adds another TokenUsage to this one, summing all fields. This is useful for accumulating token usage across multiple LLM calls.
func (*TokenUsage) IsEmpty ¶
func (t *TokenUsage) IsEmpty() bool
IsEmpty returns true if no tokens were used.
type Tool ¶
type Tool interface {
// Name 返回工具标识符
//
// 名称应在工具注册表中唯一,并遵循命名约定
// (小写字母,下划线分隔)
Name() string
// Description 返回工具的功能描述
//
// 此描述供 LLM 理解何时以及如何使用工具
// 应当清晰简洁
Description() string
// Invoke 使用给定输入执行工具
//
// 工具应处理输入参数并返回结果
// 如果执行失败则返回错误
Invoke(ctx context.Context, input *ToolInput) (*ToolOutput, error)
// ArgsSchema 返回工具的输入模式(JSON Schema 格式)
//
// 此模式定义工具接受的参数结构
// LLM 使用它生成有效的工具调用
//
// 示例模式:
// {
// "type": "object",
// "properties": {
// "query": {"type": "string", "description": "搜索查询"}
// },
// "required": ["query"]
// }
ArgsSchema() string
}
Tool 表示智能体可以调用的可执行工具
所有工具实现都应实现此接口
实现位置:
- tools.BaseTool - 基础实现,包含通用功能
- tools/compute/* - 计算工具
- tools/http/* - HTTP 请求工具
- tools/search/* - 搜索工具
- tools/shell/* - Shell 执行工具
- tools/practical/* - 实用工具
参见:tools/tool.go 的基础实现
type ToolCall ¶
type ToolCall struct {
// ID 是此工具调用的唯一标识符
//
// 用于在日志和追踪中关联调用
ID string `json:"id"`
// ToolName 是被调用工具的名称
ToolName string `json:"tool_name"`
// Args 是传递给工具的参数
Args map[string]interface{} `json:"args"`
// Result 是工具的输出
//
// 如果调用仍在进行中可能为 nil
Result *ToolOutput `json:"result,omitempty"`
// Error 包含调用失败时的错误信息
//
// 调用成功时为空字符串
Error string `json:"error,omitempty"`
// StartTime 是工具调用开始的时间(Unix 时间戳)
StartTime int64 `json:"start_time"`
// EndTime 是工具调用完成的时间(Unix 时间戳)
//
// 如果调用仍在进行中则为零
EndTime int64 `json:"end_time,omitempty"`
// Metadata 包含关于调用的额外上下文
//
// 可能包括调用者信息、追踪 ID 等
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ToolCall 表示工具调用的记录
用于日志记录、审计和调试 它捕获工具调用的完整上下文
type ToolExecutor ¶
type ToolExecutor interface {
// ExecuteTool 按名称使用给定参数执行工具
//
// 执行器负责:
// - 按名称查找工具
// - 验证参数是否符合工具模式
// - 执行工具
// - 处理错误和超时
ExecuteTool(ctx context.Context, toolName string, args map[string]interface{}) (*ToolResult, error)
// ListTools 返回所有可用工具
//
// 这对于需要发现可用工具的智能体很有用
ListTools() []Tool
}
ToolExecutor 表示可以执行工具的组件
此接口由需要运行工具的组件实现 例如智能体和工作流引擎
实现位置:
- agents/executor/executor_agent.go - 执行器智能体实现
- tools/registry.go - 具有执行能力的工具注册表
type ToolInput ¶
type ToolInput struct {
// Args 包含工具的输入参数
//
// Args 的结构应与工具的 ArgsSchema 匹配
Args map[string]interface{} `json:"args"`
// Context 是执行上下文(不序列化)
//
// 用于取消、超时和传递请求范围的值
Context context.Context `json:"-"`
// CallerID 标识调用工具的身份
//
// 可选,用于授权和审计
CallerID string `json:"caller_id,omitempty"`
// TraceID 用于分布式追踪
//
// 可选,帮助跨系统跟踪工具执行
TraceID string `json:"trace_id,omitempty"`
}
ToolInput 表示工具执行输入
此结构包含执行工具所需的所有信息 包括参数和用于追踪和调试的元数据
type ToolOutput ¶
type ToolOutput struct {
// Result 包含工具的输出数据
//
// 类型取决于具体工具,常见类型:
// - string: 文本输出
// - map[string]interface{}: 结构化数据
// - []byte: 二进制数据
Result interface{} `json:"result"`
// Success 指示工具是否成功执行
//
// 如果工具无错误完成则为 true,否则为 false
Success bool `json:"success"`
// Error 包含错误消息(当 Success 为 false 时)
//
// 当 Success 为 true 时为空字符串
Error string `json:"error,omitempty"`
// Metadata 包含关于执行的额外信息
//
// 可选,可能包括:
// - execution_time: 工具运行时长
// - retries: 重试次数
// - cost: API 调用成本(对于外部服务)
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ToolOutput 表示工具执行输出
此结构包含工具执行的结果 以及状态信息和元数据
type ToolResult ¶
type ToolResult struct {
// ToolName 是被执行工具的名称
ToolName string `json:"tool_name"`
// Output 包含工具的执行输出
Output *ToolOutput `json:"output"`
// ExecutionTime 是工具执行时长(毫秒)
//
// 可选,用于性能监控
ExecutionTime int64 `json:"execution_time,omitempty"`
}
ToolResult 表示 ToolExecutor 执行工具的结果
与 ToolOutput 不同,它包含执行器跟踪的额外信息 例如执行的工具名称
type ValidatableTool ¶ added in v0.5.0
type ValidatableTool interface {
Tool
// Validate 在执行前验证工具输入
//
// 如果输入无效则返回错误,错误消息应清楚描述输入的问题
Validate(ctx context.Context, input *ToolInput) error
}
ValidatableTool 是工具可以实现的可选接口 用于提供自定义输入验证逻辑
如果工具实现了此接口,验证器将在执行工具之前调用 Validate 允许进行比单独使用 JSON schema 更复杂的验证
示例实现:
func (t *MyTool) Validate(ctx context.Context, input *ToolInput) error {
// 自定义验证逻辑
if val, ok := input.Args["amount"].(float64); ok && val < 0 {
return fmt.Errorf("amount must be non-negative")
}
return nil
}
type VectorStore ¶
type VectorStore interface {
// SimilaritySearch performs vector similarity search and returns the most similar documents.
//
// Parameters:
// - ctx: Context for cancellation and timeouts
// - query: The query string to search for
// - topK: Maximum number of results to return
//
// Returns documents sorted by similarity (most similar first).
SimilaritySearch(ctx context.Context, query string, topK int) ([]*Document, error)
// SimilaritySearchWithScore returns documents with their similarity scores.
//
// This is useful when you need to filter results based on a score threshold
// or display confidence levels to users.
//
// The Score field in each returned Document will be populated.
SimilaritySearchWithScore(ctx context.Context, query string, topK int) ([]*Document, error)
// AddDocuments adds new documents to the vector store.
//
// The implementation should:
// - Generate embeddings for documents without them
// - Store the document content and metadata
// - Index the vectors for efficient similarity search
AddDocuments(ctx context.Context, docs []*Document) error
// Delete removes documents by their IDs.
//
// This is useful for:
// - Removing outdated information
// - GDPR/data deletion compliance
// - Managing store size
Delete(ctx context.Context, ids []string) error
}
VectorStore is the canonical interface for vector storage and similarity search.
This interface unifies multiple previous definitions:
- retrieval/vector_store.go (Document-based vector search)
- memory/manager.go (Embedding-based vector search)
Implementations: memory.MemoryVectorStore, qdrant.QdrantStore, etc.
The interface provides document-oriented vector operations, which is the most common use case for RAG and retrieval systems.