Help us shape the future of Go! Take the 2026 Go Developer Survey

wire

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package wire holds the plain values that a decoded response and a prepared question set are made of: answers, token usage, model cards, response metadata and the prepared question tables.

The package imports the standard library only. internal/codec fills these values and the root package wraps them in its exported types (type NoulAnswer struct{ w wire.NoulAnswer }), so both can share the shapes without an import cycle, and the weekly gotip canary can test this package on a toolchain that internal/codec refuses to build on.

Every value here is read-only once it has been handed to the root package: slices and maps are shared, not copied.

Index

Constants

View Source
const RequestIDHeader = "X-Typesafe-Request-Id"

RequestIDHeader is the canonical form of the response header that carries the server's identifier for a request (x-typesafe-request-id on the wire).

Variables

View Source
var (
	// ErrInvalidUTF8 reports a string that is not valid UTF-8. JSON text is
	// Unicode, and the Python SDK cannot produce such a string at all.
	ErrInvalidUTF8 = errors.New("string is not valid UTF-8")
	// ErrContentShape reports JSON content that is not an object or an array:
	// the API takes text, a JSON object or a JSON array where it takes
	// content, and text is written from a string, never from JSON.
	ErrContentShape = errors.New("JSON content must be an object or an array")
	// ErrUnsupportedValue reports a raw question field value of a type the
	// serialiser does not write, or a float that JSON cannot represent.
	ErrUnsupportedValue = errors.New("unsupported value")
)

Errors of the question serialiser.

Functions

func AppendAnswer

func AppendAnswer(dst []byte, a *Answer) ([]byte, error)

AppendAnswer appends a to dst as the payload of its kind: see AppendNoulAnswer, AppendChoiceAnswer and AppendScoreAnswer. An Answer of KindUnknown holds no value and is written null.

func AppendAnswers

func AppendAnswers(dst []byte, s *Answers) ([]byte, error)

AppendAnswers appends s to dst as a JSON object from question names to answers, in the order of Answers.Entries, as the answers member of a response payload. An entry of KindUnknown, which holds no value, is left out. A nil s is written {}.

func AppendChoiceAnswer

func AppendChoiceAnswer(dst []byte, a *ChoiceAnswer) ([]byte, error)

AppendChoiceAnswer appends a to dst as {"type":"choice","choice":…,"confidence":…,"probabilities":{…}}, the probabilities in the order the answer lists them.

func AppendContent

func AppendContent(dst []byte, c Content) ([]byte, error)

AppendContent appends c to dst: text as a JSON string (AppendString), a JSON object or array compacted (AppendJSON). JSON content that holds anything else fails with ErrContentShape.

func AppendJSON

func AppendJSON(dst, raw []byte) ([]byte, error)

AppendJSON appends raw, which must hold exactly one JSON value (RFC 8259) with optional whitespace around it, to dst without its insignificant whitespace. Everything else is copied byte for byte: strings keep their escape sequences, numbers their spelling.

The value is checked, not decoded: structure, literals, number grammar, string escapes, and that every string is valid UTF-8 without a raw control character. A failure is a *SyntaxError, and dst is returned unchanged. Nesting depth is not limited here; the scan is iterative and its memory grows with the depth only.

func AppendModelCard

func AppendModelCard(dst []byte, c *ModelCard) ([]byte, error)

AppendModelCard appends c to dst as {"name":…,"description":…,"release_date":…}, as the Python SDK's ModelMetadata.model_dump_json writes it.

func AppendModelList

func AppendModelList(dst []byte, l *ModelList) ([]byte, error)

AppendModelList appends l to dst as the payload of a list-models response, {"models":[{"name":…,"description":…,"release_date":…},…]}, as the Python SDK's ListModelsResponse.model_dump_json writes it.

func AppendNoulAnswer

func AppendNoulAnswer(dst []byte, a *NoulAnswer) ([]byte, error)

AppendNoulAnswer appends a to dst as {"type":"noul","noul":…}.

func AppendScoreAnswer

func AppendScoreAnswer(dst []byte, a *ScoreAnswer) ([]byte, error)

