agentic

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: MIT Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Agentic

CI Go Reference

A lightweight, type-safe Go framework for building AI agents with tool use, structured output, and multi-agent orchestration.

Current release: v0.8.0.

Features

  • Provider-agnostic -- pluggable Model interface with 9 built-in providers
  • Type-safe tools -- generic tool builders with automatic JSON Schema generation from Go structs
  • Structured output -- TypedAgent[OutputT] returns validated typed results
  • Streaming -- first-class streaming with channel-based event delivery
  • Resumable execution -- explicit Driver control for start, continue, gate or handler suspension, and resume
  • Execution events -- canonical lifecycle, transcript, tool, and preview events for one run
  • Dependency injection -- opt-in, exact dependency types shared by runs, prompts, tools, validators, and handoffs
  • Multi-agent -- delegate tasks between agents with Handoff
  • Context-aware tools -- cancellation, deadlines, tracing, and request-scoped values
  • Approval and channel tools -- human approval gates and channel-backed results
  • History processors -- truncation, sliding window, and LLM-based summarization
  • Multi-modal -- images, audio, video, and document inputs
  • MCP support -- use tools from Model Context Protocol servers
  • Embeddings -- provider-agnostic Embedder interface with OpenAI, Voyage AI, Cohere, Gemini, Ollama, and Bedrock implementations and retrieval-tuned query/document input types
  • Multi-representation encoding -- RepresentationEncoder returns dense, learned sparse, and token multi-vectors from one call, with validated vector-space identity, via DeepInfra, an endpoint you operate, Hugging Face, SageMaker, Pinecone, or ONNX Runtime in your own process
  • Reranking -- Reranker cross-encoder interface with Voyage AI and Cohere implementations for two-stage retrieval
  • Thinking tokens -- extended reasoning for Anthropic, OpenAI o-series, and Gemini
  • Output validation -- struct tag validation with automatic retry
  • Optional OpenTelemetry -- GenAI spans, structured event logs, and metrics in a separate module with content capture off by default

Installation

go get github.com/regularkevvv/agentic
go get github.com/regularkevvv/agentic/provider/openai # choose only the provider(s) you use

Requires Go 1.25.5 or later.

The Agentic OpenTelemetry integration is intentionally a separate module:

go get github.com/regularkevvv/agentic/otel

Pass agenticotel.New() through agentic.WithInstrumentation to emit an invoke_agent span containing provider-request and tool spans, the GenAI metric set, and structured exception/evaluation log records. The root Agentic source and public instrumentation API do not import OTel or the optional adapter, and prompt/tool content stays off unless explicitly enabled. See otel/README.md for setup, privacy controls, and the pinned semantic-convention revision. just otel-e2e runs a credential-free, Dockerized Collector proof and asserts the exported traces, metrics, logs, correlation, topology, scenarios, and privacy tripwire.

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    agentic "github.com/regularkevvv/agentic"
    "github.com/regularkevvv/agentic/provider/openai"
)

func main() {
    model, _ := openai.New("gpt-4o")
    agent := agentic.NewAgent("You are a helpful assistant.", model)

    result, err := agent.Run(context.Background(), "Hello!")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result.Output)
}

Tools

Define tools with automatic schema inference from Go types:

type GetWeatherInput struct {
    _        struct{} `tool:"Look up the current weather for a city"`
    Location string   `json:"location" description:"City name"`
    Unit     string   `json:"unit,omitempty" enum:"celsius,fahrenheit"`
}

agentic.AddTool(agent, func(ctx context.Context, input GetWeatherInput) (WeatherOutput, error) {
    return WeatherOutput{Temperature: 24, Condition: "sunny"}, nil
})

AddTool is context-aware by default so cancellation, deadlines, and tracing propagate from the agent run. Use AddToolPlain only for a small function that does not need context. AddToolWithContext is an explicit alias for AddTool.

Tools with dependencies:

type MyDeps struct {
    DB *sql.DB
}

agent := agentic.NewAgentWithDeps[*MyDeps]("Answer database questions.", model)
agentic.AddToolWithDeps(agent, func(ctx agentic.RunContext[*MyDeps], input QueryInput) (QueryOutput, error) {
    rows, _ := ctx.Deps.DB.QueryContext(ctx.Ctx, input.SQL)
    return QueryOutput{Rows: rows}, nil
})

