aikit

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 17 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

aikit

aikit is an AI SDK for Go: text and object generation, streaming, tool calling, failover, middleware, agents, MCP, and chat-platform bots. It is pure Go, builds with CGO_ENABLED=0, and the core needs only the standard library.

It is the AI layer of Fletch, and it works in any Go program without Fletch.

Modules

Each driver and runtime is its own module, so a binary pulls in only what it uses.

Module What it is Dependencies
github.com/fletchhq/aikit Messages, the Model contract, tools, structured output, failover, middleware, observers, vectors. Packages schema, stream/vercel, stream/agui, aitest, airec, eval Standard library only
github.com/fletchhq/aikit/mcp Model Context Protocol server and client over stdio and Streamable HTTP, plus mcptest Standard library only
github.com/fletchhq/aikit/openai OpenAI Responses and Chat Completions, compatible endpoints, Azure OpenAI, embeddings, images, speech aikit
github.com/fletchhq/aikit/anthropic Anthropic Messages API aikit
github.com/fletchhq/aikit/gemini Gemini API aikit
github.com/fletchhq/aikit/bedrock Amazon Bedrock Converse aikit, AWS SDK v2
github.com/fletchhq/aikit/vertex Gemini on Vertex AI aikit, aikit/gemini, x/oauth2
github.com/fletchhq/aikit/obs OpenTelemetry GenAI spans, Prometheus metrics, PHI redaction aikit, OpenTelemetry
github.com/fletchhq/aikit/agent Stateful agents, threads, approvals, background turns, HTTP chat endpoints aikit, Fletch quiver, pubsub, router, audit, cli
github.com/fletchhq/aikit/nock SQLite and Postgres stores for agents, links, and vectors aikit/agent, Fletch nock
github.com/fletchhq/aikit/live Crest and Live chat views aikit/agent, Fletch live, crest
github.com/fletchhq/aikit/converse Slack, GitHub, Telegram, and web chat bots aikit/agent, Fletch quiver, router

Quick start

go get github.com/fletchhq/aikit github.com/fletchhq/aikit/openai
model := openai.New(os.Getenv("OPENAI_API_KEY")).Model(os.Getenv("OPENAI_MODEL"))

res, err := aikit.GenerateText(ctx, model, aikit.User("Name three Go proverbs."),
	aikit.WithMaxSteps(4))
if err != nil {
	return err
}
fmt.Println(res.Text())

examples/standalone-ai serves an agent and its tools on a plain http.ServeMux, with the same tools over MCP.

Docs

  • AI: generation, streaming, tools, middleware, observability, testing, evals
  • Agents: the agent runtime, stores, chat endpoints and views
  • Converse: chat-platform bots
  • MCP: servers, clients, auth, testing

When github.com/fletchhq/aikit is in a Fletch app's go.mod, fletch ax sync and fletch docs automatically discover and sync its docs/ and skills/.

Agent skills for these topics are in skills/aikit.

Stability

The exported API of aikit and aikit/mcp is frozen: TestAPIFreeze compares it with testdata/api_freeze.txt, and removing or changing anything fails the test. The other modules may still change.

depgraph_test.go holds the module graph: aikit and aikit/mcp use only the standard library, each driver depends only on the contract it implements, and only aikit/obs imports OpenTelemetry.

Development

go.work lists every module except examples/standalone-ai, which builds in module mode against this checkout.

for m in $(go work edit -json | sed -nE 's/.*"DiskPath": "([^"]*)".*/\1/p') examples/standalone-ai; do
	(cd "$m" && CGO_ENABLED=0 go test -race ./...)
done
scripts/lint.sh   # golangci-lint v2.15.0, CGO_ENABLED=0

License

Licensed under either of MIT or Apache-2.0, at your option.

Documentation

Overview

Package aikit is the provider-neutral core of aikit, an AI SDK for Go: messages, the Model contract, tools, structured output, failover, per-step middleware, and observers. It needs only the standard library; provider drivers live in their own modules (aikit/openai, aikit/anthropic, aikit/gemini, aikit/bedrock, aikit/vertex).

Index

Constants

View Source
const (
	OpGenerateText   = "generate_text"
	OpStreamText     = "stream_text"
	OpGenerateObject = "generate_object"
	OpStreamObject   = "stream_object"
)

The operations a run reports in RunInfo.Operation.

View Source
const DefaultToolSearchThreshold = 20

DefaultToolSearchThreshold is how many deferred tools a toolset holds before they are loaded through tool search.

View Source
const SearchToolsName = "search_tools"

SearchToolsName is the name of the emulated tool-search meta-tool.

View Source
const SimilaritySearchName = "similarity_search"

SimilaritySearchName is the name of the SimilaritySearch tool.

Variables

View Source
var (
	ErrRateLimited         = errors.New("aikit: rate limited")
	ErrOverloaded          = errors.New("aikit: provider overloaded")
	ErrInsufficientCredits = errors.New("aikit: insufficient credits")
	ErrContextLength       = errors.New("aikit: context length exceeded")
	ErrInvalidRequest      = errors.New("aikit: invalid request")
	ErrContentFiltered     = errors.New("aikit: content filtered")
	ErrStopped             = errors.New("aikit: stopped by middleware")
)

