chat

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 21 Imported by: 5 modules, 4 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

Package chat defines the lowest-level LLM chat abstraction.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrContextLengthExceeded means the request exceeded the model's context window.
	ErrContextLengthExceeded = errors.New("context length exceeded")
	// ErrRateLimited means the model service rate limited the request.
	ErrRateLimited = errors.New("rate limited")
	// ErrUnauthorized means authentication with the model service failed.
	ErrUnauthorized = errors.New("unauthorized")
	// ErrAborted means the caller canceled the request.
	ErrAborted = errors.New("aborted")
)
View Source
var DefaultImageLimits = ImageLimits{
	MaxWidth:    2000,
	MaxHeight:   2000,
	MaxBytes:    4_718_592,
	JPEGQuality: 80,
}

DefaultImageLimits are conservative defaults: at most 2000 pixels on the longest side and at most 4.5MB of base64 (below Anthropic's 5MB limit).

Functions

func DetectMIME

func DetectMIME(data []byte) string

DetectMIME detects the MIME type from the content, returning application/octet-stream when it cannot be detected.

func Float

func Float(v float64) *float64

Float returns a pointer to v, for setting Options.Temperature.

func IsContextOverflow

func IsContextOverflow(message string) bool

IsContextOverflow reports whether an error message means the context window was exceeded.

func ParseOutput

func ParseOutput(msg *Message, format *OutputFormat) (json.RawMessage, error)

ParseOutput extracts JSON from an assistant message and validates it against the schema of format. JSON wrapped in a markdown code block is unwrapped first. A failed validation returns an *Error of KindInvalidOutput.

func ParseRetryAfter

func ParseRetryAfter(h http.Header) time.Duration

ParseRetryAfter parses the server's suggested retry delay from the response headers, returning 0 when it cannot be parsed.

func SchemaFor

func SchemaFor[T any](opts ...SchemaOption) (json.RawMessage, error)

SchemaFor generates a JSON Schema from a Go type, for structured output and tool parameters.

By default every struct field is required and extra fields are forbidden, which satisfies the strict modes of all providers; field descriptions are given with the `jsonschema:"description=..."` tag.

func ValidateJSON

func ValidateJSON(schema, data json.RawMessage) error

ValidateJSON validates a JSON document against a JSON Schema. An invalid schema also returns an error.

func WithUsageContext

func WithUsageContext(ctx context.Context, usageCtx UsageContext) context.Context

WithUsageContext stores business attribution in ctx for the usage recorder.

Types

type Builder

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

Builder accumulates a provider's streaming output and produces an event sequence that honors the Client contract.

Every provider emits events through a Builder: it guarantees that start comes first, blocks are closed in pairs, there is exactly one terminal event, and Event.Message is always the message accumulated so far. Each method returns false when the caller has stopped iterating; the provider should return immediately.

func NewBuilder

func NewBuilder(yield func(Event) bool, info ModelInfo) *Builder

NewBuilder creates a Builder. The provider, API and model of info are recorded on the assistant message and used to tell whether a replay goes to the same model.

func (*Builder) CurrentIndex

func (b *Builder) CurrentIndex() int

CurrentIndex returns the position of the open block in Message.Content, or -1 when no block is open.

func (*Builder) Done

func (b *Builder) Done(reason StopReason) bool

Done finishes normally with a done event. An empty reason is inferred from the content.

func (*Builder) EndBlock

func (b *Builder) EndBlock() bool

EndBlock closes the open text or thinking block. It does nothing when no block is open.

func (*Builder) Fail

func (b *Builder) Fail(err error) bool

Fail finishes with an error event; the message keeps the content generated so far. A tool call block that is still open has incomplete arguments and is dropped.

func (*Builder) Finished

func (b *Builder) Finished() bool

Finished reports whether a terminal event has been emitted or the caller has stopped iterating.

func (*Builder) Image

func (b *Builder) Image(mimeType string, data []byte) bool

Image appends a complete model-generated image and emits an image event.

func (*Builder) ImageSigned

func (b *Builder) ImageSigned(mimeType string, data []byte, signature string) bool

ImageSigned appends a generated image with a signature, a provider-private identifier that must be sent back unchanged on replay.

func (*Builder) RedactedThinking

func (b *Builder) RedactedThinking(data string) bool

RedactedThinking appends a redacted thinking block; data is the encrypted payload that must be sent back unchanged.

func (*Builder) SetResponse

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

SetResponse records the response ID and the actual model returned by the server.

func (*Builder) SetSignature

func (b *Builder) SetSignature(index int, signature string)

SetSignature sets the signature of an existing block, which may already be closed. Signatures are not part of the event content; they appear in the final message (the Message of the done / error event).

func (*Builder) SetUsage

func (b *Builder) SetUsage(u Usage)

SetUsage updates the accumulated token usage.

func (*Builder) SignOpenBlock

func (b *Builder) SignOpenBlock(signature string)

SignOpenBlock sets the signature of the open text or tool call block. It does nothing when no block is open. A signature is a provider-private identifier that must be sent back unchanged on replay and is only valid for the original model.

func (*Builder) Start

func (b *Builder) Start() bool

Start emits the start event. Calling it again has no effect.

func (*Builder) TextDelta

func (b *Builder) TextDelta(s string) bool

TextDelta appends a text delta, opening a text block if needed.

func (*Builder) ThinkingDelta

func (b *Builder) ThinkingDelta(s string) bool

ThinkingDelta appends a thinking delta, opening a thinking block if needed.

func (*Builder) ThinkingSignature

func (b *Builder) ThinkingSignature(sig string) bool

ThinkingSignature sets the signature of the current thinking block, opening one if needed.

func (*Builder) ToolCall

func (b *Builder) ToolCall(id, name string, args json.RawMessage) bool

ToolCall appends a complete tool call.

func (*Builder) ToolCallEnd

func (b *Builder) ToolCallEnd(args json.RawMessage) bool

ToolCallEnd closes the current tool call block with its complete arguments; empty arguments become {}.

func (*Builder) ToolCallStart

func (b *Builder) ToolCallStart(id, name string) bool

ToolCallStart opens a tool call block with empty arguments.

type CacheRetention

type CacheRetention string

CacheRetention is how long a prompt cache entry is kept.

const (
	CacheRetentionNone CacheRetention = "none"
	// CacheRetentionShort is the default (5 minutes on Anthropic).
	CacheRetentionShort CacheRetention = "short"
	// CacheRetentionLong uses the provider's long retention (1 hour on Anthropic, with more expensive writes).
	CacheRetentionLong CacheRetention = "long"
)

type Client

type Client interface {
	Stream(ctx context.Context, req Request) iter.Seq[Event]
	Info() ModelInfo
}

Client is the lowest-level chat client interface. It neither executes tools nor stores history.

The event sequence returned by Stream honors this contract:

  • it starts with EventStart and ends with exactly one EventDone or EventError;
  • text, thinking and tool call blocks come as paired Start/Delta/End events, and Index is the block's position in Message.Content; image blocks have no deltas: a single EventImage gives the complete image;
  • every failure (including cancellation) is reported through EventError, whose Message keeps the content generated so far; on failure a tool call block that is still open has incomplete arguments and is dropped (no end event);
  • Event.Message is a live object that advances with the events and is only valid during the callback; call Clone to keep it;
  • when the caller stops iterating early, the implementation should release the underlying connection immediately.

func Chain

func Chain(base Client, middlewares ...Middleware) Client

Chain applies middlewares in order: the first is the outermost, seeing the request first and the events last.

func WithUsageRecorder

func WithUsageRecorder(base Client, recorder UsageRecorder, opts ...UsageOption) Client

WithUsageRecorder adds usage recording to a Client.

type ContentBlock

type ContentBlock struct {
	Type ContentType `json:"type"`
	// Text is the text of a text or thinking block.
	Text string `json:"text,omitempty"`
	// Signature is the replayable signature of a thinking block; a redacted thinking block stores its encrypted payload here.
	Signature string `json:"signature,omitempty"`
	// Redacted marks a thinking block hidden by safety policy; only Signature is meaningful.
	Redacted bool `json:"redacted,omitempty"`
	// The next five fields describe a media block: MIMEType decides how the model handles it, the content comes from
	// File (a file uploaded to the provider), Data (inline) or URL, and Name is an optional file name.
	// File is used when the target model can reach it; otherwise Data or URL is the fallback, see NormalizeForModel.
	MIMEType string   `json:"mime_type,omitempty"`
	Data     []byte   `json:"data,omitempty"`
	URL      string   `json:"url,omitempty"`
	File     *FileRef `json:"file,omitempty"`
	Name     string   `json:"name,omitempty"`
	// ToolCall is the content of a tool call block.
	ToolCall *ToolCall `json:"tool_call,omitempty"`
}

ContentBlock is a message content block. The blocks of an assistant message keep the exact order returned by the model and are restored unchanged when sent back.

func CloneBlocks

func CloneBlocks(in []ContentBlock) []ContentBlock

CloneBlocks returns a deep copy of the content blocks.

func Media

func Media(data []byte) ContentBlock

Media creates an inline media block: an image, PDF, audio, video, text file or any other content. The type is detected from the content; it is application/octet-stream when it cannot be detected. When the detected type is not specific enough (an Office document is only detected as zip, for example), give a file name with an extension via WithName, or set the type with WithMIME.

The framework does not restrict, convert or compress the content; it passes it to the provider as is. Whether the provider accepts it is for the caller to check; when it does not, the request fails.

func MediaFile added in v0.2.1

func MediaFile(file FileRef, mimeType string) ContentBlock

MediaFile creates a media block that refers to an uploaded file. mimeType is required: it decides whether the file is sent as an image or a document. Without a fallback the block becomes a note when the target model cannot reach the file; prefer WithFile on a block that keeps the URL or data.

func MediaURL

func MediaURL(rawURL string) ContentBlock

MediaURL creates a media block that references a URL; the provider fetches the content itself. The type is inferred from the extension of the URL path, falling back to application/octet-stream; WithMIME sets it explicitly.

The framework neither downloads nor checks the URL: whether it is reachable, whether the content fits the model's size limits and when the link expires are the caller's responsibility. History is replayed on every turn, so once the link breaks every request in the session fails.

func Text

func Text(text string) ContentBlock

Text creates a text content block.

func (ContentBlock) IsAudio

func (b ContentBlock) IsAudio() bool

IsAudio reports whether the block is audio.

func (ContentBlock) IsImage

func (b ContentBlock) IsImage() bool

IsImage reports whether the block is an image.

func (ContentBlock) IsMedia

func (b ContentBlock) IsMedia() bool

IsMedia reports whether the block is a media block.

func (ContentBlock) IsVideo

func (b ContentBlock) IsVideo() bool

IsVideo reports whether the block is video.

func (ContentBlock) WithFile added in v0.2.1

func (b ContentBlock) WithFile(file FileRef) ContentBlock

WithFile returns the media block referring to an uploaded file; its URL or data stays as the fallback for models that cannot reach the file.

func (ContentBlock) WithMIME

func (b ContentBlock) WithMIME(mimeType string) ContentBlock

WithMIME returns the media block with the given MIME type.

func (ContentBlock) WithName

func (b ContentBlock) WithName(name string) ContentBlock

WithName returns the media block with a file name. When the type is not detected yet or not specific enough, it is completed from the file extension.

type ContentType

type ContentType string

ContentType is the type of a message content block.

const (
	ContentTypeText ContentType = "text"
	// ContentTypeMedia is media content such as images, documents, audio and video; see Media and MediaURL.
	ContentTypeMedia    ContentType = "media"
	ContentTypeThinking ContentType = "thinking"
	ContentTypeToolCall ContentType = "tool_call"
)

type Error

type Error struct {
	Kind ErrorKind
	// Status is the HTTP status code, or 0 when unknown.
	Status int
	// RetryAfter is the delay suggested by the server, or 0 when not provided.
	RetryAfter time.Duration
	Message    string
	// Err is the underlying original error.
	Err error
}

Error is the chat layer's unified model call error.

func AsError

func AsError(err error) *Error

AsError converts any error to an *Error, returning an *Error unchanged.

func WrapError

func WrapError(ctx context.Context, err error, status int, retryAfter time.Duration) *Error

WrapError wraps a provider's underlying error as an *Error.

A finished ctx means the caller canceled, which is classified as KindAborted; when status is 0 the error type and message decide.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is lets errors.Is match sentinel errors by kind.

func (*Error) Retryable

func (e *Error) Retryable() bool

Retryable reports whether the error is worth retrying.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorKind

type ErrorKind string

ErrorKind classifies a failed model call, to decide whether to retry or to compact the context.

const (
	KindUnknown        ErrorKind = "unknown"
	KindContextLength  ErrorKind = "context_length"
	KindRateLimit      ErrorKind = "rate_limit"
	KindQuota          ErrorKind = "quota"
	KindServer         ErrorKind = "server"
	KindNetwork        ErrorKind = "network"
	KindAuth           ErrorKind = "auth"
	KindInvalidRequest ErrorKind = "invalid_request"
	KindRefusal        ErrorKind = "refusal"
	// KindInvalidOutput means the model output does not have the required format (invalid JSON or not matching the schema).
	KindInvalidOutput ErrorKind = "invalid_output"
	KindAborted       ErrorKind = "aborted"
)

func ClassifyMessage

func ClassifyMessage(message string) ErrorKind

ClassifyMessage classifies an error by its message when there is no status code (for example an error event in the middle of a stream).

func ClassifyStatus

func ClassifyStatus(status int, message string) ErrorKind

ClassifyStatus classifies an error by its HTTP status code and message.

func (ErrorKind) Retryable

func (k ErrorKind) Retryable() bool

Retryable reports whether this kind of error is usually transient, so a retry may succeed.

type Event

type Event struct {
	Type EventType
	// Index is the position in Message.Content of the content block the event belongs to.
	Index int
	// Delta is the incremental text of text_delta / thinking_delta.
	Delta string
	// Content is the complete text of the block at text_end / thinking_end.
	Content string
	// ToolCall is set on tool_call_start / tool_call_end events.
	ToolCall *ToolCall
	// Reason gives the stop reason on done / error events.
	Reason StopReason
	// Message is the assistant message accumulated so far; on done / error it is the final message.
	// It is a live object that is only valid during the callback; call Clone to keep it.
	Message *Message
	// Err gives the typed error on error events.
	Err error
}

Event is a streaming model output event. It only describes model output, not tool execution.

type EventType

type EventType string

EventType is the type of a streaming chat event.

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"
	// At EventToolCallStart the tool name is known and the arguments are empty; EventToolCallEnd carries the complete call.
	// Tool arguments are not streamed incrementally yet, so there is no tool_call_delta.
	EventToolCallStart EventType = "tool_call_start"
	EventToolCallEnd   EventType = "tool_call_end"
	// EventImage gives a complete model-generated image. Image blocks have no deltas; the event itself closes the block.
	EventImage EventType = "image"
	EventDone  EventType = "done"
	EventError EventType = "error"
)

