agent

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package agent provides the AI agent runtime for omniagent.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent is the AI agent that processes messages.

func New

func New(config Config, opts ...Option) (*Agent, error)

New creates a new agent with optional configuration.

Example:

agent, err := agent.New(config,
    agent.WithStorage(sqliteStorage),
    agent.WithCompiledSkill(investSkill),
)

func (*Agent) ClearSession added in v0.6.0

func (a *Agent) ClearSession(ctx context.Context, sessionID string) error

ClearSession clears the conversation history for a session.

func (*Agent) Close

func (a *Agent) Close() error

Close closes the agent and releases resources.

func (*Agent) CloseCompiledSkills added in v0.5.0

func (a *Agent) CloseCompiledSkills() error

CloseCompiledSkills closes all registered compiled skills.

func (*Agent) ContextEngine added in v0.6.0

func (a *Agent) ContextEngine() *agentctx.Engine

ContextEngine returns the context engine, or nil if not configured.

func (*Agent) DeleteSession added in v0.6.0

func (a *Agent) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession removes a session.

func (*Agent) Dispatcher added in v0.6.0

func (a *Agent) Dispatcher() *hooks.Dispatcher

Dispatcher returns the event dispatcher.

func (*Agent) GetCompiledSkills added in v0.5.0

func (a *Agent) GetCompiledSkills() []compiled.Skill

GetCompiledSkills returns all registered compiled skills.

func (*Agent) GetSession added in v0.6.0

func (a *Agent) GetSession(ctx context.Context, sessionID string) (*sessions.Session, error)

GetSession retrieves a session by ID. Returns nil if sessions are not configured or session doesn't exist.

func (*Agent) GetSkills

func (a *Agent) GetSkills() []*skills.Skill

GetSkills returns the loaded skills.

func (*Agent) HookRegistry added in v0.6.0

func (a *Agent) HookRegistry() *hooks.Registry

HookRegistry returns the hook registry.

func (*Agent) InitCompiledSkills added in v0.5.0

func (a *Agent) InitCompiledSkills(ctx context.Context) error

InitCompiledSkills initializes all registered compiled skills.

func (*Agent) InitHooks added in v0.6.0

func (a *Agent) InitHooks(ctx context.Context) error

InitHooks initializes all registered hooks.

func (*Agent) ListSessions added in v0.6.0

func (a *Agent) ListSessions(ctx context.Context) ([]string, error)

ListSessions returns all session IDs.

func (*Agent) LoadSkills

func (a *Agent) LoadSkills(dirs []string) error

LoadSkills loads skills from the given directories.

func (*Agent) Process

func (a *Agent) Process(ctx context.Context, sessionID, content string) (string, error)

Process processes a message and returns a response. This is a stateless call that doesn't use session history. Use ProcessWithSession for conversation continuity.

func (*Agent) ProcessWithMemory

func (a *Agent) ProcessWithMemory(ctx context.Context, sessionID, content string) (string, error)

ProcessWithMemory processes a message using conversation memory. Deprecated: Use ProcessWithSession instead.

func (*Agent) ProcessWithSession added in v0.6.0

func (a *Agent) ProcessWithSession(ctx context.Context, sessionID, content string) (string, error)

ProcessWithSession processes a message using persistent session history. Conversation history is automatically loaded and saved.

func (*Agent) RegisterCompiledSkill added in v0.5.0

func (a *Agent) RegisterCompiledSkill(skill compiled.Skill) error

RegisterCompiledSkill registers a compiled skill with the agent. This converts the skill's tools to agent tools and registers them.

func (*Agent) RegisterTool

func (a *Agent) RegisterTool(tool Tool)

RegisterTool registers a tool with the agent.

func (*Agent) SessionStore added in v0.6.0

func (a *Agent) SessionStore() *sessions.Store

SessionStore returns the session store, or nil if not configured.

func (*Agent) SetContextEngine added in v0.6.0

func (a *Agent) SetContextEngine(engine *agentctx.Engine)