The error classes every driver maps provider errors to. Match them with errors.Is.

Functions

func Failoverable

func Failoverable(err error) bool

Failoverable reports whether another model may be tried after err: a rate limit, an overload, or exhausted credits. It is false for invalid requests, context-length errors, schema errors, guardrail trips, and stops.

func Stop

func Stop(reason string) error

Stop returns an error that ends a run; it matches ErrStopped. Middleware returns it to end a run on purpose.

func StreamObject

func StreamObject[T any](ctx context.Context, m Model, p Prompt, opts ...Option) iter.Seq2[Partial[T], error]

StreamObject is GenerateObject as a stream of partial values. A snapshot is yielded whenever the decoded value changes. A repair attempt starts again from an empty value.

func StreamText

func StreamText(ctx context.Context, m Model, p Prompt, opts ...Option) iter.Seq2[Event, error]

StreamText is GenerateText as a stream. It yields each step's content events, the results of the tools it runs, a StepFinish per step, and a final Finish with the whole response. Breaking out of the loop cancels the run.

Types

type ApprovalDecision

type ApprovalDecision struct {
	Approved bool
	// Reason is shown to the model when the call is rejected.
	Reason string
	// Args, when set, replace the call's arguments.
	Args json.RawMessage
}

ApprovalDecision is the answer to an ApprovalRequest.

type ApprovalRequest

type ApprovalRequest struct {
	// ID is unique per call; it is the tool call ID.
	ID   string
	Tool string
	Args json.RawMessage
}

ApprovalRequest is a tool call that waits for a person's decision.

type ApprovalRequested

type ApprovalRequested struct{ Request ApprovalRequest }

ApprovalRequested says a tool call waits for a decision.

type Approver

type Approver interface {
	Approve(ctx context.Context, req ApprovalRequest) (ApprovalDecision, error)
}

Approver decides tool calls that need approval, possibly by waiting for a person. Without one, a run stops with FinishApproval.

type ApproverFunc

type ApproverFunc func(ctx context.Context, req ApprovalRequest) (ApprovalDecision, error)

ApproverFunc adapts a function to Approver.

func (ApproverFunc) Approve

Approve calls f.

type Audio

type Audio struct {
	Data     []byte
	MIMEType string
}

Audio is audio input.

type CachePolicy

type CachePolicy uint8

CachePolicy marks where a driver places prompt-cache breakpoints.

const (
	CacheSystem CachePolicy = 1 << iota
	CacheTools
	// CacheHistory marks the last message, so the next turn reads the
	// whole conversation from cache.
	CacheHistory
)

The cache breakpoints. Combine them with |.

type EmbedConfig

type EmbedConfig struct {
	// Dimensions asks for shorter vectors where the model supports it.
	Dimensions int
	// Task is a provider hint such as "RETRIEVAL_QUERY" (Gemini).
	Task string
}

EmbedConfig is what EmbedOptions set. Drivers read it with NewEmbedConfig.

func NewEmbedConfig

func NewEmbedConfig(opts ...EmbedOption) EmbedConfig

NewEmbedConfig applies opts.

type EmbedOption

type EmbedOption func(*EmbedConfig)

EmbedOption configures one Embed call.

func WithDimensions

func WithDimensions(n int) EmbedOption

WithDimensions asks for vectors of n dimensions.

func WithEmbedTask

func WithEmbedTask(task string) EmbedOption

WithEmbedTask passes a task hint to providers that take one.

type Embedder

type Embedder interface {
	Embed(ctx context.Context, in []string, o ...EmbedOption) (Embeddings, error)
}

Embedder turns text into vectors.

type Embeddings

type Embeddings struct {
	Vectors [][]float32
	Usage   Usage
}

Embeddings are the vectors of an Embed call, in input order.

type Event

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

Event is one item of a stream: TextDelta, ReasoningDelta, ToolCallStart, ToolCallDelta, ToolCallEnd, ToolResult, StepFinish, ApprovalRequested, FailoverEvent, or Finish. The set is closed.

type FailoverEvent

type FailoverEvent struct {
	// From and To are "provider/model".
	From, To string
	Err      error
}

FailoverEvent says a model failed with a failoverable error and the next one is tried.

type File

type File struct {
	Name     string
	MIMEType string
	URL      string
	// FileID is a file the provider already stores.
	FileID string
	Data   []byte
}

File is a document, such as a PDF, given by URL, provider file ID, or its bytes.

type Filter

type Filter struct {
	Key, Value string
}

Filter keeps the documents whose Meta[Key] is Value.

type Finish

type Finish struct{ Response *Response }

Finish ends a stream with the whole response.

type FinishReason

type FinishReason string

FinishReason is why a model stopped.

const (
	FinishStop          FinishReason = "stop"
	FinishLength        FinishReason = "length"
	FinishToolCalls     FinishReason = "tool_calls"
	FinishContentFilter FinishReason = "content_filter"
	// FinishApproval means a tool call waits for approval and no
	// Approver was set; Response.Approvals lists the calls.
	FinishApproval FinishReason = "approval"
	FinishOther    FinishReason = "other"
)

