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
- Variables
- func Failoverable(err error) bool
- func Stop(reason string) error
- func StreamObject[T any](ctx context.Context, m Model, p Prompt, opts ...Option) iter.Seq2[Partial[T], error]
- func StreamText(ctx context.Context, m Model, p Prompt, opts ...Option) iter.Seq2[Event, error]
- type ApprovalDecision
- type ApprovalRequest
- type ApprovalRequested
- type Approver
- type ApproverFunc
- type Audio
- type CachePolicy
- type EmbedConfig
- type EmbedOption
- type Embedder
- type Embeddings
- type Event
- type FailoverEvent
- type File
- type Filter
- type Finish
- type FinishReason
- type GeneratedImage
- type Guardrail
- type GuardrailError
- type HostedTool
- type Image
- type ImageGenerator
- type ImagePrompt
- type Limit
- type Message
- type Messages
- type Middleware
- type Model
- type Named
- type NativeToolSearch
- type Notice
- type NoticeKind
- type Observer
- type Option
- func WithApprover(a Approver) Option
- func WithCache(p CachePolicy) Option
- func WithContentCapture() Option
- func WithMaxSteps(n int) Option
- func WithMaxTokens(n int) Option
- func WithMeta(kv map[string]string) Option
- func WithMiddleware(mw ...Middleware) Option
- func WithObserver(o Observer) Option
- func WithProviderOptions(provider string, fields map[string]any) Option
- func WithReasoning(r ReasoningOptions) Option
- func WithRepair(n int) Option
- func WithSystem(s string) Option
- func WithTemperature(t float64) Option
- func WithToolChoice(tc ToolChoice) Option
- func WithToolSearchThreshold(n int) Option
- func WithTools(ts ...Tool) Option
- type Part
- type Partial
- type Price
- type Pricing
- type Prompt
- type ProviderError
- type Ranked
- type Reasoning
- type ReasoningDelta
- type ReasoningOptions
- type RedactScope
- type Redactor
- type RedactorFunc
- type Request
- type Reranker
- type Response
- type Role
- type RunEnd
- type RunInfo
- type SchemaError
- type SimilarDoc
- type SpeechConfig
- type SpeechGenerator
- type SpeechOption
- type Step
- type StepEnd
- type StepFinish
- type StepFunc
- type StepInfo
- type StepResult
- type Text
- type TextDelta
- type Tool
- type ToolAnnotated
- type ToolApproval
- type ToolAuthorizer
- type ToolCall
- type ToolCallDelta
- type ToolCallEnd
- type ToolCallError
- type ToolCallGuardrail
- type ToolCallStart
- type ToolChoice
- type ToolDeferred
- type ToolEnd
- type ToolInfo
- type ToolOption
- type ToolOutputSchema
- type ToolResult
- type Toolset
- type TranscribeConfig
- type TranscribeOption
- type Transcriber
- type Transcript
- type TypedTool
- func (t *TypedTool[In, Out]) Call(ctx context.Context, args json.RawMessage) (json.RawMessage, error)
- func (t *TypedTool[In, Out]) Deferred() bool
- func (t *TypedTool[In, Out]) Description() string
- func (t *TypedTool[In, Out]) Destructive() bool
- func (t *TypedTool[In, Out]) InputSchema() json.RawMessage
- func (t *TypedTool[In, Out]) Name() string
- func (t *TypedTool[In, Out]) NeedsApproval(ctx context.Context, args json.RawMessage) bool
- func (t *TypedTool[In, Out]) OutputSchema() json.RawMessage
- func (t *TypedTool[In, Out]) ReadOnly() bool
- type Usage
- type VectorDoc
- type VectorHit
- type VectorStore
Constants ¶
const ( OpGenerateText = "generate_text" OpStreamText = "stream_text" OpGenerateObject = "generate_object" OpStreamObject = "stream_object" )
The operations a run reports in RunInfo.Operation.
const DefaultToolSearchThreshold = 20
DefaultToolSearchThreshold is how many deferred tools a toolset holds before they are loaded through tool search.
const SearchToolsName = "search_tools"
SearchToolsName is the name of the emulated tool-search meta-tool.
const SimilaritySearchName = "similarity_search"
SimilaritySearchName is the name of the SimilaritySearch tool.
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
func (f ApproverFunc) Approve(ctx context.Context, req ApprovalRequest) (ApprovalDecision, error)
Approve calls f.
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 ¶
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 ¶
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 ¶
HostedTool is a tool a provider runs itself, such as web search. Only a model of that provider can take it.
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 ¶
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 ¶
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 ¶
MaxInputTokens stops a run once it has used n input tokens.
func MaxSteps ¶
MaxSteps stops a run before its step n+1. Unlike WithMaxSteps, reaching it is an error.
func MaxTotalTokens ¶
MaxTotalTokens stops a run once it has used n tokens.
type Message ¶
Message is one turn of a conversation.
func System ¶
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.
type Middleware ¶
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 ¶
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 ¶
WithApprover decides tool calls that need approval. Without one, a run that reaches such a call stops with FinishApproval.
func WithContentCapture ¶
func WithContentCapture() Option
WithContentCapture lets observers see prompts, answers, and tool input and output, after every Redact middleware has run.
func WithMaxSteps ¶
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 ¶
WithMaxTokens caps the output tokens of each step.
func WithMiddleware ¶
func WithMiddleware(mw ...Middleware) Option
WithMiddleware wraps each step. The first middleware is the outermost.
func WithObserver ¶
WithObserver reports the run to o. Observers see no prompt or answer text unless WithContentCapture is set.
func WithProviderOptions ¶
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 ¶
WithRepair sets how many times invalid structured output is sent back to the model with the validation errors. Default 1.
func WithTemperature ¶
WithTemperature sets the sampling temperature.
func WithToolChoice ¶
func WithToolChoice(tc ToolChoice) Option
WithToolChoice says whether the model must call a tool.
func WithToolSearchThreshold ¶
WithToolSearchThreshold sets how many deferred tools a run holds before they load through tool search. Default DefaultToolSearchThreshold.
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 Pricing ¶
Pricing maps model IDs to prices. The app supplies it; aikit ships no price table because prices change.
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 Reasoning ¶
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 RedactorFunc ¶
RedactorFunc adapts a function to Redactor.
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.
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 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 ¶
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.
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.
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 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 ¶
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 ¶
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 ¶
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 Destructive ¶
func Destructive() ToolOption
Destructive marks a tool whose effects cannot be undone.
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.
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.
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 ¶
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]) Description ¶
Description returns the tool's description.
func (*TypedTool[In, Out]) Destructive ¶
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]) NeedsApproval ¶
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.
type Usage ¶
Usage counts tokens. Input includes CacheRead and CacheWrite; Output includes Reasoning.
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 ¶
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.
Source Files
¶
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
|