llm

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ChatContextVersionLegacy = 0
	ChatContextVersion2      = 2
)
View Source
const (
	JudgeNoul   = "noul"   // does this hold? -> probability of yes
	JudgeChoice = "choice" // which one? -> option id + distribution
	JudgeScore  = "score"  // how much? -> weighted position on ordered levels
)

Judgment question types. A judge vendor answers typed questions about a state and returns calibrated probabilities; it does not write text.

View Source
const (
	JudgeMediaText      = "text"
	JudgeMediaImage     = "image"
	JudgeMediaAudio     = "audio"
	JudgeMediaEmbedding = "embedding"
)

Judge state media kinds.

View Source
const (
	// MaxTokensSmall covers short structured replies: course descriptions,
	// detected language codes, a couple of extra questions, audio phrase picks.
	MaxTokensSmall = 8_000
	// MaxTokensPlan covers list-shaped plans: lesson lists, course ladders, deck plans.
	MaxTokensPlan = 16_000
	// MaxTokensTheory covers one lesson's HTML theory (prompts ask for ~1-4k characters).
	MaxTokensTheory = 16_000
	// MaxTokensLarge covers the big structured payloads: exercises with questions,
	// stepping JSON, phrase banks, placement tests.
	MaxTokensLarge = 32_000
	// MaxTokensCombined covers the vocab single-call path that returns bank,
	// theory, stepping and exercises together.
	MaxTokensCombined = 48_000
)

Output ceilings for generation calls. Output tokens cost ~8x input on the expensive tier ($10.00 vs $1.25 per 1M), so an unbounded generation is the costliest failure mode in the service. These bound the tail; they are not sized to the length each prompt asks for.

The reason they look so generous: thinking tokens are charged against the same budget, thinking is on by default for every Gemini 2.5/3.x model in the collection, and a thinking budget alone can reach tens of thousands of tokens. A ceiling near the actual answer length would be spent entirely on thinking and return nothing. Each tier therefore has to cover thinking plus the answer, and the adapters retry uncapped if a ceiling is exhausted anyway.

Bounding thinking directly (ThinkingConfig.ThinkingBudget) would be the sharper lever, but this SDK exposes only ThinkingBudget while Gemini 3 documents thinking_level, so support is unverified — sending an unsupported value risks 400-ing every generation call. Validate against the live API before adding it.

Variables

View Source
var ErrEmbeddingUnsupported = errors.New("embeddings not supported by this adapter")

ErrEmbeddingUnsupported marks an adapter that cannot produce text embeddings.

View Source
var ErrImageGenerationUnsupported = errors.New("image generation not supported by this adapter")

ErrImageGenerationUnsupported marks an adapter with no native image model.

View Source
var ErrJudgmentUnsupported = errors.New("judgment not supported by this adapter")

ErrJudgmentUnsupported marks an adapter with no judgment model.

View Source
var ErrNoAudioContent = errors.New("no audio in TTS response")

ErrNoAudioContent marks a TTS reply that arrived intact but carried no audio — the preview models answer 200 with text instead. Retryable on purpose: it is transient per call, and treating it as terminal stops the chain from ever reaching another vendor.

View Source
var ErrOutputTruncated = errors.New("output truncated: hit max output tokens")

ErrOutputTruncated means the vendor ran out of output budget even with no ceiling of ours in play — the adapters lift theirs and retry before surfacing this, so reaching it means the model's own limit was hit. Deliberately not retryable: the same prompt hits the same wall, so retrying burns the full prompt cost on a doomed call. Callers see a failed task instead of a half-written JSON payload silently reaching the database.

View Source
var ErrSchemaViolation = errors.New("response does not match the requested schema")

ErrSchemaViolation marks a reply that parsed as JSON but does not match the requested schema. Separate from a parse failure so callers can tell "not JSON at all" from "JSON of the wrong shape" in logs.

View Source
var ErrStreamingNotSupported = errors.New("streaming not supported")

Functions

func CheckResponseSchema

func CheckResponseSchema(raw string, schema *ResponseSchema) error

