Documentation
¶
Overview ¶
Package chat defines the lowest-level LLM chat abstraction.
Index ¶
- Variables
- func DetectMIME(data []byte) string
- func Float(v float64) *float64
- func IsContextOverflow(message string) bool
- func ParseOutput(msg *Message, format *OutputFormat) (json.RawMessage, error)
- func ParseRetryAfter(h http.Header) time.Duration
- func SchemaFor[T any](opts ...SchemaOption) (json.RawMessage, error)
- func ValidateJSON(schema, data json.RawMessage) error
- func WithUsageContext(ctx context.Context, usageCtx UsageContext) context.Context
- type Builder
- func (b *Builder) CurrentIndex() int
- func (b *Builder) Done(reason StopReason) bool
- func (b *Builder) EndBlock() bool
- func (b *Builder) Fail(err error) bool
- func (b *Builder) Finished() bool
- func (b *Builder) Image(mimeType string, data []byte) bool
- func (b *Builder) ImageSigned(mimeType string, data []byte, signature string) bool
- func (b *Builder) RedactedThinking(data string) bool
- func (b *Builder) ServerTool(name string, raw json.RawMessage) bool
- func (b *Builder) SetResponse(id, model string)
- func (b *Builder) SetSignature(index int, signature string)
- func (b *Builder) SetUsage(u Usage)
- func (b *Builder) SignOpenBlock(signature string)
- func (b *Builder) Start() bool
- func (b *Builder) TextDelta(s string) bool
- func (b *Builder) ThinkingDelta(s string) bool
- func (b *Builder) ThinkingSignature(sig string) bool
- func (b *Builder) ToolCall(id, name string, args json.RawMessage) bool
- func (b *Builder) ToolCallEnd(args json.RawMessage) bool
- func (b *Builder) ToolCallStart(id, name string) bool
- type CacheRetention
- type Client
- type ContentBlock
- func (b ContentBlock) IsAudio() bool
- func (b ContentBlock) IsImage() bool
- func (b ContentBlock) IsMedia() bool
- func (b ContentBlock) IsVideo() bool
- func (b ContentBlock) WithFile(file FileRef) ContentBlock
- func (b ContentBlock) WithMIME(mimeType string) ContentBlock
- func (b ContentBlock) WithName(name string) ContentBlock
- type ContentType
- type Error
- type ErrorKind
- type Event
- type EventType
- type FileRef
- type HTTPHooks
- type Hooks
- type ImageLimits
- type Message
- func Collect(events iter.Seq[Event]) (*Message, error)
- func Complete(ctx context.Context, c Client, req Request) (*Message, error)
- func CompleteJSON[T any](ctx context.Context, c Client, req Request) (T, *Message, error)
- func NewUserTextMessage(text string) Message
- func NormalizeForModel(msgs []Message, target ModelInfo, opts ...NormalizeOption) []Message
- type Middleware
- type ModelInfo
- type NormalizeOption
- type Options
- type OutputFormat
- type ReasoningLevel
- type Request
- type Role
- type SchemaOption
- type StopReason
- type StreamFunc
- type ToolCall
- type ToolChoice
- type ToolChoiceMode
- type ToolDef
- type Usage
- type UsageContext
- type UsageEvent
- type UsageOption
- type UsageRecorder
- type WrapFunc
Constants ¶
This section is empty.
Variables ¶
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 = errors.New("unauthorized") // ErrAborted means the caller canceled the request. ErrAborted = errors.New("aborted") )
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 ¶
DetectMIME detects the MIME type from the content, returning application/octet-stream when it cannot be detected.
func IsContextOverflow ¶
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 ¶
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 ¶
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 ¶
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 ¶
EndBlock closes the open text or thinking block. It does nothing when no block is open.
func (*Builder) Fail ¶
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 ¶
Finished reports whether a terminal event has been emitted or the caller has stopped iterating.
func (*Builder) ImageSigned ¶
ImageSigned appends a generated image with a signature, a provider-private identifier that must be sent back unchanged on replay.
func (*Builder) RedactedThinking ¶
RedactedThinking appends a redacted thinking block; data is the encrypted payload that must be sent back unchanged.
func (*Builder) ServerTool ¶ added in v0.2.3
func (b *Builder) ServerTool(name string, raw json.RawMessage) bool
ServerTool appends a complete record of a tool the provider ran on its side and emits a server_tool event; raw is replayed unchanged to the same API.
func (*Builder) SetResponse ¶
SetResponse records the response ID and the actual model returned by the server.
func (*Builder) SetSignature ¶
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) SignOpenBlock ¶
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) ThinkingDelta ¶
ThinkingDelta appends a thinking delta, opening a thinking block if needed.
func (*Builder) ThinkingSignature ¶
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 ¶
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 ¶
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 and server tool blocks have no deltas: a single EventImage or EventServerTool gives the complete block;
- 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"`
// Raw is the provider's own JSON of a server tool block; Name then holds the server tool's name.
Raw json.RawMessage `json:"raw,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.
What a block points to (the bytes of Data, Raw and ToolCall.Arguments, and *File) is read-only once the block is handed on: the framework shares it between copies instead of copying it, so code that needs other content assigns new values rather than writing into them. A caller passing Data in must not reuse that buffer afterwards.
func CloneBlocks ¶
func CloneBlocks(in []ContentBlock) []ContentBlock
CloneBlocks returns a copy of the content blocks that can be changed without affecting in, sharing the bytes they point to.
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 (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" // ContentTypeServerTool is a record of a tool the provider ran on its side, such as a tool search call and its result. // It is provider-private: Raw is sent back unchanged to the same API and dropped for any other, see ServerTool. ContentTypeServerTool ContentType = "server_tool" )
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 WrapError ¶
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.
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 ¶
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 ¶
ClassifyStatus classifies an error by its HTTP status code and message.
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" // EventServerTool gives a complete record of a tool the provider ran on its side, such as a tool search; like an image, // the event itself closes the block. It is for progress display only: the record needs no handling. EventServerTool EventType = "server_tool" 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.
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 Complete ¶
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 ¶
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 ¶
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;
- keeps server tool records only for the API that produced them;
- 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 ¶
Clone returns a copy of the message whose blocks can be changed without affecting m. The bytes the blocks point to are shared, as they are read-only (see ContentBlock), so a copy costs the same however large its media.
func (Message) TextContent ¶
TextContent joins the text blocks of the message, for logs and tests.
type Middleware ¶
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.
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 {
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. The model is not among them: a Client talks to one model, and another model is another Client.
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" // ReasoningMax is the highest effort; it falls back to xhigh when the model does not support it. ReasoningMax ReasoningLevel = "max" )
type Request ¶
Request is a chat request.
func WithOutputInstructions ¶
WithOutputInstructions returns the request with the output format written into the system prompt and Output cleared, for providers without native structured output.
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 ¶
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"`
// Deferred keeps the tool out of the model's context until the model finds it through the provider's tool search.
// The full definition is still sent with every request, since the provider searches it there; once found it enters the
// context and stays callable for the rest of the conversation. Providers or models without tool search ignore it and
// show the tool from the start. Keep it stable within a session: changing it changes the cached prompt prefix.
Deferred bool `json:"deferred,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.
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.
Source Files
¶
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. |
|
imageproc
module
|