Documentation
¶
Overview ¶
Package dive provides a Go library for building AI agents and integrating with leading LLMs. It takes a library-first approach, providing a clean API for embedding AI capabilities into Go applications.
The core types are:
- Agent orchestrates LLM interactions with tool execution and conversation management.
- Tool and TypedTool define callable tools that an LLM can invoke.
- Response captures the output from an agent's response generation.
- Hooks groups hook slices for customizing agent behavior at key points. Hook types: PreGenerationHook, PostGenerationHook, PreToolUseHook, PostToolUseHook, PostToolUseFailureHook, StopHook, PreIterationHook.
Quick Start ¶
agent, _ := dive.NewAgent(dive.AgentOptions{
Name: "Assistant",
SystemPrompt: "You are a helpful assistant.",
Model: anthropic.New(),
})
response, _ := agent.CreateResponse(ctx, dive.WithInput("Hello!"))
fmt.Println(response.OutputText())
Built-in tools are available in the github.com/deepnoodle-ai/dive/toolkit package. LLM providers are in the github.com/deepnoodle-ai/dive/providers subpackages.
Index ¶
- Constants
- Variables
- func AbortGeneration(reason string) error
- func AbortGenerationWithCause(reason string, cause error) error
- func AwaitBackgroundTasks(ctx context.Context, tasks []*BackgroundTaskHandle) (map[string]*ToolResult, error)
- func CloseTurn(turn []*llm.Message, outcome *TurnOutcome) []*llm.Message
- func DateTimeString(t time.Time) string
- func DecodePendingInput[T any](p *PendingToolCall) (T, error)
- func HasSystemReminder(messages []*llm.Message, name string) bool
- func IsUserFeedback(err error) (string, bool)
- func LockSession(ctx context.Context, id string) (lockedCtx context.Context, unlock func(), err error)
- func NewReminderMessage(r Reminder) *llm.Message
- func NewUserFeedback(feedback string) error
- func Ptr[T any](t T) *T
- func RemoveReminder(messages []*llm.Message, name string) []*llm.Message
- func RemoveSystemReminder(messages []*llm.Message, name string) []*llm.Message
- func ReportProgress(ctx context.Context, progress *ToolProgress)
- func SetSystemReminder(messages []*llm.Message, name, content string) []*llm.Message
- func SoftCanceled(ctx context.Context) bool
- func StreamOutput(ctx context.Context, text string)
- func StripReminders(messages []*llm.Message) []*llm.Message
- func ToolCallID(ctx context.Context) string
- func TurnID(ctx context.Context) string
- func WithSoftCancel(parent context.Context) (ctx context.Context, cancel func())
- func WithToolCallID(ctx context.Context, id string) context.Context
- func WithToolProgressFunc(ctx context.Context, fn func(toolCallID string, progress *ToolProgress)) context.Context
- func WithToolStreamFunc(ctx context.Context, fn func(toolCallID string, text string)) context.Context
- func WithTurnID(ctx context.Context, id string) context.Context
- type Agent
- func (a *Agent) CancelSuspendedTurn(ctx context.Context, opts ...CreateResponseOption) (*Response, error)
- func (a *Agent) CreateResponse(ctx context.Context, opts ...CreateResponseOption) (response *Response, err error)
- func (a *Agent) Description() string
- func (a *Agent) HasTools() bool
- func (a *Agent) ID() string
- func (a *Agent) Model() llm.LLM
- func (a *Agent) Name() string
- func (a *Agent) SetModel(model llm.LLM)
- func (a *Agent) SetSystemPrompt(prompt string)
- func (a *Agent) SystemPrompt() string
- func (a *Agent) Tools() []Tool
- func (a *Agent) Version() string
- type AgentOptions
- type AgentRunInfo
- type AgentRunSpan
- type AutoApproveDialog
- type BackgroundTaskHandle
- type ChatInfo
- type ChatSpan
- type CompletedToolCall
- type CreateResponseOption
- func WithBackgroundResults(handles []*BackgroundTaskHandle, results map[string]*ToolResult) CreateResponseOption
- func WithContinue() CreateResponseOption
- func WithEventCallback(callback EventCallback) CreateResponseOption
- func WithInput(input string) CreateResponseOption
- func WithMessages(messages ...*llm.Message) CreateResponseOption
- func WithModelOnlyReminder(reminder Reminder) CreateResponseOption
- func WithPromptCacheKey(key string) CreateResponseOption
- func WithResume(state *SuspensionState, results map[string]*ToolResult) CreateResponseOption
- func WithResumeRequest(req ResumeRequest) CreateResponseOption
- func WithSession(s Session) CreateResponseOption
- func WithToolResults(results map[string]*ToolResult) CreateResponseOption
- func WithValue(key string, value any) CreateResponseOption
- type CreateResponseOptions
- type DenyAllDialog
- type Dialog
- type DialogInput
- type DialogOption
- type DialogOutput
- type DurabilityOptions
- type EventCallback
- type Extension
- type FuncToolOption
- type GenerationError
- type HookAbortError
- type HookContext
- type Hooks
- type IncompleteTurnDecision
- type IncompleteTurnHook
- type IncompleteTurnOptions
- type JudgmentDecision
- type ModelSettings
- type NopTracer
- type OnSuspendHook
- type PendingToolCall
- type PersistenceState
- type PostBackgroundToolUseHook
- type PostGenerationHook
- type PostToolUseFailureHook
- type PostToolUseHook
- type PreGenerationHook
- type PreIterationHook
- type PreToolUseHook
- type Reminder
- func FindLatestReminder(messages []*llm.Message, name string) (Reminder, bool)
- func FindReminder(message *llm.Message, name string) (Reminder, bool)
- func NewContextReminder(name, content string) (Reminder, error)
- func NewOperatorReminder(name, content string) (Reminder, error)
- func NewTurnOutcomeReminder(outcome *TurnOutcome) Reminder
- func ParseLegacyReminderText(text string) (Reminder, bool)
- type ReminderRecording
- type ReminderTier
- type Response
- type ResponseItem
- type ResponseItemType
- type ResponseStatus
- type ResumeRequest
- type Schema
- type SchemaProperty
- type SchemaType
- type Session
- type SessionClaimer
- type SessionSnapshot
- type SessionStartHook
- type SessionStartResult
- type SessionStartSource
- type StopDecision
- type StopHook
- type SuspendReason
- type SuspendResult
- type SuspendableSession
- type SuspensionState
- type TerminalDialog
- type TerminalDialogOptions
- type Tool
- type ToolAnnotations
- type ToolCallInfo
- type ToolCallPreview
- type ToolCallRecord
- type ToolCallResult
- type ToolCallSpan
- type ToolCallState
- type ToolDeclarer
- type ToolPreviewer
- type ToolProgress
- type ToolProgressEvent
- type ToolResult
- func NewBackgroundResult(ctx context.Context, description string, ...) *ToolResult
- func NewBackgroundResultFull(ctx context.Context, description string, ...) *ToolResult
- func NewSuspendResult(prompt string, metadata map[string]any) *ToolResult
- func NewSuspendResultWithReason(prompt string, reason SuspendReason, metadata map[string]any) *ToolResult
- func NewToolResult(content ...*ToolResultContent) *ToolResult
- func NewToolResultError(text string) *ToolResult
- func NewToolResultText(text string) *ToolResult
- type ToolResultContent
- type ToolResultContentType
- type ToolStreamEvent
- type Toolset
- type ToolsetFunc
- type Tracer
- type Turn
- type TurnNext
- type TurnOrigin
- type TurnOriginKind
- type TurnOutcome
- type TurnReason
- type TurnStore
- type TypedTool
- type TypedToolAdapter
- func (t *TypedToolAdapter[T]) Annotations() *ToolAnnotations
- func (t *TypedToolAdapter[T]) Call(ctx context.Context, input any) (*ToolResult, error)
- func (t *TypedToolAdapter[T]) Description() string
- func (t *TypedToolAdapter[T]) Name() string
- func (t *TypedToolAdapter[T]) PreviewCall(ctx context.Context, input any) *ToolCallPreview
- func (t *TypedToolAdapter[T]) Schema() *Schema
- func (t *TypedToolAdapter[T]) ToolConfiguration(providerName string) map[string]any
- func (t *TypedToolAdapter[T]) Unwrap() TypedTool[T]
- type TypedToolPreviewer
- type UnknownToolError
- type UserFeedbackError
Constants ¶
const ( // ToolCallNotRunText answers a tool call the turn ended before it // started. The call had no effect. ToolCallNotRunText = llm.ToolCallNotRunText // ToolCallUnknownText answers a tool call that was running when the turn // ended and had not reported a result. Whether it took effect is unknown. ToolCallUnknownText = llm.ToolCallUnknownText )
const ( ReminderTierContextual = llm.ReminderTierContextual ReminderTierOperator = llm.ReminderTierOperator )
const ReminderNameTurnContinue = "turn-continue"
ReminderNameTurnContinue is the name of the reminder WithContinue adds, saying the user asked to continue.
const ReminderNameTurnIncomplete = "turn-incomplete"
ReminderNameTurnIncomplete is the name of the reminder that closes an incomplete turn. Its Details hold the TurnOutcome (see FindTurnOutcome).
const (
// StateKeyCompactionEvent stores the compaction event for post-generation hooks.
StateKeyCompactionEvent = "compaction_event"
)
Well-known keys for HookContext.Values used by experimental packages. Using these constants instead of raw strings prevents typos and makes cross-package dependencies explicit.
const TurnSchema = 1
TurnSchema is the Turn.Schema of the records this version of Dive writes.
Variables ¶
var ( ErrLLMNoResponse = errors.New("llm did not return a response") ErrNoLLM = errors.New("no llm provided") // ErrReentrantSession is returned when CreateResponse is invoked on a // session whose lock is already held by the calling context — i.e. a // tool, hook, or subagent reachable from an in-flight CreateResponse // called back into the same session ID. Without this check the nested // call would deadlock waiting on a lock its own caller holds. Use a // separate session for nested agent calls. ErrReentrantSession = errors.New("dive: reentrant CreateResponse on a session whose turn is already in progress") // ErrBatchHalted is the ToolCallResult.Error of a call the agent did not // run because an earlier call in the same model response failed (see // ToolAnnotations.HaltsBatch). No PreToolUse, PostToolUse or // PostToolUseFailure hook fires for such a call, but its tool_call and // tool_call_result events are still emitted. ErrBatchHalted = errors.New("dive: not executed because an earlier call in the batch failed") // ErrToolCallNotRun is the ToolCallResult.Error of a call the turn ended // before it started. Its result text is ToolCallNotRunText. ErrToolCallNotRun = errors.New("dive: not run because the turn ended") // ErrToolCallUnknown is the ToolCallResult.Error of a call that was // running when the turn ended and had not reported. Its result text is // ToolCallUnknownText. ErrToolCallUnknown = errors.New("dive: result unknown because the turn ended") )
var ErrConflictingToolResult = errors.New("dive: a different result was already accepted for this tool call")
ErrConflictingToolResult is returned when a resume supplies a result for a call that already has a different one. It also matches ErrUnknownPendingToolCall, since the call is not pending.
var ErrContinueWithInput = errors.New("dive: WithContinue takes no new input and cannot resume a suspended turn")
ErrContinueWithInput is returned when WithContinue is combined with new input on a session, or with a resume.
var ErrInputOnSuspendedSession = errors.New("dive: session is suspended; resume the current turn before supplying new input")
ErrInputOnSuspendedSession is returned when CreateResponse is called with new user input on a session-backed suspended session. Resume the turn first (via WithResume / WithToolResults); new input belongs in a fresh turn after the suspended one resolves.
var ErrNoSuspendedTurn = errors.New("dive: no suspended turn to resume")
ErrNoSuspendedTurn is returned from CreateResponse when WithResume or WithToolResults is supplied but there is no suspended turn to resume (neither the session nor the options carry one).
var ErrResumeRequired = errors.New("dive: session is suspended; pass WithResume or WithToolResults to continue the turn")
ErrResumeRequired is returned when CreateResponse is called on a suspended session without any explicit opt-in (no WithResume, no WithToolResults, no new input). Resume is explicit — the agent does not silently re-save an idle suspended turn.
var ErrRevisionConflict error = &revisionConflictError{}
ErrRevisionConflict is wrapped by the error of a TurnStore checkpoint, or of a ResumeRequest, whose expected revision or turn is no longer the stored one: the session changed since the caller read it. Reload and retry. A checkpoint refused with it wrote nothing: errors.Is(err, ErrSaveRejected) holds.
var ErrSaveRejected = errors.New("dive: session rejected the write before writing")
ErrSaveRejected is wrapped by a Session's write error when the session refused the write before writing anything, as session.Session does for a write its state does not allow. The agent then reports PersistenceFailed; any other error is PersistenceUnknown, since the write may have landed.
var ErrSessionClaimed error = &sessionClaimedError{}
ErrSessionClaimed is wrapped by the error of SessionClaimer.ClaimSession when another owner holds the session, and of a checkpoint refused because the session is now another owner's. A checkpoint refused with it wrote nothing: errors.Is(err, ErrSaveRejected) holds.
var ErrSessionNotSuspended = errors.New("dive: WithResume supplied but the attached session has no suspended turn to resume")
ErrSessionNotSuspended is returned when WithResume supplies an explicit SuspensionState but the attached SuspendableSession is not currently suspended. The completed resume would be persisted via SaveResumedTurn, which fails on a non-suspended session — so the mismatch is detected before generation rather than after tokens have been spent.
var ErrStopContinueWithoutInput = errors.New("dive: stop hook continued with no reason and no appended Recorded reminder")
ErrStopContinueWithoutInput fails a turn whose Stop hook asked to continue with an empty Reason and appended no Recorded reminder.
var ErrUnknownPendingToolCall = errors.New("dive: unknown pending tool call id")
ErrUnknownPendingToolCall is returned when a resume call supplies tool results for an ID that is not in the pending set.
var ErrUnreconciledToolCalls = errors.New("dive: the last turn has tool calls with unknown results; continue it before giving new input")
ErrUnreconciledToolCalls is returned when new input is given on a session whose last turn stopped with a call whose result is unknown (TurnOutcome.Next is TurnNextReconcile), and IncompleteTurnOptions.RequireReconcile is set. Continue the turn (WithContinue) or remove it first. A compaction does not clear it; a continuation does.
var NewSchema = schema.NewSchema
NewSchema creates a new Schema with the given properties and required fields.
Functions ¶
func AbortGeneration ¶ added in v1.0.0
AbortGeneration creates a HookAbortError to abort generation. Use this in hooks when a critical failure occurs that should stop generation entirely.
func AbortGenerationWithCause ¶ added in v1.0.0
AbortGenerationWithCause creates a HookAbortError with an underlying cause.
func AwaitBackgroundTasks ¶ added in v1.5.0
func AwaitBackgroundTasks(ctx context.Context, tasks []*BackgroundTaskHandle) (map[string]*ToolResult, error)
AwaitBackgroundTasks blocks until all tasks deliver results or ctx is cancelled, then returns a map of task ID → *ToolResult. On cancellation it returns partial results plus ctx.Err(). Background goroutines continue running after cancellation; their results remain readable on each handle's Done channel.
func CloseTurn ¶ added in v1.34.0
func CloseTurn(turn []*llm.Message, outcome *TurnOutcome) []*llm.Message
CloseTurn returns turn with every client tool call that has no result answered, and the outcome recorded at the end as the turn-incomplete reminder, so the turn can be sent to a provider again. A call the outcome lists as unknown is answered with ToolCallUnknownText; any other unanswered call with ToolCallNotRunText, and the recorded outcome's ToolCalls gains a not_started record for it. The recorded outcome is read back with FindTurnOutcome. CloseTurn modifies neither turn nor outcome.
The agent closes every incomplete turn this way before saving it; an application that keeps turns itself can apply it to messages it holds.
func DateTimeString ¶ added in v1.0.0
DateTimeString returns a human-readable string describing the given time, including the date, time of day, and day of the week.
func DecodePendingInput ¶ added in v1.5.0
func DecodePendingInput[T any](p *PendingToolCall) (T, error)
DecodePendingInput decodes the pending call's Input JSON into a value of type T. Generic wrapper around PendingToolCall.UnmarshalInput for call sites that prefer a return value over an out-parameter.
func HasSystemReminder ¶ added in v1.5.0
HasSystemReminder returns true if a named <system-reminder> block exists in the first user message.
func IsUserFeedback ¶ added in v1.0.0
IsUserFeedback checks if an error is user feedback and returns the feedback text. Returns the feedback string and true if it's user feedback, empty string and false otherwise.
func LockSession ¶ added in v1.34.0
func LockSession(ctx context.Context, id string) (lockedCtx context.Context, unlock func(), err error)
LockSession takes the per-session lock that CreateResponse holds for the whole of a run on a session with this ID. A caller that changes a session outside the agent (CancelSuspension, a rewind, an import) takes it so the change is ordered with any run on that session: it waits for a run in progress to finish, including that run's final session write.
The returned context marks the lock as held; a CreateResponse on the same session made with it fails with ErrReentrantSession instead of deadlocking. unlock releases the lock; calls after the first do nothing. LockSession returns ErrReentrantSession when ctx already holds the lock, and ctx.Err() when ctx ends while waiting. The lock is per process: it does not order runs in different processes.
func NewReminderMessage ¶ added in v1.14.0
NewReminderMessage builds a recorded input message for an appended reminder. Operator reminders use the system role internally; providers normalize that role according to their known capabilities, falling back to a tagged user message where native operator authority is unavailable.
func NewUserFeedback ¶ added in v1.0.0
NewUserFeedback creates a UserFeedbackError with the given feedback.
func Ptr ¶ added in v1.0.0
func Ptr[T any](t T) *T
Ptr returns a pointer to the given value. This is useful for setting optional pointer fields in structs like ModelSettings.
func RemoveReminder ¶ added in v1.14.0
RemoveReminder removes typed reminders with name using copy-on-write.
func RemoveSystemReminder ¶ added in v1.5.0
RemoveSystemReminder removes a named <system-reminder> block from the first user message. Returns the messages unchanged if the block is not found.
func ReportProgress ¶ added in v1.6.0
func ReportProgress(ctx context.Context, progress *ToolProgress)
ReportProgress delivers a structured progress snapshot from a running tool. Tools call this whenever they have a typed progress update worth surfacing to UIs or evaluators — e.g. on each stdout chunk, after each scanned file, or on a periodic percent-complete tick. Each call replaces the previous snapshot; it is not a delta.
Safe to call even if no progress function is configured (it's a no-op) and safe to call any number of times during a single tool execution. Nil snapshots are dropped.
ReportProgress and StreamOutput are independent channels: tools may use one, the other, or both. StreamOutput carries text deltas (append); ReportProgress carries structured ToolProgress snapshots (replace).
func SetSystemReminder ¶ added in v1.5.0
SetSystemReminder inserts or replaces a named <system-reminder> block as a separate text content block in the first user message. Each reminder gets its own content block, keeping user text pristine.
This provides a stable, cache-friendly location for injecting context that persists across generations. Placing reminders in the first user message ensures they sit right after the system prompt in the conversation, forming a stable prefix for prompt caching.
If there is no user message in the conversation, one is created and prepended.
The block format is:
<system-reminder name="skills"> ...content... </system-reminder>
func SoftCanceled ¶ added in v1.34.0
SoftCanceled reports whether ctx carries a soft cancel request that has been made. A long-running tool may check it to wind down early.
func StreamOutput ¶ added in v1.5.0
StreamOutput sends a chunk of streaming output from a tool to the UI. Tools call this during execution to provide real-time feedback. Safe to call even if no stream function is configured (it's a no-op).
func StripReminders ¶ added in v1.14.0
StripReminders removes all typed reminders using copy-on-write. User-authored text that resembles a reminder is preserved.
func ToolCallID ¶ added in v1.5.0
ToolCallID returns the tool call ID from the context, or empty string.
func TurnID ¶ added in v1.34.0
TurnID returns the ID of the turn the context belongs to (Turn.ID), or an empty string. It is stable across the invocations of one turn: a resume, and a continuation of an open turn on a TurnStore, keep it. With ToolCallID it forms a key a tool can hand to a service that supports idempotency keys.
func WithSoftCancel ¶ added in v1.34.0
WithSoftCancel returns a copy of parent that carries a cancel request. Calling cancel asks an agent run using ctx to end at its next step boundary: before its next model call, and before each tool call it has not started. Tool calls already running finish; calls not started are answered with ToolCallNotRunText. The turn ends incomplete with TurnReasonCanceled and an error for which errors.Is(err, context.Canceled) holds, exactly as a hard cancellation does. A second, ordinary context cancellation still stops the run at once.
The request travels with the context, so a subagent started by a tool sees it and stops at its own boundary. Calling cancel more than once has no further effect.
func WithToolCallID ¶ added in v1.5.0
WithToolCallID returns a context with the given tool call ID. This is set by the agent before calling a tool, so tools can associate state with their specific invocation.
func WithToolProgressFunc ¶ added in v1.6.0
func WithToolProgressFunc(ctx context.Context, fn func(toolCallID string, progress *ToolProgress)) context.Context
WithToolProgressFunc returns a context with a structured progress function. This is set by the agent before calling a tool, enabling tools to emit typed progress snapshots (exit code, byte count, parsed progress) in addition to or instead of text-only StreamOutput.
Tools call ReportProgress to deliver a snapshot; the agent re-emits it as a ResponseItem of type ResponseItemTypeToolProgress carrying the ToolProgress.
func WithToolStreamFunc ¶ added in v1.5.0
func WithToolStreamFunc(ctx context.Context, fn func(toolCallID string, text string)) context.Context
WithToolStreamFunc returns a context with a streaming output function. This is set by the agent before calling a tool, enabling tools to stream incremental output to the UI during execution.
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent represents an intelligent AI entity that can autonomously use tools to process information while responding to chat messages.
func NewAgent ¶ added in v0.0.10
func NewAgent(opts AgentOptions) (*Agent, error)
NewAgent returns a new Agent configured with the given options.
func (*Agent) CancelSuspendedTurn ¶ added in v1.34.0
func (a *Agent) CancelSuspendedTurn(ctx context.Context, opts ...CreateResponseOption) (*Response, error)
CancelSuspendedTurn closes a suspended turn without calling the model, so the conversation can move on while keeping what the turn did. The pending calls are answered as unknown, since their requests may be out in the world; the calls that completed keep their results; the turn is incomplete with TurnReasonCanceled, and TurnOutcome.Next is TurnNextReconcile when a pending call is not read-only. The closed turn replaces the suspended one in the session, which is no longer suspended, and the OnIncompleteTurn hooks run as for any incomplete turn. It returns Status == ResponseStatusIncomplete with a nil error, since nothing failed, unless the save fails.
The suspended turn comes from the session, or from WithResume(state, nil) with the pre-turn history in WithMessages for a stateless caller, who appends Response.Turn.Messages to that history. Other options, such as WithSession and WithEventCallback, apply as for CreateResponse; tool results and WithContinue are refused. It returns ErrNoSuspendedTurn when there is no suspended turn.
func (*Agent) CreateResponse ¶
func (*Agent) Description ¶ added in v1.5.0
Description returns the free-form purpose/role description set via AgentOptions.Description, or "" if none was provided.
func (*Agent) ID ¶ added in v1.5.0
ID returns the agent's stable identifier set via AgentOptions.ID, or "" if none was provided.
func (*Agent) SetModel ¶ added in v1.5.0
SetModel replaces the agent's LLM. This allows switching models mid-session. It panics if model is nil; use NewAgent to validate the initial model.
func (*Agent) SetSystemPrompt ¶ added in v1.5.0
SetSystemPrompt replaces the agent's system prompt.
func (*Agent) SystemPrompt ¶ added in v1.5.0
SystemPrompt returns the agent's current system prompt.
type AgentOptions ¶ added in v0.0.10
type AgentOptions struct {
// SystemPrompt is the system prompt sent to the LLM.
SystemPrompt string
// Model is the LLM to use for generation.
Model llm.LLM
// Tools available to the agent (static).
Tools []Tool
// Toolsets provide dynamic tool resolution. Each toolset's Tools() method
// is called before each LLM request, enabling context-dependent tool
// availability. Tools from toolsets are merged with static Tools.
Toolsets []Toolset
// Extensions provide additional tools, hooks, and system prompt rules.
// Extensions are merged in order: tools are appended, hooks are appended
// to their respective slices, and rules are appended to the system prompt.
// Extension tools and hooks come after those set directly on AgentOptions.
Extensions []Extension
// Hooks groups all agent-level hooks.
Hooks Hooks
// Infrastructure
Logger llm.Logger
ModelSettings *ModelSettings
// LLMHooks are provider-level hooks passed to the LLM on each generation.
// These are distinct from agent-level hooks which control the agent's
// generation loop.
LLMHooks llm.Hooks
// Optional name for logging.
Name string
// Description is a free-form purpose/role description. Surfaced via
// Tracer (e.g. as gen_ai.agent.description) for observability.
Description string
// Version identifies a revision of the agent's prompt/tooling/config
// (e.g. "1.0.0", "2025-05-01"). Surfaced via Tracer.
Version string
// ID is a stable identifier for the agent, useful in multi-tenant
// systems for correlating runs to a specific agent record. Surfaced
// via Tracer. Empty values are not auto-generated.
ID string
// Tracer observes the agent's lifecycle (run start/end, each chat
// iteration, each tool call) for tracing, metrics, or audit logging.
// Defaults to NopTracer. The OpenTelemetry adapter lives in the
// dive/otel module.
Tracer Tracer
// Session enables persistent conversation state. When set, the agent
// automatically loads history before generation and saves new messages
// after generation. Can be overridden per-call with WithSession.
Session Session
// Timeouts and limits
ResponseTimeout time.Duration
ToolIterationLimit int
// IncompleteTurns configures what the agent does with a turn that stops
// before it completes.
IncompleteTurns IncompleteTurnOptions
// Durability configures per-step checkpoints and execution ownership on
// a session that stores turn records.
Durability DurabilityOptions
// ParallelToolExecution enables concurrent execution of tool calls when
// the LLM returns multiple tool calls in a single message. When false
// (the default), tool calls are executed sequentially in order.
//
// When enabled, ToolCallResult events and PostToolUse hooks fire in
// completion order (fastest tool first), not in the order the LLM
// declared the tool calls.
ParallelToolExecution bool
}
AgentOptions are used to configure an Agent.
type AgentRunInfo ¶ added in v1.5.0
type AgentRunInfo struct {
// Agent is the agent handling the run.
Agent *Agent
// Session is the active session for this run (per-call WithSession overrides
// AgentOptions.Session). Nil for stateless calls.
Session Session
}
AgentRunInfo describes an agent run at the moment it begins.
type AgentRunSpan ¶ added in v1.5.0
type AgentRunSpan interface {
// SetResponse records the final response. Called before End on the
// happy path; not called when the agent fails before producing one.
SetResponse(*Response)
// SetUsage records aggregate token usage across all iterations of the
// run. Called before End on the happy path.
SetUsage(*llm.Usage)
// End marks the run as finished. err is non-nil only if the run failed
// outright; a suspended response is not an error.
End(err error)
}
AgentRunSpan represents an in-flight agent-run observation. The agent calls End exactly once.
type AutoApproveDialog ¶ added in v1.0.0
type AutoApproveDialog struct{}
AutoApproveDialog automatically approves confirmations and selects first/default options.
func (*AutoApproveDialog) Show ¶ added in v1.0.0
func (d *AutoApproveDialog) Show(ctx context.Context, in *DialogInput) (*DialogOutput, error)
type BackgroundTaskHandle ¶ added in v1.5.0
type BackgroundTaskHandle struct {
// TaskID is a unique identifier for this background task.
TaskID string
// ToolUseID is the LLM tool_use block ID for the call that started this task.
ToolUseID string
// TurnID is the ID of the turn whose tool call started this task. A turn
// started by WithBackgroundResults links to it in Turn.Origin.
TurnID string
// Description is the human-readable description supplied to NewBackgroundResult.
Description string
// Done delivers exactly one *ToolResult when the background goroutine
// finishes. The channel is buffered (cap 1) so the goroutine can always
// send without blocking even if the caller never reads.
Done <-chan *ToolResult
// contains filtered or unexported fields
}
BackgroundTaskHandle is the caller-facing handle for a background task. It is returned on Response.BackgroundTasks after any turn in which one or more tools returned a BackgroundResult, and after a turn that stopped while a parallel tool call was still running: that call's result was recorded as unknown (ToolCallUnknownText), and its handle delivers the tool's result when it returns. The Done channel delivers exactly one *ToolResult when the background goroutine completes.
type ChatInfo ¶ added in v1.5.0
type ChatInfo struct {
// Agent is the agent handling the run.
Agent *Agent
// Session is the active session, or nil for stateless calls.
Session Session
// Model is the model name configured for this iteration. May be empty if
// the provider applies its own default.
Model string
// Streaming reports whether the agent dispatched this iteration through
// LLM.Stream (true) or LLM.Generate (false).
Streaming bool
// MaxTokens, Temperature, FrequencyPenalty, PresencePenalty mirror the
// matching llm.Config fields when set. Nil means "unset / provider default."
MaxTokens *int
Temperature *float64
FrequencyPenalty *float64
PresencePenalty *float64
// SystemPrompt is the system prompt sent for this iteration.
SystemPrompt string
// Messages is the conversation history sent for this iteration. Tracers
// that emit message payloads (e.g. gen_ai.input.messages) read this; the
// slice MUST NOT be mutated.
Messages []*llm.Message
// Iteration is the zero-based iteration number within the agent run.
Iteration int
}
ChatInfo describes a single LLM iteration at the moment it begins.
type ChatSpan ¶ added in v1.5.0
type ChatSpan interface {
// SetResponse records the LLM response. Called before End on the happy
// path; not called when Generate / Stream errors before producing one.
SetResponse(*llm.Response)
// SetTimeToFirstChunk records elapsed seconds from request issue to the
// first content-bearing chunk. Streaming iterations only.
SetTimeToFirstChunk(seconds float64)
// End marks the iteration as finished. err is non-nil only when the
// underlying Generate / Stream call returned an error.
End(err error)
}
ChatSpan represents an in-flight chat-iteration observation. The agent calls End exactly once.
type CompletedToolCall ¶ added in v1.5.0
type CompletedToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Input json.RawMessage `json:"input"`
Result *ToolResult `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
CompletedToolCall describes a tool call that ran to completion in the same iteration where a sibling suspended. Informational — the result is already present in the turn's message history (and in the session, when one is used). Exposed on SuspensionState so a SaaS UI can render "here's what we finished before pausing for your input" without reconstructing from the raw messages.
Result and Error describe the same completion in two distinct ways:
- Result is the ToolResult the tool returned; it may have IsError set if the tool reported a normal error outcome.
- Error is a Go-level error string, set only when the tool's Call method itself returned a non-nil error (tool panic, transport failure, etc). Empty whenever Result is non-nil.
type CreateResponseOption ¶ added in v0.0.10
type CreateResponseOption func(*CreateResponseOptions)
CreateResponseOption is a type signature for defining new LLM generation options.
func WithBackgroundResults ¶ added in v1.5.0
func WithBackgroundResults(handles []*BackgroundTaskHandle, results map[string]*ToolResult) CreateResponseOption
WithBackgroundResults injects completed background task results as a synthetic user message at the start of the next CreateResponse call. handles provides descriptions and ordering; results maps task ID to the completed *ToolResult. Obtain both from Response.BackgroundTasks and AwaitBackgroundTasks.
Example:
results, err := dive.AwaitBackgroundTasks(ctx, resp.BackgroundTasks)
if err != nil { ... }
nextResp, err := agent.CreateResponse(ctx,
dive.WithBackgroundResults(resp.BackgroundTasks, results),
dive.WithSession(sess),
)
func WithContinue ¶ added in v1.34.0
func WithContinue() CreateResponseOption
WithContinue asks for another invocation of the conversation as recorded, with no new input: the model is called on the history as it stands. It is how a stopped, failed or cut-off turn is picked up without rerunning any tool, since every tool result is already in the record. A "turn-continue" reminder says the user asked to continue from where the turn stopped: recorded before the new output when the history ends in an assistant message, so the request never ends in an assistant turn, which some models reject as a prefill, and model-only when it ends in an incomplete turn's outcome reminder.
On a TurnStore session whose last turn is incomplete, the continuation folds into that turn: the model sees it without its outcome reminder, the turn keeps its ID, and it is saved again with the new output, so Response.Turn.Messages is the whole turn. On any other session, pass it without input: the continuation is saved as its own turn, and Response.Turn.Messages is its reminder, if recorded, and its output. A stateless caller passes its history with WithMessages; the messages are history, not input, and Response.Turn.Messages is appended to them. It returns ErrResumeRequired on a suspended session, which must be resumed first, ErrContinueWithInput with input on a session or with a resume, and an error when there is no history at all.
func WithEventCallback ¶
func WithEventCallback(callback EventCallback) CreateResponseOption
WithEventCallback specifies a callback function that will be invoked for each item generated during response creation.
func WithInput ¶
func WithInput(input string) CreateResponseOption
WithInput specifies a simple text input string to be used in the generation. This is a convenience wrapper that creates a single user message.
func WithMessages ¶
func WithMessages(messages ...*llm.Message) CreateResponseOption
WithMessages specifies the messages to be used in the generation.
func WithModelOnlyReminder ¶ added in v1.15.0
func WithModelOnlyReminder(reminder Reminder) CreateResponseOption
WithModelOnlyReminder appends runtime context for this CreateResponse without including it in OutputMessages or session persistence.
func WithPromptCacheKey ¶ added in v1.21.0
func WithPromptCacheKey(key string) CreateResponseOption
WithPromptCacheKey sets the provider prompt-cache routing key for this call. Stateless applications that share one Agent across conversations should pass a stable, distinct key for each conversation. Session-backed agents derive a private key from Session.ID automatically.
func WithResume ¶ added in v0.0.12
func WithResume(state *SuspensionState, results map[string]*ToolResult) CreateResponseOption
WithResume supplies a prior SuspensionState together with the tool results that satisfy its pending calls, bundling the two values a stateless resume requires into a single option. The caller still passes their pre-turn history via WithMessages; the agent splices state.TurnMessages onto that history to reconstruct the full conversation.
Partial resumes are allowed: pass results for a subset of the pending calls and the agent returns a new suspended Response listing the remaining pending. Pass a nil map of results to re-submit the state without advancing (rare — useful for cross-process handoff where the resumer just wants the agent to take authority over a newer snapshot).
When a SuspendableSession is in use, WithResume overrides the session's stored state — useful when the caller holds a more recent snapshot. Session-backed callers who simply want to resume from the session's stored state should use WithToolResults instead.
Supplying an ID that is not in the pending set returns ErrUnknownPendingToolCall without mutating session state.
func WithResumeRequest ¶ added in v1.34.0
func WithResumeRequest(req ResumeRequest) CreateResponseOption
WithResumeRequest resumes the session's suspended turn with req's results, after checking that it is still the turn and revision the caller read. It needs a session that implements TurnStore. Supplying a result a previous resume already accepted is not an error, so a resume whose outcome was unknown can be sent again as it was.
func WithSession ¶ added in v1.0.0
func WithSession(s Session) CreateResponseOption
WithSession overrides the agent's default session for a single call. This is useful in server scenarios where one agent handles multiple sessions.
func WithToolResults ¶ added in v1.5.0
func WithToolResults(results map[string]*ToolResult) CreateResponseOption
WithToolResults supplies externally-obtained tool results to resume a session-backed suspended agent. The keys are tool_call IDs taken from a prior Response.Suspension.PendingToolCalls. The values are caller-constructed ToolResults; an IsError result flows through the PostToolUseFailure path as if the tool itself had failed.
Use WithToolResults when the agent has a SuspendableSession — the session supplies the SuspensionState automatically. Stateless callers, or callers doing cross-process handoff, should use WithResume instead (which bundles both the state and the tool results).
If the caller supplies results for only a subset of pending IDs, the agent stays suspended and returns a new suspended Response listing the remaining pending calls. If any supplied ID is not in the pending set, CreateResponse returns ErrUnknownPendingToolCall without mutating session state.
Concurrent CreateResponse calls on the same session (resume or otherwise) are serialized automatically by an in-process per-session lock keyed on Session.ID() — see the Session interface documentation.
func WithValue ¶ added in v1.0.0
func WithValue(key string, value any) CreateResponseOption
WithValue sets a single key-value pair that will be available in HookContext.Values during generation. Multiple WithValue calls accumulate.
type CreateResponseOptions ¶ added in v0.0.10
type CreateResponseOptions struct {
// Messages contains the input messages for this generation. These are
// appended to any existing session messages before sending to the LLM.
Messages []*llm.Message
// ModelOnlyReminders are appended at the conversation tail for this request
// but excluded from OutputMessages and session persistence.
ModelOnlyReminders []Reminder
// EventCallback is invoked for each response item during generation.
// Callbacks include messages, tool calls, and tool results.
EventCallback EventCallback
// Values contains arbitrary key-value pairs that are copied into
// HookContext.Values before hooks run. This allows callers to pass
// data to hooks (e.g. session IDs) through CreateResponse options.
Values map[string]any
// Session overrides AgentOptions.Session for this call.
// Useful in server scenarios where one agent serves multiple sessions.
Session Session
// PromptCacheKey routes requests from the same conversation to the same
// provider prompt cache. When empty, the agent derives one from the active
// Session or falls back to a key that is stable for this Agent instance.
PromptCacheKey string
// ToolResults, when non-nil, supplies externally-obtained tool results
// to a resume call. Keys are tool_call IDs from a prior suspended
// Response's Suspension.PendingToolCalls; values are the results the
// caller obtained out-of-band. Typically set via WithResume (stateless)
// or WithToolResults (session-backed).
ToolResults map[string]*ToolResult
// Suspension, when non-nil, supplies a SuspensionState from a prior
// suspended Response, used by stateless callers to resume a turn
// without a SuspendableSession. The agent splices
// Suspension.TurnMessages onto the pre-turn history passed via
// WithMessages to reconstruct the full conversation. When a
// SuspendableSession is in use this option overrides the session's
// stored state (useful for cross-process handoff where the resumer
// holds a newer snapshot than what was persisted). Typically set via
// WithResume rather than assigned directly.
Suspension *SuspensionState
// BackgroundHandles and BackgroundResults, when both non-nil, inject
// completed background task results as a synthetic user message at the
// start of the next generation. Set via WithBackgroundResults.
BackgroundHandles []*BackgroundTaskHandle
BackgroundResults map[string]*ToolResult
// Continue asks for another invocation of the conversation as recorded,
// with no new input. Set via WithContinue.
Continue bool
// ResumeTurnID and ExpectedRevision, when set, are checked against the
// session's open turn and revision before a resume. Set via
// WithResumeRequest.
ResumeTurnID string
ExpectedRevision uint64
// contains filtered or unexported fields
}
CreateResponseOptions contains configuration for LLM generations.
This struct holds all the options that can be passed to Agent.CreateResponse. Options are typically set using the With* functions rather than directly modifying this struct.
func (*CreateResponseOptions) Apply ¶ added in v0.0.10
func (o *CreateResponseOptions) Apply(opts []CreateResponseOption)
Apply invokes any supplied options. Used internally in Dive.
type DenyAllDialog ¶ added in v1.0.0
type DenyAllDialog struct{}
DenyAllDialog denies all confirmations and cancels all other dialogs.
func (*DenyAllDialog) Show ¶ added in v1.0.0
func (d *DenyAllDialog) Show(ctx context.Context, in *DialogInput) (*DialogOutput, error)
type Dialog ¶ added in v1.0.0
type Dialog interface {
// Show presents a dialog to the user and waits for their response.
Show(ctx context.Context, in *DialogInput) (*DialogOutput, error)
}
Dialog handles user interaction prompts during agent execution.
Implementations of this interface provide the UI layer for confirmations, selections, and text input. The prompt type is determined by which fields are set in DialogInput:
- Confirm mode: set Confirm=true (yes/no question)
- Select mode: set Options (pick one)
- MultiSelect mode: set Options and MultiSelect=true (pick many)
- Input mode: none of the above (free-form text)
Example implementation for auto-approve:
type AutoApproveDialog struct{}
func (d *AutoApproveDialog) Show(ctx context.Context, in *DialogInput) (*DialogOutput, error) {
if in.Confirm {
return &DialogOutput{Confirmed: true}, nil
}
if len(in.Options) > 0 {
return &DialogOutput{Values: []string{in.Options[0].Value}}, nil
}
return &DialogOutput{Text: in.Default}, nil
}
type DialogInput ¶ added in v1.0.0
type DialogInput struct {
// Title is a short heading for the dialog.
Title string
// Message provides additional context or instructions.
Message string
// Confirm indicates this is a yes/no confirmation dialog.
// When true, the response's Confirmed field contains the answer.
Confirm bool
// Options provides choices for selection dialogs.
// When non-empty, the response's Values field contains selected option values.
Options []DialogOption
// MultiSelect allows selecting multiple options.
// Only applies when Options is non-empty.
MultiSelect bool
// Default is the pre-selected value.
// Type depends on mode: bool (confirm), string (select/input), []string (multi-select).
Default string
// Validate is an optional validation function for text input.
// Return an error to reject the input with a message.
Validate func(string) error
// Tool is the tool requesting this dialog (optional, for context).
Tool Tool
// Call is the specific tool invocation (optional, for context).
Call *llm.ToolUseContent
}
DialogInput describes what to present to the user.
type DialogOption ¶ added in v1.0.0
type DialogOption struct {
// Value is the machine-readable identifier returned when selected.
Value string
// Label is the human-readable text displayed to the user.
Label string
// Description provides additional context about this option.
Description string
}
DialogOption represents a selectable choice.
type DialogOutput ¶ added in v1.0.0
type DialogOutput struct {
// Confirmed is the answer for Confirm mode dialogs.
Confirmed bool
// Values contains selected option values.
// For single-select, this has one element.
// For multi-select, this may have zero or more elements.
Values []string
// Text is the entered text for Input mode dialogs.
Text string
// Canceled indicates the user dismissed the dialog without responding.
Canceled bool
// AllowSession indicates the user wants to allow all similar actions this session.
AllowSession bool
// Feedback contains user-provided text when denying (e.g., "try a different approach").
Feedback string
}
DialogOutput contains the user's response.
type DurabilityOptions ¶ added in v1.34.0
type DurabilityOptions struct {
// CheckpointSteps records the turn in the session at each step of an
// invocation, with ResponseStatusRunning: before the first model call,
// after each model response whose tool calls will run, as each tool
// call starts (ToolCallStateRunning) and as each result arrives; the
// invocation's end records the turn as before. A step checkpoint that
// fails stops the turn before the step, so no tool runs unrecorded.
//
// An invocation that finds its session's last turn running closes it
// first, as an incomplete turn with TurnReasonProcessExit: its running
// calls are unknown, and Next is TurnNextReconcile unless every one of
// them is read-only. A tool that ran between its running checkpoint and
// its result's is the window that remains; TurnID(ctx) and
// ToolCallID(ctx) give it a stable key for idempotent requests.
//
// It needs a session that implements TurnStore; session.FileStore
// appends a line per step.
CheckpointSteps bool
// Claim claims the session for Owner before an invocation loads it
// (SessionClaimer), renews the claim while the invocation runs, and
// releases it at the end. An invocation on a session another owner
// holds fails with ErrSessionClaimed before doing anything, and one
// whose claim is lost while it runs is cancelled. Every process that
// runs an agent on the session must claim it. It needs a session that
// implements SessionClaimer.
Claim bool
// Owner names this agent in its claims. It must differ between
// processes. Default: a random name for each Agent.
Owner string
// ClaimTTL is how long a claim lasts unless it is renewed; the agent
// renews it every third of that, so a claim a process left when it
// exited expires within ClaimTTL. Default 30 seconds.
ClaimTTL time.Duration
}
DurabilityOptions configures what the agent does so that a turn survives the process running it, and so that several processes can share a session. Both are off by default: the agent then records a turn once, when the invocation ends.
type EventCallback ¶
type EventCallback func(ctx context.Context, item *ResponseItem) error
EventCallback is a function called with each item produced while an agent is using tools or generating a response. Callbacks may be invoked concurrently from multiple goroutines (e.g. parallel tool calls, tool streaming) — implementations must be safe for concurrent use.
type Extension ¶ added in v1.5.0
type Extension interface {
// Tools returns additional tools to make available to the agent.
Tools() []Tool
// Hooks returns hooks to register on the agent.
Hooks() Hooks
// Rules returns text to append to the agent's system prompt.
// Returns empty string if no rules are needed.
Rules() string
}
Extension bundles tools, hooks, and system prompt rules that extend an agent's capabilities. Implementations provide any combination of these, returning nil/empty for aspects they don't use.
type FuncToolOption ¶ added in v1.0.0
type FuncToolOption interface {
// contains filtered or unexported methods
}
FuncToolOption configures a FuncTool.
func WithFuncToolAnnotations ¶ added in v1.0.0
func WithFuncToolAnnotations(a *ToolAnnotations) FuncToolOption
WithFuncToolAnnotations sets annotations on a FuncTool.
func WithFuncToolSchema ¶ added in v1.0.0
func WithFuncToolSchema(s *Schema) FuncToolOption
WithFuncToolSchema overrides the auto-generated schema.
type GenerationError ¶ added in v1.8.0
type GenerationError struct {
// Err is the underlying error that terminated the generation loop.
Err error
// Usage is the token usage accumulated across all LLM calls that
// completed in the failed turn. Never nil, but may be zero-valued when
// the very first call failed.
Usage *llm.Usage
// OutputMessages are the messages produced in the turn before the
// failure, in order, closed as Response.OutputMessages is.
OutputMessages []*llm.Message
// Items are the response items accumulated before the failure.
Items []*ResponseItem
// Response is the incomplete response CreateResponse returned with this
// error, or nil for a failed partial resume.
Response *Response
}
GenerationError wraps a failure after the turn began, carrying the usage, output messages, and response items accumulated before the failure. When iteration N of a turn fails after earlier iterations succeeded — meaning tools with real side effects may have already run and tokens have already been paid for — callers can recover cost accounting and partial work via errors.As:
resp, err := agent.CreateResponse(ctx, ...)
if err != nil {
var genErr *dive.GenerationError
if errors.As(err, &genErr) {
recordUsage(genErr.Usage)
}
}
CreateResponse returns the incomplete Response alongside the error, and Response is the same value; it is nil only when a partial resume fails, since the turn is then still suspended. A partial resume can fail in its session write after the write landed, so the caller reloads the suspension (SuspendableSession.LoadSuspension) before resubmitting; a result the session already accepted is refused with ErrUnknownPendingToolCall.
The turn is closed before it is returned and saved: every tool call is answered, and a turn-incomplete reminder recording Response.Turn.Outcome is the last message, so OutputMessages is a valid history. With IncompleteTurnOptions.Discard, OutputMessages is left as the error found it and nothing is saved.
func (*GenerationError) Error ¶ added in v1.8.0
func (e *GenerationError) Error() string
func (*GenerationError) Unwrap ¶ added in v1.8.0
func (e *GenerationError) Unwrap() error
type HookAbortError ¶ added in v1.0.0
type HookAbortError struct {
Reason string
HookType string // "PreGeneration", "PostGeneration", "PreToolUse", "PostToolUse", "PostToolUseFailure"
HookName string // Optional: name/description of the hook that aborted
Cause error // Optional: underlying error
}
HookAbortError signals that a hook wants to abort generation entirely. When returned from any hook, CreateResponse will abort and return this error. Use this for safety violations, compliance issues, or critical failures.
Regular errors (non-HookAbortError) are handled gracefully:
- PreGeneration: aborts (setup is required)
- PostGeneration: logged only
- PreToolUse: converted to Deny message
- PostToolUse: logged only
- PostToolUseFailure: logged only
func (*HookAbortError) Error ¶ added in v1.0.0
func (e *HookAbortError) Error() string
func (*HookAbortError) Unwrap ¶ added in v1.0.0
func (e *HookAbortError) Unwrap() error
type HookContext ¶ added in v1.0.0
type HookContext struct {
// Agent is the agent running the generation.
Agent *Agent
// Session is the active session for this CreateResponse call (per-call
// override via WithSession takes priority over AgentOptions.Session).
// Nil for stateless calls. Hooks can read Session.ID() to attach
// gen_ai.conversation.id or correlate work across turns.
Session Session
// Values provides arbitrary storage for hooks to communicate.
// Persists across all phases within one CreateResponse call.
Values map[string]any
// SystemPrompt is the system prompt that will be sent to the LLM.
SystemPrompt string
// Messages contains the conversation history plus new input messages.
Messages []*llm.Message
// SessionStartSource is set for SessionStart hooks and reports why the hook
// is firing (see SessionStartSource). Empty for all other hook types.
SessionStartSource SessionStartSource
// Response is the complete Response object returned by CreateResponse.
Response *Response
// OutputMessages contains the messages generated during this response.
OutputMessages []*llm.Message
// Usage contains token usage statistics for this generation.
Usage *llm.Usage
// Tool is the tool being executed.
Tool Tool
// Call contains the tool invocation details including input.
Call *llm.ToolUseContent
// Result contains the tool execution result (PostToolUse/PostToolUseFailure only).
Result *ToolCallResult
// UpdatedInput, when set by a PreToolUse hook, replaces Call.Input before
// the tool is executed. Only the last hook's UpdatedInput takes effect.
UpdatedInput []byte
// AdditionalContext, when set by a hook, is appended as a text content
// block to the tool result message sent to the LLM. This lets hooks
// provide guidance without modifying the tool result itself.
AdditionalContext string
// StopHookActive is true when this stop check was triggered by a
// previous stop hook continuation. Check this to prevent infinite loops.
StopHookActive bool
// Iteration is the zero-based iteration number within the generation loop.
Iteration int
// FinalCall, when a PreIteration hook sets it, makes the upcoming model
// call the last one of this generation loop: tools are disabled for it, as
// at the tool iteration limit. To tell the model why, append a Recorded
// reminder in the same hook; it is delivered before the call and kept in
// the turn's output. The agent clears the flag once applied.
FinalCall bool
// Turn is the turn as it will be returned and saved. Set for
// OnIncompleteTurn hooks, whose Turn.Outcome is mutable.
Turn *Turn
// contains filtered or unexported fields
}
HookContext provides mutable access to the generation context. All hook types receive a *HookContext. Fields are populated based on the hook phase:
- PreGeneration: Agent, Session, Values, SystemPrompt, Messages
- PostGeneration: Agent, Session, Values, SystemPrompt, Messages, Response, OutputMessages, Usage
- PreToolUse: Agent, Session, Values, Tool, Call
- PostToolUse: Agent, Session, Values, Tool, Call, Result
- PostToolUseFailure: Agent, Session, Values, Tool, Call, Result
- Stop: Agent, Session, Values, Response, OutputMessages, Usage, StopHookActive
- PreIteration: Agent, Session, Values, SystemPrompt, Messages, Iteration
- OnIncompleteTurn: Agent, Session, Values, SystemPrompt, Messages, Response, OutputMessages, Usage, Turn
The Values map allows hooks to communicate with each other by storing arbitrary data that persists across the hook chain within a single CreateResponse call.
func NewHookContext ¶ added in v1.0.0
func NewHookContext() *HookContext
NewHookContext creates a new HookContext with initialized Values map.
func (*HookContext) AppendReminder ¶ added in v1.14.0
func (h *HookContext) AppendReminder(reminder Reminder, recording ReminderRecording) error
AppendReminder queues a reminder for the next iteration boundary. Recorded reminders are included in OutputMessages; ModelOnly reminders live only for the remainder of this CreateResponse call.
type Hooks ¶ added in v1.0.0
type Hooks struct {
// SessionStart hooks fire once per session, before the first LLM call, when
// the loaded session has no prior messages. Returned messages are prepended
// to the conversation as seed messages. Errors abort CreateResponse.
SessionStart []SessionStartHook
// PreGeneration hooks are called before the LLM generation loop.
PreGeneration []PreGenerationHook
// PostGeneration hooks are called after the LLM generation loop completes.
PostGeneration []PostGenerationHook
// PreToolUse hooks are called before each tool execution.
PreToolUse []PreToolUseHook
// PostToolUse hooks are called after each successful tool execution.
PostToolUse []PostToolUseHook
// PostToolUseFailure hooks are called after each failed tool execution.
PostToolUseFailure []PostToolUseFailureHook
// Stop hooks run when the agent is about to finish responding.
// A hook can prevent stopping by returning a StopDecision with Continue: true.
Stop []StopHook
// PreIteration hooks run before each LLM call within the generation loop.
PreIteration []PreIterationHook
// OnSuspend hooks run when the agent transitions into a suspended state,
// before PostGeneration. Use to notify external systems that human input
// is needed.
OnSuspend []OnSuspendHook
// OnIncompleteTurn hooks run when a turn ends incomplete, for any
// reason, after the turn is closed and before it is saved. They can
// repair the messages that will be saved, change the recorded error,
// notify an external system, or discard the turn. They do not run for an
// error exit when IncompleteTurnOptions.Discard is set.
OnIncompleteTurn []IncompleteTurnHook
// PostBackgroundToolUse hooks fire when background task results are
// delivered to the agent — i.e. when WithBackgroundResults is used on the
// next CreateResponse call. The hook receives the final *ToolResult and
// the original tool/call metadata from the HookContext. This is the
// correct point to close OTel spans opened at tool call time.
//
// Hooks run in the main agent goroutine, never from a background goroutine.
// Errors are logged but do not affect the response (same as PostGeneration).
PostBackgroundToolUse []PostBackgroundToolUseHook
}
Hooks groups all agent hook slices.
type IncompleteTurnDecision ¶ added in v1.34.0
type IncompleteTurnDecision struct {
// Discard drops the turn: nothing is saved, as if
// IncompleteTurnOptions.Discard were set for this call. The response
// still reports the closed turn, with Persistence none.
Discard bool
}
IncompleteTurnDecision tells the agent what to do with an incomplete turn.
type IncompleteTurnHook ¶ added in v1.34.0
type IncompleteTurnHook func(ctx context.Context, hctx *HookContext) (*IncompleteTurnDecision, error)
IncompleteTurnHook runs when a turn ends incomplete, after the turn is closed and before it is saved. It receives:
- hctx.Turn: the turn as it will be returned and saved. Turn.Outcome is mutable; the saved outcome reminder is built from it after the hooks.
- hctx.OutputMessages: the closed output without the outcome reminder. A hook may replace or edit it; what it holds after the hooks is saved, followed by the outcome reminder.
- hctx.Response, hctx.Usage and hctx.Messages.
Its context is not cancelled even when a cancellation ended the turn, so the hook can do I/O. Recorded reminders it appends are saved before the outcome reminder. A regular error is logged; a decision with Discard set drops the turn.
type IncompleteTurnOptions ¶ added in v1.34.0
type IncompleteTurnOptions struct {
// Discard restores the behaviour before v1.34 for a turn that ends in an
// error: nothing is saved, no OnIncompleteTurn hook runs, no not-run,
// unknown or turn_ended item is emitted, the output is left as the
// error found it, and a failed resume leaves the session suspended.
// CreateResponse still returns the incomplete Response with the error,
// with Turn.Persistence none. A turn the model itself stopped short
// (output limit, context limit, iteration limit, provider stop, pause)
// is still closed and saved. For applications that keep incomplete turns
// themselves.
Discard bool
// DropPartialText leaves out the text the model was still writing when
// a streamed response stopped.
DropPartialText bool
// SaveTimeout bounds the session write at the end of an invocation. The
// write, like the OnIncompleteTurn and OnSuspend hooks, runs on a
// context without the cancellation that may have ended the turn, so
// that the turn is kept. Default 30 seconds.
SaveTimeout time.Duration
// RequireReconcile refuses new input on a session whose last turn
// stopped with a call whose result is unknown (TurnOutcome.Next is
// TurnNextReconcile), with ErrUnreconciledToolCalls, so that such a turn
// is continued (WithContinue) or removed before the conversation moves
// on. On a TurnStore the latest turn record decides, so a compaction
// that summarized the turn does not clear it; on another session, the
// outcome reminder at the end of the history does. By default the new
// turn starts, and the model sees the unknown calls' results and the
// outcome reminder.
RequireReconcile bool
}
IncompleteTurnOptions configures what the agent does with a turn that stops before it completes. By default such a turn is closed (every tool call answered, the outcome recorded as a turn-incomplete reminder), passed to OnIncompleteTurn hooks, and saved to the session like any other turn.
type JudgmentDecision ¶ added in v1.6.0
JudgmentDecision is the structured verdict a model returns from a judgment hook. OK reports whether the action may proceed; Reason explains a block and is surfaced back to the agent.
type ModelSettings ¶ added in v0.0.10
type ModelSettings struct {
Temperature *float64
PresencePenalty *float64
FrequencyPenalty *float64
ParallelToolCalls *bool
Caching *bool
MaxTokens *int
ReasoningBudget *int
ReasoningEffort llm.ReasoningEffort
Thinking llm.ThinkingType
ThinkingDisplay llm.ThinkingDisplay
Speed llm.Speed
// TaskBudget gives the model an advisory token budget for each
// CreateResponse: every model call of the turn shares it. See
// llm.TaskBudget.
TaskBudget *llm.TaskBudget
ToolChoice *llm.ToolChoice
Features []string
RequestHeaders http.Header
MCPServers []llm.MCPServerConfig
}
ModelSettings are used to configure details of the LLM for an Agent.
func (*ModelSettings) Options ¶ added in v1.0.0
func (m *ModelSettings) Options() []llm.Option
Options returns the LLM options corresponding to the model settings.
type NopTracer ¶ added in v1.5.0
type NopTracer struct{}
NopTracer is a Tracer that does nothing. It is the default tracer used by agents that do not configure one.
func (NopTracer) StartAgentRun ¶ added in v1.5.0
func (NopTracer) StartAgentRun(ctx context.Context, _ AgentRunInfo) (context.Context, AgentRunSpan)
func (NopTracer) StartToolCall ¶ added in v1.5.0
func (NopTracer) StartToolCall(ctx context.Context, _ ToolCallInfo) (context.Context, ToolCallSpan)
type OnSuspendHook ¶ added in v1.5.0
type OnSuspendHook func(ctx context.Context, hctx *HookContext) error
OnSuspendHook fires when the agent transitions into a suspended state, BEFORE PostGeneration runs and BEFORE the suspended turn is persisted to the session. Use this to notify an external system that human input is needed (email, Slack, task creation, webhook dispatch).
hctx.Response is populated with the suspended Response. Status is ResponseStatusSuspended and Response.Suspension is a non-nil *SuspensionState carrying PendingToolCalls, CompletedToolCalls, and TurnMessages. Regular errors are logged; returning a HookAbortError aborts the call before the session is marked suspended, so the caller sees an error and the session stays in its previous state. Because the hook runs BEFORE persistence, aborting does not require any compensating rollback — there is simply nothing on disk to roll back.
Partial resumes (a suspended session resumed with only some of the awaited results) do NOT re-fire OnSuspend, since they continue an existing suspension rather than announcing a new one.
type PendingToolCall ¶ added in v1.5.0
type PendingToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Input json.RawMessage `json:"input"`
Prompt string `json:"prompt,omitempty"`
Reason SuspendReason `json:"reason,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
// HaltsBatch records that the call takes part in batch halting (see
// ToolAnnotations.HaltsBatch), so an error result supplied for it on
// resume halts the batch even if the resuming agent's tools changed.
HaltsBatch bool `json:"halts_batch,omitempty"`
}
PendingToolCall describes a tool call awaiting an external result.
Metadata type fidelity ¶
Metadata values are round-tripped through JSON whenever a SuspensionState is deep-copied (during LoadSuspension, partial resume, etc.) or persisted to disk. After a round trip, numeric values come back as float64 and custom struct types become generic map[string]any. Tool authors attaching structured metadata should expect this loss of type fidelity and stick to JSON-friendly values.
func (*PendingToolCall) UnmarshalInput ¶ added in v1.5.0
func (p *PendingToolCall) UnmarshalInput(into any) error
UnmarshalInput decodes the pending call's Input JSON into the given destination. Convenience for the common pattern of reading the original tool arguments when handling a suspend out-of-band.
type PersistenceState ¶ added in v1.34.0
type PersistenceState string
PersistenceState says whether a session recorded a turn.
const ( // PersistenceNone means nothing was saved: there is no session, the // session does not store this kind of state (a suspension on a session // that is not a SuspendableSession), or the turn was discarded // (IncompleteTurnOptions.Discard, IncompleteTurnDecision.Discard). PersistenceNone PersistenceState = "none" // PersistenceSaved means the session acknowledged the write. PersistenceSaved PersistenceState = "saved" // PersistenceFailed means the session refused the write before writing // anything: its error wraps ErrSaveRejected. PersistenceFailed PersistenceState = "failed" // PersistenceUnknown means the write returned any other error, or did // not finish within IncompleteTurnOptions.SaveTimeout. The write may // still have landed, as when a file store fails after replacing the // file, so the caller reloads the session before acting on it. PersistenceUnknown PersistenceState = "unknown" )
type PostBackgroundToolUseHook ¶ added in v1.5.0
type PostBackgroundToolUseHook func(ctx context.Context, hctx *HookContext) error
PostBackgroundToolUseHook fires when a background task's result is delivered to the agent — specifically when WithBackgroundResults is used on the next CreateResponse call. The hook receives a HookContext with the final *ToolResult and the original tool/call metadata.
This hook always runs in the main agent goroutine (never from the background goroutine). It is the correct place to close OTel spans that were opened at the original tool call time.
Errors are logged but do not affect the response.
type PostGenerationHook ¶ added in v1.0.0
type PostGenerationHook func(ctx context.Context, hctx *HookContext) error
PostGenerationHook is called after the LLM generation loop completes, on a completed or suspended turn. An incomplete turn runs OnIncompleteTurn hooks instead.
PostGeneration hooks run in order and can:
- Read hctx.Response to access the complete response
- Read hctx.OutputMessages to access generated messages
- Read hctx.Usage to access token usage statistics
- Read data from hctx.Values stored by earlier hooks
- Perform side effects like logging, saving, or notifications
PostGeneration hook errors are logged but do NOT affect the returned Response. This design ensures that generation results are not lost due to post-processing failures (e.g., if saving to a database fails).
func UsageLogger ¶ added in v1.0.0
func UsageLogger(logFunc func(usage *llm.Usage)) PostGenerationHook
UsageLogger returns a PostGenerationHook that logs token usage after each generation using the provided callback function.
func UsageLoggerWithSlog ¶ added in v1.0.0
func UsageLoggerWithSlog(logger llm.Logger) PostGenerationHook
UsageLoggerWithSlog returns a PostGenerationHook that logs token usage using an slog.Logger.
type PostToolUseFailureHook ¶ added in v1.0.0
type PostToolUseFailureHook func(ctx context.Context, hctx *HookContext) error
PostToolUseFailureHook is called after a tool call fails.
The hook receives the same context as PostToolUseHook, but fires only when the tool execution returned an error or the result has IsError set. This mirrors Claude Code's separate PostToolUseFailure event.
Hooks can set hctx.AdditionalContext to inject context into the tool result message.
Hook errors are logged but do not affect the tool result.
func MatchToolPostFailure ¶ added in v1.0.0
func MatchToolPostFailure(pattern string, hook PostToolUseFailureHook) PostToolUseFailureHook
MatchToolPostFailure returns a PostToolUseFailureHook that only runs when the tool name matches the given pattern. The pattern is a Go regexp. If the pattern fails to compile, the returned hook always returns the compilation error.
type PostToolUseHook ¶ added in v0.0.12
type PostToolUseHook func(ctx context.Context, hctx *HookContext) error
PostToolUseHook is called after a tool call succeeds.
The hook receives context about the completed tool call including the result. Hooks can modify hctx.Result to transform the tool output before it's sent to the LLM in the next generation iteration.
Hooks can set hctx.AdditionalContext to inject context into the tool result message.
Hook errors are logged but do not affect the tool result.
func MatchToolPost ¶ added in v1.0.0
func MatchToolPost(pattern string, hook PostToolUseHook) PostToolUseHook
MatchToolPost returns a PostToolUseHook that only runs when the tool name matches the given pattern. The pattern is a Go regexp. If the pattern fails to compile, the returned hook always returns the compilation error.
type PreGenerationHook ¶ added in v1.0.0
type PreGenerationHook func(ctx context.Context, hctx *HookContext) error
PreGenerationHook is called before the LLM generation loop begins.
PreGeneration hooks run in order and can:
- Modify hctx.SystemPrompt to customize the system prompt
- Modify hctx.Messages to inject context or load session history
- Store data in hctx.Values for use by later hooks
- Return an error to abort generation entirely
If any PreGeneration hook returns an error, generation is aborted and CreateResponse returns that error. No subsequent hooks are called.
func CompactionHook ¶ added in v1.0.0
func CompactionHook(messageThreshold int, summarizer func(context.Context, []*llm.Message) ([]*llm.Message, error)) PreGenerationHook
CompactionHook returns a PreGenerationHook that triggers context compaction when the message count exceeds the given threshold.
The summarizer function is called when compaction is triggered. It receives the current messages and should return compacted messages. If the summarizer returns an error, the hook returns that error (aborting generation).
func InjectContext ¶ added in v1.0.0
func InjectContext(content ...llm.Content) PreGenerationHook
InjectContext returns a PreGenerationHook that prepends the given content to the conversation as a user message.
This is useful for injecting context that should appear before the user's actual input, such as:
- Relevant documentation or code snippets
- Previous conversation summaries
- Environment information or system state
Example:
agent, _ := dive.NewAgent(dive.AgentOptions{
SystemPrompt: "You are a coding assistant.",
Model: model,
Hooks: dive.Hooks{
PreGeneration: []dive.PreGenerationHook{
dive.InjectContext(
llm.NewTextContent("Current working directory: /home/user/project"),
llm.NewTextContent("Git branch: main"),
),
},
},
})
type PreIterationHook ¶ added in v1.0.0
type PreIterationHook func(ctx context.Context, hctx *HookContext) error
PreIterationHook is called before each LLM call within the generation loop. Use these to modify the system prompt or messages between iterations.
hctx.Iteration provides the zero-based iteration number. Errors abort generation (same as PreGeneration).
A hook that rewrites hctx.Messages should keep the messages it does not change as the same pointers. With a task budget (ModelSettings.TaskBudget), a message of the turn that is no longer in hctx.Messages counts as removed, and its tokens are taken off the remaining budget; a copy of it counts as removed although its content is still sent.
type PreToolUseHook ¶ added in v0.0.12
type PreToolUseHook func(ctx context.Context, hctx *HookContext) error
PreToolUseHook is called before a tool is executed.
All hooks run in order. If any hook returns an error, the tool is denied and the error message is sent to the LLM. If all hooks return nil, the tool is executed.
Hooks can set hctx.UpdatedInput to rewrite tool arguments before execution, and hctx.AdditionalContext to inject context into the tool result message.
Error handling:
- nil: no objection (tool runs if all hooks return nil)
- error: deny the tool (error message sent to LLM)
- *HookAbortError: abort generation entirely
func MatchTool ¶ added in v1.0.0
func MatchTool(pattern string, hook PreToolUseHook) PreToolUseHook
MatchTool returns a PreToolUseHook that only runs when the tool name matches the given pattern. The pattern is a Go regexp. If the pattern fails to compile, the returned hook always denies tool execution with the compilation error.
func PromptToolGate ¶ added in v1.6.0
func PromptToolGate(model llm.LLM, prompt string) PreToolUseHook
PromptToolGate returns a PreToolUseHook that asks model whether the pending tool call is acceptable per prompt. If the model answers ok=false the call is denied (a returned error denies a tool in Dive) and the reason is sent back to the agent.
It fails closed: a model or transport error denies the call, because a safety gate that silently allows on error is worse than an occasional false deny. Pair it with MatchTool to scope the gate to specific tools, and pass a cheap model — this adds one call per matched tool invocation.
type Reminder ¶ added in v1.14.0
type Reminder struct {
Name string `json:"name"`
Tier ReminderTier `json:"tier"`
Content string `json:"content"`
// Details is structured data about the reminder for applications,
// recorded with it and never rendered to the model. Values must be
// JSON-friendly: after a round trip through a session, numbers are
// float64 and structs are map[string]any.
Details map[string]any `json:"details,omitempty"`
}
Reminder is a validated, named block of runtime-injected context.
func FindLatestReminder ¶ added in v1.14.0
FindLatestReminder searches typed reminders from newest to oldest.
func FindReminder ¶ added in v1.14.0
FindReminder finds a typed reminder in one message. It never parses text.
func NewContextReminder ¶ added in v1.14.0
NewContextReminder creates user-adjacent runtime context.
func NewOperatorReminder ¶ added in v1.14.0
NewOperatorReminder creates context asserted by the application operator.
func NewTurnOutcomeReminder ¶ added in v1.34.0
func NewTurnOutcomeReminder(outcome *TurnOutcome) Reminder
NewTurnOutcomeReminder builds the reminder recorded at the end of an incomplete turn: a contextual reminder named ReminderNameTurnIncomplete whose Details hold the outcome. Applications match the name and read the details with FindTurnOutcome; the Content is Dive's wording for the reason, written for the model, and may change between releases.
func ParseLegacyReminderText ¶ added in v1.14.0
ParseLegacyReminderText recognizes one complete legacy text reminder. This is heuristic and must not be used for provenance- or security-sensitive UI.
type ReminderRecording ¶ added in v1.14.0
type ReminderRecording string
ReminderRecording controls whether an appended reminder is returned in OutputMessages and therefore eligible for session persistence.
const ( Recorded ReminderRecording = "recorded" ModelOnly ReminderRecording = "model_only" )
type ReminderTier ¶ added in v1.14.0
type ReminderTier = llm.ReminderTier
ReminderTier is the authority assigned to runtime-injected context.
type Response ¶
type Response struct {
// Model represents the model that generated the response
Model string `json:"model,omitempty"`
// Items contains the individual response items including
// messages, tool calls, and tool results.
Items []*ResponseItem `json:"items,omitempty"`
// OutputMessages contains the messages generated during this response.
// This includes assistant messages and tool result messages in the order
// they were produced. Use these messages to continue a multi-turn
// conversation: pass the original input messages plus OutputMessages
// plus a new user message on the next call.
OutputMessages []*llm.Message `json:"output_messages,omitempty"`
// Usage contains token usage information
Usage *llm.Usage `json:"usage,omitempty"`
// CreatedAt is the timestamp when this response was created
CreatedAt time.Time `json:"created_at,omitempty"`
// FinishedAt is the timestamp when this response was completed
FinishedAt *time.Time `json:"finished_at,omitempty"`
// StopReason is the provider's raw stop reason for the last model
// response of this call ("end_turn", "max_tokens", "tool_use", ...), or
// "" when the call made no model request, as on a partial resume.
// llm.ClassifyStopReason says what kind of stop it was. StopDetails
// carries the provider's structured detail when it reports one, such as
// a refusal category.
StopReason string `json:"stop_reason,omitempty"`
StopDetails *llm.StopDetails `json:"stop_details,omitempty"`
// Status is ResponseStatusCompleted for normal returns,
// ResponseStatusSuspended when at least one tool returned SuspendResult,
// or ResponseStatusIncomplete when the turn stopped short.
// An empty Status means Completed (back-compat).
Status ResponseStatus `json:"status,omitempty"`
// Turn is the turn as this invocation left it: the messages a session
// saves, the usage, the outcome or the suspension, and whether a session
// recorded it. It is set for every status once the turn has begun,
// which is just before the PreGeneration hooks run; an error before
// that returns no Response.
Turn *Turn `json:"turn,omitempty"`
// Suspension carries the suspend/resume turn snapshot. It is populated:
//
// - When Status == ResponseStatusSuspended (the agent is paused
// mid-turn): Pending and Completed tool calls plus the in-progress
// turn messages.
// - When Status == ResponseStatusCompleted on a call that resumed a
// previously suspended turn: PendingToolCalls is nil, TurnMessages
// holds the final merged turn. Stateless callers flush by
// appending TurnMessages to their pre-turn history.
//
// It is nil on plain completions that did not involve suspend or
// resume. See the SuspensionState docs for the canonical stateless
// usage pattern.
Suspension *SuspensionState `json:"suspension,omitempty"`
// BackgroundTasks is non-nil and non-empty when one or more tools
// returned BackgroundResult during this turn. Each handle provides a Done
// channel that delivers exactly one *ToolResult when the background
// goroutine finishes. Status remains ResponseStatusCompleted — background
// tasks do not change the response's terminal status.
//
// Use AwaitBackgroundTasks to block for all results, then pass them to
// the next CreateResponse call via WithBackgroundResults. For the simple
// interactive loop case, use ContinueWithBackground.
//
// Handles may be dropped without causing goroutine leaks: the background
// goroutine sends to its buffered channel (cap 1) and exits regardless of
// whether any caller reads the result.
BackgroundTasks []*BackgroundTaskHandle `json:"-"`
}
Response represents the output from an Agent's response generation.
func ContinueWithBackground ¶ added in v1.5.0
func ContinueWithBackground(ctx context.Context, agent *Agent, resp *Response, opts ...CreateResponseOption) (*Response, error)
ContinueWithBackground is the convenience wrapper for interactive loops. It awaits all background tasks on resp.BackgroundTasks, then calls agent.CreateResponse with the results injected. If resp.BackgroundTasks is empty, resp is returned unchanged. Additional opts (e.g. WithSession) are passed through.
Callers should loop until the returned response has no BackgroundTasks:
resp, err := agent.CreateResponse(ctx, dive.WithInput("run the test suite"))
for err == nil && len(resp.BackgroundTasks) > 0 {
resp, err = dive.ContinueWithBackground(ctx, agent, resp)
}
func (*Response) OutputText ¶
OutputText returns the answer text of the response: all of the text in the final message, or "" when there is no message or it has no text. It is llm.Message.AnswerText of that message: fragments of one passage (adjacent text blocks, such as Anthropic citation splits) are concatenated, and separate passages (text blocks with other content between them, or with different OpenAI phases) are joined with a blank line ("\n\n").
Text from earlier messages in the turn, such as "Let me check..." before a tool call, is not included. Read OutputMessages for the full turn.
func (*Response) ToolCallResults ¶
func (r *Response) ToolCallResults() []*ToolCallResult
ToolCallResults returns all tool call results from the response.
type ResponseItem ¶
type ResponseItem struct {
// Type of the response item
Type ResponseItemType `json:"type,omitempty"`
// Event is set if the response item is an event
Event *llm.Event `json:"event,omitempty"`
// Message is set if the response item is a message
Message *llm.Message `json:"message,omitempty"`
// ToolCall is set if the response item is a tool call
ToolCall *llm.ToolUseContent `json:"tool_call,omitempty"`
// ToolCallPreview is set on a tool call item when the tool implements
// ToolPreviewer, so a UI can show what the call is doing before it
// finishes. It is the same preview later set on ToolCallResult.Preview.
ToolCallPreview *ToolCallPreview `json:"tool_call_preview,omitempty"`
// ToolCallResult is set if the response item is a tool call result
ToolCallResult *ToolCallResult `json:"tool_call_result,omitempty"`
// ToolStream is set if the response item is streaming tool output
ToolStream *ToolStreamEvent `json:"tool_stream,omitempty"`
// ToolProgress is set if the response item is a structured progress snapshot.
ToolProgress *ToolProgressEvent `json:"tool_progress,omitempty"`
// Suspension is set on a ResponseItemTypeSuspended item. It mirrors
// Response.Suspension.
Suspension *SuspensionState `json:"suspension,omitempty"`
// Turn is set on a ResponseItemTypeTurnEnded item. It mirrors
// Response.Turn.
Turn *Turn `json:"turn,omitempty"`
// Extension holds optional data from experimental packages.
// The concrete type depends on the ResponseItemType.
Extension any `json:"extension,omitempty"`
// Usage contains token usage information, if applicable
Usage *llm.Usage `json:"usage,omitempty"`
}
ResponseItem contains either a message, tool call, tool result, or LLM event. Multiple items may be generated in response to a single prompt.
type ResponseItemType ¶
type ResponseItemType string
ResponseItemType represents the type of response item emitted during response generation.
Response items are delivered via the EventCallback during CreateResponse. They provide real-time visibility into the agent's activity including initialization, messages, tool calls, and streaming events.
const ( // ResponseItemTypeMessage indicates a complete message is available from the agent. // The Message field contains the full assistant message including any tool calls. ResponseItemTypeMessage ResponseItemType = "message" // ResponseItemTypeToolCall indicates a tool call is about to be executed. // The ToolCall field contains the tool name and input parameters. ResponseItemTypeToolCall ResponseItemType = "tool_call" // ResponseItemTypeToolCallResult indicates a tool call has completed. // The ToolCallResult field contains the tool output or error. ResponseItemTypeToolCallResult ResponseItemType = "tool_call_result" // ResponseItemTypeModelEvent indicates a streaming event from the LLM. // The Event field contains the raw LLM event for real-time UI updates. ResponseItemTypeModelEvent ResponseItemType = "model_event" // ResponseItemTypeToolStream indicates streaming output from a tool during execution. // The ToolStream field contains the tool call ID and a chunk of text. ResponseItemTypeToolStream ResponseItemType = "tool_stream" // ResponseItemTypeToolProgress indicates a structured progress snapshot // from a tool during execution. The ToolProgress field contains the tool // call ID and a *ToolProgress snapshot (Display/Metadata). Use this when // text-only ToolStream isn't enough — e.g. to render a live progress // widget with structured fields like exit_code or files_scanned. ResponseItemTypeToolProgress ResponseItemType = "tool_progress" // ResponseItemTypeSuspended is emitted when the agent transitions into a // suspended state, before ResponseItemTypeTurnEnded. The Suspension // field carries the same SuspensionState as Response.Suspension. // // Deprecated: use ResponseItemTypeTurnEnded, whose Turn.Suspension // carries the same state. ResponseItemTypeSuspended ResponseItemType = "suspended" // ResponseItemTypeTurnEnded is the terminal item of every invocation // that reached the turn boundary (see Response.Turn): completed, // suspended or incomplete. The Turn field mirrors Response.Turn. Stream // consumers treat it as end-of-stream. It is emitted after the session // write, on a context that is not cancelled; an error the callback // returns for it is logged and does not change the return. It is not // added to Response.Items. ResponseItemTypeTurnEnded ResponseItemType = "turn_ended" )
type ResponseStatus ¶ added in v1.5.0
type ResponseStatus string
ResponseStatus indicates the terminal state of a CreateResponse call.
const ( // ResponseStatusCompleted is the default: the agent finished normally. // An empty Status is treated as Completed for backward compatibility. ResponseStatusCompleted ResponseStatus = "completed" // ResponseStatusSuspended means one or more tool calls in the final // iteration returned SuspendResult. The agent has persisted the partial // turn to its session and expects a future CreateResponse call with // WithToolResults to supply the missing tool outputs. ResponseStatusSuspended ResponseStatus = "suspended" // ResponseStatusIncomplete means the turn stopped before it finished. // Response.Turn.Outcome says why and what can continue it. When an error // ended the turn, CreateResponse returns the response together with an // error that wraps a *GenerationError; when the model or its provider // stopped it short (an output limit, the iteration limit, ...), the // error is nil. The turn is closed and saved like any other: see // IncompleteTurnOptions and WithContinue. ResponseStatusIncomplete ResponseStatus = "incomplete" // ResponseStatusRunning is the status of a turn record an invocation is // still advancing, as a step checkpoint stores it // (DurabilityOptions.CheckpointSteps). CreateResponse never returns it. A // running turn found when a session loads was left by an invocation // that did not finish, and the agent closes it with // TurnReasonProcessExit. ResponseStatusRunning ResponseStatus = "running" )
type ResumeRequest ¶ added in v1.34.0
type ResumeRequest struct {
// TurnID is the suspended turn's Turn.ID (SuspensionState.TurnID).
// Empty skips the check.
TurnID string
// ExpectedRevision is the session revision the caller read the
// suspension at (Turn.Revision, SessionSnapshot.Revision). Zero skips
// the check.
ExpectedRevision uint64
// ToolResults are the results for pending calls, as for
// WithToolResults.
ToolResults map[string]*ToolResult
}
ResumeRequest resumes a suspended turn on a TurnStore session, naming the turn and the session revision the caller read it at, with the results it supplies. A stale turn or revision fails with ErrRevisionConflict before anything runs; the caller reloads the session and decides again.
type SchemaProperty ¶ added in v0.0.12
Type aliases for easy access to schema types used in tool definitions
type SchemaType ¶ added in v0.0.12
type SchemaType = schema.SchemaType
Type aliases for easy access to schema types used in tool definitions
const ( Object SchemaType = schema.Object Array SchemaType = schema.Array String SchemaType = schema.String Integer SchemaType = schema.Integer Number SchemaType = schema.Number Boolean SchemaType = schema.Boolean Null SchemaType = schema.Null )
SchemaType constants for JSON Schema types
type Session ¶ added in v1.0.0
type Session interface {
// ID returns a unique identifier for this session.
ID() string
// Messages returns the conversation history.
Messages(ctx context.Context) ([]*llm.Message, error)
// SaveTurn persists messages from a single turn. An incomplete turn is
// saved the same way; its last message records the outcome (see
// FindTurnOutcome). The agent calls it on a context without the
// cancellation that may have ended the turn, bounded by
// IncompleteTurnOptions.SaveTimeout. An error that wraps ErrSaveRejected
// says nothing was written.
SaveTurn(ctx context.Context, messages []*llm.Message, usage *llm.Usage) error
}
Session provides persistent conversation state across multiple turns. The agent calls Messages before generation to load history, and SaveTurn after generation to persist new messages.
Agents are stateless by default. Setting Session on AgentOptions or passing WithSession per-call enables automatic history loading and saving.
Concurrency ¶
Agent.CreateResponse serializes calls that share a session ID using an in-process per-ID lock, so two goroutines (or two agents) calling CreateResponse on the same session will run one after the other rather than interleaving their Messages() reads and SaveTurn writes. This is a correctness guarantee — implementations are not expected to coordinate concurrent access themselves. It is an in-process guarantee only; for multi-process deployments that share a session, use a backend with its own serialization (e.g. a database with row locks) rather than FileStore, which is single-writer-per-session by design.
type SessionClaimer ¶ added in v1.34.0
type SessionClaimer interface {
TurnStore
// ClaimSession claims the session for owner for ttl, or renews owner's
// claim. It fails with an error that wraps ErrSessionClaimed while
// another owner holds a claim that has not expired. Once it succeeds,
// Load reflects every write the store holds, including those another
// process made, and the store refuses a checkpoint through this session
// with ErrSessionClaimed if another owner claims the session after this
// claim expires.
ClaimSession(ctx context.Context, owner string, ttl time.Duration) error
// ReleaseSession ends owner's claim. Releasing a claim owner does not
// hold does nothing.
ReleaseSession(ctx context.Context, owner string) error
}
SessionClaimer is an optional TurnStore extension for execution ownership: several processes that run the agent on one session claim it before an invocation does any work, so that only one of them runs tools and writes to the session at a time. The in-process lock (LockSession) serializes invocations within one process only, and a revision conflict rejects a stale write only after both processes have run their tools.
A claim is a lease: it lasts until the owner releases it or its time to live passes, so a claim left by a process that exited expires. The agent claims the session when DurabilityOptions.Claim is set, renews the claim while the invocation runs, and releases it at the end.
type SessionSnapshot ¶ added in v1.34.0
type SessionSnapshot struct {
// History is the conversation before the open turn: every completed
// turn, and any incomplete turn later turns superseded, as the model
// sees them.
History []*llm.Message
// OpenTurn is the last turn when it is suspended, incomplete or
// running, and nil when it completed. Its Messages are closed; an
// incomplete turn's end with the outcome reminder. A running turn's are
// as the last step checkpoint left them: the calls it records as
// running have no result.
OpenTurn *Turn
// Revision is the session revision the snapshot was read at.
Revision uint64
// LatestOutcome is the outcome of the session's latest turn when that
// turn is incomplete, even when a compaction followed it and it is no
// longer open. Nil when the latest turn completed, is suspended or is
// running.
LatestOutcome *TurnOutcome
}
SessionSnapshot is what TurnStore.Load returns.
type SessionStartHook ¶ added in v1.6.0
type SessionStartHook func(ctx context.Context, hctx *HookContext) (*SessionStartResult, error)
SessionStartHook fires once at the start of a conversation — before the first LLM call — when the active session has no prior messages and the turn is NOT resuming a suspended one. It is not called on later turns of an existing session, nor on resume.
Use it to bootstrap a conversation from external state (project config, user preferences, memory) without a PreGenerationHook that manually inspects the history for emptiness. Return a *SessionStartResult whose Messages are prepended to the conversation; set Persist to choose durable vs ephemeral seeding (see SessionStartResult). Returning a nil result is a no-op. If a hook returns an error, CreateResponse returns that error immediately.
HookContext.SessionStartSource reports why the hook fired (see SessionStartSource).
Note: a stateless agent (no Session) has no prior messages on any call, so the hook fires on every CreateResponse. The trigger is "no prior messages on a non-resume turn", not "first ever call for this session object".
type SessionStartResult ¶ added in v1.6.0
type SessionStartResult struct {
// Messages are prepended to the conversation, ahead of the user input, so
// the model sees them on the first generation. An empty slice is a no-op.
Messages []*llm.Message
// Persist controls whether Messages are written to the session so they
// survive beyond the first generation:
//
// - true — durable seed context. Messages are saved as a pre-turn and
// remain in the conversation on every later turn and on resume
// (e.g. project config, user preferences, long-lived memory).
// - false — ephemeral priming. Messages influence only the first
// generation and are never saved; later turns do not see them.
//
// Persist requires a Session. Stateless calls (no Session) have nowhere to
// save to, so seeds are always ephemeral regardless of this flag.
Persist bool
}
SessionStartResult is returned by a SessionStartHook to seed a conversation before its first LLM call.
type SessionStartSource ¶ added in v1.6.0
type SessionStartSource string
SessionStartSource describes why SessionStart hooks are firing for a turn. It is reported on HookContext.SessionStartSource so a hook can tailor its seeding to the situation.
const ( // SessionStartStartup is a brand-new conversation: the active session has // no prior messages and the turn is not resuming a suspended one. It is the // only source the agent emits today; the field exists so future sources // (e.g. re-seeding after compaction) can reuse this hook without an API // change. SessionStartStartup SessionStartSource = "startup" )
type StopDecision ¶ added in v1.0.0
type StopDecision struct {
// Continue, when true, prevents the agent from stopping.
// The Reason is injected as a user message so the LLM knows
// why it should keep going.
Continue bool
// Reason is added to the conversation as a "stop-continuation" reminder
// that says the input arrived from the user. Leave it empty when the hook
// appended its own Recorded reminder with hctx.AppendReminder, for content
// that did not come from the user: the loop then re-enters with no
// stop-continuation message. Continue with an empty Reason and no
// appended Recorded reminder fails the turn with
// ErrStopContinueWithoutInput.
Reason string
}
StopDecision tells the agent what to do after a stop hook runs.
type StopHook ¶ added in v1.0.0
type StopHook func(ctx context.Context, hctx *HookContext) (*StopDecision, error)
StopHook is called when the agent is about to stop responding. A hook can prevent stopping by returning a StopDecision with Continue: true, which re-enters the generation loop. A non-empty Reason is injected as a user message. A hook that appended a Recorded reminder with hctx.AppendReminder may leave Reason empty: the loop then re-enters with only the appended reminders as new input.
hctx.StopHookActive is true when this stop check was triggered by a previous stop hook continuation. Check this to prevent infinite loops.
func PromptStopHook ¶ added in v1.6.0
PromptStopHook returns a StopHook that asks model whether the agent's work so far satisfies the task described by prompt. If the model answers ok=false, the agent keeps working with the model's reason as its next instruction.
It fails open: on a model or transport error the error is returned (Dive logs it and lets the agent stop), so a flaky judge never traps a turn. It honors hctx.StopHookActive — after forcing one continuation it steps aside, so the agent cannot loop forever on the judge's say-so.
Pass a cheap model (e.g. a small/fast one); this adds one call per stop.
type SuspendReason ¶ added in v1.5.0
type SuspendReason string
SuspendReason classifies why a tool suspended so that adapters (A2A, custom UIs) can project the correct external state without guessing. When empty, callers should treat the reason as SuspendReasonInput.
const ( // SuspendReasonInput means the agent needs information from the user // before it can continue. This is the default. SuspendReasonInput SuspendReason = "input_required" // SuspendReasonAuth means the agent is blocked on an authentication or // authorization step (OAuth flow, approval gate, etc.). SuspendReasonAuth SuspendReason = "auth_required" )
type SuspendResult ¶ added in v1.5.0
type SuspendResult struct {
// Prompt is optional human-readable text describing what the agent is
// waiting for. Surfaced to the caller via PendingToolCall.Prompt.
Prompt string `json:"prompt,omitempty"`
// Reason classifies the suspension. Surfaced to the caller via
// PendingToolCall.Reason. When empty, treated as SuspendReasonInput.
Reason SuspendReason `json:"reason,omitempty"`
// Metadata is optional structured data the tool wants to attach to the
// suspension so the caller can render a richer UI (request IDs, form
// URLs, expiration hints, etc.). It is surfaced via
// PendingToolCall.Metadata.
//
// Metadata values are round-tripped through JSON during deep-copy and
// persistence: numeric types come back as float64 and custom struct
// types become generic map[string]any. Stick to JSON-friendly values
// and expect that loss of type fidelity.
Metadata map[string]any `json:"metadata,omitempty"`
}
SuspendResult is the signal a tool returns to pause the agent mid-turn and hand control back to the caller. It is NOT an error — it is a first-class result type. The agent observes it, persists the partial turn, and returns a suspended Response. On resume, the caller supplies a real ToolResult for the suspended call via WithResume or WithToolResults.
type SuspendableSession ¶ added in v1.5.0
type SuspendableSession interface {
Session
// LoadSuspension returns the stored suspension state for this session,
// or nil if the session is not currently suspended. The returned value
// is a deep copy — mutations do not affect session internals.
LoadSuspension() *SuspensionState
// SaveSuspendedTurn persists a partial turn whose final tool_result
// message is missing one or more tool_result blocks, together with the
// SuspensionState that describes the pending work. Implementations
// should store the state so a subsequent LoadSuspension returns an
// equivalent value.
SaveSuspendedTurn(ctx context.Context, messages []*llm.Message, usage *llm.Usage, state *SuspensionState) error
// SaveResumedTurn replaces the last (suspended) event with the resumed
// turn, completed or closed incomplete, and clears the stored suspension
// state. Implementations should return an error if the session is not
// currently suspended.
SaveResumedTurn(ctx context.Context, messages []*llm.Message, usage *llm.Usage) error
// CancelSuspension abandons a suspended turn, clearing the suspension
// state and removing the partial turn from the session history.
// Returns ErrNotSuspended if the session is not currently suspended.
// After cancellation, the session is ready for a fresh turn as if the
// suspended turn never happened.
CancelSuspension(ctx context.Context) error
}
SuspendableSession is an optional extension of Session for callers who want suspend/resume state to be auto-persisted alongside the conversation history. A plain Session — or no session at all — also supports suspend/resume; in that case the caller manages the SuspensionState themselves via Response.Suspension and WithResume.
type SuspensionState ¶ added in v1.5.0
type SuspensionState struct {
// PendingToolCalls are the tool calls awaiting external results. On
// resume the caller must supply a ToolResult for each via
// WithResume/WithToolResults; partial resumes are allowed and remaining
// entries stay pending. Nil on a resume-completed SuspensionState.
PendingToolCalls []*PendingToolCall `json:"pending_tool_calls,omitempty"`
// CompletedToolCalls are tool calls that ran to completion in the same
// iteration as a suspending sibling, and the calls whose results a
// resume has since supplied, with the result as supplied. Their results
// are already in TurnMessages. A resume that supplies the same result
// again for one of these calls skips it; a different result fails with
// ErrConflictingToolResult.
CompletedToolCalls []*CompletedToolCall `json:"completed_tool_calls,omitempty"`
// TurnMessages is the complete set of messages that belong to the
// in-progress (or just-completed) turn, in order, including the user
// input that kicked it off and every assistant/tool_result message
// produced across all iterations of this turn. The agent rebuilds the
// full conversation on resume as preHistory + TurnMessages.
//
// On a resume-completed SuspensionState, TurnMessages reflects the
// final merged view (including the last merged tool_result and the
// final assistant message), so stateless callers can append it to
// their pre-turn history in one operation.
TurnMessages []*llm.Message `json:"turn_messages,omitempty"`
// BatchHalted records that a halting call in the suspended batch failed
// (see ToolAnnotations.HaltsBatch), so the batch's later halting calls
// are answered with ErrBatchHalted on resume. It is recorded rather than
// worked out again on resume, where the agent's tools may have changed.
BatchHalted bool `json:"batch_halted,omitempty"`
// TurnID is the suspended turn's Turn.ID, which a resume keeps. Empty
// for a state saved before Dive recorded turn IDs.
TurnID string `json:"turn_id,omitempty"`
// Usage is the suspended turn's usage so far, summed over every
// invocation of it. The agent adds it to Response.Turn.Usage when the
// turn is resumed. session.Session fills it from the suspended turn; a
// session that does not track it leaves it nil.
Usage *llm.Usage `json:"usage,omitempty"`
}
SuspensionState is the payload describing a suspended turn. It is populated on Response.Suspension whenever a CreateResponse call interacted with suspend/resume logic and is handed back to the agent via WithResume on the next call.
When Response.Suspension is populated ¶
SuspensionState is set on the Response in two situations:
- Status == ResponseStatusSuspended. The agent has paused mid-turn and at least one entry is in PendingToolCalls. TurnMessages carries the in-progress turn snapshot.
- Status == ResponseStatusCompleted on a call that resumed a previously suspended turn. PendingToolCalls is nil (all pending work was resolved). TurnMessages carries the final merged turn so stateless callers can flush it into their local history in one step without having to reconcile a stale partial tool_result from their saved state.
It is NOT populated on a plain completion that never involved suspend or resume.
Stateless caller pattern ¶
A caller managing history themselves holds two values: their pre-turn history and the most recent Response.Suspension (or nil). The pattern:
resp, _ := agent.CreateResponse(ctx,
dive.WithMessages(history...),
dive.WithResume(saved, toolResults), // omit if no active turn
)
if resp.Suspension != nil {
if len(resp.Suspension.PendingToolCalls) > 0 {
saved = resp.Suspension // still suspended
} else {
history = append(history, resp.Suspension.TurnMessages...)
saved = nil // turn committed
}
}
SuspendableSession implementations persist this state on the caller's behalf so session-backed callers only need to pass WithToolResults.
type TerminalDialog ¶ added in v1.0.0
type TerminalDialog struct {
// contains filtered or unexported fields
}
TerminalDialog implements Dialog using stdin/stdout.
func NewTerminalDialog ¶ added in v1.0.0
func NewTerminalDialog() *TerminalDialog
NewTerminalDialog creates a Dialog that prompts via stdin/stdout.
func NewTerminalDialogWithOptions ¶ added in v1.0.0
func NewTerminalDialogWithOptions(opts TerminalDialogOptions) *TerminalDialog
NewTerminalDialogWithOptions creates a Dialog with custom input/output.
func (*TerminalDialog) Show ¶ added in v1.0.0
func (d *TerminalDialog) Show(ctx context.Context, in *DialogInput) (*DialogOutput, error)
type TerminalDialogOptions ¶ added in v1.0.0
TerminalDialogOptions configures a TerminalDialog.
type Tool ¶
type Tool interface {
// Name of the tool.
Name() string
// Description of the tool.
Description() string
// Schema describes the parameters used to call the tool.
Schema() *Schema
// Annotations returns optional properties that describe tool behavior.
Annotations() *ToolAnnotations
// Call is the function that is called to use the tool.
Call(ctx context.Context, input any) (*ToolResult, error)
}
Tool is an interface for a tool that can be called by an LLM.
func FuncTool ¶ added in v1.0.0
func FuncTool[T any](name, description string, fn func(ctx context.Context, input T) (*ToolResult, error), opts ...FuncToolOption) Tool
FuncTool creates a Tool from a function with an auto-generated schema.
The schema is generated from the input type T using struct tags. Use json tags for field names, description tags for parameter descriptions, and omitempty to mark optional fields. See schema.Generate for all supported tags.
Example:
type WeatherInput struct {
City string `json:"city" description:"City name"`
Units string `json:"units,omitempty" description:"Temperature units" enum:"celsius,fahrenheit"`
}
weatherTool := dive.FuncTool("get_weather", "Get current weather",
func(ctx context.Context, input *WeatherInput) (*dive.ToolResult, error) {
return dive.NewToolResultText("72°F"), nil
},
)
type ToolAnnotations ¶
type ToolAnnotations struct {
Title string `json:"title,omitempty"`
ReadOnlyHint bool `json:"readOnlyHint,omitempty"`
DestructiveHint bool `json:"destructiveHint,omitempty"`
IdempotentHint bool `json:"idempotentHint,omitempty"`
OpenWorldHint bool `json:"openWorldHint,omitempty"`
EditHint bool `json:"editHint,omitempty"` // Indicates file edit operations for acceptEdits mode
// SequentialOnlyHint marks a tool as unsafe for parallel execution.
// When the agent has ParallelToolExecution enabled and a batch of tool
// calls includes ANY tool with this hint set, the entire batch falls back
// to sequential execution. Use for tools that mutate shared state (a
// working-directory chdir, a non-thread-safe SDK, a singleton resource).
// Default false = parallel-safe, matching the existing behavior.
SequentialOnlyHint bool `json:"sequentialOnlyHint,omitempty"`
// HaltsBatch chains the tool's calls within one model response, like
// shell commands joined by &&: once one fails, every later HaltsBatch
// call in that response is answered with an error saying it was not
// executed, without running its PreToolUse hooks or the tool. Use it for
// actions that depend on the ones before them, such as typing after the
// click that should have focused a field. Implies SequentialOnlyHint.
//
// A call fails when its result reaches the model as an error: the tool
// returned an IsError result or a Go error, a PreToolUse hook denied it,
// or a hook replaced its result with an error. Calls to tools without
// the annotation neither halt the batch nor are halted by it. Calls to a
// provider-defined toolset's members (llm.ToolUseContent.ToolsetName
// set) behave as if they carried HaltsBatch, since the provider's
// contract requires it. See ErrBatchHalted.
HaltsBatch bool `json:"haltsBatch,omitempty"`
Extra map[string]any `json:"extra,omitempty"`
}
ToolAnnotations contains optional metadata hints that describe a tool's behavior. These hints help agents and permission systems make decisions about tool usage.
func (*ToolAnnotations) MarshalJSON ¶
func (a *ToolAnnotations) MarshalJSON() ([]byte, error)
func (*ToolAnnotations) UnmarshalJSON ¶
func (a *ToolAnnotations) UnmarshalJSON(data []byte) error
type ToolCallInfo ¶ added in v1.5.0
type ToolCallInfo struct {
// Agent is the agent handling the run.
Agent *Agent
// Session is the active session, or nil for stateless calls.
Session Session
// Tool is the tool that will be invoked.
Tool Tool
// Call carries the tool name, call ID, and JSON arguments.
Call *llm.ToolUseContent
}
ToolCallInfo describes a tool invocation at the moment it begins.
type ToolCallPreview ¶ added in v0.0.12
type ToolCallPreview struct {
// Summary is a short description of what the tool will do, e.g., "Fetch https://example.com"
Summary string `json:"summary"`
// Details is optional longer markdown with more context about the operation.
Details string `json:"details,omitempty"`
}
ToolCallPreview contains human-readable information about a pending tool call.
type ToolCallRecord ¶ added in v1.34.0
type ToolCallRecord struct {
ID string `json:"id"`
Name string `json:"name"`
State ToolCallState `json:"state"`
}
ToolCallRecord is what is known about one tool call of a turn.
type ToolCallResult ¶
type ToolCallResult struct {
ID string
Name string
Input any
Preview *ToolCallPreview // Preview generated before execution (if tool implements ToolPreviewer)
Result *ToolResult // Protocol-level result sent to the LLM
Error error // Go error from tool.Call() or dispatch, including UnknownToolError, ErrBatchHalted, ErrToolCallNotRun and ErrToolCallUnknown
AdditionalContext string // Context injected by hooks, appended to the tool result message
BackgroundHandle *BackgroundTaskHandle // Non-nil when the tool returned BackgroundResult
// contains filtered or unexported fields
}
ToolCallResult is a tool call that has been made. This is used to understand what calls have happened during an LLM interaction.
Error and Result.IsError track different failure modes:
- Error is a Go-level execution or dispatch error, such as tool.Call() failing unexpectedly or an unknown tool name. Inspect typed errors with errors.As when the distinction matters.
- Result.IsError is a protocol-level flag — the tool ran but reported a failure to the LLM (e.g. via NewToolResultError). Both are surfaced to the LLM as an error result.
type ToolCallSpan ¶ added in v1.5.0
type ToolCallSpan interface {
// SetResult records the tool's result. Called before End for both
// success and tool-reported-error paths; not called when the tool panics
// or the agent itself fails to invoke it.
SetResult(*ToolCallResult)
// End marks the call as finished. err is non-nil only when the agent
// failed to invoke the tool (e.g. panic, missing tool); a tool that
// returned IsError=true reports success here and the failure on the
// result.
End(err error)
}
ToolCallSpan represents an in-flight tool-call observation. The agent calls End exactly once.
type ToolCallState ¶ added in v1.34.0
type ToolCallState string
ToolCallState is what is known about a tool call.
const ( // ToolCallStateCompleted: a result is recorded, success or tool error. ToolCallStateCompleted ToolCallState = "completed" // ToolCallStateNotStarted: the call never started; it had no effect. ToolCallStateNotStarted ToolCallState = "not_started" // ToolCallStateUnknown: the call started and no result was recorded; it // may have taken effect. ToolCallStateUnknown ToolCallState = "unknown" // ToolCallStateWaiting: the call suspended and its turn is waiting for // its result (SuspensionState.PendingToolCalls). ToolCallStateWaiting ToolCallState = "waiting" // ToolCallStateRunning: a step checkpoint recorded the call as started // and no result yet. Only a running turn has such a call; when the turn // is closed, the call is unknown. ToolCallStateRunning ToolCallState = "running" )
type ToolDeclarer ¶ added in v1.33.0
type ToolDeclarer interface {
// DeclaredTools returns the names of the tools this tool's definition
// declares.
DeclaredTools() []string
}
ToolDeclarer is implemented by a tool whose provider definition declares other tools too, such as anthropic.ComputerToolset, which declares left_click, screenshot and the rest of Anthropic's computer actions.
The model calls a declared tool by its own name, and the agent runs the call with the Tool of that name, like any other call; that Tool is also what permission rules and hooks see. While the declarer is among the tools sent to the model, the agent leaves the tools it declares out of the request, since the provider already has their definitions. Without the declarer they are sent as ordinary tools, so the same tools serve a model that takes the provider's toolset and one that doesn't.
type ToolPreviewer ¶ added in v0.0.12
type ToolPreviewer interface {
// PreviewCall returns a markdown description of what the tool will do
// given the input. The input is the same type passed to Call().
PreviewCall(ctx context.Context, input any) *ToolCallPreview
}
ToolPreviewer is an optional interface that tools can implement to provide human-readable previews of what they will do before execution.
type ToolProgress ¶ added in v1.6.0
type ToolProgress struct {
// Display is a human-readable markdown summary of the latest progress
// state, e.g. "47/100 files scanned, 2.3 MB".
Display string `json:"display,omitempty"`
// Metadata is arbitrary structured progress data: exit_code, duration_ms,
// files_scanned, bytes_read, percent_complete, etc. Consumers (TUIs,
// audit logs, eval harnesses) read this to render live progress widgets
// or score partial outputs. JSON-friendly values only.
Metadata map[string]any `json:"metadata,omitempty"`
}
ToolProgress is a structured progress snapshot a tool may emit during execution via ReportProgress(ctx, *ToolProgress). Use it when text-only StreamOutput isn't enough — e.g. to surface a running exit code, byte count, or percent-complete to UIs and evaluators before the tool returns.
Each snapshot is latest-wins, NOT a delta: every Display/Metadata replaces the previous one. Text deltas belong on StreamOutput, which appends. The two are independent channels — a tool may use either, both, or neither. The agent re-emits each snapshot as a ResponseItem of type ResponseItemTypeToolProgress; consumers receive it through the EventCallback configured on the CreateResponse call.
Delivered in-process, Metadata preserves its Go types. A consumer that serializes the event itself gets JSON's usual coercions (numbers become float64, structs become map[string]any), so stick to JSON-friendly values.
type ToolProgressEvent ¶ added in v1.6.0
type ToolProgressEvent struct {
ToolCallID string `json:"tool_call_id"`
Progress *ToolProgress `json:"progress"`
}
ToolProgressEvent contains a structured progress snapshot emitted by a tool during execution via ReportProgress. Distinct from ToolStreamEvent, which carries text deltas; each snapshot is latest-wins in-progress state.
type ToolResult ¶
type ToolResult struct {
// Content is the tool output sent to the LLM.
Content []*ToolResultContent `json:"content"`
// Display is an optional human-readable markdown summary of the result.
// If empty, consumers should fall back to Content for display.
Display string `json:"display,omitempty"`
// IsError indicates whether the tool call resulted in an error.
IsError bool `json:"isError,omitempty"`
// Suspend, when non-nil, tells the agent to suspend its turn rather than
// send this tool result to the LLM. Must be the only field set on the
// ToolResult (no Content, no Display, no IsError). Use NewSuspendResult
// to construct.
Suspend *SuspendResult `json:"suspend,omitempty"`
// Background, when non-nil, tells the agent that work has been dispatched
// to a background goroutine. The goroutine sends exactly one *ToolResult
// to Background.done when it finishes. Must be the only field set on the
// ToolResult. Use NewBackgroundResult or NewBackgroundResultFull to construct.
Background *backgroundResult `json:"-"`
}
ToolResult is the output from a tool call.
ToolResult is a tagged union between a normal result (Content / Display / IsError), a suspend result (Suspend), and a background result (Background). A single ToolResult must set exactly one of the three — either the regular fields OR Suspend OR Background, never multiple. The agent validates this at the boundary and a malformed result is surfaced as an IsError result routed through the PostToolUseFailure hook chain. Use NewToolResult*/NewSuspendResult*/ NewBackgroundResult* constructors rather than filling the fields directly.
func NewBackgroundResult ¶ added in v1.5.0
func NewBackgroundResult(ctx context.Context, description string, fn func(ctx context.Context) (string, error)) *ToolResult
NewBackgroundResult is the primary constructor for starting a background task from a tool. fn receives a context derived from the tool's execution context so cancellation propagates. The goroutine and channel are managed by Dive.
Example:
func (t *BuildTool) Call(ctx context.Context, input *BuildInput) (*dive.ToolResult, error) {
return dive.NewBackgroundResult(ctx, "building project", func(ctx context.Context) (string, error) {
output, err := runBuild(ctx, input.Target)
if err != nil {
return "", err
}
return output, nil
}), nil
}
func NewBackgroundResultFull ¶ added in v1.5.0
func NewBackgroundResultFull(ctx context.Context, description string, fn func(ctx context.Context) *ToolResult) *ToolResult
NewBackgroundResultFull is the advanced constructor for tools that need full control over the result (setting IsError, Display, or structured content).
Example:
return dive.NewBackgroundResultFull(ctx, "running tests", func(ctx context.Context) *dive.ToolResult {
out, err := runTests(ctx)
if err != nil {
return dive.NewToolResultError(err.Error())
}
return dive.NewToolResultText(out).WithDisplay("# Test Results\n" + out)
}), nil
func NewSuspendResult ¶ added in v1.5.0
func NewSuspendResult(prompt string, metadata map[string]any) *ToolResult
NewSuspendResult returns a *ToolResult whose Suspend field is set. Use it from a tool's Call method; pass nil for metadata if none is needed:
return dive.NewSuspendResult("Waiting for approval from @alice", nil), nil
return dive.NewSuspendResult("Waiting for approval", map[string]any{
"request_id": requestID,
"form_url": url,
}), nil
func NewSuspendResultWithReason ¶ added in v1.5.0
func NewSuspendResultWithReason(prompt string, reason SuspendReason, metadata map[string]any) *ToolResult
NewSuspendResultWithReason is like NewSuspendResult but sets a reason classifying why the tool suspended:
return dive.NewSuspendResultWithReason("Sign in to continue",
dive.SuspendReasonAuth, map[string]any{"auth_url": url}), nil
func NewToolResult ¶
func NewToolResult(content ...*ToolResultContent) *ToolResult
NewToolResult creates a new ToolResult with the given content.
func NewToolResultError ¶
func NewToolResultError(text string) *ToolResult
NewToolResultError creates a new ToolResult containing an error message.
func NewToolResultText ¶
func NewToolResultText(text string) *ToolResult
NewToolResultText creates a new ToolResult with the given text content.
func (*ToolResult) WithDisplay ¶ added in v0.0.12
func (r *ToolResult) WithDisplay(display string) *ToolResult
WithDisplay sets the Display field and returns the receiver for chaining.
type ToolResultContent ¶
type ToolResultContent struct {
Type ToolResultContentType `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Annotations map[string]any `json:"annotations,omitempty"`
}
ToolResultContent is a single content block within a tool result, such as text output, an image, or audio data.
type ToolResultContentType ¶
type ToolResultContentType string
ToolResultContentType indicates the media type of a tool result content block.
const ( ToolResultContentTypeText ToolResultContentType = "text" ToolResultContentTypeImage ToolResultContentType = "image" ToolResultContentTypeAudio ToolResultContentType = "audio" )
func (ToolResultContentType) String ¶
func (t ToolResultContentType) String() string
type ToolStreamEvent ¶ added in v1.5.0
ToolStreamEvent contains a chunk of streaming output from a tool.
type Toolset ¶ added in v1.0.0
type Toolset interface {
// Name identifies this toolset for logging and debugging.
Name() string
// Tools returns the tools available in the current context.
// Called before each LLM request. Implementations should cache tool
// instances and avoid re-creating them on every call.
Tools(ctx context.Context) ([]Tool, error)
}
Toolset provides dynamic tool resolution. Tools() is called before each LLM request, allowing the available tools to vary based on runtime context. Use toolsets for MCP servers, permission-filtered tools, or context-dependent tool availability.
type ToolsetFunc ¶ added in v1.0.0
type ToolsetFunc struct {
// ToolsetName identifies this toolset.
ToolsetName string
// Resolve returns the tools for the current context.
Resolve func(ctx context.Context) ([]Tool, error)
}
ToolsetFunc adapts a function into a Toolset.
func (*ToolsetFunc) Name ¶ added in v1.0.0
func (f *ToolsetFunc) Name() string
Name returns the toolset name.
type Tracer ¶ added in v1.5.0
type Tracer interface {
// StartAgentRun is called once per CreateResponse. Implementations should
// open a root operation span (or equivalent) and return a derived ctx that
// carries it. The agent threads that ctx into every downstream call so
// chat and tool spans nest under it.
StartAgentRun(ctx context.Context, info AgentRunInfo) (context.Context, AgentRunSpan)
// StartChat is called once per LLM iteration, before the model is invoked.
// The returned ctx is passed into LLM.Generate / LLM.Stream so any spans
// the provider's HTTP client emits (e.g. via otelhttp middleware) nest
// under the chat span.
StartChat(ctx context.Context, info ChatInfo) (context.Context, ChatSpan)
// StartToolCall is called once per tool invocation, before Tool.Call. The
// returned ctx is passed into Tool.Call so any spans the tool's internals
// emit nest under the execute_tool span.
StartToolCall(ctx context.Context, info ToolCallInfo) (context.Context, ToolCallSpan)
}
Tracer observes an agent's lifecycle. The agent calls the Start* methods at each lifecycle boundary and threads the returned context into the operation that follows, so spans created by the tracer naturally nest under their caller.
Tracer is the right shape for observation (tracing, metrics, audit logging). It is intentionally separate from the hook system, which handles modification (rewriting prompts, denying tool calls, injecting context).
Implementations live in adapter packages — see the dive/otel module for the OpenTelemetry adapter. NopTracer is the default.
func MultiTracer ¶ added in v1.5.0
MultiTracer fans Start* calls out to N tracers and returns a span whose methods fan out in turn. The ctx returned by the first tracer is the input to the next, so each tracer's span context layers on top of the previous — independent tracing systems can coexist without trampling each other.
Nil entries are filtered out. MultiTracer of zero non-nil tracers is equivalent to NopTracer.
type Turn ¶ added in v1.34.0
type Turn struct {
// Schema versions the record; TurnSchema for records this version of
// Dive writes.
Schema int `json:"schema,omitempty"`
// ID identifies the turn across the invocations that advance it: a
// resume and a continuation of an open turn on a TurnStore keep it. A
// tool reads it with TurnID(ctx), for example as part of an idempotency
// key.
ID string `json:"id,omitempty"`
// Revision is the session revision at which a TurnStore last
// checkpointed the record, or zero when it was not checkpointed. Pass
// it back as ResumeRequest.ExpectedRevision.
Revision uint64 `json:"revision,omitempty"`
// Origin says what started the turn. Nil when it is not known, as for a
// turn resumed from a SuspensionState alone.
Origin *TurnOrigin `json:"origin,omitempty"`
// Status is the turn's state as this invocation left it: completed,
// suspended or incomplete. It is Response.Status. A step checkpoint
// stores a turn still in progress as running.
Status ResponseStatus `json:"status,omitempty"`
// Messages is what a session saves for this invocation, closed so it
// can be sent again. For a fresh turn it is the input and the output,
// including a synthetic background-results message, which
// OutputMessages does not carry. For a resume it is the whole suspended
// turn merged with this invocation's output, since the session replaces
// the suspended event. For a continuation (WithContinue) of an open
// turn on a TurnStore it is the whole turn: the open turn without its
// outcome reminder, then this invocation's output. For any other
// continuation it is the output alone. A stateless caller appends it to
// the history it held before the call (before the suspended turn, on a
// resume).
Messages []*llm.Message `json:"messages"`
// Usage is the turn's usage: this invocation's model calls, plus, on a
// resume, what the suspended turn had accumulated
// (SuspensionState.Usage). It is never nil. Response.Usage is this
// invocation's alone, which is what a session is handed.
Usage *llm.Usage `json:"usage,omitempty"`
// Outcome is set when Status is ResponseStatusIncomplete.
Outcome *TurnOutcome `json:"outcome,omitempty"`
// Suspension is set when Status is ResponseStatusSuspended. It is the
// same value as Response.Suspension.
Suspension *SuspensionState `json:"suspension,omitempty"`
// ToolCalls is the state of every client tool call in the turn, in
// order: completed, waiting for a result on a suspended turn,
// not_started, or unknown, and running in a step checkpoint.
ToolCalls []ToolCallRecord `json:"tool_calls,omitempty"`
// Superseded is set on an incomplete turn that later turns followed
// without continuing it: it was abandoned, its record intact. Set by a
// TurnStore on the records it lists; the agent never sets it.
Superseded bool `json:"superseded,omitempty"`
// Persistence says whether a session recorded this state.
Persistence PersistenceState `json:"persistence"`
}
Turn is the record of one turn as the invocation that returned it left it: the unit a session saves and a stateless caller appends to its history. It is set on Response.Turn for every status once the turn has begun, and on the terminal ResponseItemTypeTurnEnded item. A TurnStore stores it as the turn's record (TurnStore.CheckpointTurn).
type TurnNext ¶ added in v1.34.0
type TurnNext string
TurnNext says what an incomplete turn needs next.
const ( // TurnNextContinue: another model call on the history as it stands. TurnNextContinue TurnNext = "continue" // TurnNextReconcile: a call with an unknown result must be checked // before the model is called again. TurnNextReconcile TurnNext = "reconcile" // TurnNextInput: nothing to continue; the next move is the user's. TurnNextInput TurnNext = "input" )
type TurnOrigin ¶ added in v1.34.0
type TurnOrigin struct {
Kind TurnOriginKind `json:"kind"`
// TurnID links a turn started by background results to the turn that
// started the task.
TurnID string `json:"turn_id,omitempty"`
}
TurnOrigin says what started a turn.
type TurnOriginKind ¶ added in v1.34.0
type TurnOriginKind string
TurnOriginKind is what started a turn.
const ( // TurnOriginInput: new input. TurnOriginInput TurnOriginKind = "input" // TurnOriginContinue: WithContinue with no open turn to continue, or on // a session that is not a TurnStore. TurnOriginContinue TurnOriginKind = "continue" // TurnOriginBackground: delivered background results // (WithBackgroundResults). TurnOriginBackground TurnOriginKind = "background" )
type TurnOutcome ¶ added in v1.34.0
type TurnOutcome struct {
// Reason says what stopped the turn.
Reason TurnReason `json:"reason"`
// Error is the error that ended the invocation, as text, or the raw
// stop reason for TurnReasonProviderStopped. An OnIncompleteTurn hook
// may rewrite it before it is saved, for example to remove a request ID
// from a provider error.
Error string `json:"error,omitempty"`
// Hook is the hook type ("PreToolUse", "Stop", ...) for
// TurnReasonHookAbort.
Hook string `json:"hook,omitempty"`
// UsageUnknown is set when a model call's usage could not be observed,
// as when a stream died before its usage arrived, so a zero usage is
// not a measurement.
UsageUnknown bool `json:"usage_unknown,omitempty"`
// ToolCalls records every call of the batch in flight when the turn
// stopped, in call order, with what is known about it. Empty when the
// turn stopped between batches.
ToolCalls []ToolCallRecord `json:"tool_calls,omitempty"`
// Next says what the turn needs: another model call on the record as it
// stands, reconciliation of a call with an unknown result first, or new
// input because there is nothing to continue. It is TurnNextReconcile
// whenever a call in ToolCalls is unknown and its tool is not annotated
// ReadOnlyHint. Advisory: the application decides.
Next TurnNext `json:"next"`
}
TurnOutcome says how an incomplete turn stopped and what can continue it. It is set on Response.Turn.Outcome, given to OnIncompleteTurn hooks, and recorded as the details of the turn-incomplete reminder that closes the turn (see FindTurnOutcome).
func FindLatestTurnOutcome ¶ added in v1.34.0
func FindLatestTurnOutcome(messages []*llm.Message) (*TurnOutcome, bool)
FindLatestTurnOutcome returns the most recent outcome recorded in messages, searching from newest to oldest.
func FindTurnOutcome ¶ added in v1.34.0
func FindTurnOutcome(message *llm.Message) (*TurnOutcome, bool)
FindTurnOutcome returns the outcome recorded in a message by the turn-incomplete reminder, if it has one.
type TurnReason ¶ added in v1.34.0
type TurnReason string
TurnReason says what stopped an incomplete turn.
const ( // TurnReasonCanceled: the context was cancelled, or a soft cancel was // requested (WithSoftCancel). The error wraps context.Canceled. TurnReasonCanceled TurnReason = "canceled" // TurnReasonDeadline: the context's deadline passed, including // AgentOptions.ResponseTimeout. The error wraps context.DeadlineExceeded. TurnReasonDeadline TurnReason = "deadline" // TurnReasonProviderError: a model call failed, after the provider's // own retries, before its response began to stream. TurnReasonProviderError TurnReason = "provider_error" // TurnReasonStreamInterrupted: a model response stopped streaming // before it finished. TurnReasonStreamInterrupted TurnReason = "stream_interrupted" // TurnReasonHookAbort: a hook returned a *HookAbortError. TurnReasonHookAbort TurnReason = "hook_abort" // TurnReasonCallbackError: the event callback returned an error. TurnReasonCallbackError TurnReason = "callback_error" // TurnReasonError: any other error; TurnOutcome.Error says which. TurnReasonError TurnReason = "error" // TurnReasonOutputLimit: the model stopped at its output limit // (max_tokens). The answer is valid as far as it goes; its tool calls // were not run. TurnReasonOutputLimit TurnReason = "output_limit" // TurnReasonContextLimit: the response filled the model's context // window. The same history cannot be sent again as it is: shorten it // before continuing. TurnReasonContextLimit TurnReason = "context_limit" // TurnReasonIterationLimit: the model still requested tool calls when // AgentOptions.ToolIterationLimit was reached. They were not run. TurnReasonIterationLimit TurnReason = "iteration_limit" // TurnReasonProviderStopped: the provider ended the response early for // a reason it did not name as a limit or a refusal, or with a stop // reason Dive does not recognize on a response that requested tool // calls. TurnOutcome.Error is the raw stop reason; no call was run. TurnReasonProviderStopped TurnReason = "provider_stopped" // TurnReasonPause: a server tool loop paused (pause_turn) more times // than the agent continues it in one invocation. TurnReasonPause TurnReason = "pause" // TurnReasonProcessExit: the invocation advancing the turn ended without // recording how the turn ended, as when its process exited. The agent // sets it when it loads a turn a step checkpoint left running // (DurabilityOptions.CheckpointSteps); the calls recorded as running // are unknown. TurnReasonProcessExit TurnReason = "process_exit" )
type TurnStore ¶ added in v1.34.0
type TurnStore interface {
Session
// Load returns the history needed to build context, the open turn if
// any (suspended, incomplete, or running when a step checkpoint left
// it), and the session revision a later checkpoint must carry.
Load(ctx context.Context) (*SessionSnapshot, error)
// CheckpointTurn records the turn's state and returns the new session
// revision. A turn whose ID is the open turn's replaces it; any other
// turn is added after it. It fails with an error that wraps
// ErrRevisionConflict when the stored revision is not expectedRevision,
// and the caller reloads. The revision is the session's, advanced by
// every write (a checkpoint, a save, a compaction, a removal), so a
// checkpoint fails when anything changed since the load. The store
// keeps its own copy of turn.
//
// It is also how a caller imports a turn it holds, such as a
// Response.Turn from another process, with the same conflict check.
CheckpointTurn(ctx context.Context, expectedRevision uint64, turn *Turn) (uint64, error)
}
TurnStore is an optional Session extension that stores turn records. The agent loads the history and the open turn from it at the start of every invocation (Load), and records the turn at the end (CheckpointTurn) in place of SaveTurn, SaveSuspendedTurn and SaveResumedTurn. An incomplete turn stays open, and a WithContinue invocation folds into it instead of adding a turn of its own. session.Session implements it.
With DurabilityOptions.CheckpointSteps the agent also checkpoints the turn at each step of the invocation, with ResponseStatusRunning. A store that supports this should append each such checkpoint rather than rewrite the session, since there is one per model response and tool call.
Load takes a context and returns an error, unlike LoadSuspension, so a remote store can implement it.
type TypedTool ¶
type TypedTool[T any] interface { // Name of the tool. Name() string // Description of the tool. Description() string // Schema describes the parameters used to call the tool. Schema() *Schema // Annotations returns optional properties that describe tool behavior. Annotations() *ToolAnnotations // Call is the function that is called to use the tool. Call(ctx context.Context, input T) (*ToolResult, error) }
TypedTool is a tool that can be called with a specific type of input.
type TypedToolAdapter ¶
type TypedToolAdapter[T any] struct { // contains filtered or unexported fields }
TypedToolAdapter is an adapter that allows a TypedTool to be used as a regular Tool. Specifically the Call method accepts `input any` and then internally unmarshals the input to the correct type and passes it to the TypedTool.
func ToolAdapter ¶
func ToolAdapter[T any](tool TypedTool[T]) *TypedToolAdapter[T]
ToolAdapter creates a new TypedToolAdapter for the given tool.
func (*TypedToolAdapter[T]) Annotations ¶
func (t *TypedToolAdapter[T]) Annotations() *ToolAnnotations
func (*TypedToolAdapter[T]) Call ¶
func (t *TypedToolAdapter[T]) Call(ctx context.Context, input any) (*ToolResult, error)
func (*TypedToolAdapter[T]) Description ¶
func (t *TypedToolAdapter[T]) Description() string
func (*TypedToolAdapter[T]) Name ¶
func (t *TypedToolAdapter[T]) Name() string
func (*TypedToolAdapter[T]) PreviewCall ¶ added in v0.0.12
func (t *TypedToolAdapter[T]) PreviewCall(ctx context.Context, input any) *ToolCallPreview
PreviewCall implements ToolPreviewer by delegating to the underlying TypedTool if it implements TypedToolPreviewer[T].
func (*TypedToolAdapter[T]) Schema ¶
func (t *TypedToolAdapter[T]) Schema() *Schema
func (*TypedToolAdapter[T]) ToolConfiguration ¶
func (t *TypedToolAdapter[T]) ToolConfiguration(providerName string) map[string]any
ToolConfiguration delegates to the underlying tool's ToolConfiguration method if it implements the llm.ToolConfiguration interface.
func (*TypedToolAdapter[T]) Unwrap ¶
func (t *TypedToolAdapter[T]) Unwrap() TypedTool[T]
Unwrap returns the underlying TypedTool.
type TypedToolPreviewer ¶ added in v0.0.12
type TypedToolPreviewer[T any] interface { // PreviewCall returns a markdown description of what the tool will do. PreviewCall(ctx context.Context, input T) *ToolCallPreview }
TypedToolPreviewer is an optional interface that typed tools can implement to provide human-readable previews with typed input.
type UnknownToolError ¶ added in v1.21.0
UnknownToolError reports a tool call whose name matched nothing in the toolset declared for the request. No tool was dispatched.
func (*UnknownToolError) Error ¶ added in v1.21.0
func (e *UnknownToolError) Error() string
type UserFeedbackError ¶ added in v1.0.0
type UserFeedbackError struct {
Feedback string
}
UserFeedbackError wraps user-provided feedback when they deny a tool call. This allows distinguishing user feedback from actual errors.
func (*UserFeedbackError) Error ¶ added in v1.0.0
func (e *UserFeedbackError) Error() string
Source Files
¶
- agent.go
- agent_unknown_tool.go
- background.go
- closeturn.go
- context.go
- dialog.go
- dialog_terminal.go
- dive.go
- doc.go
- durability.go
- hookjudgment.go
- hooks.go
- model_settings.go
- outcome.go
- reminder.go
- response.go
- schema.go
- softcancel.go
- state.go
- system_reminder.go
- taskbudget.go
- tool.go
- tool_input_canonical.go
- toolbatch.go
- tracer.go
- turn.go
- utilities.go
Directories
¶
| Path | Synopsis |
|---|---|
|
a2a
module
|
|
|
demos
|
|
|
colosseum
module
|
|
|
examples
module
|
|
|
experimental
|
|
|
sandbox/proxy
Package proxy provides a simple HTTP/HTTPS proxy that enforces a domain allowlist.
|
Package proxy provides a simple HTTP/HTTPS proxy that enforces a domain allowlist. |
|
toolkit/extended
Package extended provides extended tools for AI agents.
|
Package extended provides extended tools for AI agents. |
|
cmd/dive
module
|
|
|
mcp
module
|
|
|
internal
|
|
|
procgroup
Package procgroup makes CommandContext cancellation end a shell command's whole process tree.
|
Package procgroup makes CommandContext cancellation end a shell command's whole process tree. |
|
tokenest
Package tokenest estimates the tokens of messages without a tokenizer.
|
Package tokenest estimates the tokens of messages without a tokenizer. |
|
toolimagetest
Package toolimagetest checks, against a live model, that an image a tool returns reaches the model.
|
Package toolimagetest checks, against a live model, that an image a tool returns reaches the model. |
|
Package llm defines the unified abstraction layer over different LLM providers.
|
Package llm defines the unified abstraction layer over different LLM providers. |
|
Package media provides unified multi-provider image and video generation.
|
Package media provides unified multi-provider image and video generation. |
|
otel
module
|
|
|
Package permission provides tool permission management for Dive agents.
|
Package permission provides tool permission management for Dive agents. |
|
Package providers contains the LLM provider registry, shared error types, and helpers for provider implementations.
|
Package providers contains the LLM provider registry, shared error types, and helpers for provider implementations. |
|
deepinfra
Package deepinfra provides DeepInfra's OpenAI-compatible Chat Completions API.
|
Package deepinfra provides DeepInfra's OpenAI-compatible Chat Completions API. |
|
modelcaps
Package modelcaps records which reasoning and sampling parameters each model accepts, so providers can clamp or drop a setting a model cannot take instead of sending a request the API will reject.
|
Package modelcaps records which reasoning and sampling parameters each model accepts, so providers can clamp or drop a setting a model cannot take instead of sending a request the API will reject. |
|
modelcatalog
Package modelcatalog defines the embedded provider catalog format used by Dive.
|
Package modelcatalog defines the embedded provider catalog format used by Dive. |
|
google
module
|
|
|
grok
module
|
|
|
meta
module
|
|
|
openai
module
|
|
|
Package session provides persistent conversation state for Dive agents.
|
Package session provides persistent conversation state for Dive agents. |
|
Package skill provides production-quality support for agent skills and slash commands.
|
Package skill provides production-quality support for agent skills and slash commands. |
|
Package subagent defines specialized subagents that a parent agent can spawn via the Agent tool (see toolkit/orchestration).
|
Package subagent defines specialized subagents that a parent agent can spawn via the Agent tool (see toolkit/orchestration). |
|
Package toolkit provides a collection of tools for AI agents to interact with the local filesystem, execute shell commands, search the web, and communicate with users.
|
Package toolkit provides a collection of tools for AI agents to interact with the local filesystem, execute shell commands, search the web, and communicate with users. |
|
firecrawl
Package firecrawl provides a client for the Firecrawl v2 API.
|
Package firecrawl provides a client for the Firecrawl v2 API. |
|
orchestration
Package orchestration provides tools for spawning subagents and controlling background runs, aligned with Claude Code's tool model:
|
Package orchestration provides tools for spawning subagents and controlling background runs, aligned with Claude Code's tool model: |