CheckResponseSchema validates a model's raw reply against the schema the caller asked for. It exists for vendors whose API cannot enforce a schema (DeepSeek among them): the proxy asks for JSON in the prompt, then verifies the shape here rather than handing an unchecked document to the caller.

Checked: types, required keys, array element shape, enum values and, where the schema sets additionalProperties false, unknown keys. Descriptions and format are hints for the vendor and are not enforced here.

func CheckToolCalls added in v0.13.1

func CheckToolCalls(calls []*ToolCall, tools []*Tool) error

CheckToolCalls validates each call's arguments against the parameters of the tool it names, so a malformed call is caught like a malformed reply.

func CopyBool added in v0.13.1

func CopyBool(b *bool) *bool

CopyBool copies an optional flag so the copy can change independently.

func EstimateOutputTokens

func EstimateOutputTokens(runes int) int

EstimateOutputTokens estimates output tokens from character or rune count.

func ExtractHTTPStatusCode

func ExtractHTTPStatusCode(err error) (int, bool)

ExtractHTTPStatusCode resolves HTTP status codes across supported provider SDKs.

func IsCapacityExhausted

func IsCapacityExhausted(err error) bool

IsCapacityExhausted reports whether err signals local capacity or queue saturation.

func IsContentFilterError

func IsContentFilterError(err error) bool

IsContentFilterError reports whether err indicates an Azure or vendor content filter block.

func IsRetryableError

func IsRetryableError(err error) bool

IsRetryableError returns true if the error is from an LLM API and has a retryable HTTP status code (429 Too Many Requests or 5xx server errors), or is a transport failure (reset, refused, EOF on a reused connection) that never got a status.

func IsShadowTraffic

func IsShadowTraffic(ctx context.Context) bool

IsShadowTraffic checks if context is marked as shadow traffic.

func IsTransportFailure added in v0.13.1

func IsTransportFailure(err error) bool

IsTransportFailure covers what vendor SDKs used to retry on their own: the connection failed before a status arrived. Caller cancellations, DNS misses and TLS verification failures are excluded: retrying them cannot help.

func ParseRetryAfter added in v0.13.1

func ParseRetryAfter(h http.Header, now time.Time) (time.Duration, bool)

ParseRetryAfter reads retry-after-ms (OpenAI, Azure) before the standard Retry-After header, which is either delay-seconds or an HTTP date.

func RemoveMarkdownCodeBlocks

func RemoveMarkdownCodeBlocks(text string) string

RemoveMarkdownCodeBlocks removes markdown code blocks from a text string. It handles various formats including ```json, ```, and closing backticks that may be on the same line or a separate line.

func RetryAfter added in v0.13.1

func RetryAfter(err error) (time.Duration, bool)

RetryAfter returns how long the vendor asked callers to wait, read from a 429 or 503 reply: the Retry-After headers of OpenAI-compatible and Anthropic APIs, or the google.rpc.RetryInfo detail of Gemini. Other statuses carry no promise.

func SchemaPromptInstruction

func SchemaPromptInstruction(schema *ResponseSchema) string

SchemaPromptInstruction describes the wanted shape in words, for models that cannot be handed a schema through the API. Appended to the system instruction so the reply is JSON in the first place.

func ShouldSkipToNextModel

func ShouldSkipToNextModel(err error) bool

ShouldSkipToNextModel reports whether err or any wrapped error indicates that the chain should advance to the next candidate model immediately.

func TruncatedError

func TruncatedError(vendor, model string, producedChars int) error

TruncatedError builds the error both adapters return when a generation stops on its output ceiling, so the ceiling that needs raising is named in the log line.

func VendorHTTPClient added in v0.13.1

func VendorHTTPClient() *http.Client

VendorHTTPClient is the shared client for calls to model vendors and local nodes, so every adapter reuses one connection pool. It sets no timeout: callers bound each call with their context.

func WithShadowTraffic

func WithShadowTraffic(ctx context.Context) context.Context

WithShadowTraffic marks context as shadow/evaluation traffic.

Types

type BatchAdapter