Structured Output

type Summary struct {
    Title    string   `json:"title"    validate:"required"`
    Points   []string `json:"points"   validate:"required,min=1"`
}

agent := agentic.NewTypedAgent[Summary](
    "Summarize the input as structured data.",
    model,
    "Return a structured summary.",
)

result, _ := agent.Run(ctx, "Summarize Go's strengths.")
fmt.Println(result.Output.Title)  // typed access

Providers

provider/ is flat because capability is not single-valued: Bedrock is a model and an embedder, Cohere an embedder and a reranker, DeepInfra an embedder and an encoder. Any arrangement by role would have to file those packages in two places, so the table is the index instead — and a test enforces that every provider declares its capabilities in code, so this cannot silently go stale. Each production provider is also its own Go module. The import paths are unchanged, but choosing one provider no longer adds every provider SDK to the root Agentic module graph or to your application's module graph.

Provider Import Chat Embed Encode Rerank
OpenAI provider/openai ✓ ✓
Anthropic provider/anthropic ✓
Google Gemini provider/gemini ✓ ✓
Azure OpenAI provider/azure ✓
AWS Bedrock provider/bedrock ✓ ✓
Together AI provider/together ✓
OpenRouter provider/openrouter ✓
Ollama provider/ollama ✓ ✓
Grok provider/grok ✓
Voyage AI provider/voyageai ✓ ✓
Cohere provider/cohere ✓ ✓
DeepInfra provider/deepinfra ✓ ✓
Endpoint you operate provider/endpoint ✓ ✓
Hugging Face router provider/huggingface ✓ ✓
SageMaker provider/sagemaker ✓ ✓
Pinecone Inference provider/pinecone ✓ ✓
In-process ONNX provider/local/onnx ✓

Chat is Model/StreamModel, Embed is Embedder, Encode is RepresentationEncoder (dense, learned sparse, and multi-vector in one pass), Rerank is Reranker. Implement the matching interface to add your own.

Every production provider is outside the root module. provider/local/onnx differs from the network providers because it also needs CGO and a native ONNX Runtime, so it is excluded from go.work and the ordinary contributor build. Constructors:

openai.New("gpt-4o")                          anthropic.New("claude-sonnet-4-6")
gemini.New("gemini-2.0-flash")                bedrock.New("anthropic.claude-sonnet-4-6")
azure.New(deployment, azure.WithEndpoint(u), azure.WithAPIKey(k))
together.New("meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo")
openrouter.New("anthropic/claude-sonnet-4")   ollama.New("llama3.1")
grok.New("grok-3")

Embeddings

The same interface-plus-providers pattern covers embeddings: agentic.Embedder is the interface, with implementations in provider/openai, provider/voyageai, provider/cohere, provider/gemini, provider/ollama, and provider/bedrock.

import "github.com/regularkevvv/agentic/provider/voyageai"

embedder, _ := voyageai.New("voyage-3.5") // key from VOYAGE_API_KEY
// or: openai.NewEmbedder("text-embedding-3-small")
// or: cohere.New("embed-v4.0"), gemini.NewEmbedder("gemini-embedding-001"),
//     ollama.NewEmbedder("nomic-embed-text"), bedrock.NewEmbedder("amazon.titan-embed-text-v2:0")

// Index documents, then embed queries against them:
docs, _ := agentic.EmbedDocuments(ctx, embedder, "The monthly budget is $2,000.")
query, _ := agentic.EmbedQuery(ctx, embedder, "what is the budget?")

EmbedQuery and EmbedDocuments set the request's InputType. Retrieval-tuned providers (Voyage AI, Cohere, Gemini) use it to prepend a task instruction before vectorizing, which embeds queries near their answering documents; providers without the concept (OpenAI) ignore it. For similarity, clustering, or classification, call Embed directly and leave InputType unset.

Requests are batch-first (Input []string), support dimension control via Dimensions on models that allow it (OpenAI text-embedding-3 and later; Voyage AI voyage-3.5 and later), and report token usage. Vectors are returned in input order as [][]float32. provider/test.NewTestEmbedder provides a deterministic in-memory fake for tests.

Multi-representation encoding

