inference

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: AGPL-3.0 Imports: 4 Imported by: 0

Documentation

Overview

Package inference owns provider-neutral inference values and stream events.

Index

Constants

This section is empty.

Variables

View Source
var ErrDocumentSourceConflict = errors.New("a document part names more than one source")

ErrDocumentSourceConflict reports a document part that names more than one source for the same bytes.

View Source
var ErrModerationInputEmpty = errors.New("a moderation request needs at least one input")

ErrModerationInputEmpty reports a moderation request with nothing to classify.

View Source
var ErrModerationResultCountMismatch = errors.New(
	"a moderation response must answer every request input exactly once",
)

ErrModerationResultCountMismatch reports a response whose result count disagrees with the request's input count. A caller reads each result by position, so a shorter or longer list silently answers the wrong input.

View Source
var ErrModerationScoreOutOfRange = errors.New(
	"a moderation category score falls outside zero through one",
)

ErrModerationScoreOutOfRange reports a category score outside the unit interval. Every moderation provider publishes a normalized score, so a number outside it is a decoding fault rather than an unusual answer.

View Source
var ErrRerankDocumentsEmpty = errors.New("a rerank request needs at least one document")

ErrRerankDocumentsEmpty reports a rerank request with nothing to rank.

View Source
var ErrRerankDocumentsExceedBound = errors.New("a rerank request holds more documents than the offering accepts")

ErrRerankDocumentsExceedBound reports a document list longer than the selected offering accepts. A provider refuses the whole batch rather than ranking a prefix of it, so the caller pays for a round trip that could not have succeeded.

View Source
var ErrRerankQueryEmpty = errors.New("a rerank request needs a query")

ErrRerankQueryEmpty reports a rerank request with nothing to rank against.

View Source
var ErrRerankResultOutOfRange = errors.New("a rerank result names a document the request does not hold")

ErrRerankResultOutOfRange reports a result that names a document position the request never held.

View Source
var ErrRerankScoreOutOfRange = errors.New("a rerank relevance score falls outside zero through one")

ErrRerankScoreOutOfRange reports a relevance score outside the unit interval. Every rerank provider publishes a normalized score, so a number outside it is a decoding fault rather than an unusual answer, and a caller that ranked on it would rank on a number the schema says cannot exist.

Functions

This section is empty.

Types

type Audio added in v1.1.0

type Audio struct {
	URL    string
	Data   []byte
	Format string
}

Audio describes an audio input. A caller sends either a URL or inline Data, and Format names the container, such as "wav" or "mp3".

type AudioChunk added in v1.1.0

type AudioChunk struct {
	Data       []byte
	Transcript string
}

AudioChunk is one streamed piece of a spoken answer. Data holds the audio bytes for this chunk, and Transcript holds the text the model spoke in it. A provider sends either or both in one chunk, so neither field implies the other.

type AudioOutput added in v1.1.0

type AudioOutput struct {
	Voice  string
	Format string
}

AudioOutput asks the model to speak its answer. Voice names the provider's voice, and Format names the container the caller wants back, such as "wav" or "mp3". A provider that serves audio output requires both, so neither carries a gateway default: an unset field stays unset on the wire and the provider answers for it.

type Batch added in v1.2.0

type Batch struct {
	// ID is the Starport batch identifier.
	ID string
	// Endpoint is the operation path every line calls.
	Endpoint string
	// InputFileID names the stored input file.
	InputFileID string
	// OutputFileID names the stored result file, or is empty while the batch
	// has not written one.
	OutputFileID string
	// ErrorFileID names the stored error file, or is empty when every line
	// succeeded or none has failed yet.
	ErrorFileID string
	// State is the canonical job state word.
	State string
	// Reason states why a failed or cancelled batch stopped. It is empty for
	// every other state.
	Reason string
	// TotalLines is how many request lines the input file holds, or zero
	// while the batch has not counted them.
	TotalLines int
	// CompletedLines is how many lines produced a result.
	CompletedLines int
	// FailedLines is how many lines produced an error-file entry.
	FailedLines int
	// CreatedUnix is when Starport recorded the batch.
	CreatedUnix int64
	// CompletedUnix is when the batch reached a terminal state, or zero while
	// it has not.
	CompletedUnix int64
}

Batch is the canonical answer a caller reads about one batch it submitted.

func (Batch) Clone added in v1.2.0

func (b Batch) Clone() Batch

Clone returns a copy that shares nothing with the original.

type BatchCreateRequest added in v1.2.0

type BatchCreateRequest struct {
	// InputFileID names the stored JSONL file the batch reads.
	InputFileID string
	// Endpoint is the one operation path every line in the batch calls, such
	// as "/v1/chat/completions".
	Endpoint string
	// CompletionWindow is the window the caller asked for. The gateway
	// validates and echoes it rather than scheduling by it, because a
	// self-hosted gateway starts the work at once.
	CompletionWindow string
}

