agent

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package agent provides a unified interface for all LLM agents in the system.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetSharedContext added in v0.6.1

func GetSharedContext(ctx context.Context, req *Request) (profile, recentTopics, innerCircle string)

GetSharedContext extracts profile, recent topics, and inner circle from SharedContext (request or context.Context).

Returns empty XML-tagged defaults if SharedContext is not available. Callers that need DB fallback should implement it themselves.

This helper eliminates duplicated fallback logic across agents.

func GetUserID added in v0.6.1

func GetUserID(req *Request) int64

GetUserID extracts user ID from request SharedContext or params. Returns 0 if not found.

func WithContext

func WithContext(ctx context.Context, shared *SharedContext) context.Context

WithContext injects SharedContext into context.Context.

Types

type Agent

type Agent interface {
	// Type returns the agent's type identifier.
	Type() AgentType

	// Execute runs the agent with the given request.
	Execute(ctx context.Context, req *Request) (*Response, error)
}

Agent is the core interface all agents implement.

type AgentType

type AgentType string

AgentType identifies an agent.

const (
	TypeLaplace      AgentType = "laplace"
	TypeReranker     AgentType = "reranker"
	TypeEnricher     AgentType = "enricher"
	TypeSplitter     AgentType = "splitter"
	TypeMerger       AgentType = "merger"
	TypeArchivist    AgentType = "archivist"
	TypeDeduplicator AgentType = "deduplicator"
	TypeScout        AgentType = "scout"
	TypeExtractor    AgentType = "extractor"
)

func (AgentType) String

func (t AgentType) String() string

String implements fmt.Stringer.

type AgenticOptions

type AgenticOptions struct {
	MaxTurns    int
	Tools       []openrouter.Tool
	ToolHandler func(ctx context.Context, calls []openrouter.ToolCall) []openrouter.Message
	Timeout     time.Duration
	TurnTimeout time.Duration
	Reasoning   *openrouter.ReasoningConfig
	Plugins     []openrouter.Plugin
	ToolChoice  any // "auto", "none", "required", or specific tool
}

AgenticOptions for multi-turn agents.

type Capabilities

type Capabilities struct {
	// Execution model
	IsAgentic         bool // Uses tool calls (multi-turn)
	SupportsStreaming bool // Can stream responses

	// Input capabilities
	SupportedMedia []string // ["image", "audio", "pdf"]
	MaxInputTokens int      // Context limit

	// Output format
	OutputFormat string // "text", "json", "structured"
}

Capabilities describes what an agent can do.

type CapableAgent

type CapableAgent interface {
	Agent

	// Capabilities returns the agent's capabilities.
	Capabilities() Capabilities

	// Description returns a human-readable description for tool use.
	Description() string
}

CapableAgent extends Agent with metadata for discovery.

type ContextService

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

ContextService loads and manages SharedContext.

func NewContextService

func NewContextService(
	factRepo storage.FactRepository,
	topicRepo storage.TopicRepository,
	cfg *config.Config,
	logger *slog.Logger,
) *ContextService

NewContextService creates a new ContextService.

func (*ContextService) Load

func (c *ContextService) Load(ctx context.Context, userID int64) *SharedContext

Load creates SharedContext for a user. Call once per request at the beginning of processing.

func (*ContextService) SetPeopleRepository added in v0.5.1

func (c *ContextService) SetPeopleRepository(repo storage.PeopleRepository)

SetPeopleRepository sets the people repository for loading inner circle.

type Executor

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

Executor provides common execution logic for agents.

func NewExecutor

func NewExecutor(
	client openrouter.Client,
	agentLogger *agentlog.Logger,
	logger *slog.Logger,
) *Executor

NewExecutor creates a new Executor.

func (*Executor) AgentLogger

func (e *Executor) AgentLogger() *agentlog.Logger

AgentLogger returns the agent logger.

func (*Executor) Client

func (e *Executor) Client() openrouter.Client

Client returns the underlying OpenRouter client. Useful for agents that need custom request handling.

func (*Executor) ExecuteAgentic

func (e *Executor) ExecuteAgentic(ctx context.Context, req SingleShotRequest, opts AgenticOptions) (*Response, error)

ExecuteAgentic runs a multi-turn agent loop with tool calls.

func (*Executor) ExecuteSingleShot

func (e *Executor) ExecuteSingleShot(ctx context.Context, req SingleShotRequest) (*Response, error)

ExecuteSingleShot runs a single LLM call with logging.

type MediaPart

type MediaPart struct {
	Type     string // "image", "audio", "file"
	MimeType string
	Data     []byte
	URL      string // Alternative to Data
}

