Documentation
¶
Index ¶
- Variables
- func Clean(id string) string
- func CompleteJSON(jsonStr string) string
- func ConvertTo[T any](v any) (T, bool)
- func ExtractJSON(text string) (any, error)
- func ExtractJSONFromMarkdown(md string) string
- func GetJSONObjectLines(text string) []string
- func HasJSONValue(raw json.RawMessage) bool
- func InferJSONSchema(x any) *jsonschema.Schema
- func IsNil[T any](v T) bool
- func JSONString(x any) string
- func MapToStruct[T any](m map[string]any) (T, error)
- func NormalizeInput(data any, schema map[string]any) (any, error)
- func ParsePartialJSON(jsonStr string) (any, error)
- func PrettyJSONString(x any) string
- func PromptStateFromContext(ctx context.Context) any
- func ReadJSONFile(filename string, pvalue any) error
- func SchemaAsMap(s *jsonschema.Schema) map[string]any
- func StructToMap[T any](v T) (map[string]any, error)
- func UnmarshalAndNormalize[T any](input json.RawMessage, schema map[string]any) (T, error)
- func UnmarshalAndNormalizeWith[T any](input json.RawMessage, schema map[string]any, compiled *CompiledSchema) (T, error)
- func ValidJSON(s string) bool
- func ValidateIsJSONArray(schema map[string]any) bool
- func ValidateJSON(dataBytes json.RawMessage, schema map[string]any) error
- func ValidateRaw(dataBytes json.RawMessage, schemaBytes json.RawMessage) error
- func ValidateValue(data any, schema map[string]any) error
- func WithPromptState(ctx context.Context, getState func() any) context.Context
- func WriteJSONFile(filename string, value any) error
- func Zero[T any]() T
- type CompiledSchema
- type ContextKey
- type Environment
- type ExtractItemsResult
Constants ¶
This section is empty.
Variables ¶
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/exp/tool (SendChunk). The any value is *ai.ModelResponseChunk (typed as any to avoid a circular import).
var ToolPartialSenderKey = NewContextKey[func(context.Context, any)]()
ToolPartialSenderKey is the context key for streaming partial tool responses. Set by ai/generate.go (handleToolRequests), read by ai/exp/tool (SendPartial).
Functions ¶
func CompleteJSON ¶ added in v1.3.0
CompleteJSON attempts to complete an incomplete JSON string.
func ConvertTo ¶ added in v1.10.0
ConvertTo attempts to convert a value to type T. It tries a direct type assertion first, then falls back to a JSON round-trip for values that were deserialized from JSON (e.g., map[string]any instead of a concrete struct).
func ExtractJSON ¶ added in v1.3.0
ExtractJSON extracts JSON from string with lenient parsing rules. It handles both complete and partial JSON structures.
func ExtractJSONFromMarkdown ¶ added in v0.1.0
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
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 IsNil ¶ added in v1.4.0
IsNil returns true if v is nil or a nil pointer/interface/map/slice/channel/func.
func JSONString ¶
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
MapToStruct converts a map[string]any to a struct of type T via JSON round-trip.
func NormalizeInput ¶ added in v1.0.4
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 ParsePartialJSON ¶ added in v1.3.0
ParsePartialJSON attempts to parse incomplete JSON by completing it.
func PrettyJSONString ¶ added in v0.1.0
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
PromptStateFromContext returns the state attached by WithPromptState, or nil if none is attached. The getter is invoked on each call.
func ReadJSONFile ¶
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).
func StructToMap ¶ added in v1.4.0
StructToMap converts a struct to map[string]any via JSON round-trip.
func UnmarshalAndNormalize ¶ added in v1.1.0
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 ValidateIsJSONArray ¶ added in v0.5.0
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 ¶
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 WithPromptState ¶ added in v1.10.0
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 WriteJSONFile ¶
WriteJSONFile writes value to filename as JSON.
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
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.