type BatchAdapter interface {
	SubmitBatch(ctx context.Context, batchID string, items []*BatchSubmitItem) (vendorJobID string, err error)
	GetBatch(ctx context.Context, vendorJobID string) (*BatchJobStatus, error)
	CancelBatch(ctx context.Context, vendorJobID string) error
	FetchBatchResults(ctx context.Context, vendorJobID string, items []*BatchSubmitItem) ([]*BatchItemResult, error)
}

BatchAdapter is the generic interface for batch generation vendors.

type BatchItemError

type BatchItemError struct {
	Code    int32  `json:"code"`
	Reason  string `json:"reason"`
	Message string `json:"message"`
}

BatchItemError represents an error for one item in a batch.

func NewBatchItemError

func NewBatchItemError(code codes.Code, reason, message string) *BatchItemError

NewBatchItemError builds a BatchItemError from a standard gRPC status code.

func (*BatchItemError) JSON

func (e *BatchItemError) JSON() []byte

JSON serializes the error for storage.

type BatchItemResult

type BatchItemResult struct {
	CustomID string
	Response *Response
	Error    *BatchItemError
}

BatchItemResult is the outcome of one item in a completed batch.

type BatchJobStatus

type BatchJobStatus struct {
	State       string // PENDING, RUNNING, SUCCEEDED, FAILED, CANCELLED, EXPIRED
	TotalCount  int32
	DoneCount   int32
	FailedCount int32
	CompletedAt *time.Time
	Error       string
}

BatchJobStatus is the vendor status for a batch job.

type BatchSubmitItem

type BatchSubmitItem struct {
	CustomID string
	Chat     *ChatContext
}

BatchSubmitItem is one request in a batch submission.

type Caller

type Caller struct {
	UserID string
	Meta   map[string]string
}

Caller attributes an LLM request for usage tracking: the internal user id plus optional metadata forwarded to usage events (e.g. batch job and task ids, so token expense can be aggregated per job).

type CandidateEvaluation

type CandidateEvaluation struct {
	ID             string
	Answers        map[string]*JudgeAnswer
	CompositeScore float64
	Rank           int
}

CandidateEvaluation holds evaluation answers, rank, and composite score.

type CapacityExhausted

type CapacityExhausted interface {
	CapacityExhausted() bool
}

CapacityExhausted marks errors caused by local queue or pool saturation. These bypass circuit breaker failure accounting and skip to fallback models.

type ChatContext

type ChatContext struct {
	Version int // Version for backward compatibility (0 = legacy, 2 = new format)
	ChatID  int64
	UserID  int64

	ActionID      string // Action ID for usage tracking (e.g., "exercise.generate_question")
	MessagesLimit int

	BaseSystemInstruction string // Persistent system instructions (not in messages)
	// contains filtered or unexported fields
}

func NewChatContext

func NewChatContext() *ChatContext

func (*ChatContext) AddAssistantMessage

func (c *ChatContext) AddAssistantMessage(message string)

func (*ChatContext) AddAssistantMessageWithToolCalls

func (c *ChatContext) AddAssistantMessageWithToolCalls(message string, toolCalls []*ToolCall)

func (*ChatContext) AddSystemMessage

func (c *ChatContext) AddSystemMessage(message string)

func (*ChatContext) AddToolMessage

func (c *ChatContext) AddToolMessage(toolCallID, text string)

func (*ChatContext) AddUserMessage

func (c *ChatContext) AddUserMessage(message string)

func (*ChatContext) AddUserMessageWithParts

func (c *ChatContext) AddUserMessageWithParts(text string, parts []*ContentPart)

func (*ChatContext) ClearMessages

func (c *ChatContext) ClearMessages()

func (*ChatContext) ClearNotProtectedMessages

func (c *ChatContext) ClearNotProtectedMessages()

func (*ChatContext) Clone

func (c *ChatContext) Clone() *ChatContext

Clone creates an isolated copy of the context so async background operations like shadow routing can modify metadata without data races.

func (*ChatContext) Context

func (c *ChatContext) Context() context.Context