AppendScoreAnswer appends a to dst as {"type":"score","score":…,"confidence":…,"legend":{…},"probabilities":{…}}, the legend and the probabilities in the order the answer lists them, each level a decimal member name. A text level is a JSON string; a structured level is spliced as its bytes, which must hold one JSON object or array (the decoder's: the bytes the response carried). Empty structured bytes fail with ErrContentShape.

func AppendString

func AppendString(dst []byte, s string) ([]byte, error)

AppendString appends s to dst as a JSON string: quoted, with '"' and '\' escaped, U+0008, U+0009, U+000A, U+000C and U+000D written as \b, \t, \n, \f and \r, and the other characters below U+0020 as \u00XX. Everything else is copied as is: no HTML escaping, no escaping of U+007F, U+2028, U+2029 or any other non-ASCII character. The bytes are those typesafe-sdk-python's to_json writes for the same string.

It fails with ErrInvalidUTF8, returning dst unchanged, when s is not valid UTF-8.

func AppendSystemOneResult

func AppendSystemOneResult(dst []byte, r *SystemOneResult) ([]byte, error)

AppendSystemOneResult appends r to dst as the payload of a System One response, {"model":…,"usage":{…},"answers":{…}}, the bytes the Python SDK's SystemOneResponse.model_dump_json writes: no HTTP metadata, and none of the nouls, choices and scores views.

func AppendUsage

func AppendUsage(dst []byte, u *Usage) []byte

AppendUsage appends u to dst as {"input_tokens":…,"output_tokens":…}, a count the response left out as null, as the Python SDK's Usage.model_dump_json writes it.

func SkipSpace

func SkipSpace(raw []byte, i int) int

SkipSpace returns the offset of the first byte at or after i that is not JSON whitespace (space, tab, line feed, carriage return).

Types

type Answer

type Answer struct {
	// Kind selects the field that holds the value.
	Kind Kind
	// Noul is the value when Kind is KindNoul.
	Noul NoulAnswer
	// Choice is the value when Kind is KindChoice.
	Choice ChoiceAnswer
	// Score is the value when Kind is KindScore.
	Score ScoreAnswer
}

Answer is one answer of any kind. Kind says which of Noul, Choice and Score holds the value; the other two are zero. An Answer of KindUnknown holds no value.

type AnswerEntry

type AnswerEntry struct {
	// Name is the question name.
	Name string
	// Answer is the answer.
	Answer Answer
}

AnswerEntry is one answer with the name of the question it answers.

type Answers

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

Answers is the set of answers of one response, keyed by question name.

It behaves as a Python dict built from the response's "answers" object: a name keeps the position at which it first appeared and takes the value of its last appearance, so a document that repeats a name (JSON allows it, the API does not do it) yields one entry. The zero value is an empty set ready to use.

func (*Answers) Entries

func (s *Answers) Entries() []AnswerEntry

Entries returns the entries in the order their names first appeared. The slice is shared with s: callers must not modify it, and it is valid until the next Put.

func (*Answers) Get

func (s *Answers) Get(name string) (Answer, bool)

Get returns the answer to the question called name, and whether there is one.

func (*Answers) GrowInto

func (s *Answers) GrowInto(spare []AnswerEntry, n int)

GrowInto makes room for n more entries, so that the next n calls to Put with new names do not reallocate; a negative n is treated as zero. When the set is empty and spare's capacity has room for n entries, n > 0, the entries go into spare's array from its first element (its length is ignored), whose elements past len(s.Entries()) the set may overwrite, and nothing is allocated; otherwise the set grows its own array, and a set of no entries stays nil, as the decode without a spare leaves it. A caller that gives spare keeps no other use of its array.

func (*Answers) Len

func (s *Answers) Len() int

Len returns the number of entries.

func (*Answers) Put

func (s *Answers) Put(name string, a Answer)

Put stores a under name. A new name is appended; a name already present keeps its position and takes a (last wins).

type Builder

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

Builder serialises a question set, one question at a time, into the compact JSON object a request sends as "questions", and records the tables of a Prepared set on the way.

Members are written in the order the API's schema and the Python SDK use: "type", then "instructions", then "criteria". The zero Builder is ready to use. After a method returns an error the Builder must not be used again.

func (*Builder) Choice

func (b *Builder) Choice(name string, instructions *Content, labels []string, description func(i int) *Content) error

Choice writes a choice question whose options are labels, in order; the description of option i is description(i), written as null when it is nil. The labels become the question's Options table: the caller must not modify them afterwards. Labels are not checked for repeats.

func (*Builder) Finish

func (b *Builder) Finish(p *Prepared)

Finish closes the JSON object and makes *p the prepared set, so that a caller holding a Prepared inside a larger value does not pay a second allocation. Questions has no spare capacity: an append to it copies instead of writing into memory the set shares. The Builder must not be used afterwards.

func (*Builder) Grow

func (b *Builder) Grow(questions, size int)

Grow reserves room for questions more questions and size more bytes of serialised form, so that a Builder given a good estimate never regrows.

func (*Builder) GrowLevels

func (b *Builder) GrowLevels(n int)

GrowLevels reserves room for the spans of n more JSON score levels, the levels Builder.Finish points at their compact bytes, so that a Builder told how many there are records them without regrowing.

func (*Builder) Noul

func (b *Builder) Noul(name string, instructions, yes, no *Content) error

Noul writes a yes/no question. A nil instructions leaves the member out; a nil yes or no leaves that outcome out of "criteria", and "criteria" is left out when both are nil.

func (*Builder) Raw

func (b *Builder) Raw(name, typ string, fields map[string]any, leaf Leaf) error

Raw writes a question of type typ, a type the SDK may not model, whose other members are fields, in sorted key order after "type". A field value is nil, a bool, a string, an integer or float kind, []any, []string, map[string]any or map[string]string (maps written in sorted key order, nested to any depth up to 1000 levels), or a value leaf knows. fields must not name "type". The question's Kind is ParseKind of typ; a raw question has no Options or Levels table.

func (*Builder) Score

func (b *Builder) Score(name string, instructions *Content, levels []Content) error

Score writes a score question whose levels are levels, lowest first. The levels become the question's Levels table: the caller must not modify them afterwards, and [Builder.Prepared] points every JSON level at its compact bytes inside the finished set.

type ChoiceAnswer

type ChoiceAnswer struct {
	// Choice is the label of the option with the highest probability.
	Choice string
	// Confidence is how sure the model is of the pick, from 0 to 1.
	Confidence float64
	// Probabilities lists every option with its probability. Labels are
	// unique; the order is the order the decoder stored them in.
	Probabilities []LabelProbability
}

ChoiceAnswer is the value of a choice answer.

func (*ChoiceAnswer) Probability

func (a *ChoiceAnswer) Probability(label string) (float64, bool)

Probability returns the probability of the option called label, and whether the answer lists that option.

type Content

type Content struct {
	// Text is the text when JSON is nil, and empty otherwise.
	Text string
	// JSON is the encoding of a JSON object or array, or nil when the content
	// is text. An empty object is []byte("{}"), never nil.
	JSON []byte
}

Content is text, or a JSON object or array: the shape of question instructions, option and level descriptions, and the score legends a response echoes back.

Text is held decoded (no quotes, no escape sequences). A JSON object or array is held as bytes, so that it can be spliced into a request or compared with a response byte for byte: the compact bytes a question set produced, or the exact bytes a response carried, escapes and any whitespace included.

func (Content) IsJSON

func (c Content) IsJSON() bool

IsJSON reports whether c holds a JSON object or array rather than text.

type Kind

type Kind uint8

Kind is the kind of question an answer belongs to, named on the wire by the answer's "type" member.

const (
	// KindUnknown is the zero Kind: an answer whose type this version of the
	// SDK does not model, or one whose type is not known yet.
	KindUnknown Kind = iota
	// KindNoul is a yes/no answer, "type": "noul".
	KindNoul
	// KindChoice is a choice answer, "type": "choice".
	KindChoice
	// KindScore is a score answer, "type": "score".
	KindScore
)

func ParseKind

func ParseKind(typ string) Kind

ParseKind returns the Kind whose wire name is typ, or KindUnknown when typ names a type this version does not model. The match is exact and case-sensitive, as the API's discriminator is.

func (Kind) String

func (k Kind) String() string

String returns the wire name of k ("noul", "choice" or "score"), or "unknown" for KindUnknown and for any value outside the enumeration.

type LabelProbability

type LabelProbability struct {
	// Label is the option's name.
	Label string
	// Probability is the option's probability, from 0 to 1.
	Probability float64
}

LabelProbability is the probability the model gave one option of a choice question.

type Leaf

type Leaf func(dst []byte, v any) ([]byte, bool, error)

Leaf appends the JSON of a raw question field value of a type the serialiser does not know, and reports whether it knew it. The root package passes one for its own types.

type LegendEntry

type LegendEntry struct {
	// Level is the score level, counted from zero.
	Level uint32
	// Description is the level's description: text, or a JSON object or
	// array kept as the exact bytes it arrived as (the question's own bytes
	// when they are equal).
	Description Content
}

LegendEntry is the description a score question gave one level, as the response echoes it back.

type LevelProbability

type LevelProbability struct {
	// Level is the score level, counted from zero.
	Level uint32
	// Probability is the level's probability, from 0 to 1.
	Probability float64
}

LevelProbability is the probability the model gave one level of a score question.

type MemberError

type MemberError struct {
	// Member is the member's path inside the question object, as the API
	// names it: "instructions", "criteria.true", "criteria.<label>",
	// "criteria[<level>]", or a raw field's name followed by the path of the
	// offending value inside it (".key" and "[index]" segments).
	Member string
	// Err is the reason.
	Err error
}

MemberError reports a question member that could not be written.

func (*MemberError) Error

func (e *MemberError) Error() string

Error returns the member path and the reason. A path that is not valid UTF-8, such as one naming an option label with a stray byte, is quoted with Go escapes so that the text stays printable.

func (*MemberError) Unwrap

func (e *MemberError) Unwrap() error

Unwrap returns the reason.

type ModelCard

type ModelCard struct {
	// Name is the model name or alias a request's model member accepts.
	Name string
	// Description is the human-readable description of the model.
	Description string
	// ReleaseDate is the release date, formatted as YYYY-MM-DD.
	ReleaseDate string
}

ModelCard describes one model the account can use, as GET /v1/models lists it.

type ModelList

type ModelList struct {
	// Models lists the models the account can use, in the order the
	// response lists them.
	Models []ModelCard
}

ModelList is the decoded body of a list-models response.

type NoulAnswer

type NoulAnswer struct {
	// Noul is the probability, from 0 to 1, that the answer is yes or the
	// statement is true.
	Noul float64
}

NoulAnswer is the value of a yes/no answer.

type Prepared

type Prepared struct {
	// Questions is the compact JSON object that is the value of a request's
	// "questions" member, spliced into every request body as is.
	Questions []byte
	// contains filtered or unexported fields
}

Prepared is a question set serialised once and reused by every call that asks it.

It is read-only once Builder.Finish has made it, and safe for concurrent use. The entries sit behind Prepared.Entries so that the lookup index built over them cannot go stale.

func (*Prepared) Entries

func (p *Prepared) Entries() []PreparedQuestion

Entries returns the questions in the order they were added. The slice is shared with p: callers must not modify it.

func (*Prepared) Lookup

func (p *Prepared) Lookup(name string) (*PreparedQuestion, bool)

Lookup returns the question called name, and whether the set has one. The returned pointer refers into the set's own entries: it must not be used to modify them.

type PreparedQuestion

type PreparedQuestion struct {
	// Name is the question name.
	Name string
	// Kind is the question's kind.
	Kind Kind
	// Options lists a choice question's option labels in the order they were
	// added. It is nil for the other kinds.
	Options []string
	// Levels lists a score question's level descriptions; a description's
	// index is its level. It is nil for the other kinds.
	Levels []Content
}

PreparedQuestion is one question of a prepared set: its name and kind, and the tables the decoder interns response strings against.

type ResponseMeta

type ResponseMeta struct {
	// Status is the HTTP status code.
	Status int
	// Header is the response header. It is shared, not copied.
	Header http.Header
	// Body is the body exactly as it was received. It is shared, not
	// copied, and must not be modified.
	Body []byte
}

ResponseMeta is the HTTP side of a response: what it arrived with, kept for the caller and for error reports.

func (*ResponseMeta) RequestID

func (m *ResponseMeta) RequestID() (string, bool)

RequestID returns the server's identifier for the request, from the x-typesafe-request-id header, and whether the header was present. A header repeated in the response yields its values joined with ", " in the order they arrived, as the Python SDK's request_id reads them (httpx's Headers.get, py:_core/errors.py:115); a single value is returned as is, without allocating. The value is the server's text as it arrived: a caller that puts it into a log line or an error message escapes and cuts it first.

type ScoreAnswer

type ScoreAnswer struct {
	// Score is the expected score: the probability-weighted average of the
	// levels. It may fall between two levels.
	Score float64
	// Confidence is how sure the model is of the score, from 0 to 1.
	Confidence float64
	// Legend lists every level with its description. Levels are unique; the
	// order is the order the decoder stored them in.
	Legend []LegendEntry
	// Probabilities lists every level with its probability. Levels are
	// unique; the order is the order the decoder stored them in.
	Probabilities []LevelProbability
}

ScoreAnswer is the value of a score answer.

func (*ScoreAnswer) Description

func (a *ScoreAnswer) Description(level uint32) (Content, bool)

Description returns the description of level, and whether the legend lists that level.

func (*ScoreAnswer) Probability

func (a *ScoreAnswer) Probability(level uint32) (float64, bool)

Probability returns the probability of level, and whether the answer lists that level.

type SyntaxError

type SyntaxError struct {
	// Offset is the byte offset in the input at which the problem was found.
	Offset int
	// contains filtered or unexported fields
}

SyntaxError reports JSON text that is not exactly one valid JSON value.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

Error returns the problem and its offset.

type SystemOneResult

type SystemOneResult struct {
	// Model is the model that answered.
	Model string
	// Usage is the token usage the response reported.
	Usage Usage
	// Answers holds the answers, keyed by question name.
	Answers Answers
}

SystemOneResult is the decoded body of a System One response: the model that answered, the token usage and the answers.

type Usage

type Usage struct {
	// InputTokens is the number of billable input tokens.
	InputTokens uint64
	// OutputTokens is the number of output tokens.
	OutputTokens uint64
	// HasInputTokens reports whether the response carried input_tokens.
	HasInputTokens bool
	// HasOutputTokens reports whether the response carried output_tokens.
	HasOutputTokens bool
}

Usage is the token usage a response reported. The API may leave either count out; an absent count has its Has flag false and its value zero, which is never the same as a reported zero.

Jump to

Keyboard shortcuts

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