message

package
v0.0.0-...-7871f83 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2025 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package message provides types for representing multi-modal conversational messages between humans, AI assistants, tools, and systems.

Overview

Messages are the fundamental unit of communication in agent conversations. The message package defines structured message types with support for:

  • Text content
  • Structured data
  • File attachments
  • Tool calls and responses
  • Multiple content parts per message

Message Types

Different message types represent different conversation participants:

// System message (instructions for AI)
system := message.NewSystemMessageFromText("You are a helpful assistant")

// Human message (user input)
human := message.NewHumanMessageFromText("Hello, how are you?")

// AI message (assistant response)
ai := message.NewAIMessageFromText("I'm doing well, thank you!")

// Tool message (tool execution result)
tool := message.NewToolMessage(toolID, toolName, resultJSON)

Multi-Part Messages

Messages can contain multiple content parts:

parts := message.Parts{
	message.TextPart{Text: "Here is the image:"},
	message.FilePart{
		File: message.FileURI{URI: "https://example.com/image.jpg"},
		MimeType: "image/jpeg",
	},
}
msg := message.NewAIMessage(parts)

Content Types

Supported content part types:

  • TextPart: Plain UTF-8 text
  • DataPart: Structured data (JSON objects)
  • FilePart: File attachments (bytes, base64, path, or URI)
  • FunctionCallPart: Tool invocation requests
  • FunctionResponsePart: Tool execution results

Tool Calling

AI messages can request tool execution:

calls := []message.FunctionCall{
	{
		ID:        "call_123",
		Name:      "get_weather",
		Arguments: `{"location": "Boston"}`,
	},
}
aiMsg := message.NewAIMessage(nil)
aiMsg.ToolCalls = calls

Tool results are returned as tool messages:

result := message.NewToolMessage(
	"call_123",
	"get_weather",
	`{"temperature": 72, "conditions": "sunny"}`,
)

Message Interface

All message types implement the Message interface:

type Message interface {
	Type() Type
	Parts() Parts
	Clone() Message
}

Cloning

Messages are immutable - use Clone() to create copies:

original := message.NewHumanMessageFromText("Hello")
cloned := original.Clone()

Conversation History

Messages are typically stored in slices:

conversation := []message.Message{
	message.NewSystemMessageFromText("You are helpful"),
	message.NewHumanMessageFromText("Hello"),
	message.NewAIMessageFromText("Hi there!"),
}

Type Constants

Message types are identified by constants:

const (
	TypeSystem   Type = "system"   // System instructions
	TypeHuman    Type = "human"    // User input
	TypeAI       Type = "ai"       // Assistant response
	TypeChat     Type = "chat"     // Generic chat message
	TypeFunction Type = "function" // Function/tool call
	TypeTool     Type = "tool"     // Tool result
)

Best Practices

  • Use appropriate message types for each participant
  • Keep system messages concise and clear
  • Structure tool responses as JSON when possible
  • Clone messages before mutation
  • Preserve message order in conversations

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HasToolCalls

func HasToolCalls(msg Message) bool

HasToolCalls checks if a message contains tool calls. Returns true if the message is an AIMessage with at least one tool call.

Example:

if message.HasToolCalls(msg) {
    // Route to tool execution
}

func MarshalMessage

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

MarshalMessage implements json.Marshaler for Message interface.

Types

type AIMessage

type AIMessage struct {
	ToolCalls []ToolCall
	Name      string
	// contains filtered or unexported fields
}

AIMessage models an assistant/AI response.

func NewAIMessage

func NewAIMessage(parts Parts, opts ...Option) *AIMessage

NewAIMessage creates an AI message from parts.

func NewAIMessageFromText

func NewAIMessageFromText(text string, opts ...Option) *AIMessage

NewAIMessageFromText creates an AI message from plain text.

func (*AIMessage) Clone

func (m *AIMessage) Clone() Message

Clone creates a deep copy of the message.

func (*AIMessage) Parts

func (m *AIMessage) Parts() Parts

Parts returns the message content.

func (*AIMessage) String

func (m *AIMessage) String() string

String returns the text content of the message.

func (*AIMessage) Type

func (m *AIMessage) Type() Type

Type returns the message type.

type AIMessageChunk

type AIMessageChunk struct {
	BaseMessageChunk
	ToolCalls []ToolCall
}

AIMessageChunk is a streaming fragment of an AI response. Unlike AIMessage, chunks are yielded in real-time during streaming but are NOT added to the conversation state. The final complete AIMessage is added to state after streaming completes.

AIMessageChunk implements the Message interface, allowing it to be yielded from agent.Run() alongside regular messages. Use type assertion to distinguish chunks from complete messages:

for msg, err := range agent.Run(ctx, messages) {
    switch m := msg.(type) {
    case *message.AIMessageChunk:
        fmt.Print(m.String()) // Stream partial output
    case *message.AIMessage:
        // Final complete message (already in state)
    }
}

func NewAIMessageChunk

func NewAIMessageChunk(text string, opts ...Option) *AIMessageChunk

NewAIMessageChunk creates a new AI message chunk.

func (*AIMessageChunk) Clone

func (c *AIMessageChunk) Clone() Message

Clone creates a deep copy of the AI message chunk. Implements the Message interface.

func (*AIMessageChunk) CloneChunk

func (c *AIMessageChunk) CloneChunk() *AIMessageChunk

CloneChunk creates a deep copy returning the concrete type. Use this when you need to preserve the *AIMessageChunk type.

func (*AIMessageChunk) Merge

func (c *AIMessageChunk) Merge(other *AIMessageChunk) (*AIMessageChunk, error)

Merge combines this AI message chunk with another.

type BaseMessageChunk

type BaseMessageChunk struct {
	// contains filtered or unexported fields
}

BaseMessageChunk represents a streaming fragment of a message.

func NewBaseMessageChunk

func NewBaseMessageChunk(msgType Type, text string, opts ...Option) *BaseMessageChunk

NewBaseMessageChunk creates a new message chunk with the given type.

func (*BaseMessageChunk) Clone

func (c *BaseMessageChunk) Clone() *BaseMessageChunk

Clone creates a deep copy of the chunk.

func (*BaseMessageChunk) Merge

Merge combines this chunk with another chunk.

func (*BaseMessageChunk) Parts

func (c *BaseMessageChunk) Parts() Parts

Parts returns the message content.

func (*BaseMessageChunk) String

func (c *BaseMessageChunk) String() string

String returns the text content of the chunk.

func (*BaseMessageChunk) Type

func (c *BaseMessageChunk) Type() Type

Type returns the message type.

type ChatMessage

type ChatMessage struct {
	// contains filtered or unexported fields
}

ChatMessage models a custom-role chat message.

func NewChatMessage

func NewChatMessage(role string, text string, opts ...Option) *ChatMessage

NewChatMessage creates a chat message with a custom role.

func (*ChatMessage) Clone

func (m *ChatMessage) Clone() Message

Clone creates a deep copy of the message.

func (*ChatMessage) Parts

func (m *ChatMessage) Parts() Parts

Parts returns the message content.

func (*ChatMessage) String

func (m *ChatMessage) String() string

String returns the text content of the message.

func (*ChatMessage) Type

func (m *ChatMessage) Type() Type

Type returns the message type.

type DataPart

type DataPart struct {
	Data map[string]any `json:"data"`
}

DataPart is a structured data segment (for example a JSON object map).

type FileBase64

type FileBase64 struct {
	Base64 string `json:"base64"`
}

FileBase64 represents a file with its content provided as a base64-encoded string.

type FilePart

type FilePart struct {
	File     FilePartContent `json:"file"`
	MimeType string          `json:"mimeType"`
	Name     string          `json:"name"`
}

FilePart represents a file segment within a message or artifact.

type FilePartContent

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

FilePartContent is a discriminated union representing file payloads.

type FilePath

type FilePath struct {
	Path string `json:"path"`
}

FilePath represents a local filesystem path to a file.

type FileRawBytes

type FileRawBytes struct {
	Bytes []byte `json:"bytes"`
}

FileRawBytes represents a file with its content provided directly as raw bytes.

type FileURI

type FileURI struct {
	URI string `json:"uri"`
}

FileURI represents a file whose content is available via URI.

type FunctionCall

type FunctionCall struct {
	ID        string `json:"id,omitzero"`
	Name      string `json:"name"`
	Arguments string `json:"arguments,omitzero"`
}

FunctionCall describes a tool/function invocation request.

type FunctionCallPart

type FunctionCallPart struct {
	FunctionCall *FunctionCall `json:"functionCall"`
}

FunctionCallPart wraps a FunctionCall as a content part.

type FunctionMessage

type FunctionMessage struct {
	Name string
	// contains filtered or unexported fields
}

FunctionMessage captures serialized tool/function responses.

func NewFunctionMessage

func NewFunctionMessage(name string, text string, opts ...Option) *FunctionMessage

NewFunctionMessage creates a function message with the given name and text.

func (*FunctionMessage) Clone

func (m *FunctionMessage) Clone() Message

Clone creates a deep copy of the message.

func (*FunctionMessage) Parts

func (m *FunctionMessage) Parts() Parts

Parts returns the message content.

func (*FunctionMessage) String

func (m *FunctionMessage) String() string

String returns the text content of the message.

func (*FunctionMessage) Type

func (m *FunctionMessage) Type() Type

Type returns the message type.

type FunctionResponse

type FunctionResponse struct {
	ID       string `json:"id,omitzero"`
	Name     string `json:"name"`
	Response any    `json:"response,omitzero"`
}

FunctionResponse describes the outcome of a function call.

type FunctionResponsePart

type FunctionResponsePart struct {
	FunctionResponse *FunctionResponse `json:"functionResponse"`
}

FunctionResponsePart wraps a FunctionResponse as a content part.

type HumanMessage

type HumanMessage struct {
	// contains filtered or unexported fields
}

HumanMessage models a human/user authored message.

func NewHumanMessage

func NewHumanMessage(parts Parts, opts ...Option) *HumanMessage

NewHumanMessage creates a human message from parts.

func NewHumanMessageFromText

func NewHumanMessageFromText(text string, opts ...Option) *HumanMessage

NewHumanMessageFromText creates a human message from plain text.

func (*HumanMessage) Clone

func (m *HumanMessage) Clone() Message

Clone creates a deep copy of the message.

func (*HumanMessage) Parts

func (m *HumanMessage) Parts() Parts

Parts returns the message content.

func (*HumanMessage) String

func (m *HumanMessage) String() string

String returns the text content of the message.

func (*HumanMessage) Type

func (m *HumanMessage) Type() Type

Type returns the message type.

type Message

type Message interface {
	fmt.Stringer

	Type() Type
	Parts() Parts
	Clone() Message
}

Message represents the minimal shape shared across message variants.

func FromSerializable

func FromSerializable(sm *SerializableMessage) (Message, error)

FromSerializable converts a SerializableMessage back to a Message interface.

func UnmarshalMessage

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

UnmarshalMessage implements json.Unmarshaler for Message interface.

type Option

type Option func(*messageBase)

Option configures creation of messageBase derivatives.

func WithMetadata

func WithMetadata(metadata map[string]any) Option

WithMetadata sets metadata key-value pairs on a message.

type Part

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

Part is a polymorphic segment of role-based content. Concrete part types implement the unexported isPart marker to form a closed set.

type PartKind

type PartKind string

PartKind represents the type of a serializable content part.

const (
	PartKindText             PartKind = "text"
	PartKindData             PartKind = "data"
	PartKindFile             PartKind = "file"
	PartKindFunctionCall     PartKind = "function_call"
	PartKindFunctionResponse PartKind = "function_response"
)

Part kind constants for serialization.

type Parts

type Parts = []Part

Parts represents an ordered sequence of content parts.

type SerialPart

type SerialPart struct {
	Kind PartKind       `json:"kind"`
	Data map[string]any `json:"data"`
}

SerialPart represents a serializable content part.

type SerializableMessage

type SerializableMessage struct {
	MsgType    Type         `json:"type"`
	Parts      []SerialPart `json:"parts"`
	ToolCalls  []ToolCall   `json:"tool_calls,omitempty"`
	Name       string       `json:"name,omitempty"`
	ToolCallID string       `json:"tool_call_id,omitempty"`
}

