Documentation
¶
Overview ¶
Package types defines the shared data types of the runtime: messages and their content parts, tool calls and results, streaming chunks and costs.
Index ¶
- Constants
- func CountMediaParts(msg Message) int
- func CountPartsByType(msg Message, contentType string) int
- func ExtractTextContent(msg Message) string
- func HasOnlyTextContent(msg Message) bool
- func MigrateMessagesToLegacy(messages []Message) error
- func MigrateMessagesToMultimodal(messages []Message)
- func MigrateToLegacy(msg *Message) error
- func MigrateToMultimodal(msg *Message)
- func NewMessageID() string
- func NormalizeRawMessage(raw json.RawMessage) json.RawMessage
- type Caller
- type ChunkReader
- type ChunkWriter
- type ContentPart
- func MetadataOnlyParts(parts []ContentPart) []ContentPart
- func NewAudioPart(filePath string) (ContentPart, error)
- func NewAudioPartFromData(base64Data, mimeType string) ContentPart
- func NewAudioPartFromStorageRef(ref, mimeType string) ContentPart
- func NewDocumentPart(filePath string) (ContentPart, error)
- func NewDocumentPartFromData(base64Data, mimeType string) ContentPart
- func NewDocumentPartFromStorageRef(ref, mimeType string) ContentPart
- func NewImagePart(filePath string, detail *string) (ContentPart, error)
- func NewImagePartFromData(base64Data, mimeType string, detail *string) ContentPart
- func NewImagePartFromStorageRef(ref, mimeType string, detail *string) ContentPart
- func NewImagePartFromURL(url string, detail *string) ContentPart
- func NewTextPart(text string) ContentPart
- func NewThinkingPart(text string) ContentPartdeprecated
- func NewVideoPart(filePath string) (ContentPart, error)
- func NewVideoPartFromData(base64Data, mimeType string) ContentPart
- func NewVideoPartFromStorageRef(ref, mimeType string) ContentPart
- func SplitMultimodalMessage(msg Message) (text string, mediaParts []ContentPart)
- type CostInfo
- type CostLineItem
- type MediaChunk
- type MediaContent
- type MediaItemSummary
- type MediaSummary
- type Message
- func CloneMessage(msg Message) Message
- func CombineTextAndMedia(role, text string, mediaParts []ContentPart) Message
- func ConvertTextToMultimodal(role, content string) Message
- func EnsureMessageID(msg Message) Message
- func ExcludeInterrupted(msgs []Message) []Message
- func NewAssistantMessage(content string) Message
- func NewMultimodalMessage(role string, parts []ContentPart) Message
- func NewSystemMessage(content string) Message
- func NewTextMessage(role, content string) Message
- func NewToolResultMessage(result MessageToolResult) Message
- func NewUserMessage(content string) Message
- func StripReasoning(msgs []Message) []Message
- func (m *Message) AddAudioPart(filePath string) error
- func (m *Message) AddDocumentPart(filePath string) error
- func (m *Message) AddImagePart(filePath string, detail *string) error
- func (m *Message) AddImagePartFromURL(url string, detail *string)
- func (m *Message) AddPart(part ContentPart)
- func (m *Message) AddTextPart(text string)
- func (m *Message) AddVideoPart(filePath string) error
- func (m *Message) GetContent() string
- func (m *Message) HasMediaContent() bool
- func (m *Message) ID() string
- func (m *Message) IsHeardPrefix() bool
- func (m *Message) IsInterrupted() bool
- func (m *Message) IsMultimodal() bool
- func (m *Message) LeavesModelContext() bool
- func (m Message) MarshalJSON() ([]byte, error)
- func (m *Message) Metadata() map[string]any
- func (m *Message) SetMultimodalContent(parts []ContentPart)
- func (m *Message) SetTextContent(text string)
- func (m *Message) UnmarshalJSON(data []byte) error
- type MessageToolCall
- type MessageToolResult
- type OpaqueReasoning
- type ReasoningTrace
- type StreamingMediaConfig
- type ToolCallRecord
- type ToolDef
- type ToolErrorType
- type ToolStats
- type ValidationError
- type ValidationResult
Examples ¶
Constants ¶
const ( ContentTypeText = "text" ContentTypeImage = "image" ContentTypeAudio = "audio" ContentTypeVideo = "video" ContentTypeDocument = "document" ContentTypeThinking = "thinking" )
ContentType constants for different content part types
const ( MIMETypeImageJPEG = "image/jpeg" MIMETypeImagePNG = "image/png" MIMETypeImageGIF = "image/gif" MIMETypeImageWebP = "image/webp" MIMETypeAudioMP3 = "audio/mpeg" MIMETypeAudioWAV = "audio/wav" MIMETypeAudioOgg = "audio/ogg" MIMETypeAudioWebM = "audio/webm" MIMETypeVideoMP4 = "video/mp4" MIMETypeVideoWebM = "video/webm" MIMETypeVideoOgg = "video/ogg" MIMETypePDF = "application/pdf" MIMETypeDocx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" MIMETypeDoc = "application/msword" MIMETypeMarkdown = "text/markdown" MIMETypePlainText = "text/plain" MIMETypeCSV = "text/csv" MIMETypeJSON = "application/json" MIMETypeXML = "application/xml" )
Common MIME types
const ( FinishReasonStop = "stop" // natural completion FinishReasonMaxOutputTokens = "max_output_tokens" // output budget (incl. reasoning) exhausted FinishReasonToolUse = "tool_use" // stopped to call tools FinishReasonSafety = "safety" // blocked by safety / content filter FinishReasonRefusal = "refusal" // model declined to answer // FinishReasonInterrupted marks a partial reply kept from a stream that // failed or was canceled before the model finished. It is set by the // runtime, never by a provider, and the message is kept in the transcript // but never sent back to the model. Meta[MetaInterruptedCause] says why. FinishReasonInterrupted = "interrupted" // FinishReasonError marks a provider call that failed and left nothing // to keep. It is set by the runtime, never by a provider, and only on // the end of a streamed provider call (providers.ProviderCallEnd): no // message is stored for such a call. FinishReasonError = "error" )
Canonical finish reasons. Each provider normalizes its raw wire value onto one of these before populating Message.FinishReason, so consumers can reliably detect e.g. an output-cap truncation regardless of provider. An unknown provider value passes through verbatim rather than mapping here.
const ( // MetaHeardMs is how much of the reply's audio the caller heard, in // milliseconds (int64). MetaHeardMs = "heard_ms" // MetaAudioMs is the reply's audio duration, in milliseconds (int64). MetaAudioMs = "audio_ms" // MetaPlayedFraction is MetaHeardMs over MetaAudioMs, from 0 to 1 // (float64, three decimals). MetaPlayedFraction = "played_fraction" // MetaPlayoutCut says why the reply's playback was cut: PlayoutCutBargeIn, // PlayoutCutGuardrail or PlayoutCutSessionClosed. MetaPlayoutCut = "playout_cut" // MetaHeardPrefix, set to true, marks a reply whose text was truncated to // what the caller heard of it (a cascaded voice session's speech-out // stage does this; a realtime session, whose audio transcripts carry no // timing, keeps the whole text). See IsHeardPrefix. MetaHeardPrefix = "_heard_prefix" )
Message.Meta keys a realtime voice session sets on a reply the caller did not hear in full, when it tracks playout (the SDK's OpenVoice and WithPlayoutTracking). The reply keeps its own FinishReason: it completed, and only its playback was cut, so it stays in model context with any tool calls it made.
const ( // PlayoutCutBargeIn: the caller barged in while the reply played. PlayoutCutBargeIn = "barge-in" // PlayoutCutSessionClosed: the session ended (closed, drained or canceled) // while the reply played. PlayoutCutSessionClosed = "session-closed" // PlayoutCutGuardrail: a guardrail blocked the reply and cut it. PlayoutCutGuardrail = "guardrail" )
Values of MetaPlayoutCut.
const MetaBlockedInput = "_blocked_input"
MetaBlockedInput is the Message.Meta key, set to true, that marks the canned assistant reply substituted for a user turn an input guardrail or a provider BeforeCall hook blocked. The reply and the blocked user message before it are kept in the transcript but never sent to the model.
const MetaCallerTurn = "caller_turn"
MetaCallerTurn is the Message.Meta key under which a duplex (realtime or voice) pipeline stores, on each reply, the 0-based index of the caller turn it answers (int; a number, once a store has encoded it): the turn index its guardrails and turn evals reported. A session that resumes the conversation goes on from it, so a spoken turn no transcript was stored for still counts.
const MetaExcludedFromModel = "_excluded_from_model"
MetaExcludedFromModel is the Message.Meta key, set to true, that keeps a message out of model context on its own: the transcript keeps it, but no provider request, summary, extracted memory or retrieval index is built from it. Unlike MetaBlockedInput on a canned reply it never takes the message before it out too. A host that rebuilds a history from a client's copy marks with it each message the stored history kept out of model context (the SDK's ReplaceHistory does), so the client's ordering cannot let it back in.
const MetaInjectedContext = "_injected_context"
MetaInjectedContext is the Message.Meta key holding text a host put in front of a user's message as its first text part: context the application supplied with the message (the AG-UI adapter's WithInputContext), not the user's words. A host comparing the message with a client's copy of it compares the text after it.
const MetaInterruptedCause = "_interrupted_cause"
MetaInterruptedCause is the Message.Meta key holding why an interrupted reply stopped: the error text of the stream failure or cancellation.
const MetaMessageID = "_message_id"
MetaMessageID is the Message.Meta key holding the message's stable id: a string the runtime assigns when it first stores the message (see EnsureMessageID), kept with the message in every state store, so the message reads back under the same id however often the history is loaded. A message stored before ids were assigned has none; ID returns "" for it.
const MetaMessageMetadata = "message_metadata"
MetaMessageMetadata is the Message.Meta key holding the metadata an application attached to this message (the SDK's WithMessageMetadata): what the user selected, the view they were on, anything that is not chat text.
It is one key holding the application's map, not keys merged into Meta, so application keys can never collide with the runtime's own. Read it with Message.Metadata. It is stored with the message and carried on its message.created event, and never sent to a provider.
const MetaToolsOffered = "_tools_offered"
MetaToolsOffered is the Message.Meta key carrying the tool names the turn handed the provider for the round that produced this message.
It records what the model COULD call, which no other record captures: ToolCalls say what it chose to do, and a tool the model was offered but never used leaves no trace anywhere else. That is the difference between a skill's allowed-tools grant that works and one that silently does nothing.
The value is []string when freshly stamped and []any after a JSON round-trip through a state store; read it with evals.ExtractToolsOffered, which handles both.
Variables ¶
This section is empty.
Functions ¶
func CountMediaParts ¶
CountMediaParts returns the number of media parts (image, audio, video) in a message
func CountPartsByType ¶
CountPartsByType returns the number of parts of a specific type in a message
func ExtractTextContent ¶
ExtractTextContent extracts all text content from a message, regardless of format. This is useful for backward compatibility when you need only the text.
func HasOnlyTextContent ¶
HasOnlyTextContent returns true if the message contains only text (no media)
func MigrateMessagesToLegacy ¶
MigrateMessagesToLegacy converts a slice of multimodal messages to legacy format in-place. Returns an error if any message contains media content.
func MigrateMessagesToMultimodal ¶
func MigrateMessagesToMultimodal(messages []Message)
MigrateMessagesToMultimodal converts a slice of legacy messages to multimodal format in-place
func MigrateToLegacy ¶
MigrateToLegacy converts a multimodal message back to legacy text-only format. This is for systems that don't support multimodal content. Returns an error if the message contains non-text content.
func MigrateToMultimodal ¶
func MigrateToMultimodal(msg *Message)
MigrateToMultimodal converts a legacy text-only message to use the Parts structure.
func NewMessageID ¶ added in v2.22.0
func NewMessageID() string
NewMessageID returns a new, random stable message id (see MetaMessageID).
func NormalizeRawMessage ¶
func NormalizeRawMessage(raw json.RawMessage) json.RawMessage
NormalizeRawMessage returns a valid JSON value for raw, substituting "{}" when raw is nil, empty, OR not well-formed JSON. Two crash sources in the agent loop motivate this: LLMs routinely emit tool calls with no arguments (empty), and a streamed tool call cut off at max_tokens leaves *truncated* args (e.g. `{"path":"foo`) — non-empty but invalid. Both fail json.RawMessage's encoder with "unexpected end of JSON input". Provider request builders and the message types call this at the boundary so a missing or broken blob degrades to {} instead of crashing a request or losing a whole run's saved output.
Types ¶
type Caller ¶ added in v2.22.0
type Caller struct {
// ID identifies the caller in the host's own terms.
ID string
// Claims carries host-defined attributes of the caller. When exec hooks
// or exec evals are configured, Claims must be JSON-encodable data: a
// value encoding/json cannot encode (a func, a channel, a cycle) makes an
// exec filter hook deny the call with a marshal error, an exec observe
// hook skip it, and an exec eval fail. Receivers must treat Claims as
// read-only: one map is shared by parallel tool calls, forks and hooks.
Claims map[string]any
}
Caller is who a conversation acts for. A host sets it once (sdk.WithCaller) and PromptKit puts it on the requests it builds; it is never carried on context.Context. PromptKit hands it only to the host's own code at its action points: tool executors, tool hooks, provider hooks and chunk interceptors, session hooks, memory retrievers, extractors and stores, eval handlers and the workflow transition authorizer. Exec hooks receive it in the JSON on their stdin (as "Caller" with "ID" and "Claims"), exec eval handlers as "caller" in their context. Otherwise PromptKit never persists, logs or emits it: it is not in events, spans, the state store or recordings. PromptKit never reads ID or Claims itself.
type ChunkReader ¶
type ChunkReader struct {
// contains filtered or unexported fields
}
ChunkReader reads from an io.Reader and produces MediaChunks. Useful for converting continuous streams (e.g., microphone input) into chunks.
Example usage:
reader := NewChunkReader(micInput, config)
for {
chunk, err := reader.NextChunk(ctx)
if err == io.EOF {
break
}
if err != nil {
return err
}
session.SendChunk(ctx, chunk)
}
func NewChunkReader ¶
func NewChunkReader(r io.Reader, config StreamingMediaConfig) *ChunkReader
NewChunkReader creates a new ChunkReader that reads from the given reader and produces MediaChunks according to the config.
func (*ChunkReader) NextChunk ¶
func (cr *ChunkReader) NextChunk(ctx context.Context) (*MediaChunk, error)
NextChunk reads the next chunk from the reader. Returns io.EOF when the stream is complete. IsLast is true only when the underlying reader returns data together with io.EOF. A reader that returns io.EOF with no data ends the stream with a nil chunk and io.EOF, so IsLast is never set on a chunk for such readers.
type ChunkWriter ¶
type ChunkWriter struct {
// contains filtered or unexported fields
}
ChunkWriter writes MediaChunks to an io.Writer. Useful for converting chunks back into continuous streams (e.g., speaker output).
Example usage:
writer := NewChunkWriter(speakerOutput)
for chunk := range session.Response() {
if chunk.MediaData != nil {
_, err := writer.WriteChunk(&MediaChunk{Data: chunk.MediaData.Data})
if err != nil {
return err
}
}
}
func NewChunkWriter ¶
func NewChunkWriter(w io.Writer) *ChunkWriter
NewChunkWriter creates a new ChunkWriter that writes to the given writer.
func (*ChunkWriter) Flush ¶
func (cw *ChunkWriter) Flush() error
Flush flushes any buffered data to the underlying writer (if it supports flushing).
func (*ChunkWriter) WriteChunk ¶
func (cw *ChunkWriter) WriteChunk(chunk *MediaChunk) (int, error)
WriteChunk writes a MediaChunk to the underlying writer. Returns the number of bytes written and any error encountered.
type ContentPart ¶
type ContentPart struct {
Type string `json:"type"` // a ContentType constant: "text", "image", "audio", "video", "document", "thinking"
// For text content
Text *string `json:"text,omitempty"`
// For media content (image, audio, video)
Media *MediaContent `json:"media,omitempty"`
}
ContentPart represents a single piece of content in a multimodal message. A message can contain multiple parts: text, images, audio, video and documents.
func MetadataOnlyParts ¶
func MetadataOnlyParts(parts []ContentPart) []ContentPart
MetadataOnlyParts returns a copy of parts with binary data stripped. Text parts are preserved as-is. Media parts keep metadata (MIMEType, SizeKB, Width, Height, Duration, etc.) and URL references, but Data and FilePath are set to nil. This is useful for event emission where binary payloads are unnecessary overhead.
func NewAudioPart ¶
func NewAudioPart(filePath string) (ContentPart, error)
NewAudioPart creates a ContentPart with audio content from a file path
func NewAudioPartFromData ¶
func NewAudioPartFromData(base64Data, mimeType string) ContentPart
NewAudioPartFromData creates a ContentPart with base64-encoded audio data
func NewAudioPartFromStorageRef ¶
func NewAudioPartFromStorageRef(ref, mimeType string) ContentPart
NewAudioPartFromStorageRef creates an audio ContentPart backed by a storage reference.
func NewDocumentPart ¶
func NewDocumentPart(filePath string) (ContentPart, error)
NewDocumentPart creates a ContentPart with document content from a file path
func NewDocumentPartFromData ¶
func NewDocumentPartFromData(base64Data, mimeType string) ContentPart
NewDocumentPartFromData creates a ContentPart with base64-encoded document data
func NewDocumentPartFromStorageRef ¶
func NewDocumentPartFromStorageRef(ref, mimeType string) ContentPart
NewDocumentPartFromStorageRef creates a document ContentPart backed by a storage reference.
func NewImagePart ¶
func NewImagePart(filePath string, detail *string) (ContentPart, error)
NewImagePart creates a ContentPart with image content from a file path
func NewImagePartFromData ¶
func NewImagePartFromData(base64Data, mimeType string, detail *string) ContentPart
NewImagePartFromData creates a ContentPart with base64-encoded image data
func NewImagePartFromStorageRef ¶
func NewImagePartFromStorageRef(ref, mimeType string, detail *string) ContentPart
NewImagePartFromStorageRef creates an image ContentPart backed by a durable storage reference. The reference is resolved to a URL or bytes at provider-call time (see providers.MediaLoader).
func NewImagePartFromURL ¶
func NewImagePartFromURL(url string, detail *string) ContentPart
NewImagePartFromURL creates a ContentPart with image content from a URL
Example ¶
ExampleNewImagePartFromURL builds a multimodal image part from a URL. Parts are the unit of multimodal content; a Message carries a []ContentPart.
package main
import (
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/types"
)
func main() {
part := types.NewImagePartFromURL("https://example.com/cat.png", nil)
fmt.Println("type:", part.Type)
}
Output: type: image
func NewTextPart ¶
func NewTextPart(text string) ContentPart
NewTextPart creates a ContentPart with text content
func NewThinkingPart
deprecated
func NewThinkingPart(text string) ContentPart
NewThinkingPart creates a ContentPart with thinking/reasoning content. Thinking parts are stored alongside text parts but excluded from GetContent().
Deprecated: reasoning now lives on Message.Reasoning (a ReasoningTrace), off Parts, so it is structurally excluded from content/exports/future context. New code should populate Message.Reasoning, not a thinking ContentPart.
func NewVideoPart ¶
func NewVideoPart(filePath string) (ContentPart, error)
NewVideoPart creates a ContentPart with video content from a file path
func NewVideoPartFromData ¶
func NewVideoPartFromData(base64Data, mimeType string) ContentPart
NewVideoPartFromData creates a ContentPart with base64-encoded video data
func NewVideoPartFromStorageRef ¶
func NewVideoPartFromStorageRef(ref, mimeType string) ContentPart
NewVideoPartFromStorageRef creates a video ContentPart backed by a storage reference.
func SplitMultimodalMessage ¶
func SplitMultimodalMessage(msg Message) (text string, mediaParts []ContentPart)
SplitMultimodalMessage splits a multimodal message into separate text and media parts. Returns the text content and a slice of media content parts.
func (*ContentPart) Validate ¶
func (cp *ContentPart) Validate() error
Validate checks if the ContentPart is valid
type CostInfo ¶
type CostInfo struct {
InputTokens int `json:"input_tokens"` // Uncached input tokens across all modalities
OutputTokens int `json:"output_tokens"` // Visible output tokens across all modalities
CachedTokens int `json:"cached_tokens,omitempty"` // Cache-read tokens
InputCostUSD float64 `json:"input_cost_usd"` // Cost of input tokens in USD
OutputCostUSD float64 `json:"output_cost_usd"` // Cost of output tokens in USD
CachedCostUSD float64 `json:"cached_cost_usd,omitempty"` // Cost of cache-read tokens in USD
TotalCost float64 `json:"total_cost_usd"` // Total cost in USD
// Per-unit fields populated when a provider prices its usage.
Quantities map[string]float64 `json:"quantities,omitempty"` // Raw billable quantities by unit name
DimensionMatch map[string]string `json:"dimension_match,omitempty"` // Dimension key-value pairs (e.g. size, quality)
ProviderName string `json:"provider_name,omitempty"` // Provider that produced this cost entry
Model string `json:"model,omitempty"` // Model that served the call, when known
Capability string `json:"capability,omitempty"` // ProviderType as string for JSON portability
Latency time.Duration `json:"latency_ns,omitempty"` // Time taken by the provider call
// Breakdown is a per-line-item view of the cost. A priced provider call
// fills it with one item per billed unit. On the aggregated rollup it merges
// the items of every contributing message by (provider, capability, unit,
// dimensions), so a report can show per-unit detail.
Breakdown []CostLineItem `json:"breakdown,omitempty"`
}
CostInfo tracks token usage and associated costs for LLM operations. All cost values are in USD. Used for both individual messages and aggregated tracking.
Example ¶
ExampleCostInfo shows reading the cost of an LLM turn. The flat headline fields are the quick view; Quantities/Breakdown carry the per-unit detail populated on the unit-keyed cost path.
package main
import (
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/types"
)
func main() {
ci := types.CostInfo{
InputTokens: 1000,
OutputTokens: 500,
InputCostUSD: 0.003,
OutputCostUSD: 0.015,
TotalCost: 0.018,
Quantities: map[string]float64{"input_token": 1000, "output_token": 500},
}
fmt.Printf("$%.3f total (%d in / %d out)\n", ci.TotalCost, ci.InputTokens, ci.OutputTokens)
}
Output: $0.018 total (1000 in / 500 out)
type CostLineItem ¶
type CostLineItem struct {
Provider string `json:"provider,omitempty"`
Capability string `json:"capability,omitempty"`
Unit string `json:"unit"`
Quantity float64 `json:"quantity"`
USD float64 `json:"usd"`
Dimensions map[string]string `json:"dimensions,omitempty"`
}
CostLineItem is one row of a cost breakdown, suitable for surfacing in reports. Carries provider + capability tags so consumers can group across the conversation without re-deriving them.
type MediaChunk ¶
type MediaChunk struct {
// Data contains the raw media bytes for this chunk
Data []byte `json:"data"`
// SequenceNum is the sequence number for ordering chunks (starts at 0)
SequenceNum int64 `json:"sequence_num"`
// Timestamp indicates when this chunk was created
Timestamp time.Time `json:"timestamp"`
// IsLast indicates if this is the final chunk in the stream
IsLast bool `json:"is_last"`
// Metadata contains chunk-specific metadata (MIME type, encoding, etc.)
Metadata map[string]string `json:"metadata,omitempty"`
}
MediaChunk represents a chunk of streaming media data. Used for bidirectional streaming where media is sent or received in chunks.
Example usage:
chunk := &MediaChunk{
Data: audioData,
SequenceNum: 1,
Timestamp: time.Now(),
IsLast: false,
Metadata: map[string]string{"mime_type": "audio/pcm"},
}
type MediaContent ¶
type MediaContent struct {
// Data source: set at least one; Validate rejects URL combined with Data or FilePath
Data *string `json:"data,omitempty"` // Base64-encoded media data
FilePath *string `json:"file_path,omitempty"` // Local file path
URL *string `json:"url,omitempty"` // External URL (http/https)
// Storage backend reference (used when media is externalized)
StorageReference *string `json:"storage_reference,omitempty"` // Backend-specific storage reference
// Media metadata
MIMEType string `json:"mime_type"` // e.g., "image/jpeg", "audio/mp3", "video/mp4"
Format *string `json:"format,omitempty"` // Optional format hint (e.g., "png", "mp3", "mp4")
SizeKB *int64 `json:"size_kb,omitempty"` // Optional size in kilobytes
Detail *string `json:"detail,omitempty"` // Optional detail level for images: "low", "high", "auto"
Caption *string `json:"caption,omitempty"` // Optional caption/description
Duration *int `json:"duration,omitempty"` // Optional duration in seconds (for audio/video)
BitRate *int `json:"bit_rate,omitempty"` // Optional bit rate in kbps (for audio/video)
Channels *int `json:"channels,omitempty"` // Optional number of channels (for audio)
Width *int `json:"width,omitempty"` // Optional width in pixels (for image/video)
Height *int `json:"height,omitempty"` // Optional height in pixels (for image/video)
FPS *int `json:"fps,omitempty"` // Optional frames per second (for video)
PolicyName *string `json:"policy_name,omitempty"` // Retention policy name
}
MediaContent represents media data (image, audio, video, document) in a message. The payload is inline base64 data, a local file path, an external URL or a storage reference. Validate lists the permitted combinations.
func (*MediaContent) GetBase64Data
deprecated
func (mc *MediaContent) GetBase64Data() (string, error)
GetBase64Data returns the base64-encoded data for this media content. If the data is already base64-encoded, it returns it directly. If the data is from a file, it reads and encodes the file. If the data is from a URL or StorageReference, it returns an error (caller should use MediaLoader).
Deprecated: For new code, use providers.MediaLoader.GetBase64Data which supports all sources including storage references and URLs with proper context handling.
func (*MediaContent) ReadData ¶
func (mc *MediaContent) ReadData() (io.ReadCloser, error)
ReadData returns an io.Reader for the media content. For base64 data, it decodes and returns a reader. For file paths, it opens and returns the file. For URLs, it returns an error (caller should fetch separately).
func (*MediaContent) Validate ¶
func (mc *MediaContent) Validate() error
Validate checks if the MediaContent is valid.
At least one of Data, FilePath, URL or StorageReference must be set, and MIMEType must be non-empty. Data + FilePath is permitted: Data is the canonical bytes and FilePath is an origin hint. URL is mutually exclusive with both Data and FilePath: a URL refers to an external resource that is not carried inline.
type MediaItemSummary ¶
type MediaItemSummary struct {
Type string `json:"type"` // Content type: "image", "audio", "video", "document"
Source string `json:"source"` // Source description (file path, URL, or "inline data")
MIMEType string `json:"mime_type"` // MIME type
SizeBytes int `json:"size_bytes"` // Size in bytes (0 if unknown)
Detail string `json:"detail,omitempty"` // Detail level for images
Loaded bool `json:"loaded"` // Whether media was successfully loaded
Error string `json:"error,omitempty"` // Error message if loading failed
}
MediaItemSummary provides details about a single media item in a message.
type MediaSummary ¶
type MediaSummary struct {
TotalParts int `json:"total_parts"` // Total number of content parts
TextParts int `json:"text_parts"` // Number of text parts
ImageParts int `json:"image_parts"` // Number of image parts
AudioParts int `json:"audio_parts"` // Number of audio parts
VideoParts int `json:"video_parts"` // Number of video parts
DocumentParts int `json:"document_parts"` // Number of document parts
MediaItems []MediaItemSummary `json:"media_items,omitempty"` // Details of each media item
}
MediaSummary provides a high-level overview of media content in a message. This is included in JSON output to make multimodal messages more observable.
type Message ¶
type Message struct {
Role string `json:"role"` // "system", "user", "assistant", "tool"
Content string `json:"content"` // Message content (legacy text-only, maintained for backward compatibility)
// Multimodal content parts (text, images, audio, video)
// If Parts is non-empty, it takes precedence over Content.
// For backward compatibility, if Parts is empty, Content will be used.
Parts []ContentPart `json:"parts,omitempty"`
// Tool invocations (for assistant messages that call tools)
ToolCalls []MessageToolCall `json:"tool_calls,omitempty"`
// Tool result (for tool role messages)
// When Role="tool", this contains the tool execution result
ToolResult *MessageToolResult `json:"tool_result,omitempty"`
// Source indicates where this message originated (runtime-only, not persisted in JSON)
// Values: "statestore" (loaded from StateStore), "pipeline" (created during execution), "" (user input),
// "recorded_input" (user input the input RecordingStage has already recorded)
Source string `json:"-"`
// Metadata for observability and tracking
Timestamp time.Time `json:"timestamp,omitempty"` // When the message was created
LatencyMs int64 `json:"latency_ms,omitempty"` // Time taken to generate (for assistant messages)
CostInfo *CostInfo `json:"cost_info,omitempty"` // Token usage and cost tracking
// Provider-reported reason the assistant stopped, normalized onto the
// canonical vocabulary (see FinishReason* constants). Empty if unreported.
FinishReason string `json:"finish_reason,omitempty"`
Meta map[string]interface{} `json:"meta,omitempty"` // Custom metadata
// Reasoning holds the turn's model reasoning, off Parts so it is not content
// and is excluded from future-turn context by default. See ReasoningTrace.
Reasoning *ReasoningTrace `json:"reasoning,omitempty"`
// Validation results (for assistant messages)
Validations []ValidationResult `json:"validations,omitempty"`
}
Message represents a single message in a conversation. This is the canonical message type used throughout the system.
func CloneMessage ¶
CloneMessage returns a copy of a message. Parts (including their media content), ToolCalls, ToolResult, CostInfo, Meta and Validations are copied into new slices, maps and structs. Values nested inside them are shared with the original: tool-call Args, ToolResult.Parts, CostInfo.Quantities, CostInfo.DimensionMatch and Breakdown, Reasoning, the values in Meta, and ValidationResult.Details.
func CombineTextAndMedia ¶
func CombineTextAndMedia(role, text string, mediaParts []ContentPart) Message
CombineTextAndMedia creates a multimodal message from separate text and media parts. This is the inverse of SplitMultimodalMessage.
func ConvertTextToMultimodal ¶
ConvertTextToMultimodal is a convenience function that creates a multimodal message from a role and text content. This helps with code migration.
func EnsureMessageID ¶ added in v2.22.0
EnsureMessageID returns msg carrying a stable id: msg itself when it has one (ID), otherwise a copy with a new, random id under MetaMessageID. The copy gets its own Meta map, so the id never reaches another holder of msg's Meta.
func ExcludeInterrupted ¶ added in v2.9.0
ExcludeInterrupted returns msgs without interrupted replies, for any path that sends history back to a model. A half-finished reply would mislead the model, and one cut off mid tool call leaves a call with no result, which providers reject. The transcript keeps them; only model context drops them. msgs is returned as-is when it holds none.
What a caller heard of a spoken reply they cut off (IsHeardPrefix) is kept: it was said, so the model goes on from it, as a realtime model goes on from the reply its provider truncated to what was heard.
func NewAssistantMessage ¶
NewAssistantMessage creates an assistant message with text content.
func NewMultimodalMessage ¶
func NewMultimodalMessage(role string, parts []ContentPart) Message
NewMultimodalMessage creates a message with multimodal content parts. When using Parts, the Content field is intentionally left empty as GetContent() will extract text from Parts.
Example ¶
ExampleNewMultimodalMessage builds a message combining text and image parts. GetContent() extracts the text part(s) from Parts.
package main
import (
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/types"
)
func main() {
parts := []types.ContentPart{
types.NewTextPart("What is in this image?"),
types.NewImagePartFromURL("https://example.com/cat.png", nil),
}
msg := types.NewMultimodalMessage("user", parts)
fmt.Println(msg.GetContent())
fmt.Println("parts:", len(msg.Parts))
}
Output: What is in this image? parts: 2
func NewSystemMessage ¶
NewSystemMessage creates a system message with text content.
func NewTextMessage ¶
NewTextMessage creates a simple text message. Use this for user, assistant, or system messages with text-only content.
Example ¶
ExampleNewTextMessage builds a simple text turn.
package main
import (
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/types"
)
func main() {
msg := types.NewTextMessage("user", "Hello!")
fmt.Println(msg.Role, "->", msg.GetContent())
}
Output: user -> Hello!
func NewToolResultMessage ¶
func NewToolResultMessage(result MessageToolResult) Message
NewToolResultMessage creates a properly normalized tool result message. This ensures Content and ToolResult.Parts are always synchronized, which is required for provider compatibility and consistent behavior.
IMPORTANT: Always use this constructor instead of directly creating Message{Role: "tool", ToolResult: ...} to avoid Content/ToolResult.Parts synchronization issues.
func NewUserMessage ¶
NewUserMessage creates a user message with text content.
func StripReasoning ¶
StripReasoning returns copies of msgs with Reasoning cleared, for persistence or export paths that must not retain model reasoning (the default behavior; see Message.Reasoning). The input slice and its messages are not mutated.
func (*Message) AddAudioPart ¶
AddAudioPart adds an audio content part from a file path
func (*Message) AddDocumentPart ¶
AddDocumentPart adds a document content part from a file path
func (*Message) AddImagePart ¶
AddImagePart adds an image content part from a file path
func (*Message) AddImagePartFromURL ¶
AddImagePartFromURL adds an image content part from a URL
func (*Message) AddPart ¶
func (m *Message) AddPart(part ContentPart)
AddPart adds a content part to the message. If this is the first part added, it clears the legacy Content field.
func (*Message) AddTextPart ¶
AddTextPart adds a text content part to the message
func (*Message) AddVideoPart ¶
AddVideoPart adds a video content part from a file path
func (*Message) GetContent ¶
GetContent returns the content of the message. This is the recommended way to access message content as it handles all cases: 1. For tool messages (Role="tool") with a ToolResult: returns ToolResult.GetTextContent() 2. For multimodal messages: returns concatenated text parts 3. For legacy messages: returns the Content field
func (*Message) HasMediaContent ¶
HasMediaContent returns true if the message contains any media (image, audio, video, document)
func (*Message) ID ¶ added in v2.22.0
ID returns the message's stable id (MetaMessageID), or "" when it has none.
func (*Message) IsHeardPrefix ¶ added in v2.22.0
IsHeardPrefix reports whether m is what a caller heard of a spoken reply they cut off: an interrupted reply whose text was truncated to what had played (Meta MetaHeardPrefix), with no tool calls. A reply whose playback was cut but whose text was not (a realtime reply: playout_cut alone) is not: much of its text was never heard.
func (*Message) IsInterrupted ¶ added in v2.9.0
IsInterrupted reports whether m is a partial reply kept from a stream that failed before the model finished (see FinishReasonInterrupted).
func (*Message) IsMultimodal ¶
IsMultimodal returns true if the message contains multimodal content (Parts)
func (*Message) LeavesModelContext ¶ added in v2.22.0
LeavesModelContext reports whether m is left out of history sent back to a model (ExcludeInterrupted): an interrupted reply that is not what a caller heard of it.
func (Message) MarshalJSON ¶
MarshalJSON implements custom JSON marshaling for Message. This enhances the output by: 1. Populating the Content field with a human-readable summary when Parts exist 2. Adding a MediaSummary field for observability of multimodal content 3. Omitting Content field when ToolResult is present to avoid duplication
func (*Message) Metadata ¶ added in v2.14.0
Metadata returns a copy of the metadata an application attached to the message (see MetaMessageMetadata), or nil when there is none. The copy is deep, so changing it never changes the message, or any other holder of the message's Meta.
func (*Message) SetMultimodalContent ¶
func (m *Message) SetMultimodalContent(parts []ContentPart)
SetMultimodalContent sets the message content to multimodal parts. This clears the legacy Content field.
func (*Message) SetTextContent ¶
SetTextContent sets the message content to simple text. This clears any existing Parts and sets the legacy Content field.
func (*Message) UnmarshalJSON ¶
UnmarshalJSON implements custom JSON unmarshaling for Message. After unmarshaling, if ToolResult is present, copy its Content to Message.Content for provider compatibility (providers expect Content field to be populated).
type MessageToolCall ¶
type MessageToolCall struct {
ID string `json:"id"` // Unique identifier for this tool call
Name string `json:"name"` // Name of the tool to invoke
Args json.RawMessage `json:"args"` // JSON-encoded tool arguments
// ProviderMetadata carries opaque provider-specific fields that must be
// round-tripped back to the provider on subsequent turns. Keys are
// namespaced by provider (e.g. "gemini.thought_signature"). This is
// required for providers like Gemini 3 that emit signed tool-call
// parts which must be replayed verbatim to pass server-side validation.
ProviderMetadata map[string]string `json:"provider_metadata,omitempty"`
}
MessageToolCall represents a request to call a tool within a Message. The Args field contains the JSON-encoded arguments for the tool.
func (MessageToolCall) MarshalJSON ¶
func (mtc MessageToolCall) MarshalJSON() ([]byte, error)
MarshalJSON ensures Args is always valid JSON (empty -> {}). A tool call with no arguments must never crash request building or result persistence.
type MessageToolResult ¶
type MessageToolResult struct {
ID string `json:"id"` // References the MessageToolCall.ID that triggered this result
Name string `json:"name"` // Tool name that was executed
Error string `json:"error,omitempty"` // Error message if tool execution failed
ErrorType ToolErrorType `json:"error_type,omitempty"` // Classification of failure reason
// Parts contains the multimodal result content (text, images, etc.).
Parts []ContentPart `json:"parts,omitempty" yaml:"parts,omitempty"`
LatencyMs int64 `json:"latency_ms"` // Tool execution latency in milliseconds
}
MessageToolResult represents the result of a tool execution in a Message. When embedded in Message, the Message.Role should be "tool".
func NewTextToolResult ¶
func NewTextToolResult(id, name, text string) MessageToolResult
NewTextToolResult creates a MessageToolResult with text-only content. This is the most common case and should be used everywhere that would otherwise set a text string Content.
func (*MessageToolResult) GetTextContent ¶
func (r *MessageToolResult) GetTextContent() string
GetTextContent returns concatenated text from all text parts. This is the recommended way to access tool result content as text.
func (*MessageToolResult) HasMedia ¶
func (r *MessageToolResult) HasMedia() bool
HasMedia returns true if any non-text parts exist in the tool result.
type OpaqueReasoning ¶
type OpaqueReasoning struct {
Provider string `json:"provider"` // claude | openai | gemini
Kind string `json:"kind"` // see Kind values above
Data string `json:"data"` // opaque payload
Ref string `json:"ref,omitempty"` // optional association (e.g. tool-call id)
}
OpaqueReasoning is a provider-native reasoning token (signature / encrypted block) preserved for intra-turn round-trip. Never displayed, never content. Kind values: thinking_signature, redacted_thinking, thought_signature, encrypted_reasoning (provider-specific).
type ReasoningTrace ¶
type ReasoningTrace struct {
Text string `json:"text,omitempty"`
Opaque []OpaqueReasoning `json:"opaque,omitempty"`
Redacted bool `json:"redacted,omitempty"`
}
ReasoningTrace holds a model's reasoning/"thinking" for one assistant turn. It is a sibling of content (NOT a ContentPart), so GetContent()/Parts-based consumers (external conversation stores, exports, the events bus) exclude it by default. Text is human-readable (display/record only); Opaque holds provider round-trip tokens that may be fed back where a provider requires, never shown.
type StreamingMediaConfig ¶
type StreamingMediaConfig struct {
// Type specifies the media type being streamed
// Values: ContentTypeAudio, ContentTypeVideo, ContentTypeImage
Type string `json:"type"`
// ChunkSize is the target size in bytes for each chunk
// Typical values: 4096-8192 for audio, 32768-65536 for video
ChunkSize int `json:"chunk_size"`
// SampleRate is the audio sample rate in Hz
// Common values: 8000 (phone quality), 16000 (wideband), 44100 (CD quality), 48000 (pro audio)
SampleRate int `json:"sample_rate,omitempty"`
// Encoding specifies the audio encoding format
// Values: "pcm" (raw), "opus", "mp3", "aac"
Encoding string `json:"encoding,omitempty"`
// Channels is the number of audio channels
// Values: 1 (mono), 2 (stereo)
Channels int `json:"channels,omitempty"`
// BitDepth is the audio bit depth in bits
// Common values: 16, 24, 32
BitDepth int `json:"bit_depth,omitempty"`
// Width is the video width in pixels
Width int `json:"width,omitempty"`
// Height is the video height in pixels
Height int `json:"height,omitempty"`
// FrameRate is the video frame rate (FPS)
// Common values: 24, 30, 60
FrameRate int `json:"frame_rate,omitempty"`
// BufferSize is the maximum number of chunks to buffer
// Larger values increase latency but provide more stability
// Typical values: 5-20
BufferSize int `json:"buffer_size,omitempty"`
// FlushInterval is how often to flush buffered data (if applicable)
FlushInterval time.Duration `json:"flush_interval,omitempty"`
// Metadata contains additional provider-specific configuration
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
StreamingMediaConfig configures streaming media input parameters. It configures audio, video and image streaming sessions with providers.
Example usage for audio streaming:
config := &StreamingMediaConfig{
Type: ContentTypeAudio,
ChunkSize: 8192, // 8KB chunks
SampleRate: 16000, // 16kHz audio
Encoding: "pcm", // Raw PCM audio
Channels: 1, // Mono
BufferSize: 10, // Buffer 10 chunks
}
func (*StreamingMediaConfig) Validate ¶
func (c *StreamingMediaConfig) Validate() error
Validate checks that Type is audio, video or image. Audio and video require a positive ChunkSize. Audio also requires a positive SampleRate and Channels and a non-empty Encoding. Video requires a positive Width, Height and FrameRate.
type ToolCallRecord ¶
type ToolCallRecord struct {
TurnIndex int `json:"turn_index"`
ToolName string `json:"tool_name"`
Arguments map[string]any `json:"arguments"`
Result any `json:"result,omitempty"`
Error string `json:"error,omitempty"`
ErrorType ToolErrorType `json:"error_type,omitempty"`
Duration time.Duration `json:"duration,omitempty"`
}
ToolCallRecord captures a single tool invocation for eval/assertion context. Shared between runtime/evals and PromptArena's assertions.
type ToolDef ¶
type ToolDef struct {
Name string `json:"name"` // Unique tool name
Description string `json:"description"` // Human-readable description of what the tool does
InputSchema json.RawMessage `json:"input_schema"` // JSON Schema for input validation
OutputSchema json.RawMessage `json:"output_schema,omitempty"` // Optional JSON Schema for output validation
}
ToolDef represents a tool definition that can be provided to an LLM. The InputSchema and OutputSchema use JSON Schema format for validation.
func (ToolDef) MarshalJSON ¶
MarshalJSON ensures InputSchema is always valid JSON (empty -> {}). A tool with no input schema must never crash a provider request.
type ToolErrorType ¶
type ToolErrorType string
ToolErrorType classifies why a tool call failed.
const ( // ToolErrorNone indicates a successful tool call (zero value). ToolErrorNone ToolErrorType = "" // ToolErrorValidation indicates the LLM sent invalid arguments (schema mismatch, null args). ToolErrorValidation ToolErrorType = "validation" // ToolErrorExecution indicates the tool ran but returned an error. ToolErrorExecution ToolErrorType = "execution" // ToolErrorApproval indicates a user or policy rejected the tool call. ToolErrorApproval ToolErrorType = "approval" )
type ToolStats ¶
type ToolStats struct {
TotalCalls int `json:"total_calls"` // Total number of tool calls
ByTool map[string]int `json:"by_tool"` // Count of calls per tool name
}
ToolStats tracks tool usage statistics across a conversation or run. Useful for monitoring which tools are being used and how frequently.
type ValidationError ¶
type ValidationError struct {
Type string `json:"type"` // Error type: "args_invalid" | "result_invalid" | "policy_violation"
Tool string `json:"tool"` // Name of the tool that failed validation
Detail string `json:"detail"` // Human-readable error details
}
ValidationError represents a validation failure in tool usage or message content. It provides structured error information when validation fails.
type ValidationResult ¶
type ValidationResult struct {
ValidatorType string `json:"validator_type"` // Type of validator
Passed bool `json:"passed"` // Whether the validation passed
Details map[string]interface{} `json:"details,omitempty"` // Validator-specific details
Timestamp time.Time `json:"timestamp,omitempty"` // When validation was performed
}
ValidationResult represents the outcome of a validator check on a message. These are attached to assistant messages to show which validations passed or failed.