type FileRef added in v0.2.1

type FileRef struct {
	// Scope names the store the file lives in and must equal the target model's ModelInfo.FileScope for the file to be used.
	Scope string `json:"scope"`
	// ID is the provider's file ID; for Gemini it is the file URI.
	ID string `json:"id"`
	// ExpiresAt is when the store deletes the file, zero for never; shortly before it the file is no longer used.
	ExpiresAt time.Time `json:"expires_at,omitzero"`
}

FileRef refers to a file uploaded to a provider's file store, such as the Anthropic or OpenAI Files API, so requests carry an ID instead of the content. Provider clients' UploadFile returns a media block with it filled in.

File IDs are readable by every key of the store (an Anthropic workspace, an OpenAI project): create and keep them on the server side and never accept them from end users, or one user can read another's files.

type HTTPHooks

type HTTPHooks struct {
	// OnPayload receives the raw request body before it is sent; a non-nil return value replaces the body, nil leaves it unchanged.
	OnPayload func(ctx context.Context, body []byte) []byte
	// OnResponse is called after the response headers arrive, before the body is read.
	OnResponse func(ctx context.Context, status int, header http.Header)
}

HTTPHooks are debugging hooks at the raw HTTP layer. They sit below each provider's SDK and see the request body actually sent. Use them to inspect requests, read rate limit headers, or patch parameters that are not wrapped yet; for regular extensions use Middleware.