Context returns the request context associated with this chat, or context.Background().

func (*ChatContext) CutMessages

func (c *ChatContext) CutMessages(maximumLength int)

func (*ChatContext) EstimateInputTokens

func (c *ChatContext) EstimateInputTokens() int

EstimateInputTokens estimates input tokens based on runes in instructions and messages, plus heuristic token allowances for media parts.

func (*ChatContext) GetActionID

func (c *ChatContext) GetActionID() string

GetActionID returns the action ID for usage tracking

func (*ChatContext) GetBaseSystemInstruction

func (c *ChatContext) GetBaseSystemInstruction() string

GetBaseSystemInstruction returns the persistent base system instruction

func (*ChatContext) GetInternalUserID

func (c *ChatContext) GetInternalUserID() string

GetInternalUserID returns the user ID as a string (UUID) for usage tracking

func (*ChatContext) GetMaxOutputTokens

func (c *ChatContext) GetMaxOutputTokens() int

GetMaxOutputTokens returns the output ceiling, or 0 when the caller set none.

func (*ChatContext) GetMessages

func (c *ChatContext) GetMessages() []*Message

func (*ChatContext) GetMeta

func (c *ChatContext) GetMeta() map[string]string

GetMeta returns the metadata attached to usage events for this chat.

func (*ChatContext) GetRequestInstruction

func (c *ChatContext) GetRequestInstruction() string

GetRequestInstruction returns the current per-request instruction and clears it

func (*ChatContext) GetResponseSchema

func (c *ChatContext) GetResponseSchema() *ResponseSchema

func (*ChatContext) GetToolChoice

func (c *ChatContext) GetToolChoice() *ToolChoice

func (*ChatContext) GetTools

func (c *ChatContext) GetTools() []*Tool

func (*ChatContext) GobDecode

func (c *ChatContext) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface for ChatContext

func (*ChatContext) GobEncode

func (c *ChatContext) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface for ChatContext

func (*ChatContext) GoogleSearchEnabled

func (c *ChatContext) GoogleSearchEnabled() bool

GoogleSearchEnabled reports whether search grounding was requested.

func (*ChatContext) MarshalBinary

func (c *ChatContext) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface for ChatContext using Gob and a type alias.

func (*ChatContext) PeekRequestInstruction

func (c *ChatContext) PeekRequestInstruction() string

PeekRequestInstruction returns the current per-request instruction without clearing it.

func (*ChatContext) RemoveLastMessages

func (c *ChatContext) RemoveLastMessages(count int)

RemoveLastMessages removes the last N non-protected messages from the context This is useful for cleanup when an operation fails after adding messages Protected messages are preserved and will not be removed

func (*ChatContext) RewriteMessages

func (c *ChatContext) RewriteMessages(fn func(m *Message))

RewriteMessages applies an in-place transform to each message in the context.

func (*ChatContext) SetActionID

func (c *ChatContext) SetActionID(actionID string)

SetActionID sets the action ID for usage tracking

func (*ChatContext) SetBaseSystemInstruction

func (c *ChatContext) SetBaseSystemInstruction(instruction string)

SetBaseSystemInstruction updates the persistent base system instruction

func (*ChatContext) SetCaller

func (c *ChatContext) SetCaller(caller Caller)

SetCaller sets usage attribution in one call: the internal user id plus the usage-event metadata.

func (*ChatContext) SetEnableGoogleSearch

func (c *ChatContext) SetEnableGoogleSearch()

SetEnableGoogleSearch asks for Google Search grounding on this request. Advisory: adapters without a search tool ignore it, so callers wanting fresh facts should route to a Google candidate explicitly.

func (*ChatContext) SetInternalUserID

func (c *ChatContext) SetInternalUserID(userID string)

SetInternalUserID sets the user ID string (UUID) for usage tracking

func (*ChatContext) SetMaxOutputTokens

func (c *ChatContext) SetMaxOutputTokens(max int)

SetMaxOutputTokens caps generated tokens for this chat. Output costs ~8x input on the expensive tier, so every generation call should set a ceiling generous enough to never clip valid content — it exists to stop runaways, not to shape output.

