message

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package message defines the message and content primitives that are the universal currency of the framework.

A Message carries a Role and an ordered list of typed Content parts — text, reasoning, data and URI references, function calls and results, usage, and annotations, among others. Agent input and output, tool results, and workflow payloads all flow as messages. Content parts marshal to and from a discriminated JSON representation so messages can be persisted and replayed.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeDataURI

func DecodeDataURI(uri string) (data []byte, mediaType string, err error)

DecodeDataURI parses a data URI (RFC 2397) and returns the decoded bytes together with its media type. It is intended for providers that must send inline binary data (rather than a URI reference) when handling a URIContent whose URI is a data: URI.

Types

type AlwaysApproveToolApprovalResponseContent

type AlwaysApproveToolApprovalResponseContent struct {
	ContentHeader

	InnerResponse *ToolApprovalResponseContent `json:"innerResponse"`

	// AlwaysApproveTool, when true, indicates a standing rule to auto-approve
	// all future calls to the same tool regardless of arguments.
	AlwaysApproveTool bool `json:"AlwaysApproveTool,omitempty"`

	// AlwaysApproveToolWithArguments, when true, indicates a standing rule to
	// auto-approve future calls to the same tool only when the arguments
	// match exactly.
	AlwaysApproveToolWithArguments bool `json:"AlwaysApproveToolWithArguments,omitempty"`
}

AlwaysApproveToolApprovalResponseContent wraps a tool approval response and adds standing rule hints for tool-approval middleware.

func (*AlwaysApproveToolApprovalResponseContent) MarshalJSON

func (t *AlwaysApproveToolApprovalResponseContent) MarshalJSON() ([]byte, error)

type AnnotatedRegion

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

AnnotatedRegion describes the portion of an associated Content to which an annotation applies.

type AnnotatedRegions

type AnnotatedRegions []AnnotatedRegion

AnnotatedRegions is a slice of AnnotatedRegion values; its UnmarshalJSON decodes each element as a discriminated union based on its type discriminator (currently TextSpanAnnotatedRegion).

func (*AnnotatedRegions) UnmarshalJSON

func (as *AnnotatedRegions) UnmarshalJSON(data []byte) error

type Annotation

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

Annotation represents an annotation on content.

type Annotations

type Annotations []Annotation

Annotations is a slice of Annotation values; its UnmarshalJSON decodes each element as a discriminated union based on its type discriminator (currently CitationAnnotation).

func (*Annotations) UnmarshalJSON

func (as *Annotations) UnmarshalJSON(data []byte) error

type CitationAnnotation

type CitationAnnotation struct {
	AdditionalProperties map[string]any   `json:",omitzero"`
	AnnotatedRegions     AnnotatedRegions `json:",omitempty"`
	RawRepresentation    any              `json:"-"`

	FileID   string `json:",omitempty"` // Source identifier associated with the annotation.
	Snippet  string `json:",omitempty"` // Snippet or excerpt from the source that was cited.
	Title    string `json:",omitempty"` // Title or name of the source.
	ToolName string `json:",omitempty"` // Name of any tool involved in the production of the associated content.
	URL      string `json:",omitempty"` // URI from which the source material was retrieved.
}

CitationAnnotation represents an annotation that links content to source references, such as documents, URLs, files, or tool outputs.

func (*CitationAnnotation) MarshalJSON

func (t *CitationAnnotation) MarshalJSON() ([]byte, error)

type CodeInterpreterToolCallContent

type CodeInterpreterToolCallContent struct {
	ContentHeader

	CallID string
	Inputs Contents
}

CodeInterpreterToolCallContent represents a call to a hosted code-interpreter tool, correlated by CallID, whose Inputs hold the submitted code or content.

func (*CodeInterpreterToolCallContent) MarshalJSON

func (t *CodeInterpreterToolCallContent) MarshalJSON() ([]byte, error)

type CodeInterpreterToolResultContent

type CodeInterpreterToolResultContent struct {
	ContentHeader

	CallID  string
	Outputs Contents
}

CodeInterpreterToolResultContent represents the result of a hosted code-interpreter tool call, correlated by CallID, whose Outputs hold the produced content.