The finish reasons.

type GeneratedImage

type GeneratedImage struct {
	Data     []byte
	MIMEType string
	// RevisedPrompt is the prompt the provider actually used, when it
	// reports one.
	RevisedPrompt string
}

GeneratedImage is a made image.

type Guardrail

type Guardrail interface {
	CheckInput(ctx context.Context, msgs []Message) error
	CheckOutput(ctx context.Context, r *StepResult) error
}

Guardrail checks what goes into and comes out of a model. Return a *GuardrailError, or any error, to refuse.

type GuardrailError

type GuardrailError struct {
	Name   string
	Reason string
	// Stage is "input", "output", or "tool".
	Stage string
}

GuardrailError is a guardrail's refusal. It never triggers failover.

func (*GuardrailError) Error

func (e *GuardrailError) Error() string

type HostedTool

type HostedTool interface {
	Tool
	HostedBy() string
}

HostedTool is a tool a provider runs itself, such as web search. Only a model of that provider can take it.

type Image

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

Image is an image given by URL or by its bytes.

type ImageGenerator

type ImageGenerator interface {
	GenerateImage(ctx context.Context, p ImagePrompt) (*GeneratedImage, error)
}

ImageGenerator makes images from a prompt.

type ImagePrompt

type ImagePrompt struct {
	Prompt string
	// Size is a provider size such as "1024x1024"; "" is the default.
	Size string
	// Quality is a provider quality such as "high"; "" is the default.
	Quality string
}

ImagePrompt describes an image to make.

type Limit

type Limit func(s *Step) error

Limit is one bound of a Budget. It returns a non-nil error, usually from Stop, when the next step must not run.

func MaxCost

func MaxCost(usd float64, p Pricing) Limit

MaxCost stops a run once its steps cost usd or more under p. A step whose model p does not price stops the run, so a missing price never lets a run spend without bound.

func MaxInputTokens

func MaxInputTokens(n int) Limit

MaxInputTokens stops a run once it has used n input tokens.

func MaxSteps

func MaxSteps(n int) Limit

MaxSteps stops a run before its step n+1. Unlike WithMaxSteps, reaching it is an error.

func MaxTotalTokens

func MaxTotalTokens(n int) Limit

MaxTotalTokens stops a run once it has used n tokens.

type Message

type Message struct {
	Role  Role
	Parts []Part
}

Message is one turn of a conversation.

func Assistant

func Assistant(text string, parts ...Part) Message

Assistant returns an assistant message with text and any further parts.

func System

func System(text string) Message

System returns a system message. Drivers move system messages into the provider's system field.

func ToolMessage

func ToolMessage(results ...ToolResult) Message

ToolMessage returns a tool message with the results.

func User

func User(text string, parts ...Part) Message

User returns a user message with text and any further parts.

func (Message) Text

func (m Message) Text() string

Text joins the message's Text parts.

func (Message) ToolCalls

func (m Message) ToolCalls() []ToolCall

ToolCalls lists the message's tool calls in order.

type Messages

type Messages []Message

Messages is a conversation used as a prompt.

type Middleware

type Middleware func(next StepFunc) StepFunc

Middleware wraps every step of a run.

func Budget

func Budget(limits ...Limit) Middleware

Budget stops a run before a step that would go past any limit.

func Guard

func Guard(gs ...Guardrail) Middleware

Guard runs guardrails on each step's input, output, and tool calls. On a streamed run the output check runs after the step's text has streamed.

func Redact

func Redact(r Redactor, scope RedactScope) Middleware

Redact rewrites text with r. With RedactPrompt the model never sees the original text; with RedactObserver only traces and the dev dashboard are spared it.

func RouteModel

func RouteModel(fn func(s *Step) Model) Middleware

RouteModel picks each step's model. Returning nil keeps the step's model.

type Model

type Model interface {
	// Provider names the provider, such as "openai" or "anthropic".
	Provider() string
	// ID is the provider's model ID.
	ID() string
	Generate(ctx context.Context, req *Request) (*Response, error)
	Stream(ctx context.Context, req *Request) iter.Seq2[Event, error]
}

Model is one model of one provider.

Stream yields content events in order and ends with exactly one Finish that carries the whole response, the same value Generate returns. An error ends the sequence.

func Failover

func Failover(primary Model, fallbacks ...Model) Model

Failover returns a Model that tries primary, then each fallback in turn, after a Failoverable error. A stream fails over only before its first content event; an error after that ends the stream. A request with a HostedTool goes only to models of the tool's provider. Each switch is reported as a FailoverEvent.

Provider and ID are the primary's.

type Named

type Named interface{ Name() string }

Named is a Guardrail or Redactor that names itself in errors and traces.

type NativeToolSearch

type NativeToolSearch interface {
	NativeToolSearch() bool
}

NativeToolSearch is a Model whose provider loads deferred tools itself. Other models get the search_tools meta-tool instead.

type Notice

