conversation

package
v0.0.0-beta Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package conversation manages message history and emits events for LLM interactions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

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

Builder manages conversation history and emits UI events.

Message lifecycle:

StartAssistant() → creates current message, emits MessageStarted
AppendContent/AppendThinking → appends to current, emits MessagePartAdded/Updated
AddToolCall/StartToolCall/CompleteToolCall → manages tool call parts
FinalizeAssistant() → commits current to history, emits MessageFinalized

current is nil between messages. Methods that require current log a warning and return if called outside the Start/Finalize lifecycle.

func NewBuilder

func NewBuilder(sink EventSink, systemPrompt string, systemTokens int, estimate func(context.Context, string) int) *Builder

NewBuilder creates a new conversation builder with the given event sink, system prompt, pre-computed system token count, and estimate function.

func (*Builder) AddAssistantMessage

func (b *Builder) AddAssistantMessage(msg message.Message)

AddAssistantMessage adds a complete assistant message to the API history. This should be called after receiving a response from the provider.

func (*Builder) AddBookmark

func (b *Builder) AddBookmark(label string)

AddBookmark adds a structural bookmark divider to the history and emits MessageAdded. Bookmarks are rendered as separators in the UI, persisted, but never sent to any LLM.

func (*Builder) AddDisplayMessage

func (b *Builder) AddDisplayMessage(ctx context.Context, role roles.Role, content string)

AddDisplayMessage adds a display-only message to the history and emits MessageAdded. Display-only messages are visible in the UI and persisted but never sent to any LLM.

func (*Builder) AddEphemeralToolResult

func (b *Builder) AddEphemeralToolResult(ctx context.Context, toolName, toolCallID, result string, estimatedTokens int)

AddEphemeralToolResult adds a tool result that will be pruned after one model turn. Used for pre-execution errors (tool not found, policy deny, parse failures, etc.) that the model needs to see once but shouldn't persist in history. When estimatedTokens > 0, it is used directly (avoids re-estimation).

func (*Builder) AddMetadata

func (b *Builder) AddMetadata(data map[string]any)

AddMetadata adds a structured metadata message to the history. Metadata is not rendered in the UI and never sent to any LLM, but persists in sessions and is included in structured exports (JSON/JSONL).

func (*Builder) AddToolCall

func (b *Builder) AddToolCall(id, name string, args map[string]any)

AddToolCall adds a pending tool call to the current message with pre-formatted args.

func (*Builder) AddToolResult

func (b *Builder) AddToolResult(ctx context.Context, toolName, toolCallID, result string, estimatedTokens int)

AddToolResult adds a tool execution result to the API history. When estimatedTokens > 0, it is used directly (avoids re-estimation).

func (*Builder) AddUserMessage

func (b *Builder) AddUserMessage(ctx context.Context, text string, estimatedTokens int)

AddUserMessage adds a completed user message and emits MessageAdded. When estimatedTokens > 0, it is used directly (avoids re-estimation of already-estimated text).

func (*Builder) AddUserMessageWithImages

func (b *Builder) AddUserMessageWithImages(ctx context.Context, text string, images message.Images, estimatedTokens int)

AddUserMessageWithImages adds a completed user message with images and emits MessageAdded. Images flow through to providers via their convert layers (Ollama: raw bytes, OpenRouter/LlamaCPP: base64 data URLs). When estimatedTokens > 0, it is used directly (avoids re-estimation).

func (*Builder) AppendContent

func (b *Builder) AppendContent(content string)

AppendContent appends content text to the current assistant message. Merges with the last content part if present, otherwise creates a new part.

func (*Builder) AppendThinking

func (b *Builder) AppendThinking(thinking string)

AppendThinking appends thinking text to the current assistant message.

func (*Builder) BackfillToolTokens

func (b *Builder) BackfillToolTokens(delta int)

BackfillToolTokens distributes an API-reported token delta across tool result messages added since the last assistant message. Walks backward from the end. Single tool result (common case) gets the full delta; multiple distribute proportionally by content length.

func (*Builder) Clear

func (b *Builder) Clear()

Clear removes all messages except the system prompt from the history.

func (*Builder) CompleteToolCall

func (b *Builder) CompleteToolCall(ctx context.Context, id, result string, err error)

CompleteToolCall marks a tool call as complete with its result, matching by ID.