Some retrieval models produce more than one view of a text from a single forward pass. BGE-M3 produces a dense vector, a learned sparse vector, and a per-token multi-vector at once. agentic.Embedder carries the first and nothing else, so agentic.RepresentationEncoder sits beside it and carries all three without flattening them.

import "github.com/regularkevvv/agentic/provider/deepinfra"

encoder, _ := deepinfra.New(deepinfra.BGEM3Model) // token from DEEPINFRA_TOKEN

resp, _ := agentic.EncodeDocuments(ctx, encoder,
    []string{"PostgreSQL supports sparse vectors"},
    agentic.RepresentationDense,
    agentic.RepresentationSparse,
)

item := resp.Data[0]
denseSpace := resp.Spaces[agentic.RepresentationDense]
sparseSpace := resp.Spaces[agentic.RepresentationSparse]

// Store item.Dense and item.Sparse in your index, each beside its space ID.

Outputs are explicit because they differ in cost by orders of magnitude. Data has one entry per input, in input order, carrying exactly the kinds you asked for.

Store space.ID beside every value. Two vectors from the same named model but different weights revisions, or two sparse vectors from different tokenizer vocabularies, are not comparable — and the failure is silent, in the form of quietly worse recall rather than an error. The ID is a deterministic hash of the fields that make values comparable, so two processes agree on it without coordinating.

Which representations each encoder returns — the Encode column above, in detail:

Import Constructor Dense Sparse Multi-vector
provider/deepinfra deepinfra.New(deepinfra.BGEM3Model) Yes Yes Yes
provider/endpoint endpoint.New(endpointURL) Yes Yes Optional
provider/huggingface huggingface.NewShared(model) Yes No No
provider/sagemaker sagemaker.New(ctx, endpointName) Yes Yes Optional
provider/pinecone pinecone.New(model) Yes Yes No
provider/local/onnx onnx.New(model, tokenizer, space) No Yes No

Agentic normalizes inference and stops there. Indexing, BM25, candidate fusion, and final ranking belong to the retrieval system you build on top, which is why nothing here returns a score.

Existing Embedder code is unaffected. EmbedderAsRepresentationEncoder drives any dense embedder through the new interface, and RepresentationEncoderAsEmbedder drives a multi-output encoder through the old one, so sparse output can be adopted when your index is ready for it. provider/test.NewTestRepresentationEncoder is a deterministic fake, and provider/test/conformance.RunRepresentation is the shared contract suite that every provider — and your own — is checked against.

provider/endpoint speaks the versioned protocol to any host running a handler that implements it — a Hugging Face Inference Endpoint, a container, or a process on a laptop — and takes its token from AGENTIC_ENDPOINT_TOKEN, or none at all with endpoint.WithoutAuthentication(). provider/sagemaker speaks the same protocol through SageMaker Runtime. See docs/multi-representation-inference.md for the full contract.

provider/local/onnx encodes sparse vectors in your own process with no server at all. Like every production provider it is a nested module, but unlike the pure-Go network providers it is absent from go.work: it needs CGO, a native ONNX Runtime, and a statically linked tokenizer, none of which can be a condition of working on the ordinary library. See provider/local/onnx/README.md for the setup, which is a real barrier rather than a formality.

Reranking

A reranker is a cross-encoder: it scores the query against each document directly, which is markedly more accurate than comparing independently computed embeddings, and markedly more expensive. The usual arrangement is two stages — retrieve a shortlist with an Embedder, then reorder it with a Reranker. agentic.Reranker is the interface, with implementations in provider/voyageai and provider/cohere.

import "github.com/regularkevvv/agentic/provider/voyageai"

reranker, _ := voyageai.NewReranker("rerank-2.5") // key from VOYAGE_API_KEY
// or: cohere.NewReranker("rerank-v3.5")

resp, _ := agentic.Rerank(ctx, reranker, "what is the budget?", shortlist, 5)
for _, r := range resp.Results { // ordered by descending score
    fmt.Printf("%.3f  %s\n", r.Score, r.Document)
}

RerankResult.Index maps each result back to its position in the input slice, so metadata kept in a parallel slice rejoins cleanly. Scores are ordinal within a single response only — rank by them, never threshold across providers, models, or calls. provider/test.NewTestReranker provides a deterministic fake for tests.

Agent-to-Agent

Delegate tasks to specialized sub-agents:

researcher := agentic.NewAgentWithDeps[*MyDeps]("You are a research assistant.", model)
writer := agentic.NewAgentWithDeps[*MyDeps]("You write clear reports.", model)

// The identity handoff passes the writer's exact dependency value to the child.
writer.AddHandoffWithDeps(agentic.NewIdentityTextHandoff(
    "research", "Delegate research tasks", researcher,
))

result, err := writer.Run(ctx, "Research and report on Go.", deps)

Approval and Channel-Backed Tools

Tools that require human approval before execution:

tool, handler, _ := agentic.ApprovalTool(
    "delete_record", "Delete a database record",
    func(ctx context.Context, input DeleteInput) (string, error) {
        return db.Delete(input.ID)
    },
    func(ctx context.Context, call agentic.ToolUse) (bool, error) {
        return promptUser("Approve deletion of %s?", call.Input["id"]), nil
    },
)

ApprovalTool runs the approval callback and, if approved, the handler during the current agent run. ChannelTool similarly waits for one channel result, cancellation, or an optional timeout. Neither API suspends and later resumes a durable workflow.

Streaming

stream, _ := agent.RunStream(ctx, "Tell me a story.")
for event := range stream.Events {
    if event.Type == agentic.StreamEventTextDelta {
        fmt.Print(event.Delta)
    }
}

Controlled and Resumable Runs

Run remains the concise API for ordinary one-shot requests. When an orchestrator needs to continue a transcript, install per-run controls, or resume a deferred tool batch, opt into the explicit Driver capability:

driver, err := agentic.RequireDriver[string](agent)
if err != nil {
    log.Fatal(err)
}

events := agentic.EventSinkFunc(func(context.Context, agentic.Event) error {
    return nil // persist or observe canonical execution events here
})
prompt := agentic.NewTextMessage(agentic.RoleUser, "Prepare the report.")
execution, err := driver.Drive(ctx, agentic.DriveInput{
    Mode:   agentic.DriveStart,
    Prompt: &prompt,
}, agentic.WithRunEventSink(events))
if err != nil {
    log.Fatal(err)
}
fmt.Println(execution.Status)

DriveContinue accepts an already paired transcript without appending a synthetic user prompt. A ToolGate may suspend an admitted batch before any handler runs; persist the returned Execution.Result.Messages and Execution.Suspension, then call Resume with exactly one ToolResumeDecision for each suspended executable call. Bind and BindProvider still return Runner, while their concrete values also implement Driver and can be checked with RequireDriver.

A handler that can discover deferred work only after it starts may opt into SuspendableToolHandler and return ToolHandlerSuspension. The driver isolates that handler from other regular calls before execution and leaves its tool frontier open. On Resume, the same handler reads its persisted deferral and the caller-validated decision payload with CurrentToolResume. Ordinary handlers and gate-originated resumptions never receive that resume context. Composite tool hosts use WithToolCallContext before invoking a nested handler so it receives its own call identity without inheriting the outer handler's resume payload.

Experimental Durable Harness

The repository also contains the nested experimental module github.com/regularkevvv/agentic/harness. Its Phase 5 surface adds durable single-process sessions, steering/follow-up/next-turn queues, interruption and recovery, bounded cursor subscriptions, transcript repair, Local and Memory environments, session-scoped artifact spill, an immutable capability DAG, context compaction, default-deny permissions, exact deferred resume, and capture-restricted in-process child agents with separate durable sessions, addressed inboxes, tagged events, recursion limits, cancellation, and shared budget accounting.

The low-level constructor is harness.NewRuntime; it depends on generic journal, codec, event, environment, clock/ID, and result-processing ports. Concrete memory, JSONL, local, file, in-process, subprocess, and GoMonty adapters are selected only at the application composition root. harness.New(...).Build() composes public capabilities without changing those dependency directions, while harness.Default is an explicit local convenience assembly. Subagents, codemode, long-term memory, skills, and evals remain optional capabilities rather than part of that default. The GoMonty codemode adapter pins the source-only regularkevvv/gomonty fork and requires explicit verified runtime preparation; importing Agentic never downloads or builds native code. See harness/README.md for the exact experimental boundary.

History Processors

Manage context window with built-in processors:

agent := agentic.NewAgent("You are helpful.", model,
    agentic.WithHistoryProcessor(agentic.TruncateHistory(20)),
)

// Or chain multiple processors
agentic.WithHistoryProcessor(agentic.ChainProcessors(
    agentic.SlidingWindowHistory(4000, tokenCounter),
    agentic.TruncateHistory(50),
))

Choosing a dependency pattern

  • Use closures for a fixed service that is the same for every run.
  • Use NewAgentWithDeps[D] or NewTypedAgentWithDeps[O, D] when application state varies by run and should be checked across prompts, tools, validators, and handoffs.
  • Use Bind(deps) when an orchestrator needs a ready Runner[O] for one fixed dependency value.
  • Use BindProvider(provider) when dependencies must be resolved once at the beginning of every run. Provider and dependency-validation failures happen before prompt, model, or tool side effects.
agent := agentic.NewAgentWithDeps[*MyDeps]("Be helpful.", model)

var fixed agentic.Runner[string] = agent.Bind(deps)
result, err := fixed.Run(ctx, prompt)

perRun := agent.BindProvider(func(ctx context.Context) (*MyDeps, error) {
    return dependenciesForRequest(ctx)
})

Project Layout

Agentic solves two problems that share providers and nothing else. Chat is the agent loop — model, tools, streaming, handoffs. Retrieval is turning text into vectors and ordering results — Embedder, RepresentationEncoder, Reranker. Neither half references the other, and a test enforces it.

agentic/            the library: one import path, both halves
  tool/             tool builders, registry, toolsets
  mcp/              Model Context Protocol client and toolset
  provider/         every provider, flat — see the table above
    <vendor>/       one dependency-isolated module per provider
    test/           the one exception: doubles and the contract suite
  internal/
    core/           chat primitives
    retrieval/      vector primitives
    providerhttp/   HTTP retry and bounded reads, shared by providers
    testutil/       doubles for this repository's own tests
  harness/          nested module: durable sessions (experimental)
  otel/             nested module: optional OpenTelemetry integration
  e2e/              nested module: live tests and runnable examples
    localinference/ nested module: the example that runs a model in-process
  provider/local/onnx/  nested module: that model's encoder (CGO)
  docs/             what exists; docs/design/ records why

A nested module exists to keep something out of the dependency graph of go get agentic, and for no other reason. The two CGO modules are also absent from go.work, so go build ./... works without a native ONNX Runtime installed; CI gates them in a separate job.

ARCHITECTURE.md is the full map, including a table of where each kind of new code goes and which rules are enforced by tests rather than by convention.

Examples

cp .env.example .env   # fill in your API key
go run ./e2e/examples/basic
go run ./e2e/examples/tools
go run ./e2e/examples/structured

The examples live in the nested e2e module so that what they need to be readable — a table writer, a live API key — never reaches an application that imports the library. The committed go.work is what keeps them runnable from the repository root.

See e2e/examples/ for details.

Contributing

See CONTRIBUTING.md for development setup, testing, and PR guidelines.

License

MIT

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

View Source
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)

View Source
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

View Source
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

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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

func Bool(v bool) *bool

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

func Float64(v float64) *float64

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

func Int(v int) *int

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

func IntPtr(v int) *int

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

func IsModelRetry(err error) bool

IsModelRetry checks if an error is a ModelRetry.

func IsProviderError added in v0.3.0

func IsProviderError(err error) bool

IsProviderError checks if an error is a ProviderError.

func IsUsageLimitExceeded

func IsUsageLimitExceeded(err error) bool

IsUsageLimitExceeded checks if an error is a UsageLimitExceededError.

func IsValidationError

func IsValidationError(err error) bool

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

func String(v string) *string

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

func ValidateStruct(v any) error

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 NewAgent

func NewAgent(systemPrompt string, model Model, opts ...AgentOption) *Agent

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 (a *Agent) AddHandoff(h *Handoff) *Agent

func (*Agent) AddTool

func (a *Agent) AddTool(tool Tool, handler ToolHandler) *Agent

func (*Agent) AddToolset

func (a *Agent) AddToolset(set Toolset) *Agent

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) Run

func (a *Agent) Run(ctx context.Context, prompt string, opts ...RunOption) (*Result[string], error)

func (*Agent) RunStream

func (a *Agent) RunStream(ctx context.Context, prompt string, opts ...RunOption) (*StreamResult, error)

func (*Agent) SetOutputToolNames

func (a *Agent) SetOutputToolNames(names map[string]bool) *Agent

func (*Agent) SetRegistry

func (a *Agent) SetRegistry(registry ToolRegistry) *Agent

type AgentIdentity added in v0.7.0

type AgentIdentity struct {
	Name        string
	Description string
	Version     string
}

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]) Run

func (a *AgentWithDeps[D]) Run(ctx context.Context, prompt string, deps D, opts ...RunOption) (*Result[string], error)

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

func (AssistantCommittedEvent) TurnIndex added in v0.4.0

func (e AssistantCommittedEvent) TurnIndex() int

func (AssistantCommittedEvent) Type added in v0.4.0

func (e AssistantCommittedEvent) Type() EventType

type AudioURL

type AudioURL = core.AudioURL

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

type DepsProvider[D any] func(context.Context) (D, error)

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

type DepsValidator[D any] func(context.Context, D) error

DepsValidator checks application invariants before any run side effect.

type DocumentURL

type DocumentURL = core.DocumentURL

type DriveInput added in v0.4.0

type DriveInput struct {
	Mode    DriveMode
	History []Message
	Prompt  *Message
}

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.

func RequireDriver added in v0.4.0

func RequireDriver[O any](runner Runner[O]) (Driver[O], error)

RequireDriver returns the execution driver capability for a ready-to-run runner. It never reconstructs an agent loop from Runner.Run.

type DynamicPrompt

type DynamicPrompt func(context.Context) (string, error)

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

type Embedder = retrieval.Embedder

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

func EmbedDocuments(ctx context.Context, e Embedder, texts ...string) (*EmbeddingResponse, error)

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

func EmbedQuery(ctx context.Context, e Embedder, texts ...string) (*EmbeddingResponse, error)

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 EventSink added in v0.4.0

type EventSink interface {
	Emit(context.Context, Event) error
}

EventSink receives canonical events synchronously.

type EventSinkFunc added in v0.4.0

type EventSinkFunc func(context.Context, Event) error

EventSinkFunc adapts a function to EventSink.

func (EventSinkFunc) Emit added in v0.4.0

func (f EventSinkFunc) Emit(ctx context.Context, event Event) error

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 Function

type Function = core.Function

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 HandoffSummaryFunc

type HandoffSummaryFunc func(context.Context, []Message) (string, error)

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

type HistoryProcessorFunc func(ctx context.Context, messages []Message) ([]Message, error)

HistoryProcessorFunc is a function adapter for HistoryProcessor.

func (HistoryProcessorFunc) Process

func (f HistoryProcessorFunc) Process(ctx context.Context, messages []Message) ([]Message, error)

type ImageData

type ImageData = core.ImageData

type ImageURL

type ImageURL = core.ImageURL

type Instrumentation added in v0.7.0

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

type Message = core.Message

func NewImageDataMessage

func NewImageDataMessage(text string, data []byte, mediaType string) Message

NewImageDataMessage creates a user message with text and inline image data.

func NewImageFileMessage

func NewImageFileMessage(text string, filePath string) (Message, error)

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

func NewImageURLMessage(text string, imageURL string, detail ...string) Message

NewImageURLMessage creates a user message with text and an image URL.

func NewMultiPartMessage

func NewMultiPartMessage(parts ...Part) Message

NewMultiPartMessage creates a user message with multiple content parts.

func NewTextMessage

func NewTextMessage(role MessageRole, text string) Message

func NewToolResultMessage

func NewToolResultMessage(toolUseID string, content string, isError bool) Message

func NewToolResultMessageFor added in v0.3.0

func NewToolResultMessageFor(toolUseID, toolName, content string, isError bool) Message

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

func NewToolUseMessage(toolUses ...ToolUse) Message

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 Model

type Model = core.Model

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

func (OutputValidatedEvent) TurnIndex added in v0.4.0

func (e OutputValidatedEvent) TurnIndex() int

func (OutputValidatedEvent) Type added in v0.4.0

func (e OutputValidatedEvent) Type() EventType

type OutputValidator

type OutputValidator interface {
	Validate(ctx context.Context, output string) error
}

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

type OutputValidatorFunc func(ctx context.Context, output string) error

OutputValidatorFunc is a function adapter for OutputValidator.

func (OutputValidatorFunc) Validate

func (f OutputValidatorFunc) Validate(ctx context.Context, output string) error