type Notice struct {
	RunID string
	Kind  NoticeKind
	Step  int
	// From and To are set for failovers.
	From, To string
	// Approval is set for approval notices; its Args only with content
	// capture.
	Approval *ApprovalRequest
	// Approved is the decision of an approval_resolved notice.
	Approved bool
	Reason   string
	Err      error
}

Notice is a run event that is not a span: a failover, a guardrail trip, an approval, a stop, or a repair turn.

type NoticeKind

type NoticeKind string

NoticeKind names a Notice.

const (
	NoticeFailover         NoticeKind = "failover"
	NoticeGuardrail        NoticeKind = "guardrail"
	NoticeApproval         NoticeKind = "approval_requested"
	NoticeApprovalResolved NoticeKind = "approval_resolved"
	NoticeStopped          NoticeKind = "stopped"
	NoticeRepair           NoticeKind = "repair"
)

The notice kinds.

type Observer

type Observer interface {
	StartRun(ctx context.Context, r RunInfo) (context.Context, func(RunEnd))
	StartStep(ctx context.Context, s StepInfo) (context.Context, func(StepEnd))
	StartTool(ctx context.Context, t ToolInfo) (context.Context, func(ToolEnd))
	Notice(ctx context.Context, n Notice)
}

Observer is told about each run, step, and tool call, for tracing, metrics, and the dev dashboard. Prompt, answer, and tool input and output fields are empty unless the run has WithContentCapture, and then they have passed every Redact middleware.

type Option

type Option func(*config)

Option configures one generation.

func WithApprover

func WithApprover(a Approver) Option

WithApprover decides tool calls that need approval. Without one, a run that reaches such a call stops with FinishApproval.

func WithCache

func WithCache(p CachePolicy) Option

WithCache marks prompt-cache breakpoints.

func WithContentCapture

func WithContentCapture() Option

WithContentCapture lets observers see prompts, answers, and tool input and output, after every Redact middleware has run.

func WithMaxSteps

func WithMaxSteps(n int) Option

WithMaxSteps caps the model calls of a run, so the model can call tools and read their results up to n-1 times. Default 1: tools requested in the only step run, but the model does not see their results.

func WithMaxTokens

func WithMaxTokens(n int) Option

WithMaxTokens caps the output tokens of each step.

func WithMeta

func WithMeta(kv map[string]string) Option

WithMeta attaches labels to the run's steps and observer reports.

func WithMiddleware

func WithMiddleware(mw ...Middleware) Option

WithMiddleware wraps each step. The first middleware is the outermost.

func WithObserver

func WithObserver(o Observer) Option

WithObserver reports the run to o. Observers see no prompt or answer text unless WithContentCapture is set.

func WithProviderOptions

func WithProviderOptions(provider string, fields map[string]any) Option

WithProviderOptions merges fields into the request body sent to provider, such as {"store": false} for "openai".

func WithReasoning

func WithReasoning(r ReasoningOptions) Option

WithReasoning sets the thinking effort or budget.

func WithRepair

func WithRepair(n int) Option

WithRepair sets how many times invalid structured output is sent back to the model with the validation errors. Default 1.

func WithSystem

func WithSystem(s string) Option

WithSystem sets the system prompt.

func WithTemperature

func WithTemperature(t float64) Option

WithTemperature sets the sampling temperature.

func WithToolChoice

func WithToolChoice(tc ToolChoice) Option

WithToolChoice says whether the model must call a tool.

func WithToolSearchThreshold

func WithToolSearchThreshold(n int) Option

WithToolSearchThreshold sets how many deferred tools a run holds before they load through tool search. Default DefaultToolSearchThreshold.

func WithTools

func WithTools(ts ...Tool) Option

WithTools offers tools to the model. Duplicate names fail the run.

type Part

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

Part is one piece of a message: Text, Image, File, Audio, ToolCall, ToolResult, or Reasoning. The set is closed.

type Partial

type Partial[T any] struct {
	Value T
	// Text is the JSON received so far for the current attempt.
	Text string
	Done bool
	// Response is set on the last snapshot.
	Response *Response
}

Partial is a snapshot of a streamed object. Value holds what the JSON so far decodes to; Done is set once, on the last snapshot, after the whole answer validated.

type Price

type Price struct {
	Input      float64
	Output     float64
	CacheRead  float64
	CacheWrite float64
}

Price is the cost of a model in US dollars per million tokens.

type Pricing

type Pricing map[string]Price

Pricing maps model IDs to prices. The app supplies it; aikit ships no price table because prices change.

func (Pricing) Cost

func (p Pricing) Cost(model string, u Usage) (float64, bool)

Cost returns what usage u of model costs, and false when the model has no price.

type Prompt

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

Prompt is the input of a generation: a Message or Messages.

type ProviderError

type ProviderError struct {
	Provider string
	Model    string
	// Code is the provider's error code or type, when it sends one.
	Code    string
	Message string
	Status  int
	// RetryAfter is how long the provider asked to wait, or 0.
	RetryAfter time.Duration
	// Err is one of the sentinel errors.
	Err error
}

ProviderError is an error a provider returned.

func StatusError