func (HTTPHooks) HTTPClient

func (h HTTPHooks) HTTPClient(base *http.Client) *http.Client

HTTPClient returns an http.Client with the hooks installed; without hooks it returns base unchanged. A nil base uses the default configuration.

type Hooks

type Hooks struct {
	// BeforeRequest is called before the request is sent and may modify it (slices in the request are shared with the caller;
	// copy them before changing messages). Returning an error aborts the call and the stream ends with an error event.
	BeforeRequest func(ctx context.Context, req *Request) error
	// OnEvent is called for every event. Event.Message is only valid during the callback.
	OnEvent func(ctx context.Context, event Event)
	// AfterResponse is called after the stream ends with the final message, also on failure (including the partial content).
	// It is not called when the caller stops iterating early.
	AfterResponse func(ctx context.Context, req Request, msg *Message)
}

Hooks are callbacks for observing or slightly adjusting requests, a simplified form of Wrap. Every field may be nil.

type ImageLimits

type ImageLimits struct {
	MaxWidth  int
	MaxHeight int
	// MaxBytes limits the size after base64 encoding.
	MaxBytes    int
	JPEGQuality int
}

ImageLimits describe the image specs a model accepts.

func (ImageLimits) WithDefaults

func (l ImageLimits) WithDefaults() ImageLimits