MediaPart represents multimodal input.

type Message

type Message struct {
	Role    string
	Content string
}

Message represents a conversation message.

type Registry

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

Registry holds all registered agents.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new Registry.

func (*Registry) Count

func (r *Registry) Count() int

Count returns the number of registered agents.

func (*Registry) Get

func (r *Registry) Get(t AgentType) Agent

Get retrieves an agent by type. Returns nil if not found.

func (*Registry) Has

func (r *Registry) Has(t AgentType) bool

Has checks if an agent type is registered.

func (*Registry) List

func (r *Registry) List() []Agent

List returns all registered agents.

func (*Registry) MustGet

func (r *Registry) MustGet(t AgentType) Agent

MustGet retrieves an agent or panics (for initialization).

func (*Registry) Register

func (r *Registry) Register(agent Agent)

Register adds an agent to the registry.

func (*Registry) Types

func (r *Registry) Types() []AgentType

Types returns all registered agent types.

type Request

type Request struct {
	// Context (from ContextService)
	Shared *SharedContext

	// Query
	Query    string    // Main query/content to process
	Messages []Message // Conversation history (for chat agents)

	// Multimodal
	Media []MediaPart // Images, audio, files

	// Agent-specific
	Params map[string]any // Custom parameters
}

Request is the unified input for all agents.

type RequestBuilder added in v0.6.1

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

RequestBuilder builds Request objects for testing.

func NewRequestBuilder added in v0.6.1

func NewRequestBuilder() *RequestBuilder

NewRequestBuilder creates a new RequestBuilder with defaults.

func (*RequestBuilder) Build added in v0.6.1

func (b *RequestBuilder) Build() *Request

Build returns the constructed Request.

func (*RequestBuilder) WithMedia added in v0.6.1

func (b *RequestBuilder) WithMedia(media []MediaPart) *RequestBuilder

WithMedia sets the multimodal media parts.

func (*RequestBuilder) WithMessages added in v0.6.1

func (b *RequestBuilder) WithMessages(messages []Message) *RequestBuilder

WithMessages sets the conversation messages.

func (*RequestBuilder) WithParam added in v0.6.1

func (b *RequestBuilder) WithParam(key string, value any) *RequestBuilder

WithParam sets a single parameter.

func (*RequestBuilder) WithParams added in v0.6.1

func (b *RequestBuilder) WithParams(params map[string]any) *RequestBuilder

WithParams sets all parameters.

func (*RequestBuilder) WithQuery added in v0.6.1

func (b *RequestBuilder) WithQuery(query string) *RequestBuilder

WithQuery sets the query string.

func (*RequestBuilder) WithShared added in v0.6.1

func (b *RequestBuilder) WithShared(shared *SharedContext) *RequestBuilder

WithShared sets the SharedContext.

type Response

type Response struct {
	// Content
	Content    string // Text response
	Structured any    // Parsed result (for JSON agents)

	// Metadata
	Tokens    TokenUsage
	Duration  time.Duration
	Reasoning string // Chain-of-thought (if available)

	// Agent-specific
	Metadata map[string]any
}

Response is the unified output from all agents.

type ResponseBuilder added in v0.6.1

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

ResponseBuilder builds Response objects for testing.

func NewResponseBuilder added in v0.6.1

func NewResponseBuilder() *ResponseBuilder

NewResponseBuilder creates a new ResponseBuilder with defaults.

func (*ResponseBuilder) Build added in v0.6.1

func (b *ResponseBuilder) Build() *Response

Build returns the constructed Response.

func (*ResponseBuilder) WithContent added in v0.6.1

func (b *ResponseBuilder) WithContent(content string) *ResponseBuilder

WithContent sets the text content.

func (*ResponseBuilder) WithDuration added in v0.6.1

func (b *ResponseBuilder) WithDuration(d time.Duration) *ResponseBuilder

WithDuration sets the execution duration.

func (*ResponseBuilder) WithMetadata added in v0.6.1

func (b *ResponseBuilder) WithMetadata(key string, value any) *ResponseBuilder

WithMetadata sets a metadata key-value pair.

func (*ResponseBuilder) WithReasoning added in v0.6.1

func (b *ResponseBuilder) WithReasoning(reasoning string) *ResponseBuilder

WithReasoning sets the reasoning text.

func (*ResponseBuilder) WithStructured added in v0.6.1

func (b *ResponseBuilder) WithStructured(data any) *ResponseBuilder

WithStructured sets the structured data result.

func (*ResponseBuilder) WithTokens added in v0.6.1

func (b *ResponseBuilder) WithTokens(prompt, completion, total int) *ResponseBuilder

