protocol

package
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Wire protocol abstraction shared by every agentic API, independent of any provider

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EstimateTokens

func EstimateTokens(parts []Part) int

Rough tokens the parts carry, text and arguments at four bytes a token and attachments at a flat figure

func MarshalBody

func MarshalBody(v any, extra map[string]json.RawMessage) ([]byte, error)

Serializes a wire request without HTML escaping and deep merges extra fields over it

func ParseArgs

func ParseArgs(raw string) (json.RawMessage, error)

Validates streamed tool arguments as a JSON object, treating no text as empty arguments

func Register

func Register(p Protocol)

Makes p available to Lookup under its ID, panicking on a duplicate

func Replayable

func Replayable(origin, id ID) bool

Reports whether a signed part may be replayed to protocol id, true when no origin was recorded

func RequiresMaxTokens

func RequiresMaxTokens(p Protocol) bool

Reports whether the protocol must be sent an output budget

Types

type Builder

type Builder struct {
	Response Response
	// Protocol stamped on signed parts so other protocols know not to replay them
	Origin ID
	// contains filtered or unexported fields
}

Assembles neutral events and the final Response from protocol specific stream fragments

func (*Builder) AddServerToolResult

func (b *Builder) AddServerToolResult(p ServerToolResult)

Appends a vendor side tool outcome as a complete part

func (*Builder) Cite

func (b *Builder) Cite(key string, c Citation) error

Attaches a source citation to the text block under key

func (*Builder) Close

func (b *Builder) Close(key string) error

Finalizes the block under key, parsing tool arguments into a JSON object

func (*Builder) Delta

func (b *Builder) Delta(key, delta string) error

Appends a text, thinking or tool argument fragment to the block under key

func (*Builder) Events

func (b *Builder) Events() []Event

Returns and clears the events produced since the previous call

func (*Builder) Finish

func (b *Builder) Finish(stop StopReason, raw string, usage Usage) error

Closes every open block in order, records the outcome and emits the done event

func (*Builder) IsOpen

func (b *Builder) IsOpen(key string) bool

Reports whether a block under key is still receiving deltas

func (*Builder) OpenServerToolCall

func (b *Builder) OpenServerToolCall(key, id, name string)

func (*Builder) OpenText

func (b *Builder) OpenText(key string)

func (*Builder) OpenThinking

func (b *Builder) OpenThinking(key string, redacted bool)

func (*Builder) OpenToolCall

func (b *Builder) OpenToolCall(key, id, name string)

func (*Builder) Signature

func (b *Builder) Signature(key, signature string) error

Appends replay signature bytes to the thinking or tool call block under key

func (*Builder) Start

func (b *Builder) Start(id, model string)

Records the response identity and emits the start event once

func (*Builder) Usage

func (b *Builder) Usage(u Usage)

Records usage known before the stream ends and emits a usage event

type Call

type Call struct {
	Method string
	// Path relative to the provider base URL, already containing any model segment
	Path   string
	Query  url.Values
	Header http.Header
	Body   []byte
}

HTTP request parts a provider completes with a base URL and credentials

type Citation

type Citation struct {
	Title string
	URL   string
	// Name or index of a supplied document the span was drawn from
	Document string
	// Character offsets of the span inside the owning text
	Start int
	End   int
	// Quoted source passage when the protocol supplies one
	Cited string
}

Source reference attached to a span of text

type Document

type Document struct {
	MediaType string
	Data      []byte
	Name      string
}

File contents such as a PDF or plain text handed to the model as a document

type Error

type Error struct {
	Status  int
	Type    string
	Message string
	// Overload or throttling the wire reports by type rather than status, worth a retry like a 429 or 5xx
	Transient bool
}

Failure reported by the remote API with its wire level type and message

func (*Error) Error

func (e *Error) Error() string

type Event

type Event struct {
	Type EventType
	// Position of the affected part in Response.Content
	Index int
	// Text, thinking or tool argument fragment on delta events
	Delta string
	// Every argument fragment received so far on tool call delta events
	Partial string
	// Initial part on start events and the complete part on end events
	Part Part
	// Source attached to the text part at Index on citation events
	Citation Citation
	Response Response
}

