types

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsErrorCode

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode 检查错误是否为指定的错误码

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if an error is retryable. Uses errors.As to correctly handle wrapped errors.

func LLMModel

func LLMModel(ctx context.Context) (string, bool)

LLMModel extracts LLM model from context.

func PromptBundleVersion

func PromptBundleVersion(ctx context.Context) (string, bool)

PromptBundleVersion extracts prompt bundle version from context.

func Roles added in v1.0.0

func Roles(ctx context.Context) ([]string, bool)

Roles extracts user roles from context.

func RunID

func RunID(ctx context.Context) (string, bool)

RunID extracts run ID from context.

func TenantID

func TenantID(ctx context.Context) (string, bool)

TenantID extracts tenant ID from context.

func TraceID

func TraceID(ctx context.Context) (string, bool)

TraceID extracts trace ID from context.

func UserID

func UserID(ctx context.Context) (string, bool)

UserID extracts user ID from context.

func WithLLMModel

func WithLLMModel(ctx context.Context, model string) context.Context

WithLLMModel adds LLM model to context.

func WithPromptBundleVersion

func WithPromptBundleVersion(ctx context.Context, version string) context.Context

WithPromptBundleVersion adds prompt bundle version to context.

func WithRoles added in v1.0.0

func WithRoles(ctx context.Context, roles []string) context.Context

WithRoles adds user roles to context.

func WithRunID

func WithRunID(ctx context.Context, runID string) context.Context

WithRunID adds run ID to context.

func WithTenantID

func WithTenantID(ctx context.Context, tenantID string) context.Context

WithTenantID adds tenant ID to context.

func WithTraceID

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID adds trace ID to context.

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID adds user ID to context.

Types

type AgentConfig

type AgentConfig struct {
	// Core configuration (required)
	Core CoreConfig `json:"core"`

	// LLM configuration
	LLM LLMConfig `json:"llm"`

	// Feature configurations (optional)
	Features FeaturesConfig `json:"features,omitempty"`

	// Extension configurations (optional)
	Extensions ExtensionsConfig `json:"extensions,omitempty"`

	// Metadata for custom data
	Metadata map[string]string `json:"metadata,omitempty"`
}

AgentConfig represents the complete configuration for an agent. This replaces the flat Config structure with a more organized approach.

func (*AgentConfig) IsGuardrailsEnabled

func (c *AgentConfig) IsGuardrailsEnabled() bool

IsGuardrailsEnabled checks if guardrails are enabled.

func (*AgentConfig) IsMCPEnabled

func (c *AgentConfig) IsMCPEnabled() bool

IsMCPEnabled checks if MCP is enabled.

func (*AgentConfig) IsMemoryEnabled

func (c *AgentConfig) IsMemoryEnabled() bool

IsMemoryEnabled checks if memory is enabled.

func (*AgentConfig) IsObservabilityEnabled

func (c *AgentConfig) IsObservabilityEnabled() bool

IsObservabilityEnabled checks if observability is enabled.

func (*AgentConfig) IsReflectionEnabled

func (c *AgentConfig) IsReflectionEnabled() bool

IsReflectionEnabled checks if reflection is enabled.

func (*AgentConfig) IsSkillsEnabled

func (c *AgentConfig) IsSkillsEnabled() bool

IsSkillsEnabled checks if skills are enabled.

func (*AgentConfig) IsToolSelectionEnabled

func (c *AgentConfig) IsToolSelectionEnabled() bool

IsToolSelectionEnabled checks if tool selection is enabled.

func (*AgentConfig) Validate

func (c *AgentConfig) Validate() error

Validate validates the configuration.

type Annotation added in v1.2.0

type Annotation struct {
	Type       string `json:"type"` // "url_citation"
	StartIndex int    `json:"start_index,omitempty"`
	EndIndex   int    `json:"end_index,omitempty"`
	URL        string `json:"url,omitempty"`
	Title      string `json:"title,omitempty"`
}

Annotation represents a citation or reference annotation in a message.

type CoreConfig

type CoreConfig struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Type        string `json:"type"`
	Description string `json:"description,omitempty"`
}

CoreConfig contains essential agent identity and behavior settings.

type EnhancedMemoryExtension