SetContextEngine sets the context engine.

func (*Agent) SetStorage added in v0.5.0

func (a *Agent) SetStorage(s kvs.Store)

SetStorage sets the storage backend for the agent. This also injects storage into any storage-aware compiled skills.

type BaseTool

type BaseTool struct {
	// contains filtered or unexported fields
}

BaseTool provides a base implementation for tools.

func NewBaseTool

func NewBaseTool(name, description string, parameters map[string]interface{}, handler func(ctx context.Context, args json.RawMessage) (string, error)) *BaseTool

NewBaseTool creates a new base tool.

func (*BaseTool) Description

func (t *BaseTool) Description() string

func (*BaseTool) Execute

func (t *BaseTool) Execute(ctx context.Context, args json.RawMessage) (string, error)

func (*BaseTool) Name

func (t *BaseTool) Name() string

func (*BaseTool) Parameters

func (t *BaseTool) Parameters() map[string]interface{}

type Config

type Config struct {
	Provider          string
	Model             string
	APIKey            string //nolint:gosec // G117: APIKey is intentionally stored for provider authentication
	BaseURL           string
	Temperature       float64
	MaxTokens         int
	SystemPrompt      string
	Logger            *slog.Logger
	ObservabilityHook omnillm.ObservabilityHook
}

Config configures the agent.

type Option added in v0.5.0

type Option func(*Agent) error

Option configures the agent.

func WithCompiledHook added in v0.6.0

func WithCompiledHook(hook hooks.Hook) Option

WithCompiledHook registers a compiled hook for handling events. Compiled hooks implement the hooks.Hook interface and support initialization, cleanup, and multi-event handling.

Example:

type AuditHook struct {
    logger *slog.Logger
}

func (h *AuditHook) Name() string { return "audit" }
func (h *AuditHook) Events() []hooks.EventType {
    return []hooks.EventType{hooks.EventMessageReceived, hooks.EventMessageSent}
}
func (h *AuditHook) Handle(ctx context.Context, event hooks.Event) error {
    h.logger.Info("event", "type", event.Type, "data", event.Data)
    return nil
}
func (h *AuditHook) Init(ctx context.Context) error { return nil }
func (h *AuditHook) Close() error { return nil }

agent, err := agent.New(config,
    agent.WithCompiledHook(&AuditHook{logger: slog.Default()}),
)

func WithCompiledSkill added in v0.5.0

func WithCompiledSkill(skill compiled.Skill) Option

WithCompiledSkill registers a compiled skill with the agent. Multiple skills can be registered by calling this option multiple times.

Example:

agent, err := agent.New(config,
    agent.WithCompiledSkill(investSkill),
    agent.WithCompiledSkill(weatherSkill),
)

func WithContextConfig added in v0.6.0

func WithContextConfig(cfg agentctx.Config) Option

WithContextConfig creates a context engine with the given configuration. This is a convenience option for simple context configuration.

Example:

agent, err := agent.New(config,
    agent.WithContextConfig(context.Config{
        MaxMessages: 50,
        MaxTokens:   8000,
    }),
)

func WithContextEngine added in v0.6.0

func WithContextEngine(engine *agentctx.Engine) Option

WithContextEngine sets the context engine for conversation management. This enables automatic windowing and token limit enforcement.

Example:

engine := context.New(context.Config{
    MaxMessages: 50,
    MaxTokens:   8000,
})
agent, err := agent.New(config,
    agent.WithContextEngine(engine),
)

func WithCronScheduler added in v0.6.0

func WithCronScheduler() Option

WithCronScheduler registers the cron skill for scheduled job execution. This requires storage to be configured (use WithStorage or WithSessionsFromStorage).

Example:

sqliteStore, _ := sqlite.New(sqlite.Config{Path: "data.db"})
agent, err := agent.New(config,
    agent.WithSessionsFromStorage(sqliteStore),
    agent.WithCronScheduler(),
)

func WithHook added in v0.6.0

func WithHook(event hooks.EventType, handler hooks.HandlerFunc) Option

