types

package
v1.4.6 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AgentID added in v1.4.6

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

AgentID extracts agent ID from context.

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 LLMProvider added in v1.4.6

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

LLMProvider extracts LLM provider hint from context.

func LLMRoutePolicy added in v1.4.6

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

LLMRoutePolicy extracts LLM route policy from context.

func ParentRunID added in v1.4.6

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

ParentRunID extracts parent run ID 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 SpanID added in v1.4.6

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

SpanID extracts span 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 WithAgentID added in v1.4.6

func WithAgentID(ctx context.Context, agentID string) context.Context

WithAgentID adds agent ID to context for scope isolation.

func WithLLMModel

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

WithLLMModel adds LLM model to context.

func WithLLMProvider added in v1.4.6

func WithLLMProvider(ctx context.Context, provider string) context.Context

WithLLMProvider adds LLM provider hint to context.

func WithLLMRoutePolicy added in v1.4.6

func WithLLMRoutePolicy(ctx context.Context, routePolicy string) context.Context

WithLLMRoutePolicy adds LLM route policy to context.

func WithParentRunID added in v1.4.6

func WithParentRunID(ctx context.Context, parentRunID string) context.Context

WithParentRunID adds parent run ID to context for sub-agent run hierarchy tracking.

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 WithSpanID added in v1.4.6

func WithSpanID(ctx context.Context, spanID string) context.Context

WithSpanID adds span ID to context for trace isolation. Sub-agents get independent span IDs while sharing the parent trace_id.

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"`

	// Runtime execution behavior configuration
	Runtime RuntimeConfig `json:"runtime,omitempty"`

	// 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 (runtime behavior). Note: This is distinct from config.AgentConfig which is for deployment configuration (YAML/env loading, flat structure). This type uses a modular nested structure (Core/LLM/Features/Extensions) for runtime agent behavior configuration. Deployment-to-runtime conversion is implemented in config.AgentConfig.ToRuntimeConfig().

func (*AgentConfig) IsGuardrailsEnabled

func (c *AgentConfig) IsGuardrailsEnabled() bool

IsGuardrailsEnabled checks if guardrails are enabled.

func (*AgentConfig) IsLSPEnabled added in v1.4.6

func (c *AgentConfig) IsLSPEnabled() bool

IsLSPEnabled checks if LSP is 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 AgentEventType added in v1.4.6

type AgentEventType string

AgentEventType defines unified agent event names.

const (
	AgentEventStateChange       AgentEventType = "state_change"
	AgentEventToolCall          AgentEventType = "tool_call"
	AgentEventFeedback          AgentEventType = "feedback"
	AgentEventApprovalRequested AgentEventType = "approval_requested"
	AgentEventApprovalResponded AgentEventType = "approval_responded"
	AgentEventSubagentCompleted AgentEventType = "subagent_completed"
	AgentEventRunStart          AgentEventType = "agent_run_start"
	AgentEventRunComplete       AgentEventType = "agent_run_complete"
	AgentEventRunError          AgentEventType = "agent_run_error"
)

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 AvatarDriveMode added in v1.4.6

type AvatarDriveMode string

AvatarDriveMode defines unified drive mode for avatar generation.

const (
	AvatarDriveModeText  AvatarDriveMode = "text"
	AvatarDriveModeAudio AvatarDriveMode = "audio"
	AvatarDriveModeVideo AvatarDriveMode = "video"
)

func (AvatarDriveMode) IsValid added in v1.4.6

func (m AvatarDriveMode) IsValid() bool

IsValid returns whether this avatar drive mode is supported.

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 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. types.Error is the internal canonical error type; API DTO conversion is centralized at api.ErrorInfoFromTypesError.

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 ExecutionStatus added in v1.4.6

type ExecutionStatus string

ExecutionStatus represents the unified execution status across agent and workflow layers. This replaces the cross-layer dependency on agent/persistence.TaskStatus.

const (
	ExecutionStatusPending   ExecutionStatus = "pending"
	ExecutionStatusRunning   ExecutionStatus = "running"
	ExecutionStatusCompleted ExecutionStatus = "completed"
	ExecutionStatusFailed    ExecutionStatus = "failed"
	ExecutionStatusCancelled ExecutionStatus = "cancelled"
	ExecutionStatusTimeout   ExecutionStatus = "timeout"
)

func (ExecutionStatus) IsTerminal added in v1.4.6

func (s ExecutionStatus) IsTerminal() bool

IsTerminal returns true if the status represents a terminal state.

type ExtensionsConfig

type ExtensionsConfig struct {
	Skills        *SkillsConfig        `json:"skills,omitempty"`
	MCP           *MCPConfig           `json:"mcp,omitempty"`
	LSP           *LSPConfig           `json:"lsp,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"`
	OnInputFailure     string   `json:"on_input_failure,omitempty"`
	OnOutputFailure    string   `json:"on_output_failure,omitempty"`
}

GuardrailsConfig configures input/output validation.

func DefaultGuardrailsConfig

func DefaultGuardrailsConfig() *GuardrailsConfig

DefaultGuardrailsConfig returns sensible defaults.

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 for runtime agent behavior (model parameters). Note: This is distinct from config.LLMConfig which contains infrastructure connection parameters (APIKey, BaseURL, Timeout, MaxRetries) for deployment configuration.