type EnhancedMemoryExtension interface {
	// StoreWithImportance stores memory with importance scoring.
	StoreWithImportance(ctx context.Context, content string, importance float64) error
	// RetrieveByRelevance retrieves memories by relevance to query.
	RetrieveByRelevance(ctx context.Context, query string, topK int) ([]MemoryRecord, error)
	// Consolidate performs memory consolidation.
	Consolidate(ctx context.Context) error
	// Decay applies memory decay based on time and access patterns.
	Decay(ctx context.Context) error
}

EnhancedMemoryExtension provides advanced memory capabilities.

type Error

type Error struct {
	Code       ErrorCode `json:"code"`
	Message    string    `json:"message"`
	HTTPStatus int       `json:"http_status,omitempty"`
	Retryable  bool      `json:"retryable"`
	Provider   string    `json:"provider,omitempty"`
	Cause      error     `json:"-"`
}

Error represents a structured error with code, message, and metadata.

func AsError

func AsError(err error) (*Error, bool)

AsError 尝试将 error 转换为 *Error

func NewAuthenticationError

func NewAuthenticationError(message string) *Error

NewAuthenticationError 创建认证错误

func NewError

func NewError(code ErrorCode, message string) *Error

NewError creates a new Error with the given code and message.

func NewInternalError

func NewInternalError(message string) *Error

NewInternalError 创建内部错误

func NewInvalidRequestError

func NewInvalidRequestError(message string) *Error

NewInvalidRequestError 创建无效请求错误

func NewNotFoundError

func NewNotFoundError(message string) *Error

NewNotFoundError 创建未找到错误

func NewRateLimitError

func NewRateLimitError(message string) *Error

NewRateLimitError 创建限流错误

func NewServiceUnavailableError

func NewServiceUnavailableError(message string) *Error

NewServiceUnavailableError 创建服务不可用错误

func NewTimeoutError

func NewTimeoutError(message string) *Error

NewTimeoutError 创建超时错误

func WrapError

func WrapError(err error, code ErrorCode, message string) *Error

WrapError 包装标准错误为 types.Error Uses errors.As to correctly handle wrapped errors.

func WrapErrorf

func WrapErrorf(err error, code ErrorCode, format string, args ...any) *Error

WrapErrorf 包装标准错误为 types.Error(支持格式化)

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause.

func (*Error) WithCause

func (e *Error) WithCause(cause error) *Error

WithCause adds a cause to the error.

func (*Error) WithHTTPStatus

func (e *Error) WithHTTPStatus(status int) *Error

WithHTTPStatus sets the HTTP status code.

func (*Error) WithProvider

func (e *Error) WithProvider(provider string) *Error

WithProvider sets the provider name.

func (*Error) WithRetryable

func (e *Error) WithRetryable(retryable bool) *Error

WithRetryable marks the error as retryable.

type ErrorCode

type ErrorCode string

ErrorCode represents a unified error code across the framework.

const (
	ErrInvalidRequest      ErrorCode = "INVALID_REQUEST"
	ErrAuthentication      ErrorCode = "AUTHENTICATION"
	ErrUnauthorized        ErrorCode = "UNAUTHORIZED"
	ErrForbidden           ErrorCode = "FORBIDDEN"
	ErrRateLimit           ErrorCode = "RATE_LIMIT"
	ErrQuotaExceeded       ErrorCode = "QUOTA_EXCEEDED"
	ErrModelNotFound       ErrorCode = "MODEL_NOT_FOUND"
	ErrContextTooLong      ErrorCode = "CONTEXT_TOO_LONG"
	ErrContentFiltered     ErrorCode = "CONTENT_FILTERED"
	ErrToolValidation      ErrorCode = "TOOL_VALIDATION"
	ErrRoutingUnavailable  ErrorCode = "ROUTING_UNAVAILABLE"
	ErrModelOverloaded     ErrorCode = "MODEL_OVERLOADED"
	ErrUpstreamTimeout     ErrorCode = "UPSTREAM_TIMEOUT"
	ErrTimeout             ErrorCode = "TIMEOUT"
	ErrUpstreamError       ErrorCode = "UPSTREAM_ERROR"
	ErrInternalError       ErrorCode = "INTERNAL_ERROR"
	ErrServiceUnavailable  ErrorCode = "SERVICE_UNAVAILABLE"
	ErrProviderUnavailable ErrorCode = "PROVIDER_UNAVAILABLE"
)

LLM error codes

