Help us shape the future of Go! Take the 2026 Go Developer Survey

base

package
v1.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrTypeMismatch = errors.New("type mismatch")

ErrTypeMismatch reports that a value's Go type cannot be reinterpreted as the requested type in ConvertToExact.

This package cannot classify it, since core/status depends on this one. A caller that surfaces the failure past the framework boundary must attach a sentinel users can match, as ai.ErrInputTypeMismatch does.

View Source
var FailedModelResponse func(ctx context.Context, req any, err error) any

FailedModelResponse builds the record of a model call that failed without a response: an *ai.ModelResponse for req (an *ai.ModelRequest) and err, as a failed Generate reports it. Package ai, which owns those types, sets it when it loads; it is type-erased for the same reason as WithPromptState.

View Source
var SoftToolErrorsKey = NewContextKey[*SoftToolErrors]()

SoftToolErrorsKey is the context key for the call's SoftToolErrors. Set by the SoftToolErrors middleware (plugins/middleware), read by ai/generate.go.

View Source
var ToolCallKey = NewContextKey[*ToolCall]()

ToolCallKey is the context key holding the ToolCall of the tool stage. Set by the hook chain in ai/generate.go, read by the tool constructors in ai.

View Source
var ToolChunkSenderKey = NewContextKey[func(context.Context, any)]()

ToolChunkSenderKey is the context key for streaming raw model response chunks from within a tool. Set by ai/generate.go (handleToolRequests), read by ai/tool (SendChunk). The any value is *ai.ModelResponseChunk (typed as any to avoid a circular import).

View Source
var ToolHookKey = NewContextKey[string]()

ToolHookKey is the context key naming the stage a tool call is running in: the id of the WrapTool hook whose turn it is, empty inside the tool itself. Set per stage by the hook chain in ai/generate.go, read by ai/tool (Interrupt) to attribute an interrupt to the stage that raised it.

View Source
var ToolOriginalInputKey = NewContextKey[any]()

ToolOriginalInputKey is the context key holding a tool call's pre-replacement input, set when the caller restarted the call with a new input. Set by the hook chain in ai/generate.go on the stage the restart answers (see ToolRestart), read by ai (ToolContext.OriginalInput) and by ai/tool (OriginalInput).

View Source
var ToolPartSinkKey = NewContextKey[*PartSink]()

ToolPartSinkKey is the context key for the PartSink that collects content parts attached during one tool call. Set by ai around the whole tool call, the WrapTool hook chain included, so a hook can attach parts too; read by ai/tool (AttachParts).

View Source
var ToolReleasedKey = NewContextKey[bool]()

ToolReleasedKey is the context key marking a stage that let the call through before: the restart answers a later stage. Set per stage by the hook chain in ai/generate.go, read by ai/tool (Released).

View Source
var ToolRestartKey = NewContextKey[*ToolRestart]()

ToolRestartKey is the context key holding the ToolRestart a resumed tool call answers, for the hook chain to deliver.

View Source
var ToolResumeKey = NewContextKey[any]()

ToolResumeKey is the context key holding the data a caller sent when restarting an interrupted tool call, as the caller gave it: a map[string]any after a wire hop or from a map restart, the caller's struct from a typed restart in process. Set by the hook chain in ai/generate.go on the one stage the restart answers (see ToolRestart); each reader converts it to what it returns with ConvertTo, so a value that is already the wanted type is handed over untouched, with its Go types intact: ai (ToolContext.Resumed, IsToolResumed, ResumedValue), ai/tool (ResumeData), and the resume parameter of an ai.NewResumableTool tool. A bare restart stores an empty map, so presence of the key, not its contents, marks a call as resumed.

Functions

func CheckObjectPayload added in v1.14.0

func CheckObjectPayload(data any, what string) error

CheckObjectPayload is the check half of ObjectPayload, for a caller that leaves the conversion to the reader: it costs a type inspection, not a JSON round trip, except for a type with its own encoding, which is encoded to see what it produces. nil passes, as a bare interrupt or restart.

func Clean

func Clean(id string) string

Clean returns a valid filename for id.

func CloneSchema added in v1.12.0

func CloneSchema(schema map[string]any) map[string]any

