msg

package
v0.97.8 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: GPL-3.0 Imports: 6 Imported by: 0

Documentation

Overview

Package msg defines shared agent domain types used across subpackages.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMaxSteps        = errors.New("agent: max steps exceeded")
	ErrAborted         = errors.New("agent: aborted")
	ErrToolNotFound    = errors.New("agent: tool not found")
	ErrEmptyContext    = errors.New("agent: empty context")
	ErrInvalidContinue = errors.New("agent: cannot continue from assistant message")
)

Functions

func AssistantDisplayText

func AssistantDisplayText(m AssistantMessage) string

AssistantDisplayText renders user-visible assistant content from a message.

func CoalesceAssistantHistoryMessages

func CoalesceAssistantHistoryMessages(texts []string) []string

CoalesceAssistantHistoryMessages merges consecutive assistant tool-call snapshots, keeping the richest display text for each run.

func IsAssistantToolSummary

func IsAssistantToolSummary(text string) bool

IsAssistantToolSummary reports whether text is a compact tool-call display line.

func IsToolCallOnlyContent added in v0.95.0

func IsToolCallOnlyContent(text string) bool

IsToolCallOnlyContent reports whether text is exclusively tool-call JSON with no preceding user-visible assistant text.

func IsToolCallPayload

func IsToolCallPayload(text string) bool

IsToolCallPayload reports whether text is a serialized tool invocation payload.

func IsToolCallStreamDelta added in v0.95.0

func IsToolCallStreamDelta(delta string) bool

IsToolCallStreamDelta reports whether one streaming chunk carries tool-call JSON emitted by langchaingo instead of user-visible assistant text.

func SanitizeAssistantDisplayText

func SanitizeAssistantDisplayText(text string) string

SanitizeAssistantDisplayText returns user-visible assistant text, collapsing raw tool-call JSON into a one-line summary.

func SummarizeToolCallParts

func SummarizeToolCallParts(calls []ToolCallPart) string

SummarizeToolCallParts renders structured tool calls as a one-line summary.

func SummarizeToolCallPayload

func SummarizeToolCallPayload(text string) string

SummarizeToolCallPayload renders tool-call JSON as a compact one-line summary.

func TrimToolCallStreamContent added in v0.95.0

func TrimToolCallStreamContent(text string) string

TrimToolCallStreamContent removes langchaingo tool-call JSON from assistant text, keeping any preceding user-visible content.

Types

type AfterToolCallFn

type AfterToolCallFn func(ctx AfterToolContext) (*AfterToolResult, error)

AfterToolCallFn runs after a tool executes and may patch its result.

type AfterToolContext

type AfterToolContext struct {
	Assistant AssistantMessage
	ToolCall  ToolCallPart
	Args      map[string]any
	Result    ToolResultMessage
	Context   *Context
}

AfterToolContext is passed to after-tool hooks.

type AfterToolResult

type AfterToolResult struct {
	Parts     []ContentPart
	IsError   *bool
	Terminate bool
}

AfterToolResult can patch a tool result or request early termination.

type AgentMessage

type AgentMessage interface {
	Role() MessageRole
}

AgentMessage is the domain message type used throughout the agent loop.

type AssistantMessage

type AssistantMessage struct {
	Parts      []ContentPart
	Model      string
	StopReason string
	Usage      *Usage
	Timestamp  time.Time
	// TurnDurationMs is elapsed milliseconds for the full agent turn (LLM + tools).
	TurnDurationMs int64
	// ThinkingDurationMs is elapsed milliseconds for the reasoning stream phase.
	ThinkingDurationMs int64
	// ThinkingText is accumulated reasoning output for UI replay after refresh.
	ThinkingText string
	// RunDurationMs is total run milliseconds; set on the final assistant message of a run.
	RunDurationMs int64
}

AssistantMessage is a model turn with optional text and tool calls.

func (AssistantMessage) Role

Role returns RoleAssistant.

func (AssistantMessage) TextContent

func (m AssistantMessage) TextContent() string

TextContent concatenates text parts for convenience.

func (AssistantMessage) ToolCalls

func (m AssistantMessage) ToolCalls() []ToolCallPart

ToolCalls extracts tool call parts from the assistant message.

type BeforeToolCallFn

type BeforeToolCallFn func(ctx BeforeToolContext) (*BeforeToolResult, error)

BeforeToolCallFn runs before a tool executes and may block it.

type BeforeToolContext

type BeforeToolContext struct {
	Assistant AssistantMessage
	ToolCall  ToolCallPart
	Args      map[string]any
	Context   *Context
}

BeforeToolContext is passed to before-tool hooks.

type BeforeToolResult

type BeforeToolResult struct {
	Block  bool
	Reason string
}

BeforeToolResult can block a tool call before execution.

type BranchSummaryMessage

type BranchSummaryMessage struct {
	Summary   string
	FromID    string
	Timestamp time.Time
}

BranchSummaryMessage injects branch context after tree navigation.

func (BranchSummaryMessage) Role

Role returns RoleBranchSummary.

type CompactionSummaryMessage

type CompactionSummaryMessage struct {
	Summary      string
	TokensBefore int
	Timestamp    time.Time
}

CompactionSummaryMessage injects compacted history context.

func (CompactionSummaryMessage) Role

Role returns RoleCompactionSummary.

type Config

type Config struct {
	MaxSteps            int
	ToolExecution       ToolExecutionMode
	ModelName           string
	ChatModel           string
	ToolModel           string
	Temperature         float64
	MaxTokens           int
	TransformContext    TransformContextFn
	ConvertToLLM        ConvertToLLMFn
	PrepareNextTurn     PrepareNextTurnFn
	ShouldStopAfterTurn ShouldStopAfterTurnFn
	BeforeToolCall      BeforeToolCallFn
	AfterToolCall       AfterToolCallFn
	GetSteeringMessages GetMessagesFn
	GetFollowUpMessages GetMessagesFn
	SteeringMode        QueueMode
	FollowUpMode        QueueMode
	// LLMRetryMaxAttempts overrides default LLM retries when > 0.
	LLMRetryMaxAttempts int
	// LLMRetryInitialInterval overrides the first retry delay when > 0.
	LLMRetryInitialInterval time.Duration
	// LLMRetryMaxInterval caps the delay between retries when > 0.
	LLMRetryMaxInterval time.Duration
	// LLMRetryMultiplier controls delay growth when > 0.
	LLMRetryMultiplier float64
}

Config holds runtime options for an agent loop invocation.

func (Config) WithDefaults

func (c Config) WithDefaults() Config

WithDefaults fills zero values with package defaults.

type ContentPart

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

ContentPart is a union of message part types.

type Context

type Context struct {
	SystemPrompt string
	Messages     []AgentMessage
	ModelName    string
}

Context holds the mutable state passed through the agent loop.

type ConvertToLLMFn

type ConvertToLLMFn func(messages []AgentMessage) ([]llms.MessageContent, error)

ConvertToLLMFn converts agent messages to langchaingo message content.

type CustomMessage

type CustomMessage struct {
	CustomType         string
	Parts              []ContentPart
	DisplayOnly        bool
	ExcludeFromContext bool
	Timestamp          time.Time
}

CustomMessage is an application-specific message rendered before LLM calls.

func (CustomMessage) Role

func (CustomMessage) Role() MessageRole

Role returns RoleCustom.

type GetMessagesFn

type GetMessagesFn func() ([]AgentMessage, error)

GetMessagesFn drains steering or follow-up queues at loop checkpoints.

type ImagePart

type ImagePart struct {
	MIMEType string
	Data     []byte
	URL      string
}

ImagePart holds image content for multimodal messages.

type MessageRole

type MessageRole string

MessageRole identifies the role of an agent message in the session tree.

const (
	RoleUser              MessageRole = "user"
	RoleAssistant         MessageRole = "assistant"
	RoleToolResult        MessageRole = "toolResult"
	RoleCustom            MessageRole = "custom"
	RoleBranchSummary     MessageRole = "branchSummary"
	RoleCompactionSummary MessageRole = "compactionSummary"
)

type PrepareNextTurnFn

type PrepareNextTurnFn func(ctx TurnContext) (*TurnUpdate, error)

PrepareNextTurnFn refreshes state at turn boundaries.

type QueueMode

type QueueMode string

QueueMode controls how queued steering/follow-up messages drain.

const (
	QueueAll QueueMode = "all"
	QueueOne QueueMode = "one-at-a-time"
)

type ShouldStopAfterTurnFn

type ShouldStopAfterTurnFn func(ctx TurnContext) (bool, error)

ShouldStopAfterTurnFn allows callers to end the loop after a completed turn.

type StopReason

type StopReason string

StopReason describes why an assistant turn ended.

const (
	StopReasonComplete StopReason = "complete"
	StopReasonError    StopReason = "error"
	StopReasonAborted  StopReason = "aborted"
)

type TextPart

type TextPart struct {
	Text string
}

TextPart holds plain text content in a multi-part message.

type ToolCallPart

type ToolCallPart struct {
	ID        string
	Name      string
	Arguments string
}

ToolCallPart is a tool invocation requested by the assistant.

type ToolExecutionMode

type ToolExecutionMode string

ToolExecutionMode controls how multiple tool calls from one assistant turn run.

const (
	ToolExecutionParallel   ToolExecutionMode = "parallel"
	ToolExecutionSequential ToolExecutionMode = "sequential"
)

type ToolResultMessage

type ToolResultMessage struct {
	ToolCallID string
	Name       string
	Parts      []ContentPart
	IsError    bool
	Timestamp  time.Time
	// DurationMs is elapsed milliseconds for tool execution.
	DurationMs int64
}

ToolResultMessage carries the result of executing a tool call.

func (ToolResultMessage) Role

Role returns RoleToolResult.

type TransformContextFn

type TransformContextFn func(messages []AgentMessage) ([]AgentMessage, error)

TransformContextFn prunes or enriches messages before LLM conversion.

type TurnContext

type TurnContext struct {
	Message     AssistantMessage
	ToolResults []ToolResultMessage
	Context     *Context
	NewMessages []AgentMessage
}

TurnContext is passed to turn-boundary hooks after each assistant response.

type TurnUpdate

type TurnUpdate struct {
	Context   *Context
	ModelName string
}

TurnUpdate replaces runtime state before the next provider request.

type Usage

type Usage struct {
	PromptTokens     int
	CompletionTokens int
	TotalTokens      int
	CacheRead        int
	CacheWrite       int
}

Usage captures token consumption reported by the LLM provider.

type UserMessage

type UserMessage struct {
	Parts     []ContentPart
	Timestamp time.Time
}

UserMessage is a user turn, optionally multimodal.

func (UserMessage) Role

func (UserMessage) Role() MessageRole

Role returns RoleUser.

Jump to

Keyboard shortcuts

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