Documentation
¶
Overview ¶
Copyright (C) 2025 Aleutian AI (jinterlante@aleutian.ai) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. See the LICENSE.txt file for the full license text.
NOTE: This work is subject to additional terms under AGPL v3 Section 7. See the NOTICE.txt file for details regarding AI system attribution.
Package datatypes provides data structures for the orchestrator service.
This file contains request and response types for direct chat endpoints (non-RAG LLM chat). For RAG chat types, see rag.go.
Package datatypes provides type definitions for the Aleutian orchestrator.
This file contains types for the unified inference API that communicates with Sapheneia's /orchestration/v1/predict endpoint.
Copyright (C) 2025 Aleutian AI (jinterlante@aleutian.ai) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. See the LICENSE.txt file for the full license text.
NOTE: This work is subject to additional terms under AGPL v3 Section 7. See the NOTICE.txt file for details regarding AI system attribution.
Package datatypes provides type definitions for the Aleutian orchestrator.
This file contains version 2 trading signal types that include full inference traceability via request/response ID linking. These types align with the backtest scenario YAML structure (strategies/*.yaml) and enable audit trails from forecast to trade.
Index ¶
- Constants
- Variables
- func EnsureWeaviateSchema(client *weaviate.Client)
- func FindOrCreateSessionUUID(ctx context.Context, client *weaviate.Client, sessionID string) (string, error)
- func FindOrCreateSessionWithTTL(ctx context.Context, client *weaviate.Client, sessionID string, ...) (string, error)
- func GetConversationSchema() *models.Class
- func GetDataspaceConfigSchema() *models.Class
- func GetDocumentSchema() *models.Class
- func GetRecencyDecayRate(preset string) float64
- func GetSessionSchema() *models.Class
- func GetVerificationLogSchema() *models.Class
- func ParseGraphQLResponse[T any](resp *models.GraphQLResponse) (*T, error)
- func ResetSessionTTL(ctx context.Context, client *weaviate.Client, weaviateUUID string, ...) error
- func WithBeacon(props map[string]interface{}, sessionUUID string)
- type AgentMessage
- type AgentStepRequest
- type AgentStepResponse
- type BacktestScenario
- type BeaconRef
- type ChatRAGRequest
- type ChatRAGResponse
- type ChatTurn
- type CodeSnippetProperties
- type ContextData
- type ContextSummary
- type Conversation
- type ConversationProperties
- type ConversationQueryResponse
- type ConversationResult
- type DataCoverageInfo
- type DataField
- type DataSource
- type DataspaceConfigProperties
- type DataspaceConfigQueryResponse
- type DataspaceConfigResult
- type DirectChatRequest
- type DirectChatResponse
- type DocumentProperties
- type DocumentQueryResponse
- type DocumentResult
- type EmbeddingRequest
- type EmbeddingResponse
- type EvaluationConfig
- type EvaluationResult
- type ForecastData
- type ForecastRecord
- type ForecastResult
- type Harbor
- type HistoryTurn
- type HorizonSpec
- type InferenceMetadata
- type InferenceRef
- type InferenceRequest
- type InferenceResponse
- type Message
- type MetricsResponse
- type ModelParams
- type ModelPullRequest
- type ModelPullResponse
- type OHLCData
- type Period
- type PortfolioState
- type PortfolioStateRecord
- type PriceInfo
- type ProgressEvent
- type ProgressEventType
- type QuantileForecast
- type RAGRequest
- type RAGResponse
- type RagEngineResponse
- type RetrievalChunk
- type RetrievalDetails
- type RetrievalRequest
- type RetrievalResponse
- type ScenarioMetadata
- type Session
- type SessionContext
- type SessionProperties
- type SessionQueryResponse
- type SessionResult
- type SkepticAuditDetails
- type SourceInfo
- type StreamEvent
- func (e *StreamEvent) WithContent(content string) *StreamEvent
- func (e *StreamEvent) WithError(err string) *StreamEvent
- func (e *StreamEvent) WithMessage(msg string) *StreamEvent
- func (e *StreamEvent) WithSessionId(sessionId string) *StreamEvent
- func (e *StreamEvent) WithSources(sources []SourceInfo) *StreamEvent
- type TemperatureOverrides
- type TickerInfo
- type TokenUsage
- type ToolCall
- type ToolFunction
- type TradingSignalRecord
- type TradingSignalRequest
- func (r *TradingSignalRequest) GetAvailableCash() float64
- func (r *TradingSignalRequest) GetCurrentPosition() float64
- func (r *TradingSignalRequest) GetCurrentPrice() float64
- func (r *TradingSignalRequest) GetForecastPrice() float64
- func (r *TradingSignalRequest) GetInitialCapital() float64
- func (r *TradingSignalRequest) GetStrategyParams() map[string]interface{}
- func (r *TradingSignalRequest) GetStrategyType() string
- func (r *TradingSignalRequest) GetTicker() string
- type TradingSignalRequestV2
- func (r *TradingSignalRequestV2) GetAvailableCash() float64
- func (r *TradingSignalRequestV2) GetCurrentPosition() float64
- func (r *TradingSignalRequestV2) GetCurrentPrice() float64
- func (r *TradingSignalRequestV2) GetForecastPrice() float64
- func (r *TradingSignalRequestV2) GetInitialCapital() float64
- func (r *TradingSignalRequestV2) GetStrategyParams() map[string]interface{}
- func (r *TradingSignalRequestV2) GetStrategyType() string
- func (r *TradingSignalRequestV2) GetTicker() string
- func (r *TradingSignalRequestV2) HasInferenceRef() bool
- func (r *TradingSignalRequestV2) ToV1() TradingSignalRequest
- func (r *TradingSignalRequestV2) Validate() error
- type TradingSignalRequester
- type TradingSignalResponse
- type VerifiedPipelineConfig
- type VerifiedStreamAnswer
- type VerifiedStreamError
- type WeaviateConversationMemoryObject
- type WeaviateObject
- type WeaviateSchemas
- type WeaviateSessionObject
Constants ¶
const ( // MaxMessageContentBytes is the maximum size of a single message content. // Per SEC-003: Unbounded message input mitigation. MaxMessageContentBytes = 32 * 1024 // 32KB // MaxMessagesPerRequest is the maximum number of messages in a request. // Per SEC-004: Unbounded message history mitigation. MaxMessagesPerRequest = 100 // MaxBudgetTokens is the maximum token budget for thinking mode. MaxBudgetTokens = 65536 )
Variables ¶
var RecencyDecayPreset = map[string]float64{
"none": 0.0,
"gentle": 0.01,
"moderate": 0.05,
"aggressive": 0.1,
}
RecencyDecayPreset defines decay rates for recency bias presets.
Presets ¶
- none: No decay (λ=0). Default, backward compatible.
- gentle: λ=0.01. 50% at ~69 days. General knowledge bases.
- moderate: λ=0.05. 50% at ~14 days. News, changelogs.
- aggressive: λ=0.1. 50% at ~7 days. Fast-changing data.
Functions ¶
func EnsureWeaviateSchema ¶
func FindOrCreateSessionUUID ¶
func FindOrCreateSessionUUID(ctx context.Context, client *weaviate.Client, sessionID string) (string, error)
FindOrCreateSessionUUID finds a session by its session_id and returns its Weaviate UUID If it doesn't exist, it creates one and returns the new UUID
func FindOrCreateSessionWithTTL ¶
func FindOrCreateSessionWithTTL(ctx context.Context, client *weaviate.Client, sessionID string, sessionCtx SessionContext) (string, error)
FindOrCreateSessionWithTTL finds or creates a session with optional TTL and context.
Description ¶
Like FindOrCreateSessionUUID, but also sets TTL on new sessions and resets TTL on existing sessions (for the "resets on each message" behavior). Additionally stores dataspace and pipeline for session resume.
Inputs ¶
- ctx: Context for cancellation and tracing.
- client: Weaviate client.
- sessionID: Session identifier (e.g., "sess_abc123").
- sessionCtx: Session context with dataspace, pipeline, and TTL.
Outputs ¶
- string: Weaviate UUID of the session.
- error: Non-nil if operation fails.
func GetConversationSchema ¶
func GetDataspaceConfigSchema ¶
GetDataspaceConfigSchema returns the schema for the DataspaceConfig class.
Description ¶
DataspaceConfig stores configuration for a logical data space, including default retention policies. This enables per-dataspace TTL settings.
Properties ¶
- data_space_name: Unique identifier for the data space (e.g., 'work', 'personal').
- retention_days: Default retention period in days for new documents. 0 = indefinite.
- created_at: Unix milliseconds when this config was created.
- modified_at: Unix milliseconds when this config was last modified.
Example ¶
config := GetDataspaceConfigSchema() client.Schema().ClassCreator().WithClass(config).Do(ctx)
func GetDocumentSchema ¶
func GetRecencyDecayRate ¶
GetRecencyDecayRate returns the decay rate for a given preset.
Description ¶
Looks up the decay rate (λ) for the given preset name. If the preset is not recognized, returns 0.0 (no decay) for backward compatibility.
Inputs ¶
- preset: One of "none", "gentle", "moderate", "aggressive"
Outputs ¶
- float64: The decay rate λ for exponential decay formula
func GetSessionSchema ¶
func ParseGraphQLResponse ¶
func ParseGraphQLResponse[T any](resp *models.GraphQLResponse) (*T, error)
ParseGraphQLResponse parses a Weaviate GraphQL response into the target type.
Description ¶
This generic function encapsulates the marshal/unmarshal pattern required to convert Weaviate's dynamic response (map[string]models.JSONObject) into a strongly-typed Go struct. The target type T must have json tags matching the expected response shape.
Type Parameters ¶
- T: The target struct type with json tags matching the response shape.
Inputs ¶
- resp: The GraphQL response from Weaviate client's Do() method.
Outputs ¶
- *T: Pointer to the parsed struct.
- error: Non-nil if response is nil or parsing fails.
Example ¶
type SessionResponse struct {
Get struct {
Session []struct {
SessionID string `json:"session_id"`
} `json:"Session"`
} `json:"Get"`
}
resp, err := client.GraphQL().Get().WithClassName("Session").Do(ctx)
if err != nil { ... }
parsed, err := ParseGraphQLResponse[SessionResponse](resp)
if err != nil { ... }
for _, s := range parsed.Get.Session {
fmt.Println(s.SessionID)
}
Limitations ¶
- Requires the target type to exactly match the expected response structure.
- Type mismatches will result in zero values, not errors.
Assumptions ¶
- The response Data field is JSON-marshalable.
- The target type T has correct json tags.
func ResetSessionTTL ¶
func ResetSessionTTL(ctx context.Context, client *weaviate.Client, weaviateUUID string, ttlExpiresAt, ttlDurationMs int64) error
ResetSessionTTL updates the TTL expiration time on an existing session.
Description ¶
Called on each message to reset the TTL countdown. The session will expire ttlDurationMs milliseconds from now.
Inputs ¶
- ctx: Context for cancellation.
- client: Weaviate client.
- weaviateUUID: The Weaviate object UUID of the session.
- ttlExpiresAt: New expiration timestamp (Unix milliseconds).
- ttlDurationMs: Original TTL duration in milliseconds.
Outputs ¶
- error: Non-nil if update fails.
func WithBeacon ¶
Types ¶
type AgentMessage ¶
type AgentMessage struct {
Role string `json:"role"`
Content string `json:"content"`
ToolCallId string `json:"tool_call_id,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
}
AgentMessage represents a single turn in the conversation history. This mirrors the standard OpenAI/Anthropic message format.
type AgentStepRequest ¶
type AgentStepRequest struct {
Query string `json:"query"`
History []AgentMessage `json:"history"`
}
AgentStepRequest is the payload the CLI sends to the Orchestrator/Python container. It includes the full history so that the container remains stateless.
type AgentStepResponse ¶
type AgentStepResponse struct {
Type string `json:"type"` // "answer" or "tool_call"
Content string `json:"content,omitempty"` // The final answer (if Type="answer")
// Fields populated if Type="tool_call"
ToolName string `json:"tool,omitempty"`
ToolArgs map[string]interface{} `json:"args,omitempty"`
ToolID string `json:"tool_id,omitempty"` // Must be sent back in the next request
}
AgentStepResponse is the decision the Agent makes. It tells the CLI to either "stop and print" (Type="answer") or "do work" (Type="tool_call").
type BacktestScenario ¶
type BacktestScenario struct {
Metadata ScenarioMetadata `yaml:"metadata" json:"metadata"`
Evaluation struct {
Ticker string `yaml:"ticker" json:"ticker"`
FetchStartDate string `yaml:"fetch_start_date" json:"fetch_start_date"`
StartDate string `yaml:"start_date" json:"start_date"` //YYYYMMDD
EndDate string `yaml:"end_date" json:"end_date"` //YYYYMMDD
} `yaml:"evaluation" json:"evaluation"`
Forecast struct {
Model string `yaml:"model" json:"model"`
ContextSize int `yaml:"context_size" json:"context_size"`
HorizonSize int `yaml:"horizon_size" json:"horizon_size"`
ComputeMode string `yaml:"compute_mode" json:"compute_mode"` // "legacy" (default) or "unified"
Quantiles []float64 `yaml:"quantiles" json:"quantiles"` // Optional quantiles (e.g., [0.1, 0.5, 0.9])
} `yaml:"forecast" json:"forecast"`
Trading struct {
InitialCapital float64 `yaml:"initial_capital" json:"initial_capital"`
InitialPosition float64 `yaml:"initial_position" json:"initial_position"`
InitialCash float64 `yaml:"initial_cash" json:"initial_cash"`
StrategyType string `yaml:"strategy_type" json:"strategy_type"`
Params map[string]interface{} `yaml:"params" json:"params"`
} `yaml:"trading" json:"trading"`
}
BacktestScenario represents the full configuration file
type BeaconRef ¶
type BeaconRef struct {
Beacon string `json:"beacon"`
}
WithBeacon adds an inSession beacon reference to the properties map.
Description ¶
Creates the cross-reference format Weaviate requires for linking objects. Note: The "localhost" in the beacon URI is part of Weaviate's standard cross-reference format and is NOT an actual host - it's a protocol identifier. See: https://weaviate.io/developers/weaviate/manage-data/cross-references
Inputs ¶
- props: The property map to add the beacon to.
- sessionUUID: The Weaviate UUID of the target Session object.
Example ¶
props := docProps.ToMap() WithBeacon(props, sessionUUID)
BeaconRef represents a Weaviate cross-reference beacon.
type ChatRAGRequest ¶
type ChatRAGRequest struct {
Id string `json:"id,omitempty"` // Request ID (server-generated for tracing)
CreatedAt int64 `json:"created_at,omitempty"` // Unix timestamp when request was created
Message string `json:"message"` // Current user message
SessionId string `json:"session_id,omitempty"` // Optional: resume session
Pipeline string `json:"pipeline,omitempty"` // RAG pipeline (default: reranking)
Bearing string `json:"bearing,omitempty"` // Topic filter for retrieval
Stream bool `json:"stream,omitempty"` // Enable SSE streaming
History []ChatTurn `json:"history,omitempty"` // Previous turns (if not using session)
ContentHash string `json:"content_hash,omitempty"` // SHA-256 hash of message for integrity
StrictMode bool `json:"strict_mode,omitempty"` // Strict RAG: only answer from docs
TemperatureOverrides *TemperatureOverrides `json:"temperature_overrides,omitempty"` // Verified pipeline: per-role temps
Strictness string `json:"strictness,omitempty"` // Verified pipeline: "strict" or "balanced"
DataSpace string `json:"data_space,omitempty"` // Data space to filter queries by (e.g., "work", "personal")
VersionTag string `json:"version_tag,omitempty"` // Specific version to query (e.g., "v1"); empty = current
SessionTTL string `json:"session_ttl,omitempty"` // Session TTL (e.g., "24h", "7d"). Resets on each message.
RecencyBias string `json:"recency_bias,omitempty"` // Recency bias preset: none, gentle, moderate, aggressive
}
ChatRAGRequest is used for conversational RAG with multi-turn support.
Hash Chain ¶
ContentHash contains SHA-256 hash of the message content for integrity verification. The server computes this on receipt and includes it in audit logs.
Verified Pipeline Configuration ¶
When Pipeline is "verified", the TemperatureOverrides field can be used to customize the temperature for each debate role (optimist, skeptic, refiner). The Strictness field controls how strictly the optimist must cite sources.
func (*ChatRAGRequest) EnsureDefaults ¶
func (r *ChatRAGRequest) EnsureDefaults()
EnsureDefaults populates default values for optional fields that were not provided by the client. This method should be called after binding the JSON request but before validation.
Fields populated:
- Id: Generated UUID if empty. Used for request tracing and logging.
- CreatedAt: Current Unix timestamp if zero. Records when request was received.
- Pipeline: Defaults to "reranking" if empty. This is the recommended pipeline for most use cases as it provides good accuracy with reasonable latency.
This method modifies the receiver in place and is idempotent - calling it multiple times will not change already-set values.
Example:
req := &ChatRAGRequest{Message: "Hello"}
req.EnsureDefaults()
// req.Id is now set to a UUID
// req.CreatedAt is now set to current timestamp
// req.Pipeline is now "reranking"
func (*ChatRAGRequest) EnsureSessionId ¶
func (r *ChatRAGRequest) EnsureSessionId() string
EnsureSessionId generates a new session ID if one was not provided in the request, and returns the session ID (whether newly generated or existing).
Session IDs are UUIDs that identify a conversation across multiple requests. They are used to:
- Store and retrieve conversation history from Weaviate
- Group related turns together for context management
- Enable session resume functionality in the CLI
This method modifies the receiver's SessionId field in place if it was empty.
Returns the session ID string, which is guaranteed to be non-empty after this method returns.
Example:
req := &ChatRAGRequest{Message: "Hello"}
sessionId := req.EnsureSessionId()
// sessionId is now a valid UUID
// req.SessionId is also set to the same value
func (*ChatRAGRequest) Validate ¶
func (r *ChatRAGRequest) Validate() error
Validate performs validation on a ChatRAGRequest to ensure all required fields are present and all provided values are within acceptable bounds.
Validation rules:
- Message: Required, cannot be empty. This is the user's input text.
- Pipeline: Optional, but if provided must be one of the supported pipelines: "standard", "reranking", "raptor", "graph", "rig", "semantic".
- SessionId: Optional, will be generated if not provided (see EnsureSessionId).
- Bearing: Optional, used for topic filtering during retrieval.
- Stream: Optional, defaults to false.
- History: Optional, used to provide conversation context without server-side sessions.
Returns nil if validation passes, or an error describing the first validation failure encountered. Callers should check the error before proceeding with request processing.
Example:
req := &ChatRAGRequest{Message: "What is authentication?"}
if err := req.Validate(); err != nil {
return fmt.Errorf("invalid request: %w", err)
}
type ChatRAGResponse ¶
type ChatRAGResponse struct {
Id string `json:"id"` // Response ID (for logging/tracing)
CreatedAt int64 `json:"created_at"` // Unix timestamp when response was generated
Answer string `json:"answer"` // LLM response text
SessionId string `json:"session_id"` // Session this belongs to
Sources []SourceInfo `json:"sources,omitempty"` // Retrieved sources
TurnCount int `json:"turn_count"` // Number of turns in session
ContentHash string `json:"content_hash,omitempty"` // SHA-256 hash of answer
ChainHash string `json:"chain_hash,omitempty"` // Final hash from streaming chain
}
ChatRAGResponse is the non-streaming response.
Hash Chain ¶
ContentHash is SHA-256 hash of the answer content. ChainHash is the final hash if this response was generated via streaming (accumulated from all StreamEvent hashes).
func NewChatRAGResponse ¶
func NewChatRAGResponse(answer, sessionId string, sources []SourceInfo, turnCount int) *ChatRAGResponse
NewChatRAGResponse creates a new ChatRAGResponse with auto-generated ID and timestamp. This constructor ensures that all responses have consistent identification for logging, tracing, and potential database storage.
Parameters:
- answer: The LLM-generated response text to the user's query. This is the main content that will be displayed to the user.
- sessionId: The session ID this response belongs to. Should match the session ID from the corresponding ChatRAGRequest.
- sources: Slice of SourceInfo structs representing the retrieved documents that were used to generate the answer. May be nil or empty if no sources were used (e.g., for greetings or when RAG retrieval found nothing).
- turnCount: The total number of conversation turns including this one. Used by the CLI to display conversation length and manage context.
Returns a pointer to a new ChatRAGResponse with Id and CreatedAt automatically populated.
Example:
sources := []SourceInfo{{Source: "auth.go", Score: 0.95}}
resp := NewChatRAGResponse(
"Authentication uses JWT tokens...",
"sess_abc123",
sources,
5,
)
type ChatTurn ¶
type ChatTurn struct {
Id string `json:"id"` // Turn ID (uuid)
CreatedAt int64 `json:"created_at"` // Unix timestamp when turn was created
Role string `json:"role"` // "user" or "assistant"
Content string `json:"content"` // Message content
Sources []SourceInfo `json:"sources,omitempty"` // Sources used (assistant only)
}
ChatTurn represents a single turn in a conversation
type CodeSnippetProperties ¶
type ContextData ¶
type ContextData struct {
Values []float64 `json:"values"`
Period Period `json:"period"`
Source DataSource `json:"source"`
StartDate string `json:"start_date"`
EndDate string `json:"end_date"`
Field DataField `json:"field"`
}
ContextData holds historical time-series data with full provenance.
Description:
ContextData encapsulates the input context window for a forecast, including the actual values and metadata about their origin.
Fields:
- Values: The time-series values (most recent last)
- Period: Time interval between points
- Source: Where the data came from
- StartDate: First date in the series (YYYY-MM-DD)
- EndDate: Last date in the series (YYYY-MM-DD)
- Field: Which OHLCV field the values represent
JSON Tags:
All fields are serialized with snake_case names.
Example:
context := ContextData{
Values: []float64{100.0, 101.5, 99.8, 102.0},
Period: Period1d,
Source: SourceInfluxDB,
StartDate: "2025-01-01",
EndDate: "2025-01-04",
Field: FieldClose,
}
Limitations:
- Values must be in chronological order
- Does not support missing values (NaN handling)
- Date format must be YYYY-MM-DD
Assumptions:
- len(Values) matches the number of periods between dates
- All values are valid (no NaN or Inf)
type ContextSummary ¶
type ContextSummary struct {
Length int `json:"length"`
Period Period `json:"period"`
Source DataSource `json:"source"`
StartDate string `json:"start_date"`
EndDate string `json:"end_date"`
Field DataField `json:"field"`
}
ContextSummary echoes back what context was used.
Description:
ContextSummary confirms the context that was actually used for the forecast, which may differ from the request if truncation occurred.
Fields:
- Length: Number of context points used
- Period: Time interval of context
- Source: Data source
- StartDate: First context date
- EndDate: Last context date
- Field: OHLCV field used
Example:
summary := ContextSummary{
Length: 252,
Period: Period1d,
Source: SourceInfluxDB,
StartDate: "2025-01-01",
EndDate: "2025-12-31",
Field: FieldClose,
}
Limitations:
- Does not include the actual values (to save bandwidth)
Assumptions:
- Matches the request context unless truncation occurred
type Conversation ¶
type ConversationProperties ¶
type ConversationProperties struct {
SessionId string `json:"session_id"`
Question string `json:"question"`
Answer string `json:"answer"`
Timestamp int64 `json:"timestamp"`
}
func (*ConversationProperties) ToMap ¶
func (p *ConversationProperties) ToMap() map[string]interface{}
ToMap converts ConversationProperties to map[string]interface{} for Weaviate.
Description ¶
Converts the typed ConversationProperties struct to the map format required by Weaviate's WithProperties() method.
Outputs ¶
- map[string]interface{}: Property map ready for Weaviate client.
Example ¶
props := ConversationProperties{SessionId: "sess_123", Question: "...", Answer: "..."}
client.Data().Creator().WithProperties(props.ToMap()).Do(ctx)
type ConversationQueryResponse ¶
type ConversationQueryResponse struct {
Get struct {
Conversation []ConversationResult `json:"Conversation"`
} `json:"Get"`
}
ConversationQueryResponse represents the response from querying the Conversation class.
Fields ¶
- Get.Conversation: Array of conversation turns.
type ConversationResult ¶
type ConversationResult struct {
SessionID string `json:"session_id"`
Question string `json:"question"`
Answer string `json:"answer"`
Timestamp int64 `json:"timestamp"`
TurnNumber *int `json:"turn_number"`
}
ConversationResult represents a single conversation turn from a query.
type DataCoverageInfo ¶
type DataCoverageInfo struct {
Ticker string
OldestDate time.Time
NewestDate time.Time
PointCount int
HasData bool
}
DataCoverageInfo holds information about available data for a ticker in InfluxDB
type DataField ¶
type DataField string
DataField indicates which OHLCV field the values represent.
Description:
DataField specifies which component of price data is being used. Time-series forecasting typically uses adjusted close prices.
Valid Values:
- "open": Opening price
- "high": Highest price in period
- "low": Lowest price in period
- "close": Closing price
- "adj_close": Split/dividend-adjusted close
- "volume": Trading volume
Example:
context := ContextData{
Field: datatypes.FieldAdjClose,
}
Limitations:
- Does not support derived fields (e.g., VWAP, returns)
- Cannot represent multi-field inputs
Assumptions:
- Forecasting models expect single-field input
- adj_close is preferred for equity forecasting
type DataSource ¶
type DataSource string
DataSource indicates the origin of time-series data.
Description:
DataSource tracks where historical data was obtained from, enabling data quality assessment and reproducibility.
Valid Values:
- "yahoo": Yahoo Finance API
- "influxdb": Local InfluxDB storage
- "alpaca": Alpaca Markets API
- "binance": Binance exchange API
- "polygon": Polygon.io API
- "coinbase": Coinbase exchange API
- "kraken": Kraken exchange API
- "synthetic": Generated/simulated data
- "unknown": Source not specified
Example:
context := ContextData{
Source: datatypes.SourceInfluxDB,
}
Limitations:
- Cannot express hybrid sources (data from multiple providers)
- New providers require code changes to add constants
Assumptions:
- Each data point comes from a single source
- Source is set by the data fetching layer, not the user
const ( SourceYahoo DataSource = "yahoo" SourceInfluxDB DataSource = "influxdb" SourceAlpaca DataSource = "alpaca" SourceBinance DataSource = "binance" SourcePolygon DataSource = "polygon" // Polygon.io API SourceCoinbase DataSource = "coinbase" // Coinbase exchange API SourceKraken DataSource = "kraken" // Kraken exchange API SourceSynthetic DataSource = "synthetic" SourceUnknown DataSource = "unknown" )
type DataspaceConfigProperties ¶
type DataspaceConfigProperties struct {
DataSpaceName string `json:"data_space_name"`
RetentionDays int `json:"retention_days"`
CreatedAt int64 `json:"created_at"`
ModifiedAt int64 `json:"modified_at"`
}
DataspaceConfigProperties represents the properties for creating/updating a DataspaceConfig object.
Description ¶
Used when creating or updating a dataspace configuration. The RetentionDays field sets the default TTL for documents ingested into this dataspace when no explicit --ttl flag is provided.
Fields ¶
- DataSpaceName: Unique identifier for the data space. Must be non-empty.
- RetentionDays: Default retention period in days. 0 = indefinite (no default TTL).
- CreatedAt: Unix milliseconds when the config was created.
- ModifiedAt: Unix milliseconds when the config was last modified.
Example ¶
props := DataspaceConfigProperties{
DataSpaceName: "work",
RetentionDays: 90,
CreatedAt: time.Now().UnixMilli(),
ModifiedAt: time.Now().UnixMilli(),
}
client.Data().Creator().WithClassName("DataspaceConfig").
WithProperties(props.ToMap()).Do(ctx)
func (*DataspaceConfigProperties) ToMap ¶
func (p *DataspaceConfigProperties) ToMap() map[string]interface{}
ToMap converts DataspaceConfigProperties to map[string]interface{} for Weaviate.
Description ¶
Converts the typed DataspaceConfigProperties struct to the map format required by Weaviate's WithProperties() method.
Outputs ¶
- map[string]interface{}: Property map ready for Weaviate client.
type DataspaceConfigQueryResponse ¶
type DataspaceConfigQueryResponse struct {
Get struct {
DataspaceConfig []DataspaceConfigResult `json:"DataspaceConfig"`
} `json:"Get"`
}
DataspaceConfigQueryResponse represents the response from querying the DataspaceConfig class.
Fields ¶
- Get.DataspaceConfig: Array of dataspace configuration objects.
type DataspaceConfigResult ¶
type DataspaceConfigResult struct {
DataSpaceName string `json:"data_space_name"`
RetentionDays int `json:"retention_days"`
CreatedAt int64 `json:"created_at"`
ModifiedAt int64 `json:"modified_at"`
Additional struct {
ID string `json:"id"`
} `json:"_additional"`
}
DataspaceConfigResult represents a single dataspace config from a query.
Description ¶
Contains the configuration for a logical data space, including default retention policies that apply to new documents ingested into the space.
Fields ¶
- DataSpaceName: Unique identifier for the data space.
- RetentionDays: Default retention period in days. 0 = indefinite.
- CreatedAt: Unix milliseconds when the config was created.
- ModifiedAt: Unix milliseconds when the config was last modified.
type DirectChatRequest ¶
type DirectChatRequest struct {
RequestID string `json:"request_id" validate:"required,uuid4"`
Timestamp int64 `json:"timestamp" validate:"required,gt=0"`
Messages []Message `json:"messages" validate:"required,min=1,max=100,dive"`
EnableThinking bool `json:"enable_thinking"`
BudgetTokens int `json:"budget_tokens" validate:"gte=0,lte=65536"`
Tools []interface{} `json:"tools,omitempty"`
ContentHash string `json:"content_hash,omitempty"`
}
DirectChatRequest represents a direct LLM chat request body.
Description ¶
DirectChatRequest contains the messages and optional parameters for direct LLM chat (without RAG retrieval). This is used for the POST /v1/chat/direct endpoint. Every request includes a unique ID and timestamp for audit trails and database storage.
Fields ¶
- RequestID: Required. Unique identifier for this request (UUID v4). Used for tracing, audit logging, and database correlation.
- Timestamp: Required. Unix timestamp in milliseconds (UTC) when request was created. Used for audit trails, ordering, and retention policy enforcement.
- Messages: Required. Conversation history with 1-100 messages. Each message must have a Role ("user", "assistant", "system") and Content. Content is limited to 32KB per message (SEC-003 compliance).
- EnableThinking: Optional. Enable Claude extended thinking mode. When true, Claude will show its reasoning process.
- BudgetTokens: Optional. Token budget for thinking mode (0-65536). Only used when EnableThinking is true. Default: 2048 if not specified.
- Tools: Optional. Tool definitions for function calling. Allows the LLM to call defined functions.
Validation ¶
Uses go-playground/validator:
- RequestID: required, must be valid UUID v4
- Timestamp: required, must be > 0
- Messages: required, 1-100 elements, each element validated
- Messages[].Content: max 32768 bytes (32KB) per SEC-003
- BudgetTokens: must be 0-65536
Examples ¶
// Simple chat
req := DirectChatRequest{
RequestID: "550e8400-e29b-41d4-a716-446655440000",
Timestamp: time.Now().UnixMilli(),
Messages: []Message{
{Role: "user", Content: "Hello"},
},
}
Limitations ¶
- No streaming support in this request type (use stream endpoint)
- Tools feature requires compatible LLM backend
- Message content limited to 32KB (larger payloads rejected)
- Maximum 100 messages per request (history truncation may be needed)
Assumptions ¶
- At least one message is provided
- Messages are in chronological order
- RequestID is generated client-side (UUID v4)
- Timestamp is Unix UTC timestamp in milliseconds
Hash Chain ¶
ContentHash contains SHA-256 hash of the messages content for integrity verification. The server computes this on receipt and includes it in audit logs.
Security References ¶
- SEC-003: Message size limits (security_architecture_review.md)
- SEC-005: Error message sanitization (security_architecture_review.md)
func (*DirectChatRequest) EnsureDefaults ¶
func (r *DirectChatRequest) EnsureDefaults()
EnsureDefaults populates default values for optional fields.
Description ¶
Generates RequestID and Timestamp if not provided by the client. This ensures all requests have proper identifiers for tracing and auditing.
Examples ¶
req := &DirectChatRequest{Messages: messages}
req.EnsureDefaults()
// req.RequestID is now a UUID
// req.Timestamp is now a Unix timestamp
func (*DirectChatRequest) Validate ¶
func (r *DirectChatRequest) Validate() error
Validate validates the DirectChatRequest fields.
Description ¶
Performs validation using go-playground/validator tags and custom validators. This method should be called after binding the JSON request.
Outputs ¶
- error: Non-nil if validation failed, with details about which field
Examples ¶
if err := req.Validate(); err != nil {
return fmt.Errorf("invalid request: %w", err)
}
type DirectChatResponse ¶
type DirectChatResponse struct {
ResponseID string `json:"response_id"`
RequestID string `json:"request_id"`
Timestamp int64 `json:"timestamp"`
Answer string `json:"answer"`
ThinkingContent string `json:"thinking,omitempty"`
Usage *TokenUsage `json:"usage,omitempty"`
ProcessingTimeMs int64 `json:"processing_time_ms,omitempty"`
ContentHash string `json:"content_hash,omitempty"`
ChainHash string `json:"chain_hash,omitempty"`
}
DirectChatResponse represents the response from a direct chat request.
Description ¶
Contains the LLM's generated response. For simple responses, only the Answer field is populated. Extended thinking responses may include additional metadata. Every response includes a unique ID and timestamp for audit trails and database storage.
Fields ¶
- ResponseID: Unique identifier for this response (UUID v4). Generated server-side. Used for audit logging and database correlation.
- RequestID: Echo of the request ID for correlation. Enables request-response matching in logs and databases.
- Timestamp: Unix timestamp in milliseconds (UTC) when response was generated. Used for audit trails, latency calculation, and retention policies.
- Answer: The LLM's generated response text.
- ThinkingContent: Optional. The reasoning process if EnableThinking was true.
- Usage: Optional. Token usage statistics.
- ProcessingTimeMs: Time taken to process the request in milliseconds.
Examples ¶
Response JSON:
{
"response_id": "660f9500-f39c-52e5-b827-557766551111",
"request_id": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": 1735817400000,
"answer": "Hello! How can I help you today?",
"processing_time_ms": 1250
}
Limitations ¶
- ThinkingContent only populated for Claude with extended thinking
Hash Chain ¶
ContentHash is SHA-256 hash of the answer content for integrity verification. ChainHash is the final hash if this response was generated via streaming (accumulated from all StreamEvent hashes).
Database Schema Alignment ¶
- ResponseID: Primary key for responses table
- RequestID: Foreign key to requests table
- Timestamp: Indexed for time-range queries and retention
func NewDirectChatResponse ¶
func NewDirectChatResponse(requestID, answer string) *DirectChatResponse
NewDirectChatResponse creates a new DirectChatResponse with auto-generated ID and timestamp.
Description ¶
This constructor ensures that all responses have consistent identification for logging, tracing, and potential database storage.
Inputs ¶
- requestID: The request ID to echo back for correlation
- answer: The LLM-generated response text
Outputs ¶
- *DirectChatResponse: A new response with ResponseID and Timestamp set
Examples ¶
resp := NewDirectChatResponse("req-uuid", "Hello! How can I help?")
type DocumentProperties ¶
type DocumentProperties struct {
Content string `json:"content"`
Source string `json:"source"`
ParentSource string `json:"parent_source"`
DataSpace string `json:"data_space"`
VersionTag string `json:"version_tag"`
VersionNumber int `json:"version_number"`
IsCurrent bool `json:"is_current"`
TurnNumber int `json:"turn_number"`
IngestedAt int64 `json:"ingested_at"`
TTLExpiresAt int64 `json:"ttl_expires_at"`
}
DocumentProperties represents the properties for creating a Document object.
func (*DocumentProperties) ToMap ¶
func (p *DocumentProperties) ToMap() map[string]interface{}
ToMap converts DocumentProperties to map[string]interface{} for Weaviate.
type DocumentQueryResponse ¶
type DocumentQueryResponse struct {
Get struct {
Document []DocumentResult `json:"Document"`
} `json:"Get"`
}
DocumentQueryResponse represents the response from querying the Document class.
Fields ¶
- Get.Document: Array of document objects.
type DocumentResult ¶
type DocumentResult struct {
Content string `json:"content"`
Source string `json:"source"`
ParentSource string `json:"parent_source"`
DataSpace string `json:"data_space"`
VersionTag string `json:"version_tag"`
VersionNumber *int `json:"version_number"`
IsCurrent *bool `json:"is_current"`
TurnNumber *int `json:"turn_number"`
IngestedAt int64 `json:"ingested_at"`
TTLExpiresAt int64 `json:"ttl_expires_at"`
Additional struct {
ID string `json:"id"`
Distance *float32 `json:"distance"`
Certainty *float32 `json:"certainty"`
} `json:"_additional"`
}
DocumentResult represents a single document from a query.
type EmbeddingRequest ¶
type EmbeddingRequest struct {
Text string `json:"text"`
}
type EmbeddingResponse ¶
type EmbeddingResponse struct {
Id string `json:"id"`
Timestamp int `json:"timestamp"`
Text string `json:"text"`
Vector []float32 `json:"vector"`
Dim int `json:"dim"`
}
func (*EmbeddingResponse) Get ¶
func (e *EmbeddingResponse) Get(text string) error
func (*EmbeddingResponse) GetWithContext ¶
func (e *EmbeddingResponse) GetWithContext(ctx context.Context, text string) error
GetWithContext fetches embeddings with context support for cancellation and timeout.
Description ¶
This is a context-aware version of Get() that respects cancellation signals. Use this when the embedding call is part of an HTTP request handler or other cancelable operation.
Inputs ¶
- ctx: Context for cancellation and timeout.
- text: The text to embed.
Outputs ¶
- error: Non-nil if context is canceled, timed out, or embedding fails.
Example ¶
var emb EmbeddingResponse
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
if err := emb.GetWithContext(ctx, "What is AI?"); err != nil { ... }
type EvaluationConfig ¶
type EvaluationConfig struct {
Tickers []TickerInfo
Models []string
EvaluationDate string // "20250117"
RunID string
// Strategy configuration
StrategyType string
StrategyParams map[string]interface{}
// Forecast configuration
ContextSize int
HorizonSize int
// Portfolio configuration
InitialCapital float64
InitialPosition float64
InitialCash float64
}
EvaluationConfig configures the evaluation run
type EvaluationResult ¶
type EvaluationResult struct {
Ticker string
Model string
EvaluationDate string
RunID string
ForecastHorizon int
StrategyType string
ForecastPrice float64
CurrentPrice float64
Action string
Size float64
Value float64
Reason string
AvailableCash float64
PositionAfter float64
Stopped bool
ThresholdValue float64
ExecutionSize float64
Timestamp time.Time
// Inference metadata (populated only in unified compute mode)
RequestID string // Request tracing ID (empty in legacy mode)
ResponseID string // Response tracing ID (empty in legacy mode)
InferenceTimeMs int // Model inference time in milliseconds (0 in legacy mode)
Device string // Compute device: "cpu", "cuda:0", "mps" (empty in legacy mode)
ModelFamily string // Model family: "chronos", "timesfm", etc. (empty in legacy mode)
}
EvaluationResult is the final data point stored in InfluxDB.
Description:
EvaluationResult contains all information about a single evaluation point, including forecast data, trading signal results, and inference metadata. This struct is persisted to InfluxDB for analysis and reporting.
Fields:
- Core fields: Ticker, Model, EvaluationDate, RunID, ForecastHorizon, StrategyType
- Forecast fields: ForecastPrice, CurrentPrice
- Trading fields: Action, Size, Value, Reason, AvailableCash, PositionAfter, Stopped
- Strategy params: ThresholdValue, ExecutionSize
- Metadata fields: RequestID, ResponseID, InferenceTimeMs, Device, ModelFamily
Limitations:
- Metadata fields are only populated when using unified compute mode
- Legacy mode leaves metadata fields empty/zero
Assumptions:
- Timestamp is set by the caller at evaluation time
- RequestID and ResponseID are UUIDs when populated
type ForecastData ¶
type ForecastData struct {
Values []float64 `json:"values"`
Period Period `json:"period"`
StartDate string `json:"start_date"`
EndDate string `json:"end_date"`
}
ForecastData holds the forecast output.
Description:
ForecastData contains the predicted values and their temporal metadata.
Fields:
- Values: Predicted values (chronological order)
- Period: Time interval between predictions
- StartDate: First forecast date (YYYY-MM-DD)
- EndDate: Last forecast date (YYYY-MM-DD)
Example:
forecast := ForecastData{
Values: []float64{101.5, 102.0, 101.8},
Period: Period1d,
StartDate: "2026-01-01",
EndDate: "2026-01-03",
}
Limitations:
- Values are point estimates (median of distribution)
- Does not include confidence intervals (see Quantiles)
Assumptions:
- len(Values) == horizon.Length from request
type ForecastRecord ¶ added in v1.0.0
type ForecastRecord struct {
Ticker string
Model string
ModelFamily string
ForecastPrice float64
CurrentPrice float64
Horizon int
InferenceTimeMs int
ForecastDate string // ISO date string (YYYYMMDD)
ConfidenceLower float64
ConfidenceUpper float64
Timestamp time.Time // Evaluation date (used as InfluxDB point timestamp)
}
ForecastRecord represents a forecast to persist in the "forecasts" InfluxDB measurement. Stores the full forecast context for auditability and multi-horizon analysis.
type ForecastResult ¶
type ForecastResult struct {
Name string `json:"name"`
Forecast []float64 `json:"forecast"`
Message string `json:"message"`
}
ForecastResult matches the JSON response from /v1/timeseries/forecast
type Harbor ¶
type Harbor struct {
Id string `json:"id"` // Harbor ID (uuid)
CreatedAt int64 `json:"created_at"` // Unix timestamp when harbor was created
Name string `json:"name"` // User-defined name
TurnIndex int `json:"turn_index"` // Index of the turn this bookmark points to
}
Harbor represents a saved conversation bookmark
type HistoryTurn ¶
type HistoryTurn struct {
Id string `json:"id,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
Question string `json:"question"`
Answer string `json:"answer"`
Hash string `json:"hash,omitempty"`
}
HistoryTurn represents a single question-answer pair in conversation history.
Description ¶
HistoryTurn captures a complete exchange between user and assistant. Used for loading previous conversation context when resuming sessions. Each turn has a unique ID and timestamp for database storage.
Fields ¶
- Id: Unique identifier for this turn (UUID v4).
- CreatedAt: Unix timestamp in milliseconds when turn was created.
- Question: The user's input message.
- Answer: The assistant's response.
- Hash: SHA-256 hash of Question+Answer. Used for tamper detection. Formula: SHA256(Question || Answer || CreatedAt || PrevHash)
func NewHistoryTurn ¶
func NewHistoryTurn(question, answer string) *HistoryTurn
NewHistoryTurn creates a new HistoryTurn with auto-generated ID and timestamp.
Description ¶
Creates a HistoryTurn capturing a question-answer exchange. The ID and timestamp are automatically populated for database storage.
Inputs ¶
- question: The user's input message.
- answer: The assistant's response.
Outputs ¶
- *HistoryTurn: Ready for storage or transmission.
Examples ¶
turn := NewHistoryTurn("What is OAuth?", "OAuth is an authorization framework...")
type HorizonSpec ¶
HorizonSpec defines the forecast horizon parameters.
Description:
HorizonSpec specifies how far into the future the model should predict.
Fields:
- Length: Number of periods to forecast
- Period: Time interval for forecast points
Example:
horizon := HorizonSpec{
Length: 10,
Period: Period1d,
}
Limitations:
- Maximum horizon depends on the model
- Forecast period should match context period
Assumptions:
- Length > 0
- Period matches the context period (models don't interpolate)
type InferenceMetadata ¶
type InferenceMetadata struct {
InferenceTimeMs int `json:"inference_time_ms"`
ModelVersion string `json:"model_version,omitempty"`
Device string `json:"device,omitempty"`
ModelFamily string `json:"model_family,omitempty"`
}
InferenceMetadata provides execution details.
Description:
InferenceMetadata contains information about how the inference was performed, useful for debugging and performance monitoring.
Fields:
- InferenceTimeMs: Time taken for model inference in milliseconds
- ModelVersion: Specific model version used
- Device: Compute device (cpu, cuda:0, mps)
- ModelFamily: Model family (chronos, timesfm, moirai)
Example:
metadata := InferenceMetadata{
InferenceTimeMs: 245,
ModelVersion: "1.0.0",
Device: "cpu",
ModelFamily: "chronos",
}
Assumptions:
- InferenceTimeMs does not include network latency
type InferenceRef ¶
type InferenceRef struct {
RequestID string `json:"request_id"`
ResponseID string `json:"response_id"`
}
InferenceRef links a trading signal to its originating inference request.
Description:
InferenceRef provides traceability from trading decisions back to the forecast that informed them. This enables audit trails, debugging of the full decision pipeline, and compliance reporting.
Fields:
- RequestID: The inference request UUID (from InferenceRequest.RequestID)
- ResponseID: The inference response UUID (from InferenceResponse.ResponseID)
Example:
// After calling inference service
ref := InferenceRef{
RequestID: inferenceReq.RequestID,
ResponseID: inferenceResp.ResponseID,
}
Limitations:
- Both IDs must be valid UUIDs from a prior inference call
- Empty IDs indicate legacy mode (no tracing available)
- Does not validate that the referenced inference exists
Assumptions:
- The referenced inference has already completed successfully
- IDs are set by the caller after receiving inference response
func (*InferenceRef) IsSet ¶
func (r *InferenceRef) IsSet() bool
IsSet returns true if both inference IDs are populated.
Description:
IsSet checks whether this reference has valid inference tracing IDs. A reference is considered set only when both RequestID and ResponseID are non-empty strings.
Inputs:
None (operates on receiver)
Outputs:
- bool: true if both IDs are non-empty, false otherwise
Example:
if ref.IsSet() {
slog.Info("Linked to inference", "req_id", ref.RequestID)
}
Limitations:
- Does not validate UUID format
- Does not verify IDs exist in any external system
Assumptions:
- Empty string means "not set"
type InferenceRequest ¶
type InferenceRequest struct {
RequestID string `json:"request_id"`
Timestamp time.Time `json:"timestamp"`
Ticker string `json:"ticker"`
Model string `json:"model"`
Context ContextData `json:"context"`
Horizon HorizonSpec `json:"horizon"`
Params *ModelParams `json:"params,omitempty"`
}
InferenceRequest is the unified request for all forecasting models.
Description:
InferenceRequest contains all information needed to generate a forecast, including the input context, model selection, and inference parameters. The RequestID enables end-to-end request tracing.
Fields:
- RequestID: UUID for tracing (generated by caller)
- Timestamp: When the request was created
- Ticker: Asset symbol (e.g., "SPY", "BTCUSD")
- Model: Model identifier (e.g., "amazon/chronos-t5-tiny")
- Context: Historical data and metadata
- Horizon: Forecast horizon specification
- Params: Optional model parameters (nil for defaults)
Example:
req := InferenceRequest{
RequestID: uuid.New().String(),
Timestamp: time.Now().UTC(),
Ticker: "SPY",
Model: "amazon/chronos-t5-tiny",
Context: ContextData{
Values: closeHistory,
Period: Period1d,
Source: SourceInfluxDB,
StartDate: "2025-01-01",
EndDate: "2025-12-31",
Field: FieldClose,
},
Horizon: HorizonSpec{
Length: 10,
Period: Period1d,
},
Params: &ModelParams{
NumSamples: 20,
},
}
Limitations:
- Ticker validation is the caller's responsibility
- Model name must match Sapheneia's supported models
- Context.Values cannot be empty
Assumptions:
- RequestID is unique per request
- Timestamp is in UTC
- Context.Period matches Horizon.Period
func (*InferenceRequest) Validate ¶
func (r *InferenceRequest) Validate() error
Validate checks that the InferenceRequest is valid before sending.
Description:
Validate performs runtime validation of the request, checking that all required fields are present and have valid values. Should be called before sending the request to avoid unnecessary network calls.
Inputs:
None (operates on receiver)
Outputs:
- error: Non-nil if validation fails, with descriptive message
Validations Performed:
- RequestID is non-empty
- Ticker is non-empty and passes ticker validation
- Model is non-empty and contains "/" (full name format)
- Context.Values is non-empty
- Context.Period is valid
- Context.StartDate and EndDate are non-empty
- Horizon.Length > 0
- Horizon.Period is valid
- If Params != nil, NumSamples >= 0, Temperature > 0 (if set)
- If Params.Quantiles provided, all values in [0, 1]
Example:
req := &InferenceRequest{
RequestID: "", // Invalid!
}
if err := req.Validate(); err != nil {
log.Fatalf("Invalid request: %v", err)
}
Limitations:
- Does not validate that dates are parseable
- Does not validate model exists in Sapheneia
Assumptions:
- Full model names contain "/" (e.g., "amazon/chronos-t5-tiny")
type InferenceResponse ¶
type InferenceResponse struct {
RequestID string `json:"request_id"`
ResponseID string `json:"response_id"`
Timestamp time.Time `json:"timestamp"`
Ticker string `json:"ticker"`
Model string `json:"model"`
Forecast ForecastData `json:"forecast"`
ContextSummary ContextSummary `json:"context_summary"`
Quantiles []QuantileForecast `json:"quantiles,omitempty"`
Metadata InferenceMetadata `json:"metadata"`
}
InferenceResponse is the unified response from all forecasting models.
Description:
InferenceResponse contains the forecast results along with tracing IDs and metadata. The ResponseID links back to the RequestID for tracing.
Fields:
- RequestID: Echoed from the request
- ResponseID: UUID generated by the inference service
- Timestamp: When the response was created
- Ticker: Echoed from request
- Model: Echoed from request
- Forecast: Point forecast results
- ContextSummary: Context that was used
- Quantiles: Optional quantile forecasts
- Metadata: Execution metadata
Example:
resp := InferenceResponse{
RequestID: "req-123",
ResponseID: "resp-456",
Timestamp: time.Now().UTC(),
Ticker: "SPY",
Model: "amazon/chronos-t5-tiny",
Forecast: ForecastData{
Values: []float64{101.5, 102.0},
Period: Period1d,
StartDate: "2026-01-01",
EndDate: "2026-01-02",
},
ContextSummary: ContextSummary{
Length: 252,
Period: Period1d,
Source: SourceInfluxDB,
StartDate: "2025-01-01",
EndDate: "2025-12-31",
Field: FieldClose,
},
Quantiles: []QuantileForecast{
{Quantile: 0.1, Values: []float64{99.5, 100.0}},
{Quantile: 0.9, Values: []float64{103.5, 104.0}},
},
Metadata: InferenceMetadata{
InferenceTimeMs: 245,
Device: "cpu",
},
}
Limitations:
- Quantiles may be empty if not requested or model doesn't support
Assumptions:
- RequestID matches the request's RequestID
- ResponseID is unique per response
type Message ¶
type Message struct {
MessageID string `json:"message_id,omitempty" validate:"omitempty,uuid4"`
Timestamp int64 `json:"timestamp,omitempty" validate:"omitempty,gt=0"`
Role string `json:"role" validate:"required,oneof=user assistant system"`
Content string `json:"content" validate:"required,maxbytes"`
}
Message represents a single message in a conversation.
Description ¶
Message is the fundamental unit of conversation in both direct chat and RAG chat endpoints. Each message has a role (who said it) and content (what they said). Optional ID and timestamp fields enable database storage and audit trails.
Fields ¶
- MessageID: Optional. Unique identifier for this message (UUID v4). Used for database correlation and message-level operations.
- Timestamp: Optional. Unix timestamp in milliseconds (UTC) when message was created. Used for ordering, audit trails, and retention policies.
- Role: Required. The role of the message sender. Must be one of: "user", "assistant", "system".
- Content: Required. The message text content. Limited to 32KB per SEC-003 compliance.
Validation ¶
- Role: required, must be "user", "assistant", or "system"
- Content: required, max 32KB (validated via maxbytes custom validator in chat.go)
- MessageID: optional, but if provided must be valid UUID v4
- Timestamp: optional, but if provided must be > 0
Security References ¶
- SEC-003: Message size limits (security_architecture_review.md)
type MetricsResponse ¶ added in v1.0.0
type MetricsResponse struct {
SharpeRatio float64 `json:"sharpe_ratio"` // Risk-adjusted return (annualized)
MaxDrawdown float64 `json:"max_drawdown"` // Maximum peak-to-trough decline (negative value)
CAGR float64 `json:"cagr"` // Compound Annual Growth Rate
CalmarRatio float64 `json:"calmar_ratio"` // CAGR / |MaxDrawdown|
WinRate float64 `json:"win_rate"` // Percentage of positive return periods (0-1)
}
MetricsResponse contains computed performance metrics from the metrics service. These metrics are calculated from the portfolio's return series after a backtest.
type ModelParams ¶
type ModelParams struct {
NumSamples int `json:"num_samples,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
TopK int `json:"top_k,omitempty"`
TopP float64 `json:"top_p,omitempty"`
Quantiles []float64 `json:"quantiles,omitempty"`
}
ModelParams holds model-specific inference parameters.
Description:
ModelParams contains optional tuning parameters that affect how the model generates predictions. Not all models support all parameters.
Fields:
- NumSamples: Number of samples for probabilistic models (must be > 0, server default: 20)
- Temperature: Sampling temperature (must be > 0, server default: 1.0)
- TopK: Top-K sampling parameter
- TopP: Top-P (nucleus) sampling parameter
- Quantiles: Which quantiles to return (e.g., [0.1, 0.5, 0.9])
Example:
// With explicit parameters
params := &ModelParams{
NumSamples: 100,
Temperature: 0.8,
Quantiles: []float64{0.1, 0.5, 0.9},
}
// For server defaults, use nil Params in InferenceRequest
req := InferenceRequest{Params: nil} // Sapheneia uses num_samples=20, temperature=1.0
Limitations:
- Not all models respect all parameters
- Chronos models ignore temperature
- Zero values are NOT allowed (use nil Params for server defaults)
Assumptions:
- NumSamples > 0 (required by Sapheneia gt=0 constraint)
- Temperature > 0 (required by Sapheneia gt=0 constraint)
- Quantiles are in range [0, 1]
type ModelPullRequest ¶
type ModelPullResponse ¶
type OHLCData ¶
type OHLCData struct {
Time []time.Time `json:"time"`
Open []float64 `json:"open_history"`
High []float64 `json:"high_history"`
Low []float64 `json:"low_history"`
Close []float64 `json:"close_history"`
AdjClose []float64 `json:"adj_close_history"`
Volume []float64 `json:"volume_history"`
}
OHLCData holds historical OHLC price data
type Period ¶
type Period string
Period represents the time frequency of time-series data points.
Description:
Period defines the interval between consecutive data points in a time series. Common periods include daily (1d), hourly (1h), and various intraday intervals.
Valid Values:
- "1m": One minute
- "5m": Five minutes
- "15m": Fifteen minutes
- "30m": Thirty minutes
- "1h": One hour
- "4h": Four hours
- "1d": One day (trading day)
- "1w": One week
- "1M": One month
Example:
period := datatypes.Period1d
if period == datatypes.Period1d {
log.Println("Daily data")
}
Limitations:
- Does not support arbitrary intervals (e.g., 7m, 3d)
- "1M" represents calendar months, not 30-day periods
Assumptions:
- Trading days exclude weekends and holidays
- Intraday periods assume continuous trading (24h for crypto)
func (Period) IsValid ¶
IsValid checks if the Period is a valid value.
Description:
IsValid returns true if the Period is one of the defined constants.
Inputs:
None (operates on receiver)
Outputs:
- bool: true if valid, false otherwise
Example:
p := Period("invalid")
if !p.IsValid() {
log.Println("Invalid period")
}
type PortfolioState ¶
type PortfolioState struct {
Position float64 `json:"position"`
Cash float64 `json:"cash"`
InitialCapital float64 `json:"initial_capital"`
}
PortfolioState captures the current portfolio position.
Description:
PortfolioState provides a snapshot of the portfolio at decision time, used by trading strategies to determine position sizing and available capital. This maps directly to the trading section in strategy YAML.
Fields:
- Position: Current number of shares/units held (from scenario.Trading.InitialPosition)
- Cash: Available cash for trading (from scenario.Trading.InitialCash)
- InitialCapital: Starting capital for P&L calculation (from scenario.Trading.InitialCapital)
Example:
// From strategy YAML trading section
state := PortfolioState{
Position: scenario.Trading.InitialPosition,
Cash: scenario.Trading.InitialCash,
InitialCapital: scenario.Trading.InitialCapital,
}
Limitations:
- Single asset portfolio only
- Does not track unrealized P&L
- Does not include margin or leverage
Assumptions:
- Position is non-negative (long-only strategies per Sapheneia)
- Cash is non-negative
- InitialCapital > 0
type PortfolioStateRecord ¶ added in v1.0.0
type PortfolioStateRecord struct {
Ticker string
PortfolioValue float64
Cash float64
Position float64
PositionValue float64
CurrentPrice float64
CumulativeReturn float64
Drawdown float64
StepIndex int
SnapshotDate string // ISO date string (YYYYMMDD)
Timestamp time.Time // Evaluation date (used as InfluxDB point timestamp)
}
PortfolioStateRecord represents a portfolio snapshot to persist in the "portfolio_state" measurement. Pre-computed equity curve point with risk metrics for visualization.
type PriceInfo ¶
type PriceInfo struct {
Current float64 `json:"current"`
Forecast float64 `json:"forecast"`
Period Period `json:"period"`
Source DataSource `json:"source"`
AsOfDate string `json:"as_of_date"`
}
PriceInfo holds current and forecast prices with metadata.
Description:
PriceInfo encapsulates price data used for trading decisions, including provenance information for audit purposes. This structure aligns with the inference response format.
Fields:
- Current: The current market price at decision time
- Forecast: The model's predicted price (first value from forecast)
- Period: Time period of the forecast (e.g., Period1d)
- Source: Origin of the price data (e.g., SourceInfluxDB)
- AsOfDate: Reference date for the prices (YYYY-MM-DD format)
Example:
prices := PriceInfo{
Current: 450.00,
Forecast: 455.00,
Period: Period1d,
Source: SourceInfluxDB,
AsOfDate: "2026-01-20",
}
Limitations:
- Does not include bid/ask spread
- Single price point, not full OHLCV
- Does not include confidence intervals
Assumptions:
- Prices are in the same currency
- Current price is from the same source as historical data
- Forecast is the median/mean prediction (quantile 0.5)
type ProgressEvent ¶
type ProgressEvent struct {
EventType ProgressEventType `json:"event_type"`
Message string `json:"message"`
Timestamp string `json:"timestamp,omitempty"`
Attempt int `json:"attempt,omitempty"`
TraceID string `json:"trace_id,omitempty"`
RetrievalDetails *RetrievalDetails `json:"retrieval_details,omitempty"`
AuditDetails *SkepticAuditDetails `json:"audit_details,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
ProgressEvent represents a single progress update during verified pipeline execution.
Description ¶
Progress events are streamed via SSE to provide real-time feedback during the skeptic/optimist debate. Each event has a type, message, and optional detailed information depending on the event type and verbosity level.
Fields ¶
- EventType: The type of progress event (from ProgressEventType enum).
- Message: Human-readable summary message (always present).
- Timestamp: ISO 8601 timestamp when the event occurred.
- Attempt: Current verification attempt (1-indexed, max 3).
- TraceID: OpenTelemetry trace ID for debugging (verbosity >= 2).
- RetrievalDetails: Details about retrieval (RETRIEVAL_COMPLETE only).
- AuditDetails: Details about skeptic audit (SKEPTIC_AUDIT_COMPLETE only).
- ErrorMessage: Error description (ERROR event type only).
Verbosity Levels ¶
The CLI uses verbosity to control what is displayed:
- Level 0: Silent (no progress shown)
- Level 1: Summary (shows Message only)
- Level 2: Detailed (shows Message + details + trace link)
Examples ¶
// Verbosity 1 display
fmt.Printf("[%s] %s\n", event.EventType, event.Message)
// Verbosity 2 display with OTel link
if event.TraceID != "" {
fmt.Printf(" View trace: http://localhost:16686/trace/%s\n", event.TraceID)
}
type ProgressEventType ¶
type ProgressEventType string
ProgressEventType defines the discrete stages of the skeptic/optimist debate.
Description ¶
These event types are emitted during the verified RAG pipeline execution and streamed to clients for real-time feedback. Each type corresponds to a specific stage of the debate pattern.
Values ¶
- RetrievalStart: Document retrieval has begun
- RetrievalComplete: Documents retrieved, includes count and sources
- DraftStart: Optimist is generating initial answer
- DraftComplete: Initial draft ready for skeptic review
- SkepticAuditStart: Skeptic is analyzing the draft
- SkepticAuditComplete: Skeptic has rendered verdict
- RefinementStart: Refiner is correcting hallucinations
- RefinementComplete: Refined answer ready for re-audit
- VerificationComplete: Final answer verified, debate concluded
- Error: An error occurred during pipeline execution
Examples ¶
if event.EventType == ProgressEventTypeSkepticAuditComplete {
if event.AuditDetails != nil && !event.AuditDetails.IsVerified {
fmt.Printf("Found %d hallucinations\n", len(event.AuditDetails.Hallucinations))
}
}
const ( ProgressEventTypeRetrievalStart ProgressEventType = "retrieval_start" ProgressEventTypeRetrievalComplete ProgressEventType = "retrieval_complete" ProgressEventTypeDraftStart ProgressEventType = "draft_start" ProgressEventTypeDraftComplete ProgressEventType = "draft_complete" ProgressEventTypeSkepticAuditStart ProgressEventType = "skeptic_audit_start" ProgressEventTypeSkepticAuditComplete ProgressEventType = "skeptic_audit_complete" ProgressEventTypeRefinementStart ProgressEventType = "refinement_start" ProgressEventTypeRefinementComplete ProgressEventType = "refinement_complete" ProgressEventTypeVerificationComplete ProgressEventType = "verification_complete" ProgressEventTypeError ProgressEventType = "error" )
type QuantileForecast ¶
type QuantileForecast struct {
Quantile float64 `json:"quantile"`
Values []float64 `json:"values"`
}
QuantileForecast holds a single quantile forecast.
Description:
QuantileForecast contains the predicted values at a specific quantile level, enabling uncertainty estimation.
Fields:
- Quantile: The quantile level (0.0 to 1.0)
- Values: Predicted values at this quantile
Example:
q90 := QuantileForecast{
Quantile: 0.9,
Values: []float64{103.0, 104.5, 103.8},
}
Limitations:
- Quantile must be in [0, 1]
Assumptions:
- len(Values) matches the forecast horizon
type RAGRequest ¶
type RAGRequest struct {
Query string `json:"query"`
SessionId string `json:"session_id"`
Pipeline string `json:"pipeline"`
NoRag bool `json:"no_rag"`
DataSpace string `json:"data_space,omitempty"` // Data space to filter queries by (e.g., "work", "personal")
SessionTTL string `json:"session_ttl,omitempty"` // Session TTL (e.g., "24h", "7d"). Resets on each message.
}
type RAGResponse ¶
type RAGResponse struct {
Answer string `json:"answer"`
SessionId string `json:"session_id"`
Sources []SourceInfo `json:"sources,omitempty"`
}
type RagEngineResponse ¶
type RagEngineResponse struct {
Answer string `json:"answer"`
Sources []SourceInfo `json:"sources,omitempty"`
}
type RetrievalChunk ¶
type RetrievalChunk struct {
Content string `json:"content"`
Source string `json:"source"`
RerankScore *float64 `json:"rerank_score,omitempty"`
}
RetrievalChunk represents a single document chunk from retrieval-only mode.
Description ¶
Each chunk contains the document content, source identifier, and optional relevance score from the reranking model.
Fields ¶
- Content: The actual document text.
- Source: Document name, path, or URL identifying the source.
- RerankScore: Relevance score from reranking (higher = more relevant).
type RetrievalDetails ¶
type RetrievalDetails struct {
DocumentCount int `json:"document_count"`
Sources []string `json:"sources,omitempty"`
HasRelevantDocs bool `json:"has_relevant_docs"`
}
RetrievalDetails contains document retrieval information.
Description ¶
This struct is populated during RETRIEVAL_COMPLETE events at verbosity level 2. It provides information about the documents retrieved for the query before the skeptic/optimist debate begins.
Fields ¶
- DocumentCount: Number of documents retrieved.
- Sources: List of source identifiers (filenames, URLs, etc.).
- HasRelevantDocs: Whether relevant documents were found.
Examples ¶
if details.HasRelevantDocs {
fmt.Printf("Found %d documents: %v\n", details.DocumentCount, details.Sources)
}
type RetrievalRequest ¶
type RetrievalRequest struct {
Query string `json:"query"`
Pipeline string `json:"pipeline,omitempty"`
SessionId string `json:"session_id,omitempty"`
StrictMode bool `json:"strict_mode"`
MaxChunks int `json:"max_chunks,omitempty"`
DataSpace string `json:"data_space,omitempty"` // Data space to filter queries by
}
RetrievalRequest is the request sent to the Python RAG engine's retrieval-only endpoint. It returns document content without LLM generation.
Description ¶
This request type supports the streaming integration where: 1. Python RAG retrieves and reranks documents 2. Go orchestrator receives raw document content 3. Go orchestrator streams LLM response with full document context
This fixes the "two-LLM" problem where Python generated an answer, then Go used that answer as "context" for a second LLM that would say "no documents found" even when sources were displayed.
Fields ¶
- Query: The user's query to retrieve documents for.
- Pipeline: The RAG pipeline to use ("reranking" or "verified").
- SessionId: Optional session ID for session-scoped document filtering.
- StrictMode: If true, only return documents above relevance threshold.
- MaxChunks: Maximum number of document chunks to return (default: 5).
Supported Pipelines ¶
- "reranking": Cross-encoder reranking for better relevance ordering.
- "verified": Skeptic/optimist debate for hallucination prevention.
func NewRetrievalRequest ¶
func NewRetrievalRequest(query, sessionId string) *RetrievalRequest
NewRetrievalRequest creates a new RetrievalRequest with default values.
Description ¶
Creates a RetrievalRequest with sensible defaults:
- Pipeline: "reranking" (cross-encoder reranking)
- StrictMode: true (only return relevant documents)
- MaxChunks: 5 (matches top_k_final in reranking pipeline)
Inputs ¶
- query: The user's query to retrieve documents for.
- sessionId: Optional session ID (pass empty string for no session).
Outputs ¶
- *RetrievalRequest: Ready to be sent to the RAG engine.
Examples ¶
req := NewRetrievalRequest("What is Detroit known for?", "sess_abc123")
req := NewRetrievalRequest("authentication", "") // No session
req := NewRetrievalRequest("query", "").WithPipeline("verified")
func (*RetrievalRequest) WithDataSpace ¶
func (r *RetrievalRequest) WithDataSpace(dataSpace string) *RetrievalRequest
WithDataSpace sets the data space filter and returns the request for chaining.
Description ¶
Sets the data space for query isolation. Documents are filtered to only include those from the specified data space (e.g., "work" or "personal"). If not set or empty, searches across ALL data spaces (no isolation).
Inputs ¶
- dataSpace: The data space name to filter by.
Outputs ¶
- *RetrievalRequest: The modified request for method chaining.
Examples ¶
req := NewRetrievalRequest("query", "sess_123").WithDataSpace("work")
func (*RetrievalRequest) WithMaxChunks ¶
func (r *RetrievalRequest) WithMaxChunks(max int) *RetrievalRequest
WithMaxChunks sets the maximum chunks and returns the request for chaining.
func (*RetrievalRequest) WithPipeline ¶
func (r *RetrievalRequest) WithPipeline(pipeline string) *RetrievalRequest
WithPipeline sets the RAG pipeline and returns the request for chaining.
Description ¶
Sets the retrieval pipeline to use. Supported pipelines:
- "reranking": Cross-encoder reranking for better relevance ordering.
- "verified": Skeptic/optimist debate for hallucination prevention.
Inputs ¶
- pipeline: The pipeline name ("reranking" or "verified").
Outputs ¶
- *RetrievalRequest: The modified request for method chaining.
Examples ¶
req := NewRetrievalRequest("query", "sess_123").WithPipeline("verified")
func (*RetrievalRequest) WithStrictMode ¶
func (r *RetrievalRequest) WithStrictMode(strict bool) *RetrievalRequest
WithStrictMode sets the strict mode flag and returns the request for chaining.
type RetrievalResponse ¶
type RetrievalResponse struct {
Chunks []RetrievalChunk `json:"chunks"`
ContextText string `json:"context_text"`
HasRelevantDocs bool `json:"has_relevant_docs"`
}
RetrievalResponse is the response from the Python RAG engine's retrieval-only endpoint.
Description ¶
Contains the retrieved document chunks, pre-formatted context text for direct use in LLM prompts, and a flag indicating whether relevant documents were found.
Fields ¶
- Chunks: List of retrieved document chunks with content and metadata.
- ContextText: Formatted string with "[Document N: source]" headers ready for LLM context. This enables clear citation in responses.
- HasRelevantDocs: Boolean indicating if documents above the relevance threshold were found. Used to determine if "no documents" message should be shown.
Context Format Example ¶
[Document 1: detroit_history.md] Detroit was founded in 1701 by French colonists... [Document 2: detroit_economy.md] The city's economy was historically based on automotive manufacturing...
type ScenarioMetadata ¶
type ScenarioMetadata struct {
ID string `yaml:"id" json:"id"`
Version string `yaml:"version" json:"version"`
Description string `yaml:"description" json:"description"`
Author string `yaml:"author" json:"author"`
Created string `yaml:"created" json:"created"`
}
ScenarioMetadata tracks the identity of the strategy being tested
type SessionContext ¶ added in v1.0.0
SessionContext holds context values that should be stored with a session.
Description ¶
SessionContext captures the configuration used when a session was created, allowing resume to restore the exact same experience.
Fields ¶
- DataSpace: The data space filter for RAG queries (e.g., "work", "personal").
- Pipeline: The RAG pipeline to use (e.g., "reranking", "verified").
- TTL: TTL duration string (e.g., "24h", "7d"). Empty = no TTL.
type SessionProperties ¶
type SessionProperties struct {
SessionId string `json:"session_id"`
Summary string `json:"summary"`
Timestamp int64 `json:"timestamp"`
TTLExpiresAt int64 `json:"ttl_expires_at"`
TTLDurationMs int64 `json:"ttl_duration_ms"`
DataSpace string `json:"data_space"`
Pipeline string `json:"pipeline"`
}
func (*SessionProperties) ToMap ¶
func (p *SessionProperties) ToMap() map[string]interface{}
ToMap converts SessionProperties to map[string]interface{} for Weaviate.
Description ¶
Converts the typed SessionProperties struct to the map format required by Weaviate's WithProperties() method.
Outputs ¶
- map[string]interface{}: Property map ready for Weaviate client.
Example ¶
props := SessionProperties{SessionId: "sess_123", Summary: "...", Timestamp: now}
client.Data().Creator().WithProperties(props.ToMap()).Do(ctx)
type SessionQueryResponse ¶
type SessionQueryResponse struct {
Get struct {
Session []SessionResult `json:"Session"`
} `json:"Get"`
}
SessionQueryResponse represents the response from querying the Session class.
Fields ¶
- Get.Session: Array of session objects with their Weaviate UUIDs.
type SessionResult ¶
type SessionResult struct {
SessionID string `json:"session_id"`
Summary string `json:"summary"`
Timestamp int64 `json:"timestamp"`
TTLExpiresAt int64 `json:"ttl_expires_at"`
TTLDurationMs int64 `json:"ttl_duration_ms"`
Additional struct {
ID string `json:"id"`
} `json:"_additional"`
}
SessionResult represents a single session from a query.
type SkepticAuditDetails ¶
type SkepticAuditDetails struct {
IsVerified bool `json:"is_verified"`
Reasoning string `json:"reasoning"`
Hallucinations []string `json:"hallucinations,omitempty"`
MissingEvidence []string `json:"missing_evidence,omitempty"`
SourcesCited []int `json:"sources_cited,omitempty"`
}
SkepticAuditDetails contains detailed skeptic audit results.
Description ¶
This struct is populated during SKEPTIC_AUDIT_COMPLETE events at verbosity level 2. It provides granular information about what the skeptic found, including specific hallucinations and missing evidence.
Fields ¶
- IsVerified: True if all claims are supported by evidence.
- Reasoning: The skeptic's explanation of the verdict.
- Hallucinations: List of specific unsupported claims.
- MissingEvidence: List of facts needing evidence.
- SourcesCited: Indices of sources referenced (0-based).
Examples ¶
if !details.IsVerified {
for _, h := range details.Hallucinations {
fmt.Printf(" Unsupported: %s\n", h)
}
}
type SourceInfo ¶
type SourceInfo struct {
Id string `json:"id,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
Source string `json:"source"`
Distance float64 `json:"distance,omitempty"`
Score float64 `json:"score,omitempty"`
Hash string `json:"hash,omitempty"`
VersionNumber *int `json:"version_number,omitempty"` // Document version (1, 2, 3...)
IsCurrent *bool `json:"is_current,omitempty"` // True if this is the latest version
IngestedAt int64 `json:"ingested_at,omitempty"` // Unix ms timestamp when document was ingested
}
SourceInfo represents a retrieved document source from RAG retrieval.
Description ¶
SourceInfo captures metadata about a document retrieved during RAG processing. Each source has a unique ID and timestamp for database storage and audit trails.
Fields ¶
- Id: Unique identifier for this source record (UUID v4).
- CreatedAt: Unix timestamp in milliseconds when source was retrieved.
- Source: Document name, path, or URL identifying the source.
- Distance: Vector distance (lower = more similar). Used by some pipelines.
- Score: Relevance score (higher = more relevant). Used by reranking pipelines.
- Hash: SHA-256 hash of source content at retrieval time. Used for tamper detection and audit trails. Part of the hash chain.
Notes ¶
Distance and Score are mutually exclusive - only one will be set depending on the RAG pipeline used.
func ApplyRecencyDecay ¶
func ApplyRecencyDecay(sources []SourceInfo, decayRate float64) []SourceInfo
ApplyRecencyDecay applies time-based decay to source scores.
Description ¶
Applies exponential decay to document scores based on age:
final_score = semantic_score * exp(-λ * age_in_days)
Where λ (lambda) is the decay rate. Higher λ = faster decay. After decay, sources are re-sorted by score (highest first).
When To Use ¶
Use recency decay ONLY for time-sensitive content where newer = more relevant:
- News articles and current events
- Changelogs and release notes
- Daily/weekly reports
- Time-series data
Do NOT use for document versioning (handled by is_current filter) or static knowledge bases where old content is equally valid.
Inputs ¶
- sources: Slice of SourceInfo to apply decay to.
- decayRate: The decay rate λ. Use GetRecencyDecayRate() for presets.
Outputs ¶
- []SourceInfo: Sources with adjusted scores, sorted by score descending.
Notes ¶
- If decayRate is 0, returns sources unchanged.
- Uses Score field if set, otherwise Distance (inverted for decay).
- IngestedAt must be set for decay to work; 0 = no decay applied.
func NewSourceInfo ¶
func NewSourceInfo(source string) *SourceInfo
NewSourceInfo creates a new SourceInfo with auto-generated ID and timestamp.
Description ¶
Creates a SourceInfo for a retrieved document source. The ID and timestamp are automatically populated for database storage and tracing.
Inputs ¶
- source: Document name, path, or URL identifying the source.
Outputs ¶
- *SourceInfo: Ready for use with Score or Distance set separately.
Examples ¶
src := NewSourceInfo("auth.go").WithScore(0.95)
src := NewSourceInfo("api.md").WithDistance(0.123)
func (*SourceInfo) WithDistance ¶
func (s *SourceInfo) WithDistance(distance float64) *SourceInfo
WithDistance sets the vector distance on a SourceInfo and returns it for chaining.
func (*SourceInfo) WithScore ¶
func (s *SourceInfo) WithScore(score float64) *SourceInfo
WithScore sets the relevance score on a SourceInfo and returns it for chaining.
type StreamEvent ¶
type StreamEvent struct {
Id string `json:"id"` // Event ID (for ordering/deduplication)
CreatedAt int64 `json:"created_at"` // Unix timestamp (milliseconds)
Type string `json:"type"` // "status", "token", "sources", "done", "error"
Message string `json:"message,omitempty"` // For status events
Content string `json:"content,omitempty"` // For token events
Sources []SourceInfo `json:"sources,omitempty"` // For sources event
SessionId string `json:"session_id,omitempty"` // For done event
Error string `json:"error,omitempty"` // For error event
Hash string `json:"hash,omitempty"` // SHA-256 hash of this event
PrevHash string `json:"prev_hash,omitempty"` // Hash of previous event in chain
}
StreamEvent represents a single SSE event for streaming responses.
Hash Chain ¶
Each event contains Hash and PrevHash fields for tamper-evident logging. Formula: Hash_N = SHA256(Content_N || CreatedAt_N || Hash_{N-1})
This enables detection of:
- Missing events (gap in chain)
- Modified events (hash mismatch)
- Reordered events (prev_hash mismatch)
func NewStreamEvent ¶
func NewStreamEvent(eventType string) *StreamEvent
NewStreamEvent creates a new StreamEvent of the specified type with auto-generated ID and timestamp. Use the builder methods (WithMessage, WithContent, etc.) to populate type-specific fields.
Supported event types:
- "status": Progress updates (e.g., "Searching knowledge base...")
- "token": Individual tokens for streaming LLM output
- "sources": Retrieved source documents after RAG retrieval
- "done": Signals end of stream, includes final session ID
- "error": Error occurred during processing
Example:
event := NewStreamEvent("status").WithMessage("Searching knowledge base...")
event := NewStreamEvent("token").WithContent("The")
event := NewStreamEvent("error").WithError("Connection timeout")
func (*StreamEvent) WithContent ¶
func (e *StreamEvent) WithContent(content string) *StreamEvent
WithContent sets the Content field on a StreamEvent and returns the event for method chaining. This is used with "token" type events to stream individual tokens from the LLM response.
Example:
event := NewStreamEvent("token").WithContent("authentication")
func (*StreamEvent) WithError ¶
func (e *StreamEvent) WithError(err string) *StreamEvent
WithError sets the Error field on a StreamEvent and returns the event for method chaining. This is used with "error" type events to communicate error details to the client.
Example:
event := NewStreamEvent("error").WithError("RAG engine unavailable")
func (*StreamEvent) WithMessage ¶
func (e *StreamEvent) WithMessage(msg string) *StreamEvent
WithMessage sets the Message field on a StreamEvent and returns the event for method chaining. This is typically used with "status" type events to communicate progress to the client.
Example:
event := NewStreamEvent("status").WithMessage("Found 8 relevant chunks")
func (*StreamEvent) WithSessionId ¶
func (e *StreamEvent) WithSessionId(sessionId string) *StreamEvent
WithSessionId sets the SessionId field on a StreamEvent and returns the event for method chaining. This is typically used with "done" type events to communicate the final session ID to the client for potential resume.
Example:
event := NewStreamEvent("done").WithSessionId("sess_abc123")
func (*StreamEvent) WithSources ¶
func (e *StreamEvent) WithSources(sources []SourceInfo) *StreamEvent
WithSources sets the Sources field on a StreamEvent and returns the event for method chaining. This is used with "sources" type events to send the retrieved document sources to the client after RAG retrieval completes.
Example:
sources := []SourceInfo{{Source: "auth.go", Score: 0.95}}
event := NewStreamEvent("sources").WithSources(sources)
type TemperatureOverrides ¶
type TemperatureOverrides struct {
Optimist *float64 `json:"optimist,omitempty"`
Skeptic *float64 `json:"skeptic,omitempty"`
Refiner *float64 `json:"refiner,omitempty"`
}
TemperatureOverrides allows per-request temperature configuration for the verified pipeline's debate roles.
Description ¶
The verified pipeline uses three LLM roles with different temperature needs:
- Optimist: Generates initial draft (higher temp = more creative)
- Skeptic: Audits for hallucinations (lower temp = more consistent)
- Refiner: Rewrites to remove hallucinations (balanced temp)
All fields are optional. Omitted fields use the pipeline's configured defaults (from environment variables or config).
Fields ¶
- Optimist: Temperature for draft generation (0.0-2.0, default: 0.6)
- Skeptic: Temperature for skeptic audits (0.0-2.0, default: 0.2)
- Refiner: Temperature for refinement (0.0-2.0, default: 0.4)
Examples ¶
// More creative drafts, stricter verification
overrides := &TemperatureOverrides{Optimist: ptr(0.8), Skeptic: ptr(0.1)}
// Conservative mode (all low temperatures)
overrides := &TemperatureOverrides{Optimist: ptr(0.3), Skeptic: ptr(0.1), Refiner: ptr(0.2)}
func (*TemperatureOverrides) ToMap ¶
func (t *TemperatureOverrides) ToMap() map[string]float64
ToMap converts TemperatureOverrides to a map for JSON serialization. Only includes non-nil values.
type TickerInfo ¶
TickerInfo represents a ticker to evaluate
type TokenUsage ¶
type TokenUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
}
TokenUsage contains token consumption statistics.
Description ¶
Tracks input and output token counts for billing and monitoring.
Fields ¶
- InputTokens: Number of tokens in the prompt/messages
- OutputTokens: Number of tokens in the response
type ToolCall ¶
type ToolCall struct {
Id string `json:"id"`
Type string `json:"type"` // usually "function"
Function ToolFunction `json:"function"`
}
ToolCall represents the LLM's request to execute a function.
type ToolFunction ¶
type TradingSignalRecord ¶ added in v1.0.0
type TradingSignalRecord struct {
Ticker string
StrategyType string
Action string
ForecastPrice float64
CurrentPrice float64
PositionBefore float64
PositionAfter float64
TradeSize float64
TradeValue float64
CashBefore float64
CashAfter float64
Reason string
SignalDate string // ISO date string (YYYYMMDD)
Timestamp time.Time // Evaluation date (used as InfluxDB point timestamp)
}
TradingSignalRecord represents a trading signal to persist in the "trading_signals" measurement. Captures both before and after state for each trade decision.
type TradingSignalRequest ¶
type TradingSignalRequest struct {
// Ticker and forecast info
Ticker string `json:"ticker" binding:"required"`
ForecastPrice float64 `json:"forecast_price" binding:"required,gt=0"`
CurrentPrice *float64 `json:"current_price,omitempty"` // Optional, will fetch from InfluxDB if not provided
// Portfolio state
CurrentPosition float64 `json:"current_position" binding:"required,gte=0"`
AvailableCash float64 `json:"available_cash" binding:"required,gte=0"`
InitialCapital float64 `json:"initial_capital" binding:"required,gt=0"`
// Strategy configuration
StrategyType string `json:"strategy_type" binding:"required,oneof=threshold return quantile"`
StrategyParams map[string]interface{} `json:"strategy_params" binding:"required"`
// Historical data parameters
HistoryDays int `json:"history_days,omitempty"` // Default: 252 (1 year)
}
TradingSignalRequest is the request structure for the trading signal endpoint
func (*TradingSignalRequest) GetAvailableCash ¶
func (r *TradingSignalRequest) GetAvailableCash() float64
GetAvailableCash returns the available cash from V1 request.
func (*TradingSignalRequest) GetCurrentPosition ¶
func (r *TradingSignalRequest) GetCurrentPosition() float64
GetCurrentPosition returns the current position from V1 request.
func (*TradingSignalRequest) GetCurrentPrice ¶
func (r *TradingSignalRequest) GetCurrentPrice() float64
GetCurrentPrice returns the current price from V1 request. Returns 0 if CurrentPrice was not set.
func (*TradingSignalRequest) GetForecastPrice ¶
func (r *TradingSignalRequest) GetForecastPrice() float64
GetForecastPrice returns the forecast price from V1 request.
func (*TradingSignalRequest) GetInitialCapital ¶
func (r *TradingSignalRequest) GetInitialCapital() float64
GetInitialCapital returns the initial capital from V1 request.
func (*TradingSignalRequest) GetStrategyParams ¶
func (r *TradingSignalRequest) GetStrategyParams() map[string]interface{}
GetStrategyParams returns the strategy params from V1 request.
func (*TradingSignalRequest) GetStrategyType ¶
func (r *TradingSignalRequest) GetStrategyType() string
GetStrategyType returns the strategy type from V1 request.
func (*TradingSignalRequest) GetTicker ¶
func (r *TradingSignalRequest) GetTicker() string
GetTicker returns the ticker symbol from V1 request.
type TradingSignalRequestV2 ¶
type TradingSignalRequestV2 struct {
RequestID string `json:"request_id"`
Timestamp time.Time `json:"timestamp"`
Ticker string `json:"ticker"`
StrategyType string `json:"strategy_type"`
Prices PriceInfo `json:"prices"`
Portfolio PortfolioState `json:"portfolio"`
StrategyParams map[string]interface{} `json:"strategy_params"`
InferenceRef InferenceRef `json:"inference_ref"`
}
TradingSignalRequestV2 is the new trading signal request with full traceability.
Description:
TradingSignalRequestV2 extends the legacy V1 request with inference tracing and structured price/portfolio data. This enables full audit trails from forecast to trade, which is required for compliance and debugging. The structure aligns with the backtest scenario YAML format: - Prices.Forecast comes from inference response - Portfolio maps to scenario.Trading section - StrategyType/Params map to scenario.Trading.strategy_type/params
Fields:
- RequestID: Unique ID for this trading request (UUID)
- Timestamp: When the request was created (UTC)
- Ticker: Asset symbol (from scenario.Evaluation.ticker)
- StrategyType: Trading strategy (from scenario.Trading.strategy_type)
- Prices: Current and forecast price info
- Portfolio: Current portfolio state
- StrategyParams: Strategy-specific parameters (from scenario.Trading.params)
- InferenceRef: Link to originating inference request/response
Example:
// Building V2 request after inference
req := TradingSignalRequestV2{
RequestID: uuid.New().String(),
Timestamp: time.Now().UTC(),
Ticker: scenario.Evaluation.Ticker,
StrategyType: scenario.Trading.StrategyType,
Prices: PriceInfo{
Current: currentPrice,
Forecast: inferenceResp.Forecast.Values[0],
Period: Period1d,
Source: SourceInfluxDB,
AsOfDate: currentDate,
},
Portfolio: PortfolioState{
Position: currentPosition,
Cash: availableCash,
InitialCapital: scenario.Trading.InitialCapital,
},
StrategyParams: scenario.Trading.Params,
InferenceRef: InferenceRef{
RequestID: inferenceReq.RequestID,
ResponseID: inferenceResp.ResponseID,
},
}
Limitations:
- Requires prior inference call for InferenceRef
- Sapheneia trading service doesn't support V2 yet (must convert to V1)
- Not backwards compatible with V1 trading service
Assumptions:
- InferenceRef is set when using unified API mode
- Trading service supports the strategy type specified
- StrategyParams contains all required parameters for the strategy
func NewTradingSignalRequestV2 ¶
func NewTradingSignalRequestV2( ticker string, strategyType string, prices PriceInfo, portfolio PortfolioState, params map[string]interface{}, inferenceRef InferenceRef, ) *TradingSignalRequestV2
NewTradingSignalRequestV2 creates a new V2 request with generated UUID.
Description:
NewTradingSignalRequestV2 is a convenience constructor that generates a new request ID and sets the timestamp. Use this when building a V2 request from backtest scenario data.
Inputs:
- ticker: Asset symbol (e.g., "SPY")
- strategyType: Strategy name (e.g., "threshold", "return", "quantile")
- prices: Price information with current and forecast
- portfolio: Current portfolio state
- params: Strategy-specific parameters from YAML
- inferenceRef: Link to originating inference (can be empty)
Outputs:
- *TradingSignalRequestV2: Fully constructed request ready for use
Example:
req := NewTradingSignalRequestV2(
"SPY",
"threshold",
PriceInfo{Current: 450, Forecast: 455, Period: Period1d, Source: SourceInfluxDB},
PortfolioState{Position: 0, Cash: 100000, InitialCapital: 100000},
map[string]interface{}{"threshold_type": "absolute", "threshold_value": 2.0},
InferenceRef{RequestID: req.RequestID, ResponseID: resp.ResponseID},
)
Limitations:
- Does not validate inputs (caller must ensure validity)
Assumptions:
- UUID generation does not fail
- Caller provides valid strategy parameters
func (*TradingSignalRequestV2) GetAvailableCash ¶
func (r *TradingSignalRequestV2) GetAvailableCash() float64
GetAvailableCash returns the available cash for trading.
Description:
GetAvailableCash implements TradingSignalRequester interface. Returns the cash available for new purchases.
Inputs:
None (operates on receiver)
Outputs:
- float64: The available cash
Example:
cash := req.GetAvailableCash() // 50000.00
Limitations:
None
Assumptions:
- Cash is non-negative
func (*TradingSignalRequestV2) GetCurrentPosition ¶
func (r *TradingSignalRequestV2) GetCurrentPosition() float64
GetCurrentPosition returns the current position size.
Description:
GetCurrentPosition implements TradingSignalRequester interface. Returns the number of shares/units currently held.
Inputs:
None (operates on receiver)
Outputs:
- float64: The current position (shares/units)
Example:
position := req.GetCurrentPosition() // 100.0
Limitations:
None
Assumptions:
- Position is non-negative (long-only)
func (*TradingSignalRequestV2) GetCurrentPrice ¶
func (r *TradingSignalRequestV2) GetCurrentPrice() float64
GetCurrentPrice returns the current market price.
Description:
GetCurrentPrice implements TradingSignalRequester interface. Returns the current price at decision time.
Inputs:
None (operates on receiver)
Outputs:
- float64: The current price
Example:
current := req.GetCurrentPrice() // 450.00
Limitations:
None
Assumptions:
- Current price is positive
func (*TradingSignalRequestV2) GetForecastPrice ¶
func (r *TradingSignalRequestV2) GetForecastPrice() float64
GetForecastPrice returns the model's forecast price.
Description:
GetForecastPrice implements TradingSignalRequester interface. Returns the predicted price from the inference response.
Inputs:
None (operates on receiver)
Outputs:
- float64: The forecast price
Example:
forecast := req.GetForecastPrice() // 455.00
Limitations:
None
Assumptions:
- Forecast price is positive
func (*TradingSignalRequestV2) GetInitialCapital ¶
func (r *TradingSignalRequestV2) GetInitialCapital() float64
GetInitialCapital returns the initial capital for P&L calculation.
Description:
GetInitialCapital implements TradingSignalRequester interface. Returns the starting capital from the backtest scenario.
Inputs:
None (operates on receiver)
Outputs:
- float64: The initial capital
Example:
capital := req.GetInitialCapital() // 100000.00
Limitations:
None
Assumptions:
- InitialCapital is positive
func (*TradingSignalRequestV2) GetStrategyParams ¶
func (r *TradingSignalRequestV2) GetStrategyParams() map[string]interface{}
GetStrategyParams returns the strategy-specific parameters.
Description:
GetStrategyParams implements TradingSignalRequester interface. Returns the parameters from the YAML trading.params section.
Inputs:
None (operates on receiver)
Outputs:
- map[string]interface{}: Strategy parameters (e.g., threshold_type, threshold_value)
Example:
params := req.GetStrategyParams()
// {"threshold_type": "absolute", "threshold_value": 2.0, "execution_size": 10.0}
Limitations:
- Returns nil if no params were set
Assumptions:
- Params match the strategy type's requirements
func (*TradingSignalRequestV2) GetStrategyType ¶
func (r *TradingSignalRequestV2) GetStrategyType() string
GetStrategyType returns the trading strategy type.
Description:
GetStrategyType implements TradingSignalRequester interface. Returns the strategy type as specified in the YAML (threshold, return, quantile).
Inputs:
None (operates on receiver)
Outputs:
- string: The strategy type (e.g., "threshold")
Example:
stratType := req.GetStrategyType() // "threshold"
Limitations:
None
Assumptions:
- StrategyType matches one of the supported Sapheneia strategies
func (*TradingSignalRequestV2) GetTicker ¶
func (r *TradingSignalRequestV2) GetTicker() string
GetTicker returns the asset ticker symbol.
Description:
GetTicker implements TradingSignalRequester interface.
Inputs:
None (operates on receiver)
Outputs:
- string: The ticker symbol (e.g., "SPY")
Example:
ticker := req.GetTicker() // "SPY"
Limitations:
None
Assumptions:
- Ticker was set during construction
func (*TradingSignalRequestV2) HasInferenceRef ¶
func (r *TradingSignalRequestV2) HasInferenceRef() bool
HasInferenceRef returns true if inference tracing is available.
Description:
HasInferenceRef checks whether this request has valid inference reference IDs for traceability purposes. This is true when using the unified API mode.
Inputs:
None (operates on receiver)
Outputs:
- bool: true if both RequestID and ResponseID are non-empty
Example:
if req.HasInferenceRef() {
slog.Info("Request linked to inference",
"trading_id", req.RequestID,
"inference_id", req.InferenceRef.RequestID,
)
}
Limitations:
- Does not validate UUID format
- Does not verify IDs exist in any system
Assumptions:
- Empty InferenceRef means legacy mode was used
func (*TradingSignalRequestV2) ToV1 ¶
func (r *TradingSignalRequestV2) ToV1() TradingSignalRequest
ToV1 converts the V2 request to V1 format for Sapheneia compatibility.
Description:
ToV1 converts this V2 request to the legacy V1 TradingSignalRequest format. This is required because Sapheneia's trading service doesn't support V2 yet. The conversion preserves all trading-relevant fields but drops the inference tracing (which should be logged separately).
Inputs:
None (operates on receiver)
Outputs:
- TradingSignalRequest: V1 format request for Sapheneia
Example:
v2Req := NewTradingSignalRequestV2(...) v1Req := v2Req.ToV1() response, err := evaluator.CallTradingService(ctx, v1Req)
Limitations:
- InferenceRef is lost in conversion (log it before converting)
- V2-specific RequestID/Timestamp are not preserved
Assumptions:
- Sapheneia trading service accepts V1 format
- All required V1 fields can be derived from V2
func (*TradingSignalRequestV2) Validate ¶
func (r *TradingSignalRequestV2) Validate() error
Validate checks if the V2 request is valid for trading.
Description:
Validate performs validation on the V2 request to ensure all required fields are present and have valid values. This should be called before sending the request to the trading service.
Inputs:
None (operates on receiver)
Outputs:
- error: nil if valid, error describing the validation failure otherwise
Example:
if err := req.Validate(); err != nil {
return fmt.Errorf("invalid trading request: %w", err)
}
Limitations:
- Does not validate strategy-specific parameters
- Does not verify InferenceRef IDs exist
Assumptions:
- Caller wants basic validation before API call
type TradingSignalRequester ¶
type TradingSignalRequester interface {
GetTicker() string
GetStrategyType() string
GetForecastPrice() float64
GetCurrentPrice() float64
GetCurrentPosition() float64
GetAvailableCash() float64
GetInitialCapital() float64
GetStrategyParams() map[string]interface{}
}
TradingSignalRequester defines the contract for trading signal requests.
Description:
TradingSignalRequester provides a common interface for both legacy (V1) and V2 trading signal requests, enabling polymorphic handling in the evaluator without knowing which version is being used.
Implementations:
- TradingSignalRequest (V1, legacy - no tracing)
- TradingSignalRequestV2 (V2, new - with inference tracing)
Example:
func processSignal(req TradingSignalRequester) {
ticker := req.GetTicker()
forecast := req.GetForecastPrice()
// Process regardless of V1 or V2
}
Limitations:
- Does not expose all fields (use type assertion for V2-specific fields)
- GetCurrentPrice may return nil for V1 if not set
Assumptions:
- All implementations provide valid, non-empty ticker
- Prices are positive values
type TradingSignalResponse ¶
type TradingSignalResponse struct {
Action string `json:"action"` // "buy", "sell", or "hold"
Size float64 `json:"size"` // Position size to execute
Value float64 `json:"value"` // Dollar value of trade
Reason string `json:"reason"` // Explanation
AvailableCash float64 `json:"available_cash"` // Cash after trade
PositionAfter float64 `json:"position_after"` // Position after trade
Stopped bool `json:"stopped"` // Strategy stopped flag
CurrentPrice float64 `json:"current_price"` // Current price used
ForecastPrice float64 `json:"forecast_price"` // Forecast price used
Ticker string `json:"ticker"` // Ticker symbol
}
TradingSignalResponse is the response from the trading service
type VerifiedPipelineConfig ¶
type VerifiedPipelineConfig struct {
TemperatureOverrides *TemperatureOverrides `json:"temperature_overrides,omitempty"`
Strictness string `json:"strictness,omitempty"` // "strict" or "balanced"
}
VerifiedPipelineConfig contains configuration options specific to the verified (skeptic/optimist) RAG pipeline.
Description ¶
This struct extends the standard RAG request with verified-pipeline-specific options like temperature overrides and strictness mode.
Fields ¶
- TemperatureOverrides: Per-role temperature settings (optional)
- Strictness: "strict" (cite every fact) or "balanced" (allow synthesis)
Examples ¶
config := &VerifiedPipelineConfig{
TemperatureOverrides: &TemperatureOverrides{Skeptic: ptr(0.1)},
Strictness: "strict",
}
type VerifiedStreamAnswer ¶
type VerifiedStreamAnswer struct {
Answer string `json:"answer"`
Sources []map[string]any `json:"sources,omitempty"`
IsVerified bool `json:"is_verified"`
}
VerifiedStreamAnswer is the final answer event from verified streaming.
Description ¶
This struct is sent in the "answer" SSE event after the verification process completes. It contains the final verified (or unverified) answer and the sources used.
Fields ¶
- Answer: The final answer text (may include verification warning).
- Sources: List of sources used to generate the answer.
- IsVerified: True if the answer passed skeptic verification.
Examples ¶
if !answer.IsVerified {
fmt.Println("Warning: Some claims could not be verified")
}
type VerifiedStreamError ¶
type VerifiedStreamError struct {
Error string `json:"error"`
}
VerifiedStreamError represents an error during verified streaming.
Description ¶
This struct is sent in the "error" SSE event if the pipeline fails. The stream will close after this event.
Fields ¶
- Error: Description of what went wrong.
type WeaviateConversationMemoryObject ¶
type WeaviateConversationMemoryObject struct {
Class string `json:"class"`
Properties ConversationProperties `json:"properties"`
Vector []float32 `json:"vector"`
}
type WeaviateObject ¶
type WeaviateObject struct {
Class string `json:"class"`
Properties CodeSnippetProperties `json:"properties"`
Vector []float32 `json:"vector"`
}
type WeaviateSchemas ¶
type WeaviateSchemas struct {
Schemas []struct {
Class string `json:"class"`
Description string `json:"description"`
Vectorizer string `json:"vectorizer"`
Properties []struct {
Name string `json:"name"`
DataType []string `json:"dataType"`
Description string `json:"description"`
} `json:"properties"`
} `json:"schemas"`
}
func (*WeaviateSchemas) InitializeSchemas ¶
func (w *WeaviateSchemas) InitializeSchemas()
type WeaviateSessionObject ¶
type WeaviateSessionObject struct {
Class string `json:"class"`
Properties SessionProperties `json:"properties"`
}