message

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: MIT Imports: 5 Imported by: 2

Documentation

Overview

Package message provides types and utilities for handling AI model messages and content.

This package defines the core message structures used across all AI providers, including support for text, images, tool calls, and multimodal content. It provides a unified interface for creating and manipulating messages regardless of the underlying AI provider.

Key types include Message for representing conversations, various ContentPart implementations for different content types, and utility functions for message creation and manipulation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MarshalMessage

func MarshalMessage(msg BaseMessage) ([]byte, error)

MarshalMessage converts a BaseMessage to JSON bytes with type envelope

func MarshalMessages

func MarshalMessages(messages []BaseMessage) ([]byte, error)

MarshalMessages converts a slice of BaseMessage to JSON bytes

Types

type Attachment

type Attachment struct {
	// MIMEType specifies the media type of the attachment (e.g., "image/png", "text/plain").
	MIMEType string
	// Data contains the raw binary data of the attachment.
	Data []byte
}

Attachment represents a file attachment with its MIME type and binary data.

type BaseMessage

type BaseMessage interface {
	// GetSource returns the source identifier for this message.
	GetSource() string
	// GetCreatedAt returns the creation timestamp of the message.
	GetCreatedAt() time.Time
	// GetContent returns the message content as a generic interface.
	GetContent() interface{}
	// GetMetadata returns the metadata map for this message.
	GetMetadata() map[string]interface{}
	// SetMetadata sets a metadata key-value pair for this message.
	SetMetadata(key string, value interface{})
	// GetRole returns the role of the message sender.
	GetRole() Role
	// GetModel returns the model ID associated with this message.
	GetModel() model.ID
	// SetModel sets the model ID for this message.
	SetModel(modelID model.ID)
}

BaseMessage defines the interface for advanced message implementations with metadata, source tracking, and extended functionality.

func UnmarshalMessage

func UnmarshalMessage(data []byte) (BaseMessage, error)

UnmarshalMessage converts JSON bytes back to a BaseMessage instance

func UnmarshalMessages

func UnmarshalMessages(data []byte) ([]BaseMessage, error)

UnmarshalMessages converts JSON bytes back to a slice of BaseMessage

type BinaryContent

type BinaryContent struct {
	// Path is an optional file path identifier for the binary content.
	Path string
	// MIMEType specifies the media type of the binary data.
	MIMEType string
	// Data contains the raw binary content.
	Data []byte
}

BinaryContent represents binary data (like images) embedded directly in a message.

func (BinaryContent) String

func (bc BinaryContent) String(provider model.Provider) string

String returns the binary content as a base64-encoded string, formatted according to the specified provider's requirements.

type ContentPart

type ContentPart interface {
	// contains filtered or unexported methods
}

ContentPart represents a piece of content within a message. It can be text, images, tool calls, or tool results.

type ContentType

type ContentType string

ContentType identifies the kind of a multimodal content part.

const (
	ContentTypeText     ContentType = "text"
	ContentTypeImage    ContentType = "image"
	ContentTypeBinary   ContentType = "binary"
	ContentTypeImageURL ContentType = "image_url"
)

Multimodal content type constants used in API payloads.

type Envelope

type Envelope struct {
	Type string          `json:"type"`
	Data json.RawMessage `json:"data"`
}

Envelope wraps a typed JSON payload for serialization and routing.

type FinishReason

type FinishReason string

FinishReason indicates why a model stopped generating tokens.

const (
	// FinishReasonEndTurn indicates the model naturally completed its response.
	FinishReasonEndTurn FinishReason = "end_turn"
	// FinishReasonMaxTokens indicates the response was truncated due to token limits.
	FinishReasonMaxTokens FinishReason = "max_tokens"
	// FinishReasonToolUse indicates the model wants to use a tool.
	FinishReasonToolUse FinishReason = "tool_use"
	// FinishReasonCanceled indicates the request was canceled by the user.
	FinishReasonCanceled FinishReason = "canceled"
	// FinishReasonError indicates an error occurred during generation.
	FinishReasonError FinishReason = "error"
	// FinishReasonUnknown indicates an unknown finish reason.
	FinishReasonUnknown FinishReason = "unknown"
)

type ImageURLContent

type ImageURLContent struct {
	// URL is the location of the image resource.
	URL string `json:"url"`
	// Detail specifies the level of detail for image processing (e.g., "low", "high").
	Detail string `json:"detail,omitempty"`
}

ImageURLContent represents an image referenced by URL within a message.

func (ImageURLContent) String

func (iuc ImageURLContent) String() string

String returns the image URL as a string.

type Message

type Message struct {
	// Role indicates who sent the message (user, assistant, system, or tool).
	Role Role
	// Parts contains the various content components of the message.
	Parts []ContentPart
	// Model identifies which AI model this message is associated with.
	Model model.ID
	// CreatedAt is a Unix timestamp (nanoseconds) indicating when the message was created.
	CreatedAt int64
}

Message represents a single message in a conversation with an AI model. It can contain multiple content parts including text, images, tool calls, and tool results.

func NewAssistantMessage

func NewAssistantMessage() Message

NewAssistantMessage creates a new empty assistant message.

func NewMessage

func NewMessage(role Role, parts []ContentPart) Message

NewMessage creates a new message with the specified role and content parts.

func NewSummaryMessage

func NewSummaryMessage(text string) Message

NewSummaryMessage creates a new summary message with the given text content.

func NewSystemMessage

func NewSystemMessage(text string) Message

NewSystemMessage creates a new system message with the given text content.

func NewUserMessage

func NewUserMessage(text string) Message

NewUserMessage creates a new user message with the given text content.

func (*Message) AddBinary

func (m *Message) AddBinary(mimeType string, data []byte)

AddBinary adds binary content to the message with the specified MIME type.

func (*Message) AddFinish

func (m *Message) AddFinish(_ FinishReason)

AddFinish adds a finish reason to the message. This is currently a placeholder for future finish reason support.

func (*Message) AddImageURL

func (m *Message) AddImageURL(url, detail string)

AddImageURL adds an image URL content part to the message.

func (*Message) AddToolResult

func (m *Message) AddToolResult(tr ToolResult)

AddToolResult appends a tool result to the message parts.

func (*Message) AppendContent

func (m *Message) AppendContent(delta string)

AppendContent adds text to the existing text content or creates new text content.

func (*Message) AppendReasoningContent

func (m *Message) AppendReasoningContent(_ string)

AppendReasoningContent adds reasoning text content to the message. This is currently a placeholder for future reasoning content support.

func (*Message) AppendToolCalls

func (m *Message) AppendToolCalls(tc []ToolCall)

AppendToolCalls adds tool calls to the message without clearing existing content.

func (*Message) BinaryContent

func (m *Message) BinaryContent() []BinaryContent

BinaryContent returns all binary content parts from the message.

func (*Message) Content

func (m *Message) Content() TextContent

Content returns the first text content part from the message.

func (*Message) ImageURLContent

func (m *Message) ImageURLContent() []ImageURLContent

ImageURLContent returns all image URL content parts from the message.

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

MarshalJSON encodes the message and its typed content parts for JSON storage.

func (*Message) SetToolCalls

func (m *Message) SetToolCalls(tc []ToolCall)

SetToolCalls replaces all message parts with the provided tool calls.

func (*Message) SetToolResults

func (m *Message) SetToolResults(tr []ToolResult)

SetToolResults replaces all message parts with the provided tool results.

func (*Message) ToolCalls

func (m *Message) ToolCalls() []ToolCall

ToolCalls returns all tool call parts from the message.

func (*Message) ToolResults

func (m *Message) ToolResults() []ToolResult

ToolResults returns all tool result parts from the message.

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON into a message, dispatching on each wrapped part's type tag.

type MultiModalContent

type MultiModalContent struct {
	Type     ContentType `json:"type"`
	Text     string      `json:"text,omitempty"`
	ImageURL string      `json:"image_url,omitempty"`
	MIMEType string      `json:"mime_type,omitempty"`
	Data     []byte      `json:"data,omitempty"`
	Detail   string      `json:"detail,omitempty"`
}

MultiModalContent is one segment of a multimodal message (text, image URL, or binary).

func NewBinaryContent

func NewBinaryContent(mimeType string, data []byte) MultiModalContent

NewBinaryContent creates a binary content part with MIME type and data

func NewImageURLContent

func NewImageURLContent(url, detail string) MultiModalContent

NewImageURLContent creates an image URL content part with optional detail level

func NewTextContent

func NewTextContent(text string) MultiModalContent

NewTextContent creates a text content part for multimodal messages

func (MultiModalContent) GetDataURL

func (mmc MultiModalContent) GetDataURL(provider model.Provider) string

GetDataURL returns a data URL or base64 payload suitable for the given provider.

func (MultiModalContent) String

func (mmc MultiModalContent) String() string

