worker

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 11, 2026 License: MIT Imports: 11 Imported by: 0

README ΒΆ

OmniAgent Worker

Go CI Go Lint Go SAST Docs Docs Visualization License

Go-first multi-agent worker framework for building task-oriented agent teams.

Overview

omniagent-worker provides building blocks for creating multi-agent systems in Go:

  • βš™οΈ Worker: Minimal interface for task-oriented agents
  • 🎯 Coordinator: Manages worker teams with workflow support
  • πŸ“¦ Pool: In-process worker management for embedded use
  • πŸ‘οΈ AgentOps: Full observability via OpenTelemetry-compatible tracing

Installation

go get github.com/plexusone/omniagent-worker

Quick Start

In-Process Workers (Embedded)
package main

import (
    "context"

    worker "github.com/plexusone/omniagent-worker"
)

func main() {
    ctx := context.Background()

    // Create coordinator
    coord := worker.NewCoordinator(worker.CoordinatorConfig{
        ID: "my-coordinator",
    })

    // Register workers
    coord.Pool().Register(NewMyWorker())

    // Execute
    resp, err := coord.Execute(ctx, &worker.CoordinatorRequest{
        Input: map[string]any{"topic": "example"},
    })
}
Standalone HTTP Server
package main

import (
    "context"

    worker "github.com/plexusone/omniagent-worker"
    "github.com/plexusone/omniagent-worker/server"
)

func main() {
    ctx := context.Background()

    myWorker := NewMyWorker(worker.WorkerConfig{
        ID:   "my-worker",
        Type: "processor",
    })

    server.Run(ctx, myWorker, server.Config{Port: 8080})
}

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚           server/ (optional)                β”‚
β”‚  HTTP endpoints, health checks, A2A         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚              Core Package                   β”‚
β”‚  Worker, Coordinator, Pool, AgentOps        β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚           External Dependencies             β”‚
β”‚  omniobserve/agentops, omnillm, eino        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

OmniAgent Family

omniagent-worker is part of the OmniAgent family:

Package Purpose
omniagent Full conversational assistant with channels
omniagent-worker Task-oriented workers and coordinators

Documentation

License

MIT License - see LICENSE for details.

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 ΒΆ

View Source
const (
	ErrCodeValidation   = "VALIDATION_ERROR"
	ErrCodeExecution    = "EXECUTION_ERROR"
	ErrCodeTimeout      = "TIMEOUT_ERROR"
	ErrCodeLLM          = "LLM_ERROR"
	ErrCodeNotFound     = "NOT_FOUND"
	ErrCodeUnavailable  = "UNAVAILABLE"
	ErrCodeInternal     = "INTERNAL_ERROR"
	ErrCodeCancelled    = "CANCELLED"
	ErrCodeRateLimited  = "RATE_LIMITED"
	ErrCodeUnauthorized = "UNAUTHORIZED"
)

Error codes.

View Source
const (
	HealthStatusHealthy   = "healthy"
	HealthStatusDegraded  = "degraded"
	HealthStatusUnhealthy = "unhealthy"
)

Health status constants.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func IsWorkerError ΒΆ

func IsWorkerError(err error) bool

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 ΒΆ

func (b *BaseWorker) Execute(ctx context.Context, req *Request) (*Response, error)

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) ID ΒΆ

func (b *BaseWorker) ID() string

ID returns the worker ID.

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) Type ΒΆ

func (b *BaseWorker) Type() string

Type returns the worker type.

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 ΒΆ

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) ID ΒΆ

func (c *Coordinator) ID() string

ID returns the coordinator ID.

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.

func (*Coordinator) Shutdown ΒΆ

func (c *Coordinator) Shutdown(ctx context.Context) error

Shutdown shuts down the coordinator and all pool workers.

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 NewPool ΒΆ

func NewPool() *Pool

NewPool creates a new worker pool.

func (*Pool) Execute ΒΆ

func (p *Pool) Execute(ctx context.Context, workerID string, req *Request) (*Response, error)

Execute calls a worker in the pool. Returns an error if the worker is not found.

func (*Pool) Get ΒΆ

func (p *Pool) Get(id string) (Worker, bool)

Get retrieves a worker by ID.

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) IDs ΒΆ

func (p *Pool) IDs() []string

IDs returns the IDs of all registered workers.

func (*Pool) Init ΒΆ

func (p *Pool) Init(ctx context.Context) error

Init initializes all workers in the pool. Stops and returns the first error encountered.

func (*Pool) List ΒΆ

func (p *Pool) List() []Worker

List returns all registered workers.

func (*Pool) Register ΒΆ

func (p *Pool) Register(w Worker) error

Register adds a worker to the pool. Returns an error if a worker with the same ID already exists.

func (*Pool) Shutdown ΒΆ

func (p *Pool) Shutdown(ctx context.Context) error

Shutdown shuts down all workers in the pool. Continues on error and returns the last error encountered.

func (*Pool) Size ΒΆ

func (p *Pool) Size() int

Size returns the number of workers in the pool.

func (*Pool) Unregister ΒΆ

func (p *Pool) Unregister(id string) error

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 ΒΆ

func NewRequest(input map[string]any) *Request

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.

func NewResponse ΒΆ

func NewResponse(requestID string, output map[string]any) *Response

NewResponse creates a successful 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.

func (*SequentialWorkflow) Execute ΒΆ

func (w *SequentialWorkflow) Execute(ctx context.Context, input map[string]any, dispatcher WorkerDispatcher) (map[string]any, error)

Execute runs workers sequentially, passing output from one to the next.

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) Execute ΒΆ

func (c *WorkerClient) Execute(ctx context.Context, req *Request) (*Response, error)

Execute calls the remote worker's execute endpoint.

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.

func (WorkflowFunc) Execute ΒΆ

func (f WorkflowFunc) Execute(ctx context.Context, input map[string]any, dispatcher WorkerDispatcher) (map[string]any, error)

Execute 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.

Directories ΒΆ

Path Synopsis
Package server provides HTTP server functionality for workers and coordinators.
Package server provides HTTP server functionality for workers and coordinators.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL