types

package
v0.194.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0, MIT Imports: 4 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

Package types defines the core data structures for yaah's provider communication layer: chat messages, tool definitions, and provider request/response shapes. These follow the OpenAI Chat Completions format, which is the de-facto standard across providers.

Index

Constants

View Source
const (
	// SupervisionKeyFileExisted is the declaration-payload key the write
	// tool sets to report whether its target file existed before the
	// call (bool).
	SupervisionKeyFileExisted = "file_existed"
)

Supervision constants shared by the tool layer (which observes facts) and the supervision layer (which classifies them). Keeping both sides on one symbol means a rename compiles instead of silently reverting the classification to warn-on-every-write.

Variables

This section is empty.

Functions

func DecodeContentValue added in v0.138.0

func DecodeContentValue(raw json.RawMessage) (text, thinking string, err error)

DecodeContentValue normalizes a wire content value into its visible text and its reasoning text. The value is either a plain JSON string (the OpenAI shape) or an array of typed blocks (zai/GLM). The streaming and non-streaming paths share this decoder because the same endpoint sends the same block array on both.

A top-level shape that is neither is an error, and the caller turns it into one warning per turn: silently dropping the chunk is how lost reasoning stays invisible.

func MergeReasoning added in v0.138.0

func MergeReasoning(field, blocks string) string

MergeReasoning joins the two places a reasoning-capable endpoint may put reasoning in one response: the reasoning_content field and thinking blocks carried in content. Endpoints that send both echo the same text twice, so equal halves collapse to one copy; unequal halves both survive, since the two places can hold complementary segments.

func ToolSchemaRef added in v0.87.4

func ToolSchemaRef(tool string) string

ToolSchemaRef is the declaration SchemaRef for a tool name, the shape the trace middleware publishes and the supervision rules match on.

Types

type CacheControl added in v0.6.1

type CacheControl struct {
	Type string `json:"type"`
}

CacheControl marks a message for Anthropic prompt caching.

type ChatRequest

type ChatRequest struct {
	Model      string    `json:"model"`
	Messages   []Message `json:"messages"`
	Tools      []ToolDef `json:"tools,omitempty"`
	ToolChoice any       `json:"tool_choice,omitempty"`
	// Temperature and TopP are optional sampling controls; nil omits the
	// field so the provider's default applies. Pointers keep an explicit
	// 0 (deterministic sampling) distinct from unset.
	Temperature     *float64        `json:"temperature,omitempty"`
	TopP            *float64        `json:"top_p,omitempty"`
	MaxTokens       int             `json:"max_tokens,omitempty"`
	Stream          bool            `json:"stream"`
	StreamOptions   *StreamOptions  `json:"stream_options,omitempty"`
	ResponseFormat  *ResponseFormat `json:"response_format,omitempty"`
	ReasoningEffort string          `json:"reasoning_effort,omitempty"`

	// SuppressReasoning omits the reasoning field from the wire entirely
	// instead of sending it empty. Set by the retry path after a provider
	// rejected the field: an empty value is still a present field, which is
	// exactly what drew the rejection.
	SuppressReasoning bool `json:"-"`
}

ChatRequest is the request body sent to /chat/completions.

type ChatResponse

type ChatResponse struct {
	ID      string   `json:"id"`
	Model   string   `json:"model"`
	Choices []Choice `json:"choices"`
	Usage   Usage    `json:"usage,omitempty"`
}

ChatResponse is the response from /chat/completions.

type Choice

type Choice struct {
	Index        int     `json:"index"`
	Message      Message `json:"message"`
	FinishReason string  `json:"finish_reason"`
}

Choice is a single completion choice.

type CompletionTokensDetails added in v0.16.0

type CompletionTokensDetails struct {
	ReasoningTokens          int `json:"reasoning_tokens"`
	AudioTokens              int `json:"audio_tokens,omitempty"`
	AcceptedPredictionTokens int `json:"accepted_prediction_tokens,omitempty"`
	RejectedPredictionTokens int `json:"rejected_prediction_tokens,omitempty"`
}

CompletionTokensDetails breaks down where completion tokens were spent.

type Message

type Message struct {
	Role             string `json:"role"`
	Content          string `json:"content"`
	Refusal          string `json:"refusal,omitempty"`
	ReasoningContent string `json:"reasoning_content,omitempty"`
	// ReasoningSignature is the opaque signature an Anthropic-compatible
	// provider returns with a thinking block. It must be replayed verbatim
	// alongside ReasoningContent or the request is rejected with
	// "the thinking mode must be passed back to the API".
	ReasoningSignature string        `json:"reasoning_signature,omitempty"`
	ToolCalls          []ToolCall    `json:"tool_calls,omitempty"`
	ToolCallID         string        `json:"tool_call_id,omitempty"`
	Name               string        `json:"name,omitempty"`
	CacheControl       *CacheControl `json:"cache_control,omitempty"`
}

Message represents a single chat message in the agent's internal conversation history. It is NOT the wire format sent to providers — see providers/wire.go for the lowering step that handles provider-specific serialization (content nullability, reasoning_content presence, etc.).

func AssistantMsg

func AssistantMsg(content string, toolCalls []ToolCall) Message

AssistantMsg creates an assistant message with optional tool calls.

func SystemMsg

func SystemMsg(content string) Message

SystemMsg creates a system message.

func ToolResultMsg

func ToolResultMsg(callID, name, content string) Message

ToolResultMsg creates a tool result message to append to the conversation.

func UserMsg

func UserMsg(content string) Message

UserMsg creates a user message.

type PromptTokensDetails added in v0.16.0

type PromptTokensDetails struct {
	CachedTokens int `json:"cached_tokens"`
	AudioTokens  int `json:"audio_tokens,omitempty"`
}

