Documentation
¶
Overview ¶
Package agentic builds AI agents in Go: tool use, structured output, streaming, resumable execution, and multi-agent delegation, over a provider interface rather than a vendor SDK.
The two halves ¶
Agentic covers two problems that share providers but nothing else. Chat is the agent loop — Agent sends a conversation to a Model, executes the tools the model asks for, and folds the results back until the model stops. Retrieval is the vector side — Embedder turns text into dense vectors, RepresentationEncoder returns dense, learned sparse, and token multi-vector forms from one call, and Reranker scores query-document pairs directly.
Nothing on one side depends on the other. A program that only embeds never constructs an agent, and the split is real in the source: the chat types live in internal/core and the retrieval types in internal/retrieval, with no reference between them. This package re-exports both so that callers import one path, and the aliases are the only place the halves meet.
Providers ¶
Every provider lives under provider/ and declares what it implements with a compile-time assertion, because capability is not one-to-one: bedrock is a model and an embedder, cohere an embedder and a reranker. The README carries the table of which provider does what, and a test in this package fails if a provider stops declaring it.
Getting started ¶
model, err := openai.New("gpt-4o")
agent := agentic.NewAgent("You are a helpful assistant.", model)
result, err := agent.Run(ctx, "What is the capital of France?")
See ARCHITECTURE.md in the repository for where each kind of code lives, and the README for worked examples of each feature.
Index ¶
- Constants
- Variables
- func AddHandoff[T toolTarget](target T, handoff *Handoff) T
- func AddHandoffWithDeps[D any, T dependencyToolTarget[D]](target T, handoff *HandoffWithDeps[D]) T
- func AddTool[T toolTarget, TInput, TOutput any](target T, handler func(context.Context, TInput) (TOutput, error), ...) T
- func AddToolPlain[T toolTarget, TInput, TOutput any](target T, handler func(TInput) (TOutput, error), opts ...AutoToolOption) T
- func AddToolWithContext[T toolTarget, TInput, TOutput any](target T, handler func(context.Context, TInput) (TOutput, error), ...) T
- func AddToolWithDeps[D, TInput, TOutput any, T dependencyToolTarget[D]](target T, handler func(RunContext[D], TInput) (TOutput, error), ...) T
- func ApprovalTool[TInput any, TOutput any](name, description string, ...) (Tool, ToolHandler, error)
- func AutoTool[TInput any, TOutput any](handler func(input TInput) (TOutput, error), opts ...AutoToolOption) (Tool, ToolHandler, error)
- func AutoToolWithContext[TInput any, TOutput any](handler func(ctx context.Context, input TInput) (TOutput, error), ...) (Tool, ToolHandler, error)
- func AutoToolWithDeps[TInput any, TOutput any, DepsT any](handler func(ctx RunContext[DepsT], input TInput) (TOutput, error), ...) (Tool, ToolHandler, error)
- func Bool(v bool) *bool
- func ChannelTool[TInput any, TOutput any](name, description string, ...) (Tool, ToolHandler, error)
- func Float64(v float64) *float64
- func FormatToolResult(result interface{}) string
- func Int(v int) *int
- func IntPtr(v int) *int
- func IsModelRetry(err error) bool
- func IsProviderError(err error) bool
- func IsUsageLimitExceeded(err error) bool
- func IsValidationError(err error) bool
- func MustApprovalTool[TInput any, TOutput any](name, description string, ...) (Tool, ToolHandler)
- func MustAutoTool[TInput any, TOutput any](handler func(input TInput) (TOutput, error), opts ...AutoToolOption) (Tool, ToolHandler)
- func MustAutoToolWithContext[TInput any, TOutput any](handler func(ctx context.Context, input TInput) (TOutput, error), ...) (Tool, ToolHandler)
- func MustAutoToolWithDeps[TInput any, TOutput any, DepsT any](handler func(ctx RunContext[DepsT], input TInput) (TOutput, error), ...) (Tool, ToolHandler)
- func MustChannelTool[TInput any, TOutput any](name, description string, ...) (Tool, ToolHandler)
- func MustToolPlain[TInput any, TOutput any](name, description string, handler func(input TInput) (TOutput, error), ...) (Tool, ToolHandler)
- func MustToolWithContext[TInput any, TOutput any](name, description string, ...) (Tool, ToolHandler)
- func MustToolWithDeps[TInput any, TOutput any, DepsT any](name, description string, ...) (Tool, ToolHandler)
- func RegisterToolset(registry ToolRegistry, set Toolset) error
- func String(v string) *string
- func ToolPlain[TInput any, TOutput any](name, description string, handler func(input TInput) (TOutput, error), ...) (Tool, ToolHandler, error)
- func ToolWithContext[TInput any, TOutput any](name, description string, ...) (Tool, ToolHandler, error)
- func ToolWithDeps[TInput any, TOutput any, DepsT any](name, description string, ...) (Tool, ToolHandler, error)
- func ValidateStruct(v any) error
- func WithToolCallContext(ctx context.Context, call ToolCallContext) context.Context
- type Agent
- func (a *Agent) AddAutoTool(tool Tool, handler ToolHandler) *Agent
- func (a *Agent) AddHandoff(h *Handoff) *Agent
- func (a *Agent) AddTool(tool Tool, handler ToolHandler) *Agent
- func (a *Agent) AddToolset(set Toolset) *Agent
- func (a *Agent) Drive(ctx context.Context, input DriveInput, opts ...RunOption) (*Execution[string], error)
- func (a *Agent) Resume(ctx context.Context, input ResumeInput, opts ...RunOption) (*Execution[string], error)
- func (a *Agent) Run(ctx context.Context, prompt string, opts ...RunOption) (*Result[string], error)
- func (a *Agent) RunStream(ctx context.Context, prompt string, opts ...RunOption) (*StreamResult, error)
- func (a *Agent) SetOutputToolNames(names map[string]bool) *Agent
- func (a *Agent) SetRegistry(registry ToolRegistry) *Agent
- type AgentIdentity
- type AgentInvocationMode
- type AgentOperation
- type AgentOperationResult
- type AgentOperationSpan
- type AgentOption
- func WithAgentIdentity(identity AgentIdentity) AgentOption
- func WithEndStrategy(strategy EndStrategy) AgentOption
- func WithHistoryProcessor(p HistoryProcessor) AgentOption
- func WithInstrumentation(instrumentation Instrumentation) AgentOption
- func WithMaxIterations(maxIter int) AgentOption
- func WithMaxTokens(maxTokens int) AgentOption
- func WithMaxValidationRetries(n int) AgentOption
- func WithModelMetadata(metadata ModelMetadata) AgentOption
- func WithOutputValidator(v OutputValidator) AgentOption
- func WithOutputValidatorFunc(fn func(context.Context, string) error) AgentOption
- func WithPromptCache(config PromptCacheConfig) AgentOption
- func WithRetries(config RetryConfig) AgentOption
- func WithSystemPrompts(prompts ...string) AgentOption
- func WithTemperature(temp float64) AgentOption
- func WithThinking(config ThinkingConfig) AgentOption
- func WithToolChoice(choice ToolChoice) AgentOption
- func WithToolPrepare(fn ToolPrepareFunc) AgentOption
- func WithTopP(topP float64) AgentOption
- func WithUsageLimits(limits UsageLimits) AgentOption
- type AgentWithDeps
- func (a *AgentWithDeps[D]) AddAutoTool(tool Tool, handler ToolHandler) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) AddHandoff(h *Handoff) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) AddHandoffWithDeps(h *HandoffWithDeps[D]) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) AddOutputValidator(v OutputValidatorWithDeps[D]) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) AddTool(tool Tool, handler ToolHandler) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) AddToolset(set Toolset) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) Bind(deps D) Runner[string]
- func (a *AgentWithDeps[D]) BindProvider(provider DepsProvider[D]) Runner[string]
- func (a *AgentWithDeps[D]) Drive(ctx context.Context, input DriveInput, deps D, opts ...RunOption) (*Execution[string], error)
- func (a *AgentWithDeps[D]) Resume(ctx context.Context, input ResumeInput, deps D, opts ...RunOption) (*Execution[string], error)
- func (a *AgentWithDeps[D]) Run(ctx context.Context, prompt string, deps D, opts ...RunOption) (*Result[string], error)
- func (a *AgentWithDeps[D]) RunStream(ctx context.Context, prompt string, deps D, opts ...RunOption) (*StreamResult, error)
- func (a *AgentWithDeps[D]) SetDepsValidator(fn DepsValidator[D]) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) SetDynamicPrompt(fn DynamicPromptWithDeps[D]) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) SetOutputToolNames(names map[string]bool) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) SetRegistry(registry ToolRegistry) *AgentWithDeps[D]
- func (a *AgentWithDeps[D]) SetToolPrepare(fn ToolPrepareFuncWithDeps[D]) *AgentWithDeps[D]
- type ApprovalFunc
- type AssistantCommittedEvent
- type AudioURL
- type AutoToolOption
- type CachePoint
- type ChannelToolOption
- type ChatRequest
- type ChatResponse
- type CompletionCandidate
- type CompletionSource
- type ContentType
- type ContextToolHandler
- type DepsProvider
- type DepsToolHandler
- type DepsValidator
- type DocumentURL
- type DriveInput
- type DriveMode
- type Driver
- type DynamicPrompt
- type DynamicPromptWithDeps
- type Embedder
- type EmbeddingInputType
- type EmbeddingRequest
- type EmbeddingResponse
- type EmbeddingUsage
- type EndStrategy
- type Event
- type EventNature
- type EventSink
- type EventSinkFunc
- type EventType
- type Execution
- type ExecutionSnapshot
- type ExecutionStatus
- type FinishReason
- type FuncToolset
- type Function
- type Handoff
- type HandoffInputFilter
- type HandoffOption
- type HandoffSummaryFunc
- type HandoffWithDeps
- func NewHandoffWithDeps[ParentD, ChildD, O any](name, description string, child *TypedAgentWithDeps[O, ChildD], ...) *HandoffWithDeps[ParentD]
- func NewIdentityHandoff[O, D any](name, description string, child *TypedAgentWithDeps[O, D], ...) *HandoffWithDeps[D]
- func NewIdentityTextHandoff[D any](name, description string, child *AgentWithDeps[D], opts ...HandoffOption) *HandoffWithDeps[D]
- func NewTextHandoffWithDeps[ParentD, ChildD any](name, description string, child *AgentWithDeps[ChildD], ...) *HandoffWithDeps[ParentD]
- type HistoryProcessor
- type HistoryProcessorFunc
- type ImageData
- type ImageURL
- type Instrumentation
- type InvalidRepresentationRequestError
- type InvalidRepresentationResponseError
- type JSONSchemaFormat
- type MaxIterationsError
- type Message
- func NewImageDataMessage(text string, data []byte, mediaType string) Message
- func NewImageFileMessage(text string, filePath string) (Message, error)
- func NewImageURLMessage(text string, imageURL string, detail ...string) Message
- func NewMultiPartMessage(parts ...Part) Message
- func NewTextMessage(role MessageRole, text string) Message
- func NewToolResultMessage(toolUseID string, content string, isError bool) Message
- func NewToolResultMessageFor(toolUseID, toolName, content string, isError bool) Message
- func NewToolUseMessage(toolUses ...ToolUse) Message
- type MessageHistory
- type MessageRole
- type Model
- type ModelMetadata
- type ModelMetadataProvider
- type ModelOperation
- type ModelOperationResult
- type ModelOperationSpan
- type ModelRetry
- type NativeOutputSpec
- type OutputMode
- type OutputModeSpec
- type OutputSpec
- type OutputValidatedEvent
- type OutputValidator
- type OutputValidatorFunc
- type OutputValidatorWithDeps
- type OutputValidatorWithDepsFunc
- type Part
- func AudioURLPart(url string, format ...string) Part
- func CachePointPart(ttl ...string) Part
- func DocumentURLPart(url string, mediaType ...string) Part
- func ImageDataPart(data []byte, mediaType string) Part
- func ImageURLPart(url string, detail ...string) Part
- func TextPart(text string) Part
- func UploadedFilePart(fileID string, providerName string) Part
- func VideoURLPart(url string) Part
- type PlainToolHandler
- type PromptCacheConfig
- type PromptCacheRetention
- type PromptedOutputSpec
- func (s *PromptedOutputSpec[T]) Mode() OutputMode
- func (s *PromptedOutputSpec[T]) Parse(msg Message) (T, error)
- func (s *PromptedOutputSpec[T]) ResponseFormat() *ResponseFormat
- func (s *PromptedOutputSpec[T]) SystemPromptSuffix() string
- func (s *PromptedOutputSpec[T]) Tools() []Tool
- func (s *PromptedOutputSpec[T]) WithTemplate(template string) *PromptedOutputSpec[T]
- type ProviderError
- type Representation
- type RepresentationCapabilities
- type RepresentationEncoder
- type RepresentationKind
- type RepresentationLimits
- type RepresentationRequest
- type RepresentationResponse
- type RepresentationUsage
- type RepresentationValidator
- type RequestUsage
- type RerankRequest
- type RerankResponse
- type RerankResult
- type RerankUsage
- type Reranker
- type ResponseFormat
- type ResponseFormatSpec
- type Result
- type ResumeInput
- type RetryConfig
- type RunCompletedEvent
- type RunContext
- type RunEndedEvent
- type RunErrorEvent
- type RunInterruptedEvent
- type RunMetadata
- type RunOption
- func WithMessages(messages ...Message) RunOption
- func WithRunEndStrategy(strategy EndStrategy) RunOption
- func WithRunEventSink(sink EventSink) RunOption
- func WithRunHistoryProcessor(p HistoryProcessor) RunOption
- func WithRunInstrumentation(instrumentation Instrumentation) RunOption
- func WithRunMaxIterations(maxIter int) RunOption
- func WithRunMaxTokens(maxTokens int) RunOption
- func WithRunMetadata(metadata RunMetadata) RunOption
- func WithRunModelStreaming(enabled bool) RunOption
- func WithRunPromptCache(config PromptCacheConfig) RunOption
- func WithRunTemperature(temp float64) RunOption
- func WithRunToolCancellationGrace(grace time.Duration) RunOption
- func WithRunToolChoice(choice ToolChoice) RunOption
- func WithRunToolGate(gate ToolGate) RunOption
- func WithRunToolResultProcessor(processor ToolResultProcessor) RunOption
- func WithRunToolsets(toolsets ...Toolset) RunOption
- func WithRunTurnHook(hook TurnHook) RunOption
- func WithRunUsageLimits(limits UsageLimits) RunOption
- type RunResult
- type RunStartedEvent
- type RunSuspendedEvent
- type Runner
- type SimilarityMetric
- type SparseVector
- type StreamEvent
- type StreamEventType
- type StreamModel
- type StreamResult
- type StreamRunner
- type StreamingRunner
- type SuspendableToolHandler
- type Suspension
- type SystemPromptAppender
- type TextOutputSpec
- type TextPreviewEvent
- type TextProcessorOutputSpec
- type ThinkingBlock
- type ThinkingConfig
- type ThinkingPreviewEvent
- type Tool
- type ToolArgumentPreviewEvent
- type ToolBatchDecision
- type ToolBatchPlannedEvent
- type ToolCallContext
- type ToolCallPreviewEvent
- type ToolChoice
- type ToolConfig
- type ToolDeferral
- type ToolDisposition
- type ToolDispositionKind
- type ToolExecutionResult
- type ToolGate
- type ToolGateFunc
- type ToolHandler
- type ToolHandlerSuspension
- type ToolOperation
- type ToolOperationResult
- type ToolOperationSpan
- type ToolOption
- type ToolOutputSpec
- type ToolPrepareFunc
- type ToolPrepareFuncWithDeps
- type ToolRegistry
- type ToolResult
- type ToolResultCommittedEvent
- type ToolResultProcessor
- type ToolResultProcessorFunc
- type ToolResumeAction
- type ToolResumeContext
- type ToolResumeDecision
- type ToolStartedEvent
- type ToolType
- type ToolUse
- type Toolset
- type Turn
- type TurnAction
- type TurnDecision
- type TurnEndedEvent
- type TurnHook
- type TurnMessagesInjectedEvent
- type TurnStartedEvent
- type TypedAgent
- func NewTypedAgent[O any](systemPrompt string, model Model, outputDescription string, ...) *TypedAgent[O]
- func NewTypedAgentDynamic[O any](promptFn DynamicPrompt, model Model, outputDescription string, ...) *TypedAgent[O]
- func NewTypedAgentWithMode[O any](systemPrompt string, model Model, output OutputSpec[O], opts ...AgentOption) *TypedAgent[O]
- func (a *TypedAgent[O]) AddAutoTool(tool Tool, handler ToolHandler) *TypedAgent[O]
- func (a *TypedAgent[O]) AddHandoff(h *Handoff) *TypedAgent[O]
- func (a *TypedAgent[O]) AddOutputValidator(v TypedOutputValidator[O]) *TypedAgent[O]
- func (a *TypedAgent[O]) AddTool(tool Tool, handler ToolHandler) *TypedAgent[O]
- func (a *TypedAgent[O]) AddToolset(set Toolset) *TypedAgent[O]
- func (a *TypedAgent[O]) Drive(ctx context.Context, input DriveInput, opts ...RunOption) (*Execution[O], error)
- func (a *TypedAgent[O]) Resume(ctx context.Context, input ResumeInput, opts ...RunOption) (*Execution[O], error)
- func (a *TypedAgent[O]) Run(ctx context.Context, prompt string, opts ...RunOption) (*Result[O], error)
- func (a *TypedAgent[O]) RunStream(ctx context.Context, prompt string, opts ...RunOption) (*StreamResult, error)
- func (a *TypedAgent[O]) SetRegistry(registry ToolRegistry) *TypedAgent[O]
- type TypedAgentWithDeps
- func NewTypedAgentWithDeps[O, D any](systemPrompt string, model Model, outputDescription string, ...) *TypedAgentWithDeps[O, D]
- func NewTypedAgentWithDepsDynamic[O, D any](promptFn DynamicPromptWithDeps[D], model Model, outputDescription string, ...) *TypedAgentWithDeps[O, D]
- func NewTypedAgentWithDepsMode[O, D any](systemPrompt string, model Model, output OutputSpec[O], opts ...AgentOption) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) AddAutoTool(tool Tool, handler ToolHandler) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) AddHandoff(h *Handoff) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) AddHandoffWithDeps(h *HandoffWithDeps[D]) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) AddOutputValidator(v TypedOutputValidator[O]) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) AddOutputValidatorWithDeps(v TypedOutputValidatorWithDeps[D, O]) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) AddTextOutputValidator(v OutputValidatorWithDeps[D]) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) AddTool(tool Tool, handler ToolHandler) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) AddToolset(set Toolset) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) Bind(deps D) Runner[O]
- func (a *TypedAgentWithDeps[O, D]) BindProvider(provider DepsProvider[D]) Runner[O]
- func (a *TypedAgentWithDeps[O, D]) Drive(ctx context.Context, input DriveInput, deps D, opts ...RunOption) (*Execution[O], error)
- func (a *TypedAgentWithDeps[O, D]) Resume(ctx context.Context, input ResumeInput, deps D, opts ...RunOption) (*Execution[O], error)
- func (a *TypedAgentWithDeps[O, D]) Run(ctx context.Context, prompt string, deps D, opts ...RunOption) (*Result[O], error)
- func (a *TypedAgentWithDeps[O, D]) RunStream(ctx context.Context, prompt string, deps D, opts ...RunOption) (*StreamResult, error)
- func (a *TypedAgentWithDeps[O, D]) SetDepsValidator(fn DepsValidator[D]) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) SetDynamicPrompt(fn DynamicPromptWithDeps[D]) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) SetRegistry(registry ToolRegistry) *TypedAgentWithDeps[O, D]
- func (a *TypedAgentWithDeps[O, D]) SetToolPrepare(fn ToolPrepareFuncWithDeps[D]) *TypedAgentWithDeps[O, D]
- type TypedOutputValidator
- type TypedOutputValidatorFunc
- type TypedOutputValidatorWithDeps
- type TypedOutputValidatorWithDepsFunc
- type TypedRunResult
- type UnsupportedRepresentationError
- type UploadedFile
- type Usage
- type UsageLimitExceededError
- type UsageLimits
- type ValidationError
- type VectorSpace
- type VideoURL
Constants ¶
const ( EmbeddingInputNone = retrieval.EmbeddingInputNone EmbeddingInputQuery = retrieval.EmbeddingInputQuery EmbeddingInputDocument = retrieval.EmbeddingInputDocument RepresentationDense = retrieval.RepresentationDense RepresentationSparse = retrieval.RepresentationSparse RepresentationMultiVector = retrieval.RepresentationMultiVector SimilarityCosine = retrieval.SimilarityCosine SimilarityDotProduct = retrieval.SimilarityDotProduct ToolTypeFunction = core.ToolTypeFunction ToolChoiceNone = core.ToolChoiceNone ToolChoiceAuto = core.ToolChoiceAuto ToolChoiceRequired = core.ToolChoiceRequired FinishReasonStop = core.FinishReasonStop FinishReasonLength = core.FinishReasonLength FinishReasonToolCalls = core.FinishReasonToolCalls FinishReasonContentFilter = core.FinishReasonContentFilter FinishReasonError = core.FinishReasonError FinishReasonUnknown = core.FinishReasonUnknown RoleSystem = core.RoleSystem RoleUser = core.RoleUser RoleAssistant = core.RoleAssistant RoleTool = core.RoleTool ContentText = core.ContentText ContentImageURL = core.ContentImageURL ContentToolUse = core.ContentToolUse ContentToolResult = core.ContentToolResult ContentThinking = core.ContentThinking ContentImageData = core.ContentImageData ContentAudioURL = core.ContentAudioURL ContentVideoURL = core.ContentVideoURL ContentDocumentURL = core.ContentDocumentURL ContentCachePoint = core.ContentCachePoint ContentUploadedFile = core.ContentUploadedFile PromptCacheNone = core.PromptCacheNone PromptCacheShort = core.PromptCacheShort PromptCacheLong = core.PromptCacheLong OutputModeTool = core.OutputModeTool OutputModeNative = core.OutputModeNative OutputModePrompted = core.OutputModePrompted OutputModeText = core.OutputModeText )
Domain constants (from core)
const ( StreamEventTextDelta = core.StreamEventTextDelta StreamEventToolCallStart = core.StreamEventToolCallStart StreamEventToolCallDelta = core.StreamEventToolCallDelta StreamEventToolResult = core.StreamEventToolResult StreamEventDone = core.StreamEventDone StreamEventError = core.StreamEventError StreamEventThinkingDelta = core.StreamEventThinkingDelta ExecutionCompleted = core.ExecutionCompleted ExecutionSuspended = core.ExecutionSuspended ExecutionStopped = core.ExecutionStopped ExecutionInterrupted = core.ExecutionInterrupted ExecutionFailed = core.ExecutionFailed )
Stream event constants
const DefaultPromptedTemplate = `` /* 140-byte string literal not displayed */
DefaultPromptedTemplate is the default template for prompted output. The {schema} placeholder is replaced with the JSON schema.
Variables ¶
var ( ErrDriveInput = errors.New("invalid driver input") ErrTranscriptInvalid = errors.New("invalid transcript") ErrSuspensionVersion = errors.New("unsupported suspension version") ErrSuspensionMismatch = errors.New("suspension does not match execution") ErrResumeDecision = errors.New("invalid tool resume decision") ErrTurnDecision = errors.New("invalid turn decision") ErrExecutionSuspended = errors.New("agent execution suspended") ErrExecutionStopped = errors.New("agent execution stopped") ErrExecutionInterrupted = errors.New("agent execution interrupted") ErrExecutionFailed = errors.New("agent execution failed") )
Input and transcript errors are returned before any model request or tool handler starts.
var ( ErrUnsupportedRepresentation = retrieval.ErrUnsupportedRepresentation ErrInvalidRepresentationRequest = retrieval.ErrInvalidRepresentationRequest ErrInvalidRepresentationResponse = retrieval.ErrInvalidRepresentationResponse )
Representation encoding errors. Each is matched by errors.Is from the typed errors the encoders return, so callers can branch on the class of failure without depending on a concrete error type.
var ErrDriverRequired = errors.New("runner must implement agentic.Driver")
ErrDriverRequired is returned when a Runner does not expose the explicit Driver capability required for session-controlled execution.
var ErrNilDeps = errors.New("agent dependencies must not be nil")
ErrNilDeps is returned before any external effect when a dependency-aware run receives a nil or typed-nil dependency value.
var ErrToolHandlerSuspension = errors.New("invalid tool handler suspension")
ErrToolHandlerSuspension reports a handler that violated the opt-in suspension protocol.
Functions ¶
func AddHandoff ¶
func AddHandoff[T toolTarget](target T, handoff *Handoff) T
func AddHandoffWithDeps ¶
func AddHandoffWithDeps[D any, T dependencyToolTarget[D]](target T, handoff *HandoffWithDeps[D]) T
func AddTool ¶
func AddTool[T toolTarget, TInput, TOutput any]( target T, handler func(context.Context, TInput) (TOutput, error), opts ...AutoToolOption, ) T
AddTool registers the standard context-aware handler on any agent facade.
func AddToolPlain ¶
func AddToolPlain[T toolTarget, TInput, TOutput any]( target T, handler func(TInput) (TOutput, error), opts ...AutoToolOption, ) T
AddToolPlain registers a context-free handler on any agent facade.
func AddToolWithContext ¶
func AddToolWithContext[T toolTarget, TInput, TOutput any]( target T, handler func(context.Context, TInput) (TOutput, error), opts ...AutoToolOption, ) T
AddToolWithContext is an explicit spelling of AddTool.
func AddToolWithDeps ¶
func AddToolWithDeps[D, TInput, TOutput any, T dependencyToolTarget[D]]( target T, handler func(RunContext[D], TInput) (TOutput, error), opts ...AutoToolOption, ) T
AddToolWithDeps registers a handler only when its D exactly matches the dependency-aware facade's D.
func ApprovalTool ¶
func ApprovalTool[TInput any, TOutput any]( name, description string, handler func(ctx context.Context, input TInput) (TOutput, error), approvalFn ApprovalFunc, opts ...ChannelToolOption, ) (Tool, ToolHandler, error)
ApprovalTool creates a synchronous tool that requires approval before execution.
func AutoTool ¶
func AutoTool[TInput any, TOutput any]( handler func(input TInput) (TOutput, error), opts ...AutoToolOption, ) (Tool, ToolHandler, error)
func AutoToolWithContext ¶
func AutoToolWithContext[TInput any, TOutput any]( handler func(ctx context.Context, input TInput) (TOutput, error), opts ...AutoToolOption, ) (Tool, ToolHandler, error)
func AutoToolWithDeps ¶
func AutoToolWithDeps[TInput any, TOutput any, DepsT any]( handler func(ctx RunContext[DepsT], input TInput) (TOutput, error), opts ...AutoToolOption, ) (Tool, ToolHandler, error)
func Bool ¶ added in v0.3.0
Bool returns a pointer to v. See Int for why these fields are pointers.
req := &agentic.EmbeddingRequest{Input: texts, Truncate: agentic.Bool(false)}
func ChannelTool ¶
func ChannelTool[TInput any, TOutput any]( name, description string, handler func(ctx context.Context, input TInput) (<-chan TOutput, error), opts ...ChannelToolOption, ) (Tool, ToolHandler, error)
func Float64 ¶ added in v0.3.0
Float64 returns a pointer to v. See Int for why these fields are pointers.
req := &agentic.ChatRequest{Temperature: agentic.Float64(0.2)}
func FormatToolResult ¶
func FormatToolResult(result interface{}) string
func Int ¶ added in v0.3.0
Int returns a pointer to v.
Optional request fields are pointers so that "unset" is distinguishable from a meaningful zero — a MaxTokens of 0 is not the same as leaving the provider to choose. This makes those fields writable inline:
req := &agentic.ChatRequest{MaxTokens: agentic.Int(1024)}
func IntPtr ¶
IntPtr is a helper to create *int values for UsageLimits fields.
Example:
limits := agentic.UsageLimits{
MaxRequests: agentic.IntPtr(10),
MaxTotalTokens: agentic.IntPtr(50000),
}
func IsModelRetry ¶
IsModelRetry checks if an error is a ModelRetry.
func IsProviderError ¶ added in v0.3.0
IsProviderError checks if an error is a ProviderError.
func IsUsageLimitExceeded ¶
IsUsageLimitExceeded checks if an error is a UsageLimitExceededError.
func IsValidationError ¶
IsValidationError checks if an error is a ValidationError.
func MustApprovalTool ¶
func MustApprovalTool[TInput any, TOutput any]( name, description string, handler func(ctx context.Context, input TInput) (TOutput, error), approvalFn ApprovalFunc, opts ...ChannelToolOption, ) (Tool, ToolHandler)
MustApprovalTool is like ApprovalTool but panics on definition errors.
func MustAutoTool ¶
func MustAutoTool[TInput any, TOutput any]( handler func(input TInput) (TOutput, error), opts ...AutoToolOption, ) (Tool, ToolHandler)
func MustAutoToolWithContext ¶
func MustAutoToolWithContext[TInput any, TOutput any]( handler func(ctx context.Context, input TInput) (TOutput, error), opts ...AutoToolOption, ) (Tool, ToolHandler)
func MustAutoToolWithDeps ¶
func MustAutoToolWithDeps[TInput any, TOutput any, DepsT any]( handler func(ctx RunContext[DepsT], input TInput) (TOutput, error), opts ...AutoToolOption, ) (Tool, ToolHandler)
func MustChannelTool ¶
func MustChannelTool[TInput any, TOutput any]( name, description string, handler func(ctx context.Context, input TInput) (<-chan TOutput, error), opts ...ChannelToolOption, ) (Tool, ToolHandler)
MustChannelTool is like ChannelTool but panics on definition errors.
func MustToolPlain ¶
func MustToolPlain[TInput any, TOutput any]( name, description string, handler func(input TInput) (TOutput, error), opts ...ToolOption, ) (Tool, ToolHandler)
func MustToolWithContext ¶
func MustToolWithContext[TInput any, TOutput any]( name, description string, handler func(ctx context.Context, input TInput) (TOutput, error), opts ...ToolOption, ) (Tool, ToolHandler)
func MustToolWithDeps ¶
func MustToolWithDeps[TInput any, TOutput any, DepsT any]( name, description string, handler func(ctx RunContext[DepsT], input TInput) (TOutput, error), opts ...ToolOption, ) (Tool, ToolHandler)
func RegisterToolset ¶
func RegisterToolset(registry ToolRegistry, set Toolset) error
func String ¶ added in v0.3.0
String returns a pointer to v. See Int for why these fields are pointers.
func ToolPlain ¶
func ToolPlain[TInput any, TOutput any]( name, description string, handler func(input TInput) (TOutput, error), opts ...ToolOption, ) (Tool, ToolHandler, error)
func ToolWithContext ¶
func ToolWithContext[TInput any, TOutput any]( name, description string, handler func(ctx context.Context, input TInput) (TOutput, error), opts ...ToolOption, ) (Tool, ToolHandler, error)
func ToolWithDeps ¶
func ToolWithDeps[TInput any, TOutput any, DepsT any]( name, description string, handler func(ctx RunContext[DepsT], input TInput) (TOutput, error), opts ...ToolOption, ) (Tool, ToolHandler, error)
func ValidateStruct ¶
ValidateStruct validates a struct using `validate` struct tags. Returns a *ValidationError with human-readable messages if validation fails, or nil if validation passes (or the value has no validate tags).
This is used automatically by ToolOutputSpec when parsing structured output, but can also be called directly.
func WithToolCallContext ¶ added in v0.5.1
func WithToolCallContext(ctx context.Context, call ToolCallContext) context.Context
WithToolCallContext starts a fresh logical tool invocation. It installs call metadata for CurrentToolCall and clears any handler-owned resume metadata inherited from an outer composite tool. Driver-managed handlers receive this context automatically; composite tool hosts use it before invoking a nested handler.
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent is a non-generic text agent without application dependencies.
func NewAgentDynamic ¶
func NewAgentDynamic(promptFn DynamicPrompt, model Model, opts ...AgentOption) *Agent
func (*Agent) AddAutoTool ¶
func (a *Agent) AddAutoTool(tool Tool, handler ToolHandler) *Agent
func (*Agent) AddHandoff ¶
func (*Agent) AddToolset ¶
func (*Agent) Drive ¶ added in v0.4.0
func (a *Agent) Drive(ctx context.Context, input DriveInput, opts ...RunOption) (*Execution[string], error)
Drive starts or continues a dependency-free text execution.
func (*Agent) Resume ¶ added in v0.4.0
func (a *Agent) Resume(ctx context.Context, input ResumeInput, opts ...RunOption) (*Execution[string], error)
Resume completes a suspended dependency-free text execution.
func (*Agent) SetRegistry ¶
func (a *Agent) SetRegistry(registry ToolRegistry) *Agent
type AgentIdentity ¶ added in v0.7.0
AgentIdentity is the application-owned identity of an agent definition.
type AgentInvocationMode ¶ added in v0.7.0
type AgentInvocationMode string
AgentInvocationMode identifies the public execution entry point.
const ( AgentInvocationStart AgentInvocationMode = "start" AgentInvocationContinue AgentInvocationMode = "continue" AgentInvocationResume AgentInvocationMode = "resume" )
type AgentOperation ¶ added in v0.7.0
type AgentOperation struct {
Agent AgentIdentity
Model ModelMetadata
ModelName string
// Request contains the stable request settings and tool definitions known
// at invocation start. Messages are carried separately in Input. Tools are
// omitted when a dynamic tool-preparation callback can change them per turn.
Request ChatRequest
Run RunMetadata
Mode AgentInvocationMode
Input []Message
}
AgentOperation describes one Drive, Resume, or RunStream invocation.
type AgentOperationResult ¶ added in v0.7.0
type AgentOperationResult struct {
Status ExecutionStatus
Messages []Message
Usage Usage
FinishReason FinishReason
Error error
}
AgentOperationResult is the terminal state of one invocation. Suspensions close the invocation normally and can be resumed by a later invocation.
type AgentOperationSpan ¶ added in v0.7.0
type AgentOperationSpan interface {
End(AgentOperationResult)
}
type AgentOption ¶
type AgentOption func(*agentConfig)
AgentOption configures static agent behavior. Options that consume a dependency or typed output attach through the corresponding typed facade.
func WithAgentIdentity ¶ added in v0.7.0
func WithAgentIdentity(identity AgentIdentity) AgentOption
WithAgentIdentity supplies the stable agent identity used by observability integrations. Empty fields remain unknown rather than being fabricated.
func WithEndStrategy ¶
func WithEndStrategy(strategy EndStrategy) AgentOption
func WithHistoryProcessor ¶
func WithHistoryProcessor(p HistoryProcessor) AgentOption
func WithInstrumentation ¶ added in v0.7.0
func WithInstrumentation(instrumentation Instrumentation) AgentOption
WithInstrumentation observes every agent invocation, model request, and admitted tool execution. The observer is optional; Agentic's source and public API import no OpenTelemetry packages, while github.com/regularkevvv/agentic/otel supplies the standard adapter. Nested agents inherit an observer through context unless they explicitly configure one; passing nil explicitly disables inheritance.
func WithMaxIterations ¶
func WithMaxIterations(maxIter int) AgentOption
func WithMaxTokens ¶
func WithMaxTokens(maxTokens int) AgentOption
func WithMaxValidationRetries ¶
func WithMaxValidationRetries(n int) AgentOption
func WithModelMetadata ¶ added in v0.7.0
func WithModelMetadata(metadata ModelMetadata) AgentOption
WithModelMetadata overrides metadata discovered from the Model. This is useful for custom providers and compatible endpoints.
func WithOutputValidator ¶
func WithOutputValidator(v OutputValidator) AgentOption
WithOutputValidator adds a dependency-free text output validator.
func WithOutputValidatorFunc ¶
func WithOutputValidatorFunc(fn func(context.Context, string) error) AgentOption
func WithPromptCache ¶ added in v0.6.0
func WithPromptCache(config PromptCacheConfig) AgentOption
WithPromptCache configures a stable provider prompt-cache identity for every run. Harness normally overrides the key per durable session.
func WithRetries ¶
func WithRetries(config RetryConfig) AgentOption
func WithSystemPrompts ¶
func WithSystemPrompts(prompts ...string) AgentOption
WithSystemPrompts replaces the constructor prompt with static prompt segments joined by a blank line.
func WithTemperature ¶
func WithTemperature(temp float64) AgentOption
func WithThinking ¶
func WithThinking(config ThinkingConfig) AgentOption
func WithToolChoice ¶
func WithToolChoice(choice ToolChoice) AgentOption
func WithToolPrepare ¶
func WithToolPrepare(fn ToolPrepareFunc) AgentOption
func WithTopP ¶
func WithTopP(topP float64) AgentOption
func WithUsageLimits ¶
func WithUsageLimits(limits UsageLimits) AgentOption
type AgentWithDeps ¶
type AgentWithDeps[D any] struct { // contains filtered or unexported fields }
AgentWithDeps is a text agent whose run graph carries exact D.
func NewAgentWithDeps ¶
func NewAgentWithDeps[D any](systemPrompt string, model Model, opts ...AgentOption) *AgentWithDeps[D]
func NewAgentWithDepsDynamic ¶
func NewAgentWithDepsDynamic[D any](promptFn DynamicPromptWithDeps[D], model Model, opts ...AgentOption) *AgentWithDeps[D]
func (*AgentWithDeps[D]) AddAutoTool ¶
func (a *AgentWithDeps[D]) AddAutoTool(tool Tool, handler ToolHandler) *AgentWithDeps[D]
func (*AgentWithDeps[D]) AddHandoff ¶
func (a *AgentWithDeps[D]) AddHandoff(h *Handoff) *AgentWithDeps[D]
func (*AgentWithDeps[D]) AddHandoffWithDeps ¶
func (a *AgentWithDeps[D]) AddHandoffWithDeps(h *HandoffWithDeps[D]) *AgentWithDeps[D]
func (*AgentWithDeps[D]) AddOutputValidator ¶
func (a *AgentWithDeps[D]) AddOutputValidator(v OutputValidatorWithDeps[D]) *AgentWithDeps[D]
func (*AgentWithDeps[D]) AddTool ¶
func (a *AgentWithDeps[D]) AddTool(tool Tool, handler ToolHandler) *AgentWithDeps[D]
func (*AgentWithDeps[D]) AddToolset ¶
func (a *AgentWithDeps[D]) AddToolset(set Toolset) *AgentWithDeps[D]
func (*AgentWithDeps[D]) Bind ¶
func (a *AgentWithDeps[D]) Bind(deps D) Runner[string]
func (*AgentWithDeps[D]) BindProvider ¶
func (a *AgentWithDeps[D]) BindProvider(provider DepsProvider[D]) Runner[string]
func (*AgentWithDeps[D]) Drive ¶ added in v0.4.0
func (a *AgentWithDeps[D]) Drive(ctx context.Context, input DriveInput, deps D, opts ...RunOption) (*Execution[string], error)
Drive starts or continues a dependency-aware text execution with its exact dependency value.
func (*AgentWithDeps[D]) Resume ¶ added in v0.4.0
func (a *AgentWithDeps[D]) Resume(ctx context.Context, input ResumeInput, deps D, opts ...RunOption) (*Execution[string], error)
Resume completes a suspended dependency-aware text execution with its exact dependency value.
func (*AgentWithDeps[D]) RunStream ¶
func (a *AgentWithDeps[D]) RunStream(ctx context.Context, prompt string, deps D, opts ...RunOption) (*StreamResult, error)
func (*AgentWithDeps[D]) SetDepsValidator ¶
func (a *AgentWithDeps[D]) SetDepsValidator(fn DepsValidator[D]) *AgentWithDeps[D]
func (*AgentWithDeps[D]) SetDynamicPrompt ¶
func (a *AgentWithDeps[D]) SetDynamicPrompt(fn DynamicPromptWithDeps[D]) *AgentWithDeps[D]
func (*AgentWithDeps[D]) SetOutputToolNames ¶
func (a *AgentWithDeps[D]) SetOutputToolNames(names map[string]bool) *AgentWithDeps[D]
func (*AgentWithDeps[D]) SetRegistry ¶
func (a *AgentWithDeps[D]) SetRegistry(registry ToolRegistry) *AgentWithDeps[D]
func (*AgentWithDeps[D]) SetToolPrepare ¶
func (a *AgentWithDeps[D]) SetToolPrepare(fn ToolPrepareFuncWithDeps[D]) *AgentWithDeps[D]
type ApprovalFunc ¶
type ApprovalFunc = agentictool.ApprovalFunc
type AssistantCommittedEvent ¶ added in v0.4.0
type AssistantCommittedEvent struct {
Message Message
// contains filtered or unexported fields
}
AssistantCommittedEvent is emitted once a complete assistant message has been appended to the authoritative transcript.
func (AssistantCommittedEvent) Nature ¶ added in v0.4.0
func (e AssistantCommittedEvent) Nature() EventNature
type AutoToolOption ¶
type AutoToolOption = agentictool.AutoToolOption
func AutoToolDescription ¶
func AutoToolDescription(desc string) AutoToolOption
func AutoToolName ¶
func AutoToolName(name string) AutoToolOption
type CachePoint ¶
type CachePoint = core.CachePoint
type ChannelToolOption ¶
type ChannelToolOption = agentictool.ChannelToolOption
func WithApproval ¶
func WithApproval(fn ApprovalFunc) ChannelToolOption
WithApproval configures approval on a channel-backed tool.
func WithChannelTimeout ¶
func WithChannelTimeout(d time.Duration) ChannelToolOption
WithChannelTimeout sets how long a channel-backed tool waits for a result.
type ChatRequest ¶
type ChatRequest = core.ChatRequest
type ChatResponse ¶
type ChatResponse = core.ChatResponse
type CompletionCandidate ¶ added in v0.4.0
type CompletionCandidate struct {
Source CompletionSource
ToolCallID string
}
CompletionCandidate is intentionally output-type agnostic. Hooks need to know whether a valid candidate exists and where it came from; the typed value remains in the typed Result returned to the caller.
func (CompletionCandidate) Valid ¶ added in v0.4.0
func (c CompletionCandidate) Valid() bool
Valid reports whether this is a parsed and validated completion candidate.
type CompletionSource ¶ added in v0.4.0
type CompletionSource uint8
CompletionSource describes how a validated completion was supplied.
const ( CompletionNone CompletionSource = iota CompletionText CompletionOutputTool )
type ContentType ¶
type ContentType = core.ContentType
type ContextToolHandler ¶
type ContextToolHandler[TInput any, TOutput any] = agentictool.ContextToolHandler[TInput, TOutput]
type DepsProvider ¶
DepsProvider obtains dependencies once at the beginning of each run.
type DepsToolHandler ¶
type DepsToolHandler[TInput any, TOutput any, DepsT any] = agentictool.DepsToolHandler[TInput, TOutput, DepsT]
type DepsValidator ¶
DepsValidator checks application invariants before any run side effect.
type DocumentURL ¶
type DocumentURL = core.DocumentURL
type DriveInput ¶ added in v0.4.0
DriveInput is the explicit input to a driver execution.
DriveStart requires Prompt to be a user message. DriveContinue forbids a prompt and continues directly from History. DriveRecover additionally accepts a fully paired final assistant candidate, without requesting it again. History is copied before any model or tool work begins.
type DriveMode ¶ added in v0.4.0
type DriveMode uint8
DriveMode selects whether a driver starts a fresh user turn or continues a fully paired transcript without adding a synthetic prompt.
const ( DriveStart DriveMode = iota DriveContinue // DriveRecover resumes a committed, fully paired frontier. Unlike // DriveContinue it also accepts a final assistant message without tool calls: // that candidate is re-evaluated and passed through the turn hook, without // another model request or duplicate assistant commit. Validators may rerun. // Open tool frontiers still require explicit repair or suspension resolution. DriveRecover )
type Driver ¶ added in v0.4.0
type Driver[O any] interface { Runner[O] Drive(context.Context, DriveInput, ...RunOption) (*Execution[O], error) Resume(context.Context, ResumeInput, ...RunOption) (*Execution[O], error) }
Driver is the resumable execution capability implemented by built-in agents and bound runners. Runner remains the small, source-compatible convenience interface; callers that need session control opt into Driver explicitly.
type DynamicPrompt ¶
DynamicPrompt is a dependency-free prompt callback.
type DynamicPromptWithDeps ¶
type DynamicPromptWithDeps[D any] func(RunContext[D]) (string, error)
DynamicPromptWithDeps is a prompt callback connected to an exact D.
type Embedder ¶ added in v0.2.0
func RepresentationEncoderAsEmbedder ¶ added in v0.6.0
func RepresentationEncoderAsEmbedder(encoder RepresentationEncoder) (Embedder, error)
RepresentationEncoderAsEmbedder projects a RepresentationEncoder onto the dense Embedder contract, requesting dense output only.
Use it to adopt a multi-output provider in code already written against Embedder, and to turn on its sparse output later when the index is ready. It fails at construction, not at first call, when the encoder produces no dense output.
type EmbeddingInputType ¶ added in v0.2.0
type EmbeddingInputType = retrieval.EmbeddingInputType
type EmbeddingRequest ¶ added in v0.2.0
type EmbeddingRequest = retrieval.EmbeddingRequest
type EmbeddingResponse ¶ added in v0.2.0
type EmbeddingResponse = retrieval.EmbeddingResponse
func EmbedDocuments ¶ added in v0.2.0
EmbedDocuments embeds texts as documents to be stored and searched against; use this for the indexing side of a retrieval task.
func EmbedQuery ¶ added in v0.2.0
EmbedQuery embeds texts as search queries. Retrieval-tuned providers embed queries into the region of vector space where their answering documents live; use this for the search side of a retrieval task.
type EmbeddingUsage ¶ added in v0.2.0
type EmbeddingUsage = retrieval.EmbeddingUsage
type EndStrategy ¶
type EndStrategy int
EndStrategy controls completion when one response contains multiple tools.
const ( EndStrategyExhaustive EndStrategy = iota EndStrategyEarly )
type Event ¶ added in v0.4.0
type Event interface {
Nature() EventNature
Type() EventType
TurnIndex() int
}
Event is emitted by the one execution fold at deterministic preview, commit, and lifecycle points. EventSink is synchronous by design: a sink is a low-level execution participant rather than a best-effort subscriber.
type EventNature ¶ added in v0.4.0
type EventNature uint8
EventNature separates transient provider previews from committed execution state and lifecycle transitions.
const ( EventPreview EventNature = iota EventAuthoritative EventLifecycle )
type EventSinkFunc ¶ added in v0.4.0
EventSinkFunc adapts a function to EventSink.
type EventType ¶ added in v0.4.0
type EventType uint8
EventType identifies a concrete canonical event kind.
const ( EventTypeTextPreview EventType = iota EventTypeThinkingPreview EventTypeToolCallPreview EventTypeToolArgumentPreview EventTypeAssistantCommitted EventTypeToolBatchPlanned EventTypeToolStarted EventTypeToolResultCommitted EventTypeOutputValidated EventTypeTurnMessagesInjected EventTypeRunStarted EventTypeTurnStarted EventTypeTurnEnded EventTypeRunSuspended EventTypeRunCompleted EventTypeRunInterrupted EventTypeRunError EventTypeRunEnded )
type Execution ¶ added in v0.4.0
type Execution[O any] struct { Status ExecutionStatus Result *Result[O] Suspension *Suspension }
Execution contains either a completed result or the durable partial state reached before a failure, stop, interruption, or suspension.
type ExecutionSnapshot ¶ added in v0.4.0
type ExecutionSnapshot = core.ExecutionSnapshot
type ExecutionStatus ¶ added in v0.4.0
type ExecutionStatus = core.ExecutionStatus
type FinishReason ¶
type FinishReason = core.FinishReason
type FuncToolset ¶
type FuncToolset = agentictool.FuncToolset
func NewToolset ¶
func NewToolset() *FuncToolset
type Handoff ¶
type Handoff struct {
// contains filtered or unexported fields
}
Handoff delegates to a child whose dependencies are already bound.
func NewHandoff ¶
func NewHandoff[O any](name, description string, child Runner[O], opts ...HandoffOption) *Handoff
type HandoffInputFilter ¶
type HandoffInputFilter int
const ( HandoffFullHistory HandoffInputFilter = iota HandoffLastMessage HandoffSummary )
type HandoffOption ¶
type HandoffOption func(*handoffConfig)
func WithHandoffFilter ¶
func WithHandoffFilter(filter HandoffInputFilter) HandoffOption
func WithHandoffMaxTokens ¶
func WithHandoffMaxTokens(n int) HandoffOption
func WithHandoffSummaryFunc ¶
func WithHandoffSummaryFunc(fn HandoffSummaryFunc) HandoffOption
func WithHandoffSystemPrompt ¶
func WithHandoffSystemPrompt(prompt string) HandoffOption
type HandoffWithDeps ¶
type HandoffWithDeps[D any] struct { // contains filtered or unexported fields }
HandoffWithDeps derives child dependencies from the parent run's exact D.
func NewHandoffWithDeps ¶
func NewHandoffWithDeps[ParentD, ChildD, O any]( name, description string, child *TypedAgentWithDeps[O, ChildD], mapper func(RunContext[ParentD]) (ChildD, error), opts ...HandoffOption, ) *HandoffWithDeps[ParentD]
func NewIdentityHandoff ¶
func NewIdentityHandoff[O, D any](name, description string, child *TypedAgentWithDeps[O, D], opts ...HandoffOption) *HandoffWithDeps[D]
func NewIdentityTextHandoff ¶
func NewIdentityTextHandoff[D any](name, description string, child *AgentWithDeps[D], opts ...HandoffOption) *HandoffWithDeps[D]
func NewTextHandoffWithDeps ¶
func NewTextHandoffWithDeps[ParentD, ChildD any]( name, description string, child *AgentWithDeps[ChildD], mapper func(RunContext[ParentD]) (ChildD, error), opts ...HandoffOption, ) *HandoffWithDeps[ParentD]
NewTextHandoffWithDeps is the text-output equivalent of NewHandoffWithDeps.
type HistoryProcessor ¶
type HistoryProcessor interface {
Process(ctx context.Context, messages []Message) ([]Message, error)
}
HistoryProcessor transforms the message history before it's sent to the model. The processor affects only what's sent to the model — the agent's internal message list remains complete for RunResult.AllMessages().
func ChainProcessors ¶
func ChainProcessors(processors ...HistoryProcessor) HistoryProcessor
ChainProcessors applies multiple processors in sequence. Each processor receives the output of the previous one.
func SlidingWindowHistory ¶
func SlidingWindowHistory(maxTokens int, tokenCounter func(Message) int) HistoryProcessor
SlidingWindowHistory keeps a sliding window of messages within a token budget. The system prompt is always preserved. tokenCounter estimates the token count for a single message.
func SummarizeHistory ¶
func SummarizeHistory(model Model, maxMessages int) HistoryProcessor
SummarizeHistory uses an LLM to summarize older messages when the history exceeds maxMessages. The summary replaces older messages as a single user message. The most recent maxMessages are always preserved verbatim.
func TruncateHistory ¶
func TruncateHistory(maxMessages int) HistoryProcessor
TruncateHistory keeps the system prompt (if any) plus the last maxMessages messages.
type HistoryProcessorFunc ¶
HistoryProcessorFunc is a function adapter for HistoryProcessor.
type Instrumentation ¶ added in v0.7.0
type Instrumentation interface {
StartAgent(context.Context, AgentOperation) (context.Context, AgentOperationSpan)
StartModelRequest(context.Context, ModelOperation) (context.Context, ModelOperationSpan)
StartTool(context.Context, ToolOperation) (context.Context, ToolOperationSpan)
}
Instrumentation is the dependency-neutral lifecycle observed by optional telemetry adapters. Implementations must treat values as immutable. Agentic isolates callback panics and ignores nil returned contexts and spans.
type InvalidRepresentationRequestError ¶ added in v0.6.0
type InvalidRepresentationRequestError = retrieval.InvalidRepresentationRequestError
type InvalidRepresentationResponseError ¶ added in v0.6.0
type InvalidRepresentationResponseError = retrieval.InvalidRepresentationResponseError
type JSONSchemaFormat ¶
type JSONSchemaFormat = core.JSONSchemaFormat
type MaxIterationsError ¶
type MaxIterationsError struct {
MaxIterations int
}
MaxIterationsError is returned when the agent hits the maximum iteration limit.
func (*MaxIterationsError) Error ¶
func (e *MaxIterationsError) Error() string
type Message ¶
func NewImageDataMessage ¶
NewImageDataMessage creates a user message with text and inline image data.
func NewImageFileMessage ¶
NewImageFileMessage creates a user message with text and an image loaded from a file. The media type is inferred from the file extension.
func NewImageURLMessage ¶
NewImageURLMessage creates a user message with text and an image URL.
func NewMultiPartMessage ¶
NewMultiPartMessage creates a user message with multiple content parts.
func NewTextMessage ¶
func NewTextMessage(role MessageRole, text string) Message
func NewToolResultMessage ¶
func NewToolResultMessageFor ¶ added in v0.3.0
NewToolResultMessageFor creates a tool-result message that records which tool produced it. Prefer this over NewToolResultMessage: name-keyed providers (Gemini) cannot correlate a result to its call without the name.
func NewToolUseMessage ¶
type MessageHistory ¶
type MessageHistory struct {
Messages []Message `json:"messages"`
}
MessageHistory is a serializable conversation history that can be saved, loaded, and used to resume conversations.
func LoadHistory ¶
func LoadHistory(data []byte) (*MessageHistory, error)
LoadHistory deserializes a MessageHistory from JSON bytes.
func NewHistory ¶
func NewHistory(messages ...Message) *MessageHistory
NewHistory creates a new MessageHistory from the given messages.
func (*MessageHistory) SaveJSON ¶
func (h *MessageHistory) SaveJSON() ([]byte, error)
SaveJSON serializes the MessageHistory to JSON bytes.
func (*MessageHistory) ToRunOption ¶
func (h *MessageHistory) ToRunOption() RunOption
ToRunOption converts the history into a RunOption that provides the messages as conversation history for a new run.
type MessageRole ¶
type MessageRole = core.MessageRole
type ModelMetadata ¶ added in v0.7.0
type ModelMetadata = core.ModelMetadata
type ModelMetadataProvider ¶ added in v0.7.0
type ModelMetadataProvider = core.ModelMetadataProvider
type ModelOperation ¶ added in v0.7.0
type ModelOperation struct {
Agent AgentIdentity
Model ModelMetadata
Run RunMetadata
// Request is a defensive observation copy. Opaque ProviderOptions are
// deliberately omitted because they may contain secrets, non-JSON values,
// or mutable provider-owned state.
Request ChatRequest
Iteration int
}
ModelOperation describes one logical provider request.
type ModelOperationResult ¶ added in v0.7.0
type ModelOperationResult struct {
Response *ChatResponse
Error error
}
ModelOperationResult is the terminal provider response or error.
type ModelOperationSpan ¶ added in v0.7.0
type ModelOperationSpan interface {
ObserveStreamEvent(StreamEvent)
End(ModelOperationResult)
}
type ModelRetry ¶
type ModelRetry = core.ModelRetry
ModelRetry is a sentinel error that tools can return to request a retry. When a tool returns this error, the error message is sent back to the LLM as a tool error, and the agent re-enters the loop (up to MaxRetries).
func Retry ¶
func Retry(msg string) *ModelRetry
Retry creates a ModelRetry error. Use this in tool handlers to tell the agent to send the error back to the model and try again.
Example:
func(input SearchInput) (SearchOutput, error) {
results := search(input.Query)
if len(results) == 0 {
return SearchOutput{}, agentic.Retry("No results found, try a different query")
}
return SearchOutput{Results: results}, nil
}
func Retryf ¶
func Retryf(format string, args ...interface{}) *ModelRetry
Retryf creates a ModelRetry error with a formatted message.
type NativeOutputSpec ¶
type NativeOutputSpec[T any] struct { // contains filtered or unexported fields }
NativeOutputSpec uses the model's native JSON schema output (response_format) for structured output. This is supported by OpenAI (json_schema) and Anthropic (output_config) on newer models.
The model is instructed via the API to produce JSON conforming to the schema of type T. No tool call is needed — the model returns JSON directly.
Example:
type MovieReview struct {
Title string `json:"title" description:"Movie title"`
Rating float64 `json:"rating" description:"Rating from 1-10"`
Summary string `json:"summary" description:"Brief review"`
}
output := agentic.NewNativeOutput[MovieReview]("movie_review", "A structured movie review")
func NewNativeOutput ¶
func NewNativeOutput[T any](name, description string) *NativeOutputSpec[T]
NewNativeOutput creates a NativeOutputSpec that uses native JSON schema output. The name identifies the schema (used in the API request). The description explains what the output represents.
func (*NativeOutputSpec[T]) Mode ¶
func (s *NativeOutputSpec[T]) Mode() OutputMode
Mode returns the output mode for this spec.
func (*NativeOutputSpec[T]) Parse ¶
func (s *NativeOutputSpec[T]) Parse(msg Message) (T, error)
Parse extracts the typed output from the assistant message text (JSON).
func (*NativeOutputSpec[T]) ResponseFormat ¶
func (s *NativeOutputSpec[T]) ResponseFormat() *ResponseFormat
ResponseFormat returns the ResponseFormat to include in the ChatRequest.
func (*NativeOutputSpec[T]) Tools ¶
func (s *NativeOutputSpec[T]) Tools() []Tool
Tools returns nil — native output does not use tools.
func (*NativeOutputSpec[T]) WithStrict ¶
func (s *NativeOutputSpec[T]) WithStrict(strict bool) *NativeOutputSpec[T]
WithStrict sets whether to enforce strict schema adherence. Default is true.
type OutputMode ¶
type OutputMode = core.OutputMode
type OutputModeSpec ¶
type OutputModeSpec[O any] interface { OutputSpec[O] Mode() OutputMode }
OutputModeSpec is implemented by output specs that carry an output mode. This is used by the agent to determine how to configure the request.
type OutputSpec ¶
type OutputSpec[O any] interface { // Tools returns any additional tools needed for output extraction. // For example, ToolOutputSpec adds a hidden "final_result" tool. Tools() []Tool // Parse extracts the typed output from the agent response. // It receives the final assistant message and returns the parsed output. Parse(msg Message) (O, error) }
OutputSpec defines how to extract structured output from the LLM response. The default (nil) extracts plain text.
type OutputValidatedEvent ¶ added in v0.4.0
type OutputValidatedEvent struct {
Candidate CompletionCandidate
// contains filtered or unexported fields
}
OutputValidatedEvent records a completion candidate that has passed parsing and all configured validators.
func (OutputValidatedEvent) Nature ¶ added in v0.4.0
func (e OutputValidatedEvent) Nature() EventNature
type OutputValidator ¶
OutputValidator validates agent text output and can request retries. When validation fails, the error message is sent back to the model and the agent re-enters the loop (up to maxValidationRetries).
For structured output, prefer using `validate` struct tags instead — they are applied automatically. Use OutputValidator for custom logic on the raw text response.
type OutputValidatorFunc ¶
OutputValidatorFunc is a function adapter for OutputValidator.
type OutputValidatorWithDeps ¶
type OutputValidatorWithDeps[D any] interface { Validate(RunContext[D], string) error }
OutputValidatorWithDeps validates text output with the exact run dependency.
type OutputValidatorWithDepsFunc ¶
type OutputValidatorWithDepsFunc[D any] func(RunContext[D], string) error
OutputValidatorWithDepsFunc adapts a dependency-aware validation function.
func (OutputValidatorWithDepsFunc[D]) Validate ¶
func (f OutputValidatorWithDepsFunc[D]) Validate(ctx RunContext[D], output string) error
type Part ¶
func AudioURLPart ¶
AudioURLPart creates an audio-from-URL content part.
func CachePointPart ¶
CachePointPart creates a cache point marker. When inserted into message content, it signals the provider to cache all content preceding this point. TTL can be "5m" (default) or "1h". Supported by: Anthropic, Amazon Bedrock. Silently ignored by other providers.
func DocumentURLPart ¶
DocumentURLPart creates a document-from-URL content part (e.g. PDF).
func ImageDataPart ¶
ImageDataPart creates an inline base64-encoded image content part.
func ImageURLPart ¶
ImageURLPart creates an image-from-URL content part. Optional detail parameter controls image processing fidelity ("auto", "low", "high").
func UploadedFilePart ¶
UploadedFilePart creates a reference to a file uploaded to a provider's file storage. The fileID is the provider-specific identifier returned by the provider's upload API. The providerName identifies which provider hosts the file (e.g. "anthropic", "openai").
func VideoURLPart ¶
VideoURLPart creates a video-from-URL content part.
type PlainToolHandler ¶
type PlainToolHandler[TInput any, TOutput any] = agentictool.PlainToolHandler[TInput, TOutput]
type PromptCacheConfig ¶ added in v0.6.0
type PromptCacheConfig = core.PromptCacheConfig
type PromptCacheRetention ¶ added in v0.6.0
type PromptCacheRetention = core.PromptCacheRetention
type PromptedOutputSpec ¶
type PromptedOutputSpec[T any] struct { // contains filtered or unexported fields }
PromptedOutputSpec instructs the model via the system prompt to output JSON conforming to a schema. The model receives the schema as text instructions and optionally uses the provider's JSON object mode (response_format: json_object) to ensure valid JSON output.
This is useful for providers/models that don't support native JSON schema output but do support JSON object mode.
Example:
output := agentic.NewPromptedOutput[MovieReview]()
func NewPromptedOutput ¶
func NewPromptedOutput[T any]() *PromptedOutputSpec[T]
NewPromptedOutput creates a PromptedOutputSpec.
func (*PromptedOutputSpec[T]) Mode ¶
func (s *PromptedOutputSpec[T]) Mode() OutputMode
Mode returns the output mode for this spec.
func (*PromptedOutputSpec[T]) Parse ¶
func (s *PromptedOutputSpec[T]) Parse(msg Message) (T, error)
Parse extracts the typed output from the assistant message text (JSON).
func (*PromptedOutputSpec[T]) ResponseFormat ¶
func (s *PromptedOutputSpec[T]) ResponseFormat() *ResponseFormat
ResponseFormat returns a json_object response format hint for providers that support it.
func (*PromptedOutputSpec[T]) SystemPromptSuffix ¶
func (s *PromptedOutputSpec[T]) SystemPromptSuffix() string
SystemPromptSuffix returns the text to append to the system prompt with the JSON schema instructions.
func (*PromptedOutputSpec[T]) Tools ¶
func (s *PromptedOutputSpec[T]) Tools() []Tool
Tools returns nil — prompted output does not use tools.
func (*PromptedOutputSpec[T]) WithTemplate ¶
func (s *PromptedOutputSpec[T]) WithTemplate(template string) *PromptedOutputSpec[T]
WithTemplate sets a custom template. Use {schema} as a placeholder for the JSON schema.
type ProviderError ¶ added in v0.3.0
type ProviderError struct {
// Reason is the provider's own description of the failure when it gave
// one, otherwise a description of what this library observed.
Reason string
}
ProviderError is returned when a provider completed the transport successfully but did not produce a usable turn — an in-band failure reported alongside a success status, or a response with no content at all.
func (*ProviderError) Error ¶ added in v0.3.0
func (e *ProviderError) Error() string
type Representation ¶ added in v0.6.0
type Representation = retrieval.Representation
type RepresentationCapabilities ¶ added in v0.6.0
type RepresentationCapabilities = retrieval.RepresentationCapabilities
type RepresentationEncoder ¶ added in v0.6.0
type RepresentationEncoder = retrieval.RepresentationEncoder
func EmbedderAsRepresentationEncoder ¶ added in v0.6.0
func EmbedderAsRepresentationEncoder(embedder Embedder, space VectorSpace) (RepresentationEncoder, error)
EmbedderAsRepresentationEncoder presents an existing dense Embedder as a dense-only RepresentationEncoder, so one code path can drive both the single-vector providers and the multi-output ones.
The vector space is supplied by the caller because an Embedder cannot prove one: it reports a model name and nothing about its weights revision or tokenizer. Only space.Provider is required. Model defaults to the embedder's name, Kind to dense, Metric to cosine, Dimensions to the width observed in the first response, and ID to the canonical hash of those fields.
type RepresentationKind ¶ added in v0.6.0
type RepresentationKind = retrieval.RepresentationKind
type RepresentationLimits ¶ added in v0.6.0
type RepresentationLimits = retrieval.RepresentationLimits
func DefaultRepresentationLimits ¶ added in v0.6.0
func DefaultRepresentationLimits() RepresentationLimits
DefaultRepresentationLimits returns the request and response ceilings every encoder in this repository applies: generous enough for normal retrieval workloads, tight enough that a malformed or hostile response cannot exhaust memory before validation runs.
It is exported because RepresentationValidator is. An encoder written outside this module cannot reach the same defaults otherwise, and would either invent its own numbers or run with every bound disabled — which would make a consumer's error behavior depend on where the encoder was compiled.
type RepresentationRequest ¶ added in v0.6.0
type RepresentationRequest = retrieval.RepresentationRequest
type RepresentationResponse ¶ added in v0.6.0
type RepresentationResponse = retrieval.RepresentationResponse
func EncodeDocuments ¶ added in v0.6.0
func EncodeDocuments( ctx context.Context, encoder RepresentationEncoder, texts []string, outputs ...RepresentationKind, ) (*RepresentationResponse, error)
EncodeDocuments encodes texts as documents to be stored and searched against, returning the requested representations for each.
Persist each output beside the ID of the space it came from — see [RepresentationResponse.Spaces]. Vectors without their space identity cannot be checked for compatibility later, and the failure mode of querying an index with a differently-encoded vector is quietly worse recall rather than an error.
func EncodeQueries ¶ added in v0.6.0
func EncodeQueries( ctx context.Context, encoder RepresentationEncoder, texts []string, outputs ...RepresentationKind, ) (*RepresentationResponse, error)
EncodeQueries encodes texts as search queries, returning the requested representations for each.
It is the multi-output counterpart of EmbedQuery. Outputs are explicit because they differ in cost by orders of magnitude; nothing is selected for you. Batching and splitting stay with the encoder, so what you pass is what it receives.
type RepresentationUsage ¶ added in v0.6.0
type RepresentationUsage = retrieval.RepresentationUsage
type RepresentationValidator ¶ added in v0.6.0
type RepresentationValidator = retrieval.RepresentationValidator
type RequestUsage ¶
type RequestUsage = core.RequestUsage
type RerankRequest ¶ added in v0.3.0
type RerankRequest = retrieval.RerankRequest
type RerankResponse ¶ added in v0.3.0
type RerankResponse = retrieval.RerankResponse
func Rerank ¶ added in v0.3.0
func Rerank(ctx context.Context, r Reranker, query string, documents []string, topN int) (*RerankResponse, error)
Rerank scores documents against a query and returns them ordered by descending relevance, keeping the topN highest-scoring. Pass 0 for topN to score every document.
Rerankers are cross-encoders and cost far more per document than an embedding comparison, so the usual arrangement is to retrieve a broad shortlist with EmbedQuery and narrow it here.
Scores are ordinal within one response: rank by them, but never threshold on them or compare them across providers or models. See RerankResult.
type RerankResult ¶ added in v0.3.0
type RerankResult = retrieval.RerankResult
type RerankUsage ¶ added in v0.3.0
type RerankUsage = retrieval.RerankUsage
type ResponseFormat ¶
type ResponseFormat = core.ResponseFormat
type ResponseFormatSpec ¶
type ResponseFormatSpec interface {
ResponseFormat() *ResponseFormat
}
ResponseFormatSpec is implemented by output specs that need a response_format in the ChatRequest (NativeOutputSpec and PromptedOutputSpec).
type Result ¶
type Result[O any] struct { // Output is the final typed output from the agent. Output O // Messages is the complete conversation history including tool interactions. Messages []Message // ToolCalls contains all tool calls made during the run. ToolCalls []ToolUse // ToolResults contains all tool results from executed tools. ToolResults []ToolExecutionResult // FinishReason indicates why the agent stopped. FinishReason FinishReason // Usage contains cumulative token usage for the entire run. Usage Usage // Retries is the number of retries that occurred. Retries int // contains filtered or unexported fields }
Result contains the result of an agent run.
func (*Result[O]) AllMessages ¶
AllMessages returns the complete conversation history including any history supplied to the run.
func (*Result[O]) History ¶
func (r *Result[O]) History() *MessageHistory
History returns a serializable history containing all run messages.
func (*Result[O]) NewMessages ¶
NewMessages returns only messages generated during this run.
type ResumeInput ¶ added in v0.4.0
type ResumeInput struct {
History []Message
Suspension Suspension
Decisions []ToolResumeDecision
Prompt *Message
}
ResumeInput resolves a suspended executable tool frontier. Prompt, when supplied, is appended only after all resolved tool results.
type RetryConfig ¶
type RetryConfig struct {
MaxRetries int
}
RetryConfig controls retries requested by tools.
type RunCompletedEvent ¶ added in v0.4.0
type RunCompletedEvent struct {
Usage Usage
FinishReason FinishReason
// contains filtered or unexported fields
}
func (RunCompletedEvent) Nature ¶ added in v0.4.0
func (e RunCompletedEvent) Nature() EventNature
type RunContext ¶
type RunContext[D any] = core.RunContext[D]
type RunEndedEvent ¶ added in v0.4.0
type RunEndedEvent struct {
Status ExecutionStatus
// contains filtered or unexported fields
}
func (RunEndedEvent) Nature ¶ added in v0.4.0
func (e RunEndedEvent) Nature() EventNature
type RunErrorEvent ¶ added in v0.4.0
type RunErrorEvent struct {
Error error
// contains filtered or unexported fields
}
func (RunErrorEvent) Nature ¶ added in v0.4.0
func (e RunErrorEvent) Nature() EventNature
type RunInterruptedEvent ¶ added in v0.4.0
type RunInterruptedEvent struct {
// contains filtered or unexported fields
}
func (RunInterruptedEvent) Nature ¶ added in v0.4.0
func (e RunInterruptedEvent) Nature() EventNature
type RunMetadata ¶ added in v0.7.0
RunMetadata contains correlation identifiers owned by a higher-level runtime. ConversationID maps to gen_ai.conversation.id; RunID is an Agentic-specific durable execution identifier.
type RunOption ¶
type RunOption func(*runOptions)
RunOption configures one run.
func WithMessages ¶
func WithRunEndStrategy ¶
func WithRunEndStrategy(strategy EndStrategy) RunOption
func WithRunEventSink ¶ added in v0.4.0
WithRunEventSink installs a synchronous canonical event sink for this execution only.
func WithRunHistoryProcessor ¶
func WithRunHistoryProcessor(p HistoryProcessor) RunOption
func WithRunInstrumentation ¶ added in v0.7.0
func WithRunInstrumentation(instrumentation Instrumentation) RunOption
WithRunInstrumentation overrides the agent-level observer for one execution. Passing nil disables observation for that execution.
func WithRunMaxIterations ¶
func WithRunMaxTokens ¶
func WithRunMetadata ¶ added in v0.7.0
func WithRunMetadata(metadata RunMetadata) RunOption
WithRunMetadata attaches correlation identifiers supplied by the owning runtime. Agentic never invents conversation or durable run identifiers. Nested agents inherit these identifiers unless a run explicitly replaces them, including with an empty value.
func WithRunModelStreaming ¶ added in v0.4.0
WithRunModelStreaming asks Driver to use the model streaming transport when it is available. The driver still returns one ordinary Execution.
func WithRunPromptCache ¶ added in v0.6.0
func WithRunPromptCache(config PromptCacheConfig) RunOption
WithRunPromptCache sets the stable cache identity for one run. It is a run option so session runtimes can bind their durable ID after agent creation.
func WithRunTemperature ¶
func WithRunToolCancellationGrace ¶ added in v0.4.0
WithRunToolCancellationGrace bounds how long the scheduler waits for already-admitted handlers after execution context cancellation.
func WithRunToolChoice ¶
func WithRunToolChoice(choice ToolChoice) RunOption
func WithRunToolGate ¶ added in v0.4.0
WithRunToolGate preflights regular tool batches for this execution.
func WithRunToolResultProcessor ¶ added in v0.4.0
func WithRunToolResultProcessor(processor ToolResultProcessor) RunOption
WithRunToolResultProcessor projects handler results before commit.
func WithRunToolsets ¶ added in v0.4.0
WithRunToolsets overlays immutable toolsets for this execution. The shared agent registry is never mutated.
func WithRunTurnHook ¶ added in v0.4.0
WithRunTurnHook installs a control hook for this execution only. It is a RunOption so bound runners can be controlled after dependencies are bound.
func WithRunUsageLimits ¶
func WithRunUsageLimits(limits UsageLimits) RunOption
type RunStartedEvent ¶ added in v0.4.0
type RunStartedEvent struct {
// contains filtered or unexported fields
}
func (RunStartedEvent) Nature ¶ added in v0.4.0
func (e RunStartedEvent) Nature() EventNature
type RunSuspendedEvent ¶ added in v0.4.0
type RunSuspendedEvent struct {
Suspension Suspension
// contains filtered or unexported fields
}
func (RunSuspendedEvent) Nature ¶ added in v0.4.0
func (e RunSuspendedEvent) Nature() EventNature
type Runner ¶
Runner is a ready-to-run agent capability. Dependencies, if any, have already been supplied.
type SimilarityMetric ¶ added in v0.6.0
type SimilarityMetric = retrieval.SimilarityMetric
type SparseVector ¶ added in v0.6.0
type SparseVector = retrieval.SparseVector
type StreamEvent ¶
type StreamEvent = core.StreamEvent
type StreamEventType ¶
type StreamEventType = core.StreamEventType
type StreamModel ¶
type StreamModel = core.StreamModel
type StreamResult ¶
type StreamResult = core.StreamResult
func NewStreamResult ¶
func NewStreamResult(ch <-chan StreamEvent) *StreamResult
type StreamRunner ¶
type StreamRunner interface {
RunStream(context.Context, string, ...RunOption) (*StreamResult, error)
}
StreamRunner is the independent streaming capability.
type StreamingRunner ¶
type StreamingRunner[O any] interface { Runner[O] StreamRunner }
StreamingRunner combines typed execution and streaming.
type SuspendableToolHandler ¶ added in v0.5.0
type SuspendableToolHandler interface {
MaySuspendToolExecution() bool
}
SuspendableToolHandler is an optional marker implemented by a handler that may return ToolHandlerSuspension. A suspendable handler is isolated from other regular calls before execution so a post-start deferral cannot be mixed with unrelated effects.
type Suspension ¶ added in v0.4.0
type Suspension = core.Suspension
type SystemPromptAppender ¶
type SystemPromptAppender interface {
SystemPromptSuffix() string
}
SystemPromptAppender is implemented by output specs that need to append instructions to the system prompt (PromptedOutputSpec).
type TextOutputSpec ¶
type TextOutputSpec struct{}
TextOutputSpec is the default output spec — extracts text content.
func (*TextOutputSpec) Tools ¶
func (s *TextOutputSpec) Tools() []Tool
type TextPreviewEvent ¶ added in v0.4.0
type TextPreviewEvent struct {
Delta string
// contains filtered or unexported fields
}
TextPreviewEvent carries a transient text delta from a streaming transport.
func (TextPreviewEvent) Nature ¶ added in v0.4.0
func (e TextPreviewEvent) Nature() EventNature
type TextProcessorOutputSpec ¶
type TextProcessorOutputSpec[T any] struct { // contains filtered or unexported fields }
TextProcessorOutputSpec uses a custom function to convert raw text output into a typed result. The model returns plain text, and the processor function transforms it into the desired output type.
Example:
output := agentic.NewTextProcessorOutput(func(text string) (int, error) {
return strconv.Atoi(strings.TrimSpace(text))
})
func NewTextProcessorOutput ¶
func NewTextProcessorOutput[T any](processor func(string) (T, error)) *TextProcessorOutputSpec[T]
NewTextProcessorOutput creates a TextProcessorOutputSpec with the given processor function.
func (*TextProcessorOutputSpec[T]) Mode ¶
func (s *TextProcessorOutputSpec[T]) Mode() OutputMode
Mode returns the output mode for this spec.
func (*TextProcessorOutputSpec[T]) Parse ¶
func (s *TextProcessorOutputSpec[T]) Parse(msg Message) (T, error)
Parse extracts text from the message and runs it through the processor function.
func (*TextProcessorOutputSpec[T]) Tools ¶
func (s *TextProcessorOutputSpec[T]) Tools() []Tool
Tools returns nil — text processor output does not use tools.
type ThinkingBlock ¶
type ThinkingBlock = core.ThinkingBlock
type ThinkingConfig ¶
type ThinkingConfig = core.ThinkingConfig
type ThinkingPreviewEvent ¶ added in v0.4.0
type ThinkingPreviewEvent struct {
Delta string
Signature string
ProviderName string
ThinkingID string
// contains filtered or unexported fields
}
ThinkingPreviewEvent carries a transient thinking delta from a streaming transport, including provider replay metadata when available.
func (ThinkingPreviewEvent) Nature ¶ added in v0.4.0
func (e ThinkingPreviewEvent) Nature() EventNature
type ToolArgumentPreviewEvent ¶ added in v0.4.0
type ToolArgumentPreviewEvent struct {
ToolCallID string
Delta string
// contains filtered or unexported fields
}
ToolArgumentPreviewEvent carries a transient JSON-argument delta.
func (ToolArgumentPreviewEvent) Nature ¶ added in v0.4.0
func (e ToolArgumentPreviewEvent) Nature() EventNature
type ToolBatchDecision ¶ added in v0.4.0
type ToolBatchDecision struct {
Calls []ToolDisposition
Deferral *ToolDeferral
}
ToolBatchDecision contains exactly one disposition for every input call in the same order. A suspension applies atomically to the entire batch.
type ToolBatchPlannedEvent ¶ added in v0.4.0
type ToolBatchPlannedEvent struct {
Calls []ToolUse
// contains filtered or unexported fields
}
ToolBatchPlannedEvent is emitted after call classification and before any regular tool handler starts.
func (ToolBatchPlannedEvent) Nature ¶ added in v0.4.0
func (e ToolBatchPlannedEvent) Nature() EventNature
type ToolCallContext ¶ added in v0.4.0
ToolCallContext identifies the handler invocation currently associated with a context. It is available to plain and dependency-aware tools alike.
func CurrentToolCall ¶ added in v0.4.0
func CurrentToolCall(ctx context.Context) (ToolCallContext, bool)
CurrentToolCall returns public metadata for the tool invocation associated with ctx.
type ToolCallPreviewEvent ¶ added in v0.4.0
type ToolCallPreviewEvent struct {
Call ToolUse
// contains filtered or unexported fields
}
ToolCallPreviewEvent announces a model-emitted tool call before the complete assistant message is committed. It exists so the legacy streaming adapter can preserve its tool-call-start projection without treating that preview as an admitted handler start.
func (ToolCallPreviewEvent) Nature ¶ added in v0.4.0
func (e ToolCallPreviewEvent) Nature() EventNature
type ToolChoice ¶
type ToolChoice = core.ToolChoice
type ToolConfig ¶
type ToolConfig = core.ToolConfig
type ToolDeferral ¶ added in v0.4.0
type ToolDeferral struct {
Kind string
Payload json.RawMessage
}
ToolDeferral is serializable gate-owned metadata carried in Suspension.
type ToolDisposition ¶ added in v0.4.0
type ToolDisposition struct {
Kind ToolDispositionKind
Result *ToolExecutionResult
Continue bool
}
ToolDisposition describes one gated call.
type ToolDispositionKind ¶ added in v0.4.0
type ToolDispositionKind uint8
ToolDispositionKind is the permitted gate disposition.
const ( ToolDispositionInvalid ToolDispositionKind = iota ToolDispositionExecute ToolDispositionReturn ToolDispositionSuspend )
type ToolExecutionResult ¶
type ToolExecutionResult = core.ToolExecutionResult
type ToolGate ¶ added in v0.4.0
type ToolGate interface {
EvaluateBatch(context.Context, []ToolUse) (ToolBatchDecision, error)
}
ToolGate preflights an entire regular-tool batch before any handler starts. Output tools are framework calls and are not passed to the gate.
type ToolGateFunc ¶ added in v0.4.0
type ToolGateFunc func(context.Context, []ToolUse) (ToolBatchDecision, error)
ToolGateFunc adapts a function to ToolGate.
func (ToolGateFunc) EvaluateBatch ¶ added in v0.4.0
func (f ToolGateFunc) EvaluateBatch(ctx context.Context, calls []ToolUse) (ToolBatchDecision, error)
type ToolHandler ¶
type ToolHandler = core.ToolHandler
type ToolHandlerSuspension ¶ added in v0.5.0
type ToolHandlerSuspension struct {
Deferral ToolDeferral
}
ToolHandlerSuspension asks the driver to leave the current tool frontier open and return ExecutionSuspended. It is meaningful only when returned by a handler implementing SuspendableToolHandler.
type ToolOperation ¶ added in v0.7.0
type ToolOperation struct {
Agent AgentIdentity
Run RunMetadata
Call ToolUse
Definition Tool
Attempt int
// HandlerResumed is true only when a suspendable handler is re-entered with
// ToolResumeContext. A call admitted after an approval-gate suspension is a
// fresh handler execution and remains false.
HandlerResumed bool
}
ToolOperation describes one admitted handler invocation.
type ToolOperationResult ¶ added in v0.7.0
type ToolOperationResult struct {
Result ToolExecutionResult
Error error
Suspended bool
}
ToolOperationResult is the raw handler result before result processors run.
type ToolOperationSpan ¶ added in v0.7.0
type ToolOperationSpan interface {
End(ToolOperationResult)
}
type ToolOption ¶
type ToolOption = agentictool.ToolOption
func WithToolMaxRetries ¶
func WithToolMaxRetries(n int) ToolOption
WithToolMaxRetries sets the max retry count for a specific tool.
type ToolOutputSpec ¶
type ToolOutputSpec[T any] struct { // contains filtered or unexported fields }
ToolOutputSpec uses a designated tool call for structured output. The LLM is instructed to call a tool whose input IS the structured output. This is the most reliable way to get structured output across all providers.
func NewToolOutput ¶
func NewToolOutput[T any](description string) *ToolOutputSpec[T]
NewToolOutput creates a ToolOutputSpec that extracts structured output via a tool call. The type T defines the output schema. The LLM will be given a tool with this schema and instructed to call it with the final result.
Use `validate` struct tags to enforce constraints on the output. If the LLM produces invalid output, the validation error is sent back to the model for automatic retry. See https://github.com/go-playground/validator for all available tags.
Example:
type MovieReview struct {
Title string `json:"title" validate:"required,min=1" description:"Movie title"`
Rating float64 `json:"rating" validate:"required,min=1,max=10" description:"Rating from 1-10"`
Genre string `json:"genre" validate:"required,oneof=action comedy drama" description:"Movie genre"`
Summary string `json:"summary" validate:"required,min=10" description:"Brief review"`
}
output := agentic.NewToolOutput[MovieReview]("Review a movie and provide structured feedback")
func (*ToolOutputSpec[T]) Parse ¶
func (s *ToolOutputSpec[T]) Parse(msg Message) (T, error)
func (*ToolOutputSpec[T]) Tools ¶
func (s *ToolOutputSpec[T]) Tools() []Tool
type ToolPrepareFunc ¶
ToolPrepareFunc customizes the tools sent before each model request.
type ToolPrepareFuncWithDeps ¶
type ToolPrepareFuncWithDeps[D any] func(RunContext[D], []Tool) ([]Tool, error)
ToolPrepareFuncWithDeps customizes tools with access to exact run deps.
type ToolRegistry ¶
type ToolRegistry = agentictool.ToolRegistry
func NewRegistry ¶
func NewRegistry() ToolRegistry
type ToolResult ¶
type ToolResult = core.ToolResult
type ToolResultCommittedEvent ¶ added in v0.4.0
type ToolResultCommittedEvent struct {
Result ToolExecutionResult
// contains filtered or unexported fields
}
ToolResultCommittedEvent is emitted after a paired tool result is appended.
func (ToolResultCommittedEvent) Nature ¶ added in v0.4.0
func (e ToolResultCommittedEvent) Nature() EventNature
type ToolResultProcessor ¶ added in v0.4.0
type ToolResultProcessor interface {
Process(context.Context, ToolUse, ToolExecutionResult) (ToolExecutionResult, error)
}
ToolResultProcessor projects a handler result before it is committed to the transcript and formatted for the model. It cannot change call identity or turn a handler error into success.
type ToolResultProcessorFunc ¶ added in v0.4.0
type ToolResultProcessorFunc func(context.Context, ToolUse, ToolExecutionResult) (ToolExecutionResult, error)
ToolResultProcessorFunc adapts a function to ToolResultProcessor.
func (ToolResultProcessorFunc) Process ¶ added in v0.4.0
func (f ToolResultProcessorFunc) Process(ctx context.Context, call ToolUse, result ToolExecutionResult) (ToolExecutionResult, error)
type ToolResumeAction ¶ added in v0.4.0
type ToolResumeAction uint8
ToolResumeAction describes how a suspended tool call is completed.
const ( ToolResumeInvalid ToolResumeAction = iota ToolResumeExecute ToolResumeReturn )
type ToolResumeContext ¶ added in v0.5.0
type ToolResumeContext struct {
SuspensionID string
Deferral ToolDeferral
Payload json.RawMessage
}
ToolResumeContext is attached only while Driver.Resume re-enters a handler that previously returned ToolHandlerSuspension. Deferral is the exact handler-owned value carried by the durable root suspension. Payload is the caller-validated opaque data from ToolResumeDecision.
func CurrentToolResume ¶ added in v0.5.0
func CurrentToolResume(ctx context.Context) (ToolResumeContext, bool)
CurrentToolResume returns the exact resume metadata for the current handler. Ordinary handler execution returns false.
type ToolResumeDecision ¶ added in v0.4.0
type ToolResumeDecision struct {
CallID string
Action ToolResumeAction
// Input nil means use the original persisted tool arguments.
Input map[string]any
Result *ToolExecutionResult
// Payload is opaque handler-owned resume data. The driver never interprets
// it; it is exposed only through CurrentToolResume while re-entering a
// suspendable handler. It is valid only with ToolResumeExecute.
Payload json.RawMessage
}
ToolResumeDecision resolves one executable call from a suspension.
type ToolStartedEvent ¶ added in v0.4.0
ToolStartedEvent is emitted immediately before an admitted handler starts.
func (ToolStartedEvent) Nature ¶ added in v0.4.0
func (e ToolStartedEvent) Nature() EventNature
type Turn ¶ added in v0.4.0
type Turn struct {
Index int
Messages []Message
Assistant Message
Results []ToolExecutionResult
Usage Usage
Candidate CompletionCandidate
}
Turn is the committed state visible to a per-run turn hook. Slices and messages are defensive copies owned by the hook invocation.
type TurnAction ¶ added in v0.4.0
type TurnAction uint8
TurnAction controls terminal arbitration after a committed turn.
const ( TurnDefault TurnAction = iota TurnContinue TurnStop )
type TurnDecision ¶ added in v0.4.0
type TurnDecision struct {
Action TurnAction
Inject []Message
}
TurnDecision is returned by a TurnHook. Inject is valid only with TurnContinue and contains one or more user messages.
type TurnEndedEvent ¶ added in v0.4.0
type TurnEndedEvent struct {
Candidate CompletionCandidate
Usage Usage
// contains filtered or unexported fields
}
TurnEndedEvent records a fully committed turn, including validation retry and tool-only turns. Candidate is zero when the turn has no valid output.
func (TurnEndedEvent) Nature ¶ added in v0.4.0
func (e TurnEndedEvent) Nature() EventNature
type TurnHook ¶ added in v0.4.0
type TurnHook func(context.Context, Turn) (TurnDecision, error)
TurnHook runs after turn commit and candidate validation, but before the single terminal-arbitration decision.
type TurnMessagesInjectedEvent ¶ added in v0.4.0
type TurnMessagesInjectedEvent struct {
Messages []Message
// contains filtered or unexported fields
}
TurnMessagesInjectedEvent records user messages injected by a turn hook.
func (TurnMessagesInjectedEvent) Nature ¶ added in v0.4.0
func (e TurnMessagesInjectedEvent) Nature() EventNature
type TurnStartedEvent ¶ added in v0.4.0
type TurnStartedEvent struct {
// contains filtered or unexported fields
}
func (TurnStartedEvent) Nature ¶ added in v0.4.0
func (e TurnStartedEvent) Nature() EventNature
type TypedAgent ¶
type TypedAgent[O any] struct { // contains filtered or unexported fields }
TypedAgent is a structured-output agent without application dependencies.
func NewTypedAgent ¶
func NewTypedAgent[O any](systemPrompt string, model Model, outputDescription string, opts ...AgentOption) *TypedAgent[O]
func NewTypedAgentDynamic ¶
func NewTypedAgentDynamic[O any](promptFn DynamicPrompt, model Model, outputDescription string, opts ...AgentOption) *TypedAgent[O]
func NewTypedAgentWithMode ¶
func NewTypedAgentWithMode[O any](systemPrompt string, model Model, output OutputSpec[O], opts ...AgentOption) *TypedAgent[O]
func (*TypedAgent[O]) AddAutoTool ¶
func (a *TypedAgent[O]) AddAutoTool(tool Tool, handler ToolHandler) *TypedAgent[O]
func (*TypedAgent[O]) AddHandoff ¶
func (a *TypedAgent[O]) AddHandoff(h *Handoff) *TypedAgent[O]
func (*TypedAgent[O]) AddOutputValidator ¶
func (a *TypedAgent[O]) AddOutputValidator(v TypedOutputValidator[O]) *TypedAgent[O]
func (*TypedAgent[O]) AddTool ¶
func (a *TypedAgent[O]) AddTool(tool Tool, handler ToolHandler) *TypedAgent[O]
func (*TypedAgent[O]) AddToolset ¶
func (a *TypedAgent[O]) AddToolset(set Toolset) *TypedAgent[O]
func (*TypedAgent[O]) Drive ¶ added in v0.4.0
func (a *TypedAgent[O]) Drive(ctx context.Context, input DriveInput, opts ...RunOption) (*Execution[O], error)
Drive starts or continues a dependency-free typed execution.
func (*TypedAgent[O]) Resume ¶ added in v0.4.0
func (a *TypedAgent[O]) Resume(ctx context.Context, input ResumeInput, opts ...RunOption) (*Execution[O], error)
Resume completes a suspended dependency-free typed execution.
func (*TypedAgent[O]) RunStream ¶
func (a *TypedAgent[O]) RunStream(ctx context.Context, prompt string, opts ...RunOption) (*StreamResult, error)
func (*TypedAgent[O]) SetRegistry ¶
func (a *TypedAgent[O]) SetRegistry(registry ToolRegistry) *TypedAgent[O]
type TypedAgentWithDeps ¶
type TypedAgentWithDeps[O, D any] struct { // contains filtered or unexported fields }
TypedAgentWithDeps is a structured-output agent carrying exact O and D.
func NewTypedAgentWithDeps ¶
func NewTypedAgentWithDeps[O, D any](systemPrompt string, model Model, outputDescription string, opts ...AgentOption) *TypedAgentWithDeps[O, D]
func NewTypedAgentWithDepsDynamic ¶
func NewTypedAgentWithDepsDynamic[O, D any](promptFn DynamicPromptWithDeps[D], model Model, outputDescription string, opts ...AgentOption) *TypedAgentWithDeps[O, D]
func NewTypedAgentWithDepsMode ¶
func NewTypedAgentWithDepsMode[O, D any](systemPrompt string, model Model, output OutputSpec[O], opts ...AgentOption) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) AddAutoTool ¶
func (a *TypedAgentWithDeps[O, D]) AddAutoTool(tool Tool, handler ToolHandler) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) AddHandoff ¶
func (a *TypedAgentWithDeps[O, D]) AddHandoff(h *Handoff) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) AddHandoffWithDeps ¶
func (a *TypedAgentWithDeps[O, D]) AddHandoffWithDeps(h *HandoffWithDeps[D]) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) AddOutputValidator ¶
func (a *TypedAgentWithDeps[O, D]) AddOutputValidator(v TypedOutputValidator[O]) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) AddOutputValidatorWithDeps ¶
func (a *TypedAgentWithDeps[O, D]) AddOutputValidatorWithDeps(v TypedOutputValidatorWithDeps[D, O]) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) AddTextOutputValidator ¶
func (a *TypedAgentWithDeps[O, D]) AddTextOutputValidator(v OutputValidatorWithDeps[D]) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) AddTool ¶
func (a *TypedAgentWithDeps[O, D]) AddTool(tool Tool, handler ToolHandler) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) AddToolset ¶
func (a *TypedAgentWithDeps[O, D]) AddToolset(set Toolset) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) Bind ¶
func (a *TypedAgentWithDeps[O, D]) Bind(deps D) Runner[O]
func (*TypedAgentWithDeps[O, D]) BindProvider ¶
func (a *TypedAgentWithDeps[O, D]) BindProvider(provider DepsProvider[D]) Runner[O]
func (*TypedAgentWithDeps[O, D]) Drive ¶ added in v0.4.0
func (a *TypedAgentWithDeps[O, D]) Drive(ctx context.Context, input DriveInput, deps D, opts ...RunOption) (*Execution[O], error)
Drive starts or continues a dependency-aware typed execution with its exact dependency value.
func (*TypedAgentWithDeps[O, D]) Resume ¶ added in v0.4.0
func (a *TypedAgentWithDeps[O, D]) Resume(ctx context.Context, input ResumeInput, deps D, opts ...RunOption) (*Execution[O], error)
Resume completes a suspended dependency-aware typed execution with its exact dependency value.
func (*TypedAgentWithDeps[O, D]) RunStream ¶
func (a *TypedAgentWithDeps[O, D]) RunStream(ctx context.Context, prompt string, deps D, opts ...RunOption) (*StreamResult, error)
func (*TypedAgentWithDeps[O, D]) SetDepsValidator ¶
func (a *TypedAgentWithDeps[O, D]) SetDepsValidator(fn DepsValidator[D]) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) SetDynamicPrompt ¶
func (a *TypedAgentWithDeps[O, D]) SetDynamicPrompt(fn DynamicPromptWithDeps[D]) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) SetRegistry ¶
func (a *TypedAgentWithDeps[O, D]) SetRegistry(registry ToolRegistry) *TypedAgentWithDeps[O, D]
func (*TypedAgentWithDeps[O, D]) SetToolPrepare ¶
func (a *TypedAgentWithDeps[O, D]) SetToolPrepare(fn ToolPrepareFuncWithDeps[D]) *TypedAgentWithDeps[O, D]
type TypedOutputValidator ¶
TypedOutputValidator validates typed structured output. Use this for programmatic validation that goes beyond what struct tags can express.
type TypedOutputValidatorFunc ¶
TypedOutputValidatorFunc is a function adapter for TypedOutputValidator.
func (TypedOutputValidatorFunc[O]) ValidateTyped ¶
func (f TypedOutputValidatorFunc[O]) ValidateTyped(ctx context.Context, output O) error
ValidateTyped implements TypedOutputValidator.
type TypedOutputValidatorWithDeps ¶
type TypedOutputValidatorWithDeps[D, O any] interface { ValidateTyped(RunContext[D], O) error }
TypedOutputValidatorWithDeps validates structured output with exact D and O.
type TypedOutputValidatorWithDepsFunc ¶
type TypedOutputValidatorWithDepsFunc[D, O any] func(RunContext[D], O) error
TypedOutputValidatorWithDepsFunc adapts a dependency-aware typed validator.
func (TypedOutputValidatorWithDepsFunc[D, O]) ValidateTyped ¶
func (f TypedOutputValidatorWithDepsFunc[D, O]) ValidateTyped(ctx RunContext[D], output O) error
type TypedRunResult ¶
TypedRunResult is the typed-output result retained as a familiar name.
type UnsupportedRepresentationError ¶ added in v0.6.0
type UnsupportedRepresentationError = retrieval.UnsupportedRepresentationError
type UploadedFile ¶
type UploadedFile = core.UploadedFile
type UsageLimitExceededError ¶
type UsageLimitExceededError struct {
// LimitName describes which limit was exceeded (e.g., "request_tokens", "requests").
LimitName string
// Current is the current value at the time the limit was exceeded.
Current int
// Max is the configured limit that was exceeded.
Max int
}
UsageLimitExceededError is returned when a usage limit is hit during an agent run.
func (*UsageLimitExceededError) Error ¶
func (e *UsageLimitExceededError) Error() string
type UsageLimits ¶
type UsageLimits struct {
// MaxRequestTokens caps the total prompt (input) tokens across all requests.
MaxRequestTokens *int
// MaxResponseTokens caps the total completion (output) tokens across all requests.
MaxResponseTokens *int
// MaxTotalTokens caps the combined (prompt + completion) tokens across all requests.
MaxTotalTokens *int
// MaxRequests caps the number of LLM API requests in a single run.
// Default is 50 when UsageLimits is set (via DefaultUsageLimits).
MaxRequests *int
// MaxToolCalls caps the number of successful tool call executions in a single run.
MaxToolCalls *int
}
UsageLimits defines caps on token and request usage for an agent run. All fields are pointers — nil means "no limit".
func DefaultUsageLimits ¶
func DefaultUsageLimits() UsageLimits
DefaultUsageLimits returns UsageLimits with only the request limit set (50), matching pydantic-ai's default behavior.
type ValidationError ¶
type ValidationError struct {
Message string
}
ValidationError signals output validation failed and the model should retry. Return this from a validator to have the agent send the message back to the model and request a new response.
func NewValidationError ¶
func NewValidationError(msg string) *ValidationError
NewValidationError creates a ValidationError with the given message.
func NewValidationErrorf ¶
func NewValidationErrorf(format string, args ...interface{}) *ValidationError
NewValidationErrorf creates a ValidationError with a formatted message.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type VectorSpace ¶ added in v0.6.0
type VectorSpace = retrieval.VectorSpace
Source Files
¶
- agent.go
- agent_options.go
- aliases.go
- doc.go
- driver.go
- embedding.go
- errors.go
- events.go
- execution_loop.go
- handoff.go
- history.go
- history_processor.go
- instrumentation.go
- multimodal.go
- output.go
- output_mode.go
- ptr.go
- representation.go
- reranking.go
- result.go
- run_state.go
- stream.go
- suspension.go
- tool_control.go
- tool_scheduler.go
- transcript.go
- turn.go
- typed_agent.go
- usage_limits.go
- validator.go
Directories
¶
| Path | Synopsis |
|---|---|
|
harness
module
|
|
|
codemode/gomonty
module
|
|
|
sessionloop
module
|
|
|
internal
|
|
|
core
Package core holds the chat primitives: the conversation, the model interface, the streaming protocol, and tool execution.
|
Package core holds the chat primitives: the conversation, the model interface, the streaming protocol, and tool execution. |
|
providerhttp
Package providerhttp carries the JSON-over-HTTP transport shared by the providers that POST a JSON body and read one back: bearer authentication, a bounded retry on 429 and transient 5xx responses, a bounded read of the response body, and an error that reports a failure without quoting the request back.
|
Package providerhttp carries the JSON-over-HTTP transport shared by the providers that POST a JSON body and read one back: bearer authentication, a bounded retry on 429 and transient 5xx responses, a bounded read of the response body, and an error that reports a failure without quoting the request back. |
|
retrieval
Package retrieval holds the vector primitives: embedding, multi-representation encoding, reranking, and the vector-space identity all three are keyed on.
|
Package retrieval holds the vector primitives: embedding, multi-representation encoding, reranking, and the vector-space identity all three are keyed on. |
|
retrieval/batch
Package batch splits an oversized encoding request into chunks a provider will accept, and reassembles the chunks into a single response that still satisfies the core contract.
|
Package batch splits an oversized encoding request into chunks a provider will accept, and reassembles the chunks into a single response that still satisfies the core contract. |
|
retrieval/embedbatch
Package embedbatch adapts providers whose native batch shape does not match the batch-first contract of retrieval.Embedder.
|
Package embedbatch adapts providers whose native batch shape does not match the batch-first contract of retrieval.Embedder. |
|
retrieval/wire
Package wire implements agentic.representations.v1, the portable JSON contract between Agentic and a self-operated inference endpoint.
|
Package wire implements agentic.representations.v1, the portable JSON contract between Agentic and a self-operated inference endpoint. |
|
testutil
Package testutil holds the test doubles the root package's own tests share.
|
Package testutil holds the test doubles the root package's own tests share. |
|
Package mcp provides Model Context Protocol (MCP) client integration for Agentic.
|
Package mcp provides Model Context Protocol (MCP) client integration for Agentic. |
|
otel
module
|
|
|
provider
|
|
|
test
Package test provides test doubles and contract suites for code built on Agentic.
|
Package test provides test doubles and contract suites for code built on Agentic. |
|
test/conformance
Package conformance holds the shared contract suite for representation encoders.
|
Package conformance holds the shared contract suite for representation encoders. |
|
anthropic
module
|
|
|
bedrock
module
|
|
|
cohere
module
|
|
|
deepinfra
module
|
|
|
endpoint
module
|
|
|
huggingface
module
|
|
|
local/onnx
module
|
|
|
openai
module
|
|
|
openrouter
module
|
|
|
pinecone
module
|
|
|
together
module
|
|
|
voyageai
module
|
|
|
realtime
module
|
|
|
Package tool provides tool definitions, handlers, registries, and toolsets for building LLM-callable tools in Agentic agents.
|
Package tool provides tool definitions, handlers, registries, and toolsets for building LLM-callable tools in Agentic agents. |
|
tui
module
|