WithTokens sets token usage.

type SharedContext

type SharedContext struct {
	UserID int64

	// Profile (always loaded)
	Profile      string         // Formatted <user_profile> for prompts
	ProfileFacts []storage.Fact // Raw facts (for custom formatting)

	// Topics
	RecentTopics string // Formatted <recent_topics>

	// Social Graph (v0.5.1)
	InnerCircle string // Formatted <inner_circle> (Work_Inner + Family)

	// Metadata
	Language string // "en" or "ru"
	LoadedAt time.Time
}

SharedContext holds user data shared across all agents. Loaded once per request to ensure all agents see the same data.

func FromContext

func FromContext(ctx context.Context) *SharedContext

FromContext extracts SharedContext from context.Context. Returns nil if not found.

func MustFromContext

func MustFromContext(ctx context.Context) *SharedContext

MustFromContext extracts SharedContext from context.Context. Panics if not found.

type SharedContextBuilder added in v0.6.1

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

SharedContextBuilder builds SharedContext objects for testing.

func NewSharedContextBuilder added in v0.6.1

func NewSharedContextBuilder() *SharedContextBuilder

NewSharedContextBuilder creates a new SharedContextBuilder with defaults.

func (*SharedContextBuilder) Build added in v0.6.1

func (b *SharedContextBuilder) Build() *SharedContext

Build returns the constructed SharedContext.

func (*SharedContextBuilder) WithInnerCircle added in v0.6.1

func (b *SharedContextBuilder) WithInnerCircle(circle string) *SharedContextBuilder

WithInnerCircle sets the inner circle string.

func (*SharedContextBuilder) WithLanguage added in v0.6.1

func (b *SharedContextBuilder) WithLanguage(lang string) *SharedContextBuilder

WithLanguage sets the language code.

func (*SharedContextBuilder) WithProfile added in v0.6.1

func (b *SharedContextBuilder) WithProfile(profile string) *SharedContextBuilder

WithProfile sets the profile string.

func (*SharedContextBuilder) WithProfileFacts added in v0.6.1

func (b *SharedContextBuilder) WithProfileFacts(facts []storage.Fact) *SharedContextBuilder

WithProfileFacts sets the profile facts.

func (*SharedContextBuilder) WithRecentTopics added in v0.6.1

func (b *SharedContextBuilder) WithRecentTopics(topics string) *SharedContextBuilder

WithRecentTopics sets the recent topics string.

func (*SharedContextBuilder) WithUserID added in v0.6.1

func (b *SharedContextBuilder) WithUserID(userID int64) *SharedContextBuilder

WithUserID sets the user ID.

type SingleShotRequest

type SingleShotRequest struct {
	AgentType    AgentType
	UserID       int64
	Model        string
	SystemPrompt string
	UserPrompt   string
	Messages     []openrouter.Message // Alternative to SystemPrompt+UserPrompt
	Temperature  *float64
	JSONMode     bool
	JSONSchema   *openrouter.JSONSchema // Optional: strict JSON schema validation
}

SingleShotRequest for simple one-turn agents.

type TokenUsage

type TokenUsage struct {
	Prompt     int
	Completion int
	Total      int
	Cost       *float64
}

TokenUsage tracks token consumption.

func (TokenUsage) TotalTokens

func (t TokenUsage) TotalTokens() int

TotalTokens returns the total token count. If Total is set, returns it; otherwise computes Prompt + Completion.

Directories

Path Synopsis
Package archivist provides the Archivist agent that extracts and manages facts and people from conversations for long-term memory.
Package archivist provides the Archivist agent that extracts and manages facts and people from conversations for long-term memory.
Package enricher provides the Enricher agent that expands user queries for better vector retrieval in the RAG pipeline.
Package enricher provides the Enricher agent that expands user queries for better vector retrieval in the RAG pipeline.
Package merger provides the Merger agent that evaluates whether two topics should be merged and generates a combined summary.
Package merger provides the Merger agent that evaluates whether two topics should be merged and generates a combined summary.
Package prompts provides typed parameter structs for agent prompt templates.
Package prompts provides typed parameter structs for agent prompt templates.
Package reranker provides the Reranker agent that uses tool calls to select the most relevant topics from vector search candidates.
Package reranker provides the Reranker agent that uses tool calls to select the most relevant topics from vector search candidates.
Package splitter provides the Splitter agent that segments conversation logs into distinct topics for storage and retrieval.
Package splitter provides the Splitter agent that segments conversation logs into distinct topics for storage and retrieval.
Package testing provides test utilities for the agent package.
Package testing provides test utilities for the agent package.

Jump to

Keyboard shortcuts

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