func StatusError(provider, model string, status int, h http.Header, code, msg string) *ProviderError

StatusError builds the ProviderError for an HTTP error status, reading Retry-After from h. Drivers refine Err when the body says more, such as a context-length or quota error.

func (*ProviderError) Error

func (e *ProviderError) Error() string

func (*ProviderError) Unwrap

func (e *ProviderError) Unwrap() error

Unwrap returns the sentinel error.

type Ranked

type Ranked struct {
	// Index is the document's position in the input.
	Index int
	Score float64
}

Ranked is one reranked document.

type Reasoning

type Reasoning struct {
	Text      string
	Signature string
	Redacted  string
}

Reasoning is a model's visible thinking. Signature and Redacted carry provider data that must be sent back unchanged on the next turn.

type ReasoningDelta

type ReasoningDelta struct{ Text string }

ReasoningDelta is the next piece of the model's visible thinking.

type ReasoningOptions

type ReasoningOptions struct {
	// Effort is "low", "medium", or "high" for providers that take an
	// effort level.
	Effort string
	// BudgetTokens caps thinking tokens for providers that take a budget.
	BudgetTokens int
}

ReasoningOptions sets how much a reasoning model thinks.

type RedactScope

type RedactScope uint8

RedactScope says what a Redact middleware rewrites.

const (
	// RedactPrompt rewrites the prompt sent to the model, and what
	// observers see.
	RedactPrompt RedactScope = iota
	// RedactObserver rewrites only what observers see with content
	// capture on.
	RedactObserver
)

The redaction scopes.

type Redactor

type Redactor interface {
	Redact(ctx context.Context, s string) string
}

Redactor rewrites text to hide sensitive values.

type RedactorFunc

type RedactorFunc func(ctx context.Context, s string) string

RedactorFunc adapts a function to Redactor.

func (RedactorFunc) Redact

func (f RedactorFunc) Redact(ctx context.Context, s string) string

Redact calls f.

type Request

type Request struct {
	System     string
	Messages   []Message
	Tools      []Tool
	ToolChoice ToolChoice
	// Output asks for JSON matching the schema; nil asks for text.
	Output      *schema.Schema
	MaxTokens   int
	Temperature *float64
	// Reasoning sets the thinking effort or budget. Drivers that cannot
	// reason ignore it.
	Reasoning *ReasoningOptions
	// Cache marks prompt-cache breakpoints. Drivers without explicit
	// prompt caching ignore it.
	Cache CachePolicy
	// DeferTools asks the driver to load ToolDeferred tools through the
	// provider's native tool search. The run sets it when the model
	// implements NativeToolSearch and the deferred tools pass the
	// threshold.
	DeferTools bool
	// Provider holds provider-specific request fields, keyed by
	// Model.Provider(). A driver merges its entry into the request body.
	Provider map[string]map[string]any
}

Request is one call to a model.

func (*Request) Clone

func (r *Request) Clone() *Request

Clone returns a copy of r whose slices and maps can be changed without changing r.

type Reranker

type Reranker interface {
	Rerank(ctx context.Context, query string, docs []string, topN int) ([]Ranked, error)
}

Reranker orders documents by relevance to a query.

type Response

type Response struct {
	Message      Message
	FinishReason FinishReason
	Usage        Usage
	Steps        []StepResult
	// Approvals lists the tool calls that wait for a decision when
	// FinishReason is FinishApproval.
	Approvals []ApprovalRequest
	// Raw is the provider's response body, when the driver keeps it.
	Raw json.RawMessage
}

Response is a model's answer. From GenerateText it is the last step's answer with Usage summed over all steps and Steps listing each one.

func Collect

func Collect(seq iter.Seq2[Event, error]) (*Response, error)

Collect drains a stream and returns its Finish response.

func GenerateObject

func GenerateObject[T any](ctx context.Context, m Model, p Prompt, opts ...Option) (T, *Response, error)

GenerateObject asks the model for JSON matching T's schema, validates the answer, and decodes it. Invalid output is sent back with the validation errors up to WithRepair times (default 1); after that the error is a *SchemaError, which never triggers failover.

func GenerateText

func GenerateText(ctx context.Context, m Model, p Prompt, opts ...Option) (*Response, error)

GenerateText runs the model on p, running the tools it calls, for up to WithMaxSteps model calls. The response is the last step's, with usage summed over all steps.

On error the response, when not nil, holds the steps that finished: a stop from middleware returns both.

func (*Response) Text

func (r *Response) Text() string

Text is the response message's text.

func (*Response) ToolCalls

func (r *Response) ToolCalls() []ToolCall

ToolCalls lists the tool calls of the response message.

type Role

type Role string

Role is who wrote a message.

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

The roles. A tool message carries ToolResult parts.

type RunEnd

type RunEnd struct {
	Usage        Usage
	Steps        int
	FinishReason FinishReason
	// Output is the final answer text, with content capture only.
	Output   string
	Err      error
	Duration time.Duration
}

RunEnd describes a finished run.

type RunInfo

type RunInfo struct {
	RunID     string
	Operation string
	Provider  string
	Model     string
	Meta      map[string]string
	Start     time.Time
}