CloneSchema returns a deep copy of schema, so a transform applied to the result cannot reach the caller's map. Values other than nested schemas and their arrays are the scalars JSON decodes to, which are immutable.

func CompleteJSON added in v1.3.0

func CompleteJSON(jsonStr string) string

CompleteJSON attempts to complete an incomplete JSON string. The result is always valid JSON.

Containers are closed innermost first, so an object nested in an array is closed before the array. A string value cut off mid-stream is kept and closed, minus any dangling escape sequence, and a truncated keyword is finished because only one keyword can start with a given letter. A tail that cannot be finished without inventing a value is dropped instead: a half-written key, a key whose value has not arrived yet, or a truncated number such as "1.".

Input that is malformed rather than truncated is cut back to the last position that was still well formed, which is why the grammar is tracked at all: a trailing comma before a closer, a container opened where a key belongs, or a raw control character inside a string all end the scan and take everything after them with it.

func ConvertTo added in v1.10.0

func ConvertTo[T any](v any) (T, bool)

ConvertTo is ConvertToExact for callers that only need to know whether the conversion was possible.

func ConvertToExact added in v1.12.0

func ConvertToExact[T any](v any) (T, error)

ConvertToExact converts a dynamically typed value to T.

It accepts a value that is already a T, a *T (a nil pointer yields the zero value), or a value in the JSON wire form the framework's transports produce (map[string]any, []any, a scalar), which it decodes into T. A nil value yields the zero value.

Reinterpreting one struct as an unrelated struct is refused with an error wrapping ErrTypeMismatch: a JSON round-trip between two unrelated structs succeeds while leaving every field zero, so the caller would otherwise get a blank value instead of a diagnosis.

When T cannot carry JSON's types on its own, meaning T is an interface or a map, slice or array whose elements are, the decoded value is normalized against the schema inferred from v (see NormalizeInput) so that an integer stays an int64 instead of widening to float64. That is what the reflection API does to action input, so a value reaches T with the same Go types whichever way it arrived. It also drops null-valued keys, as the wire does.

func ExtractJSON added in v1.3.0

func ExtractJSON(text string) (any, error)

ExtractJSON extracts JSON from string with lenient parsing rules. It handles both complete and partial JSON structures.

func ExtractJSONFromMarkdown added in v0.1.0

func ExtractJSONFromMarkdown(md string) string

ExtractJSONFromMarkdown returns the contents of the first fenced code block in the markdown text md. It matches code blocks with "json" identifier (case-insensitive) or code blocks without any language identifier. If there is no matching block, it returns md.

func GetJSONObjectLines added in v1.0.5

func GetJSONObjectLines(text string) []string

GetJSONObjectLines splits a string by newlines, trims whitespace from each line, and returns a slice containing only the lines that start with '{'.

func HasJSONValue added in v1.10.0

func HasJSONValue(raw json.RawMessage) bool

HasJSONValue reports whether raw carries an actual JSON value: it is non-empty and not the JSON null literal, ignoring surrounding whitespace.

func InferJSONSchema

func InferJSONSchema(x any) *jsonschema.Schema

InferJSONSchema infers a JSON schema from a Go value.

Recursion is detected by stack: while a struct type T is being reflected, T is marked in-progress. Any nested encounter of T (a self-reference) returns an "any" schema; T is unmarked when its reflection completes. Each top-level occurrence of T (siblings, repeats) gets its own full reflection — so a struct used in multiple fields produces the correct schema each time.

We can't observe reflection completion through the library's Mapper hook alone, so each struct type is reflected via a sub-Reflector. The Mapper's defer fires when the sub-Reflector returns, which is the exit point.

func IsJSONObject added in v1.14.0

func IsJSONObject(v any) bool

IsJSONObject reports whether v serializes to a JSON object by construction: a struct, possibly behind pointers, or a map with string keys. Nil, scalars, slices and arrays do not, and neither does a type with its own JSON or text encoding, such as time.Time, which can serialize to anything.

func IsNil added in v1.4.0

func IsNil[T any](v T) bool

IsNil returns true if v is nil or a nil pointer/interface/map/slice/channel/func.

func JSONString

func JSONString(x any) string

