Documentation
ΒΆ
Overview ΒΆ
Package worker provides building blocks for multi-agent systems in Go.
omniagent-worker offers a minimal, composable framework for creating task-oriented agent teams with full observability support.
Core Concepts ΒΆ
Worker is the fundamental interface for task-oriented agents. Workers are stateless request/response handlers that can be deployed in-process or as HTTP microservices.
Coordinator manages teams of workers, orchestrating workflow execution with support for both deterministic (Eino) and LLM-driven coordination.
Pool provides in-process worker management for embedded use cases, enabling lightweight deployment without HTTP overhead.
Observability ΒΆ
All operations integrate with AgentOps (omniobserve) for OpenTelemetry- compatible tracing of workflows, tasks, and handoffs.
Example ΒΆ
coord := worker.NewCoordinator(worker.CoordinatorConfig{
ID: "stats-team",
})
coord.Pool().Register(research.NewWorker())
coord.Pool().Register(synthesis.NewWorker())
resp, err := coord.Execute(ctx, &worker.CoordinatorRequest{
Input: map[string]any{"topic": "climate change"},
})
Index ΒΆ
- Constants
- func IsWorkerError(err error) bool
- type AgentOpsConfig
- type BaseWorker
- func (b *BaseWorker) AgentOps() agentops.Store
- func (b *BaseWorker) Config() WorkerConfig
- func (b *BaseWorker) Execute(ctx context.Context, req *Request) (*Response, error)
- func (b *BaseWorker) Health(ctx context.Context) HealthStatus
- func (b *BaseWorker) ID() string
- func (b *BaseWorker) Init(ctx context.Context) error
- func (b *BaseWorker) Logger() *slog.Logger
- func (b *BaseWorker) Shutdown(ctx context.Context) error
- func (b *BaseWorker) Type() string
- func (b *BaseWorker) Version() string
- type ClientOption
- type Coordinator
- func (c *Coordinator) AddRemote(id, url string, opts ...ClientOption)
- func (c *Coordinator) Execute(ctx context.Context, req *CoordinatorRequest) (*CoordinatorResponse, error)
- func (c *Coordinator) Health(ctx context.Context) HealthStatus
- func (c *Coordinator) ID() string
- func (c *Coordinator) Init(ctx context.Context) error
- func (c *Coordinator) Pool() *Pool
- func (c *Coordinator) RemoveRemote(id string)
- func (c *Coordinator) Shutdown(ctx context.Context) error
- type CoordinatorConfig
- type CoordinatorRequest
- type CoordinatorResponse
- type HealthStatus
- type LLMConfig
- type Pool
- func (p *Pool) Execute(ctx context.Context, workerID string, req *Request) (*Response, error)
- func (p *Pool) Get(id string) (Worker, bool)
- func (p *Pool) Health(ctx context.Context) HealthStatus
- func (p *Pool) IDs() []string
- func (p *Pool) Init(ctx context.Context) error
- func (p *Pool) List() []Worker
- func (p *Pool) Register(w Worker) error
- func (p *Pool) Shutdown(ctx context.Context) error
- func (p *Pool) Size() int
- func (p *Pool) Unregister(id string) error
- type Request
- type Response
- type SequentialWorkflow
- type Worker
- type WorkerClient
- type WorkerConfig
- type WorkerDispatcher
- type WorkerError
- func AsWorkerError(err error) *WorkerError
- func NewError(code, message string) *WorkerError
- func NewErrorWithCause(code, message string, cause error) *WorkerError
- func NewExecutionError(message string, cause error) *WorkerError
- func NewLLMError(message string, cause error) *WorkerError
- func NewNotFoundError(message string) *WorkerError
- func NewTimeoutError(message string) *WorkerError
- func NewValidationError(message string) *WorkerError
- type WorkflowExecutor
- type WorkflowFunc
- type WorkflowStats
Constants ΒΆ
const ( ErrCodeValidation = "VALIDATION_ERROR" ErrCodeExecution = "EXECUTION_ERROR" ErrCodeTimeout = "TIMEOUT_ERROR" ErrCodeLLM = "LLM_ERROR" ErrCodeNotFound = "NOT_FOUND" ErrCodeInternal = "INTERNAL_ERROR" ErrCodeCancelled = "CANCELLED" ErrCodeRateLimited = "RATE_LIMITED" )
Error codes.
const ( HealthStatusHealthy = "healthy" HealthStatusDegraded = "degraded" HealthStatusUnhealthy = "unhealthy" )
Health status constants.
Variables ΒΆ
This section is empty.
Functions ΒΆ
func IsWorkerError ΒΆ
IsWorkerError checks if an error is a WorkerError.
Types ΒΆ
type AgentOpsConfig ΒΆ
type AgentOpsConfig struct {
// Enabled controls whether AgentOps tracing is active.
Enabled bool
// Store is the AgentOps store for persisting traces.
// If nil and Enabled is true, a no-op store is used.
Store agentops.Store
}
AgentOpsConfig configures AgentOps observability.
type BaseWorker ΒΆ
type BaseWorker struct {
// contains filtered or unexported fields
}
BaseWorker provides common functionality for workers. Embed this in your worker implementation to get default behavior.
func NewBaseWorker ΒΆ
func NewBaseWorker(cfg WorkerConfig) BaseWorker
NewBaseWorker creates a new BaseWorker with the given configuration.
func (*BaseWorker) AgentOps ΒΆ
func (b *BaseWorker) AgentOps() agentops.Store
AgentOps returns the AgentOps store, or nil if not configured.
func (*BaseWorker) Config ΒΆ
func (b *BaseWorker) Config() WorkerConfig
Config returns the worker configuration.
func (*BaseWorker) Execute ΒΆ
Execute is not implemented in BaseWorker. You must implement this in your worker.
func (*BaseWorker) Health ΒΆ
func (b *BaseWorker) Health(ctx context.Context) HealthStatus
Health returns a healthy status by default. Override this in your worker for custom health checks.
func (*BaseWorker) Init ΒΆ
func (b *BaseWorker) Init(ctx context.Context) error
Init is a no-op default implementation. Override this in your worker if initialization is needed.
func (*BaseWorker) Logger ΒΆ
func (b *BaseWorker) Logger() *slog.Logger
Logger returns the worker's logger.
func (*BaseWorker) Shutdown ΒΆ
func (b *BaseWorker) Shutdown(ctx context.Context) error
Shutdown is a no-op default implementation. Override this in your worker if cleanup is needed.
func (*BaseWorker) Version ΒΆ
func (b *BaseWorker) Version() string
Version returns the worker version.
type ClientOption ΒΆ
type ClientOption func(*WorkerClient)
ClientOption configures a WorkerClient.
func WithHTTPClient ΒΆ
func WithHTTPClient(client *http.Client) ClientOption
WithHTTPClient sets a custom HTTP client.
func WithHeader ΒΆ
func WithHeader(key, value string) ClientOption
WithHeader adds a default header to all requests.
func WithTimeout ΒΆ
func WithTimeout(d time.Duration) ClientOption
WithTimeout sets the HTTP client timeout.
type Coordinator ΒΆ
type Coordinator struct {
// contains filtered or unexported fields
}
Coordinator manages a team of workers and orchestrates workflow execution.
func NewCoordinator ΒΆ
func NewCoordinator(cfg CoordinatorConfig) *Coordinator
NewCoordinator creates a new coordinator.
func (*Coordinator) AddRemote ΒΆ
func (c *Coordinator) AddRemote(id, url string, opts ...ClientOption)
AddRemote adds a remote worker endpoint.
func (*Coordinator) Execute ΒΆ
func (c *Coordinator) Execute(ctx context.Context, req *CoordinatorRequest) (*CoordinatorResponse, error)
Execute runs the workflow with the given input.
func (*Coordinator) Health ΒΆ
func (c *Coordinator) Health(ctx context.Context) HealthStatus
Health returns the aggregate health of the coordinator and workers.
func (*Coordinator) Init ΒΆ
func (c *Coordinator) Init(ctx context.Context) error
Init initializes the coordinator and all pool workers.
func (*Coordinator) Pool ΒΆ
func (c *Coordinator) Pool() *Pool
Pool returns the in-process worker pool.
func (*Coordinator) RemoveRemote ΒΆ
func (c *Coordinator) RemoveRemote(id string)
RemoveRemote removes a remote worker endpoint.
type CoordinatorConfig ΒΆ
type CoordinatorConfig struct {
// ID is the unique identifier for this coordinator.
ID string
// Workflow is the workflow executor for orchestration.
// If nil, a simple sequential executor is used.
Workflow WorkflowExecutor
// AgentOps configures observability.
AgentOps *AgentOpsConfig
// Logger is the logger for this coordinator.
Logger *slog.Logger
// Timeout is the maximum execution time for a workflow.
// Default: 5 minutes.
Timeout time.Duration
// MaxRetries is the maximum number of retries for failed tasks.
// Default: 3.
MaxRetries int
}
CoordinatorConfig configures a coordinator.
func (*CoordinatorConfig) Defaults ΒΆ
func (c *CoordinatorConfig) Defaults()
Defaults applies default values to the config.
type CoordinatorRequest ΒΆ
type CoordinatorRequest struct {
// WorkflowID is a unique identifier for this workflow instance.
// If empty, one will be generated.
WorkflowID string `json:"workflow_id,omitempty"`
// Input contains workflow-specific input data.
Input map[string]any `json:"input"`
}
CoordinatorRequest is the input to a coordinator.
type CoordinatorResponse ΒΆ
type CoordinatorResponse struct {
// WorkflowID echoes back the workflow ID.
WorkflowID string `json:"workflow_id"`
// Output contains workflow output data.
Output map[string]any `json:"output"`
// Stats contains execution statistics.
Stats WorkflowStats `json:"stats"`
// Error contains error information if the workflow failed.
Error *WorkerError `json:"error,omitempty"`
}
CoordinatorResponse is the output from a coordinator.
type HealthStatus ΒΆ
type HealthStatus struct {
// Status is one of "healthy", "degraded", or "unhealthy".
Status string `json:"status"`
// Details contains additional health information.
Details map[string]string `json:"details,omitempty"`
}
HealthStatus represents the health of a worker.
type LLMConfig ΒΆ
type LLMConfig struct {
// Provider is the LLM provider (e.g., "anthropic", "openai", "gemini").
Provider string
// Model is the model name (e.g., "claude-sonnet-4-20250514").
Model string
// APIKey is the API key for the provider.
// If empty, will be read from environment.
APIKey string
// BaseURL is an optional custom base URL for the provider.
BaseURL string
// Temperature controls randomness (0.0-1.0).
Temperature float64
// MaxTokens is the maximum tokens in the response.
MaxTokens int
}
LLMConfig configures the LLM client for workers.
type Pool ΒΆ
type Pool struct {
// contains filtered or unexported fields
}
Pool manages a collection of in-process workers.
func (*Pool) Execute ΒΆ
Execute calls a worker in the pool. Returns an error if the worker is not found.
func (*Pool) Health ΒΆ
func (p *Pool) Health(ctx context.Context) HealthStatus
Health returns the aggregate health of all workers. Returns "unhealthy" if any worker is unhealthy. Returns "degraded" if any worker is degraded. Returns "healthy" only if all workers are healthy.
func (*Pool) Init ΒΆ
Init initializes all workers in the pool. Stops and returns the first error encountered.
func (*Pool) Register ΒΆ
Register adds a worker to the pool. Returns an error if a worker with the same ID already exists.
func (*Pool) Shutdown ΒΆ
Shutdown shuts down all workers in the pool. Continues on error and returns the last error encountered.
func (*Pool) Unregister ΒΆ
Unregister removes a worker from the pool. Returns an error if the worker is not found.
type Request ΒΆ
type Request struct {
// ID is a unique identifier for this request.
ID string `json:"id"`
// TaskID is the AgentOps task ID for tracing.
TaskID string `json:"task_id,omitempty"`
// WorkflowID is the workflow this request belongs to.
WorkflowID string `json:"workflow_id,omitempty"`
// Input contains worker-specific input data.
Input map[string]any `json:"input"`
}
Request is the input to a worker.
func NewRequest ΒΆ
NewRequest creates a new request with a generated ID.
type Response ΒΆ
type Response struct {
// RequestID echoes back the request ID.
RequestID string `json:"request_id"`
// Output contains worker-specific output data.
Output map[string]any `json:"output"`
// Error contains structured error information if the request failed.
Error *WorkerError `json:"error,omitempty"`
}
Response is the output from a worker.
func NewErrorResponse ΒΆ
func NewErrorResponse(requestID string, err *WorkerError) *Response
NewErrorResponse creates an error response.
type SequentialWorkflow ΒΆ
type SequentialWorkflow struct {
// WorkerIDs is the ordered list of workers to execute.
WorkerIDs []string
// InputMapper maps workflow input to worker input.
// If nil, the workflow input is passed directly to each worker.
InputMapper func(workerID string, workflowInput, previousOutput map[string]any) map[string]any
}
SequentialWorkflow executes workers in sequence. This is the default workflow when none is specified.
type Worker ΒΆ
type Worker interface {
// ID returns the unique identifier for this worker instance.
ID() string
// Type returns the worker type (e.g., "research", "synthesis").
// Multiple workers can have the same type.
Type() string
// Version returns the worker implementation version.
Version() string
// Init initializes the worker. Called once before Execute.
Init(ctx context.Context) error
// Shutdown gracefully shuts down the worker.
Shutdown(ctx context.Context) error
// Health returns the current health status of the worker.
Health(ctx context.Context) HealthStatus
// Execute performs the worker's task.
Execute(ctx context.Context, req *Request) (*Response, error)
}
Worker is the base interface for task-oriented agents. Workers are stateless request/response handlers that can be deployed in-process or as HTTP microservices.
type WorkerClient ΒΆ
type WorkerClient struct {
// contains filtered or unexported fields
}
WorkerClient is an HTTP client for calling remote workers.
func NewWorkerClient ΒΆ
func NewWorkerClient(baseURL string, opts ...ClientOption) *WorkerClient
NewWorkerClient creates a new HTTP client for a remote worker.
func (*WorkerClient) Health ΒΆ
func (c *WorkerClient) Health(ctx context.Context) (HealthStatus, error)
Health checks the health of the remote worker.
type WorkerConfig ΒΆ
type WorkerConfig struct {
// ID is the unique identifier for this worker instance.
ID string
// Type is the worker type (e.g., "research", "synthesis").
Type string
// Version is the worker implementation version.
Version string
// LLM configures the LLM client for workers that need it.
// Optional - not all workers require LLM.
LLM *LLMConfig
// AgentOps configures observability.
AgentOps *AgentOpsConfig
// Logger is the logger for this worker.
// If nil, a default logger is used.
Logger *slog.Logger
// Timeout is the maximum execution time for a single request.
// Default: 60 seconds.
Timeout time.Duration
}
WorkerConfig configures a worker.
func (*WorkerConfig) Defaults ΒΆ
func (c *WorkerConfig) Defaults()
Defaults applies default values to the config.
type WorkerDispatcher ΒΆ
type WorkerDispatcher interface {
// Dispatch calls a worker by ID with the given request.
Dispatch(ctx context.Context, workerID string, req *Request) (*Response, error)
}
WorkerDispatcher is used by workflows to call workers.
type WorkerError ΒΆ
type WorkerError struct {
// Code is a machine-readable error code.
Code string `json:"code"`
// Message is a human-readable error message.
Message string `json:"message"`
// Details contains additional error context.
Details any `json:"details,omitempty"`
// Cause is the underlying error, if any.
Cause error `json:"-"`
}
WorkerError provides structured error information.
func AsWorkerError ΒΆ
func AsWorkerError(err error) *WorkerError
AsWorkerError converts an error to a WorkerError. If the error is already a WorkerError, it is returned as-is. Otherwise, a new WorkerError is created wrapping the original error.
func NewError ΒΆ
func NewError(code, message string) *WorkerError
NewError creates a new WorkerError.
func NewErrorWithCause ΒΆ
func NewErrorWithCause(code, message string, cause error) *WorkerError
NewErrorWithCause creates a new WorkerError with an underlying cause.
func NewExecutionError ΒΆ
func NewExecutionError(message string, cause error) *WorkerError
NewExecutionError creates an execution error.
func NewLLMError ΒΆ
func NewLLMError(message string, cause error) *WorkerError
NewLLMError creates an LLM error.
func NewNotFoundError ΒΆ
func NewNotFoundError(message string) *WorkerError
NewNotFoundError creates a not found error.
func NewTimeoutError ΒΆ
func NewTimeoutError(message string) *WorkerError
NewTimeoutError creates a timeout error.
func NewValidationError ΒΆ
func NewValidationError(message string) *WorkerError
NewValidationError creates a validation error.
func (*WorkerError) Error ΒΆ
func (e *WorkerError) Error() string
Error implements the error interface.
func (*WorkerError) Unwrap ΒΆ
func (e *WorkerError) Unwrap() error
Unwrap returns the underlying error.
type WorkflowExecutor ΒΆ
type WorkflowExecutor interface {
// Execute runs the workflow with the given input.
// The dispatcher is used to call workers within the workflow.
Execute(ctx context.Context, input map[string]any, dispatcher WorkerDispatcher) (map[string]any, error)
}
WorkflowExecutor defines how workflows are executed. Implement this interface to provide custom orchestration logic.
type WorkflowFunc ΒΆ
type WorkflowFunc func(ctx context.Context, input map[string]any, dispatcher WorkerDispatcher) (map[string]any, error)
WorkflowFunc is a function that implements WorkflowExecutor.
type WorkflowStats ΒΆ
type WorkflowStats struct {
// Duration is the total workflow execution time.
Duration time.Duration `json:"duration"`
// TaskCount is the number of tasks executed.
TaskCount int `json:"task_count"`
// SuccessCount is the number of successful tasks.
SuccessCount int `json:"success_count"`
// FailureCount is the number of failed tasks.
FailureCount int `json:"failure_count"`
// RetryCount is the number of retried tasks.
RetryCount int `json:"retry_count"`
}
WorkflowStats contains execution statistics.