RunInfo describes a run as it starts.

type SchemaError

type SchemaError struct {
	Schema string
	// Text is the model's last answer.
	Text     string
	Problems []schema.Problem
	Err      error
}

SchemaError is structured output that still broke its schema after the repair turns. It never triggers failover.

func (*SchemaError) Error

func (e *SchemaError) Error() string

func (*SchemaError) Unwrap

func (e *SchemaError) Unwrap() error

type SimilarDoc

type SimilarDoc struct {
	ID    string            `json:"id"`
	Text  string            `json:"text"`
	Score float64           `json:"score"`
	Meta  map[string]string `json:"meta,omitempty"`
}

SimilarDoc is one result of the SimilaritySearch tool.

type SpeechConfig

type SpeechConfig struct {
	Voice string
	// Format is the audio format, such as "mp3" or "wav".
	Format       string
	Instructions string
}

SpeechConfig is what SpeechOptions set.

func NewSpeechConfig

func NewSpeechConfig(opts ...SpeechOption) SpeechConfig

NewSpeechConfig applies opts.

type SpeechGenerator

type SpeechGenerator interface {
	Speak(ctx context.Context, text string, o ...SpeechOption) (io.ReadCloser, error)
}

SpeechGenerator turns text into audio.

type SpeechOption

type SpeechOption func(*SpeechConfig)

SpeechOption configures one Speak call.

func WithAudioFormat

func WithAudioFormat(f string) SpeechOption

WithAudioFormat picks the audio format.

func WithSpeechInstructions

func WithSpeechInstructions(s string) SpeechOption

WithSpeechInstructions tells the voice how to speak.

func WithVoice

func WithVoice(v string) SpeechOption

WithVoice picks the voice.

type Step

type Step struct {
	Index   int
	Model   Model
	Request *Request
	// Usage is the run's usage before this step.
	Usage Usage
	// History lists the run's finished steps.
	History []StepResult
	Meta    map[string]string
	// contains filtered or unexported fields
}

Step is one model call of a run, as middleware sees it before the call. Middleware may replace Model or change Request (its tools, its max tokens) for this step only.

type StepEnd

type StepEnd struct {
	Provider     string
	Model        string
	Usage        Usage
	FinishReason FinishReason
	// Output is the answer, with content capture only.
	Output   *Message
	Err      error
	Duration time.Duration
}

StepEnd describes a finished model call. Provider and Model name the model that answered, which differs from StepInfo after a failover.

type StepFinish

type StepFinish struct{ Step StepResult }

StepFinish ends one model call of a run.

type StepFunc

type StepFunc func(ctx context.Context, s *Step) (*StepResult, error)

StepFunc runs one step.

type StepInfo

type StepInfo struct {
	RunID       string
	Index       int
	Provider    string
	Model       string
	Tools       []string
	MaxTokens   int
	Temperature *float64
	// System and Messages are the prompt, with content capture only.
	System   string
	Messages []Message
	Meta     map[string]string
}

StepInfo describes a model call as it starts, after middleware has chosen its model and request.

type StepResult

type StepResult struct {
	Index        int
	Provider     string
	Model        string
	Message      Message
	FinishReason FinishReason
	Usage        Usage
	ToolResults  []ToolResult
	Duration     time.Duration
}

StepResult is one model call of a run and the tools it ran.

type Text

type Text struct{ Text string }

Text is plain text.

type TextDelta

type TextDelta struct{ Text string }

TextDelta is the next piece of the answer's text.

type Tool

type Tool interface {
	Name() string
	Description() string
	// InputSchema is the JSON Schema of the arguments object.
	InputSchema() json.RawMessage
	Call(ctx context.Context, args json.RawMessage) (json.RawMessage, error)
}

Tool is a function a model can call. Its method set uses only standard library types, so a type from another module (an MCP tool, say) can be a Tool without importing this package.

func SimilaritySearch

func SimilaritySearch(store VectorStore, e Embedder, ns string, k int) Tool

SimilaritySearch returns a read-only tool that embeds the model's query with e and returns the k closest documents of namespace ns in store.

type ToolAnnotated

type ToolAnnotated interface {
	ReadOnly() bool
	Destructive() bool
}

ToolAnnotated is a Tool that says whether it changes anything.

type ToolApproval

type ToolApproval interface {
	NeedsApproval(ctx context.Context, args json.RawMessage) bool
}

ToolApproval is a Tool whose calls may need a person's approval.

type ToolAuthorizer

type ToolAuthorizer interface {
	Authorize(ctx context.Context) error
}

ToolAuthorizer is a Tool that checks the caller before each call. An error is returned to the model as the tool's result.

type ToolCall

type ToolCall struct {
	ID   string
	Name string
	Args json.RawMessage
	// Hosted is true for a call the provider ran itself, such as web
	// search. The loop does not run it; drivers send it back unchanged.
	Hosted bool
	// Signature is provider data that must go back with the call, such as
	// a Gemini thought signature.
	Signature string
}

ToolCall is a model's request to run a tool.

type ToolCallDelta

