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
Backward Compatibility:
Type aliases exist in original locations (retrieval/, memory/, core/) for backward compatibility. These will be removed in v1.0.0. See docs/refactoring/migration-guide.md for migration instructions.
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 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 returns the agent's identifier.
Name() string
// Description returns what the agent does.
Description() string
// Plan generates an execution plan for the given input.
// This is optional and may return nil if the agent doesn't support planning.
Plan(ctx context.Context, input *Input) (*Plan, error)
}
Agent represents an autonomous agent that can process inputs and produce outputs.
All agent implementations (react, executor, specialized) should implement this interface. This is the canonical definition; all other references should use type aliases.
The Agent interface extends Runnable and adds agent-specific methods for:
- Identifying the agent (Name, Description)
- Generating execution plans
Implementations:
- core.BaseAgent - Base implementation with Runnable support
- agents/executor.ExecutorAgent - Tool execution agent
- agents/react.ReactAgent - ReAct reasoning agent
- agents/specialized.SpecializedAgent - Domain-specific agents
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 is the conversation history or input messages.
Messages []Message `json:"messages"`
// State is the persistent state data.
// Can store arbitrary key-value pairs for state management.
State State `json:"state"`
// Config contains runtime configuration options.
// Can include model settings, tool settings, etc.
Config map[string]interface{} `json:"config,omitempty"`
}
Input represents standardized input to a runnable.
Input provides a flexible structure for passing data to runnables:
- Messages: Conversation history for LLM-based processing
- State: Persistent state data
- Config: Runtime configuration options
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 identifies the message sender (user, assistant, system, function).
Role string `json:"role"`
// Content is the message text content.
Content string `json:"content"`
// Name is the optional name of the sender (for function/tool messages).
Name string `json:"name,omitempty"`
}
Message represents a single message in a conversation.
Messages are used for:
- Chat history
- LLM interactions
- Agent communication
The Role field indicates the message sender:
- "user": User input
- "assistant": AI/Agent response
- "system": System instructions
- "function": Function/Tool output
type Output ¶
type Output struct {
// Messages is the generated or modified messages.
Messages []Message `json:"messages"`
// State is the updated state data.
State State `json:"state"`
// Metadata contains additional information about the execution.
// Can include timing, model info, tool calls, etc.
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Output represents standardized output from a runnable.
Output provides a structured way to return results:
- Messages: Generated or modified messages
- State: Updated state data
- Metadata: Additional information about execution
type Plan ¶
type Plan struct {
// Steps is the ordered list of actions to execute.
Steps []Step `json:"steps"`
// Metadata contains planning metadata (confidence, reasoning, etc.).
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Plan represents an agent's execution plan.
Plan describes the steps an agent will take to accomplish a task:
- Steps: Ordered list of actions
- Metadata: Planning metadata (confidence, reasoning, etc.)
Plans are generated by Agent.Plan() and used for:
- Transparency (showing what the agent will do)
- Validation (checking if plan is acceptable)
- Optimization (modifying plan before execution)
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 executes the runnable with the given input.
// This is the primary execution method for synchronous processing.
//
// Parameters:
// - ctx: Context for cancellation and timeout control
// - input: Input data for the runnable
//
// Returns:
// - output: Result of the execution
// - error: Error if execution fails
Invoke(ctx context.Context, input *Input) (*Output, error)
// Stream executes with streaming output support.
// Allows processing output as it becomes available.
//
// Parameters:
// - ctx: Context for cancellation and timeout control
// - input: Input data for the runnable
//
// Returns:
// - chan: Channel of stream chunks
// - error: Error if stream setup fails
Stream(ctx context.Context, input *Input) (<-chan *StreamChunk, error)
}
Runnable represents any component that can be invoked with input to produce output.
This is the foundation interface implemented by agents, chains, and tools. It provides core execution capabilities including:
- Synchronous execution (Invoke)
- Streaming execution (Stream)
The Runnable interface enables composition and chaining of components through standard execution patterns.
Implementations:
- core.BaseRunnable - Base implementation with callbacks
- core.BaseAgent - Agent-specific implementation
- core.Chain - Chain of runnables
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 represents agent state that can be persisted.
State is a flexible key-value store for:
- Agent memory
- Conversation context
- Intermediate results
- Configuration data
State is preserved across invocations when using checkpointing.
type Step ¶
type Step struct {
// Action is the action to perform (e.g., "search", "analyze", "format").
Action string `json:"action"`
// Input contains parameters for the action.
Input map[string]interface{} `json:"input"`
// ToolName is the tool to invoke (if this is a tool call step).
ToolName string `json:"tool_name,omitempty"`
}
Step represents a single step in an execution plan.
Each step describes:
- Action: What to do
- Input: Parameters for the action
- ToolName: Tool to invoke (if applicable)
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 is the chunk data (can be partial output).
Content string `json:"content"`
// Metadata contains contextual information about the chunk.
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Done indicates if this is the final chunk.
Done bool `json:"done"`
}
StreamChunk represents a chunk of streaming output.
StreamChunk allows incremental processing of output:
- Content: Partial or complete output
- Metadata: Contextual information
- Done: Flag indicating stream completion
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 returns the tool identifier.
//
// The name should be unique within a tool registry and follow
// naming conventions (lowercase, underscores for separators).
Name() string
// Description returns what the tool does.
//
// This description is used by LLMs to understand when and how
// to use the tool. It should be clear and concise.
Description() string
// Invoke executes the tool with given input.
//
// The tool should process the input arguments and return results
// or an error if execution fails.
Invoke(ctx context.Context, input *ToolInput) (*ToolOutput, error)
// ArgsSchema returns the tool's input schema (JSON Schema format).
//
// This schema defines the structure of arguments the tool accepts.
// It's used by LLMs to generate valid tool calls.
//
// Example schema:
// {
// "type": "object",
// "properties": {
// "query": {"type": "string", "description": "Search query"}
// },
// "required": ["query"]
// }
ArgsSchema() string
}
Tool represents an executable tool that agents can invoke.
All tool implementations should implement this interface.
Implementation locations:
- tools.BaseTool - Base implementation with common functionality
- tools/compute/* - Computation tools
- tools/http/* - HTTP request tools
- tools/search/* - Search tools
- tools/shell/* - Shell execution tools
- tools/practical/* - Practical utility tools
See: tools/tool.go for the base implementation
type ToolCall ¶
type ToolCall struct {
// ID is a unique identifier for this tool call.
//
// Useful for correlating calls across logs and traces.
ID string `json:"id"`
// ToolName is the name of the tool that was called.
ToolName string `json:"tool_name"`
// Args are the arguments passed to the tool.
Args map[string]interface{} `json:"args"`
// Result is the output from the tool.
//
// May be nil if the call is still in progress.
Result *ToolOutput `json:"result,omitempty"`
// Error contains error information if the call failed.
//
// Empty string if the call succeeded.
Error string `json:"error,omitempty"`
// StartTime is when the tool call started (Unix timestamp).
StartTime int64 `json:"start_time"`
// EndTime is when the tool call completed (Unix timestamp).
//
// Zero if the call is still in progress.
EndTime int64 `json:"end_time,omitempty"`
// Metadata contains additional context about the call.
//
// May include caller information, trace IDs, etc.
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ToolCall represents a record of a tool invocation.
This is used for logging, auditing, and debugging purposes. It captures the complete context of a tool call.
type ToolExecutor ¶
type ToolExecutor interface {
// ExecuteTool executes a tool by name with the given arguments.
//
// The executor is responsible for:
// - Looking up the tool by name
// - Validating arguments against the tool's schema
// - Executing the tool
// - Handling errors and timeouts
ExecuteTool(ctx context.Context, toolName string, args map[string]interface{}) (*ToolResult, error)
// ListTools returns all available tools.
//
// This is useful for agents that need to discover what tools
// they can use.
ListTools() []Tool
}
ToolExecutor represents a component that can execute tools.
This interface is implemented by components that need to run tools, such as agents and workflow engines.
Implementation locations:
- agents/executor/executor_agent.go - Executor agent implementation
- tools/registry.go - Tool registry with execution capabilities
type ToolInput ¶
type ToolInput struct {
// Args contains the tool's input parameters.
//
// The structure of Args should match the tool's ArgsSchema.
Args map[string]interface{} `json:"args"`
// Context is the execution context (not serialized).
//
// This is used for cancellation, timeouts, and passing
// request-scoped values.
Context context.Context `json:"-"`
// CallerID identifies who is invoking the tool.
//
// Optional. Used for authorization and auditing.
CallerID string `json:"caller_id,omitempty"`
// TraceID is used for distributed tracing.
//
// Optional. Helps track tool execution across systems.
TraceID string `json:"trace_id,omitempty"`
}
ToolInput represents tool execution input.
This structure contains all necessary information to execute a tool, including arguments and metadata for tracing and debugging.
type ToolOutput ¶
type ToolOutput struct {
// Result contains the tool's output data.
//
// The type depends on the specific tool. Common types:
// - string: Text output
// - map[string]interface{}: Structured data
// - []byte: Binary data
Result interface{} `json:"result"`
// Success indicates whether the tool executed successfully.
//
// True if the tool completed without errors, false otherwise.
Success bool `json:"success"`
// Error contains the error message if Success is false.
//
// Empty string if Success is true.
Error string `json:"error,omitempty"`
// Metadata contains additional information about execution.
//
// Optional. May include:
// - execution_time: How long the tool took to run
// - retries: Number of retry attempts
// - cost: API call cost (for external services)
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ToolOutput represents tool execution output.
This structure contains the result of tool execution along with status information and metadata.
type ToolResult ¶
type ToolResult struct {
// ToolName is the name of the tool that was executed.
ToolName string `json:"tool_name"`
// Output contains the tool's execution output.
Output *ToolOutput `json:"output"`
// ExecutionTime is how long the tool took to execute (in milliseconds).
//
// Optional. Useful for performance monitoring.
ExecutionTime int64 `json:"execution_time,omitempty"`
}
ToolResult represents the result of a tool execution by a ToolExecutor.
This is different from ToolOutput in that it includes additional information that executors track, such as the tool that was run.
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.