JSONString returns json.Marshal(x) as a string. If json.Marshal returns an error, jsonString returns the error text as a JSON string beginning "ERROR:".

func MapToStruct added in v1.4.0

func MapToStruct[T any](m map[string]any) (T, error)

MapToStruct converts a map[string]any to a struct of type T via JSON round-trip.

func NormalizeInput added in v1.0.4

func NormalizeInput(data any, schema map[string]any) (any, error)

NormalizeInput recursively traverses a data structure and performs normalization: 1. Removes any fields with null values 2. Converts instances of float64 into int64 or float64 based on the schema's "type" property

func ObjectPayload added in v1.14.0

func ObjectPayload(data any, what string) (map[string]any, error)

ObjectPayload converts an interrupt or resume payload to the JSON object the wire contract requires: nil, a nil map and a nil pointer stay nil (a bare interrupt or restart), a map[string]any is returned as is, and any other value that is a JSON object by construction (see IsJSONObject) is converted through JSON. A scalar, slice or array is rejected; what names the payload in the error.

func ParsePartialJSON added in v1.3.0

func ParsePartialJSON(jsonStr string) (any, error)

ParsePartialJSON attempts to parse incomplete JSON by completing it.

func PrettyJSONString added in v0.1.0

func PrettyJSONString(x any) string

PrettyJSONString returns json.MarshalIndent(x, "", " ") as a string. If json.MarshalIndent returns an error, jsonString returns the error text as a JSON string beginning "ERROR:".

func PromptStateFromContext added in v1.10.0

func PromptStateFromContext(ctx context.Context) any

PromptStateFromContext returns the state attached by WithPromptState, or nil if none is attached. The getter is invoked on each call.

func ReadJSONFile

func ReadJSONFile(filename string, pvalue any) error

ReadJSONFile JSON-decodes the contents of filename into pvalue, which must be a pointer.

func SchemaAsMap added in v0.1.0

func SchemaAsMap(s *jsonschema.Schema) map[string]any

SchemaAsMap converts json schema struct to a map (JSON representation). The map is rebuilt from JSON on every call, so the caller owns it and may mutate it in place; memoizing the result here would break callers that do.

func SchemaMapFor added in v1.12.0

func SchemaMapFor[T any]() map[string]any

SchemaMapFor returns the JSON schema inferred from type T as a map, or nil for interface types (e.g. `any`), whose zero value carries no type information to infer from. Like SchemaAsMap, the returned map is freshly built on every call and belongs to the caller.

func StructToMap added in v1.4.0

func StructToMap[T any](v T) (map[string]any, error)

StructToMap converts a struct to map[string]any via JSON round-trip.

func UnmarshalAndNormalize added in v1.1.0

func UnmarshalAndNormalize[T any](input json.RawMessage, schema map[string]any) (T, error)

UnmarshalAndNormalize unmarshals JSON input, normalizes it according to the schema, validates it, and converts it to the target type T. For 'any' types, it preserves the actual types from the normalized data. For structured types, it marshals and unmarshals to properly populate the fields.

func UnmarshalAndNormalizeWith added in v1.10.0

func UnmarshalAndNormalizeWith[T any](input json.RawMessage, schema map[string]any, compiled *CompiledSchema) (T, error)

UnmarshalAndNormalizeWith is UnmarshalAndNormalize with an optional precompiled schema: when compiled is non-nil, validation uses it instead of recompiling schema, which matters on per-chunk streaming hot paths. schema is still used for normalization and must describe the same schema.

func UsageSinkFromContext added in v1.14.0

func UsageSinkFromContext(ctx context.Context) func(usage any)

UsageSinkFromContext returns the sink attached by WithUsageSink, or nil.

func ValidJSON added in v0.5.0

func ValidJSON(s string) bool

Validates if the given string is a valid JSON string

func ValidateIsJSONArray added in v0.5.0

func ValidateIsJSONArray(schema map[string]any) bool

ValidateIsJSONArray will validate if the schema represents a JSON array.

func ValidateJSON

func ValidateJSON(dataBytes json.RawMessage, schema map[string]any) error

ValidateJSON will validate JSON against the expected schema. It will return an error if it doesn't match the schema, otherwise it will return nil.

func ValidateRaw