BatchCreateRequest is one canonical request to run a batch.

func (BatchCreateRequest) Clone added in v1.2.0

Clone returns a copy that shares nothing with the original.

type BatchLine added in v1.2.0

type BatchLine struct {
	// CustomID is the caller's own name for the line. Every result carries it
	// back, because line order is the only other way to match a result to a
	// request.
	CustomID string
	// URL is the operation path the line calls. The codec has already checked
	// it against the batch endpoint.
	URL string
	// Body is the raw request body the line carries. The line runner decodes
	// it with the same codec the online route uses.
	Body []byte
}

BatchLine is one decoded request line from a batch input file.

func (BatchLine) Clone added in v1.2.0

func (l BatchLine) Clone() BatchLine

Clone returns a copy that shares nothing with the original.

type BatchLineResult added in v1.2.0

type BatchLineResult struct {
	// CustomID is the caller's name for the line, copied from the request.
	CustomID string
	// StatusCode is the HTTP status the online route would have answered.
	StatusCode int
	// RequestID is the per-line request identifier, for support and for the
	// usage record that carries the same value.
	RequestID string
	// Body is the response body, or the error body for a failed line.
	Body []byte
}

BatchLineResult is what one line produced: a response body and the status it would have carried on the online route. A non-2xx status sends the line to the error file rather than the output file.

func (BatchLineResult) Clone added in v1.2.0

func (r BatchLineResult) Clone() BatchLineResult

Clone returns a copy that shares nothing with the original.

type ChatRequest

type ChatRequest struct {
	Model          string
	FallbackModels []string
	Messages       []Message
	Sampling       Sampling
	Tools          []Tool
	ToolChoice     ToolChoice
	// ParallelToolCalls permits or forbids several tool calls in one
	// assistant turn. Nil leaves the provider default in place.
	ParallelToolCalls *bool
	Output            StructuredOutput
	Reasoning         Reasoning
	// OutputModalities names what the caller will accept back. Empty means
	// text, which is what every model served before this field existed.
	// A model that speaks its answer needs the caller to ask for audio, so
	// this is a request field and not a routing hint.
	//
	// The response cache derives its key by serializing this struct, so a
	// field added here changes the key of every request, including one that
	// never sets it. internal/response/cache owns that consequence and
	// answers for it by version, because a canonical type carries no
	// transport tag that could hide the field instead.
	OutputModalities []Modality
	// AudioOutput configures the spoken answer OutputModalities asks for.
	// Nil leaves the provider to choose, and a provider that requires a
	// voice refuses the turn itself rather than take a gateway default.
	AudioOutput   *AudioOutput
	Stream        bool
	StreamOptions StreamOptions
	User          string
	Extensions    map[string]json.RawMessage
	// DocumentParser names the extraction the caller asked for before a
	// model reads an attached document. The zero value asks for none.
	//
	// This field reaches the response cache key for the reason
	// OutputModalities above states: the key serializes this struct, and a
	// canonical type carries no transport tag that could hide a field. The
	// same bytes parsed by two engines are two different inputs, so the
	// key has to separate them. internal/response/cache answers for that by
	// version.
	DocumentParser DocumentParser
}

ChatRequest is the canonical chat inference request.

func (ChatRequest) Clone

func (r ChatRequest) Clone() ChatRequest

Clone returns an independent request copy.

type ChatResponse

type ChatResponse struct {
	ID                string
	CreatedUnix       int64
	Model             string
	ModelUsed         string
	Choices           []Choice
	Usage             Usage
	SystemFingerprint string
}

ChatResponse is the canonical completed chat response.

func (ChatResponse) Clone

func (r ChatResponse) Clone() ChatResponse

Clone returns an independent response copy.

type Choice

type Choice struct {
	Index        int
	Message      Message
	FinishReason string
	LogProbs     []LogProb
}

Choice is one completed model choice.

type ChoiceDelta

type ChoiceDelta struct {
	Index     int
	Role      Role
	Text      string
	Reasoning string
	// Audio carries one chunk of a spoken answer. OpenRouter serves audio
	// output through streaming alone, so a caller that never reads this
	// field never receives the answer at all.
	Audio *AudioChunk
	// Media carries generated parts that arrive whole rather than in
	// pieces. An image is the case that forces the field: a provider sends
	// the finished picture in one delta, so there is nothing to accumulate
	// and nothing Text could hold. Audio is the other case and keeps its
	// own field, because a spoken answer does arrive in pieces.
	Media        []ContentPart
	ToolCalls    []ToolCall
	LogProbs     []LogProb
	FinishReason string
}

ChoiceDelta contains one streamed choice update.

