llm

package
v0.24.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: AGPL-3.0 Imports: 4 Imported by: 0

Documentation

Overview

Package llm provides a internal representations of LLM inference API requests and responses which are then further mutated and handled.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ChatRequest

type ChatRequest struct {
	// Model name (e.g., "gpt-4", "claude-3-sonnet", "llama2")
	Model string `json:"model"`

	// Conversation messages
	Messages []Message `json:"messages"`

	// Whether to stream the response
	Stream *bool `json:"stream,omitempty"`

	// System prompt (some providers handle this separately from messages)
	System string `json:"system,omitempty"`

	// Generation parameters (unified across providers)
	MaxTokens   *int     `json:"max_tokens,omitempty"`
	Temperature *float64 `json:"temperature,omitempty"`
	TopP        *float64 `json:"top_p,omitempty"`
	TopK        *int     `json:"top_k,omitempty"`
	Stop        []string `json:"stop,omitempty"`
	Seed        *int     `json:"seed,omitempty"`

	// Tools are the tool definitions offered to the model, preserved as
	// raw provider JSON. The definitions are large and provider-shaped;
	// callers that only need the count (e.g. shadow-call classification:
	// the security monitor sends zero tools, the main conversation sends
	// the full set) should use len(Tools).
	Tools []json.RawMessage `json:"tools,omitempty"`

	// Provider-specific fields that don't map to common parameters
	Extra map[string]any `json:"extra,omitempty"`

	// RawRequest preserves the original request payload for cases where
	// parsing is incomplete or for debugging.
	RawRequest json.RawMessage `json:"raw_request,omitempty"`
}

ChatRequest represents a provider-agnostic chat completion request. This is the internal representation used by the proxy after parsing provider-specific request formats.

func (*ChatRequest) Params added in v0.16.0

func (r *ChatRequest) Params() *RequestParams

Params extracts the promotable request parameters from the parsed request. ToolCount is always concrete (a request with no tools field offered zero tools); Stream/MaxTokens/Temperature stay nil when the request omitted them.

type ChatResponse

type ChatResponse struct {
	// Model that generated the response
	Model string `json:"model"`

	// Response timestamp
	CreatedAt time.Time `json:"created_at,omitzero"`

	// The assistant's response message
	Message Message `json:"message"`

	// Whether generation is complete (for streaming)
	Done bool `json:"done"`

	// Stop reason (e.g., "stop", "length", "tool_use", "end_turn")
	StopReason string `json:"stop_reason,omitempty"`

	// Token usage and timing metrics
	Usage *Usage `json:"usage,omitempty"`

	// Provider-specific fields that don't map to common parameters
	Extra map[string]any `json:"extra,omitempty"`

	// RawResponse preserves the original response payload for cases where
	// parsing is incomplete or for debugging.
	RawResponse json.RawMessage `json:"raw_response,omitempty"`
}

ChatResponse represents a provider-agnostic chat completion response. This is the internal representation used by the proxy after parsing provider-specific response formats.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"` // "text", "image", "tool_use", "tool_result", "thinking"

	// Text content (type="text")
	Text string `json:"text,omitempty"`

	// Image content (type="image")
	ImageURL    string `json:"image_url,omitempty"`    // URL to image
	ImageBase64 string `json:"image_base64,omitempty"` // Base64-encoded image data
	MediaType   string `json:"media_type,omitempty"`   // MIME type (e.g., "image/png")

	// Tool use (type="tool_use") - assistant requesting tool execution
	ToolUseID string         `json:"tool_use_id,omitempty"`
	ToolName  string         `json:"tool_name,omitempty"`
	ToolInput map[string]any `json:"tool_input,omitempty"`

	// Tool result (type="tool_result") - result from tool execution
	ToolResultID string `json:"tool_result_id,omitempty"` // References the tool_use_id
	ToolOutput   string `json:"tool_output,omitempty"`
	IsError      bool   `json:"is_error,omitempty"`

	// Thinking (type="thinking") - Anthropic extended-thinking blocks.
	// Anthropic emits thinking as content_block_delta frames with type
	// "thinking_delta" followed by a "signature_delta" that authenticates the
	// block. Consumers treat Thinking as opaque text; the signature is persisted
	// so downstream tooling can verify integrity.
	Thinking          string `json:"thinking,omitempty"`
	ThinkingSignature string `json:"thinking_signature,omitempty"`

	// Content (type="web_search_tool_result" and other server-tool results) -
	// the raw result payload Anthropic returns inline on the block, captured
	// verbatim as JSON so the variable result-object shapes survive without
	// imposing a schema. ToolResultID links it to the paired server_tool_use.
	Content json.RawMessage `json:"content,omitempty"`
}

ContentBlock represents a single piece of content within a message. The Type field determines which other fields are populated.

func (ContentBlock) Clone added in v0.19.1

func (b ContentBlock) Clone() ContentBlock