func ValidateRaw(dataBytes json.RawMessage, schemaBytes json.RawMessage) error

ValidateRaw will validate JSON data against the JSON schema. It will return an error if it doesn't match the schema, otherwise it will return nil.

func ValidateValue

func ValidateValue(data any, schema map[string]any) error

ValidateValue will validate any value against the expected schema. It will return an error if it doesn't match the schema, otherwise it will return nil.

func WalkSubschemas added in v1.12.0

func WalkSubschemas(schema map[string]any, visit func(map[string]any) map[string]any)

WalkSubschemas replaces every subschema reachable from schema with visit's result: the members of properties, the items schema, a schema-valued additionalProperties, and the branches of anyOf, oneOf, and allOf, at every depth. Non-schema values (a boolean subschema, say) are left alone.

schema itself is not visited, since a transform that widens or annotates fields usually means something different for the root. Apply visit to it directly when it should be included.

func WithPromptState added in v1.10.0

func WithPromptState(ctx context.Context, getState func() any) context.Context

WithPromptState returns ctx carrying a getter for the state exposed to prompt templates via {{@state}}. getState is evaluated lazily at render time, so it observes the latest state rather than a snapshot taken when the context was built. A nil getState detaches any state previously attached.

func WithUsageSink added in v1.14.0

func WithUsageSink(ctx context.Context, sink func(usage any)) context.Context

WithUsageSink returns ctx carrying sink, which receives the usage of each model call made under ctx: a non-nil *ai.GenerationUsage, called from whatever goroutine made the call. It replaces any sink ctx already carries; a sink that should keep an enclosing one informed forwards to it.

func WriteJSONFile

func WriteJSONFile(filename string, value any) error

WriteJSONFile writes value to filename as JSON.

func Zero

func Zero[T any]() T

Zero returns the Zero value for T.

Types

type CompiledSchema added in v1.10.0

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

CompiledSchema is a JSON schema precompiled for repeated validation, e.g. per-chunk validation on streaming transports, where recompiling the schema for every payload would dominate the hot path. A nil *CompiledSchema (from a nil schema) accepts every value, matching ValidateValue's nil handling.

func CompileSchema added in v1.10.0

func CompileSchema(schema map[string]any) (*CompiledSchema, error)

CompileSchema compiles schema for repeated validation with CompiledSchema.ValidateValue. A nil schema compiles to a nil CompiledSchema, which accepts every value.

func (*CompiledSchema) ValidateValue added in v1.10.0

func (c *CompiledSchema) ValidateValue(data any) error

ValidateValue validates data against the compiled schema, with the same behavior and error shape as ValidateValue.

type ContextKey

type ContextKey[T any] struct {
	// contains filtered or unexported fields
}

A ContextKey is a unique, typed key for a value stored in a context.

func NewContextKey

func NewContextKey[T any]() ContextKey[T]

NewContextKey returns a context key for a value of type T.

func (ContextKey[T]) FromContext

func (k ContextKey[T]) FromContext(ctx context.Context) T

FromContext returns the value associated with this key in the context, or the internal.Zero value for T if the key is not present.

func (ContextKey[T]) NewContext

func (k ContextKey[T]) NewContext(ctx context.Context, value T) context.Context

NewContext returns ctx augmented with this key and the given value.

type Environment

type Environment string

An Environment is the execution context in which the program is running.

const (
	EnvironmentDev  Environment = "dev"  // development: testing, debugging, etc.
	EnvironmentProd Environment = "prod" // production: user data, SLOs, etc.
)

type ExtractItemsResult added in v1.3.0

type ExtractItemsResult struct {
	Items  []any
	Cursor int
}

ExtractItemsResult contains the result of extracting items from an array.

func ExtractItems added in v1.3.0

func ExtractItems(text string, cursor int) ExtractItemsResult

ExtractItems extracts complete objects from the first array found in the text. Processes text from the cursor position and returns both complete items and the new cursor position.

type PartSink added in v1.14.0

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

PartSink collects the content parts attached during one tool call. The values are *ai.Part, typed as any to avoid a circular import. It is safe for concurrent use: a tool may attach from goroutines it waits for. The call closes it when it returns, and a part attached after that, from a goroutine that outlived the call, is dropped rather than held.