func (*Builder) DeduplicateSystemMessages

func (b *Builder) DeduplicateSystemMessages()

DeduplicateSystemMessages keeps only the first system message, removing duplicates.

func (*Builder) DropN

func (b *Builder) DropN(n int)

DropN removes the last n messages from the history.

func (*Builder) EjectEphemeralMessages

func (b *Builder) EjectEphemeralMessages()

EjectEphemeralMessages removes ephemeral tool results and their matching calls from history. Ephemeral messages influence one turn, then get stripped along with their paired calls.

func (*Builder) EjectSyntheticMessages

func (b *Builder) EjectSyntheticMessages()

EjectSyntheticMessages removes all synthetic messages from history. Used when eject is enabled — synthetics influence one turn, then get stripped.

func (*Builder) Estimate

func (b *Builder) Estimate(ctx context.Context, text string) int

Estimate returns the token count for text using the configured estimator.

func (*Builder) FinalizeAssistant

func (b *Builder) FinalizeAssistant()

FinalizeAssistant completes the current assistant message and emits MessageFinalized.

func (*Builder) History

func (b *Builder) History() message.Messages

History returns the message history for API calls.

func (*Builder) InjectMessage

func (b *Builder) InjectMessage(ctx context.Context, role roles.Role, content string)

InjectMessage adds a synthetic message to the API history. The assistant emits a SyntheticInjected event for UI display separately.

func (*Builder) Len

func (b *Builder) Len() int

Len returns the number of messages in the history.

func (*Builder) NextID

func (b *Builder) NextID() string

NextID generates a unique message ID.

func (*Builder) PruneEmptyAssistantMessages

func (b *Builder) PruneEmptyAssistantMessages()

PruneEmptyAssistantMessages removes assistant messages with no content, thinking, or tool calls.

func (*Builder) PruneToolResults

func (b *Builder) PruneToolResults(protectTokens, argThreshold int, estimate func(string) int)

PruneToolResults prunes old tool results in the history in-place. Takes an explicit local estimate function (not the stored context-aware callback) because pruning is high-frequency and should always use local estimation.

func (*Builder) RebuildAfterCompaction

func (b *Builder) RebuildAfterCompaction(summary string, summaryTokens int, preserved message.Messages)

RebuildAfterCompaction replaces conversation history with a compaction summary and preserved recent message. The system prompt (index 0) is kept in place. summaryTokens is the pre-computed token estimate for the compaction summary.

func (*Builder) Restore

func (b *Builder) Restore(msgs message.Messages)

Restore replaces the conversation history with the given message. The first message in msgs should be the system prompt.

func (*Builder) SetError

func (b *Builder) SetError(err error)

SetError sets an error on the current assistant message.

func (*Builder) StartAssistant

func (b *Builder) StartAssistant()

StartAssistant begins a new assistant message and emits MessageStarted.

func (*Builder) StartToolCall

func (b *Builder) StartToolCall(id string)

StartToolCall transitions a Pending tool call to Running and emits MessagePartUpdated.

func (*Builder) SystemPrompt

func (b *Builder) SystemPrompt() string

SystemPrompt returns the assembled system prompt sent to the model.

func (*Builder) TrimDuplicateSynthetics

func (b *Builder) TrimDuplicateSynthetics()

TrimDuplicateSynthetics removes duplicate synthetic messages from history, keeping only the most recent occurrence of each.

func (*Builder) Turns

func (b *Builder) Turns() []sdk.Turn

Turns returns conversation turns as sdk.Turn slices. Includes only normal user/assistant text messages — excludes system, tool, synthetic, and ephemeral message.

func (*Builder) UpdateSystemPrompt

func (b *Builder) UpdateSystemPrompt(ctx context.Context, prompt string)

UpdateSystemPrompt updates the system prompt without clearing conversation history. This is used when switching modes — the conversation context is preserved. If the system prompt is missing (e.g., after clear on empty history), it is prepended.

func (*Builder) UpdateThinking

func (b *Builder) UpdateThinking(index int, thinking string)

UpdateThinking replaces the thinking content on the message at the given history index. Used by thinking management to mutate the builder in place (strip or rewrite).

type EventSink

type EventSink func(event ui.Event)

EventSink is a function that receives conversation events. Nil is safe — emit() guards all calls.

Jump to

Keyboard shortcuts

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