WithDefaults fills zero fields from DefaultImageLimits.

type Message

type Message struct {
	Role    Role           `json:"role"`
	Content []ContentBlock `json:"content,omitempty"`

	ToolCallID string `json:"tool_call_id,omitempty"`
	ToolName   string `json:"tool_name,omitempty"`
	IsError    bool   `json:"is_error,omitempty"`
	Details    any    `json:"details,omitempty"`

	// The following fields are only meaningful on assistant messages. Provider is the vendor that served the reply,
	// API the protocol it came over (see ModelInfo.API), Model the model asked for and ResponseModel the one that answered.
	Provider      string     `json:"provider,omitempty"`
	API           string     `json:"api,omitempty"`
	Model         string     `json:"model,omitempty"`
	ResponseModel string     `json:"response_model,omitempty"`
	ResponseID    string     `json:"response_id,omitempty"`
	Usage         Usage      `json:"usage,omitzero"`
	StopReason    StopReason `json:"stop_reason,omitempty"`
	ErrorMessage  string     `json:"error_message,omitempty"`
	ErrorKind     ErrorKind  `json:"error_kind,omitempty"`

	CreatedAt time.Time `json:"created_at,omitzero"`
}

Message is a provider-neutral chat message.

A user message's Content may mix text and media; an assistant message's Content may mix text, thinking, tool calls and generated images; a tool result message uses ToolCallID, ToolName, IsError and Details.

func Collect

func Collect(events iter.Seq[Event]) (*Message, error)

Collect consumes an event sequence and returns the final assistant message.

func Complete

func Complete(ctx context.Context, c Client, req Request) (*Message, error)

Complete consumes a Client's stream and returns the final assistant message. When the model call fails it returns the partial message generated so far and a typed error (*Error).

func CompleteJSON

func CompleteJSON[T any](ctx context.Context, c Client, req Request) (T, *Message, error)

CompleteJSON requests structured output and decodes it into T.

When req.Output is nil the schema is generated from T (T should be a struct). The returned message is the complete assistant message and can be appended to history. A failed model call, truncated output or output not matching the schema returns a typed *Error.

func NewUserTextMessage

func NewUserTextMessage(text string) Message

NewUserTextMessage creates a user text message.

func NormalizeForModel

func NormalizeForModel(msgs []Message, target ModelInfo, opts ...NormalizeOption) []Message

NormalizeForModel turns history into a form the target model accepts, without modifying its input:

  • drops error / aborted assistant messages: they are incomplete turns and replaying them makes the API fail;
  • adds an error result for tool calls without one, and drops orphan tool results without a matching call;
  • downgrades thinking blocks from other models to text and drops redacted ones; tool call IDs can be normalized, and provider-private signatures on text and tool call blocks, valid only for the original model, are cleared across models;
  • when the target endpoint does not support media input (see ModelInfo.SupportsMedia), replaces media in user messages and tool results with a note; uploaded files the target cannot reach (another FileScope, or about to expire) fall back to the block's data or URL, or to a note;
  • when the target model cannot replay generated images, replaces images in assistant messages with placeholder text; otherwise keeps them, without signatures across models.

func (Message) Clone

func (m Message) Clone() Message

Clone returns a deep copy of the message.

func (Message) TextContent

func (m Message) TextContent() string

TextContent joins the text blocks of the message, for logs and tests.

func (Message) ToolCalls

func (m Message) ToolCalls() []ToolCall

ToolCalls returns the tool calls in the message, in order.

type Middleware

type Middleware func(Client) Client

Middleware wraps a Client and returns a Client with extra behavior. Logging, usage recording, retries and falling back to another model are all implemented this way, and Chain stacks them.

func WithHooks

func WithHooks(h Hooks) Middleware

WithHooks turns Hooks into a middleware.

func Wrap

func Wrap(fn WrapFunc) Middleware

Wrap builds a middleware from a wrap function.

type ModelInfo

type ModelInfo struct {
	// Provider is the vendor serving the model (anthropic, deepseek...), for display, usage and errors.
	Provider string
	// API is the protocol of the endpoint (anthropic-messages, openai-responses...). Replies keep provider-private data
	// (signatures, item IDs) that only the same provider, API and model can replay.
	API             string
	Model           string
	MaxInputTokens  int
	MaxOutputTokens int
	// SupportsMedia reports whether the endpoint accepts media input. When false (a text-only endpoint), media blocks in user
	// messages and tool results are replaced with a note before the request is sent. It does not distinguish media types: whether a type is accepted is up to the provider.
	SupportsMedia bool
	// ImageOutput reports whether model-generated images in assistant messages can be replayed to this model;
	// when false, replaying history replaces those images with placeholder text.
	ImageOutput bool
	// StructuredOutput reports whether the model natively supports output constrained by a JSON Schema;
	// when false, the provider writes the format requirements into the system prompt.
	StructuredOutput bool
	// FileScope names the file store this endpoint reads uploaded files from (see FileRef.Scope), empty when it reads none.
	// Media blocks whose file belongs to another scope fall back to their data or URL on replay.
	FileScope string
	// ImageLimits are the image specs the model accepts, for callers that process images with imageproc; zero fields use the defaults.
	ImageLimits ImageLimits
}

ModelInfo describes the runtime configuration of a model.

type NormalizeOption

type NormalizeOption func(*normalizeConfig)

NormalizeOption adjusts the behavior of NormalizeForModel.

func WithToolCallIDNormalizer

func WithToolCallIDNormalizer(fn func(id string) string) NormalizeOption

WithToolCallIDNormalizer sets a function that normalizes tool call IDs. It only applies to history from other models; Anthropic, for example, requires IDs made of letters, digits, underscores and hyphens.

type Options

type Options struct {
	// Model defaults to the Client's model when empty.
	Model     string
	MaxTokens int
	// Temperature uses the model default when nil; it can be set to 0 explicitly.
	Temperature *float64
	// Output, when set, requires output that follows a JSON Schema; see OutputFormat.
	Output *OutputFormat
	// ToolChoice constrains tool calls; see ToolChoice.
	ToolChoice ToolChoice
	// Reasoning uses the model's default behavior when empty.
	Reasoning ReasoningLevel
	// CacheRetention defaults to CacheRetentionShort when empty; providers without explicit caching ignore it.
	CacheRetention CacheRetention
	Metadata       map[string]string
}

Options are the model parameters of one request. The agent passes them through unchanged, so new parameters need no changes in upper layers.

type OutputFormat

type OutputFormat struct {
	// Name is the schema name, made of letters, digits, underscores and hyphens; it defaults to "output" when empty.
	Name string
	// Schema is the JSON Schema the output must satisfy; its root should be an object.
	Schema json.RawMessage
}

OutputFormat requires the model to produce output that follows a JSON Schema.

When the model supports structured output natively (ModelInfo.StructuredOutput), the provider uses native constrained decoding; otherwise it writes the schema into the system prompt. Either way the result should be validated locally with ParseOutput. Providers accept different subsets of JSON Schema and OpenAI is the strictest: every object field is required and extra fields are forbidden. Schemas generated by SchemaFor meet this requirement.

type ReasoningLevel

type ReasoningLevel string

ReasoningLevel is a provider-neutral thinking effort, mapped by each provider to its own parameter (Anthropic's adaptive thinking effort or thinking budget, OpenAI's reasoning.effort).

const (
	// ReasoningOff turns thinking off; models that cannot turn it off use the lowest effort.
	ReasoningOff    ReasoningLevel = "off"
	ReasoningLow    ReasoningLevel = "low"
	ReasoningMedium ReasoningLevel = "medium"
	ReasoningHigh   ReasoningLevel = "high"
	// ReasoningXHigh falls back to high when the model does not support it.
	ReasoningXHigh ReasoningLevel = "xhigh"
)

type Request

type Request struct {
	Options
	SystemPrompt string
	Messages     []Message
	Tools        []ToolDef
}

Request is a chat request.

func WithOutputInstructions

func WithOutputInstructions(req Request) Request

WithOutputInstructions returns the request with the output format written into the system prompt and Output cleared, for providers without native structured output.

type Role

type Role string

Role is the role of a conversation message.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

type SchemaOption

type SchemaOption func(*schemaConfig)

SchemaOption adjusts how SchemaFor generates a schema.

func AllowOptional

func AllowOptional() SchemaOption

AllowOptional keeps optional fields: fields with omitempty are left out of required. Tool parameters use this form; structured output needs the default strict form.

type StopReason

type StopReason string

StopReason is why the model stopped generating.

const (
	StopReasonStop    StopReason = "stop"
	StopReasonLength  StopReason = "length"
	StopReasonToolUse StopReason = "tool_use"
	StopReasonError   StopReason = "error"
	StopReasonAborted StopReason = "aborted"
)

type StreamFunc

type StreamFunc func(ctx context.Context, req Request) iter.Seq[Event]

StreamFunc is one model call, with the same signature as Client.Stream.

type ToolCall

type ToolCall struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments,omitempty"`
}

ToolCall is a tool call requested by the model.

type ToolChoice

type ToolChoice struct {
	Mode ToolChoiceMode
	// Name is only used when Mode is ToolChoiceTool.
	Name string
}

ToolChoice constrains tool calls; the zero value uses the model's default behavior (auto). It is ignored when the request has no tools.

func ForceTool

func ForceTool(name string) ToolChoice

ForceTool returns a ToolChoice that requires a call to the named tool.

type ToolChoiceMode

type ToolChoiceMode string

ToolChoiceMode controls whether and how the model calls tools.

const (
	ToolChoiceAuto ToolChoiceMode = "auto"
	// ToolChoiceNone forbids tool calls.
	ToolChoiceNone ToolChoiceMode = "none"
	// ToolChoiceRequired requires at least one tool call.
	ToolChoiceRequired ToolChoiceMode = "required"
	// ToolChoiceTool requires a call to the tool named by ToolChoice.Name.
	ToolChoiceTool ToolChoiceMode = "tool"
)

type ToolDef

type ToolDef struct {
	Name          string           `json:"name"`
	Description   string           `json:"description,omitempty"`
	InputSchema   json.RawMessage  `json:"input_schema,omitempty"`
	InputExamples []map[string]any `json:"input_examples,omitempty"`
}

ToolDef is a tool definition exposed to the model.

type Usage

type Usage struct {
	Input       int     `json:"input"`
	Output      int     `json:"output"`
	CacheRead   int     `json:"cache_read"`
	CacheWrite  int     `json:"cache_write"`
	TotalTokens int     `json:"total_tokens"`
	Cost        float64 `json:"cost,omitempty"`
}

Usage holds the standard token usage of one model call.

func (Usage) Add

func (u Usage) Add(other Usage) Usage

Add returns the sum of two Usage values.

type UsageContext

type UsageContext struct {
	RequestID string
	UserID    string
	SessionID string
	TraceID   string
	Source    string
	Metadata  map[string]string
}

UsageContext holds business attribution for one model call. These fields change per request, so they travel in context.Context rather than in the Client configuration.

func UsageContextFromContext

func UsageContextFromContext(ctx context.Context) UsageContext

UsageContextFromContext reads business attribution from ctx.

type UsageEvent

type UsageEvent struct {
	Provider  string
	Model     string
	Method    string
	Usage     Usage
	Error     string
	StartedAt time.Time
	EndedAt   time.Time

	RequestID string
	UserID    string
	SessionID string
	TraceID   string
	Source    string
	Metadata  map[string]string
}

UsageEvent is the usage event emitted after a model request completes.

type UsageOption

type UsageOption func(*usageRecorderClient)

UsageOption configures the usage recorder wrapper.

func WithUsageProviderName

func WithUsageProviderName(name string) UsageOption

WithUsageProviderName sets the provider name in usage events.

type UsageRecorder

type UsageRecorder func(ctx context.Context, event UsageEvent) error

UsageRecorder is implemented by the caller to persist or report model usage. Recorder errors do not affect the model call.

type WrapFunc

type WrapFunc func(ctx context.Context, req Request, info ModelInfo, next StreamFunc) iter.Seq[Event]

WrapFunc wraps one model call: it can rewrite the request, observe or rewrite events, or call next zero or several times. The returned sequence must honor the Client.Stream contract. info is the model info of the wrapped Client.

Directories

Path Synopsis
api
anthropic module
gemini module
openai module
Package chattest provides a scripted Client for testing users of chat.Client, plus a stream contract checker.
Package chattest provides a scripted Client for testing users of chat.Client, plus a stream contract checker.
Package imageproc normalizes an image once before it enters the conversation history: it detects the format, converts it to a format models accept, and limits its dimensions and size.
Package imageproc normalizes an image once before it enters the conversation history: it detects the format, converts it to a format models accept, and limits its dimensions and size.
provider
anthropic
Package anthropic implements chat.Client with the Anthropic Messages API.
Package anthropic implements chat.Client with the Anthropic Messages API.
deepseek
Package deepseek provides constructors for DeepSeek chat.Clients.
Package deepseek provides constructors for DeepSeek chat.Clients.
gemini
Package gemini implements chat.Client for Gemini on top of the official google.golang.org/genai SDK.
Package gemini implements chat.Client for Gemini on top of the official google.golang.org/genai SDK.
openai
Package openai implements chat.Client with the OpenAI Responses API; it also works with endpoints compatible with the Responses API (such as DeepSeek).
Package openai implements chat.Client with the OpenAI Responses API; it also works with endpoints compatible with the Responses API (such as DeepSeek).

Jump to

Keyboard shortcuts

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