func (*PartSink) Add added in v1.14.0

func (s *PartSink) Add(part any)

Add appends part, or drops it once the sink is closed.

func (*PartSink) Close added in v1.14.0

func (s *PartSink) Close() []any

Close closes the sink and returns the parts attached before, in call order. Closing again returns nothing, so the parts are folded once.

type SoftToolErrors added in v1.14.0

type SoftToolErrors struct {
	Covers func(toolName string) bool
	Outer  *SoftToolErrors
}

SoftToolErrors is the policy of one SoftToolErrors middleware (plugins/middleware): which tools return their own errors, and which unknown tool names return a not-found error, to the model. It links to the policy of the middleware outside it.

func (*SoftToolErrors) Allows added in v1.14.0

func (p *SoftToolErrors) Allows(toolName string) bool

Allows reports whether p or a policy outside it covers the named tool. A nil policy covers nothing.

type ToolCall added in v1.14.0

type ToolCall struct {
	Name string
	// contains filtered or unexported fields
}

ToolCall marks the context the hook chain in ai/generate.go hands the tool stage of one tool call. The tool function that claims it owns the call's restart state and part sink; any other tool run under that context, such as a tool calling another tool directly, finds it claimed or naming another tool and runs as a call of its own. A retry that runs the tool stage again gets a fresh mark.

func (*ToolCall) Claim added in v1.14.0

func (c *ToolCall) Claim(name string) bool

Claim reports whether the tool named name owns the call c marks: c names it and no tool function claimed c before. Nil-safe.

type ToolFailError added in v1.14.0

type ToolFailError struct {
	Err error
}

ToolFailError marks a tool error as a result for the model rather than a failure of the tool loop. Created by ai/tool (Fail), read by ai/generate.go, which answers the tool request with the error message.

func (*ToolFailError) Error added in v1.14.0

func (e *ToolFailError) Error() string

func (*ToolFailError) Unwrap added in v1.14.0

func (e *ToolFailError) Unwrap() error

type ToolInterruptError added in v1.14.0

type ToolInterruptError struct {
	Data     any
	RaisedBy string
	Released []string
}

ToolInterruptError is the error a tool call returns to pause generation and hand control back to the caller. ai/tool.Interrupt is the one public way to raise it; ai recognizes it with errors.As when the tool returns, records Data on the interrupted tool request part, and reports it through ai.IsToolInterruptError. The type is internal so that raising an interrupt has a single entry point and the in-process representation can change with the wire contract.

Data is the interrupt payload: nil for a bare interrupt, otherwise the JSON object it serializes to, as a map[string]any. ai/tool.Interrupt normalizes it with ObjectPayload when the interrupt is raised, so a payload has one shape in process and after a wire hop; ai normalizes again when the tool returns, for an error built with a struct directly.

RaisedBy names the stage that raised the interrupt: the id of a WrapTool hook, read from the context under ToolHookKey by ai/tool.Interrupt, or empty for the tool function itself. ai records it on the interrupted part, and on restart delivers the answer to that stage alone.

Released lists, in chain order, the ids of the WrapTool hooks that let the call through before it interrupted. The hook chain in ai/generate.go records each as the interrupt passes back out through it; nil when no hook let the call through.

func (*ToolInterruptError) Error added in v1.14.0

func (e *ToolInterruptError) Error() string

type ToolRestart added in v1.14.0

type ToolRestart struct {
	Resume        any
	OriginalInput any
	RaisedBy      string
	Released      []string
}

ToolRestart is the restart a resumed tool call answers. ai/generate.go (restartedToolResponse) sets it on the call's context under ToolRestartKey, and the hook chain delivers it stage by stage: the stage that raised the interrupt (RaisedBy, empty for the tool itself) receives Resume and OriginalInput under ToolResumeKey and ToolOriginalInputKey, a hook the interrupted call records in Released, which let the call through before, is marked under ToolReleasedKey unless the restart replaced the input, and any other stage sees a fresh call. An interrupt that records neither RaisedBy nor Released, as one stored before they were recorded, does not say which stage it came from, so every stage receives Resume and OriginalInput and none is released.

Jump to

Keyboard shortcuts

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