Incremental update of an assistant turn with the response assembled so far

type EventType

type EventType string
const (
	EventStart               EventType = "start"
	EventTextStart           EventType = "text_start"
	EventTextDelta           EventType = "text_delta"
	EventTextEnd             EventType = "text_end"
	EventThinkingStart       EventType = "thinking_start"
	EventThinkingDelta       EventType = "thinking_delta"
	EventThinkingEnd         EventType = "thinking_end"
	EventToolCallStart       EventType = "tool_call_start"
	EventToolCallDelta       EventType = "tool_call_delta"
	EventToolCallEnd         EventType = "tool_call_end"
	EventServerToolCallStart EventType = "server_tool_call_start"
	EventServerToolCallDelta EventType = "server_tool_call_delta"
	EventServerToolCallEnd   EventType = "server_tool_call_end"
	EventServerToolResult    EventType = "server_tool_result"
	EventCitation            EventType = "citation"
	EventUsage               EventType = "usage"
	EventDone                EventType = "done"
)

type ID

type ID string

Name of a wire protocol, matching the api ids used by pi-ai

const (
	AnthropicMessages     ID = "anthropic-messages"
	OpenAICompletions     ID = "openai-completions"
	OpenAIResponses       ID = "openai-responses"
	GoogleGenerativeAI    ID = "google-generative-ai"
	BedrockConverseStream ID = "bedrock-converse-stream"
	MistralConversations  ID = "mistral-conversations"
	OllamaChat            ID = "ollama-chat"
)

func IDs

func IDs() []ID

Lists registered protocol names in sorted order

type Image

type Image struct {
	MediaType string
	Data      []byte
}

Raw image bytes with their IANA media type

type MaxTokensRequired

type MaxTokensRequired interface {
	MaxTokensRequired() bool
}

Protocol whose API refuses a request that names no output budget

type Message

type Message struct {
	Role    Role
	Content []Part
}

One conversation turn made of ordered parts

type Part

type Part interface {
	// contains filtered or unexported methods
}

Marker implemented by Text, Image, Document, Thinking, ToolCall, ToolResult, ServerToolCall and ServerToolResult

type Protocol

type Protocol interface {
	ID() ID
	// Builds the HTTP call for req, with every protocol level header but no auth
	Encode(req Request) (Call, error)
	// Parses a complete non streaming response body
	Decode(r io.Reader) (Response, error)
	// Parses a streaming response body into neutral events ending with a done event
	Stream(r io.Reader) iter.Seq2[Event, error]
	// Parses a non 2xx response body into an Error carrying the wire message
	DecodeError(status int, body []byte) *Error
}

Encodes neutral requests to one wire format and decodes its responses back

func Lookup

func Lookup(id ID) (Protocol, bool)

Finds a registered protocol by name

type Request

type Request struct {
	Model  string
	System string
	// Sends the system slot even when empty so the endpoint puts no default prompt of its own in place
	KeepSystem bool
	Messages   []Message
	Tools      []Tool
	// Zero value means the model decides
	ToolChoice    ToolChoice
	MaxTokens     int
	Temperature   *float64
	StopSequences []string
	Stream        bool
	// Raw JSON deep merged over the encoded body for protocol specific fields
	Extra map[string]json.RawMessage
}

Protocol neutral turn request

type Response

type Response struct {
	ID            string
	Model         string
	Content       []Part
	StopReason    StopReason
	RawStopReason string
	Usage         Usage
}

Completed assistant turn

func Collect

func Collect(events iter.Seq2[Event, error]) (Response, error)

Drains a stream and returns the response carried by its done event

func (Response) Text

func (r Response) Text() string

Concatenated text parts of a response in order

func (Response) ToolCalls

func (r Response) ToolCalls() []ToolCall

Tool calls the model asked for in order

type Role

type Role string
const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	// Carries only ToolResult parts answering the previous assistant turn
	RoleTool Role = "tool"
)

type ServerToolCall

