Documentation
¶
Index ¶
- Constants
- Variables
- func CheckResponseSchema(raw string, schema *ResponseSchema) error
- func CheckToolCalls(calls []*ToolCall, tools []*Tool) error
- func CopyBool(b *bool) *bool
- func EstimateOutputTokens(runes int) int
- func ExtractHTTPStatusCode(err error) (int, bool)
- func IsCapacityExhausted(err error) bool
- func IsContentFilterError(err error) bool
- func IsRetryableError(err error) bool
- func IsShadowTraffic(ctx context.Context) bool
- func IsTransportFailure(err error) bool
- func JSONText(raw json.RawMessage) string
- func LanguageName(tag string) string
- func MapJSONStrings(raw json.RawMessage, fn func(string) (string, error)) (json.RawMessage, error)
- func ParseRetryAfter(h http.Header, now time.Time) (time.Duration, bool)
- func RemoveMarkdownCodeBlocks(text string) string
- func RetryAfter(err error) (time.Duration, bool)
- func SchemaPromptInstruction(schema *ResponseSchema) string
- func ShouldSkipToNextModel(err error) bool
- func SourceCharacters(texts []string) int
- func TruncatedError(vendor, model string, producedChars int) error
- func VendorHTTPClient() *http.Client
- func WithShadowTraffic(ctx context.Context) context.Context
- type BatchAdapter
- type BatchItemError
- type BatchItemResult
- type BatchJobStatus
- type BatchSubmitItem
- type Box
- type Caller
- type CandidateEvaluation
- type CapacityExhausted
- type ChatContext
- func (c *ChatContext) AddAssistantMessage(message string)
- func (c *ChatContext) AddAssistantMessageWithToolCalls(message string, toolCalls []*ToolCall)
- func (c *ChatContext) AddSystemMessage(message string)
- func (c *ChatContext) AddToolMessage(toolCallID, text string)
- func (c *ChatContext) AddUserMessage(message string)
- func (c *ChatContext) AddUserMessageWithParts(text string, parts []*ContentPart)
- func (c *ChatContext) ClearMessages()
- func (c *ChatContext) ClearNotProtectedMessages()
- func (c *ChatContext) Clone() *ChatContext
- func (c *ChatContext) Context() context.Context
- func (c *ChatContext) CutMessages(maximumLength int)
- func (c *ChatContext) EstimateInputTokens() int
- func (c *ChatContext) GetActionID() string
- func (c *ChatContext) GetBaseSystemInstruction() string
- func (c *ChatContext) GetInternalUserID() string
- func (c *ChatContext) GetMaxOutputTokens() int
- func (c *ChatContext) GetMessages() []*Message
- func (c *ChatContext) GetMeta() map[string]string
- func (c *ChatContext) GetRequestInstruction() string
- func (c *ChatContext) GetResponseSchema() *ResponseSchema
- func (c *ChatContext) GetSampling() Sampling
- func (c *ChatContext) GetToolChoice() *ToolChoice
- func (c *ChatContext) GetTools() []*Tool
- func (c *ChatContext) GobDecode(data []byte) error
- func (c *ChatContext) GobEncode() ([]byte, error)
- func (c *ChatContext) GoogleSearchEnabled() bool
- func (c *ChatContext) MarshalBinary() ([]byte, error)
- func (c *ChatContext) PeekRequestInstruction() string
- func (c *ChatContext) RemoveLastMessages(count int)
- func (c *ChatContext) RewriteMessages(fn func(m *Message))
- func (c *ChatContext) SetActionID(actionID string)
- func (c *ChatContext) SetBaseSystemInstruction(instruction string)
- func (c *ChatContext) SetCaller(caller Caller)
- func (c *ChatContext) SetEnableGoogleSearch()
- func (c *ChatContext) SetInternalUserID(userID string)
- func (c *ChatContext) SetMaxOutputTokens(max int)
- func (c *ChatContext) SetMeta(meta map[string]string)
- func (c *ChatContext) SetRequestInstruction(instruction string)
- func (c *ChatContext) SetResponseSchema(schema *ResponseSchema)
- func (c *ChatContext) SetSampling(s Sampling)
- func (c *ChatContext) SetToolChoice(tc *ToolChoice)
- func (c *ChatContext) SetTools(tools []*Tool)
- func (c *ChatContext) UnmarshalBinary(data []byte) error
- func (c *ChatContext) UpgradeFromLegacy()
- func (c *ChatContext) WithContext(ctx context.Context) *ChatContext
- type ClientAdapter
- type ContentPart
- type ContentPartType
- type EmbeddingAdapter
- type EmbeddingItem
- type EmbeddingRequest
- type EmbeddingResult
- type EvaluateRolloutsRequest
- type EvaluateRolloutsResult
- type FunctionCall
- type FunctionDefinition
- type HTTPStatusError
- type ImageDetail
- type ImageGenerator
- type ImageResult
- type InvalidMediaError
- type Judge
- type JudgeAnswer
- type JudgeMediaChecker
- type JudgeMediaPart
- type JudgeQuestion
- type JudgeRequest
- type JudgeResult
- type Message
- type MessageType
- type NoOpUsageTracker
- type Response
- type ResponseSchema
- type RolloutCandidate
- type RolloutJudge
- type Sampling
- type SamplingSupport
- type SchemaProperty
- type SchemaPropertyType
- type SerialJudge
- type SkipToNextModel
- type SpeechResult
- type SpeechSynthesizer
- type StreamAdapter
- type StreamChunk
- type ThrottleControl
- type TokensUsage
- type Tool
- type ToolCall
- type ToolCallChunk
- type ToolChoice
- type TranslateRequest
- type TranslateResult
- type Translation
- type TranslationMismatchError
- type Translator
- type UsageTracker
Constants ¶
const ( ChatContextVersionLegacy = 0 ChatContextVersion2 = 2 )
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 JudgeBox = "box" // where is it? -> one box on an image of the state )
Judgment question types. A judge vendor answers typed questions about a state and returns calibrated probabilities; it does not write text.
const ( JudgeMediaText = "text" JudgeMediaImage = "image" JudgeMediaAudio = "audio" JudgeMediaEmbedding = "embedding" )
Judge state media kinds.
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.
const ( ParamTemperature = "temperature" ParamTopP = "top_p" ParamStop = "stop" ParamSeed = "seed" )
Sampling parameter names, as callers send them and responses report them.
const ( TranslateFormatText = "text" TranslateFormatHTML = "html" )
Translate formats. HTML keeps tags and attributes and translates text only.
Variables ¶
var AllSampling = SamplingSupport{Temperature: true, TopP: true, Stop: true, Seed: true}
AllSampling is an OpenAI-style API that takes every field.
var ErrContentBlocked = errors.New("content blocked by the vendor's safety filter")
ErrContentBlocked marks a vendor's safety refusal of the request's content. Another judge may answer; when none does, retrying the same request will not help.
var ErrEmbeddingUnsupported = errors.New("embeddings not supported by this adapter")
ErrEmbeddingUnsupported marks an adapter that cannot produce text embeddings.
var ErrImageGenerationUnsupported = errors.New("image generation not supported by this adapter")
ErrImageGenerationUnsupported marks an adapter with no native image model.
var ErrInvalidMedia = errors.New("invalid media")
ErrInvalidMedia marks judge state media a vendor would refuse as it stands (format, size, orientation): the caller's to fix, so not a vendor failure.
var ErrJudgeTooLarge = errors.New("judgment exceeds the model's context")
ErrJudgeTooLarge marks a judgment beyond the model's context window: the caller's to split, so not a vendor failure and no reason to try another model.
var ErrJudgmentUnsupported = errors.New("judgment not supported by this adapter")
ErrJudgmentUnsupported marks an adapter with no judgment model.
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.
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.
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.
var ErrStreamingNotSupported = errors.New("streaming not supported")
var ErrTranslationUnsupported = errors.New("translation not supported by this adapter")
ErrTranslationUnsupported marks an adapter that cannot translate.
var ErrUnsupportedLanguagePair = errors.New("unsupported_language_pair")
ErrUnsupportedLanguagePair marks an engine that does not serve the pair it was asked for; the chain moves on to the next model.
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
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
CopyBool copies an optional flag so the copy can change independently.
func EstimateOutputTokens ¶
EstimateOutputTokens estimates output tokens from character or rune count.
func ExtractHTTPStatusCode ¶
ExtractHTTPStatusCode resolves HTTP status codes across supported provider SDKs.
func IsCapacityExhausted ¶
IsCapacityExhausted reports whether err signals local capacity or queue saturation.
func IsContentFilterError ¶
IsContentFilterError reports whether err indicates an Azure or vendor content filter block.
func IsRetryableError ¶
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 ¶
IsShadowTraffic checks if context is marked as shadow traffic.
func IsTransportFailure ¶ added in v0.13.1
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 JSONText ¶ added in v1.8.0
func JSONText(raw json.RawMessage) string
JSONText is a JSON value as text: a string as itself, anything else compact.
func LanguageName ¶ added in v1.6.0
LanguageName is the English name of a tag's primary language, or "".
func MapJSONStrings ¶ added in v1.8.0
func MapJSONStrings(raw json.RawMessage, fn func(string) (string, error)) (json.RawMessage, error)
MapJSONStrings applies fn to every string value in raw (not to object keys, which name options) and returns the re-encoded JSON.
func ParseRetryAfter ¶ added in v0.13.1
ParseRetryAfter reads retry-after-ms (OpenAI, Azure) before the standard Retry-After header, which is either delay-seconds or an HTTP date.
func RemoveMarkdownCodeBlocks ¶
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
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 ¶
ShouldSkipToNextModel reports whether err or any wrapped error indicates that the chain should advance to the next candidate model immediately.
func SourceCharacters ¶ added in v1.6.0
SourceCharacters counts what a translation is billed by: code points of every input text, as MT vendors count them.
func TruncatedError ¶
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
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.
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 Box ¶ added in v1.8.0
type Box struct {
Top, Bottom, Left, Right float64
}
Box is a box on an image: edges as fractions 0..1 of its height (Top, Bottom) and width (Left, Right) from the top-left corner.
type Caller ¶
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) GetSampling ¶ added in v1.5.0
func (c *ChatContext) GetSampling() Sampling
GetSampling returns the caller's sampling, before any model's filter.
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) SetSampling ¶ added in v1.5.0
func (c *ChatContext) SetSampling(s Sampling)
SetSampling sets the caller's sampling. Each adapter passes on what its model takes (SamplingSupport.Apply).
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 ¶
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 ¶
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 ¶
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 InvalidMediaError ¶ added in v1.8.0
InvalidMediaError says what is wrong with which part, for the caller. Part indexes StateMedia; Field names the request field, "state_media" when empty. VendorLimit marks media over one vendor's limits that another model may take.
func (*InvalidMediaError) Error ¶ added in v1.8.0
func (e *InvalidMediaError) Error() string
func (*InvalidMediaError) Is ¶ added in v1.8.0
func (e *InvalidMediaError) Is(target error) bool
func (*InvalidMediaError) SkipToNextModel ¶ added in v1.9.0
func (e *InvalidMediaError) SkipToNextModel() bool
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
Box *Box // box questions only
// ConfidenceUnset: the vendor gave no confidence, so Confidence means nothing.
ConfidenceUnset bool
}
JudgeAnswer is one question's typed answer. Noul carries a probability; choice and score carry a distribution plus how concentrated it is.
type JudgeMediaChecker ¶ added in v1.8.0
type JudgeMediaChecker interface {
CheckJudgeMedia(media []*JudgeMediaPart, questions map[string]*JudgeQuestion) error
}
JudgeMediaChecker is an optional Judge capability: it says whether the vendor would refuse media before any call, so a batch fails before it bills. The questions matter too: some vendors take fewer images for a box question.
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
// Name is how state, instructions and criteria refer to the part; "" for
// an unnamed one.
Name 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
// InstructionsJSON and CriteriaJSON are the structured forms (an object or
// array, possibly naming images); when set they replace Instructions and
// the per-type criteria fields.
InstructionsJSON json.RawMessage
CriteriaJSON json.RawMessage
}
JudgeQuestion is one typed question. Which fields carry meaning depends on Type: Options for choice, Levels for score, the criteria pair for noul.
func (*JudgeQuestion) Flat ¶ added in v1.8.0
func (q *JudgeQuestion) Flat() *JudgeQuestion
Flat returns q with its JSON forms read as text into the plain fields (compact JSON for objects, the string itself for a JSON string), for judges that take text and for what reads levels and options. The JSON stays set.
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 ¶
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 Sampling ¶ added in v1.5.0
Sampling is the caller's sampling settings; a nil field or an empty Stop leaves the model's default.
type SamplingSupport ¶ added in v1.5.0
type SamplingSupport struct {
Temperature, TopP, Stop, Seed bool
MaxTemperature float64 // 0 means no cap below the caller's range
MaxStop int // 0 means no limit
// OneOfTemperatureTopP: the API rejects both together, so top_p goes.
OneOfTemperatureTopP bool
// NoBlankStop: the API rejects a stop sequence of whitespace alone.
NoBlankStop bool
}
SamplingSupport is what one model takes. The zero value takes nothing, so a model nobody described never gets a field its API may reject.
func (SamplingSupport) Apply ¶ added in v1.5.0
func (s SamplingSupport) Apply(in Sampling) (Sampling, []string)
Apply returns the settings the model gets and the names of those it does not get as sent: a temperature lowered to the cap, a stop list cut to the limit or rid of blank sequences the API rejects, and every field it lacks.
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 SerialJudge ¶ added in v1.9.0
type SerialJudge interface {
JudgesSerially() bool
}
SerialJudge is an optional Judge capability: the model judges rollouts one candidate after another (a node with few slots), with no rollouts route of its own, so callers skip EvaluateRollouts and call Judge in turn.
type SkipToNextModel ¶
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
// Characters is source text a translation is billed by, apart from tokens;
// zero for every other call.
Characters int
}
func (TokensUsage) Add ¶ added in v1.0.0
func (u TokensUsage) Add(o TokensUsage) TokensUsage
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 ¶
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 TranslateRequest ¶ added in v1.6.0
type TranslateRequest struct {
Texts []string
SourceLanguage string
TargetLanguage string
Format string
ActionID string
}
TranslateRequest is one call's worth of translation: every text goes from SourceLanguage (empty means detect each) to TargetLanguage.
type TranslateResult ¶ added in v1.6.0
type TranslateResult struct {
Translations []Translation
Model string
Usage TokensUsage
}
TranslateResult holds one translation per input text, in input order. Usage.Characters is the source characters billed.
func TranslateByPrompt ¶ added in v1.6.0
func TranslateByPrompt(ctx context.Context, a ClientAdapter, req *TranslateRequest, userID string, meta map[string]string) (*TranslateResult, error)
TranslateByPrompt translates with any chat model: a system prompt, the texts as JSON data and a structured reply checked for count and order. Chunks run concurrently; one mismatching chunk fails the call after one retry.
type Translation ¶ added in v1.6.0
Translation is one text's result.
type TranslationMismatchError ¶ added in v1.6.0
type TranslationMismatchError struct{ Reason string }
TranslationMismatchError is a model reply whose items do not line up with the input. The same model is unlikely to do better, so the chain moves on.
func (*TranslationMismatchError) Error ¶ added in v1.6.0
func (e *TranslationMismatchError) Error() string
func (*TranslationMismatchError) SkipToNextModel ¶ added in v1.6.0
func (e *TranslationMismatchError) SkipToNextModel() bool
type Translator ¶ added in v1.6.0
type Translator interface {
Translate(ctx context.Context, req *TranslateRequest, userID string, meta map[string]string) (*TranslateResult, error)
}
Translator is an optional adapter capability for engines that translate natively (MT servers, cloud MT). Chat models without it translate through TranslateByPrompt.
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