Documentation
¶
Overview ¶
Package agent provides a unified interface for all LLM agents in the system.
Index ¶
- func ExtractJSON(content string) string
- func FormatMediaParts(parts []interface{}, source string) string
- func FormatMediaPartsWithSources(parts []MediaPartWithSource) string
- func GetSharedContext(ctx context.Context, req *Request) (profile, recentTopics, innerCircle string)
- func GetUserID(req *Request) storage.ScopeID
- func ReferenceTime(ctx context.Context, req *Request) time.Time
- func UnmarshalLenient(content string, v any) (repaired bool, err error)
- func WithAgentType(ctx context.Context, agentType AgentType) context.Context
- func WithContext(ctx context.Context, shared *SharedContext) context.Context
- func WithReferenceTime(ctx context.Context, referenceTime time.Time) context.Context
- type Agent
- type AgentType
- type AgenticOptions
- type Capabilities
- type CapableAgent
- type ContextService
- type Executor
- func (e *Executor) AgentLogger() *agentlog.Logger
- func (e *Executor) Client() llm.Client
- func (e *Executor) ExecuteAgentic(ctx context.Context, req SingleShotRequest, opts AgenticOptions) (*Response, error)
- func (e *Executor) ExecuteSingleShot(ctx context.Context, req SingleShotRequest) (*Response, error)
- type FlexID
- type MediaEntry
- type MediaPart
- type MediaPartWithSource
- type Message
- type Registry
- type Request
- type RequestBuilder
- func (b *RequestBuilder) Build() *Request
- func (b *RequestBuilder) WithMedia(media []MediaPart) *RequestBuilder
- func (b *RequestBuilder) WithMessages(messages []Message) *RequestBuilder
- func (b *RequestBuilder) WithParam(key string, value any) *RequestBuilder
- func (b *RequestBuilder) WithParams(params map[string]any) *RequestBuilder
- func (b *RequestBuilder) WithQuery(query string) *RequestBuilder
- func (b *RequestBuilder) WithShared(shared *SharedContext) *RequestBuilder
- type Response
- type ResponseBuilder
- func (b *ResponseBuilder) Build() *Response
- func (b *ResponseBuilder) WithContent(content string) *ResponseBuilder
- func (b *ResponseBuilder) WithDuration(d time.Duration) *ResponseBuilder
- func (b *ResponseBuilder) WithMetadata(key string, value any) *ResponseBuilder
- func (b *ResponseBuilder) WithReasoning(reasoning string) *ResponseBuilder
- func (b *ResponseBuilder) WithStructured(data any) *ResponseBuilder
- func (b *ResponseBuilder) WithTokens(prompt, completion, total int) *ResponseBuilder
- type SharedContext
- type SharedContextBuilder
- func (b *SharedContextBuilder) Build() *SharedContext
- func (b *SharedContextBuilder) WithInnerCircle(circle string) *SharedContextBuilder
- func (b *SharedContextBuilder) WithLanguage(lang string) *SharedContextBuilder
- func (b *SharedContextBuilder) WithProfile(profile string) *SharedContextBuilder
- func (b *SharedContextBuilder) WithProfileFacts(facts []storage.Fact) *SharedContextBuilder
- func (b *SharedContextBuilder) WithRecentTopics(topics string) *SharedContextBuilder
- func (b *SharedContextBuilder) WithUserID(userID storage.ScopeID) *SharedContextBuilder
- type SingleShotRequest
- type TokenUsage
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ExtractJSON ¶ added in v0.10.1
ExtractJSON returns the first balanced JSON object or array found in an LLM response, stripping markdown fences, preamble text and trailing garbage. Brace tracking is string-aware (quotes and escapes inside JSON strings are handled). When no balanced JSON value is found, the content is returned unchanged so the caller's unmarshal error stays informative.
func FormatMediaParts ¶ added in v0.9.0
FormatMediaParts produces the JSON body for *.media_parts span events.
Each entry records filename + mime + decoded size + sha256 of decoded bytes. The hash matches artifacts.content_hash, so a faithful replay can look up the underlying file in the snapshotted artifact storage and reconstruct the original FilePart byte-for-byte without dragging the raw base64 payload through Tempo.
Non-FilePart entries are skipped silently — callers may pass a heterogenous content slice (e.g., llm.Message.Content as []interface{} mixing TextPart and FilePart). Returns "" when nothing recordable is found.
Use FormatMediaPartsWithSources when entries have distinct origins.
func FormatMediaPartsWithSources ¶ added in v0.9.0
func FormatMediaPartsWithSources(parts []MediaPartWithSource) string
FormatMediaPartsWithSources is the multi-source variant for laplace where current-message media and reranker-selected artifacts coexist in one event.
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
GetUserID extracts the scope id from request SharedContext or params. Returns "" if not found.
func ReferenceTime ¶ added in v0.11.0
ReferenceTime returns the request-scoped reference time, if one is available.
func UnmarshalLenient ¶ added in v0.10.1
UnmarshalLenient extracts the first balanced JSON value from content and unmarshals it into v. The repaired result reports whether extraction had to change the content (fences, preamble or trailing garbage were stripped) — callers surface it as a span attribute so repair frequency is observable.
func WithAgentType ¶ added in v0.11.0
WithAgentType associates an LLM call with the agent that initiated it.
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" TypeReactor AgentType = "reactor" )
func AgentTypeFromContext ¶ added in v0.11.0
AgentTypeFromContext returns the agent associated with the current LLM call.
type AgenticOptions ¶
type AgenticOptions struct {
MaxTurns int
Tools []llm.Tool
ToolHandler func(ctx context.Context, calls []llm.ToolCall) []llm.Message
Timeout time.Duration
TurnTimeout time.Duration
Reasoning *llm.ReasoningConfig
Plugins []llm.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 storage.ScopeID) *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.
func (*ContextService) SetScopeRepository ¶ added in v0.10.0
func (c *ContextService) SetScopeRepository(repo storage.ScopeRepository)
SetScopeRepository sets the scope repository used to detect channel scopes (Phase 6). When nil, every scope is treated as a DM.
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor provides common execution logic for agents.
func NewExecutor ¶
NewExecutor creates a new Executor.
func (*Executor) AgentLogger ¶
AgentLogger returns the agent logger.
func (*Executor) Client ¶
Client returns the underlying LLM 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 ¶
ExecuteSingleShot runs a single LLM call with logging.
type FlexID ¶ added in v0.10.1
type FlexID string
FlexID is a string-valued ID that tolerates the LLM emitting it as a JSON number ("fact_id": 5215) instead of a string ("fact_id": "5215" or "fact_id": "Fact:5215"). It unmarshals from string, number or null and marshals back as a plain string.
func (*FlexID) UnmarshalJSON ¶ added in v0.10.1
UnmarshalJSON accepts a JSON string, number or null.
type MediaEntry ¶ added in v0.9.0
type MediaEntry struct {
Filename string `json:"filename"`
Mime string `json:"mime"`
SizeBytes int `json:"size_bytes"`
SHA256 string `json:"sha256,omitempty"`
// Source distinguishes where in the prompt the part lives —
// laplace uses it to mark current_message vs reranker_selected vs
// input_artifact_id; reranker/enricher pass empty string.
Source string `json:"source,omitempty"`
}
MediaEntry is the JSON shape of one file in an *.media_parts span event. Replay relies on this exact field layout to reconstruct llm.FilePart from a snapshot DB by content_hash — keep changes coordinated with cmd/testbot/snapshot/extract.go.
type MediaPart ¶
type MediaPart struct {
Type string // "image", "audio", "file"
MimeType string
Data []byte
URL string // Alternative to Data
}
MediaPart represents multimodal input.
type MediaPartWithSource ¶ added in v0.9.0
type MediaPartWithSource struct {
Part interface{}
Source string
}
MediaPartWithSource pairs an OR FilePart with an optional source label. Pass source="" for agents that don't differentiate origin (enricher, reranker). Laplace uses it to attribute each entry to the right pipeline stage so triage can answer "which artifact came from RAG vs from the user".
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds all registered agents.
type Request ¶
type Request struct {
Shared *SharedContext
// Query
Query string // Main query/content to process
Messages []Message // Conversation history (for chat agents)
// Multimodal
Media []MediaPart // Images, audio, files
// IsChannel marks the scope as a multi-participant channel (Phase 6). Agents
// use it to select channel-framed prompts; false for DMs. Set by the caller
// from ScopeRepository.IsChannelScope at the invocation site (background loops
// have no SharedContext).
IsChannel bool
// 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 {
// Profile (always loaded)
RecentTopics string // Formatted <recent_topics>
InnerCircle string // Formatted <inner_circle> (Work_Inner + Family), or <channel_participants> for channels
// use it to select channel-framed prompts; false for DMs.
IsChannel bool
// Metadata
}
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 storage.ScopeID) *SharedContextBuilder
WithUserID sets the user ID.
type SingleShotRequest ¶
type SingleShotRequest struct {
AgentType AgentType
UserID storage.ScopeID
Model string
SystemPrompt string
UserPrompt string
Messages []llm.Message // Alternative to SystemPrompt+UserPrompt
Temperature *float64
JSONMode bool
JSONSchema *llm.JSONSchema // Optional: strict JSON schema validation
Reasoning *llm.ReasoningConfig // Optional: nil omits the field (provider default)
}
SingleShotRequest for simple one-turn agents.
type TokenUsage ¶
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.
Source Files
¶
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 imagegen implements an image-generation agent that drives OpenRouter image-output models (e.g.
|
Package imagegen implements an image-generation agent that drives OpenRouter image-output models (e.g. |
|
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 reactor provides the Reactor agent that decides whether to add an emoji reaction to a user message, and which one.
|
Package reactor provides the Reactor agent that decides whether to add an emoji reaction to a user message, and which one. |
|
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. |