const (
	ErrAgentNotReady      ErrorCode = "AGENT_NOT_READY"
	ErrAgentBusy          ErrorCode = "AGENT_BUSY"
	ErrInvalidTransition  ErrorCode = "INVALID_TRANSITION"
	ErrProviderNotSet     ErrorCode = "PROVIDER_NOT_SET"
	ErrGuardrailsViolated ErrorCode = "GUARDRAILS_VIOLATED"
)

Agent error codes

const (
	ErrContextOverflow   ErrorCode = "CONTEXT_OVERFLOW"
	ErrCompressionFailed ErrorCode = "COMPRESSION_FAILED"
	ErrTokenizerError    ErrorCode = "TOKENIZER_ERROR"
)

Context error codes

func GetErrorCode

func GetErrorCode(err error) ErrorCode

GetErrorCode extracts the error code from an error. Uses errors.As to correctly handle wrapped errors.

type EstimateTokenizer

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

EstimateTokenizer provides a simple character-based token estimation.

func NewEstimateTokenizer

func NewEstimateTokenizer() *EstimateTokenizer

NewEstimateTokenizer creates a new EstimateTokenizer.

func (*EstimateTokenizer) CountMessageTokens

func (t *EstimateTokenizer) CountMessageTokens(msg Message) int

CountMessageTokens counts tokens in a message.

func (*EstimateTokenizer) CountMessagesTokens

func (t *EstimateTokenizer) CountMessagesTokens(msgs []Message) int

CountMessagesTokens counts tokens in messages.

func (*EstimateTokenizer) CountTokens

func (t *EstimateTokenizer) CountTokens(text string) int

CountTokens counts tokens in text.

func (*EstimateTokenizer) EstimateToolTokens

func (t *EstimateTokenizer) EstimateToolTokens(tools []ToolSchema) int

EstimateToolTokens estimates tokens for tools.

type Executor added in v1.0.0

type Executor interface {
	// ID returns the agent's unique identifier.
	ID() string
	// Execute runs the agent with the given input and returns the result.
	Execute(ctx context.Context, input any) (any, error)
}

Executor is the minimal agent execution interface. All agent variants share this common contract: an identity (ID) and the ability to execute with arbitrary input/output.

Domain-specific agent interfaces (conversation, crew, handoff, evaluation) extend or specialize this contract for their own needs.

type ExtensionRegistry

type ExtensionRegistry struct {
	Reflection     ReflectionExtension
	ToolSelection  ToolSelectionExtension
	PromptEnhancer PromptEnhancerExtension
	Skills         SkillsExtension
	MCP            MCPExtension
	EnhancedMemory EnhancedMemoryExtension
	Observability  ObservabilityExtension
	Guardrails     GuardrailsExtension
}

ExtensionRegistry holds all optional extensions for an agent.

func (*ExtensionRegistry) HasEnhancedMemory

func (r *ExtensionRegistry) HasEnhancedMemory() bool

HasEnhancedMemory returns true if enhanced memory extension is available.

func (*ExtensionRegistry) HasGuardrails

func (r *ExtensionRegistry) HasGuardrails() bool

HasGuardrails returns true if guardrails extension is available.

func (*ExtensionRegistry) HasMCP

func (r *ExtensionRegistry) HasMCP() bool

HasMCP returns true if MCP extension is available.

func (*ExtensionRegistry) HasObservability

func (r *ExtensionRegistry) HasObservability() bool

HasObservability returns true if observability extension is available.

func (*ExtensionRegistry) HasPromptEnhancer

func (r *ExtensionRegistry) HasPromptEnhancer() bool

HasPromptEnhancer returns true if prompt enhancer extension is available.

func (*ExtensionRegistry) HasReflection

func (r *ExtensionRegistry) HasReflection() bool

HasReflection returns true if reflection extension is available.

func (*ExtensionRegistry) HasSkills

func (r *ExtensionRegistry) HasSkills() bool

HasSkills returns true if skills extension is available.

func (*ExtensionRegistry) HasToolSelection

func (r *ExtensionRegistry) HasToolSelection() bool

HasToolSelection returns true if tool selection extension is available.

type ExtensionsConfig

type ExtensionsConfig struct {
	Skills        *SkillsConfig        `json:"skills,omitempty"`
	MCP           *MCPConfig           `json:"mcp,omitempty"`
	Observability *ObservabilityConfig `json:"observability,omitempty"`
}