type ContentKind

type ContentKind string

ContentKind identifies one message content modality.

const (
	// ContentText identifies plain text content.
	ContentText ContentKind = "text"
	// ContentImage identifies image content.
	ContentImage ContentKind = "image"
	// ContentAudio identifies audio content.
	ContentAudio ContentKind = "audio"
	// ContentDocument identifies document content, which Starmap records as
	// the pdf modality.
	ContentDocument ContentKind = "document"
	// ContentVideo identifies video content.
	ContentVideo ContentKind = "video"
)

func ContentKinds added in v1.1.0

func ContentKinds() []ContentKind

ContentKinds lists every modality a canonical message part can carry. cloneMessage has one arm for each kind that owns a pointer, and the contract test walks this list, so a new kind cannot ship without the clone coverage that keeps one retry attempt from rewriting the next.

type ContentPart

type ContentPart struct {
	Kind         ContentKind
	Text         string
	Image        *Image
	Audio        *Audio
	Document     *Document
	Video        *Video
	CacheControl string
}

ContentPart is one typed part of a message. Kind selects which payload pointer carries the part, and the others stay nil.

type Document added in v1.1.0

type Document struct {
	URL      string
	Data     []byte
	Format   string
	Filename string

	// FileID names a stored document this gateway holds for the requesting
	// account. It is the only document reference the gateway can resolve
	// without leaving the deployment, and the only one whose bytes cannot
	// change under a cached answer: a stored file is written once and
	// deleted, never rewritten, and its identifier is never reused.
	FileID string
}

Document describes a document input, such as a PDF. Filename is separate from Format because both protocol families carry the caller's own name beside the bytes, and a parser reports page numbers against it.

A caller supplies the bytes one of three ways: inline Data, a URL the gateway fetches, or FileID, which names a document this gateway already stores for the caller's own account. The three are exclusive. A part that named two of them would leave the answer to whichever one a codec happened to read first.

func (Document) Validate added in v1.1.0

func (d Document) Validate() error

Validate refuses a document that names more than one source.

A part naming none is not this rule's concern: a codec that decoded an empty document part reports its own decode failure, and refusing here would turn that into a second, less specific message.

The refusal names the rule rather than the fields that collided, because the two protocol families spell these sources differently on the wire. A codec wraps this error with the field path of the part it was decoding, which is what tells a caller where to look.

type DocumentParser added in v1.1.0

type DocumentParser struct {
	Engine ParserEngine
}

DocumentParser names the extraction a caller asked for. The zero value means the caller asked for none, which is different from asking for the native engine: a request that named no parser leaves an attached document to whatever the chosen model does with it, and a request that named the native engine gets extracted text whether or not the model reads documents.

func (DocumentParser) Requested added in v1.1.0

func (p DocumentParser) Requested() bool

Requested reports whether the caller asked for an extraction.

type Embedding

type Embedding struct {
	Index  int
	Vector []float32
}

Embedding is one normalized vector.

type EmbeddingInput

type EmbeddingInput struct {
	Texts    []string
	TokenIDs [][]int
}

EmbeddingInput is a normalized text or token input batch.

type EmbeddingRequest

type EmbeddingRequest struct {
	Model          string
	Input          EmbeddingInput
	EncodingFormat string
	Dimensions     *int
	User           string
}

EmbeddingRequest is the canonical embedding request.

func (EmbeddingRequest) Clone

Clone returns an independent embedding request copy.

type EmbeddingResponse

type EmbeddingResponse struct {
	Model string
	Data  []Embedding
	Usage Usage
}

EmbeddingResponse is the canonical embedding response.

func (EmbeddingResponse) Clone

Clone returns an independent embedding response copy.

type GeneratedImage added in v1.1.0

type GeneratedImage struct {
	B64JSON string
	URL     string
	// RevisedPrompt is the prompt the provider actually rendered, when it
	// rewrote the one the caller sent.
	RevisedPrompt string
}

GeneratedImage is one picture an image operation produced. A provider answers with inline base64 or with a URL it hosts, never with both, and the caller asked for one of the two.

type Image

type Image struct {
	URL    string
	Detail string
}

Image describes an image input.

type ImagesRequest added in v1.1.0

type ImagesRequest struct {
	Model          string
	Prompt         string
	N              int
	Size           string
	Quality        string
	Style          string
	ResponseFormat string
	User           string
	// Image is the picture an edit starts from. An empty value means the
	// request is a generation.
	Image UploadedFile
	// Mask names the region of Image an edit may replace. It is meaningless
	// without Image.
	Mask UploadedFile
}

ImagesRequest is the canonical image generation or image edit request. One type serves both, because an edit is a generation that starts from a source image: the presence of Image is what separates them, and it is also what decides the operation the request routes to.

func (ImagesRequest) Clone added in v1.1.0

func (r ImagesRequest) Clone() ImagesRequest

Clone returns an independent image request copy.

func (ImagesRequest) IsEdit added in v1.1.0

func (r ImagesRequest) IsEdit() bool

IsEdit reports whether the request edits a source image rather than generating one. The routed operation follows this answer.

type ImagesResponse added in v1.1.0

type ImagesResponse struct {
	Model       string
	CreatedUnix int64
	Images      []GeneratedImage
	Usage       Usage
}

ImagesResponse is the canonical image operation result.

func (ImagesResponse) Clone added in v1.1.0

func (r ImagesResponse) Clone() ImagesResponse

Clone returns an independent image response copy.

type LogProb

type LogProb struct {
	Token string
	Value float64
	Bytes []int
	Top   []TopLogProb
}

LogProb reports one token probability and its alternatives.

type MediaUnits added in v1.1.0

type MediaUnits struct {
	// Images, Audio, Documents, and Videos count the parts of each kind.
	Images    int
	Audio     int
	Documents int
	Videos    int

	// InlineBytes totals the decoded bytes the request carries itself. A
	// part that names a remote reference adds nothing, because the gateway
	// never fetched the bytes behind it.
	InlineBytes int64
}

MediaUnits counts the non-text payloads one request carries. Tokens do not describe media: a caller sends a number of images, seconds of audio, or pages of a document, and a provider prices those units separately. The counts therefore stay beside the token total rather than inside it.

func EstimateMediaUnits added in v1.1.0

func EstimateMediaUnits(messages []Message) MediaUnits

EstimateMediaUnits counts the media payloads of one message list. It is the single walk over content parts that both the token estimator and the accounting path read, so one new content kind is counted in one place rather than once per caller.

A part counts by the payload it carries rather than by the kind it names. Older call sites build a part with a payload and no kind, and a media part the gateway forwards is a media part whether or not the kind was set.

func ResponseMediaUnits added in v1.1.0

func ResponseMediaUnits(choices []Choice) MediaUnits

ResponseMediaUnits counts the media the answer itself carries. A provider reports no token count for a generated image, so this walk is the only place the gateway learns how many it produced, and therefore the only place a cost or a budget can learn it.

func StreamMediaUnits added in v1.1.0

func StreamMediaUnits(deltas []ChoiceDelta) MediaUnits

StreamMediaUnits counts the media one stream chunk carries. A streamed turn reports its usage on one event and its pictures on others, so no single event holds both and a caller has to add these up across the whole stream.

func (MediaUnits) Total added in v1.1.0

func (u MediaUnits) Total() int

Total counts every media unit, whatever its kind.

type Message

type Message struct {
	Role       Role
	Content    []ContentPart
	Reasoning  string
	Name       string
	ToolCalls  []ToolCall
	ToolCallID string
}

Message is one provider-neutral conversation message.

type Modality added in v1.1.0

type Modality string

Modality names one payload family. A content kind describes one message part, while a modality describes what a request carries and what a model accepts, so a route decision compares like with like. Starmap records a document as the pdf modality, and the catalog boundary owns that translation.

const (
	// ModalityText is written or spoken language as characters.
	ModalityText Modality = "text"
	// ModalityImage is a still picture.
	ModalityImage Modality = "image"
	// ModalityAudio is recorded sound.
	ModalityAudio Modality = "audio"
	// ModalityDocument is a paged document, such as a PDF.
	ModalityDocument Modality = "document"
	// ModalityVideo is moving pictures.
	ModalityVideo Modality = "video"
)

func RequestMediaModalities added in v1.1.0

func RequestMediaModalities(messages []Message) []Modality

RequestMediaModalities lists the media modalities one message list carries, in the order ContentKinds declares them. Routing compares this list against the input modalities the catalog states for a model.

Text is not in the list. Every chat request carries text and every chat-capable model reads it, so a text entry would only put a modality check in front of traffic that already works. The defect this list closes is media sent to a model that reads none.

type ModerationCategory added in v1.2.0

type ModerationCategory struct {
	// Name is the category name exactly as the provider states it.
	Name string
	// Flagged is the provider's own threshold decision for this category.
	Flagged bool
	// Score is how strongly the input matches the category. Providers
	// normalize it to the unit interval, and the gateway does not rescale it.
	Score float64
}

ModerationCategory is one harm category's verdict on one input.

type ModerationRequest added in v1.2.0

type ModerationRequest struct {
	Model string
	// Inputs is the list of texts to classify, in the order the caller
	// supplied. A result answers the input at the same position, so the order
	// is part of the request's meaning rather than a presentation detail.
	Inputs []string
}

ModerationRequest is the canonical moderation request.

func NewModerationRequest added in v1.2.0

func NewModerationRequest(model string, inputs []string) (ModerationRequest, error)

NewModerationRequest builds a canonical moderation request and refuses the one request that cannot be answered. An empty input list classifies nothing, and it would reach a provider as a paid error, so it stops here.

func (ModerationRequest) Clone added in v1.2.0

Clone returns an independent moderation request copy.

type ModerationResponse added in v1.2.0

type ModerationResponse struct {
	// ID is the provider's identifier for this classification, kept so the
	// wire answer a caller reads matches the record the provider holds.
	ID    string
	Model string
	// Results holds one result per request input, at the same position.
	Results []ModerationResult
	Usage   Usage
}

ModerationResponse is the canonical moderation response.

func (ModerationResponse) Clone added in v1.2.0

Clone returns an independent moderation response copy.

func (ModerationResponse) Validate added in v1.2.0

func (r ModerationResponse) Validate(request ModerationRequest) error

Validate refuses a response that cannot describe the request that produced it. A codec calls it before writing, because both faults produce an answer that reads as ordinary: a missing result shifts every later verdict onto the wrong input, and a score outside the unit interval reads as a confident number the schema says cannot exist.

type ModerationResult added in v1.2.0

type ModerationResult struct {
	// Flagged reports whether any category flagged the input.
	Flagged bool
	// Categories holds one verdict per category, in the order the provider
	// stated them.
	Categories []ModerationCategory
}

ModerationResult is every category's verdict on one input.

type OutputFormat

type OutputFormat string

OutputFormat identifies the required model output shape.

const (
	// OutputText requests unstructured text output.
	OutputText OutputFormat = "text"
	// OutputJSONObject requests one JSON object.
	OutputJSONObject OutputFormat = "json_object"
	// OutputJSONSchema requests output that matches a JSON Schema.
	OutputJSONSchema OutputFormat = "json_schema"
)

type ParserEngine added in v1.1.0

type ParserEngine string

ParserEngine names how the gateway turns an attached document into text before a model reads it. It is a canonical field rather than a wire field: a caller names it on the OpenRouter family, and the router, the extraction seam, and the usage record all read the same value.

Two engines ship, and the boundary between them is who does the work. The native engine runs in this process and reaches no provider, so a document that already carries a text layer costs nothing. The recognition engine sends a page to a model the catalog serves for that operation, so it costs what the catalog says a page costs.

A vendor engine name is deliberately absent. Accepting one and then routing to a different vendor would report work this deployment did not do, so a codec refuses every name outside this vocabulary rather than fall back.

const (
	// ParserEngineNative reads a document's own text layer in process.
	ParserEngineNative ParserEngine = "native"
	// ParserEngineRecognition sends a page to a catalogued model that reads
	// text out of an image.
	ParserEngineRecognition ParserEngine = "recognition"
)

func KnownParserEngines added in v1.1.0

func KnownParserEngines() []ParserEngine

KnownParserEngines returns the engines this gateway runs, in the order a refusal should list them. A caller reading the refusal needs the whole vocabulary, not the one name it got wrong.

func (ParserEngine) Known added in v1.1.0

func (e ParserEngine) Known() bool

Known reports whether the engine is one this gateway runs.

type Reasoning

type Reasoning struct {
	Effort    ReasoningEffort
	MaxTokens *int
	Exclude   bool
}

Reasoning configures reasoning-token behavior.

type ReasoningEffort

type ReasoningEffort string

ReasoningEffort identifies the requested reasoning depth.

const (
	// ReasoningLow requests the lowest supported reasoning effort.
	ReasoningLow ReasoningEffort = "low"
	// ReasoningMedium requests medium reasoning effort.
	ReasoningMedium ReasoningEffort = "medium"
	// ReasoningHigh requests high reasoning effort.
	ReasoningHigh ReasoningEffort = "high"
)

type RecognitionRequest added in v1.1.0

type RecognitionRequest struct {
	Model string
	// Document is the whole document rather than one page. Splitting a
	// container into single-page documents needs a writer this gateway does
	// not carry, and a provider that reads a document reads its pages in
	// order anyway.
	Document UploadedFile
	// Pages is how many pages the native read counted. It travels because a
	// recognizer cannot otherwise tell a document that ended from an answer
	// that was cut short, and those two have to reach the caller differently.
	Pages int
}

RecognitionRequest asks a model to read the text off every page of one document.

func (RecognitionRequest) Clone added in v1.1.0

Clone returns an independent recognition request copy.

type RecognitionResponse added in v1.1.0

type RecognitionResponse struct {
	Model string
	// Pages holds one entry per page the provider read, in page order.
	Pages []RecognizedPage
	Usage Usage
}

RecognitionResponse is the canonical result of reading one document.