func (*CodeInterpreterToolResultContent) MarshalJSON

func (t *CodeInterpreterToolResultContent) MarshalJSON() ([]byte, error)

type Content

type Content interface {
	json.Marshaler

	Header() *ContentHeader
	// contains filtered or unexported methods
}

Content represents message content.

func CoalesceContents

func CoalesceContents(contents []Content) []Content

CoalesceContents combines sequential contents elements.

type ContentHeader

type ContentHeader struct {
	AdditionalProperties map[string]any `json:",omitzero"`
	Annotations          Annotations    `json:",omitempty"`
	RawRepresentation    any            `json:"-"`
}

ContentHeader contains common properties for all content types.

func (*ContentHeader) Header

func (ch *ContentHeader) Header() *ContentHeader

type Contents

type Contents []Content

Contents is a slice of Content that supports JSON encoding.

func (Contents) Text

func (cs Contents) Text() string

Text returns the concatenation of the Text of all TextContent items in the Contents, or the empty string if there are none.

func (*Contents) UnmarshalJSON

func (cs *Contents) UnmarshalJSON(data []byte) error

func (Contents) Usage

func (cs Contents) Usage() UsageDetails

Usage sums the UsageDetails of every UsageContent in the slice, returning the aggregate token usage (a zero UsageDetails if none is present).

type DataContent

type DataContent struct {
	ContentHeader

	// Name is an optional name associated with the data.
	// A service might use this name as part of citations or to help infer the type of data
	// being represented based on a file extension.
	Name string

	Data      string // base64-encoded data
	MediaType string
}

DataContent represents binary content with an associated media type.

The content represents in-memory data. For references to data at a remote URI, use URIContent instead.

func (*DataContent) Bytes

func (t *DataContent) Bytes() ([]byte, error)

Bytes returns the decoded data.

func (*DataContent) MarshalJSON

func (t *DataContent) MarshalJSON() ([]byte, error)

func (*DataContent) TopLevelMediaType

func (t *DataContent) TopLevelMediaType() string

TopLevelMediaType returns the normalized (lowercased, whitespace-trimmed) top-level part of the content's MediaType - the portion before the / (for example image for image/png). If MediaType contains no /, the whole normalized value is returned; if MediaType is unset, it returns an empty string.

func (*DataContent) URI

func (t *DataContent) URI() string

URI returns the Data URI representation of the content, as defined in RFC 2397:

data:[<mediatype>][;base64],<data>

func (*DataContent) UnmarshalJSON

func (t *DataContent) UnmarshalJSON(data []byte) error

type ErrorContent

type ErrorContent struct {
	ContentHeader

	Message   string
	Details   string `json:",omitempty"`
	ErrorCode string `json:",omitempty"`
}

ErrorContent represents an error.

Typically, ErrorContent is used for non-fatal errors, where something went wrong as part of the operation but the operation was still able to continue.

func (*ErrorContent) MarshalJSON

func (t *ErrorContent) MarshalJSON() ([]byte, error)

type FunctionCallContent

type FunctionCallContent struct {
	ContentHeader

	Arguments         string
	CallID            string
	Error             error // Error that occurred while mapping the original function call data to this object.
	Name              string
	InformationalOnly bool
}

FunctionCallContent represents a function call request.

func (*FunctionCallContent) GetCallID

func (t *FunctionCallContent) GetCallID() string

func (*FunctionCallContent) MarshalJSON

func (t *FunctionCallContent) MarshalJSON() ([]byte, error)

func (*FunctionCallContent) UnmarshalJSON

func (t *FunctionCallContent) UnmarshalJSON(data []byte) error

type FunctionResultContent

type FunctionResultContent struct {
	ContentHeader

	CallID string
	Error  error `json:",omitempty"` // Error that occurred if the function call failed.
	Result any   `json:",omitempty"`
}

FunctionResultContent represents the result of a function call.

func (*FunctionResultContent) MarshalJSON

func (t *FunctionResultContent) MarshalJSON() ([]byte, error)

func (*FunctionResultContent) UnmarshalJSON

func (t *FunctionResultContent) UnmarshalJSON(data []byte) error

type HostedFileContent

type HostedFileContent struct {
	ContentHeader

	FileID    string
	Name      string `json:",omitempty"`
	MediaType string `json:",omitempty"`
}

HostedFileContent represents a file that is hosted by the AI service.

Unlike DataContent which contains the data for a file or blob, this class represents a file that is hosted by the AI service and referenced by an identifier. Such identifiers are specific to the provider.

func (*HostedFileContent) MarshalJSON

func (t *HostedFileContent) MarshalJSON() ([]byte, error)

func (*HostedFileContent) TopLevelMediaType

func (t *HostedFileContent) TopLevelMediaType() string

TopLevelMediaType returns the normalized (lowercased, whitespace-trimmed) top-level part of the content's MediaType - the portion before the / (for example image for image/png). If MediaType contains no /, the whole normalized value is returned; if MediaType is unset, it returns an empty string.

type HostedVectorStoreContent

type HostedVectorStoreContent struct {
	ContentHeader

	VectorStoreID string
}

HostedVectorStoreContent represents a vector store that is hosted by the AI service.

Unlike HostedFileContent which represents a specific file that is hosted by the AI service, HostedVectorStoreContent represents a vector store that can contain multiple files, indexed for searching.

func (*HostedVectorStoreContent) MarshalJSON

func (t *HostedVectorStoreContent) MarshalJSON() ([]byte, error)

type MCPServerToolCallContent

type MCPServerToolCallContent struct {
	ContentHeader

	Arguments  string
	CallID     string
	Name       string
	ServerName string `json:",omitempty"`
}

MCPServerToolCallContent represents a tool call request to a MCP server.

This content type is used to represent an invocation of an MCP server tool by a hosted service. It is informational only and may appear as part of an approval request to convey what is being approved, or as a record of which MCP server tool was invoked.

func (*MCPServerToolCallContent) GetCallID

func (t *MCPServerToolCallContent) GetCallID() string

func (*MCPServerToolCallContent) MarshalJSON

func (t *MCPServerToolCallContent) MarshalJSON() ([]byte, error)

type MCPServerToolResultContent

type MCPServerToolResultContent struct {
	ContentHeader

	CallID     string
	Name       string
	ServerName string   `json:",omitempty"`
	Outputs    Contents `json:",omitempty"`
	Error      string   `json:",omitempty"`
}

MCPServerToolResultContent represents the result of a tool call executed by a hosted MCP server.

It mirrors MCPServerToolCallContent and conveys the outputs (and any error) produced when a hosted service runs an MCP server tool.

func (*MCPServerToolResultContent) MarshalJSON

func (t *MCPServerToolResultContent) MarshalJSON() ([]byte, error)

type Message

type Message struct {
	AdditionalProperties map[string]any `json:",omitzero"`
	Contents             Contents
	Role                 Role
	ID                   string
	AuthorName           string    `json:",omitzero"`
	Source               Source    `json:",omitzero"`
	CreatedAt            time.Time `json:",omitzero"`
	RawRepresentation    any       `json:"-"`
}

Message represents a message in a conversation.

func New

func New(contents ...Content) *Message

New creates a new Message with the given contents and RoleUser. To use a different role, set Message.Role on the returned Message.

func NewText

func NewText(text string) *Message

NewText creates a new Message with text content.

func (*Message) Clone

func (m *Message) Clone() *Message

Clone creates a shallow copy of the message, cloning its top-level map and slice containers while sharing their values and content objects.

func (*Message) String

func (m *Message) String() string

String implements fmt.Stringer, returning the concatenated text of all TextContent in the message (delegating to Contents.Text).

func (*Message) Usage

func (m *Message) Usage() UsageDetails

Usage returns the aggregated UsageDetails carried by the message's UsageContent (delegating to Contents.Usage).

type RawAnnotatedRegion

type RawAnnotatedRegion struct {
	RawRepresentation json.RawMessage
}

RawAnnotatedRegion represents a provider-specific annotated region that does not fit one of the structured region types. The original JSON is preserved in RawRepresentation and round-tripped on marshal so that newer provider-emitted region subtypes do not fail the enclosing deserialization.

func (*RawAnnotatedRegion) MarshalJSON

func (t *RawAnnotatedRegion) MarshalJSON() ([]byte, error)

type RawAnnotation

type RawAnnotation struct {
	RawRepresentation json.RawMessage
}

RawAnnotation represents a provider-specific annotation that does not fit one of the structured annotation types. The original JSON is preserved in RawRepresentation and round-tripped on marshal so that newer provider-emitted annotation subtypes do not fail the enclosing deserialization.

func (*RawAnnotation) MarshalJSON

func (t *RawAnnotation) MarshalJSON() ([]byte, error)

type RawContent

type RawContent struct {
	ContentHeader
}

RawContent represents provider-specific content that does not fit one of the structured content types. The provider value is available through ContentHeader.RawRepresentation.

func (*RawContent) MarshalJSON

func (t *RawContent) MarshalJSON() ([]byte, error)

func (*RawContent) UnmarshalJSON

func (t *RawContent) UnmarshalJSON(data []byte) error

type Role

type Role string

Role represents the role of a message sender in a conversation.

const (
	// RoleUser represents a message from the user.
	RoleUser Role = "user"
	// RoleAssistant represents a message from the assistant.
	RoleAssistant Role = "assistant"
	// RoleSystem represents a system message.
	RoleSystem Role = "system"
	// RoleTool represents a message from a tool execution.
	RoleTool Role = "tool"
)

type Source

type Source struct {
	// ID is the unique identifier of the source that generated the message.
	ID string `json:",omitzero"`

	// Type identifies the kind of component that generated the message.
	Type SourceType `json:",omitzero"`
}

Source represents attribution information for the source of a message.

type SourceType

type SourceType string

SourceType represents the type of component that generated a message.

const SourceTypeExternal SourceType = ""

SourceTypeExternal is the zero source type for messages that originated outside the agent pipeline.

type TextContent

type TextContent struct {
	ContentHeader

	Text string
}

TextContent represents plain text content.

func (*TextContent) MarshalJSON

func (t *TextContent) MarshalJSON() ([]byte, error)

func (*TextContent) String

func (t *TextContent) String() string

String returns the text of the content.

type TextReasoningContent

type TextReasoningContent struct {
	ContentHeader

	ProtectedData string `json:",omitempty"`
	Text          string
}

TextReasoningContent represents text reasoning content in a chat.

TextReasoningContent is distinct from TextContent. TextReasoningContent represents "thinking" or "reasoning" performed by the model and is distinct from the actual output text from the model, which is represented by TextContent.

func (*TextReasoningContent) MarshalJSON

func (t *TextReasoningContent) MarshalJSON() ([]byte, error)

func (*TextReasoningContent) String

func (t *TextReasoningContent) String() string

String returns the text of the reasoning content.

type TextSpanAnnotatedRegion

type TextSpanAnnotatedRegion struct {
	Start int // Start character index (inclusive) of the annotated span.
	End   int // End character index (exclusive) of the annotated span.
}

TextSpanAnnotatedRegion describes a location in the associated Content based on starting and ending character indices.

func (*TextSpanAnnotatedRegion) MarshalJSON

func (t *TextSpanAnnotatedRegion) MarshalJSON() ([]byte, error)

type ToolApprovalRequestContent

type ToolApprovalRequestContent struct {
	ContentHeader

	RequestID string
	ToolCall  ToolCallContent
}

ToolApprovalRequestContent represents a request for approval to execute a tool.

func (*ToolApprovalRequestContent) AlwaysApproveToolResponse

AlwaysApproveToolResponse creates a response that approves this tool call and records a standing rule to automatically approve all future calls to the same tool, regardless of arguments.

func (*ToolApprovalRequestContent) AlwaysApproveToolWithArgsResponse deprecated

func (t *ToolApprovalRequestContent) AlwaysApproveToolWithArgsResponse() *AlwaysApproveToolApprovalResponseContent

Deprecated: Use AlwaysApproveToolWithArgumentsResponse instead. AlwaysApproveToolWithArgsResponse is an alias for AlwaysApproveToolWithArgumentsResponse.