ExtensionsConfig contains extension-specific configurations.

type FeaturesConfig

type FeaturesConfig struct {
	Reflection     *ReflectionConfig     `json:"reflection,omitempty"`
	ToolSelection  *ToolSelectionConfig  `json:"tool_selection,omitempty"`
	PromptEnhancer *PromptEnhancerConfig `json:"prompt_enhancer,omitempty"`
	Guardrails     *GuardrailsConfig     `json:"guardrails,omitempty"`
	Memory         *MemoryConfig         `json:"memory,omitempty"`
}

FeaturesConfig contains optional feature configurations. Each feature is enabled by providing its configuration (nil = disabled).

type GuardrailsConfig

type GuardrailsConfig struct {
	Enabled            bool     `json:"enabled"`
	MaxInputLength     int      `json:"max_input_length,omitempty"`
	BlockedKeywords    []string `json:"blocked_keywords,omitempty"`
	PIIDetection       bool     `json:"pii_detection,omitempty"`
	InjectionDetection bool     `json:"injection_detection,omitempty"`
	MaxRetries         int      `json:"max_retries,omitempty"`
}

GuardrailsConfig configures input/output validation.

func DefaultGuardrailsConfig

func DefaultGuardrailsConfig() *GuardrailsConfig

DefaultGuardrailsConfig returns sensible defaults.

type GuardrailsExtension

type GuardrailsExtension interface {
	// ValidateInput validates input before processing.
	ValidateInput(ctx context.Context, input string) (*ValidationResult, error)
	// ValidateOutput validates output before returning.
	ValidateOutput(ctx context.Context, output string) (*ValidationResult, error)
	// FilterOutput applies filters to output.
	FilterOutput(ctx context.Context, output string) (string, error)
}

GuardrailsExtension provides input/output validation.

type ImageContent

type ImageContent struct {
	Type string `json:"type"` // "url" or "base64"
	URL  string `json:"url,omitempty"`
	Data string `json:"data,omitempty"` // base64 encoded
}

ImageContent represents image data for multimodal messages.

type JSONSchema

type JSONSchema struct {
	Schema      string `json:"$schema,omitempty"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`

	Type SchemaType `json:"type,omitempty"`

	// Object properties
	Properties           map[string]*JSONSchema `json:"properties,omitempty"`
	Required             []string               `json:"required,omitempty"`
	AdditionalProperties *bool                  `json:"additionalProperties,omitempty"`

	// Array items
	Items    *JSONSchema `json:"items,omitempty"`
	MinItems *int        `json:"minItems,omitempty"`
	MaxItems *int        `json:"maxItems,omitempty"`

	// Enum and const
	Enum  []any `json:"enum,omitempty"`
	Const any   `json:"const,omitempty"`

	// String constraints
	MinLength *int         `json:"minLength,omitempty"`
	MaxLength *int         `json:"maxLength,omitempty"`
	Pattern   string       `json:"pattern,omitempty"`
	Format    StringFormat `json:"format,omitempty"`

	// Numeric constraints
	Minimum *float64 `json:"minimum,omitempty"`
	Maximum *float64 `json:"maximum,omitempty"`

	// Default value
	Default any `json:"default,omitempty"`
}

JSONSchema represents a JSON Schema definition.

func FromJSON

func FromJSON(data []byte) (*JSONSchema, error)

FromJSON deserializes a schema from JSON.

func NewArraySchema

func NewArraySchema(items *JSONSchema) *JSONSchema

NewArraySchema creates a new array schema.

func NewBooleanSchema

func NewBooleanSchema() *JSONSchema

NewBooleanSchema creates a new boolean schema.

func NewEnumSchema

func NewEnumSchema(values ...any) *JSONSchema

NewEnumSchema creates a new enum schema.

func NewIntegerSchema

func NewIntegerSchema() *JSONSchema

NewIntegerSchema creates a new integer schema.

func NewNumberSchema

func NewNumberSchema() *JSONSchema

NewNumberSchema creates a new number schema.

func NewObjectSchema

func NewObjectSchema() *JSONSchema

NewObjectSchema creates a new object schema.

func NewStringSchema

func NewStringSchema() *JSONSchema

NewStringSchema creates a new string schema.

func (*JSONSchema) AddProperty

func (s *JSONSchema) AddProperty(name string, prop *JSONSchema) *JSONSchema