type ServerToolCall struct {
	ID     string
	Name   string
	Args   json.RawMessage
	Origin ID
}

Tool the vendor ran on its own side, such as web search, kept verbatim for replay

type ServerToolResult

type ServerToolResult struct {
	CallID  string
	Name    string
	Content json.RawMessage
	Origin  ID
}

Raw outcome of a vendor side tool, replayed only to the protocol that produced it

type StopReason

type StopReason string

Why the model stopped, normalized across protocols with the wire value kept beside it

const (
	StopEnd           StopReason = "stop"
	StopLength        StopReason = "length"
	StopToolUse       StopReason = "tool_use"
	StopContentFilter StopReason = "content_filter"
	// Wire value with no neutral meaning, see Response.RawStopReason
	StopOther StopReason = "other"
)

type Text

type Text struct {
	Text      string
	Citations []Citation
}

Model or user prose with any source citations the protocol attached to it

type Thinking

type Thinking struct {
	Text      string
	Signature string
	Redacted  bool
	// Protocol that issued the signature, so other protocols know not to replay it
	Origin ID
}

Model reasoning with the opaque replay token the protocol requires on the next turn

type Tool

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

Callable function offered to the model with a JSON Schema for its arguments

type ToolCall

type ToolCall struct {
	ID   string
	Name string
	Args json.RawMessage
	// Opaque replay token some protocols attach to the call itself
	Signature string
	// Protocol that issued the signature
	Origin ID
}

Model request to run a tool, with arguments as a JSON object

type ToolChoice

type ToolChoice struct {
	Mode ToolChoiceMode
	Name string
}

Constraint on whether and which tool the model must call

type ToolChoiceMode

type ToolChoiceMode string
const (
	ToolChoiceAuto     ToolChoiceMode = "auto"
	ToolChoiceNone     ToolChoiceMode = "none"
	ToolChoiceRequired ToolChoiceMode = "required"
	ToolChoiceTool     ToolChoiceMode = "tool"
)

type ToolResult

type ToolResult struct {
	CallID  string
	Name    string
	Content []Part
	IsError bool
}

Outcome of a tool run addressed to the call that asked for it

type Usage

type Usage struct {
	Input      int `json:"input"`
	Output     int `json:"output"`
	CacheRead  int `json:"cache_read"`
	CacheWrite int `json:"cache_write"`
	Reasoning  int `json:"reasoning"`
}

Token counts normalized so Input excludes cached tokens and Output includes reasoning

func (Usage) Add

func (u Usage) Add(o Usage) Usage

Sum of two usages field by field

func (Usage) Context

func (u Usage) Context() int

Tokens the request occupied on the input side, cached or not

func (Usage) Total

func (u Usage) Total() int

Every token the exchange consumed on either side

Directories

Path Synopsis
Anthropic Messages API wire protocol with paths relative to the api.anthropic.com origin
Anthropic Messages API wire protocol with paths relative to the api.anthropic.com origin
Amazon Bedrock Converse and ConverseStream wire protocol, paths relative to the regional bedrock-runtime host
Amazon Bedrock Converse and ConverseStream wire protocol, paths relative to the regional bedrock-runtime host
Gemini generateContent wire protocol with paths relative to the generativelanguage.googleapis.com origin
Gemini generateContent wire protocol with paths relative to the generativelanguage.googleapis.com origin
Mistral Conversations API, POST /v1/conversations under the api.mistral.ai base URL
Mistral Conversations API, POST /v1/conversations under the api.mistral.ai base URL
Ollama native chat wire protocol, POST /api/chat relative to the Ollama host such as http://localhost:11434
Ollama native chat wire protocol, POST /api/chat relative to the Ollama host such as http://localhost:11434
OpenAI Chat Completions wire protocol with paths relative to a base URL ending in /v1
OpenAI Chat Completions wire protocol with paths relative to a base URL ending in /v1
OpenAI Responses API wire protocol with paths relative to the api.openai.com/v1 base URL
OpenAI Responses API wire protocol with paths relative to the api.openai.com/v1 base URL

Jump to

Keyboard shortcuts

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