Validate implements 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

type Part = core.Part

func AudioURLPart

func AudioURLPart(url string, format ...string) Part

AudioURLPart creates an audio-from-URL content part.

func CachePointPart

func CachePointPart(ttl ...string) Part

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

func DocumentURLPart(url string, mediaType ...string) Part

DocumentURLPart creates a document-from-URL content part (e.g. PDF).

func ImageDataPart

func ImageDataPart(data []byte, mediaType string) Part

ImageDataPart creates an inline base64-encoded image content part.

func ImageURLPart

func ImageURLPart(url string, detail ...string) Part

ImageURLPart creates an image-from-URL content part. Optional detail parameter controls image processing fidelity ("auto", "low", "high").

func TextPart

func TextPart(text string) Part

TextPart creates a text content part.

func UploadedFilePart

func UploadedFilePart(fileID string, providerName string) Part

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

func VideoURLPart(url string) Part

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 Reranker added in v0.3.0

type Reranker = retrieval.Reranker

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

func (r *Result[O]) AllMessages() []Message

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

func (r *Result[O]) NewMessages() []Message

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

func (RunCompletedEvent) TurnIndex added in v0.4.0

func (e RunCompletedEvent) TurnIndex() int

func (RunCompletedEvent) Type added in v0.4.0

func (e RunCompletedEvent) Type() EventType

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

func (RunEndedEvent) TurnIndex added in v0.4.0

func (e RunEndedEvent) TurnIndex() int

func (RunEndedEvent) Type added in v0.4.0

func (e RunEndedEvent) Type() EventType

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

func (RunErrorEvent) TurnIndex added in v0.4.0

func (e RunErrorEvent) TurnIndex() int

func (RunErrorEvent) Type added in v0.4.0

func (e RunErrorEvent) Type() EventType

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

func (RunInterruptedEvent) TurnIndex added in v0.4.0

func (e RunInterruptedEvent) TurnIndex() int

func (RunInterruptedEvent) Type added in v0.4.0

func (e RunInterruptedEvent) Type() EventType

type RunMetadata added in v0.7.0

type RunMetadata struct {
	ConversationID string
	RunID          string
}

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 WithMessages(messages ...Message) RunOption

func WithRunEndStrategy

func WithRunEndStrategy(strategy EndStrategy) RunOption

func WithRunEventSink added in v0.4.0

func WithRunEventSink(sink EventSink) RunOption

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 WithRunMaxIterations(maxIter int) RunOption

func WithRunMaxTokens

func WithRunMaxTokens(maxTokens int) RunOption

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

func WithRunModelStreaming(enabled bool) RunOption

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 WithRunTemperature(temp float64) RunOption

func WithRunToolCancellationGrace added in v0.4.0

func WithRunToolCancellationGrace(grace time.Duration) RunOption

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

func WithRunToolGate(gate ToolGate) RunOption

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

func WithRunToolsets(toolsets ...Toolset) RunOption

WithRunToolsets overlays immutable toolsets for this execution. The shared agent registry is never mutated.

func WithRunTurnHook added in v0.4.0

func WithRunTurnHook(hook TurnHook) RunOption

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 RunResult

type RunResult = Result[string]

RunResult is the text-output result retained as a familiar name.

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

func (RunStartedEvent) TurnIndex added in v0.4.0

func (e RunStartedEvent) TurnIndex() int

func (RunStartedEvent) Type added in v0.4.0

func (e RunStartedEvent) Type() EventType

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

func (RunSuspendedEvent) TurnIndex added in v0.4.0

func (e RunSuspendedEvent) TurnIndex() int

func (RunSuspendedEvent) Type added in v0.4.0

func (e RunSuspendedEvent) Type() EventType

type Runner

type Runner[O any] interface {
	Run(context.Context, string, ...RunOption) (*Result[O], error)
}

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) Parse

func (s *TextOutputSpec) Parse(msg Message) (string, error)

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

func (TextPreviewEvent) TurnIndex added in v0.4.0

func (e TextPreviewEvent) TurnIndex() int

func (TextPreviewEvent) Type added in v0.4.0

func (e TextPreviewEvent) Type() EventType

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

func (ThinkingPreviewEvent) TurnIndex added in v0.4.0

func (e ThinkingPreviewEvent) TurnIndex() int