func (*ToolApprovalRequestContent) AlwaysApproveToolWithArgumentsResponse

func (t *ToolApprovalRequestContent) AlwaysApproveToolWithArgumentsResponse() *AlwaysApproveToolApprovalResponseContent

AlwaysApproveToolWithArgumentsResponse creates a response that approves this tool call and records a standing rule to automatically approve future calls to the same tool only when the arguments match exactly.

func (*ToolApprovalRequestContent) CreateResponse

func (t *ToolApprovalRequestContent) CreateResponse(approved bool, reason string) *ToolApprovalResponseContent

CreateResponse builds a ToolApprovalResponseContent that approves or rejects this request. It carries over the RequestID, records the decision and reason, and clones the pending tool call along with the AdditionalProperties and Annotations of the content header. Note that RawRepresentation is copied by reference.

func (*ToolApprovalRequestContent) MarshalJSON

func (t *ToolApprovalRequestContent) MarshalJSON() ([]byte, error)

func (*ToolApprovalRequestContent) UnmarshalJSON

func (t *ToolApprovalRequestContent) UnmarshalJSON(data []byte) error

type ToolApprovalResponseContent

type ToolApprovalResponseContent struct {
	ContentHeader

	RequestID string
	Reason    string `json:",omitempty"`
	Approved  bool
	ToolCall  ToolCallContent
}

ToolApprovalResponseContent represents a response to a ToolApprovalRequestContent.

func (*ToolApprovalResponseContent) MarshalJSON

func (t *ToolApprovalResponseContent) MarshalJSON() ([]byte, error)

func (*ToolApprovalResponseContent) UnmarshalJSON

func (t *ToolApprovalResponseContent) UnmarshalJSON(data []byte) error

type ToolCallContent

type ToolCallContent interface {
	Content

	GetCallID() string
}

ToolCallContent represents content that requests a tool call.

type URIContent

type URIContent struct {
	ContentHeader

	MediaType string
	URI       string
}

URIContent represents a URL, typically to hosted content such as an image, audio, or video.

func NewURIContent

func NewURIContent(uri string, mediaType string) (*URIContent, error)

NewURIContent creates a URIContent for the given URI. When mediaType is empty it is inferred from the URI; a non-empty mediaType is validated. It returns an error if the URI is invalid or the media type is malformed.

func (*URIContent) MarshalJSON

func (t *URIContent) MarshalJSON() ([]byte, error)

func (*URIContent) TopLevelMediaType

func (t *URIContent) TopLevelMediaType() string

TopLevelMediaType returns the normalized (lowercased, whitespace-trimmed) top-level part of the content's MediaType - the portion before the / (for example image for image/png). If MediaType contains no /, the whole normalized value is returned; if MediaType is unset, it returns an empty string.

type UsageContent

type UsageContent struct {
	ContentHeader

	Details UsageDetails
}

UsageContent represents usage information associated with a chat request and response.

func (*UsageContent) MarshalJSON

func (t *UsageContent) MarshalJSON() ([]byte, error)

type UsageDetails

type UsageDetails struct {
	AdditionalCounts      map[string]int64
	InputTokenCount       int64
	OutputTokenCount      int64
	TotalTokenCount       int64
	CachedInputTokenCount int64
	ReasoningTokenCount   int64
}

UsageDetails provides usage details about a request/response.

func (*UsageDetails) Add

func (u *UsageDetails) Add(other UsageDetails)

Add accumulates other into u, summing each token count field and merging AdditionalCounts (allocating the map on first use).

Directories

Path Synopsis
Package messagefilter provides composable filters over slices of messages, used to select which messages a context provider stores or forwards.
Package messagefilter provides composable filters over slices of messages, used to select which messages a context provider stores or forwards.
Package messageworkflow provides helpers for workflow executors that buffer incoming messages and act when a turn token arrives, used by the agent-hosting and group-chat executors in workflow/agentworkflow.
Package messageworkflow provides helpers for workflow executors that buffer incoming messages and act when a turn token arrives, used by the agent-hosting and group-chat executors in workflow/agentworkflow.

Jump to

Keyboard shortcuts

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