SerializableMessage wraps a Message for JSON serialization. This enables message.Message interfaces to be marshaled/unmarshaled through Redis.

func ToSerializable

func ToSerializable(msg Message) *SerializableMessage

ToSerializable converts a Message interface to a serializable form.

type SystemMessage

type SystemMessage struct {
	// contains filtered or unexported fields
}

SystemMessage models a system-role message.

func NewSystemMessage

func NewSystemMessage(parts Parts, opts ...Option) *SystemMessage

NewSystemMessage creates a system message from parts.

func NewSystemMessageFromText

func NewSystemMessageFromText(text string, opts ...Option) *SystemMessage

NewSystemMessageFromText creates a system message from plain text.

func (*SystemMessage) Clone

func (m *SystemMessage) Clone() Message

Clone creates a deep copy of the message.

func (*SystemMessage) Parts

func (m *SystemMessage) Parts() Parts

Parts returns the message content.

func (*SystemMessage) String

func (m *SystemMessage) String() string

String returns the text content of the message.

func (*SystemMessage) Type

func (m *SystemMessage) Type() Type

Type returns the message type.

type TextPart

type TextPart struct {
	Text string `json:"text"`
}

TextPart is a plain UTF-8 text content segment.

func NewTextPart

func NewTextPart(text string) TextPart

NewTextPart is a helper to construct a TextPart.

type ToolCall

type ToolCall struct {
	ID        string `json:"id"`        // Unique identifier for this tool call
	Name      string `json:"name"`      // Tool/function name to invoke
	Type      string `json:"type"`      // Call type (typically "function")
	Arguments string `json:"arguments"` // Tool arguments as JSON string (not map[string]any)
}

ToolCall mirrors LangChain tool invocation metadata.

The Arguments field is a JSON string (not a map) to avoid wasteful marshal/unmarshal cycles in the execution pipeline. Arguments flow as JSON strings from LLM generation through message processing to tool execution.

This design eliminates the need to:

  1. Unmarshal JSON string to map (from LLM)
  2. Marshal map back to JSON string (to tool)

Instead, arguments stay as JSON strings throughout:

LLM → ToolCall.Arguments (string) → tool.Call.Arguments (string) → Tool

Example:

toolCall := message.ToolCall{
    ID:        "call_abc123",
    Name:      "get_weather",
    Type:      "function",
    Arguments: `{"location":"Berlin","unit":"celsius"}`,
}

type ToolMessage

type ToolMessage struct {
	ToolCallID string
	// contains filtered or unexported fields
}

ToolMessage stores tool output tied to a specific tool call.

func NewToolMessage

func NewToolMessage(toolCallID string, text string, opts ...Option) *ToolMessage

NewToolMessage creates a tool message linked to a specific tool call ID.

func (*ToolMessage) Clone

func (m *ToolMessage) Clone() Message

Clone creates a deep copy of the message.

func (*ToolMessage) Parts

func (m *ToolMessage) Parts() Parts

Parts returns the message content.

func (*ToolMessage) String

func (m *ToolMessage) String() string

String returns the text content of the message.

func (*ToolMessage) Type

func (m *ToolMessage) Type() Type

Type returns the message type.

type Type

type Type string

Type indicates the conversational role/category associated with a message.

const (
	// TypeSystem represents system-level instructions or metadata.
	TypeSystem Type = "system"
	// TypeHuman represents user input messages.
	TypeHuman Type = "human"
	// TypeAI represents AI-generated responses.
	TypeAI Type = "ai"
	// TypeAIChunk represents a streaming chunk of an AI response.
	// Used for real-time output during streaming mode.
	// Unlike TypeAI, chunks are not added to conversation state.
	TypeAIChunk Type = "ai_chunk"
	// TypeChat represents generic chat messages.
	TypeChat Type = "chat"
	// TypeFunction represents function call results.
	TypeFunction Type = "function"
	// TypeTool represents tool execution results.
	TypeTool Type = "tool"
)

Jump to

Keyboard shortcuts

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