type ToolCallDelta struct{ ID, Args string }

ToolCallDelta is the next piece of a tool call's JSON arguments.

type ToolCallEnd

type ToolCallEnd struct{ Call ToolCall }

ToolCallEnd closes a tool call with its complete arguments.

type ToolCallError

type ToolCallError struct {
	Tool string
	Args json.RawMessage
	Err  error
}

ToolCallError is a tool call whose arguments are not valid for the tool. The first one in a run is sent back to the model as the tool's result so it can repair the call; another one ends the run with this error.

func (*ToolCallError) Error

func (e *ToolCallError) Error() string

func (*ToolCallError) Unwrap

func (e *ToolCallError) Unwrap() error

type ToolCallGuardrail

type ToolCallGuardrail interface {
	CheckToolCall(ctx context.Context, call ToolCall) error
}

ToolCallGuardrail is a Guardrail that also checks each tool call a model asks for, before it runs.

type ToolCallStart

type ToolCallStart struct{ ID, Name string }

ToolCallStart opens a tool call; its arguments follow as ToolCallDelta.

type ToolChoice

type ToolChoice string

ToolChoice says whether the model must call a tool: ToolAuto (the zero value), ToolNone, ToolRequired, or the name of the one tool to call.

const (
	ToolAuto     ToolChoice = ""
	ToolNone     ToolChoice = "none"
	ToolRequired ToolChoice = "required"
)

The tool choices that are not a tool name.

type ToolDeferred

type ToolDeferred interface {
	Deferred() bool
}

ToolDeferred is a Tool that is loaded only when a tool search finds it.

type ToolEnd

type ToolEnd struct {
	// Output is the result, with content capture only.
	Output   json.RawMessage
	IsError  bool
	Err      error
	Duration time.Duration
}

ToolEnd describes a finished tool call.

type ToolInfo

type ToolInfo struct {
	RunID  string
	Step   int
	CallID string
	Name   string
	// Args are the arguments, with content capture only.
	Args json.RawMessage
}

ToolInfo describes a tool call as it starts.

type ToolOption

type ToolOption func(*toolConfig)

ToolOption configures NewTool.

func Deferred

func Deferred() ToolOption

Deferred makes a tool eligible for tool search.

func Destructive

func Destructive() ToolOption

Destructive marks a tool whose effects cannot be undone.

func ReadOnly

func ReadOnly() ToolOption

ReadOnly marks a tool that changes nothing.

func RequireApproval

func RequireApproval(pred ...func(ctx context.Context, in any) bool) ToolOption

RequireApproval makes calls wait for approval: every call, or with predicates, the calls for which one of them returns true. A predicate gets the decoded input, the In of NewTool.

func ToolTimeout

func ToolTimeout(d time.Duration) ToolOption

ToolTimeout bounds each call.

type ToolOutputSchema

type ToolOutputSchema interface {
	OutputSchema() json.RawMessage
}

ToolOutputSchema is a Tool that describes its result.

type ToolResult

type ToolResult struct {
	CallID  string
	Name    string
	Output  json.RawMessage
	IsError bool
}

ToolResult is the output of a tool call. It is both a message part and a stream event. In a tool message it answers a ToolCall; in an assistant message it is the result of a hosted call, and Output is the provider's own block, which its driver sends back unchanged.

type Toolset

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

Toolset is a set of tools with unique names.

func Tools

func Tools(ts ...Tool) (*Toolset, error)

Tools builds a Toolset. An empty or duplicate name is an error.

func (*Toolset) Deferred

func (s *Toolset) Deferred() []Tool

Deferred lists the tools that are loaded only through tool search.

func (*Toolset) Lookup

func (s *Toolset) Lookup(name string) (Tool, bool)

Lookup returns the tool named name.

func (*Toolset) Tools

func (s *Toolset) Tools() []Tool

Tools lists the tools in the order given.

type TranscribeConfig

type TranscribeConfig struct {
	// Filename names the upload; its extension tells the format.
	Filename string
	Language string
	Prompt   string
}

TranscribeConfig is what TranscribeOptions set.

func NewTranscribeConfig

func NewTranscribeConfig(opts ...TranscribeOption) TranscribeConfig

NewTranscribeConfig applies opts.

type TranscribeOption

type TranscribeOption func(*TranscribeConfig)

TranscribeOption configures one Transcribe call.

func WithFilename

func WithFilename(name string) TranscribeOption

WithFilename names the audio upload, such as "call.mp3".

func WithLanguage

func WithLanguage(lang string) TranscribeOption

WithLanguage gives the spoken language as ISO-639-1.

type Transcriber

type Transcriber interface {
	Transcribe(ctx context.Context, audio io.Reader, o ...TranscribeOption) (*Transcript, error)
}

Transcriber turns audio into text.

type Transcript

type Transcript struct {
	Text     string
	Language string
}

Transcript is the text of some audio.

type TypedTool

type TypedTool[In, Out any] struct {
	// contains filtered or unexported fields
}

TypedTool is a Tool built from a Go function by NewTool.

func NewTool