type MultiModalMessage

type MultiModalMessage struct {
	Contents []MultiModalContent `json:"contents"`
	// contains filtered or unexported fields
}

MultiModalMessage carries multiple content parts in a single user or assistant turn.

func NewMultiModalMessage

func NewMultiModalMessage(
	source Source,
	role Role,
	contents []MultiModalContent,
) *MultiModalMessage

NewMultiModalMessage creates a multimodal message with source, role and contents

func NewUserMultiModalMessage

func NewUserMultiModalMessage(contents []MultiModalContent) *MultiModalMessage

NewUserMultiModalMessage creates a user multimodal message with the given contents

func NewUserMultiModalMessageWithAttachments

func NewUserMultiModalMessageWithAttachments(
	text string,
	attachments []Attachment,
) *MultiModalMessage

NewUserMultiModalMessageWithAttachments creates a user message with text and file attachments

func NewUserMultiModalMessageWithText

func NewUserMultiModalMessageWithText(text string) *MultiModalMessage

NewUserMultiModalMessageWithText creates a user multimodal message with text content

func (*MultiModalMessage) AddBinary

func (mmm *MultiModalMessage) AddBinary(mimeType string, data []byte)

AddBinary adds binary content to the message with the specified MIME type

func (*MultiModalMessage) AddContent

func (mmm *MultiModalMessage) AddContent(content MultiModalContent)

AddContent appends a new content part to the message

func (*MultiModalMessage) AddImageURL

func (mmm *MultiModalMessage) AddImageURL(url, detail string)

AddImageURL adds an image URL content part to the message

func (*MultiModalMessage) AddTextContent

func (mmm *MultiModalMessage) AddTextContent(text string)

AddTextContent adds a text content part to the message

func (*MultiModalMessage) AppendTextContent

func (mmm *MultiModalMessage) AppendTextContent(delta string)

AppendTextContent adds text to existing text content or creates new text content

func (*MultiModalMessage) GetBinaryContents

func (mmm *MultiModalMessage) GetBinaryContents() []MultiModalContent

GetBinaryContents returns all binary contents from the message

func (*MultiModalMessage) GetContent

func (mmm *MultiModalMessage) GetContent() interface{}

GetContent returns the contents as an interface for BaseMessage compatibility

func (*MultiModalMessage) GetContents

func (mmm *MultiModalMessage) GetContents() []MultiModalContent

GetContents returns all multimodal contents in the message

func (*MultiModalMessage) GetCreatedAt

func (bm *MultiModalMessage) GetCreatedAt() time.Time

GetCreatedAt returns the creation timestamp of the message.

func (*MultiModalMessage) GetImageURLContents

func (mmm *MultiModalMessage) GetImageURLContents() []MultiModalContent

GetImageURLContents returns all image URL contents from the message

func (*MultiModalMessage) GetMetadata

func (bm *MultiModalMessage) GetMetadata() map[string]interface{}

GetMetadata returns the metadata map, initializing it if necessary.

func (*MultiModalMessage) GetModel

func (bm *MultiModalMessage) GetModel() model.ID

GetModel returns the model ID associated with this message.

func (*MultiModalMessage) GetRole

func (bm *MultiModalMessage) GetRole() Role

GetRole returns the role of the message sender.

func (*MultiModalMessage) GetSource

func (bm *MultiModalMessage) GetSource() string

GetSource returns the string representation of the message source.

func (*MultiModalMessage) GetTextContent

func (mmm *MultiModalMessage) GetTextContent() string

GetTextContent returns the first text content or empty string if none found

func (*MultiModalMessage) MarshalJSON

func (mmm *MultiModalMessage) MarshalJSON() ([]byte, error)

MarshalJSON encodes the message including base fields and multimodal payload.

func (*MultiModalMessage) SetMetadata

func (bm *MultiModalMessage) SetMetadata(key string, value interface{})

SetMetadata sets a metadata key-value pair, initializing the map if necessary.

func (*MultiModalMessage) SetModel

func (bm *MultiModalMessage) SetModel(modelID model.ID)

SetModel sets the model ID for this message.

func (*MultiModalMessage) UnmarshalJSON