func (*ChatContext) SetMeta

func (c *ChatContext) SetMeta(meta map[string]string)

SetMeta attaches metadata to every usage event recorded for this chat (e.g. job/task ids). Keep it small — it is stored per event.

func (*ChatContext) SetRequestInstruction

func (c *ChatContext) SetRequestInstruction(instruction string)

SetRequestInstruction sets a per-request system instruction that applies only to the next GenerateText call This instruction is ephemeral and will be cleared after use. It does not persist to Redis.

func (*ChatContext) SetResponseSchema

func (c *ChatContext) SetResponseSchema(schema *ResponseSchema)

func (*ChatContext) SetToolChoice

func (c *ChatContext) SetToolChoice(tc *ToolChoice)

func (*ChatContext) SetTools

func (c *ChatContext) SetTools(tools []*Tool)

func (*ChatContext) UnmarshalBinary

func (c *ChatContext) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface for ChatContext using Gob and a type alias.

func (*ChatContext) UpgradeFromLegacy

func (c *ChatContext) UpgradeFromLegacy()

UpgradeFromLegacy upgrades a legacy ChatContext (version 0) to version 2 format It extracts system messages from the messages array and moves them to BaseSystemInstruction

func (*ChatContext) WithContext

func (c *ChatContext) WithContext(ctx context.Context) *ChatContext

WithContext associates a request context with this chat.

type ClientAdapter

type ClientAdapter interface {
	GenerateText(ctx context.Context, chat *ChatContext) (*Response, error)
}

ClientAdapter is the proxy's slice of the shared adapter interface: text generation only. Files and transcription stay in the client services, whose download URLs carry credentials the proxy must not see.

type ContentPart

type ContentPart struct {
	Type     ContentPartType
	Text     string
	MimeType string
	Data     []byte
	URL      string
	Detail   ImageDetail
	Format   string
	FileName string
}

type ContentPartType

type ContentPartType string
const (
	ContentPartTypeText     ContentPartType = "text"
	ContentPartTypeImage    ContentPartType = "image"
	ContentPartTypeAudio    ContentPartType = "audio"
	ContentPartTypeDocument ContentPartType = "document"
)

type EmbeddingAdapter

type EmbeddingAdapter interface {
	CreateEmbeddings(ctx context.Context, req *EmbeddingRequest, userID string, meta map[string]string) (*EmbeddingResult, error)
}

EmbeddingAdapter is an optional adapter capability, discovered by type assertion.

type EmbeddingItem

type EmbeddingItem struct {
	Index  int
	Values []float32
}

EmbeddingItem is one vector embedding corresponding to an input item.

type EmbeddingRequest

type EmbeddingRequest struct {
	Inputs     []string
	Model      string
	Dimensions int
	InputType  string // "query" | "document"
	ActionID   string
}

EmbeddingRequest is one call's worth of text embeddings.

type EmbeddingResult

type EmbeddingResult struct {
	Data  []EmbeddingItem
	Model string
	Usage TokensUsage
}

EmbeddingResult holds the computed vector embeddings and token usage.

type EvaluateRolloutsRequest

type EvaluateRolloutsRequest struct {
	StateJSON  string
	StateMedia []*JudgeMediaPart
	Candidates []*RolloutCandidate
	Criteria   map[string]*JudgeQuestion
	ActionID   string
}

EvaluateRolloutsRequest evaluates multiple candidate rollouts against state and criteria.

type EvaluateRolloutsResult

type EvaluateRolloutsResult struct {
	Evaluations     []*CandidateEvaluation
	BestCandidateID string
	Model           string
	Usage           TokensUsage
}

EvaluateRolloutsResult is the outcome of candidate rollouts evaluation.

type FunctionCall

type FunctionCall struct {
	Name      string
	Arguments string
}

FunctionCall represents the function name and arguments requested.

type FunctionDefinition

type FunctionDefinition struct {
	Name        string
	Description string
	Parameters  *ResponseSchema
	Strict      bool
}