PromptTokensDetails breaks down prompt token usage.

type ResponseFormat added in v0.26.0

type ResponseFormat struct {
	Type string `json:"type"`
}

ResponseFormat controls structured output mode.

type StreamChoice added in v0.138.0

type StreamChoice struct {
	Index        int         `json:"index"`
	Delta        StreamDelta `json:"delta"`
	FinishReason *string     `json:"finish_reason"`
}

StreamChoice represents a choice within a stream chunk.

type StreamChunk added in v0.138.0

type StreamChunk struct {
	ID      string         `json:"id"`
	Model   string         `json:"model"`
	Choices []StreamChoice `json:"choices"`
	Usage   *Usage         `json:"usage,omitempty"`
}

StreamChunk represents a single SSE chunk from a streaming response.

type StreamDelta added in v0.138.0

type StreamDelta struct {
	Role               string     `json:"role,omitempty"`
	Content            string     `json:"content,omitempty"`
	ReasoningContent   string     `json:"reasoning_content,omitempty"`
	ReasoningSignature string     `json:"reasoning_signature,omitempty"`
	ToolCalls          []ToolCall `json:"tool_calls,omitempty"`
	// contains filtered or unexported fields
}

StreamDelta contains the incremental content for a stream chunk.

func (StreamDelta) ContentShapeErr added in v0.138.0

func (d StreamDelta) ContentShapeErr() error

ContentShapeErr reports the content shape this delta could not decode, or nil when the delta decoded cleanly. The producer warns once per stream from it; the delta itself already degraded to empty content.

func (*StreamDelta) UnmarshalJSON added in v0.138.0

func (d *StreamDelta) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a delta that may carry content in either wire shape: the OpenAI plain string, or an array of typed blocks as zai/GLM streams it. Thinking blocks land in ReasoningContent and text blocks in Content; tool_calls and the signature fields pass through unchanged. A content shape that is neither degrades the delta to empty content — its tool calls survive, matching the response path — and the shape is recorded for SendStream's once-per-stream warning instead of dropped silently.

reasoning_content goes through the same normalizer: some endpoints send typed blocks there too, and a shape this decoder cannot read must cost the delta only its reasoning, never its visible content or tool calls.

type StreamOptions added in v0.16.0

type StreamOptions struct {
	IncludeUsage bool `json:"include_usage"`
}

StreamOptions configures streaming behaviour (e.g. include_usage).

type ToolCall

type ToolCall struct {
	ID       string     `json:"id"`
	Index    int        `json:"index,omitempty"`
	Type     string     `json:"type"`
	Function ToolCallFn `json:"function"`
}

ToolCall represents a single tool call requested by the model.

type ToolCallFn

type ToolCallFn struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ToolCallFn is the function within a tool call.

type ToolDef

type ToolDef struct {
	Type     string `json:"type"`
	Function ToolFn `json:"function"`
}

ToolDef wraps a tool function definition.

type ToolFn

type ToolFn struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Parameters  json.RawMessage `json:"parameters"`
}

ToolFn defines the JSON Schema for a tool's parameters.

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
	// CachedPromptTokens is the running sum of prompt tokens served
	// from a provider context cache (deepseek's automatic prefix cache,
	// OpenAI-style prompt_tokens_details.cached_tokens). It is folded in
	// from PromptTokensDetails at accumulation time, not on the wire.
	CachedPromptTokens      int                      `json:"cached_prompt_tokens,omitempty"`
	CompletionTokensDetails *CompletionTokensDetails `json:"completion_tokens_details,omitempty"`
	PromptTokensDetails     *PromptTokensDetails     `json:"prompt_tokens_details,omitempty"`
	// PromptIncludesCache records whether PromptTokens already contains the
	// tokens in CachedPromptTokens. OpenAI-compatible providers report the
	// inclusive total; Anthropic-shaped providers report uncached input and
	// cache reads separately. It is an internal shape marker, never sent on
	// the wire, and is set at the provider boundary.
	PromptIncludesCache bool `json:"-"`
}

Usage holds token usage statistics from the provider.

func (Usage) CacheTokens added in v0.78.0

func (u Usage) CacheTokens() int

CacheTokens reports the prompt tokens served from a provider context cache, whichever shape the usage carries: raw provider usage nests them in PromptTokensDetails (deepseek's prompt_tokens_details .cached_tokens; Anthropic's cache reads mapped at parse time); aggregates accumulate them into the top-level CachedPromptTokens. The Done event carries both (the top-level field from the aggregate copy, the details re-derived for display consumers), so this helper PREFERS the top-level field — correct for every shape — and accumulators MUST use it rather than reading either field alone: reading both would double-count.

func (Usage) GenAIInputTokens added in v0.79.2

func (u Usage) GenAIInputTokens() int

GenAIInputTokens returns the cache-INCLUSIVE prompt token total that the GenAI semantic conventions (gen_ai.usage.input_tokens) require. See InclusivePromptTokens for the shape rules. Cache-creation tokens are not captured by types.Usage today (the Anthropic parse drops cache_creation_input_tokens); if a creation field is ever added, fold it into the Anthropic-shape sum here while CacheTokens keeps reporting only the cache READ portion.

func (Usage) InclusivePromptTokens added in v0.86.2

func (u Usage) InclusivePromptTokens() int

InclusivePromptTokens returns the cache-INCLUSIVE prompt total for display and GenAI semantic conventions. The shape comes from PromptIncludesCache, set by the provider client, rather than from PromptTokensDetails: aggregates intentionally leave details nil, so a details-based heuristic cannot distinguish an OpenAI aggregate (prompt already inclusive) from an Anthropic aggregate (prompt uncached).

Jump to

Keyboard shortcuts

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