The answer is per page rather than one string. A short answer is the failure this operation actually has: a provider that stops early returns text for the pages it reached, and only a page count separates that from a document that ended there.

func (RecognitionResponse) Clone added in v1.1.0

Clone returns an independent recognition response copy.

func (RecognitionResponse) Text added in v1.1.0

func (r RecognitionResponse) Text() string

Text joins every recognized page in page order, separated by a blank line. It is the shape the native engine returns for the same document, so a model reads one string whichever engine produced it.

type RecognizedPage added in v1.1.0

type RecognizedPage struct {
	// Number is the page's one-based position in the document.
	Number int
	// Text is what the recognizer read on that page. It is empty for a page
	// that held nothing, which is a real answer rather than a failure.
	Text string
}

RecognizedPage is the text one page carried.

type RerankRequest added in v1.1.0

type RerankRequest struct {
	Model string
	// Query is the text every document is scored against.
	Query string
	// Documents is the list to rank, in the order the caller supplied. A
	// result names a position in this slice, so its order is part of the
	// request's meaning rather than a presentation detail.
	Documents []string
	// TopN is how many results the caller wants back. Nil asks for all of
	// them. It is a request for fewer results rather than a page: a provider
	// scores every document either way and bills for every document either
	// way.
	TopN *int
	// MaxTokensPerDocument caps how much of each document the provider reads.
	// Nil leaves the provider's own default in place. A provider that exceeds
	// its cap either truncates the document or splits it into chunks it bills
	// separately, so the cap is a cost control as well as a size control.
	MaxTokensPerDocument *int
}

RerankRequest is the canonical rerank request.

func NewRerankRequest added in v1.1.0

func NewRerankRequest(model, query string, documents []string) (RerankRequest, error)

NewRerankRequest builds a canonical rerank request and refuses the two requests that cannot be answered. An empty query scores every document against nothing, and an empty document list ranks nothing. Both reach a provider as a paid error, so they stop here.

func (RerankRequest) CheckDocumentBound added in v1.1.0

func (r RerankRequest) CheckDocumentBound(limit int) error

CheckDocumentBound refuses a document list longer than the offering allows. A limit of zero or less states no bound, which is what a catalog says when the provider publishes no document count.

func (RerankRequest) Clone added in v1.1.0

func (r RerankRequest) Clone() RerankRequest

Clone returns an independent rerank request copy.

type RerankResponse added in v1.1.0

type RerankResponse struct {
	Model string
	// Results holds the scored documents in relevance order, highest first.
	// It is shorter than the request when the caller asked for fewer.
	Results []RerankResult
	Usage   Usage
}

RerankResponse is the canonical rerank response.

func (RerankResponse) Clone added in v1.1.0

func (r RerankResponse) Clone() RerankResponse

Clone returns an independent rerank response copy.

func (RerankResponse) Documents added in v1.1.0

func (r RerankResponse) Documents(request RerankRequest) ([]string, error)

Documents resolves each result back to the text the request carried. A codec that has to echo the document calls this rather than storing a second copy, and a result that names a position the request does not hold is an error the caller sees rather than an empty string it cannot explain.

func (RerankResponse) Validate added in v1.1.0

func (r RerankResponse) Validate(request RerankRequest) error

Validate refuses a response that cannot describe the request that produced it. A codec calls it before writing, because both faults produce an answer that reads as ordinary: an index outside the request resolves to the wrong document, and a score outside the unit interval sorts against every other provider's scale.

type RerankResult added in v1.1.0

type RerankResult struct {
	// Index is the document's position in the request that produced it.
	Index int
	// RelevanceScore is how well that document answers the query. Providers
	// normalize it to the unit interval, and the gateway does not rescale it.
	RelevanceScore float64
}

RerankResult is one scored document.

It holds an index and no text. A copy of the document would double the memory a large batch needs, and it would let a response disagree with the request that produced it. A codec that has to echo the text reads it back out of the request it still holds.

type Role

type Role string

Role identifies a message participant.

const (
	// RoleSystem identifies a system instruction message.
	RoleSystem Role = "system"
	// RoleUser identifies a user message.
	RoleUser Role = "user"
	// RoleAssistant identifies a model response message.
	RoleAssistant Role = "assistant"
	// RoleTool identifies a tool result message.
	RoleTool Role = "tool"
)

type Sampling

type Sampling struct {
	Temperature      *float32
	TopP             *float32
	CandidateCount   *int
	MaxTokens        *int
	Stop             []string
	PresencePenalty  *float32
	FrequencyPenalty *float32
	LogitBias        map[string]int
	Seed             *int
}

Sampling contains provider-neutral generation controls.

type SpeechRequest added in v1.1.0