type LSPConfig added in v1.4.6

type LSPConfig struct {
	Enabled bool `json:"enabled"`
}

LSPConfig configures Language Server Protocol integration.

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 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 MemoryKind added in v1.4.6

type MemoryKind string

MemoryKind is the cross-layer memory category contract.

const (
	MemoryShortTerm  MemoryKind = "working"
	MemoryWorking    MemoryKind = "working"
	MemoryLongTerm   MemoryKind = "semantic"
	MemoryEpisodic   MemoryKind = "episodic"
	MemorySemantic   MemoryKind = "semantic"
	MemoryProcedural MemoryKind = "procedural"
)

type MemoryRecord

type MemoryRecord struct {
	ID        string         `json:"id"`
	AgentID   string         `json:"agent_id"`
	Kind      MemoryKind     `json:"kind"`
	Content   string         `json:"content"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	VectorID  string         `json:"vector_id,omitempty"`
	CreatedAt time.Time      `json:"created_at"`
	ExpiresAt *time.Time     `json:"expires_at,omitempty"`
}

MemoryRecord is the cross-layer memory payload contract.

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 NarrationProfile added in v1.4.6

type NarrationProfile struct {
	Voice    string  `json:"voice,omitempty"`
	Style    string  `json:"style,omitempty"`
	Emotion  string  `json:"emotion,omitempty"`
	Language string  `json:"language,omitempty"`
	Rate     float64 `json:"rate,omitempty"`
	Pitch    float64 `json:"pitch,omitempty"`
	Volume   float64 `json:"volume,omitempty"`
	PauseMS  int     `json:"pause_ms,omitempty"`
}

NarrationProfile defines a unified speech profile for TTS/narration/avatar driving.

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 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 RAGEvalMetrics added in v1.4.6

type RAGEvalMetrics struct {
	ContextRelevance float64 `json:"context_relevance"`
	Faithfulness     float64 `json:"faithfulness"`
	AnswerRelevancy  float64 `json:"answer_relevancy"`
	RecallAtK        float64 `json:"recall_at_k"`
	MRR              float64 `json:"mrr"`
}

RAGEvalMetrics defines the shared RAG evaluation metric contract.

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 RetrievalMetricsContract added in v1.4.6

type RetrievalMetricsContract struct {
	Trace              RetrievalTrace `json:"trace,omitempty"`
	RetrievalLatencyMS int64          `json:"retrieval_latency_ms"`
	RerankLatencyMS    int64          `json:"rerank_latency_ms"`
	TopK               int            `json:"topk"`
	HitCount           int            `json:"hit_count"`
	ContextTokens      int            `json:"context_tokens"`
}

RetrievalMetricsContract defines minimal retrieval observability fields.

type RetrievalRecord added in v1.4.6

type RetrievalRecord struct {
	DocID   string         `json:"doc_id"`
	Content string         `json:"content"`
	Source  string         `json:"source,omitempty"`
	Score   float64        `json:"score"`
	Trace   RetrievalTrace `json:"trace,omitempty"`
}

RetrievalRecord defines the minimal cross-layer retrieval result contract.

type RetrievalTrace added in v1.4.6

type RetrievalTrace struct {
	TraceID string `json:"trace_id,omitempty"`
	RunID   string `json:"run_id,omitempty"`
	SpanID  string `json:"span_id,omitempty"`
}

RetrievalTrace defines minimal cross-layer trace fields for retrieval flows.

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 RuntimeConfig added in v1.4.6

type RuntimeConfig struct {
	SystemPrompt       string   `json:"system_prompt,omitempty"`
	Tools              []string `json:"tools,omitempty"`
	MaxReActIterations int      `json:"max_react_iterations,omitempty"`
	ToolModel          string   `json:"tool_model,omitempty"`
}

RuntimeConfig contains runtime execution behavior options.

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 SkillCategory added in v1.4.6

type SkillCategory string

SkillCategory is the shared contract for skill classification.

const (
	SkillCategoryReasoning     SkillCategory = "reasoning"
	SkillCategoryCoding        SkillCategory = "coding"
	SkillCategoryResearch      SkillCategory = "research"
	SkillCategoryCommunication SkillCategory = "communication"
	SkillCategoryData          SkillCategory = "data"
	SkillCategoryAutomation    SkillCategory = "automation"
)

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

type VideoGenerationMode added in v1.4.6

type VideoGenerationMode string

VideoGenerationMode defines unified generation mode for video capabilities.

const (
	VideoModeTextToVideo  VideoGenerationMode = "text_to_video"
	VideoModeImageToVideo VideoGenerationMode = "image_to_video"
)

func (VideoGenerationMode) IsValid added in v1.4.6

func (m VideoGenerationMode) IsValid() bool

IsValid returns whether this video generation mode is supported.

type WorkflowNodeEventType added in v1.4.6

type WorkflowNodeEventType string

WorkflowNodeEventType defines node-level workflow observability events.

const (
	WorkflowNodeEventStart    WorkflowNodeEventType = "node_start"
	WorkflowNodeEventComplete WorkflowNodeEventType = "node_complete"
	WorkflowNodeEventError    WorkflowNodeEventType = "node_error"
)

Jump to

Keyboard shortcuts

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