func (ThinkingPreviewEvent) Type added in v0.4.0

func (e ThinkingPreviewEvent) Type() EventType

type Tool

type Tool = core.Tool

func MustNewToolFromStruct

func MustNewToolFromStruct(name, description string, input interface{}) Tool

func NewToolFromStruct

func NewToolFromStruct(name, description string, input interface{}) (Tool, error)

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

func (ToolArgumentPreviewEvent) TurnIndex added in v0.4.0

func (e ToolArgumentPreviewEvent) TurnIndex() int

func (ToolArgumentPreviewEvent) Type added in v0.4.0

func (e ToolArgumentPreviewEvent) Type() EventType

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

func (ToolBatchPlannedEvent) TurnIndex added in v0.4.0

func (e ToolBatchPlannedEvent) TurnIndex() int

func (ToolBatchPlannedEvent) Type added in v0.4.0

func (e ToolBatchPlannedEvent) Type() EventType

type ToolCallContext added in v0.4.0

type ToolCallContext struct {
	ID      string
	Name    string
	Attempt int
}

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

func (ToolCallPreviewEvent) TurnIndex added in v0.4.0

func (e ToolCallPreviewEvent) TurnIndex() int

func (ToolCallPreviewEvent) Type added in v0.4.0

func (e ToolCallPreviewEvent) Type() EventType

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

type ToolPrepareFunc func(context.Context, []Tool) ([]Tool, error)

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

func (ToolResultCommittedEvent) TurnIndex added in v0.4.0

func (e ToolResultCommittedEvent) TurnIndex() int

func (ToolResultCommittedEvent) Type added in v0.4.0

func (e ToolResultCommittedEvent) Type() EventType

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

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

type ToolStartedEvent struct {
	Call    ToolUse
	Attempt int
	// contains filtered or unexported fields
}

ToolStartedEvent is emitted immediately before an admitted handler starts.

func (ToolStartedEvent) Nature added in v0.4.0

func (e ToolStartedEvent) Nature() EventNature

func (ToolStartedEvent) TurnIndex added in v0.4.0

func (e ToolStartedEvent) TurnIndex() int

func (ToolStartedEvent) Type added in v0.4.0

func (e ToolStartedEvent) Type() EventType

type ToolType

type ToolType = core.ToolType

type ToolUse

type ToolUse = core.ToolUse

type Toolset

type Toolset = agentictool.Toolset

func CombineToolsets

func CombineToolsets(sets ...Toolset) Toolset

func FilterToolset

func FilterToolset(set Toolset, predicate func(toolName string) bool) Toolset

func PrefixToolset

func PrefixToolset(set Toolset, prefix string) Toolset

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

func (TurnEndedEvent) TurnIndex added in v0.4.0

func (e TurnEndedEvent) TurnIndex() int

func (TurnEndedEvent) Type added in v0.4.0

func (e TurnEndedEvent) Type() EventType

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

func (TurnMessagesInjectedEvent) TurnIndex added in v0.4.0

func (e TurnMessagesInjectedEvent) TurnIndex() int

func (TurnMessagesInjectedEvent) Type added in v0.4.0

func (e TurnMessagesInjectedEvent) Type() EventType

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

func (TurnStartedEvent) TurnIndex added in v0.4.0

func (e TurnStartedEvent) TurnIndex() int

func (TurnStartedEvent) Type added in v0.4.0

func (e TurnStartedEvent) Type() EventType

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]) Run

func (a *TypedAgent[O]) Run(ctx context.Context, prompt string, opts ...RunOption) (*Result[O], error)

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]) Run

func (a *TypedAgentWithDeps[O, D]) Run(ctx context.Context, prompt string, deps D, opts ...RunOption) (*Result[O], error)

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

type TypedOutputValidator[O any] interface {
	ValidateTyped(context.Context, O) error
}

TypedOutputValidator validates typed structured output. Use this for programmatic validation that goes beyond what struct tags can express.

type TypedOutputValidatorFunc

type TypedOutputValidatorFunc[O any] func(context.Context, O) error

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

type TypedRunResult[O any] = Result[O]

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 Usage

type Usage = core.Usage

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

type VideoURL

type VideoURL = core.VideoURL

Directories

Path Synopsis
harness 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

Jump to

Keyboard shortcuts

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