func NewTool[In, Out any](name, desc string, fn func(ctx context.Context, in In) (Out, error), opts ...ToolOption) *TypedTool[In, Out]

NewTool returns a tool that decodes and validates its arguments into In, calls fn, and encodes its Out as JSON. In must be a struct or a map; NewTool panics otherwise, because that is a programming error.

func (*TypedTool[In, Out]) Call

func (t *TypedTool[In, Out]) Call(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

Call decodes args, runs the function, and encodes its result. Arguments that do not match the schema return a *ToolCallError.

func (*TypedTool[In, Out]) Deferred

func (t *TypedTool[In, Out]) Deferred() bool

Deferred reports the Deferred option.

func (*TypedTool[In, Out]) Description

func (t *TypedTool[In, Out]) Description() string

Description returns the tool's description.

func (*TypedTool[In, Out]) Destructive

func (t *TypedTool[In, Out]) Destructive() bool

Destructive reports the Destructive option.

func (*TypedTool[In, Out]) InputSchema

func (t *TypedTool[In, Out]) InputSchema() json.RawMessage

InputSchema returns the strict JSON Schema of In.

func (*TypedTool[In, Out]) Name

func (t *TypedTool[In, Out]) Name() string

Name returns the tool's name.

func (*TypedTool[In, Out]) NeedsApproval

func (t *TypedTool[In, Out]) NeedsApproval(ctx context.Context, args json.RawMessage) bool

NeedsApproval applies the RequireApproval option to one call.

func (*TypedTool[In, Out]) OutputSchema

func (t *TypedTool[In, Out]) OutputSchema() json.RawMessage

OutputSchema returns the JSON Schema of Out.

func (*TypedTool[In, Out]) ReadOnly

func (t *TypedTool[In, Out]) ReadOnly() bool

ReadOnly reports the ReadOnly option.

type Usage

type Usage struct {
	Input      int
	Output     int
	CacheRead  int
	CacheWrite int
	Reasoning  int
}

Usage counts tokens. Input includes CacheRead and CacheWrite; Output includes Reasoning.

func (Usage) Add

func (u Usage) Add(v Usage) Usage

Add returns u plus v.

func (Usage) Total

func (u Usage) Total() int

Total is Input plus Output.

type VectorDoc

type VectorDoc struct {
	ID     string
	Vector []float32
	// Text is the content the vector was embedded from.
	Text string
	Meta map[string]string
}

VectorDoc is one embedded document in a VectorStore namespace.

type VectorHit

type VectorHit struct {
	VectorDoc
	Score float64
}

VectorHit is a VectorDoc returned by a query, with its cosine similarity to the query vector: 1 is the same direction, -1 the opposite.

type VectorStore

type VectorStore interface {
	// Upsert inserts docs, replacing any with the same ID in ns.
	Upsert(ctx context.Context, ns string, docs ...VectorDoc) error
	// Query returns the k documents of ns closest to v by cosine
	// similarity, best first, among those that match every filter.
	Query(ctx context.Context, ns string, v []float32, k int, f ...Filter) ([]VectorHit, error)
	// Delete removes ids from ns. Unknown ids are ignored.
	Delete(ctx context.Context, ns string, ids ...string) error
}

VectorStore stores embeddings by namespace and finds the nearest ones. Implementations must be safe for concurrent use.

Directories

Path Synopsis
agent module
Package airec records recent AI runs in memory for the dev dashboard.
Package airec records recent AI runs in memory for the dev dashboard.
Package aitest tests code that uses package aikit: a scripted fake Model, assertions on what it was asked, HTTP record and replay for drivers, and ModelContract, the suite every driver passes.
Package aitest tests code that uses package aikit: a scripted fake Model, assertions on what it was asked, HTTP record and replay for drivers, and ModelContract, the suite every driver passes.
anthropic module
bedrock module
converse module
Package eval grades an AI target against cases with deterministic checks or a judge model.
Package eval grades an AI target against cases with deterministic checks or a judge model.
gemini module
internal
wire
Package wire holds the HTTP plumbing the provider drivers share: JSON requests, server-sent event parsing, and error decoding.
Package wire holds the HTTP plumbing the provider drivers share: JSON requests, server-sent event parsing, and error decoding.
live module
mcp module
conformance module
nock module
obs module
openai module
Package schema builds JSON Schemas from Go types for tool inputs and structured output, validates JSON against them, and adapts them to the subsets each model provider accepts.
Package schema builds JSON Schemas from Go types for tool inputs and structured output, validates JSON against them, and adapts them to the subsets each model provider accepts.
stream
agui
Package agui encodes an aikit event stream as AG-UI protocol events over server-sent events, for CopilotKit and other AG-UI clients.
Package agui encodes an aikit event stream as AG-UI protocol events over server-sent events, for CopilotKit and other AG-UI clients.
vercel
Package vercel encodes an aikit event stream as the Vercel AI SDK UI message stream (protocol v1), which useChat reads over server-sent events.
Package vercel encodes an aikit event stream as the Vercel AI SDK UI message stream (protocol v1), which useChat reads over server-sent events.
vertex module

Jump to

Keyboard shortcuts

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