WithHook registers a quick handler for an event type. This is the simplest way to handle events.

Example:

agent, err := agent.New(config,
    agent.WithHook(hooks.EventMessageReceived, func(ctx context.Context, e hooks.Event) error {
        msg := e.Data.(hooks.MessageEvent)
        log.Printf("Received: %s", msg.Content)
        return nil
    }),
)

func WithMCPSkill added in v0.6.0

func WithMCPSkill(cfg mcpskill.Config) Option

WithMCPSkill registers an MCP server as a compiled skill. This spawns the MCP server as a subprocess and exposes its tools to the agent.

Example:

agent, err := agent.New(config,
    agent.WithMCPSkill(mcpskill.Config{
        Name:    "github",
        Command: []string{"npx", "-y", "@modelcontextprotocol/server-github"},
        Env: map[string]string{
            "GITHUB_TOKEN": os.Getenv("GITHUB_TOKEN"),
        },
    }),
)

func WithMaxMessages added in v0.6.0

func WithMaxMessages(max int) Option

WithMaxMessages sets a simple message limit for context. This creates a context engine with only a message limit.

Example:

agent, err := agent.New(config,
    agent.WithMaxMessages(50),
)

func WithNamedHook added in v0.6.0

func WithNamedHook(event hooks.EventType, name string, handler hooks.HandlerFunc) Option

WithNamedHook registers a named handler for an event type. The name is used in logging to identify the handler.

Example:

agent, err := agent.New(config,
    agent.WithNamedHook(hooks.EventMessageReceived, "audit-log", func(ctx context.Context, e hooks.Event) error {
        msg := e.Data.(hooks.MessageEvent)
        log.Printf("[AUDIT] Received: %s", msg.Content)
        return nil
    }),
)

func WithSessionStore added in v0.6.0

func WithSessionStore(store *sessions.Store) Option

WithSessionStore sets the session store for conversation persistence. This enables ProcessWithSession to maintain conversation history.

Example:

sqliteStore, _ := sqlite.New(sqlite.Config{Path: "data.db"})
sessionStore := sessions.NewStore(sessions.StoreConfig{Backend: sqliteStore})
agent, err := agent.New(config,
    agent.WithSessionStore(sessionStore),
)

func WithSessionsFromStorage added in v0.6.0

func WithSessionsFromStorage(backend kvs.Store) Option

WithSessionsFromStorage creates a session store from the given KVS backend. This is a convenience option that combines WithStorage and WithSessionStore.

Example:

sqliteStore, _ := sqlite.New(sqlite.Config{Path: "data.db"})
agent, err := agent.New(config,
    agent.WithSessionsFromStorage(sqliteStore),
)

func WithStorage added in v0.5.0

func WithStorage(s kvs.Store) Option

WithStorage sets the storage backend for the agent. Storage is automatically injected into any storage-aware compiled skills.

Example:

sqliteStore, _ := sqlite.New(sqlite.Config{Path: "data.db"})
agent, err := agent.New(config,
    agent.WithStorage(sqliteStore),
    agent.WithCompiledSkill(investSkill),
)

func WithTool added in v0.5.0

func WithTool(tool Tool) Option

WithTool registers a single tool with the agent.

Example:

agent, err := agent.New(config,
    agent.WithTool(myTool),
)

func WithWebhookHook added in v0.6.0

func WithWebhookHook(webhook *hooks.WebhookHook) Option

WithWebhookHook registers a webhook-based hook that sends events to an HTTP endpoint.

Example:

agent, err := agent.New(config,
    agent.WithWebhookHook(&hooks.WebhookHook{
        HookName:   "slack-notify",
        HookEvents: []hooks.EventType{hooks.EventMessageSent},
        URL:        "https://hooks.slack.com/services/xxx",
        Method:     "POST",
        Timeout:    5 * time.Second,
    }),
)

type SearchArgs

type SearchArgs struct {
	Query string `json:"query"`
	Type  string `json:"type,omitempty"` // "web", "news", "images" (default: "web")
}