type SpeechRequest struct {
	Model string
	Input string
	Voice string
	// ResponseFormat names the container the caller wants, such as mp3 or
	// wav. A provider decides the default when the caller states none.
	ResponseFormat string
	// Speed multiplies the delivery rate. A nil value means the provider
	// default, which is not the same as 0.
	Speed *float64
}

SpeechRequest is the canonical text-to-speech request.

func (SpeechRequest) Clone added in v1.1.0

func (r SpeechRequest) Clone() SpeechRequest

Clone returns an independent speech request copy.

type SpeechResponse added in v1.1.0

type SpeechResponse struct {
	Model string
	Audio []byte
	// ContentType is the media type the provider stated for Audio. The
	// gateway repeats it rather than deriving one, because the provider
	// encoded the file.
	ContentType string
	Usage       Usage
}

SpeechResponse is the canonical text-to-speech result. A speech endpoint answers with an encoded audio file rather than with JSON, so the bytes and their media type are the whole answer.

func (SpeechResponse) Clone added in v1.1.0

func (r SpeechResponse) Clone() SpeechResponse

Clone returns an independent speech response copy.

type StreamEvent

type StreamEvent struct {
	Kind              StreamEventKind
	ID                string
	CreatedUnix       int64
	Model             string
	ModelUsed         string
	SystemFingerprint string
	Deltas            []ChoiceDelta
	Usage             *Usage
}

StreamEvent is one typed provider-neutral stream transition.

func (StreamEvent) Clone

func (e StreamEvent) Clone() StreamEvent

Clone returns an independent stream event copy.

type StreamEventKind

type StreamEventKind string

StreamEventKind identifies a normalized stream transition.

const (
	// StreamStart identifies the initial canonical stream event.
	StreamStart StreamEventKind = "start"
	// StreamDelta identifies a canonical content update.
	StreamDelta StreamEventKind = "delta"
	// StreamUsage identifies a canonical token-usage update.
	StreamUsage StreamEventKind = "usage"
	// StreamEnd identifies the terminal canonical stream event.
	StreamEnd StreamEventKind = "end"
)

type StreamOptions

type StreamOptions struct {
	IncludeUsage bool
}

StreamOptions configures stream event delivery.

type StructuredOutput

type StructuredOutput struct {
	Format      OutputFormat
	Name        string
	Description string
	Schema      json.RawMessage
	Strict      bool
}

StructuredOutput describes a structured response contract.

type Tool

type Tool struct {
	Name        string
	Description string
	Parameters  json.RawMessage
}

Tool describes one callable function and its JSON Schema parameters.

type ToolCall

type ToolCall struct {
	ID        string
	Name      string
	Arguments string
}

ToolCall is one model-requested function call.

type ToolChoice

type ToolChoice struct {
	Mode ToolChoiceMode
	Name string
}

ToolChoice is an explicit provider-neutral tool selection.

type ToolChoiceMode

type ToolChoiceMode string

ToolChoiceMode selects how the model can call tools.

const (
	// ToolChoiceAuto lets the model decide whether to call a tool.
	ToolChoiceAuto ToolChoiceMode = "auto"
	// ToolChoiceNone prevents tool calls.
	ToolChoiceNone ToolChoiceMode = "none"
	// ToolChoiceRequired requires a tool call.
	ToolChoiceRequired ToolChoiceMode = "required"
	// ToolChoiceNamed requires one named tool.
	ToolChoiceNamed ToolChoiceMode = "named"
)

type TopLogProb

type TopLogProb struct {
	Token string
	Value float64
	Bytes []int
}

TopLogProb reports one alternate token probability.

type TranscriptionRequest added in v1.1.0

type TranscriptionRequest struct {
	Model string
	File  UploadedFile
	// Language names the language spoken in File, when the caller knows it.
	Language string
	// Prompt supplies vocabulary or context that helps the decoder.
	Prompt string
	// ResponseFormat names the transcript format, such as json, text, srt,
	// or vtt.
	ResponseFormat string
	// Temperature controls decoder sampling. A nil value means the provider
	// default, which is not the same as 0.
	Temperature *float64
	// Translate asks for an English transcript of speech in another
	// language. It selects the translation operation, which a provider
	// exposes at its own path, so it is a routing fact and not a hint.
	Translate bool
}

TranscriptionRequest is the canonical speech-to-text request. One type serves transcription and translation, because the two differ only in the language the transcript is written in.

func (TranscriptionRequest) Clone added in v1.1.0

Clone returns an independent transcription request copy.

type TranscriptionResponse added in v1.1.0

type TranscriptionResponse struct {
	Model string
	Text  string
	// Language is the language the provider detected, when it reported one.
	Language string
	// Duration is the length of the audio in seconds, when the provider
	// reported it.
	Duration float64
	Usage    Usage
}

TranscriptionResponse is the canonical speech-to-text result.