FunctionDefinition defines a callable function.

type HTTPStatusError

type HTTPStatusError interface {
	error
	HTTPStatus() int
}

HTTPStatusError is any vendor error carrying a raw HTTP status — the hand -rolled adapters implement it so retryability stays in one place.

type ImageDetail

type ImageDetail string
const (
	ImageDetailAuto ImageDetail = "auto"
	ImageDetailLow  ImageDetail = "low"
	ImageDetailHigh ImageDetail = "high"
)

type ImageGenerator

type ImageGenerator interface {
	GenerateImage(ctx context.Context, prompt, userID string, meta map[string]string) (*ImageResult, error)
}

ImageGenerator is an optional adapter capability, discovered by type assertion so the ClientAdapter contract stays untouched. meta carries usage attribution (e.g. genjob ids), like SynthesizeSpeech.

type ImageResult

type ImageResult struct {
	Data     []byte
	MimeType string      // e.g. "image/png"
	Model    string      // the image model actually used (not the chat model)
	Usage    TokensUsage // zero when the vendor reports no token accounting
}

ImageResult is one generated image.

type Judge

type Judge interface {
	Judge(ctx context.Context, req *JudgeRequest, userID string, meta map[string]string) (*JudgeResult, error)
}

Judge is an optional adapter capability, discovered by type assertion so the ClientAdapter contract stays untouched. meta carries usage attribution, like SynthesizeSpeech and GenerateImage.

Unlike the other modalities this one takes a context: a judgment is a decision on someone's request path, and when that caller gives up the vendor call should stop rather than run on and be billed for an answer nobody reads.

type JudgeAnswer

type JudgeAnswer struct {
	Type          string
	Choice        string
	Noul          float64
	Score         float64
	Probabilities map[string]float64
	Confidence    float64
	Legend        map[string]string
}

JudgeAnswer is one question's typed answer. Noul carries a probability; choice and score carry a distribution plus how concentrated it is.

type JudgeMediaPart

type JudgeMediaPart struct {
	Type     string
	Text     string
	MimeType string
	Data     []byte
	URL      string // https only; forwarded to the vendor, never fetched
	Detail   string // image: "auto", "low", "high"
	Format   string // audio: "wav", "mp3"
	// Embedding is a latent vector; EmbeddingModel names the encoder so a
	// vendor can reject a space it was not trained on.
	Embedding      []float32
	EmbeddingModel string
}

JudgeMediaPart is one piece of multimodal judge state. Which fields carry meaning depends on Type, as with JudgeQuestion.

type JudgeQuestion

type JudgeQuestion struct {
	Type          string
	Instructions  string
	Options       map[string]string
	Levels        []string
	TrueCriteria  string
	FalseCriteria string
}

JudgeQuestion is one typed question. Which fields carry meaning depends on Type: Options for choice, Levels for score, the criteria pair for noul.

type JudgeRequest

type JudgeRequest struct {
	// StateJSON is the caller's state, already encoded. Vendors take it
	// verbatim, so the proxy never reshapes it.
	StateJSON string
	// StateMedia is multimodal state judged alongside StateJSON. Adapters that
	// cannot forward a part must refuse the call rather than judge without it.
	StateMedia []*JudgeMediaPart
	Questions  map[string]*JudgeQuestion
	// ActionID attributes the call in usage, as ChatContext does for text.
	ActionID string
}

JudgeRequest is one call's worth of judgment. Every question is answered against the same state, in parallel and for one state's worth of tokens.

type JudgeResult

type JudgeResult struct {
	Answers map[string]*JudgeAnswer
	Model   string      // the judge model actually used
	Usage   TokensUsage // judge vendors bill input only, so Output is usually 0
}

JudgeResult is one judgment call's outcome.

type Message

type Message struct {
	Text         string
	Type         MessageType
	ToolCalls    []*ToolCall
	ToolCallID   string
	FinishReason string
	Parts        []*ContentPart
}

type MessageType

type MessageType string
const (
	MessageTypeSystem MessageType = "system"
	MessageTypeUser   MessageType = "user"
	MessageTypeBot    MessageType = "bot"
	MessageTypeTool   MessageType = "tool"
)