SearchArgs are the arguments for the search tool.

type SearchTool

type SearchTool struct {
	// contains filtered or unexported fields
}

SearchTool provides web search capabilities via omniserp.

func NewSearchTool

func NewSearchTool() (*SearchTool, error)

NewSearchTool creates a new search tool.

func (*SearchTool) Description

func (t *SearchTool) Description() string

func (*SearchTool) Execute

func (t *SearchTool) Execute(ctx context.Context, argsJSON json.RawMessage) (string, error)

func (*SearchTool) Name

func (t *SearchTool) Name() string

func (*SearchTool) Parameters

func (t *SearchTool) Parameters() map[string]interface{}

type Session deprecated

type Session struct {
	ID        string
	Messages  []provider.Message
	CreatedAt time.Time
	UpdatedAt time.Time
	Metadata  map[string]interface{}
	// contains filtered or unexported fields
}

Session represents a conversation session.

Deprecated: Use sessions.Session from github.com/plexusone/omniagent/sessions.

func (*Session) AddMessage

func (sess *Session) AddMessage(role provider.Role, content string)

AddMessage adds a message to the session.

func (*Session) Clear

func (sess *Session) Clear()

Clear removes all messages from the session.

func (*Session) GetMessages

func (sess *Session) GetMessages() []provider.Message

GetMessages returns all messages in the session.

func (*Session) GetMetadata

func (sess *Session) GetMetadata(key string) (interface{}, bool)

GetMetadata gets a metadata value.

func (*Session) SetMetadata

func (sess *Session) SetMetadata(key string, value interface{})

SetMetadata sets a metadata value.

func (*Session) Trim

func (sess *Session) Trim(n int)

Trim keeps only the last n messages.

type SessionStore deprecated

type SessionStore struct {
	// contains filtered or unexported fields
}

SessionStore manages conversation sessions.

Deprecated: Use sessions.Store from github.com/plexusone/omniagent/sessions.

func NewSessionStore

func NewSessionStore() *SessionStore

NewSessionStore creates a new session store.

func (*SessionStore) Delete

func (s *SessionStore) Delete(id string)

Delete removes a session.

func (*SessionStore) Get

func (s *SessionStore) Get(id string) *Session

Get retrieves a session by ID, creating one if it doesn't exist.

func (*SessionStore) List

func (s *SessionStore) List() []string

List returns all session IDs.

type Tool

type Tool interface {
	// Name returns the tool name.
	Name() string
	// Description returns a description of what the tool does.
	Description() string
	// Parameters returns the JSON schema for the tool parameters.
	Parameters() map[string]interface{}
	// Execute runs the tool with the given arguments.
	Execute(ctx context.Context, args json.RawMessage) (string, error)
}

Tool represents an agent tool that can be invoked.

type ToolNotFoundError

type ToolNotFoundError struct {
	Name string
}

ToolNotFoundError is returned when a tool is not found.

func (*ToolNotFoundError) Error

func (e *ToolNotFoundError) Error() string

type ToolRegistry

type ToolRegistry struct {
	// contains filtered or unexported fields
}

ToolRegistry manages available tools.

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates a new tool registry.

func (*ToolRegistry) Execute

func (r *ToolRegistry) Execute(ctx context.Context, name string, args json.RawMessage) (string, error)

Execute runs a tool by name with the given arguments.

func (*ToolRegistry) Get

func (r *ToolRegistry) Get(name string) (Tool, bool)

Get retrieves a tool by name.

func (*ToolRegistry) GetTools

func (r *ToolRegistry) GetTools() []provider.Tool

GetTools returns tool definitions for the LLM.

func (*ToolRegistry) List

func (r *ToolRegistry) List() []string

List returns all registered tool names.

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(tool Tool)

Register adds a tool to the registry.

func (*ToolRegistry) Unregister

func (r *ToolRegistry) Unregister(name string)

Unregister removes a tool from the registry.

Jump to

Keyboard shortcuts

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