AddProperty adds a property to an object schema.

func (*JSONSchema) AddRequired

func (s *JSONSchema) AddRequired(names ...string) *JSONSchema

AddRequired adds required field names.

func (*JSONSchema) ToJSON

func (s *JSONSchema) ToJSON() ([]byte, error)

ToJSON serializes the schema to JSON.

func (*JSONSchema) WithDescription

func (s *JSONSchema) WithDescription(desc string) *JSONSchema

WithDescription sets the description.

type LLMConfig

type LLMConfig struct {
	Model       string   `json:"model"`
	Provider    string   `json:"provider,omitempty"`
	MaxTokens   int      `json:"max_tokens,omitempty"`
	Temperature float32  `json:"temperature,omitempty"`
	TopP        float32  `json:"top_p,omitempty"`
	Stop        []string `json:"stop,omitempty"`
}

LLMConfig contains LLM-related settings.

type MCPConfig

type MCPConfig struct {
	Enabled   bool          `json:"enabled"`
	Endpoint  string        `json:"endpoint,omitempty"`
	AuthToken string        `json:"auth_token,omitempty"`
	Timeout   time.Duration `json:"timeout,omitempty"`
}

MCPConfig configures Model Context Protocol integration.

type MCPExtension

type MCPExtension interface {
	// Connect establishes MCP connection.
	Connect(ctx context.Context, endpoint string) error
	// Disconnect closes MCP connection.
	Disconnect(ctx context.Context) error
	// SendMessage sends a message via MCP.
	SendMessage(ctx context.Context, message any) (any, error)
	// IsConnected returns connection status.
	IsConnected() bool
}

MCPExtension provides Model Context Protocol support.

type MemoryCategory

type MemoryCategory string

MemoryCategory defines the unified memory category across the framework. This replaces the inconsistent MemoryKind (agent/) and MemoryType (agent/memory/).

const (
	// MemoryWorking represents short-term working memory for current task context.
	// Storage: In-memory or Redis with TTL.
	MemoryWorking MemoryCategory = "working"

	// MemoryEpisodic represents event-based experiential memories.
	// Storage: Vector store for semantic search.
	MemoryEpisodic MemoryCategory = "episodic"

	// MemorySemantic represents factual knowledge and learned information.
	// Storage: PostgreSQL/Qdrant for long-term persistence.
	MemorySemantic MemoryCategory = "semantic"

	// MemoryProcedural represents how-to knowledge and learned procedures.
	// Storage: Structured storage for procedure definitions.
	MemoryProcedural MemoryCategory = "procedural"
)

type MemoryConfig

type MemoryConfig struct {
	Enabled          bool          `json:"enabled"`
	ShortTermTTL     time.Duration `json:"short_term_ttl,omitempty"`
	MaxShortTermSize int           `json:"max_short_term_size,omitempty"`
	EnableLongTerm   bool          `json:"enable_long_term,omitempty"`
	EnableEpisodic   bool          `json:"enable_episodic,omitempty"`
	DecayEnabled     bool          `json:"decay_enabled,omitempty"`
}

MemoryConfig configures the memory system.

func DefaultMemoryConfig

func DefaultMemoryConfig() *MemoryConfig

DefaultMemoryConfig returns sensible defaults.

type MemoryQuery

type MemoryQuery struct {
	AgentID   string         `json:"agent_id"`
	Category  MemoryCategory `json:"category,omitempty"`
	Query     string         `json:"query,omitempty"`
	TopK      int            `json:"top_k,omitempty"`
	MinScore  float64        `json:"min_score,omitempty"`
	TimeRange *TimeRange     `json:"time_range,omitempty"`
}

MemoryQuery represents a query for memory retrieval.

type MemoryRecord