type NoOpUsageTracker

type NoOpUsageTracker struct{}

NoOpUsageTracker is a usage tracker that does nothing (for when usage collection is disabled)

func (*NoOpUsageTracker) RecordUsage

func (n *NoOpUsageTracker) RecordUsage(userID, actionID, vendor, model string, usage TokensUsage, durationMs, costNanoUSD int64, status usagev1.Status, meta map[string]string) error

type Response

type Response struct {
	Choices []*Message
	Usage   TokensUsage
}

func (*Response) AddMessage

func (r *Response) AddMessage(message *Message)

type ResponseSchema

type ResponseSchema struct {
	Type                 SchemaPropertyType         `json:"type"`
	Properties           map[string]*SchemaProperty `json:"properties"`
	Items                *SchemaProperty            `json:"items,omitempty"`
	Required             []string                   `json:"required,omitempty"`
	AdditionalProperties *bool                      `json:"additionalProperties,omitempty"`
}

func EnforceAllRequired

func EnforceAllRequired(schema *ResponseSchema) *ResponseSchema

EnforceAllRequired returns a copy of the schema in which every object-level field is required, recursively (strict structured-output modes demand it). The input is left untouched: it is shared by every model in the chain.

func (*ResponseSchema) Clone added in v0.13.1

func (s *ResponseSchema) Clone() *ResponseSchema

Clone deep-copies the schema so adapters can adjust it for one vendor without changing what the rest of the chain, and the reply check, see.

func (*ResponseSchema) Property added in v0.13.1

func (s *ResponseSchema) Property() *SchemaProperty

Property views the top level as a property, for code that walks both alike.

type RolloutCandidate

type RolloutCandidate struct {
	ID          string
	ActionJSON  string
	ActionMedia []*JudgeMediaPart
	ActionText  string
}

RolloutCandidate is one candidate action or branch in speculative evaluation.

type RolloutJudge

type RolloutJudge interface {
	EvaluateRollouts(ctx context.Context, req *EvaluateRolloutsRequest, userID string, meta map[string]string) (*EvaluateRolloutsResult, error)
}

RolloutJudge is an optional capability for adapters supporting native batch rollout scoring.

type SchemaProperty

type SchemaProperty struct {
	Type        SchemaPropertyType         `json:"type"`
	Description string                     `json:"description,omitempty"`
	Properties  map[string]*SchemaProperty `json:"properties,omitempty"` // For object types
	Items       *SchemaProperty            `json:"items,omitempty"`      // For array types
	Required    []string                   `json:"required,omitempty"`   // Required fields for object types
	Nullable    bool                       `json:"nullable,omitempty"`   // If true, allows null values (type becomes ["type", "null"] in JSON Schema)
	Enum        []string                   `json:"enum,omitempty"`       // Allowed values for string types
	Format      string                     `json:"format,omitempty"`     // e.g. "date-time", "email", "uuid"
	// AdditionalProperties false forbids keys beyond Properties; nil leaves them allowed.
	AdditionalProperties *bool `json:"additionalProperties,omitempty"`
}

func (*SchemaProperty) Clone added in v0.13.1

func (p *SchemaProperty) Clone() *SchemaProperty

Clone deep-copies the property.

type SchemaPropertyType

type SchemaPropertyType string
const (
	SchemaPropertyTypeString  SchemaPropertyType = "string"
	SchemaPropertyTypeInteger SchemaPropertyType = "integer"
	SchemaPropertyTypeNumber  SchemaPropertyType = "number"
	SchemaPropertyTypeBoolean SchemaPropertyType = "boolean"
	SchemaPropertyTypeObject  SchemaPropertyType = "object"
	SchemaPropertyTypeArray   SchemaPropertyType = "array"
)

type SkipToNextModel

type SkipToNextModel interface {
	error
	SkipToNextModel() bool
}

SkipToNextModel is implemented by errors that should bypass model-level retries and immediately advance to the next model in the fallback chain (e.g. pool capacity exhausted).