func (mmm *MultiModalMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON into a MultiModalMessage, including timestamps and metadata.

type Role

type Role string

Role describes who produced a message in a conversation (user, assistant, system, tool, or summary).

const (
	// Assistant represents messages from the AI assistant.
	Assistant Role = "assistant"
	// User represents messages from the human user.
	User Role = "user"
	// System represents system-level instructions or context.
	System Role = "system"
	// Tool represents responses from tool executions.
	Tool Role = "tool"
	// Summary represents a summarized conversation history.
	// Stored in session, converted to User when sending to LLM.
	Summary Role = "summary"
)

type Source

type Source struct {
	// Type indicates the category or provider of the message source.
	Type string `json:"type"`
	// ID is a unique identifier within the source type.
	ID string `json:"id"`
}

Source identifies where a message came from using a category string and optional instance ID.

func NewSource

func NewSource(sourceType, id string) Source

NewSource creates a message source with type and ID, generating ID if empty.

func (Source) String

func (ms Source) String() string

String returns a string representation of the message source.

type TextContent

type TextContent struct {
	// Text contains the actual text content.
	Text string `json:"text"`
}

TextContent represents plain text content within a message.

func (TextContent) String

func (tc TextContent) String() string

String returns the text content as a string.

type TextMessage

type TextMessage struct {

	// Content contains the text content of the message.
	Content string `json:"content"`
	// contains filtered or unexported fields
}

TextMessage represents a message containing only text content with extended metadata support. It implements the BaseMessage interface and provides JSON serialization capabilities.

func NewAssistantTextMessage

func NewAssistantTextMessage(content string) *TextMessage

NewAssistantTextMessage creates an assistant text message with the given content.

func NewSystemTextMessage

func NewSystemTextMessage(content string) *TextMessage

NewSystemTextMessage creates a system text message with the given content.

func NewTextMessage

func NewTextMessage(
	source Source,
	role Role,
	content string,
) *TextMessage

NewTextMessage creates a text message with source, role and content.

func NewUserTextMessage

func NewUserTextMessage(content string) *TextMessage

NewUserTextMessage creates a user text message with the given content.

func (*TextMessage) AppendText

func (tm *TextMessage) AppendText(delta string)

AppendText adds the given text to the existing content.

func (*TextMessage) GetContent

func (tm *TextMessage) GetContent() interface{}

GetContent returns the text content as an interface for BaseMessage compatibility.

func (*TextMessage) GetCreatedAt

func (bm *TextMessage) GetCreatedAt() time.Time

GetCreatedAt returns the creation timestamp of the message.

func (*TextMessage) GetMetadata

func (bm *TextMessage) GetMetadata() map[string]interface{}

GetMetadata returns the metadata map, initializing it if necessary.

func (*TextMessage) GetModel

func (bm *TextMessage) GetModel() model.ID

GetModel returns the model ID associated with this message.

func (*TextMessage) GetRole

func (bm *TextMessage) GetRole() Role

GetRole returns the role of the message sender.

func (*TextMessage) GetSource

func (bm *TextMessage) GetSource() string

GetSource returns the string representation of the message source.

func (*TextMessage) GetText

func (tm *TextMessage) GetText() string

GetText returns the text content of the message.

func (*TextMessage) MarshalJSON

func (tm *TextMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for TextMessage.

func (*TextMessage) SetMetadata

func (bm *TextMessage) SetMetadata(key string, value interface{})

SetMetadata sets a metadata key-value pair, initializing the map if necessary.

func (*TextMessage) SetModel

func (bm *TextMessage) SetModel(modelID model.ID)

SetModel sets the model ID for this message.

func (*TextMessage) UnmarshalJSON

func (tm *TextMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for TextMessage.

type ToolCall

type ToolCall struct {
	// ID is a unique identifier for this tool call.
	ID string `json:"id"`
	// Name is the name of the tool to execute.
	Name string `json:"name"`
	// Input contains the JSON-encoded parameters for the tool.
	Input string `json:"input"`
	// Type specifies the type of tool call (usually "function").
	Type string `json:"type"`
	// Finished indicates whether the tool call has completed execution.
	Finished bool `json:"finished"`
}

ToolCall represents a request to execute a tool with specific parameters.

type ToolResult

type ToolResult struct {
	// ToolCallID links this result to the corresponding tool call.
	ToolCallID string `json:"tool_call_id"`
	// Name is the name of the tool that was executed.
	Name string `json:"name"`
	// Content contains the result content from the tool execution.
	Content string `json:"content"`
	// Metadata contains additional JSON-encoded metadata about the result.
	Metadata string `json:"metadata"`
	// IsError indicates whether the tool execution resulted in an error.
	IsError bool `json:"is_error"`
}

ToolResult represents the result of a tool execution.

Jump to

Keyboard shortcuts

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