type MemoryRecord struct {
	ID          string         `json:"id"`
	AgentID     string         `json:"agent_id"`
	Category    MemoryCategory `json:"category"`
	Content     string         `json:"content"`
	Embedding   []float32      `json:"embedding,omitempty"`
	Importance  float64        `json:"importance,omitempty"`
	AccessCount int            `json:"access_count,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	VectorID    string         `json:"vector_id,omitempty"`
	Relations   []string       `json:"relations,omitempty"`
	CreatedAt   time.Time      `json:"created_at"`
	LastAccess  time.Time      `json:"last_access,omitempty"`
	ExpiresAt   *time.Time     `json:"expires_at,omitempty"`
}

MemoryRecord represents a unified memory entry structure.

type MemoryStats

type MemoryStats struct {
	TotalRecords   int            `json:"total_records"`
	ByCategory     map[string]int `json:"by_category"`
	OldestRecord   time.Time      `json:"oldest_record,omitempty"`
	NewestRecord   time.Time      `json:"newest_record,omitempty"`
	TotalSizeBytes int64          `json:"total_size_bytes,omitempty"`
}

MemoryStats provides statistics about memory usage.

type Message

type Message struct {
	Role             Role            `json:"role"`
	Content          string          `json:"content,omitempty"`
	ReasoningContent *string         `json:"reasoning_content,omitempty"` // 推理/思考内容
	ThinkingBlocks   []ThinkingBlock `json:"thinking_blocks,omitempty"`   // Claude thinking blocks(用于多轮 round-trip)
	Refusal          *string         `json:"refusal,omitempty"`           // 模型拒绝内容
	Name             string          `json:"name,omitempty"`
	ToolCalls        []ToolCall      `json:"tool_calls,omitempty"`
	ToolCallID       string          `json:"tool_call_id,omitempty"`
	IsToolError      bool            `json:"is_tool_error,omitempty"` // tool_result 是否为错误结果
	Images           []ImageContent  `json:"images,omitempty"`
	Videos           []VideoContent  `json:"videos,omitempty"`
	Annotations      []Annotation    `json:"annotations,omitempty"` // URL 引用注释
	Metadata         any             `json:"metadata,omitempty"`
	Timestamp        time.Time       `json:"timestamp,omitempty"`
}

Message represents a conversation message.

func NewAssistantMessage

func NewAssistantMessage(content string) Message

NewAssistantMessage creates a new assistant message.

func NewDeveloperMessage added in v1.2.0

func NewDeveloperMessage(content string) Message

NewDeveloperMessage creates a new developer instructions message.

func NewMessage

func NewMessage(role Role, content string) Message

NewMessage creates a new message with the given role and content.

func NewSystemMessage

func NewSystemMessage(content string) Message

NewSystemMessage creates a new system message.

func NewToolMessage

func NewToolMessage(toolCallID, name, content string) Message

NewToolMessage creates a new tool result message.

func NewUserMessage

func NewUserMessage(content string) Message

NewUserMessage creates a new user message.

func (Message) WithImages

func (m Message) WithImages(images []ImageContent) Message

WithImages adds images to the message.

func (Message) WithMetadata

func (m Message) WithMetadata(metadata any) Message

WithMetadata adds metadata to the message.

func (Message) WithToolCalls

func (m Message) WithToolCalls(calls []ToolCall) Message

WithToolCalls adds tool calls to the message.

type Named added in v1.0.0

type Named interface {
	// Name returns the agent's human-readable display name.
	Name() string
}

Named is an optional interface for agents that have a display name. Use a type assertion to check if an Executor also implements Named:

if named, ok := executor.(types.Named); ok {
    fmt.Println(named.Name())
}

type ObservabilityConfig

type ObservabilityConfig struct {
	Enabled        bool   `json:"enabled"`
	MetricsEnabled bool   `json:"metrics_enabled,omitempty"`
	TracingEnabled bool   `json:"tracing_enabled,omitempty"`
	LogLevel       string `json:"log_level,omitempty"`
	ServiceName    string `json:"service_name,omitempty"`
}

ObservabilityConfig configures metrics, tracing, and logging.

func DefaultObservabilityConfig

func DefaultObservabilityConfig() *ObservabilityConfig

DefaultObservabilityConfig returns sensible defaults.

type ObservabilityExtension

type ObservabilityExtension interface {
	// RecordMetric records a metric value.
	RecordMetric(name string, value float64, tags map[string]string)
	// StartSpan starts a new trace span.
	StartSpan(ctx context.Context, name string) (context.Context, SpanHandle)
	// LogEvent logs an event with structured data.
	LogEvent(level string, message string, fields map[string]any)
}

ObservabilityExtension provides metrics, tracing, and logging.

type PromptEnhancerConfig

type PromptEnhancerConfig struct {
	Enabled bool   `json:"enabled"`
	Mode    string `json:"mode,omitempty"` // "basic", "advanced", "custom"
}

PromptEnhancerConfig configures prompt enhancement.

func DefaultPromptEnhancerConfig

func DefaultPromptEnhancerConfig() *PromptEnhancerConfig

DefaultPromptEnhancerConfig returns sensible defaults.

type PromptEnhancerExtension

type PromptEnhancerExtension interface {
	// Enhance improves a prompt for better LLM performance.
	Enhance(ctx context.Context, prompt string, context map[string]any) (string, error)
	// GetEnhancementMode returns the current enhancement mode.
	GetEnhancementMode() string
}

PromptEnhancerExtension provides prompt optimization and enhancement.

type ReflectionConfig

type ReflectionConfig struct {
	Enabled       bool    `json:"enabled"`
	MaxIterations int     `json:"max_iterations,omitempty"`
	MinQuality    float64 `json:"min_quality,omitempty"`
	CriticPrompt  string  `json:"critic_prompt,omitempty"`
}

ReflectionConfig configures the reflection/self-improvement feature.

func DefaultReflectionConfig

func DefaultReflectionConfig() *ReflectionConfig

DefaultReflectionConfig returns sensible defaults for reflection.

type ReflectionExtension

type ReflectionExtension interface {
	// ExecuteWithReflection executes a task with reflection loop.
	ExecuteWithReflection(ctx context.Context, input any) (any, error)
	// IsEnabled returns whether reflection is enabled.
	IsEnabled() bool
}

ReflectionExtension provides self-evaluation and iterative improvement.

type Role

type Role string

Role represents the role of a message participant.

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
	RoleDeveloper Role = "developer" // OpenAI developer instructions role
)

type SchemaType

type SchemaType string

SchemaType represents JSON Schema types.

const (
	SchemaTypeString  SchemaType = "string"
	SchemaTypeNumber  SchemaType = "number"
	SchemaTypeInteger SchemaType = "integer"
	SchemaTypeBoolean SchemaType = "boolean"
	SchemaTypeNull    SchemaType = "null"
	SchemaTypeObject  SchemaType = "object"
	SchemaTypeArray   SchemaType = "array"
)

type SkillsConfig

type SkillsConfig struct {
	Enabled    bool     `json:"enabled"`
	SkillPaths []string `json:"skill_paths,omitempty"`
	AutoLoad   bool     `json:"auto_load,omitempty"`
	MaxLoaded  int      `json:"max_loaded,omitempty"`
}

SkillsConfig configures the skills system.

type SkillsExtension

type SkillsExtension interface {
	// LoadSkill loads a skill by name.
	LoadSkill(ctx context.Context, name string) error
	// ExecuteSkill executes a loaded skill.
	ExecuteSkill(ctx context.Context, name string, input any) (any, error)
	// ListSkills returns available skills.
	ListSkills() []string
}

SkillsExtension provides dynamic skill loading and execution.

type SpanHandle

type SpanHandle interface {
	// End ends the span.
	End()
	// SetAttribute sets an attribute on the span.
	SetAttribute(key string, value any)
	// RecordError records an error on the span.
	RecordError(err error)
}

SpanHandle represents a trace span that can be ended.

type StringFormat

type StringFormat string

StringFormat represents common string format constraints.

const (
	FormatDateTime StringFormat = "date-time"
	FormatDate     StringFormat = "date"
	FormatTime     StringFormat = "time"
	FormatEmail    StringFormat = "email"
	FormatURI      StringFormat = "uri"
	FormatUUID     StringFormat = "uuid"
)

type ThinkingBlock added in v1.2.0

type ThinkingBlock struct {
	Thinking  string `json:"thinking"`
	Signature string `json:"signature,omitempty"`
}

ThinkingBlock represents a Claude extended thinking content block. Used for round-tripping thinking blocks in multi-turn tool use conversations.

type TimeRange

type TimeRange struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

TimeRange represents a time range for filtering.

type TokenCounter added in v1.0.0

type TokenCounter interface {
	CountTokens(text string) int
}

TokenCounter is the minimal token counting interface. It is the common subset shared by types.Tokenizer, rag.Tokenizer, and agent/context.TokenCounter.

Any type that implements CountTokens(string) int satisfies this interface, including types.Tokenizer, types.EstimateTokenizer, rag.Tokenizer, and llm/tools.DefaultCostController (which now uses types.TokenCounter).

type TokenUsage

type TokenUsage struct {
	PromptTokens     int     `json:"prompt_tokens,omitempty"`
	CompletionTokens int     `json:"completion_tokens,omitempty"`
	TotalTokens      int     `json:"total_tokens,omitempty"`
	Cost             float64 `json:"cost,omitempty"`
}

TokenUsage represents token consumption statistics.

func (*TokenUsage) Add

func (u *TokenUsage) Add(other TokenUsage)

Add adds another TokenUsage to this one.

type Tokenizer

type Tokenizer interface {
	// CountTokens counts tokens in a text string.
	CountTokens(text string) int
	// CountMessageTokens counts tokens in a single message.
	CountMessageTokens(msg Message) int
	// CountMessagesTokens counts total tokens in a message slice.
	CountMessagesTokens(msgs []Message) int
	// EstimateToolTokens estimates tokens for tool schemas.
	EstimateToolTokens(tools []ToolSchema) int
}

Tokenizer defines the interface for token counting.

Note: Three Tokenizer interfaces exist in the project, each serving a different layer:

  • types.Tokenizer (this) — Framework-level, Message/ToolSchema-aware, no error returns
  • llm/tokenizer.Tokenizer — LLM-level, full encode/decode with errors, model-aware
  • rag.Tokenizer — RAG chunking, minimal (CountTokens + Encode), no errors

These cannot be unified without introducing circular dependencies (rag -> types.Message) or forcing incompatible method signatures (error vs no-error returns). Use rag.NewLLMTokenizerAdapter() to bridge llm/tokenizer.Tokenizer to rag.Tokenizer.

type ToolCall

type ToolCall struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
}

ToolCall represents a tool invocation request from the LLM.

type ToolResult

type ToolResult struct {
	ToolCallID string          `json:"tool_call_id"`
	Name       string          `json:"name"`
	Result     json.RawMessage `json:"result"`
	Error      string          `json:"error,omitempty"`
	Duration   time.Duration   `json:"duration"`
	FromCache  bool            `json:"from_cache,omitempty"`
}

ToolResult represents the result of a tool execution.

func (ToolResult) IsError

func (tr ToolResult) IsError() bool

IsError returns true if the tool execution failed.

func (ToolResult) ToJSON added in v1.2.0

func (tr ToolResult) ToJSON() string

ToJSON returns a JSON string representation of the ToolResult.

func (ToolResult) ToMessage

func (tr ToolResult) ToMessage() Message

ToMessage converts ToolResult to a Message.

type ToolSchema

type ToolSchema struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Parameters  json.RawMessage `json:"parameters"`
	Version     string          `json:"version,omitempty"`
}

ToolSchema defines a tool's interface for LLM function calling.

type ToolSelectionConfig

type ToolSelectionConfig struct {
	Enabled             bool    `json:"enabled"`
	MaxTools            int     `json:"max_tools,omitempty"`
	SimilarityThreshold float64 `json:"similarity_threshold,omitempty"`
	Strategy            string  `json:"strategy,omitempty"` // "semantic", "keyword", "hybrid"
}

ToolSelectionConfig configures dynamic tool selection.

func DefaultToolSelectionConfig

func DefaultToolSelectionConfig() *ToolSelectionConfig

DefaultToolSelectionConfig returns sensible defaults for tool selection.

type ToolSelectionExtension

type ToolSelectionExtension interface {
	// SelectTools selects relevant tools for a given query.
	SelectTools(ctx context.Context, query string, candidates []ToolSchema) ([]ToolSchema, error)
	// GetSelectionStrategy returns the current selection strategy.
	GetSelectionStrategy() string
}

ToolSelectionExtension provides dynamic tool selection based on context.

type ValidationError

type ValidationError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Field   string `json:"field,omitempty"`
}

ValidationError represents a single validation error.

type ValidationResult

type ValidationResult struct {
	Valid    bool              `json:"valid"`
	Errors   []ValidationError `json:"errors,omitempty"`
	Warnings []string          `json:"warnings,omitempty"`
	Filtered string            `json:"filtered,omitempty"`
}

ValidationResult represents the result of a validation check.

type VideoContent added in v1.2.0

type VideoContent struct {
	URL string   `json:"url"`
	FPS *float64 `json:"fps,omitempty"`
}

VideoContent represents video data for multimodal messages.

Jump to

Keyboard shortcuts

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