type SpeechResult

type SpeechResult struct {
	Audio      []byte      // OGG/Opus bytes (chat voice-message format)
	MimeType   string      // e.g. "audio/ogg"
	DurationMs int         // 0 when unknown (e.g. the OpenAI path)
	Model      string      // the TTS model actually used (not the chat model)
	Usage      TokensUsage // zero when the vendor reports no token accounting
}

SpeechResult is one synthesized clip.

type SpeechSynthesizer

type SpeechSynthesizer interface {
	SynthesizeSpeech(ctx context.Context, text, language, userID string, meta map[string]string) (*SpeechResult, error)
}

SpeechSynthesizer is an optional adapter capability, discovered by type assertion so the ClientAdapter contract stays untouched.

type StreamAdapter

type StreamAdapter interface {
	GenerateTextStream(ctx context.Context, chat *ChatContext, onChunk func(StreamChunk) error) error
}

StreamAdapter is an optional adapter capability for incremental text generation streaming.

type StreamChunk

type StreamChunk struct {
	Delta          string
	FinishReason   string
	Usage          *TokensUsage
	ToolCallChunks []*ToolCallChunk
}

StreamChunk is one incremental delta from a streaming model call.

type ThrottleControl

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

ThrottleControl manages up to `limit` requests per `timeWindow` seconds. If you call WaitForSlot() (instead of CanMakeRequest()), it will block until a new request can be “taken” without exceeding the limit.

func NewThrottleControl

func NewThrottleControl(limit int, timeWindowSeconds int) *ThrottleControl

func (*ThrottleControl) WaitForSlot

func (tc *ThrottleControl) WaitForSlot()

WaitForSlot will block until you are allowed to record a new request. Once it returns, a new timestamp has already been taken for you.

type TokensUsage

type TokensUsage struct {
	Input  int
	Output int
	// Prompt-cache tokens, both part of Input: read from the vendor's cache and
	// written to it. Vendors bill each at its own rate.
	CacheRead  int
	CacheWrite int
}

func (TokensUsage) Add added in v1.0.0

Add sums two usages field by field, as attempts billed one after another.

func (TokensUsage) Clamped added in v1.0.0

func (u TokensUsage) Clamped() TokensUsage

Clamped bounds the counts to their meaning: none negative, and the cache parts within Input. Pricing and usage events both rely on it.

type Tool

type Tool struct {
	Type     string
	Function FunctionDefinition
}

Tool represents an external tool callable by the model.

type ToolCall

type ToolCall struct {
	ID       string
	Type     string
	Function FunctionCall
}

ToolCall represents a specific tool call returned by the model.

type ToolCallChunk

type ToolCallChunk struct {
	Index          int32
	ID             string
	Type           string
	Name           string
	ArgumentsDelta string
}

ToolCallChunk represents a streamed chunk of a tool call.

type ToolChoice

type ToolChoice struct {
	Mode                 string // "auto", "none", "required", "specific"
	SpecificFunctionName string
}

ToolChoice steers how the model chooses tools.

type UsageTracker

type UsageTracker interface {
	// RecordUsage records a usage event asynchronously
	// Returns an error if validation fails or if the event cannot be queued for sending
	// userID is the UUID of the user making the request
	// actionID identifies the LLM action (e.g., "generate_question", "evaluate_solution")
	// vendor is the LLM vendor (e.g., "openai", "google")
	// model is the model name (e.g., "gpt-5", "gemini-2.5-pro")
	// usage is the tokens billed, input including its prompt-cache part
	// durationMs is the request duration in milliseconds
	// costNanoUSD is the call's price in nano-USD (1e-9 USD), 0 when unpriced
	// status is the request status (success, error, etc.)
	// meta is optional metadata stored on the event (keep small)
	RecordUsage(
		userID string,
		actionID string,
		vendor string,
		model string,
		usage TokensUsage,
		durationMs int64,
		costNanoUSD int64,
		status usagev1.Status,
		meta map[string]string,
	) error
}

UsageTracker is an interface for tracking LLM usage events

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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