Clone returns a deep copy of the content block in which every string and byte field is reallocated.

Provider request parsing is zero-copy (jsonv2): the parsed strings are sub-slices that alias the raw request buffer. Go frees a backing array only when no sub-slice still references it, so a single retained ContentBlock would otherwise pin the entire multi-MB request buffer alive for the life of the derived node. Cloning breaks every alias, so the raw buffer can be collected once its turn is processed.

Cloning is all-or-nothing: any one field left aliasing keeps the whole buffer pinned, so EVERY string/byte field must be copied here. The copy is byte-for-byte identical to the original — a node hashed from a cloned bucket hashes the same.

type ConversationTurn

type ConversationTurn struct {
	Provider string        `json:"provider"`
	Request  *ChatRequest  `json:"request"`
	Response *ChatResponse `json:"response"`
}

ConversationTurn represents a complete request-response pair for storage in the DAG.

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

ErrorResponse represents an error from the LLM API.

type Message

type Message struct {
	Role    string         `json:"role"`    // "system", "user", "assistant", "tool"
	Content []ContentBlock `json:"content"` // Array of content blocks
}

Message represents a single message in a conversation. Content is stored as an array of ContentBlocks to support multimodal content (text, images, tool use, etc.) in a provider-agnostic way.

func NewTextMessage

func NewTextMessage(role, text string) Message

NewTextMessage creates a simple text message with the given role and content.

func (*Message) GetText

func (m *Message) GetText() string

GetText returns the concatenated text content from all text blocks in the message. This is a convenience method for simple text-only messages.

type RequestParams added in v0.16.0

type RequestParams struct {
	System      string   `json:"system,omitempty"`
	MaxTokens   *int     `json:"max_tokens,omitempty"`
	Temperature *float64 `json:"temperature,omitempty"`
	Stream      *bool    `json:"stream,omitempty"`
	ToolCount   *int     `json:"tool_count,omitempty"`
}

RequestParams is the subset of request-envelope parameters promoted onto each node a captured call newly inserts. They identify the KIND of call that produced the node — main conversation vs harness shadow call (security monitor, title-gen, suggestion, …) — and are stored as queryable columns alongside the node without participating in the content-addressed hash.

Pointer fields distinguish "absent from the request" (nil) from a zero value, mirroring the provider wire format.

func (*RequestParams) Clone added in v0.19.1

func (r *RequestParams) Clone() *RequestParams

Clone returns a copy of the request params that shares no backing storage with the raw request buffer it was parsed from. System is reallocated, and each scalar pointer (MaxTokens, Temperature, Stream, ToolCount) is repointed at a freshly allocated value: a value parsed by jsonv2 may be allocated inside the arena that also backs the raw buffer, so copying the pointer by value would keep the whole multi-MB buffer alive. Returns nil for a nil receiver.

type StreamChunk

type StreamChunk struct {
	// Model that generated the chunk
	Model string `json:"model"`

	// Chunk timestamp
	CreatedAt time.Time `json:"created_at,omitzero"`

	// The content of this chunk (typically a partial message)
	Message Message `json:"message"`

	// Whether this is the final chunk
	Done bool `json:"done"`

	// Index for providers that support multiple parallel completions
	Index int `json:"index,omitempty"`

	// Stop reason (only present on final chunk)
	StopReason string `json:"stop_reason,omitempty"`

	// Usage metrics (typically only present on final chunk)
	Usage *Usage `json:"usage,omitempty"`
}

StreamChunk represents a single chunk in a streaming response. This is the internal representation used by the proxy after parsing provider-specific streaming formats.

type Usage

type Usage struct {
	// Token counts
	PromptTokens     int `json:"prompt_tokens,omitempty"`
	CompletionTokens int `json:"completion_tokens,omitempty"`
	TotalTokens      int `json:"total_tokens,omitempty"`

	// Cache token counts (Anthropic prompt caching)
	CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens     int `json:"cache_read_input_tokens,omitempty"`

	// TotalDurationNs is the proxy-measured wall-clock time, in nanoseconds,
	// from when the proxy received the client request to when the upstream
	// response was fully assembled. Set uniformly by the proxy across providers
	// — Anthropic and OpenAI don't surface a duration field on the wire, and
	// Ollama's server-internal `total_duration` is intentionally overwritten so
	// aggregate stats compare apples to apples.
	TotalDurationNs int64 `json:"total_duration_ns,omitempty"`

	// PromptDurationNs is provider-reported prompt-evaluation time, in
	// nanoseconds. Populated by providers that surface it (currently Ollama
	// only); left at zero otherwise.
	PromptDurationNs int64 `json:"prompt_duration_ns,omitempty"`
}

Usage contains token counts and timing information.

Directories

Path Synopsis
anthropic
Package anthropic
Package anthropic
ollama
Package ollama
Package ollama
openai
Package openai
Package openai

Jump to

Keyboard shortcuts

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