func (TranscriptionResponse) Clone added in v1.1.0

Clone returns an independent transcription response copy.

type UploadedFile added in v1.1.0

type UploadedFile struct {
	// Filename is the name the caller gave the upload. A provider reads the
	// extension to pick a decoder, so an empty name loses information the
	// caller supplied.
	Filename string
	// MediaType is the content type the caller stated, when it stated one.
	MediaType string
	// Bytes is the decoded payload.
	Bytes []byte
}

UploadedFile is one decoded file a caller sent with a request.

The bytes are held rather than streamed on purpose. A route plan retries across providers, and a retry replays the same upload. A reader is consumed by the first attempt, so an upload behind one would arrive empty at the second, and the caller would see the last provider's rejection instead of an answer.

func (UploadedFile) Clone added in v1.1.0

func (f UploadedFile) Clone() UploadedFile

Clone returns an independent upload copy.

func (UploadedFile) Present added in v1.1.0

func (f UploadedFile) Present() bool

Present reports whether the upload carries a payload.

type Usage

type Usage struct {
	InputTokens      int
	OutputTokens     int
	TotalTokens      int
	ReasoningTokens  int
	CacheReadTokens  int
	CacheWriteTokens int

	// AudioInputTokens and AudioOutputTokens count the audio a provider
	// metered at its own rate. Both are already inside InputTokens and
	// OutputTokens, the way CacheReadTokens is: a cost that adds them again
	// rather than reclassifying them bills the same audio twice.
	AudioInputTokens  int
	AudioOutputTokens int
	// GeneratedImages counts the pictures the answer carries. It is the one
	// output unit no token total can describe, because a provider prices a
	// generated image per image and reports no tokens for it.
	GeneratedImages int
	// SearchUnits counts the units a rerank provider that bills by search
	// billed. One unit covers one query against a fixed number of documents,
	// and a longer document counts as several. No token total converts into
	// it, and the offering's own basis says whether to read this field or the
	// token counts beside it.
	SearchUnits int

	// Estimated marks counts the gateway synthesized with a tokenizer
	// because the provider reported no usage. Estimated counts never
	// appear on the wire as provider-reported facts; accounting records
	// carry the flag so operators can tell estimates from measurements.
	Estimated bool
}

Usage reports normalized token counts. InputTokens includes cache reads and cache writes; CacheReadTokens and CacheWriteTokens break out the cached portions for pricing.

type Video added in v1.1.0

type Video struct {
	URL    string
	Data   []byte
	Format string
}

Video describes a video input. A caller sends either a URL or inline Data, and Format names the container, such as "mp4".

type VideoJob added in v1.1.0

type VideoJob struct {
	// ID is the Starport job identifier, and the only identifier a caller ever
	// sees for this work.
	ID string
	// Model is the catalog model identifier the job runs.
	Model string
	// Provider names who is running the work. A chat answer already reports
	// this, so a job answer reports it too.
	Provider string
	// State is the canonical job state word.
	State string
	// Reason states why a failed job produced no asset. It is empty for every
	// other state.
	Reason string
	// CreatedUnix is when Starport recorded the job.
	CreatedUnix int64
	// CompletedUnix is when the job reached a terminal state, or zero while it
	// has not.
	CompletedUnix int64
	// ExpiresUnix is when the retention window on the stored asset ends. It is
	// zero when this gateway holds no bytes for the job, which covers every job
	// that has not finished and every finished one whose bytes already went.
	//
	// A caller reads it to tell a video it can still fetch from one it cannot.
	// Without it the only way to ask is to fetch and read the refusal, which
	// spends a request per job to learn that a list of jobs is unplayable.
	ExpiresUnix int64
}

VideoJob is the canonical answer a caller reads about one job it submitted.

func (VideoJob) Clone added in v1.1.0

func (j VideoJob) Clone() VideoJob

Clone returns a copy that shares nothing with the original.

type VideoJobRequest added in v1.1.0

type VideoJobRequest struct {
	// Model is the catalog model identifier the caller asked for.
	Model string
	// Prompt describes the video to generate.
	Prompt string
	// NegativePrompt describes what to keep out of the result.
	NegativePrompt string
	// Size is the requested frame size, such as "1280x720".
	Size string
	// Seconds is the requested duration. It is a string because the two
	// published surfaces both send it as one, and a number would force a
	// guess at the unit.
	Seconds string
	// Seed makes a generation repeatable. It is a pointer because zero is a
	// seed a caller may ask for.
	Seed *int64
}

VideoJobRequest is one canonical request to generate a video.

func (VideoJobRequest) Clone added in v1.1.0

func (r VideoJobRequest) Clone() VideoJobRequest

Clone returns a copy that shares nothing with the original.

Jump to

Keyboard shortcuts

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