Documentation
¶
Overview ¶
Package aisdk is a Go port of Vercel's AI SDK.
It provides streaming LLM orchestration, tool execution, and SSE output compatible with the @ai-sdk/react hooks (useChat, useCompletion, useObject). The AI SDK docs at https://ai-sdk.dev/docs serve as the primary reference for naming, behavior, and protocol details.
Architecture ¶
The package has two layers:
- aisdk/provider (sub-package): the provider interface and types that LLM provider implementations depend on. This is a leaf package with no dependencies on the root.
- aisdk (this package): orchestration (StreamText, GenerateText), the UIMessage type, tool system, SSE stream writing, and HTTP helpers.
Streaming ¶
StreamText is the main entry point. It calls a provider.LanguageModel, runs a multi-step tool execution loop, and emits TextStreamPart events on StreamTextResult.FullStream. These events can be converted to SSE chunks via StreamTextResult.ToUIMessageStream and piped to an HTTP response with PipeUIMessageStreamToResponse.
result := aisdk.StreamText(ctx, myProvider,
aisdk.WithMessages(messages...),
aisdk.WithTools(tools),
)
aisdk.PipeUIMessageStreamToResponse(w, result.ToUIMessageStream())
For non-streaming use, GenerateText blocks until the LLM finishes and returns a populated GenerateTextResult.
Messages ¶
UIMessage is the canonical message type, matching the AI SDK's UIMessage. It is JSON-serializable for persistence. Parts are represented as an interface (Part) with concrete types (TextPart, ToolInvocationPart, etc.) for type-safe access via type switches.
Provider-level messages live in the provider sub-package as the flat discriminated provider.Message struct (with provider.NewSystemMessage, provider.NewUserMessage, provider.NewAssistantMessage, and provider.NewToolMessage constructors). ConvertToModelMessages bridges the UI-layer and provider-layer message types.
ToResponseMessages converts a slice of collected response content parts into the next-call assistant + tool messages, preserving reasoning blocks (and provider signatures) across multi-step tool execution. The same output is surfaced on ResponseMetadata.Messages for the last completed step.
ExtractTextContent and ExtractReasoningContent read the forward direction: they join text or reasoning parts from a [[]provider.ContentPart] slice (text concatenates with no separator, reasoning joins with "\n"). ExtractTextContentGenerate and ExtractReasoningContentGenerate are the equivalents for [[]provider.GenerateContentPart] returned by provider.LanguageModel's DoGenerate.
Tools ¶
Tools are defined as a ToolSet (map[string]Tool). Each tool has an optional Execute function: if nil, the tool call is returned to the caller for external execution. If set, StreamText executes it locally and feeds the result back to the model.
Standalone stream composition ¶
CreateUIMessageStream and UIMessageStreamWriter allow composing LLM output with custom data parts independently of StreamText, matching the AI SDK's createUIMessageStream API.
Index ¶
- Constants
- Variables
- func ConvertToModelMessages(messages []UIMessage, opts ...ConvertOption) ([]provider.Message, error)
- func CreateAgentUIStream(ctx context.Context, agent Agent, messages []UIMessage, ...) (<-chan UIMessageChunk, error)
- func CreateIDGenerator(opts IDGeneratorOptions) func() string
- func CreateUIMessageStream(params CreateUIMessageStreamParams) <-chan UIMessageChunk
- func ExtractReasoningContent(content []provider.ContentPart) string
- func ExtractReasoningContentGenerate(content []provider.GenerateContentPart) string
- func ExtractTextContent(content []provider.ContentPart) string
- func ExtractTextContentGenerate(content []provider.GenerateContentPart) string
- func FingerprintTools(tools ToolSet) (map[string]string, error)
- func FormatSSEEvent(chunk UIMessageChunk) ([]byte, error)
- func GenerateID() string
- func PipeAgentUIStreamToResponse(w http.ResponseWriter, stream <-chan UIMessageChunk) error
- func PipeUIMessageStreamToResponse(w http.ResponseWriter, stream <-chan UIMessageChunk) error
- func StreamUIMessage(stream <-chan UIMessageChunk, opts ...UIMessageReaderOption) <-chan UIMessage
- func ToResponseMessages(parts []provider.ContentPart) []provider.Message
- func WriteAgentUIStream(w http.ResponseWriter, ctx context.Context, agent Agent, messages []UIMessage, ...) error
- func WriteTextStream(w http.ResponseWriter, result *StreamTextResult) error
- func WriteUIMessageStream(w http.ResponseWriter, result *StreamTextResult, opts ...UIMessageStreamOption) error
- type Agent
- type AgentGenerateOption
- type AgentOption
- type AgentStreamOption
- type AgentVersion
- type BoundedArrayOutput
- type ChunkType
- type ContentPart
- type ConvertOption
- type CreateUIMessageStreamParams
- type CustomContent
- type CustomPart
- type DataPart
- type DynamicToolUIPart
- type FileContent
- type FilePart
- type GenerateOption
- type GenerateTextResult
- type GeneratedFile
- type IDGeneratorOptions
- type InvalidToolApprovalError
- type InvalidToolApprovalSignatureError
- type MissingToolResultsError
- type OnAbortState
- type OnChunkState
- type OnFinishState
- type OnStartState
- type OnStepFinishState
- type OnStepStartState
- type OnToolCallFinishState
- type OnToolCallStartState
- type Option
- func OnError(fn func(error)) Option
- func OnFinish(fn func(OnFinishState)) Option
- func OnStart(fn func(OnStartState)) Option
- func OnStepEnd(fn func(OnStepFinishState)) Option
- func OnStepFinish(fn func(OnStepFinishState)) Option
- func OnStepStart(fn func(OnStepStartState)) Option
- func OnToolCallFinish(fn func(OnToolCallFinishState)) Option
- func OnToolCallStart(fn func(OnToolCallStartState)) Option
- func WithActiveTools(names ...string) Option
- func WithFrequencyPenalty(f float64) Option
- func WithGenerateID(fn func() string) Option
- func WithHeaders(headers map[string]string) Option
- func WithInstructions(text string) Option
- func WithMaxOutputTokens(n int) Option
- func WithMaxRetries(n int) Option
- func WithMessages(msgs ...UIMessage) Option
- func WithModelMessages(msgs ...provider.Message) Option
- func WithOutput(out Output) Option
- func WithPrepareStep(fn PrepareStepFunc) Option
- func WithPresencePenalty(p float64) Option
- func WithProviderOptions(opts ...provider.ProviderOption) Option
- func WithReasoning(level provider.ReasoningEffort) Option
- func WithRepairText(fn RepairTextFunc) Option
- func WithResponseFormat(f provider.ResponseFormat) Option
- func WithSeed(s int) Option
- func WithStopSequences(seqs ...string) Option
- func WithStopWhen(conditions ...StopCondition) Option
- func WithSystem(text string) Option
- func WithSystemMessages(msgs ...SystemModelMessage) Option
- func WithTemperature(t float64) Option
- func WithTimeout(cfg TimeoutConfig) Option
- func WithToolApproval(policy ToolApprovalPolicyConfig) Option
- func WithToolApprovalSecret(secret string) Option
- func WithToolApprovalSecretBytes(secret []byte) Option
- func WithToolChoice(tc provider.ToolChoice) Option
- func WithToolRoutes(routes ToolRoutes) Option
- func WithTopK(k int) Option
- func WithTopP(p float64) Option
- type Output
- type Part
- type PrepareStepFunc
- type PrepareStepResult
- type PrepareStepState
- type ReasoningContent
- type ReasoningFileContent
- type ReasoningFileOutput
- type ReasoningFilePart
- type ReasoningOutput
- type ReasoningPart
- type ReasoningTextOutput
- type RepairTextFunc
- type ResponseMetadata
- type RetryError
- type RetryErrorReason
- type Role
- type SingleToolApprovalFunc
- type Source
- type SourceContent
- type SourceDocumentPart
- type SourceURLPart
- type StepModel
- type StepResult
- type StepStartPart
- type StepType
- type StopCondition
- type StopConditionState
- type StreamAbort
- type StreamCustom
- type StreamError
- type StreamFile
- type StreamFinish
- type StreamFinishStep
- type StreamOption
- type StreamRaw
- type StreamReasoningDelta
- type StreamReasoningEnd
- type StreamReasoningFile
- type StreamReasoningStart
- type StreamSource
- type StreamStart
- type StreamStartStep
- type StreamTextDelta
- type StreamTextEnd
- type StreamTextResult
- func (r *StreamTextResult) AggregateUsage() provider.Usage
- func (r *StreamTextResult) Content() []ContentPart
- func (r *StreamTextResult) ElementStream() <-chan json.RawMessage
- func (r *StreamTextResult) ElementStreamError() error
- func (r *StreamTextResult) Err() error
- func (r *StreamTextResult) Files() []GeneratedFile
- func (r *StreamTextResult) FinishReason() provider.FinishReason
- func (r *StreamTextResult) FullStream() <-chan TextStreamPart
- func (r *StreamTextResult) OutputError() error
- func (r *StreamTextResult) OutputValue() any
- func (r *StreamTextResult) PartialOutputStream() <-chan json.RawMessage
- func (r *StreamTextResult) ProviderMetadata() provider.ProviderMetadata
- func (r *StreamTextResult) Reasoning() []ReasoningOutput
- func (r *StreamTextResult) Response() ResponseMetadata
- func (r *StreamTextResult) ResponseMessages() []provider.Message
- func (r *StreamTextResult) Sources() []Source
- func (r *StreamTextResult) Steps() []StepResult
- func (r *StreamTextResult) Stream() <-chan TextStreamPart
- func (r *StreamTextResult) Text() string
- func (r *StreamTextResult) ToUIMessageStream(opts ...UIMessageStreamOption) <-chan UIMessageChunk
- func (r *StreamTextResult) ToolCalls() []ToolCall
- func (r *StreamTextResult) ToolResults() []ToolResult
- func (r *StreamTextResult) TotalUsage() provider.Usage
- func (r *StreamTextResult) Usage() provider.Usage
- func (r *StreamTextResult) Wait()
- func (r *StreamTextResult) Warnings() []provider.Warning
- type StreamTextStart
- type StreamToolApprovalRequest
- type StreamToolApprovalResponse
- type StreamToolCall
- type StreamToolError
- type StreamToolInputDelta
- type StreamToolInputEnd
- type StreamToolInputStart
- type StreamToolOutputDenied
- type StreamToolResult
- type SystemModelMessage
- type TextContent
- type TextPart
- type TextStreamPart
- type TimeoutConfig
- type Tool
- type ToolApproval
- type ToolApprovalConfig
- type ToolApprovalDecision
- type ToolApprovalFunc
- type ToolApprovalMap
- type ToolApprovalOptions
- type ToolApprovalPolicy
- type ToolApprovalPolicyConfig
- type ToolApprovalRequest
- type ToolApprovalRequestContent
- type ToolApprovalResponse
- type ToolApprovalResponseContent
- type ToolApprovalStatus
- type ToolCall
- type ToolCallContent
- type ToolCallNotFoundForApprovalError
- type ToolCaller
- type ToolCallerType
- type ToolDescriptionFunc
- type ToolDescriptionOptions
- type ToolDrift
- type ToolErrorContent
- type ToolExecuteFunc
- type ToolExecuteStreamFunc
- type ToolExecutionOptions
- type ToolInvocationPart
- type ToolInvocationState
- type ToolLoopAgent
- func (a *ToolLoopAgent) Generate(ctx context.Context, opts ...AgentGenerateOption) (*GenerateTextResult, error)
- func (a *ToolLoopAgent) ID() string
- func (a *ToolLoopAgent) Stream(ctx context.Context, opts ...AgentStreamOption) *StreamTextResult
- func (a *ToolLoopAgent) Tools() ToolSet
- func (a *ToolLoopAgent) Version() AgentVersion
- type ToolLoopAgentOption
- type ToolNeedsApprovalFunc
- type ToolNotExecutableError
- type ToolOption
- type ToolOutputContext
- type ToolResult
- type ToolResultContent
- type ToolRoute
- type ToolRoutes
- type ToolSet
- type TypedToolDef
- type UIMessage
- type UIMessageChunk
- func DataChunk(name string, data json.RawMessage, transient bool) UIMessageChunk
- func ErrorChunk(errorText string) UIMessageChunk
- func FileChunk(url, mediaType string) UIMessageChunk
- func FinishChunk(finishReason string) UIMessageChunk
- func ReasoningDeltaChunk(id, delta string) UIMessageChunk
- func ReasoningEndChunk(id string) UIMessageChunk
- func ReasoningFileChunk(url, mediaType string) UIMessageChunk
- func ReasoningStartChunk(id string) UIMessageChunk
- func SourceDocumentChunk(sourceID, mediaType, title string) UIMessageChunk
- func SourceURLChunk(sourceID, url string) UIMessageChunk
- func StartChunk(messageID string) UIMessageChunk
- func TextDeltaChunk(id, delta string) UIMessageChunk
- func TextEndChunk(id string) UIMessageChunk
- func TextStartChunk(id string) UIMessageChunk
- func ToolInputAvailableChunk(toolCallID, toolName string, input json.RawMessage) UIMessageChunk
- func ToolInputDeltaChunk(toolCallID, inputTextDelta string) UIMessageChunk
- func ToolInputErrorChunk(toolCallID, toolName string, input json.RawMessage, errorText string) UIMessageChunk
- func ToolInputStartChunk(toolCallID, toolName string) UIMessageChunk
- func ToolOutputAvailableChunk(toolCallID string, output json.RawMessage) UIMessageChunk
- func ToolOutputErrorChunk(toolCallID, errorText string) UIMessageChunk
- type UIMessageReaderOption
- type UIMessageStreamOnFinishState
- type UIMessageStreamOption
- func OnUIMessageStreamError(fn func(error) string) UIMessageStreamOption
- func OnUIMessageStreamFinish(fn func(UIMessageStreamOnFinishState)) UIMessageStreamOption
- func WithUIMessageStreamFinish(send bool) UIMessageStreamOption
- func WithUIMessageStreamGenerateID(fn func() string) UIMessageStreamOption
- func WithUIMessageStreamMessageMetadata(fn func(part TextStreamPart) json.RawMessage) UIMessageStreamOption
- func WithUIMessageStreamOriginalMessages(messages ...UIMessage) UIMessageStreamOption
- func WithUIMessageStreamReasoning(send bool) UIMessageStreamOption
- func WithUIMessageStreamSources(send bool) UIMessageStreamOption
- func WithUIMessageStreamStart(send bool) UIMessageStreamOption
- type UIMessageStreamWriter
- type UIPartType
- type UserToolType
Examples ¶
Constants ¶
const ( RoleSystem = provider.RoleSystem RoleUser = provider.RoleUser RoleAssistant = provider.RoleAssistant )
Role constants re-exported from the provider package.
Variables ¶
var ( ErrWriterClosed = errors.New("aisdk: write on closed stream writer") ErrAlreadyClosed = errors.New("aisdk: stream writer already closed") // ErrExecuteRequired reaches OnError when CreateUIMessageStreamParams.Execute is nil. ErrExecuteRequired = errors.New("aisdk: CreateUIMessageStreamParams.Execute is required") )
Sentinel errors for UIMessageStreamWriter.
var ErrInvalidOutputText = errors.New("aisdk: invalid output text")
ErrInvalidOutputText marks generated JSON text that fails syntax or schema validation. Typed conversion errors after successful validation do not wrap it.
var ErrNoObjectGenerated = errors.New("aisdk: no object generated")
ErrNoObjectGenerated is returned when structured output validation fails. The LLM's raw text response is still available via result.Text().
var ErrNoOutputGenerated = errors.New("aisdk: no output generated")
ErrNoOutputGenerated is returned when a model stream ends before producing output.
var SSEDone = []byte("data: [DONE]\n\n")
SSEDone is the sentinel SSE event that terminates a stream.
Functions ¶
func ConvertToModelMessages ¶
func ConvertToModelMessages(messages []UIMessage, opts ...ConvertOption) ([]provider.Message, error)
ConvertToModelMessages converts UIMessages to provider.Message slice suitable for passing to provider.LanguageModel.DoStream/DoGenerate.
func CreateAgentUIStream ¶
func CreateAgentUIStream(ctx context.Context, agent Agent, messages []UIMessage, opts ...UIMessageStreamOption) (<-chan UIMessageChunk, error)
CreateAgentUIStream creates a UIMessageChunk stream from an Agent and UI message history.
The helper validates represented states and configured static tool schemas on an isolated clone before calling Agent.Stream. Obsolete terminal static tools normalize to dynamic tools. That same normalized history is converted to model messages and preserved for response assembly. Application metadata/data schemas and unrepresented provider-tool schemas are not validated; Tool.ValidateInput is not a history validation callback.
func CreateIDGenerator ¶
func CreateIDGenerator(opts IDGeneratorOptions) func() string
CreateIDGenerator returns a function that generates IDs with the given prefix and size. Size defaults to 7 if not positive.
func CreateUIMessageStream ¶
func CreateUIMessageStream(params CreateUIMessageStreamParams) <-chan UIMessageChunk
CreateUIMessageStream creates a standalone UIMessageChunk stream. The Execute callback owns the whole stream: nothing is added to it, so Execute writes its own StartChunk and FinishChunk, or merges a stream that already carries them, such as StreamTextResult.ToUIMessageStream.
A start chunk written without a message ID receives the response message ID: the last OriginalMessages entry's ID when that entry is an assistant message, which continues it, and otherwise a generated ID. A start chunk that carries its own ID keeps it, which lets a caller supply a request-scoped ID. Without a start chunk, GenerateID and OriginalMessages reach only OnFinish, and the same holds when Execute merges a stream that stamps its own start chunk, since that ID wins.
A nil Execute, or a panic inside it, ends the stream with an error chunk rather than a crash. A chunk that cannot be applied while assembling the OnFinish message leaves the wire untouched and is reported through UIMessageStreamOnFinishState.AssemblyError.
func ExtractReasoningContent ¶
func ExtractReasoningContent(content []provider.ContentPart) string
ExtractReasoningContent returns the reasoning text from provider.ContentPartTypeReasoning parts joined by "\n", matching upstream's extractReasoningContent semantics. Non-reasoning parts are skipped. Returns "" when no reasoning parts are present.
func ExtractReasoningContentGenerate ¶
func ExtractReasoningContentGenerate(content []provider.GenerateContentPart) string
ExtractReasoningContentGenerate is the provider.GenerateContentPart counterpart of ExtractReasoningContent, for use with the content slice returned by provider.LanguageModel.DoGenerate. Returns the reasoning text from all provider.ContentReasoning parts joined by "\n", or "" if none are present.
func ExtractTextContent ¶
func ExtractTextContent(content []provider.ContentPart) string
ExtractTextContent returns the concatenation of every Text field from provider.ContentPartTypeText parts in order. Non-text parts (reasoning, tool calls, files, etc.) are skipped. Returns "" when no text parts are present.
Mirrors upstream's extractTextContent helper, which is a small but commonly needed primitive when post-processing a model's response content. Use this when you drive your own loop on top of provider.LanguageModel or post-process structures that carry [[]provider.ContentPart].
func ExtractTextContentGenerate ¶
func ExtractTextContentGenerate(content []provider.GenerateContentPart) string
ExtractTextContentGenerate is the provider.GenerateContentPart counterpart of ExtractTextContent, for use with the content slice returned by provider.LanguageModel.DoGenerate. Returns the concatenated text from all provider.ContentText parts, or "" if none are present.
func FingerprintTools ¶
FingerprintTools returns a stable digest for each tool's security-relevant definition fields: string description, input JSON schema, and title.
func FormatSSEEvent ¶
func FormatSSEEvent(chunk UIMessageChunk) ([]byte, error)
FormatSSEEvent serializes a UIMessageChunk as an SSE data line.
func GenerateID ¶
func GenerateID() string
GenerateID returns a random URL-safe ID with the default length (7 chars). If the system CSPRNG fails, it falls back to an atomic counter.
func PipeAgentUIStreamToResponse ¶
func PipeAgentUIStreamToResponse(w http.ResponseWriter, stream <-chan UIMessageChunk) error
PipeAgentUIStreamToResponse writes an already-created Agent UI stream as SSE.
func PipeUIMessageStreamToResponse ¶
func PipeUIMessageStreamToResponse(w http.ResponseWriter, stream <-chan UIMessageChunk) error
PipeUIMessageStreamToResponse writes a UIMessageChunk stream to an HTTP response as Server-Sent Events. It sets the appropriate SSE headers and terminates with a [DONE] sentinel.
When a write fails, it returns at once and drains the rest of the stream in the background, so the producer never blocks on a full buffer. Bind that producer to the request context so a client disconnect ends it.
func StreamUIMessage ¶
func StreamUIMessage(stream <-chan UIMessageChunk, opts ...UIMessageReaderOption) <-chan UIMessage
StreamUIMessage reads a UIMessageChunk stream and emits progressive UIMessage snapshots at upstream-compatible write points.
func ToResponseMessages ¶
func ToResponseMessages(parts []provider.ContentPart) []provider.Message
ToResponseMessages converts collected response content parts into the assistant + tool messages that should be fed into the next call.
It mirrors the upstream Vercel AI SDK helper at packages/ai/src/generate-text/to-response-messages.ts. The conversion preserves provider-specific metadata on every variant (notably reasoning signatures used by Anthropic extended thinking), and routes tool results the same way upstream does:
- text: assistant text part (empty text is skipped)
- reasoning: assistant reasoning part with provider.ContentPart.ProviderOptions copied from the input (this preserves Anthropic's "signature")
- reasoning-file: assistant reasoning-file part (passthrough)
- file: assistant file part
- custom: assistant custom part (Kind + ProviderOptions)
- tool-call: assistant tool-call part (provider-executed flag + options copied through)
- tool-result (provider-executed): assistant tool-result part emitted at its input position
- tool-result (client-executed): goes in the tool message
- tool-approval-request: assistant tool-approval-request part emitted at its input position
- tool-approval-response: tool message; if Approved == false, a synthetic execution-denied tool-result is appended for the matching call
- sources / unknown types: skipped
The order of parts in the assistant message follows the input order: every provider-executed tool-result appears at its own position rather than being inlined immediately after the matching tool-call. This matches upstream's main-loop traversal and lets public callers control the on-wire ordering of interleaved text / reasoning / call / result sequences.
Tool-call inputs are preserved verbatim. StreamText and GenerateText sanitize invalid non-object inputs before calling this helper.
The function does not perform any I/O and never returns an error: tool output normalization happens earlier via ToolResult.ModelOutput and the existing provider.ToolResultOutput shape, populated during execution in StreamText by dispatching the per-tool Tool.ToModelOutput hook.
The returned slice contains zero, one, or two messages: an assistant message (if any assistant content was produced) and a tool message (if any tool-results or approval responses were produced), in that order.
Compared to upstream's signature, this function does not take a ToolSet: the Go port runs Tool.ToModelOutput eagerly during tool execution and stores the result on ToolResult.ModelOutput, so by the time content reaches this helper the conversion is already done. Public callers constructing parts from raw tool output can call Tool.ToModelOutput directly.
func WriteAgentUIStream ¶
func WriteAgentUIStream(w http.ResponseWriter, ctx context.Context, agent Agent, messages []UIMessage, opts ...UIMessageStreamOption) error
WriteAgentUIStream creates an Agent UI stream and writes it as SSE.
func WriteTextStream ¶
func WriteTextStream(w http.ResponseWriter, result *StreamTextResult) error
WriteTextStream writes the text deltas from a StreamTextResult to an HTTP response as a plain text stream (for useCompletion).
func WriteUIMessageStream ¶
func WriteUIMessageStream(w http.ResponseWriter, result *StreamTextResult, opts ...UIMessageStreamOption) error
WriteUIMessageStream is a shortcut that converts a StreamTextResult to a UIMessageChunk stream and pipes it to the HTTP response as SSE.
Types ¶
type Agent ¶
type Agent interface {
Version() AgentVersion
ID() string
Tools() ToolSet
Generate(ctx context.Context, opts ...AgentGenerateOption) (*GenerateTextResult, error)
Stream(ctx context.Context, opts ...AgentStreamOption) *StreamTextResult
}
Agent is a reusable LLM agent.
Implementations wrap autonomous orchestration behind Generate and Stream while returning the same result types as GenerateText and StreamText. ToolLoopAgent implements this interface by delegating to the existing StreamText engine.
type AgentGenerateOption ¶
type AgentGenerateOption interface {
// contains filtered or unexported methods
}
AgentGenerateOption configures an Agent Generate call.
func WithAgentGenerateOptions ¶
func WithAgentGenerateOptions(opts ...GenerateOption) AgentGenerateOption
WithAgentGenerateOptions applies GenerateText options to an Agent Generate call.
type AgentOption ¶
type AgentOption interface {
AgentStreamOption
AgentGenerateOption
}
AgentOption configures both Agent Stream and Agent Generate calls.
func WithAgentMessages ¶
func WithAgentMessages(messages ...UIMessage) AgentOption
WithAgentMessages sets UI messages for an Agent call.
func WithAgentModelMessages ¶
func WithAgentModelMessages(messages ...provider.Message) AgentOption
WithAgentModelMessages sets provider model messages for an Agent call.
func WithAgentOptions ¶
func WithAgentOptions(opts ...Option) AgentOption
WithAgentOptions applies shared StreamText/GenerateText options to an Agent call.
func WithAgentPrompt ¶
func WithAgentPrompt(prompt string) AgentOption
WithAgentPrompt sets a user text prompt for an Agent call.
func WithAgentRuntimeContext ¶
func WithAgentRuntimeContext(value any) AgentOption
WithAgentRuntimeContext sets per-call Agent runtime context.
type AgentStreamOption ¶
type AgentStreamOption interface {
// contains filtered or unexported methods
}
AgentStreamOption configures an Agent Stream call.
func WithAgentStreamOptions ¶
func WithAgentStreamOptions(opts ...StreamOption) AgentStreamOption
WithAgentStreamOptions applies StreamText options to an Agent Stream call.
type AgentVersion ¶
type AgentVersion string
AgentVersion identifies the version of the Agent interface implemented by an Agent.
const ( // AgentVersionV1 is the upstream-compatible Agent interface version. AgentVersionV1 AgentVersion = "agent-v1" )
type BoundedArrayOutput ¶
BoundedArrayOutput is implemented by an array Output that may limit its element count. MaxItems reports ok=false when no maximum is set. When it reports ok, StreamTextResult.ElementStream delivers at most n elements; a negative n is treated as zero.
type ChunkType ¶
type ChunkType string
ChunkType identifies the type of a UIMessageChunk SSE event.
const ( ChunkStart ChunkType = "start" ChunkFinish ChunkType = "finish" ChunkAbort ChunkType = "abort" ChunkStartStep ChunkType = "start-step" ChunkFinishStep ChunkType = "finish-step" ChunkMessageMetadata ChunkType = "message-metadata" ChunkTextStart ChunkType = "text-start" ChunkTextDelta ChunkType = "text-delta" ChunkTextEnd ChunkType = "text-end" ChunkReasoningStart ChunkType = "reasoning-start" ChunkReasoningDelta ChunkType = "reasoning-delta" ChunkReasoningEnd ChunkType = "reasoning-end" ChunkReasoningFile ChunkType = "reasoning-file" ChunkToolInputStart ChunkType = "tool-input-start" ChunkToolInputDelta ChunkType = "tool-input-delta" ChunkToolInputAvailable ChunkType = "tool-input-available" ChunkToolInputError ChunkType = "tool-input-error" ChunkToolApprovalRequest ChunkType = "tool-approval-request" ChunkToolApprovalResponse ChunkType = "tool-approval-response" ChunkToolOutputDenied ChunkType = "tool-output-denied" ChunkToolOutputAvailable ChunkType = "tool-output-available" ChunkToolOutputError ChunkType = "tool-output-error" ChunkSourceURL ChunkType = "source-url" ChunkSourceDocument ChunkType = "source-document" ChunkFile ChunkType = "file" ChunkData ChunkType = "data" ChunkCustom ChunkType = "custom" ChunkError ChunkType = "error" )
type ContentPart ¶
type ContentPart interface {
// contains filtered or unexported methods
}
ContentPart is the interface for structured content in a StepResult. NOT the same as UIMessage Part -- this is the model output side. Consumers type-switch on: TextContent, ReasoningContent, SourceContent, FileContent, ReasoningFileContent, CustomContent, ToolCallContent, ToolApprovalRequestContent, ToolApprovalResponseContent, ToolResultContent, ToolErrorContent.
type ConvertOption ¶
type ConvertOption interface {
// contains filtered or unexported methods
}
ConvertOption configures ConvertToModelMessages.
func WithConvertDataPart ¶
func WithConvertDataPart(fn func(DataPart) (*provider.ContentPart, error)) ConvertOption
WithConvertDataPart converts user and assistant data parts to text or file content. A nil result skips the data part; callback errors abort conversion.
func WithIgnoreIncompleteToolCalls ¶
func WithIgnoreIncompleteToolCalls() ConvertOption
WithIgnoreIncompleteToolCalls skips tool calls whose input is not complete when converting UI messages to model messages.
type CreateUIMessageStreamParams ¶
type CreateUIMessageStreamParams struct {
// Execute writes the whole stream through the supplied writer. It is required.
Execute func(writer *UIMessageStreamWriter) error
// OnError maps a stream failure to the text of the emitted error chunk. It
// receives the error Execute returns, ErrExecuteRequired when Execute is nil,
// and a panic recovered from Execute. That text reaches the client, so return
// err.Error() only when every one of those sources is safe to disclose. The
// default masks them all as "An error occurred." and discards the detail, so
// log it here when an operator needs it.
OnError func(error) string
// OriginalMessages is the prior conversation. It supplies the continuation
// message ID and the OnFinish history; it is not a persistence mode switch.
OriginalMessages []UIMessage
// OnFinish runs once the stream ends, whether or not OriginalMessages is set.
OnFinish func(UIMessageStreamOnFinishState)
// GenerateID mints the response message ID. It defaults to the package-level
// GenerateID and is called at most once per stream: a continued assistant
// message supplies its own ID instead, and GenerateID is not called.
GenerateID func() string
}
CreateUIMessageStreamParams configures CreateUIMessageStream.
type CustomContent ¶
type CustomContent struct {
Kind string `json:"kind"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
CustomContent carries provider-specific custom generated content.
type CustomPart ¶
type CustomPart struct {
Kind string `json:"kind"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
CustomPart carries provider-specific custom content in a UIMessage.
type DataPart ¶
type DataPart struct {
DataName string `json:"dataName"`
ID string `json:"id,omitempty"`
Data json.RawMessage `json:"data"`
}
DataPart carries custom data in a UIMessage. On the wire, it serializes as type "data-{DataName}".
type DynamicToolUIPart ¶
type DynamicToolUIPart struct {
InputEncoding provider.ToolInputEncoding `json:"inputEncoding,omitempty"`
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
State ToolInvocationState `json:"state"`
Title *string `json:"title,omitempty"`
ToolMetadata map[string]json.RawMessage `json:"toolMetadata,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
RawInput json.RawMessage `json:"rawInput,omitempty"`
Output json.RawMessage `json:"output,omitempty"`
ErrorText *string `json:"errorText,omitempty"`
Preliminary *bool `json:"preliminary,omitempty"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
Approval *ToolApproval `json:"approval,omitempty"`
CallProviderMetadata provider.ProviderMetadata `json:"callProviderMetadata,omitzero"`
ResultProviderMetadata provider.ProviderMetadata `json:"resultProviderMetadata,omitzero"`
// contains filtered or unexported fields
}
DynamicToolUIPart carries a dynamic/MCP tool invocation in a UIMessage. Same shape and field-presence contracts as ToolInvocationPart, but with type "dynamic-tool" on the wire. Parts normalized from a static tool whose definition is unavailable or incompatible persist "dynamic": false, so model conversion keeps omitting their output while the tool remains unavailable.
func (DynamicToolUIPart) MarshalJSON ¶
func (p DynamicToolUIPart) MarshalJSON() ([]byte, error)
func (DynamicToolUIPart) PartType ¶
func (DynamicToolUIPart) PartType() string
PartType implements Part.
func (*DynamicToolUIPart) UnmarshalJSON ¶
func (p *DynamicToolUIPart) UnmarshalJSON(data []byte) error
type FileContent ¶
type FileContent struct {
File GeneratedFile `json:"file"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
FileContent represents a generated file.
type FilePart ¶
type FilePart struct {
MediaType string `json:"mediaType"`
URL string `json:"url"`
Filename *string `json:"filename,omitempty"`
ProviderReference map[string]string `json:"providerReference,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitzero"`
}
FilePart carries file data in a UIMessage. ProviderReference maps provider names to provider-specific file IDs and, when present, takes precedence over URL during conversion to model messages.
func (FilePart) MarshalJSON ¶
type GenerateOption ¶
type GenerateOption interface {
// contains filtered or unexported methods
}
GenerateOption configures a GenerateText call.
type GenerateTextResult ¶
type GenerateTextResult struct {
Text string
Reasoning []ReasoningOutput
ToolCalls []ToolCall
ToolResults []ToolResult
Files []GeneratedFile
Sources []Source
FinishReason provider.FinishReason
Usage provider.Usage
TotalUsage provider.Usage
Steps []StepResult
Warnings []provider.Warning
Content []ContentPart
Response ResponseMetadata
ResponseMessages []provider.Message
ProviderMetadata provider.ProviderMetadata
Output any
OutputError error
}
GenerateTextResult holds the complete result of a non-streaming LLM call. Text, Reasoning, FinishReason, Response and ProviderMetadata describe the final step. Content, ToolCalls, ToolResults, Files, Sources and Warnings collect every step in order. ResponseMessages holds the full generated message history, including approval-generated tool messages produced before the first model call.
func GenerateText ¶
func GenerateText(ctx context.Context, model provider.LanguageModel, opts ...GenerateOption) (*GenerateTextResult, error)
GenerateText performs a non-streaming LLM call. It runs StreamText internally and blocks until the stream completes, returning a populated result or the first error encountered. Unlike StreamText, an approval continuation also adds execution-denied results for denied provider-executed tool calls, carrying the approval ID in the OpenAI provider options so the provider can correlate them.
type GeneratedFile ¶
type GeneratedFile struct {
Data []byte `json:"-"`
Base64 string `json:"-"`
MediaType string `json:"mediaType"`
}
GeneratedFile represents a file generated by the model.
func (GeneratedFile) DataURL ¶
func (f GeneratedFile) DataURL() string
type IDGeneratorOptions ¶
IDGeneratorOptions configures CreateIDGenerator.
type InvalidToolApprovalError ¶
type InvalidToolApprovalError struct {
// ApprovalID identifies the approval response that triggered the error.
ApprovalID string
// Reason is non-empty when the response is structurally invalid (for
// example, missing `approved`) and empty when the approval ID has no
// matching prior assistant request.
Reason string
}
InvalidToolApprovalError is returned when a tool-approval-response cannot be correlated with a prior assistant approval request, or when the response itself is structurally invalid (for example, missing the required `approved` field).
Mirrors upstream's `InvalidToolApprovalError` from the Vercel AI SDK so callers can type-assert via errors.As and inspect InvalidToolApprovalError.ApprovalID.
func (*InvalidToolApprovalError) Error ¶
func (e *InvalidToolApprovalError) Error() string
type InvalidToolApprovalSignatureError ¶
InvalidToolApprovalSignatureError is returned when a signed tool approval request is replayed without a valid signature.
func (*InvalidToolApprovalSignatureError) Error ¶
func (e *InvalidToolApprovalSignatureError) Error() string
type MissingToolResultsError ¶
type MissingToolResultsError struct {
// ToolCallIDs identifies every unresolved tool call in prompt order.
ToolCallIDs []string
}
MissingToolResultsError is returned when a prompt contains non-provider-executed tool calls that have no corresponding tool results or approval responses.
func (*MissingToolResultsError) Error ¶
func (e *MissingToolResultsError) Error() string
type OnAbortState ¶
type OnAbortState struct {
Steps []StepResult
}
OnAbortState is passed to the OnAbort callback when the stream is cancelled.
type OnChunkState ¶
type OnChunkState struct {
Chunk TextStreamPart
}
OnChunkState is passed to the OnChunk callback.
type OnFinishState ¶
type OnFinishState struct {
StepResult
Steps []StepResult
TotalUsage provider.Usage
ResponseMessages []provider.Message
}
OnFinishState is passed to the OnFinish callback after all steps complete. The embedded StepResult follows the collected result projection: Content, ToolCalls, ToolResults, Files, Sources and Warnings cover every step in order, Usage is the total usage, and the remaining fields describe the final step. ResponseMessages holds the full generated message history.
type OnStepFinishState ¶
type OnStepFinishState struct {
StepResult
}
OnStepFinishState is passed to the OnStepFinish callback.
type OnStepStartState ¶
OnStepStartState is passed to the OnStepStart callback.
type OnToolCallFinishState ¶
type OnToolCallFinishState struct {
StepNumber int
Model StepModel
ToolCall ToolCall
Messages []provider.Message
DurationMs int64
Success bool
Output json.RawMessage
Error error
}
OnToolCallFinishState is passed to the OnToolCallFinish callback. Either Output+Success=true or Error+Success=false.
type OnToolCallStartState ¶
type OnToolCallStartState struct {
StepNumber int
Model StepModel
ToolCall ToolCall
Messages []provider.Message
}
OnToolCallStartState is passed to the OnToolCallStart callback.
type Option ¶
type Option interface {
StreamOption
GenerateOption
}
Option is an option that applies to both StreamText and GenerateText.
func OnFinish ¶
func OnFinish(fn func(OnFinishState)) Option
OnFinish sets a callback invoked once after the final completed step is recorded. It is not invoked when the context is cancelled; use OnAbort instead.
func OnStart ¶
func OnStart(fn func(OnStartState)) Option
OnStart sets a callback invoked when the stream starts.
func OnStepEnd ¶
func OnStepEnd(fn func(OnStepFinishState)) Option
OnStepEnd sets a callback invoked when a step completes.
func OnStepFinish ¶
func OnStepFinish(fn func(OnStepFinishState)) Option
OnStepFinish sets a callback invoked when a step completes.
func OnStepStart ¶
func OnStepStart(fn func(OnStepStartState)) Option
OnStepStart sets a callback invoked at the start of each step.
func OnToolCallFinish ¶
func OnToolCallFinish(fn func(OnToolCallFinishState)) Option
OnToolCallFinish sets a callback invoked after a tool finishes execution.
func OnToolCallStart ¶
func OnToolCallStart(fn func(OnToolCallStartState)) Option
OnToolCallStart sets a callback invoked before a tool is executed.
func WithActiveTools ¶
WithActiveTools filters which tools are active for a call.
func WithFrequencyPenalty ¶
WithFrequencyPenalty sets the frequency penalty.
func WithGenerateID ¶
WithGenerateID sets the ID generator used by orchestration-created IDs.
func WithHeaders ¶
WithHeaders sets additional request headers.
func WithInstructions ¶
WithInstructions sets a simple text instruction prompt.
func WithMaxOutputTokens ¶
WithMaxOutputTokens sets the maximum number of output tokens.
func WithMaxRetries ¶
WithMaxRetries sets the maximum number of retry attempts for transient errors. Default is 2 (up to 3 total attempts). Set to 0 to disable retry.
func WithMessages ¶
WithMessages sets the UI messages for the conversation.
func WithModelMessages ¶
WithModelMessages sets provider messages directly, bypassing UI message conversion.
func WithPrepareStep ¶
func WithPrepareStep(fn PrepareStepFunc) Option
WithPrepareStep sets a per-step preparation callback.
func WithPresencePenalty ¶
WithPresencePenalty sets the presence penalty.
func WithProviderOptions ¶
func WithProviderOptions(opts ...provider.ProviderOption) Option
WithProviderOptions sets provider-specific options from typed values. Each value's ProviderKey() determines its map key; last value wins per key.
func WithReasoning ¶
func WithReasoning(level provider.ReasoningEffort) Option
WithReasoning sets the reasoning effort level for the model.
func WithRepairText ¶
func WithRepairText(fn RepairTextFunc) Option
WithRepairText configures one optional repair attempt for invalid complete structured output. It has no effect without WithOutput. Repair runs only when ParseComplete returns both ErrNoObjectGenerated and ErrInvalidOutputText; custom Output implementations must wrap both to enable repair. The callback runs synchronously at final parsing and does not alter the raw model response.
func WithResponseFormat ¶
func WithResponseFormat(f provider.ResponseFormat) Option
WithResponseFormat sets the response format.
func WithStopSequences ¶
WithStopSequences sets the stop sequences.
func WithStopWhen ¶
func WithStopWhen(conditions ...StopCondition) Option
WithStopWhen sets stop conditions for the multi-step loop.
func WithSystemMessages ¶
func WithSystemMessages(msgs ...SystemModelMessage) Option
WithSystemMessages sets multiple system prompt segments.
func WithTemperature ¶
WithTemperature sets the sampling temperature.
func WithTimeout ¶
func WithTimeout(cfg TimeoutConfig) Option
WithTimeout sets the timeout configuration for the operation.
func WithToolApproval ¶
func WithToolApproval(policy ToolApprovalPolicyConfig) Option
WithToolApproval sets call-level tool approval policy. It takes precedence over per-tool NeedsApproval configuration. If called more than once, the latest generic or per-tool policy replaces the previous one.
func WithToolApprovalSecret ¶
WithToolApprovalSecret sets the secret used to sign and verify tool approval requests. Only approvals for locally executed tools are signed and verified; approvals for provider-executed tools are unsigned and passed to the provider unchecked, as upstream does.
func WithToolApprovalSecretBytes ¶
WithToolApprovalSecretBytes sets the byte secret used to sign and verify tool approval requests. Only approvals for locally executed tools are signed and verified; approvals for provider-executed tools are unsigned and passed to the provider unchecked, as upstream does.
func WithToolChoice ¶
func WithToolChoice(tc provider.ToolChoice) Option
WithToolChoice sets the tool choice strategy.
func WithToolRoutes ¶
func WithToolRoutes(routes ToolRoutes) Option
WithToolRoutes configures how each named tool is exposed to the model and caller tools. An unlisted tool is unchanged; a zero-value route hides it from the model while keeping it available for execution.
type Output ¶
type Output interface {
// ResponseFormat returns the provider response format configuration
// to be sent with the LLM request.
ResponseFormat() *provider.ResponseFormat
// ParseComplete validates and parses the complete LLM response text.
// Returns the parsed value (type depends on the Output mode) or an error
// if the response is invalid.
ParseComplete(text string) (any, error)
// ParsePartial attempts a best-effort parse of incomplete JSON text
// during streaming. Returns the partial value and true if parsing
// succeeded, or (nil, false) if the text is not yet parseable.
ParsePartial(text string) (any, bool)
}
Output defines a structured output specification that controls how LLM responses are formatted, parsed, and validated.
Implementations are provided by the output package: Object[T], Array[T], Choice, JSON, and Text. Array also implements BoundedArrayOutput.
type Part ¶
type Part interface {
PartType() string
}
Part is the interface for all UIMessage part types. Consumers type-switch on concrete types: TextPart, ReasoningPart, ToolInvocationPart, DynamicToolUIPart, FilePart, ReasoningFilePart, SourceURLPart, SourceDocumentPart, DataPart, CustomPart, StepStartPart.
type PrepareStepFunc ¶
type PrepareStepFunc func(PrepareStepState) (*PrepareStepResult, error)
PrepareStepFunc is a callback that customizes each step before the provider call.
type PrepareStepResult ¶
type PrepareStepResult struct {
Model provider.LanguageModel
System []SystemModelMessage
ToolChoice *provider.ToolChoice
ActiveTools []string
Messages []provider.Message
ProviderOptions provider.ProviderOptions
Context any
MaxOutputTokens *int
Temperature *float64
TopP *float64
TopK *int
PresencePenalty *float64
FrequencyPenalty *float64
StopSequences []string
Seed *int
Reasoning *provider.ReasoningEffort
}
PrepareStepResult contains per-step overrides from PrepareStep.
type PrepareStepState ¶
type PrepareStepState struct {
Steps []StepResult
StepNumber int
Model provider.LanguageModel
// Messages contains the provider messages for the current step. PrepareStep
// message overrides carry forward to later steps.
Messages []provider.Message
// InitialMessages contains the original input messages before configured
// system messages and approval-generated tool results are added.
InitialMessages []provider.Message
// ResponseMessages contains response messages accumulated before the current
// step, including approval-generated tool results from the initial input.
ResponseMessages []provider.Message
// Context contains the effective runtime context for the current step.
Context any
}
PrepareStepState is passed to the PrepareStep callback.
type ReasoningContent ¶
type ReasoningContent struct {
Text string `json:"text"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
ReasoningContent represents generated reasoning text.
type ReasoningFileContent ¶
type ReasoningFileContent struct {
File GeneratedFile `json:"file"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
ReasoningFileContent represents a file generated as part of model reasoning.
type ReasoningFileOutput ¶
type ReasoningFileOutput struct {
File GeneratedFile `json:"file"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
ReasoningFileOutput represents a file generated as model reasoning.
type ReasoningFilePart ¶
type ReasoningFilePart struct {
MediaType string `json:"mediaType"`
URL string `json:"url"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitzero"`
}
ReasoningFilePart carries a file generated as part of model reasoning.
func (ReasoningFilePart) PartType ¶
func (ReasoningFilePart) PartType() string
PartType implements Part.
type ReasoningOutput ¶
type ReasoningOutput interface {
// contains filtered or unexported methods
}
ReasoningOutput is a text or file artifact generated as model reasoning.
type ReasoningPart ¶
type ReasoningPart struct {
ID string `json:"id,omitempty"`
Text string `json:"text"`
State string `json:"state,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitzero"`
}
ReasoningPart carries model reasoning in a UIMessage.
type ReasoningTextOutput ¶
type ReasoningTextOutput struct {
Text string `json:"text"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
ReasoningTextOutput represents generated reasoning text.
type RepairTextFunc ¶
RepairTextFunc receives the original generated text and complete parse error. Return accepted=false to keep the original error, or accepted=true to validate the returned text once. A callback error takes precedence over acceptance.
type ResponseMetadata ¶
type ResponseMetadata struct {
provider.ResponseMetadata
Headers map[string]string `json:"headers,omitempty"`
Messages []provider.Message `json:"-"`
}
ResponseMetadata carries metadata about the provider response.
Messages holds the assistant + tool messages produced from this step's content via ToResponseMessages. It mirrors upstream's `result.response.messages` semantics — the next-call message tail that consumers can append to their prompt to continue the conversation. The field is in-process only (json:"-") and is not transported on any wire.
type RetryError ¶
type RetryError struct {
Reason RetryErrorReason
Errors []error
}
RetryError is returned when all retry attempts have been exhausted or a non-retryable error is encountered after retries have already started. It carries every error from each attempt and the reason retries stopped.
func (*RetryError) Error ¶
func (e *RetryError) Error() string
func (*RetryError) LastError ¶
func (e *RetryError) LastError() error
func (*RetryError) Unwrap ¶
func (e *RetryError) Unwrap() error
type RetryErrorReason ¶
type RetryErrorReason string
RetryErrorReason describes why retry stopped.
const ( RetryMaxRetriesExceeded RetryErrorReason = "maxRetriesExceeded" RetryErrorNotRetryable RetryErrorReason = "errorNotRetryable" )
type Role ¶
Role is an alias for provider.Role, used on UIMessage. UIMessages use system, user, and assistant roles.
type SingleToolApprovalFunc ¶
type SingleToolApprovalFunc func(input json.RawMessage, opts ToolExecutionOptions) (ToolApprovalDecision, error)
SingleToolApprovalFunc decides approval policy for a specific tool.
type Source ¶
type Source struct {
SourceType provider.SourceType `json:"sourceType"`
ID string `json:"id,omitempty"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
MediaType string `json:"mediaType,omitempty"`
Filename string `json:"filename,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
Source represents a reference source (URL or document) in the generated output.
type SourceContent ¶
type SourceContent struct {
Source Source `json:"source"`
}
SourceContent represents a reference source.
type SourceDocumentPart ¶
type SourceDocumentPart struct {
SourceID string `json:"sourceId"`
MediaType string `json:"mediaType"`
Title string `json:"title"`
Filename string `json:"filename,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitzero"`
}
SourceDocumentPart carries a document source reference in a UIMessage.
func (SourceDocumentPart) PartType ¶
func (SourceDocumentPart) PartType() string
PartType implements Part.
type SourceURLPart ¶
type SourceURLPart struct {
SourceID string `json:"sourceId"`
URL string `json:"url"`
Title string `json:"title,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitzero"`
}
SourceURLPart carries a URL source reference in a UIMessage.
type StepResult ¶
type StepResult struct {
StepNumber int `json:"stepNumber"`
StepType StepType `json:"stepType"`
Model StepModel `json:"model"`
Text string `json:"text"`
ReasoningText string `json:"reasoningText,omitempty"`
Reasoning []ReasoningOutput `json:"reasoning,omitempty"`
Content []ContentPart `json:"-"`
ToolCalls []ToolCall `json:"toolCalls,omitempty"`
ToolApprovalRequests []ToolApprovalRequest `json:"toolApprovalRequests,omitempty"`
ToolApprovalResponses []ToolApprovalResponse `json:"toolApprovalResponses,omitempty"`
ToolResults []ToolResult `json:"toolResults,omitempty"`
Files []GeneratedFile `json:"files,omitempty"`
Sources []Source `json:"sources,omitempty"`
FinishReason provider.FinishReason `json:"finishReason"`
IsContinued bool `json:"isContinued,omitempty"`
Usage provider.Usage `json:"usage"`
Warnings []provider.Warning `json:"warnings,omitempty"`
Request provider.RequestMetadata `json:"request,omitempty"`
Response ResponseMetadata `json:"response,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
// contains filtered or unexported fields
}
StepResult contains per-step data from the StreamText orchestration loop.
type StepStartPart ¶
type StepStartPart struct{}
StepStartPart marks the beginning of a new step in a UIMessage.
type StopCondition ¶
type StopCondition func(state StopConditionState) bool
StopCondition is a function that determines whether the step loop should stop.
func HasToolCall ¶
func HasToolCall(toolNames ...string) StopCondition
HasToolCall returns a StopCondition that stops when the most recent step called any of the named tools. Calls in earlier steps do not count, and with no names it never stops.
func StepCountIs ¶
func StepCountIs(n int) StopCondition
StepCountIs returns a StopCondition that stops after n steps.
type StopConditionState ¶
type StopConditionState struct {
Steps []StepResult
}
StopConditionState is passed to stop condition functions.
type StreamAbort ¶
type StreamAbort struct {
Reason string
}
StreamAbort signals that the stream was cancelled.
type StreamCustom ¶
type StreamCustom struct {
Kind string
ProviderMetadata provider.ProviderMetadata
}
StreamCustom carries provider-specific custom content.
type StreamError ¶
type StreamError struct {
Error error
}
StreamError carries an error from the provider or orchestration.
type StreamFile ¶
type StreamFile struct {
File GeneratedFile
ProviderMetadata provider.ProviderMetadata
}
StreamFile carries a file generated by the model.
type StreamFinish ¶
type StreamFinish struct {
FinishReason provider.FinishReason
TotalUsage *provider.Usage
}
StreamFinish signals the end of the entire StreamText orchestration.
type StreamFinishStep ¶
type StreamFinishStep struct {
Response *provider.ResponseMetadata
Usage *provider.Usage
FinishReason provider.FinishReason
ProviderMetadata provider.ProviderMetadata
}
StreamFinishStep signals the end of a step with usage and metadata.
type StreamOption ¶
type StreamOption interface {
// contains filtered or unexported methods
}
StreamOption configures a StreamText call.
func OnAbort ¶
func OnAbort(fn func(OnAbortState)) StreamOption
OnAbort sets a callback invoked when the stream is cancelled via context. Only available for StreamText.
func OnChunk ¶
func OnChunk(fn func(OnChunkState)) StreamOption
OnChunk sets a callback invoked for each streaming chunk. Only available for StreamText.
func WithIncludeRawChunks ¶
func WithIncludeRawChunks() StreamOption
WithIncludeRawChunks enables raw provider chunks in the stream. Only available for StreamText.
type StreamRaw ¶
type StreamRaw struct {
RawValue json.RawMessage
}
StreamRaw carries unprocessed provider data (when IncludeRawChunks is set).
type StreamReasoningDelta ¶
type StreamReasoningDelta struct {
ID string
Text string
ProviderMetadata provider.ProviderMetadata
}
StreamReasoningDelta carries incremental reasoning within a block.
type StreamReasoningEnd ¶
type StreamReasoningEnd struct {
ID string
ProviderMetadata provider.ProviderMetadata
}
StreamReasoningEnd closes a reasoning block.
type StreamReasoningFile ¶
type StreamReasoningFile struct {
File GeneratedFile
ProviderMetadata provider.ProviderMetadata
}
StreamReasoningFile carries a file generated as part of model reasoning.
type StreamReasoningStart ¶
type StreamReasoningStart struct {
ID string
ProviderMetadata provider.ProviderMetadata
}
StreamReasoningStart opens a reasoning block.
type StreamSource ¶
type StreamSource struct {
Source Source
}
StreamSource carries a reference source (URL or document).
type StreamStart ¶
type StreamStart struct{}
StreamStart signals the beginning of a StreamText orchestration.
type StreamStartStep ¶
type StreamStartStep struct {
Warnings []provider.Warning
Request *provider.RequestMetadata
}
StreamStartStep signals the beginning of a new step in the orchestration loop.
type StreamTextDelta ¶
type StreamTextDelta struct {
ID string
Text string
ProviderMetadata provider.ProviderMetadata
}
StreamTextDelta carries incremental text within a block.
type StreamTextEnd ¶
type StreamTextEnd struct {
Citations []provider.Citation
ID string
ProviderMetadata provider.ProviderMetadata
}
StreamTextEnd closes a text block.
type StreamTextResult ¶
type StreamTextResult struct {
// contains filtered or unexported fields
}
StreamTextResult holds the result of a StreamText call. It provides both a streaming interface (FullStream) and blocking accessors that resolve after the stream completes.
func StreamText ¶
func StreamText(ctx context.Context, model provider.LanguageModel, opts ...StreamOption) *StreamTextResult
StreamText starts an LLM streaming call with multi-step tool execution. It returns immediately; consume events via FullStream() or convert to SSE via ToUIMessageStream(). Call Wait() or use blocking accessors to wait for completion.
func (*StreamTextResult) AggregateUsage ¶
func (r *StreamTextResult) AggregateUsage() provider.Usage
AggregateUsage returns the aggregate token usage across all steps. Blocks until the stream completes.
func (*StreamTextResult) Content ¶
func (r *StreamTextResult) Content() []ContentPart
Content returns the structured content from all recorded steps in step order. The returned slice is newly allocated. Blocks until the stream completes.
func (*StreamTextResult) ElementStream ¶
func (r *StreamTextResult) ElementStream() <-chan json.RawMessage
ElementStream returns a channel of complete validated array elements during streaming. Only produces values when the Output is in array mode. Elements are delivered exactly once and in order. The count carries over between steps: a later step delivers only the elements of its array past the number already delivered, as upstream does. The channel is closed after the stream finishes and all elements are delivered. When the Output reports a maximum through BoundedArrayOutput, the channel closes as soon as the model produces an element past it, in any step, and ElementStreamError reports why.
func (*StreamTextResult) ElementStreamError ¶
func (r *StreamTextResult) ElementStreamError() error
ElementStreamError reports why ElementStream closed: an error wrapping ErrInvalidOutputText when the model produced more elements than the maximum, or nil after a normal close. It blocks until the element stream closes, which happens at the overflow or when the stream finishes. Like ElementStream, it needs a concurrent FullStream consumer. The final output is validated separately and reported by OutputError.
func (*StreamTextResult) Err ¶
func (r *StreamTextResult) Err() error
Err returns the first error encountered during streaming, or nil. Blocks until the stream completes.
func (*StreamTextResult) Files ¶
func (r *StreamTextResult) Files() []GeneratedFile
Files returns the generated files from all recorded steps in step order. The returned slice is newly allocated. Blocks until the stream completes.
func (*StreamTextResult) FinishReason ¶
func (r *StreamTextResult) FinishReason() provider.FinishReason
FinishReason returns the finish reason from the last step. Blocks until the stream completes.
func (*StreamTextResult) FullStream ¶
func (r *StreamTextResult) FullStream() <-chan TextStreamPart
FullStream returns a channel of TextStreamPart events. The channel is closed when the stream completes. Only one consumer may read the stream; a second call to FullStream or ToUIMessageStream returns a closed (empty) channel.
func (*StreamTextResult) OutputError ¶
func (r *StreamTextResult) OutputError() error
OutputError returns the structured output validation error, or nil if validation succeeded or no Output was specified. Blocks until the stream completes.
func (*StreamTextResult) OutputValue ¶
func (r *StreamTextResult) OutputValue() any
OutputValue returns the parsed structured output value, or nil if no Output was specified or parsing failed. Blocks until the stream completes.
func (*StreamTextResult) PartialOutputStream ¶
func (r *StreamTextResult) PartialOutputStream() <-chan json.RawMessage
PartialOutputStream returns a channel of partial JSON snapshots during streaming. Each emission is a json.RawMessage representing the partial parse of the accumulated text so far. Emissions are delivered exactly once and in order. The channel is closed after the stream finishes and all emissions are delivered. If no Output is set, returns a closed channel.
func (*StreamTextResult) ProviderMetadata ¶
func (r *StreamTextResult) ProviderMetadata() provider.ProviderMetadata
ProviderMetadata returns the provider metadata from the last step. Blocks until the stream completes.
func (*StreamTextResult) Reasoning ¶
func (r *StreamTextResult) Reasoning() []ReasoningOutput
Reasoning returns the reasoning output from the last step. Blocks until the stream completes.
func (*StreamTextResult) Response ¶
func (r *StreamTextResult) Response() ResponseMetadata
Response returns the response metadata from the last step. Blocks until the stream completes.
func (*StreamTextResult) ResponseMessages ¶
func (r *StreamTextResult) ResponseMessages() []provider.Message
ResponseMessages returns the full generated message history: tool messages produced by resolving approval responses before the first model call, followed by every recorded step's Response.Messages in step order. Unlike Response().Messages, which holds only the last step's messages, the result can be appended to the input messages to continue the conversation. The returned slice is newly allocated. Blocks until the stream completes.
func (*StreamTextResult) Sources ¶
func (r *StreamTextResult) Sources() []Source
Sources returns the sources from all recorded steps in step order. The returned slice is newly allocated. Blocks until the stream completes.
func (*StreamTextResult) Steps ¶
func (r *StreamTextResult) Steps() []StepResult
Steps returns all step results. Blocks until the stream completes.
func (*StreamTextResult) Stream ¶
func (r *StreamTextResult) Stream() <-chan TextStreamPart
Stream returns a channel of TextStreamPart events.
func (*StreamTextResult) Text ¶
func (r *StreamTextResult) Text() string
Text returns the generated text from the last step. Blocks until the stream completes.
func (*StreamTextResult) ToUIMessageStream ¶
func (r *StreamTextResult) ToUIMessageStream(opts ...UIMessageStreamOption) <-chan UIMessageChunk
ToUIMessageStream converts the internal event stream to UIMessageChunk events suitable for SSE output to @ai-sdk/react hooks.
func (*StreamTextResult) ToolCalls ¶
func (r *StreamTextResult) ToolCalls() []ToolCall
ToolCalls returns the tool calls from all recorded steps in step order. The returned slice is newly allocated. Blocks until the stream completes.
func (*StreamTextResult) ToolResults ¶
func (r *StreamTextResult) ToolResults() []ToolResult
ToolResults returns the tool results from all recorded steps in step order. The returned slice is newly allocated. Blocks until the stream completes.
func (*StreamTextResult) TotalUsage ¶
func (r *StreamTextResult) TotalUsage() provider.Usage
TotalUsage returns the aggregate token usage across all steps. Blocks until the stream completes.
func (*StreamTextResult) Usage ¶
func (r *StreamTextResult) Usage() provider.Usage
Usage returns the aggregate token usage across all steps. Blocks until the stream completes.
func (*StreamTextResult) Wait ¶
func (r *StreamTextResult) Wait()
Wait blocks until the stream completes.
func (*StreamTextResult) Warnings ¶
func (r *StreamTextResult) Warnings() []provider.Warning
Warnings returns all warnings accumulated across steps. Blocks until the stream completes.
type StreamTextStart ¶
type StreamTextStart struct {
ID string
ProviderMetadata provider.ProviderMetadata
}
StreamTextStart opens a text block.
type StreamToolApprovalRequest ¶
type StreamToolApprovalRequest struct {
ApprovalID string
ToolCallID string
ToolName string
Input json.RawMessage
Signature string
ProviderExecuted bool
Dynamic *bool
Title string
IsAutomatic bool
ProviderMetadata provider.ProviderMetadata
}
StreamToolApprovalRequest carries a request for user approval before tool execution.
type StreamToolApprovalResponse ¶
type StreamToolApprovalResponse struct {
ApprovalID string
ToolCallID string
ToolName string
Approved bool
Reason string
ProviderExecuted bool
Dynamic *bool
Title string
ProviderMetadata provider.ProviderMetadata
}
StreamToolApprovalResponse carries a user approval or denial decision.
type StreamToolCall ¶
type StreamToolCall struct {
ToolCallID string
ToolName string
Input json.RawMessage
Invalid bool
Error error
ProviderExecuted bool
Dynamic *bool
Title string
ProviderMetadata provider.ProviderMetadata
}
StreamToolCall carries a complete tool call (input parsed from string).
type StreamToolError ¶
type StreamToolError struct {
ToolCallID string
ToolName string
Input json.RawMessage
Error error
ProviderExecuted bool
Dynamic *bool
Title string
ProviderMetadata provider.ProviderMetadata
}
StreamToolError carries a tool execution failure.
type StreamToolInputDelta ¶
type StreamToolInputDelta struct {
ID string
Delta string
ProviderMetadata provider.ProviderMetadata
}
StreamToolInputDelta carries incremental tool arguments.
type StreamToolInputEnd ¶
type StreamToolInputEnd struct {
ID string
ProviderMetadata provider.ProviderMetadata
}
StreamToolInputEnd closes tool argument streaming.
type StreamToolInputStart ¶
type StreamToolInputStart struct {
InputEncoding provider.ToolInputEncoding
ID string
ToolName string
ProviderExecuted bool
Dynamic *bool
Title string
ProviderMetadata provider.ProviderMetadata
}
StreamToolInputStart opens tool argument streaming.
type StreamToolOutputDenied ¶
StreamToolOutputDenied carries a denied tool execution marker.
type StreamToolResult ¶
type StreamToolResult struct {
ToolCallID string
ToolName string
Input json.RawMessage
Output json.RawMessage
IsError bool
ProviderExecuted bool
Dynamic *bool
Preliminary bool
Title string
ProviderMetadata provider.ProviderMetadata
}
StreamToolResult carries a tool execution result (local or provider-executed).
type SystemModelMessage ¶
type SystemModelMessage struct {
Content string `json:"content"`
ProviderOptions provider.ProviderOptions `json:"providerOptions,omitempty"`
}
SystemModelMessage represents a segment of the system prompt.
type TextContent ¶
type TextContent struct {
Citations []provider.Citation `json:"citations,omitzero"`
Text string `json:"text"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
TextContent represents generated text content.
type TextPart ¶
type TextPart struct {
Citations []provider.Citation `json:"citations,omitzero"`
Text string `json:"text"`
State string `json:"state,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitzero"`
}
TextPart carries text content in a UIMessage.
type TextStreamPart ¶
type TextStreamPart interface {
// contains filtered or unexported methods
}
TextStreamPart is the interface for all orchestration-level stream events. StreamText emits these on FullStream(). Consumers type-switch to handle specific event types.
This is the middle layer between provider.StreamPart (raw provider events) and UIMessageChunk (SSE wire format).
type TimeoutConfig ¶
type TimeoutConfig struct {
Total time.Duration
Step time.Duration
FirstChunk time.Duration
Chunk time.Duration
}
TimeoutConfig configures timeout levels for StreamText and GenerateText. All fields default to zero (disabled).
type Tool ¶
type Tool struct {
Type UserToolType // "" or UserToolFunction for user-defined tools, UserToolProvider for provider tools
ID string // provider tool identifier (e.g. "anthropic.web_search_20250305"), only for provider tools
Args map[string]json.RawMessage // provider-specific tool configuration, only for provider tools
Description string
// DescriptionFunc overrides Description for the effective step runtime context,
// including an empty result. It must be safe for concurrent calls.
DescriptionFunc ToolDescriptionFunc
// DeferLoading excludes the tool from new step calls until ToolSearch discovers it.
// Discovery lasts only for the current generation and takes effect on the next step.
DeferLoading bool
Title string
InputSchema schema.Schema
OutputSchema schema.Schema
InputExamples []json.RawMessage
Strict *bool
ProviderOptions provider.ProviderOptions
Execute ToolExecuteFunc
ExecuteStream ToolExecuteStreamFunc
Caller *ToolCaller
NeedsApproval *ToolApprovalConfig
ValidateInput func(input json.RawMessage) error
ToModelOutput func(ToolOutputContext) (*provider.ToolResultOutput, error)
OnInputStart func(ToolExecutionOptions)
OnInputDelta func(inputTextDelta string, opts ToolExecutionOptions)
OnInputAvailable func(input json.RawMessage, opts ToolExecutionOptions)
// contains filtered or unexported fields
}
Tool defines a tool that a language model can call.
For function tools (Type "" or UserToolFunction), the tool is defined by the user with InputSchema, Execute, etc.
For provider tools (Type UserToolProvider), the tool's schema and behavior are defined by the provider. Set ID to the provider tool identifier (e.g. "anthropic.web_search_20250305") and Args for tool-specific config. Callbacks (OnInputStart, OnInputAvailable, etc.) are still supported.
Execute is optional: nil means tool calls are returned to the caller without execution (external/remote tool pattern).
func ToolSearch ¶
func ToolSearch() Tool
ToolSearch returns a core function tool that discovers explicitly deferred tools. Matches become available on the next model step within the same generation. It must be registered in a ToolSet; its original executor is not bound to a registry.
func TypedTool ¶
func TypedTool[I, O any](def TypedToolDef[I, O]) (tool Tool, err error)
TypedTool constructs a Tool from a typed definition. The input JSON Schema is derived from type I via schema.SchemaFor[I]() at construction time. The returned Tool.Execute wraps the typed execute function with automatic JSON unmarshal of input and marshal of output.
type ToolApproval ¶
type ToolApproval struct {
ID string `json:"id,omitempty"`
Approved *bool `json:"approved,omitempty"`
// Descriptor retains opaque approval request data, including JSON null.
Descriptor json.RawMessage `json:"descriptor,omitempty"`
// RequestReason explains the request; nil is absent and an empty string is present.
RequestReason *string `json:"requestReason,omitempty"`
// Reason explains the decision; nil differs from an explicitly empty reason.
Reason *string `json:"reason,omitempty"`
IsAutomatic bool `json:"isAutomatic,omitempty"`
Signature string `json:"signature,omitempty"`
}
ToolApproval carries approval status for a tool invocation. Mirrors the upstream `approval` object on `ToolUIPart` (see Vercel AI SDK `ui-messages.ts`), where ID identifies the approval request and Approved is unset while a request is pending and set true/false once the user responds.
func (*ToolApproval) UnmarshalJSON ¶
func (p *ToolApproval) UnmarshalJSON(data []byte) error
type ToolApprovalConfig ¶
type ToolApprovalConfig struct {
Required bool
Check ToolNeedsApprovalFunc
}
ToolApprovalConfig configures whether a tool invocation requires approval.
func ApprovalIf ¶
func ApprovalIf(fn ToolNeedsApprovalFunc) *ToolApprovalConfig
ApprovalIf returns a dynamic approval configuration evaluated per tool call.
func ApprovalRequired ¶
func ApprovalRequired() *ToolApprovalConfig
ApprovalRequired returns a static approval configuration that always requires approval.
type ToolApprovalDecision ¶
type ToolApprovalDecision struct {
Status ToolApprovalStatus
Reason string
}
ToolApprovalDecision is the normalized approval policy result.
type ToolApprovalFunc ¶
type ToolApprovalFunc func(ToolApprovalOptions) (ToolApprovalDecision, error)
ToolApprovalFunc decides approval policy for any tool call in a request.
type ToolApprovalMap ¶
type ToolApprovalMap map[string]ToolApprovalPolicy
ToolApprovalMap configures call-level approval policies by tool name.
type ToolApprovalOptions ¶
type ToolApprovalOptions struct {
ToolCall ToolCall
Tools ToolSet
Messages []provider.Message
Context any
}
ToolApprovalOptions carries context to a generic approval policy function.
type ToolApprovalPolicy ¶
type ToolApprovalPolicy struct {
Decision ToolApprovalDecision
Check SingleToolApprovalFunc
}
ToolApprovalPolicy configures call-level approval for a single tool.
func ApprovalPolicy ¶
func ApprovalPolicy(status ToolApprovalStatus, reason ...string) ToolApprovalPolicy
ApprovalPolicy returns a static call-level approval policy.
func ApprovalPolicyFunc ¶
func ApprovalPolicyFunc(fn SingleToolApprovalFunc) ToolApprovalPolicy
ApprovalPolicyFunc returns a dynamic call-level approval policy.
type ToolApprovalPolicyConfig ¶
type ToolApprovalPolicyConfig interface {
// contains filtered or unexported methods
}
ToolApprovalPolicyConfig is accepted by WithToolApproval.
type ToolApprovalRequest ¶
type ToolApprovalRequest struct {
ApprovalID string `json:"approvalId"`
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Input json.RawMessage `json:"input,omitempty"`
Signature string `json:"signature,omitempty"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
Dynamic *bool `json:"dynamic,omitempty"`
Title string `json:"title,omitempty"`
IsAutomatic bool `json:"isAutomatic,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
ToolApprovalRequest represents a request for user approval before executing a tool.
type ToolApprovalRequestContent ¶
type ToolApprovalRequestContent struct {
ToolApprovalRequest
}
ToolApprovalRequestContent represents a request for approval before tool execution.
type ToolApprovalResponse ¶
type ToolApprovalResponse struct {
ApprovalID string `json:"approvalId"`
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Approved bool `json:"approved"`
Reason string `json:"reason,omitempty"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
Dynamic *bool `json:"dynamic,omitempty"`
Title string `json:"title,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
ToolApprovalResponse represents a user's approval or denial of a tool request.
type ToolApprovalResponseContent ¶
type ToolApprovalResponseContent struct {
ToolApprovalResponse
}
ToolApprovalResponseContent represents an approval decision for a tool call.
type ToolApprovalStatus ¶
type ToolApprovalStatus string
ToolApprovalStatus identifies the approval policy result for a tool call.
const ( ToolApprovalNotApplicable ToolApprovalStatus = "not-applicable" ToolApprovalUserApproval ToolApprovalStatus = "user-approval" ToolApprovalApproved ToolApprovalStatus = "approved" ToolApprovalDenied ToolApprovalStatus = "denied" )
type ToolCall ¶
type ToolCall struct {
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Input json.RawMessage `json:"input"`
Invalid bool `json:"-"`
Error error `json:"-"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
Dynamic *bool `json:"dynamic,omitempty"`
Title string `json:"title,omitempty"`
}
ToolCall represents a complete tool call from the model.
type ToolCallContent ¶
type ToolCallContent struct {
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Input json.RawMessage `json:"input"`
Invalid bool `json:"-"`
Error error `json:"-"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
Dynamic *bool `json:"dynamic,omitempty"`
Title string `json:"title,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
ToolCallContent represents a tool call in the generated content.
type ToolCallNotFoundForApprovalError ¶
ToolCallNotFoundForApprovalError is returned when an approval request's referenced tool call cannot be found in any prior assistant message.
Mirrors upstream's `ToolCallNotFoundForApprovalError` from the Vercel AI SDK so callers can type-assert via errors.As and inspect both ToolCallNotFoundForApprovalError.ToolCallID and ToolCallNotFoundForApprovalError.ApprovalID.
func (*ToolCallNotFoundForApprovalError) Error ¶
func (e *ToolCallNotFoundForApprovalError) Error() string
type ToolCaller ¶
type ToolCaller struct {
Type ToolCallerType
Bind func(ToolSet) Tool
PrepareModelMessage func(ToolSet) *string
PrepareProviderOptions func(provider.ProviderOptions) provider.ProviderOptions
}
ToolCaller configures a tool that can invoke other tools.
type ToolCallerType ¶
type ToolCallerType string
ToolCallerType identifies how a caller tool invokes other tools.
const ( ToolCallerLocal ToolCallerType = "local" ToolCallerProvider ToolCallerType = "provider" )
type ToolDescriptionFunc ¶
type ToolDescriptionFunc func(ToolDescriptionOptions) string
ToolDescriptionFunc resolves a tool description for the effective step runtime context.
type ToolDescriptionOptions ¶
type ToolDescriptionOptions struct {
Context any
}
ToolDescriptionOptions carries the effective step runtime context into description resolution.
type ToolDrift ¶
type ToolDrift struct {
Added []string `json:"added"`
Removed []string `json:"removed"`
Changed []string `json:"changed"`
}
ToolDrift describes differences between two tool fingerprint maps.
func DetectToolDrift ¶
DetectToolDrift compares current tool fingerprints with a trusted baseline.
type ToolErrorContent ¶
type ToolErrorContent struct {
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Input json.RawMessage `json:"input"`
Error any `json:"-"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
Dynamic *bool `json:"dynamic,omitempty"`
Title string `json:"title,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
ToolErrorContent represents a failed tool execution in the generated content.
type ToolExecuteFunc ¶
type ToolExecuteFunc func(ctx context.Context, input json.RawMessage, opts ToolExecutionOptions) (json.RawMessage, error)
ToolExecuteFunc is the signature for a tool's execution function. It receives the parsed input and returns the tool output as JSON.
type ToolExecuteStreamFunc ¶
type ToolExecuteStreamFunc func(ctx context.Context, input json.RawMessage, opts ToolExecutionOptions, emit func(json.RawMessage) error) error
ToolExecuteStreamFunc emits preliminary outputs and returns when the tool is complete. The last emitted output is repeated as the final tool result on success.
type ToolExecutionOptions ¶
type ToolExecutionOptions struct {
ToolCallID string
Messages []provider.Message
Context any // user-defined context (experimental_context in AI SDK)
}
ToolExecutionOptions carries context into tool execution.
type ToolInvocationPart ¶
type ToolInvocationPart struct {
InputEncoding provider.ToolInputEncoding `json:"inputEncoding,omitempty"`
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
State ToolInvocationState `json:"state"`
Title *string `json:"title,omitempty"`
ToolMetadata map[string]json.RawMessage `json:"toolMetadata,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
RawInput json.RawMessage `json:"rawInput,omitempty"`
Output json.RawMessage `json:"output,omitempty"`
ErrorText *string `json:"errorText,omitempty"`
Preliminary *bool `json:"preliminary,omitempty"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
Approval *ToolApproval `json:"approval,omitempty"`
CallProviderMetadata provider.ProviderMetadata `json:"callProviderMetadata,omitzero"`
ResultProviderMetadata provider.ProviderMetadata `json:"resultProviderMetadata,omitzero"`
// contains filtered or unexported fields
}
ToolInvocationPart carries a tool invocation lifecycle in a UIMessage. Title, ErrorText and Preliminary use nil for absence and preserve explicit empty strings or false. Output-error requires a non-nil ErrorText. ToolMetadata and call/result metadata preserve non-nil empty objects. RawInput stores accumulated input-streaming text as a JSON string and retains legacy output-error input separately from Input. Other opaque JSON fields preserve JSON null, while nil means absent.
func (ToolInvocationPart) MarshalJSON ¶
func (p ToolInvocationPart) MarshalJSON() ([]byte, error)
func (ToolInvocationPart) PartType ¶
func (p ToolInvocationPart) PartType() string
PartType implements Part.
func (*ToolInvocationPart) UnmarshalJSON ¶
func (p *ToolInvocationPart) UnmarshalJSON(data []byte) error
type ToolInvocationState ¶
type ToolInvocationState string
ToolInvocationState identifies the lifecycle state of a tool invocation.
const ( ToolStateInputStreaming ToolInvocationState = "input-streaming" ToolStateInputAvailable ToolInvocationState = "input-available" ToolStateApprovalRequested ToolInvocationState = "approval-requested" ToolStateApprovalResponded ToolInvocationState = "approval-responded" ToolStateOutputAvailable ToolInvocationState = "output-available" ToolStateOutputError ToolInvocationState = "output-error" ToolStateOutputDenied ToolInvocationState = "output-denied" )
type ToolLoopAgent ¶
type ToolLoopAgent struct {
// contains filtered or unexported fields
}
ToolLoopAgent is the built-in Agent implementation backed by StreamText and GenerateText.
ToolLoopAgent stores reusable settings and merges them with per-call options for each Generate or Stream call. It defaults to StepCountIs(20) when no stop condition is configured, while direct StreamText calls keep their one-step default. Reusable and per-call lifecycle callbacks compose in reusable-then-call order and inherit StreamText's concurrency behavior.
Agent runtime context is a wrapper-level Go adaptation of upstream runtimeContext: the resolved value is propagated through PrepareStepState.Context and ToolExecutionOptions.Context. Non-nil PrepareStepResult.Context values carry forward to later steps; nil preserves the effective context because the current result shape cannot distinguish an omitted context from an intentional nil clear.
The Agent user-agent marker is added only to provider.CallOptions headers; provider modules must honor call headers for it to reach the network.
Example ¶
_ = NewToolLoopAgent(nil,
WithToolLoopAgentID("assistant"),
WithToolLoopAgentOptions(WithInstructions("Be concise.")),
)
fmt.Println(AgentVersionV1)
Output: agent-v1
func NewToolLoopAgent ¶
func NewToolLoopAgent(model provider.LanguageModel, opts ...ToolLoopAgentOption) *ToolLoopAgent
NewToolLoopAgent constructs a ToolLoopAgent for model.
Construction records settings only and does not call the provider.
func (*ToolLoopAgent) Generate ¶
func (a *ToolLoopAgent) Generate(ctx context.Context, opts ...AgentGenerateOption) (*GenerateTextResult, error)
Generate runs an Agent call to completion.
func (*ToolLoopAgent) Stream ¶
func (a *ToolLoopAgent) Stream(ctx context.Context, opts ...AgentStreamOption) *StreamTextResult
Stream starts an Agent stream call.
func (*ToolLoopAgent) Tools ¶
func (a *ToolLoopAgent) Tools() ToolSet
Tools returns a copy of the reusable tool set configured on the Agent.
func (*ToolLoopAgent) Version ¶
func (a *ToolLoopAgent) Version() AgentVersion
Version returns agent-v1.
type ToolLoopAgentOption ¶
type ToolLoopAgentOption interface {
// contains filtered or unexported methods
}
ToolLoopAgentOption configures a ToolLoopAgent.
func WithToolLoopAgentID ¶
func WithToolLoopAgentID(id string) ToolLoopAgentOption
WithToolLoopAgentID sets the optional Agent ID.
func WithToolLoopAgentOptions ¶
func WithToolLoopAgentOptions(opts ...StreamOption) ToolLoopAgentOption
WithToolLoopAgentOptions adds reusable StreamText/GenerateText settings to a ToolLoopAgent.
Shared options such as WithTools, WithInstructions, WithStopWhen, and callbacks apply to both Stream and Generate. Stream-only options such as OnChunk apply only to Stream calls.
func WithToolLoopAgentRuntimeContext ¶
func WithToolLoopAgentRuntimeContext(value any) ToolLoopAgentOption
WithToolLoopAgentRuntimeContext sets reusable Agent runtime context.
The context is delivered to callbacks and tools through PrepareStepState.Context and ToolExecutionOptions.Context. A per-call Agent runtime context overrides this value only when supplied.
type ToolNeedsApprovalFunc ¶
type ToolNeedsApprovalFunc func(input json.RawMessage, opts ToolExecutionOptions) (bool, error)
ToolNeedsApprovalFunc decides whether a tool invocation requires user approval.
type ToolNotExecutableError ¶
type ToolNotExecutableError struct {
ToolName string
}
ToolNotExecutableError is returned when an approved tool call cannot be executed locally because the tool is unknown to the current invocation or has no `Execute` function configured.
func (*ToolNotExecutableError) Error ¶
func (e *ToolNotExecutableError) Error() string
type ToolOption ¶
type ToolOption interface {
Option
ConvertOption
}
ToolOption configures tools for text generation and UI message conversion.
type ToolOutputContext ¶
type ToolOutputContext struct {
ToolCallID string
Input json.RawMessage
Output json.RawMessage
}
ToolOutputContext is passed to Tool.ToModelOutput for converting tool output to the provider's expected format.
type ToolResult ¶
type ToolResult struct {
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Input json.RawMessage `json:"input"`
Output json.RawMessage `json:"output"`
ModelOutput *provider.ToolResultOutput `json:"-"`
IsError bool `json:"isError,omitempty"`
Error error `json:"-"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
Dynamic *bool `json:"dynamic,omitempty"`
Preliminary bool `json:"preliminary,omitempty"`
Title string `json:"title,omitempty"`
}
ToolResult represents a tool execution result.
type ToolResultContent ¶
type ToolResultContent struct {
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Input json.RawMessage `json:"input"`
Output json.RawMessage `json:"output"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
Dynamic *bool `json:"dynamic,omitempty"`
Preliminary bool `json:"preliminary,omitempty"`
Title string `json:"title,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
}
ToolResultContent represents a tool execution result in the generated content.
type ToolRoute ¶
ToolRoute controls how a configured tool is exposed to the model and caller tools. Direct permits model visibility; Callers names caller tools in preparation order. A zero-value route hides the tool from the model but keeps it executable.
type ToolRoutes ¶
ToolRoutes maps callee tool names to their routes. Unlisted tools are unchanged.
type TypedToolDef ¶
type TypedToolDef[I, O any] struct { Name string Description string Title string Execute func(ctx context.Context, input I, opts ToolExecutionOptions) (O, error) OutputSchema schema.Schema InputExamples []I Strict *bool ProviderOptions provider.ProviderOptions ValidateInput func(input I) error ToModelOutput func(toolCallID string, input I, output O) (*provider.ToolResultOutput, error) OnInputStart func(ToolExecutionOptions) OnInputDelta func(inputTextDelta string, opts ToolExecutionOptions) OnInputAvailable func(input I, err error, opts ToolExecutionOptions) }
TypedToolDef defines a tool using Go types instead of raw JSON. The input schema is derived from I via schema.SchemaFor[I]() and marshal/unmarshal is handled internally, so the Execute function works with typed input and output directly.
type UIMessage ¶
type UIMessage struct {
ID string `json:"id"`
Role Role `json:"role"`
Parts []Part `json:"parts"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
UIMessage is the canonical message type for the AI SDK UI protocol. It is JSON-serializable for persistence and wire transfer.
func AssembleUIMessage ¶
func AssembleUIMessage(stream <-chan UIMessageChunk, opts ...UIMessageReaderOption) (UIMessage, error)
AssembleUIMessage reads a UIMessageChunk stream to completion and returns the final assembled assistant message.
func (UIMessage) MarshalJSON ¶
func (*UIMessage) UnmarshalJSON ¶
type UIMessageChunk ¶
type UIMessageChunk struct {
InputEncoding provider.ToolInputEncoding `json:"inputEncoding,omitempty"`
Citations []provider.Citation `json:"citations,omitzero"`
Type ChunkType `json:"type"`
// Lifecycle fields
MessageID string `json:"messageId,omitempty"`
MessageMetadata json.RawMessage `json:"messageMetadata,omitempty"`
FinishReason string `json:"finishReason,omitempty"`
Reason string `json:"reason,omitempty"`
// Content fields
ID string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
Delta string `json:"delta,omitempty"`
InputTextDelta string `json:"inputTextDelta,omitempty"`
// Tool fields
ToolCallID string `json:"toolCallId,omitempty"`
ToolName string `json:"toolName,omitempty"`
ApprovalID string `json:"approvalId,omitempty"`
Signature string `json:"signature,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
Output json.RawMessage `json:"output,omitempty"`
ErrorText string `json:"errorText,omitempty"`
// Approved is intentionally not tagged with omitempty: a denial response
// (approved=false) MUST appear on the wire. The custom MarshalJSON for
// ChunkToolApprovalResponse always writes this field, but exposing the
// raw bool would otherwise silently drop denials.
Approved bool `json:"approved"`
ProviderExecuted bool `json:"providerExecuted,omitempty"`
Dynamic *bool `json:"dynamic,omitempty"`
Preliminary bool `json:"preliminary,omitempty"`
IsAutomatic bool `json:"isAutomatic,omitempty"`
// Source fields
SourceID string `json:"sourceId,omitempty"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
// File fields
MediaType string `json:"mediaType,omitempty"`
Filename string `json:"filename,omitempty"`
// Data chunk fields (type is "data-{name}")
DataName string `json:"-"`
Data json.RawMessage `json:"data,omitempty"`
Transient bool `json:"transient,omitempty"`
ProviderMetadata provider.ProviderMetadata `json:"providerMetadata,omitempty"`
ToolMetadata json.RawMessage `json:"toolMetadata,omitempty"`
// ApprovalDescriptor carries opaque approval request data on approvalDescriptor.
ApprovalDescriptor json.RawMessage `json:"approvalDescriptor,omitempty"`
// contains filtered or unexported fields
}
UIMessageChunk is a single SSE event in the UI message stream protocol. Use the constructor functions (TextDeltaChunk, DataChunk, etc.) to create valid chunks with the correct Type set. Decoded tool chunks retain explicit empty title/reason and false preliminary/providerExecuted values. Direct scalar zero-value construction keeps optional-field omission semantics.
func DataChunk ¶
func DataChunk(name string, data json.RawMessage, transient bool) UIMessageChunk
DataChunk creates a data chunk. Set transient to true for ephemeral data that should not be persisted in message history.
func ErrorChunk ¶
func ErrorChunk(errorText string) UIMessageChunk
ErrorChunk creates an error chunk.
func FileChunk ¶
func FileChunk(url, mediaType string) UIMessageChunk
FileChunk creates a file chunk.
func FinishChunk ¶
func FinishChunk(finishReason string) UIMessageChunk
FinishChunk creates a finish chunk.
func ReasoningDeltaChunk ¶
func ReasoningDeltaChunk(id, delta string) UIMessageChunk
ReasoningDeltaChunk creates a reasoning-delta chunk.
func ReasoningEndChunk ¶
func ReasoningEndChunk(id string) UIMessageChunk
ReasoningEndChunk creates a reasoning-end chunk.
func ReasoningFileChunk ¶
func ReasoningFileChunk(url, mediaType string) UIMessageChunk
ReasoningFileChunk creates a reasoning-file chunk.
func ReasoningStartChunk ¶
func ReasoningStartChunk(id string) UIMessageChunk
ReasoningStartChunk creates a reasoning-start chunk.
func SourceDocumentChunk ¶
func SourceDocumentChunk(sourceID, mediaType, title string) UIMessageChunk
SourceDocumentChunk creates a source-document chunk.
func SourceURLChunk ¶
func SourceURLChunk(sourceID, url string) UIMessageChunk
SourceURLChunk creates a source-url chunk.
func StartChunk ¶
func StartChunk(messageID string) UIMessageChunk
StartChunk creates a start chunk. An empty messageID lets CreateUIMessageStream assign the response message ID; pass a value to keep a request-scoped ID.
func TextDeltaChunk ¶
func TextDeltaChunk(id, delta string) UIMessageChunk
TextDeltaChunk creates a text-delta chunk.
func TextEndChunk ¶
func TextEndChunk(id string) UIMessageChunk
TextEndChunk creates a text-end chunk.
func TextStartChunk ¶
func TextStartChunk(id string) UIMessageChunk
TextStartChunk creates a text-start chunk.
func ToolInputAvailableChunk ¶
func ToolInputAvailableChunk(toolCallID, toolName string, input json.RawMessage) UIMessageChunk
ToolInputAvailableChunk creates a tool-input-available chunk.
func ToolInputDeltaChunk ¶
func ToolInputDeltaChunk(toolCallID, inputTextDelta string) UIMessageChunk
ToolInputDeltaChunk creates a tool-input-delta chunk.
func ToolInputErrorChunk ¶
func ToolInputErrorChunk(toolCallID, toolName string, input json.RawMessage, errorText string) UIMessageChunk
ToolInputErrorChunk creates a tool-input-error chunk.
func ToolInputStartChunk ¶
func ToolInputStartChunk(toolCallID, toolName string) UIMessageChunk
ToolInputStartChunk creates a tool-input-start chunk.
func ToolOutputAvailableChunk ¶
func ToolOutputAvailableChunk(toolCallID string, output json.RawMessage) UIMessageChunk
ToolOutputAvailableChunk creates a tool-output-available chunk.
func ToolOutputErrorChunk ¶
func ToolOutputErrorChunk(toolCallID, errorText string) UIMessageChunk
ToolOutputErrorChunk creates a tool-output-error chunk.
func (UIMessageChunk) MarshalJSON ¶
func (c UIMessageChunk) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. Each chunk type serializes only the fields defined by the UIMessageChunk schema.
func (*UIMessageChunk) UnmarshalJSON ¶
func (c *UIMessageChunk) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler and rejects unknown chunk discriminators.
type UIMessageReaderOption ¶
type UIMessageReaderOption interface {
// contains filtered or unexported methods
}
UIMessageReaderOption configures UI message stream readers.
func WithUIMessageReaderGenerateID ¶
func WithUIMessageReaderGenerateID(fn func() string) UIMessageReaderOption
WithUIMessageReaderGenerateID configures the fallback message ID generator used when a chunk stream does not provide an ID before one is needed.
func WithUIMessageReaderInitialMessage ¶
func WithUIMessageReaderInitialMessage(message UIMessage) UIMessageReaderOption
WithUIMessageReaderInitialMessage resumes from a cloned assistant message. Non-assistant messages supply only their ID. Each reader receives an isolated copy.
type UIMessageStreamOnFinishState ¶
type UIMessageStreamOnFinishState struct {
Messages []UIMessage
IsContinuation bool
IsAborted bool
ResponseMessage UIMessage
FinishReason provider.FinishReason
// AssemblyError reports chunks that could not be applied while building
// ResponseMessage, which is otherwise complete. Check it before persisting:
// a non-nil value means the stored message is missing content the client saw.
AssemblyError error
}
UIMessageStreamOnFinishState is passed to the OnFinish callback.
type UIMessageStreamOption ¶
type UIMessageStreamOption interface {
// contains filtered or unexported methods
}
UIMessageStreamOption configures UI message stream helpers.
func OnUIMessageStreamError ¶
func OnUIMessageStreamError(fn func(error) string) UIMessageStreamOption
OnUIMessageStreamError configures error-to-text conversion for UI streams.
func OnUIMessageStreamFinish ¶
func OnUIMessageStreamFinish(fn func(UIMessageStreamOnFinishState)) UIMessageStreamOption
OnUIMessageStreamFinish configures a callback invoked after stream finish.
func WithUIMessageStreamFinish ¶
func WithUIMessageStreamFinish(send bool) UIMessageStreamOption
WithUIMessageStreamFinish configures whether finish chunks are sent.
func WithUIMessageStreamGenerateID ¶
func WithUIMessageStreamGenerateID(fn func() string) UIMessageStreamOption
WithUIMessageStreamGenerateID configures generated UI message IDs.
func WithUIMessageStreamMessageMetadata ¶
func WithUIMessageStreamMessageMetadata(fn func(part TextStreamPart) json.RawMessage) UIMessageStreamOption
WithUIMessageStreamMessageMetadata configures message metadata extraction.
func WithUIMessageStreamOriginalMessages ¶
func WithUIMessageStreamOriginalMessages(messages ...UIMessage) UIMessageStreamOption
WithUIMessageStreamOriginalMessages configures the original messages used for continuation IDs and finish callbacks. Calling this option, even with no messages, marks original messages as explicitly present.
func WithUIMessageStreamReasoning ¶
func WithUIMessageStreamReasoning(send bool) UIMessageStreamOption
WithUIMessageStreamReasoning configures whether reasoning chunks are sent.
func WithUIMessageStreamSources ¶
func WithUIMessageStreamSources(send bool) UIMessageStreamOption
WithUIMessageStreamSources configures whether source chunks are sent. Citations attached to text-end chunks and custom chunks are sent regardless.
func WithUIMessageStreamStart ¶
func WithUIMessageStreamStart(send bool) UIMessageStreamOption
WithUIMessageStreamStart configures whether start chunks are sent.
type UIMessageStreamWriter ¶
type UIMessageStreamWriter struct {
// contains filtered or unexported fields
}
UIMessageStreamWriter writes UIMessageChunk events to a stream. It is safe for concurrent use.
func (*UIMessageStreamWriter) Close ¶
func (w *UIMessageStreamWriter) Close() error
Close closes the writer. No further writes are allowed. Returns ErrAlreadyClosed if called more than once.
func (*UIMessageStreamWriter) Merge ¶
func (w *UIMessageStreamWriter) Merge(stream <-chan UIMessageChunk) error
Merge reads all chunks from the given channel and writes them to this stream.
func (*UIMessageStreamWriter) Write ¶
func (w *UIMessageStreamWriter) Write(chunk UIMessageChunk) (retErr error)
Write sends a chunk to the stream. Returns ErrWriterClosed if the writer has been closed.
type UIPartType ¶
type UIPartType string
UIPartType identifies the wire type of a UIMessage part.
const ( UIPartText UIPartType = "text" UIPartReasoning UIPartType = "reasoning" UIPartToolInvocation UIPartType = "tool-invocation" UIPartDynamicTool UIPartType = "dynamic-tool" UIPartFile UIPartType = "file" UIPartReasoningFile UIPartType = "reasoning-file" UIPartSourceURL UIPartType = "source-url" UIPartSourceDocument UIPartType = "source-document" UIPartData UIPartType = "data" UIPartCustom UIPartType = "custom" UIPartStepStart UIPartType = "step-start" )
type UserToolType ¶
type UserToolType string
UserToolType identifies the kind of user-facing tool.
const ( UserToolFunction UserToolType = "function" UserToolProvider UserToolType = "provider" UserToolDynamic UserToolType = "dynamic" )
Source Files
¶
- agent.go
- agent_ui_validation.go
- chunk.go
- citations.go
- convert.go
- doc.go
- extract_content.go
- generated_file_download.go
- generatetext.go
- http.go
- id.go
- message.go
- message_json.go
- missing_tool_results_error.go
- options.go
- output.go
- provider_options.go
- retry.go
- retry_error.go
- stream.go
- streamtext.go
- text.go
- textstream.go
- to_response_messages.go
- tool.go
- tool_approval_errors.go
- tool_approval_signature.go
- tool_caller.go
- tool_fingerprint.go
- tool_search.go
- tool_ui_json.go
- typed_tool.go
- types.go
- ui_message_reader.go
Directories
¶
| Path | Synopsis |
|---|---|
|
ai-gateway
module
|
|
|
examples
|
|
|
agent-chat
module
|
|
|
structured-extraction
module
|
|
|
internal
|
|
|
releasecheck
Package releasecheck validates the release-please component inventory.
|
Package releasecheck validates the release-please component inventory. |
|
streamrecover
Package streamrecover contains panics in stream worker goroutines, so a failure while producing, forwarding or observing one stream ends only that stream.
|
Package streamrecover contains panics in stream worker goroutines, so a failure while producing, forwarding or observing one stream ends only that stream. |
|
streamusage
Package streamusage aggregates normalized usage reported across provider stream parts.
|
Package streamusage aggregates normalized usage reported across provider stream parts. |
|
legacy
module
|
|
|
Package middleware provides a model-agnostic interception layer for provider.LanguageModel.
|
Package middleware provides a model-agnostic interception layer for provider.LanguageModel. |
|
agentobservability
module
|
|
|
enrichment
module
|
|
|
logger
module
|
|
|
prometheus
module
|
|
|
Package output provides structured output capabilities for the AI SDK.
|
Package output provides structured output capabilities for the AI SDK. |
|
Package provider defines the interface and types that LLM provider implementations depend on.
|
Package provider defines the interface and types that LLM provider implementations depend on. |
|
providers
|
|
|
anthropic
module
|
|
|
azure
module
|
|
|
bedrock
module
|
|
|
grafana
module
|
|
|
openai
module
|
|
|
openai-compatible
module
|
|
|
Package registry provides provider management for the AI SDK.
|
Package registry provides provider management for the AI SDK. |
|
Package schema provides JSON Schema generation, compilation, and validation for the AI SDK.
|
Package schema provides JSON Schema generation, compilation, and validation for the AI SDK. |
|
test
|
|
|
conformance
module
|
|
|
integration/testserver
module
|