schema

package
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Generate

func Generate(predictRef string, sourceDir string, mode Mode, parse Parser) ([]byte, error)

Generate produces an OpenAPI 3.0.2 JSON schema from a predict/train reference.

predictRef has the format "module.py:ClassName" (e.g. "predict.py:Predictor"). sourceDir is the directory containing the source file. mode selects predict vs train. parse is the parser implementation (use python.ParsePredictor).

If the COG_OPENAPI_SCHEMA environment variable is set, its value is treated as a path to a pre-built JSON schema file. The file contents are returned directly and no parsing or generation takes place.

func GenerateCombined

func GenerateCombined(sourceDir string, predictRef string, trainRef string, parse Parser) ([]byte, error)

GenerateCombined produces an OpenAPI schema for both predict and train (when both are configured) and merges them into a single document. If only one mode is configured, it returns that single schema.

If the COG_OPENAPI_SCHEMA environment variable is set, its value is treated as a path to a pre-built JSON schema file and returned directly.

func GenerateFromSource

func GenerateFromSource(source []byte, predictRef string, mode Mode, parse Parser, sourceDir string) ([]byte, error)

GenerateFromSource produces an OpenAPI 3.0.2 JSON schema from Python source bytes.

predictRef is the class or function name (e.g. "Predictor" or "predict"). parse is the parser implementation (use python.ParsePredictor). sourceDir is the project root for resolving cross-file imports. Pass "" if unknown. This is the lower-level API — it does not read files or check COG_OPENAPI_SCHEMA.

func GenerateOpenAPISchema

func GenerateOpenAPISchema(info *PredictorInfo) ([]byte, error)

GenerateOpenAPISchema produces a complete OpenAPI 3.0.2 specification from a PredictorInfo. The returned bytes are compact JSON.

func MergeSchemas

func MergeSchemas(predict, train map[string]any) map[string]any

MergeSchemas merges a predict-mode and train-mode OpenAPI schema into a single combined schema. The predict schema is used as the base; paths and component schemas from the train schema are added to it.

func TitleCase

func TitleCase(s string) string

TitleCase converts snake_case to Title Case.

func TitleCaseSingle

func TitleCaseSingle(s string) string

TitleCaseSingle title-cases a single word (first letter uppercase).

Types

type DefaultKind

type DefaultKind int

DefaultKind tags the active field in DefaultValue.

const (
	DefaultNone DefaultKind = iota
	DefaultBool
	DefaultInt
	DefaultFloat
	DefaultString
	DefaultList
	DefaultDict
	DefaultSet
)

type DefaultValue

type DefaultValue struct {
	Kind     DefaultKind
	Bool     bool
	Int      int64
	Float    float64
	Str      string
	List     []DefaultValue
	DictKeys []DefaultValue // parallel with DictVals
	DictVals []DefaultValue
}

DefaultValue represents a statically-parsed Python literal.

func (DefaultValue) MarshalJSON

func (d DefaultValue) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for DefaultValue.

func (DefaultValue) ToJSON

func (d DefaultValue) ToJSON() any

ToJSON converts a DefaultValue to its JSON representation.

type FieldType

type FieldType struct {
	Primitive  PrimitiveType
	Repetition Repetition
}

FieldType combines a primitive type with its cardinality.

func ResolveFieldType

func ResolveFieldType(ann TypeAnnotation, ctx *ImportContext) (FieldType, error)

ResolveFieldType resolves a TypeAnnotation into a FieldType.

func (FieldType) JSONType

func (ft FieldType) JSONType() map[string]any

JSONType returns the JSON Schema fragment for this field type.

type ImportContext

type ImportContext struct {
	// Names maps local name → (module, original_name)
	Names *OrderedMap[string, ImportEntry]
}

ImportContext tracks what names are imported from which modules.

func NewImportContext

func NewImportContext() *ImportContext

NewImportContext creates an empty ImportContext.

func (*ImportContext) IsBaseModel

func (ctx *ImportContext) IsBaseModel(name string) bool

IsBaseModel returns true if name resolves to cog.BaseModel or pydantic.BaseModel.

func (*ImportContext) IsBasePredictor

func (ctx *ImportContext) IsBasePredictor(name string) bool

IsBasePredictor returns true if name resolves to cog.BasePredictor.

func (*ImportContext) IsCogType

func (ctx *ImportContext) IsCogType(name string) bool

IsCogType returns true if name was imported from the "cog" module.

func (*ImportContext) IsTypingType

func (ctx *ImportContext) IsTypingType(name string) bool

IsTypingType returns true if name was imported from "typing" or "typing_extensions".

type ImportEntry

type ImportEntry struct {
	Module   string
	Original string
}

ImportEntry records where a name was imported from.

type InputField

type InputField struct {
	Name        string
	Order       int
	FieldType   FieldType
	Default     *DefaultValue
	Description *string
	GE          *float64
	LE          *float64
	MinLength   *uint64
	MaxLength   *uint64
	Regex       *string
	Choices     []DefaultValue
	Deprecated  *bool
}

InputField represents one parameter of predict/train.

func (*InputField) IsRequired

func (f *InputField) IsRequired() bool

IsRequired returns true if this field is required in the schema.

type Mode

type Mode int

Mode selects whether to extract predict or train signatures.

const (
	ModePredict Mode = iota
	ModeTrain
)

type ModelClassMap

type ModelClassMap = *OrderedMap[string, []ModelField]

ModelClassMap maps class names to their fields.

type ModelField

type ModelField struct {
	Name    string
	Type    TypeAnnotation
	Default *DefaultValue
}

ModelField is a field extracted from a BaseModel subclass.

type OrderedMap

type OrderedMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

OrderedMap is a simple insertion-ordered map.

func NewOrderedMap

func NewOrderedMap[K comparable, V any]() *OrderedMap[K, V]

NewOrderedMap creates a new empty OrderedMap.

func (*OrderedMap[K, V]) Entries

func (m *OrderedMap[K, V]) Entries(fn func(key K, value V))

Entries iterates over key-value pairs in insertion order.

func (*OrderedMap[K, V]) Get

func (m *OrderedMap[K, V]) Get(key K) (V, bool)

Get returns the value for a key and whether it exists.

func (*OrderedMap[K, V]) Keys

func (m *OrderedMap[K, V]) Keys() []K

Keys returns keys in insertion order.

func (*OrderedMap[K, V]) Len

func (m *OrderedMap[K, V]) Len() int

Len returns the number of entries.

func (*OrderedMap[K, V]) Set

func (m *OrderedMap[K, V]) Set(key K, value V)

Set inserts or updates a key-value pair.

type Parser

type Parser func(source []byte, predictRef string, mode Mode, sourceDir string) (*PredictorInfo, error)

Parser is a function that parses source code and extracts predictor info. This is defined as a type to avoid an import cycle between schema and schema/python. The concrete implementation is python.ParsePredictor.

sourceDir is the project root directory, used for resolving cross-file imports (e.g. "from .types import Output"). Pass "" if unknown.

type PredictorInfo

type PredictorInfo struct {
	Inputs *OrderedMap[string, InputField]
	Output SchemaType
	Mode   Mode
}

PredictorInfo is the top-level extraction result.

type PrimitiveType

type PrimitiveType int

PrimitiveType maps Python types to JSON Schema types.

const (
	TypeBool PrimitiveType = iota
	TypeFloat
	TypeInteger
	TypeString
	TypePath   // cog.Path — {"type":"string","format":"uri"}
	TypeFile   // cog.File (deprecated) — same wire format as Path
	TypeSecret // cog.Secret — write-only, masked
	TypeAny    // typing.Any or unresolved
)

func PrimitiveFromName

func PrimitiveFromName(name string) (PrimitiveType, bool)

PrimitiveFromName resolves a simple type name to a PrimitiveType.

func (PrimitiveType) JSONType

func (p PrimitiveType) JSONType() map[string]any

JSONType returns the JSON Schema fragment for this primitive.

func (PrimitiveType) String

func (p PrimitiveType) String() string

type Repetition

type Repetition int

Repetition describes cardinality of a field.

const (
	Required Repetition = iota
	Optional
	Repeated // list[X]
)

type SchemaError

type SchemaError struct {
	Kind    SchemaErrorKind
	Message string
}

SchemaError represents errors during schema generation.

func NewError

func NewError(kind SchemaErrorKind, msg string) *SchemaError

NewError creates a SchemaError with the given kind and message.

func WrapError

func WrapError(kind SchemaErrorKind, msg string, inner error) *SchemaError

WrapError creates a SchemaError, appending the inner error's message if non-nil.

func (*SchemaError) Error

func (e *SchemaError) Error() string

type SchemaErrorKind

type SchemaErrorKind int

SchemaErrorKind classifies schema generation errors.

const (
	ErrParse SchemaErrorKind = iota
	ErrPredictorNotFound
	ErrMethodNotFound
	ErrMissingReturnType
	ErrMissingTypeAnnotation
	ErrUnsupportedType
	ErrDefaultFactoryNotSupported
	ErrInvalidConstraint
	ErrInvalidPredictRef
	ErrOptionalOutput
	ErrConcatIteratorNotStr
	ErrChoicesNotResolvable
	ErrDefaultNotResolvable
	ErrUnresolvableType
	ErrOther
)

type SchemaField

type SchemaField struct {
	Type     SchemaType
	Default  *DefaultValue
	Required bool
}

SchemaField is a named field within a SchemaObject.

type SchemaType

type SchemaType struct {
	Kind SchemaTypeKind

	// Primitive: for Kind=SchemaPrimitive — one of the base scalar types.
	Primitive PrimitiveType

	// Array: for Kind=SchemaArray — the element type.
	Items *SchemaType

	// Dict: for Kind=SchemaDict — key and value types.
	// KeyType is always string in JSON Schema, but we track it for completeness.
	KeyType   *SchemaType
	ValueType *SchemaType

	// Object: for Kind=SchemaObject — named fields with types and defaults.
	Fields *OrderedMap[string, SchemaField]

	// Iterator/ConcatIterator: for Kind=SchemaIterator|SchemaConcatIterator.
	// The yielded element type.
	Elem *SchemaType

	// Nullable: wraps any type to allow null.
	Nullable bool
}

SchemaType is a recursive algebraic data type representing any type that can appear in a Cog predictor's output (or, in the future, input) position.

It replaces the flat OutputType/PrimitiveType system with a composable type tree that can represent dict[str, list[int]], nested BaseModel subclasses, TypedDicts, and types resolved from .pyi stubs — all without running Python.

func ResolveSchemaType

func ResolveSchemaType(ann TypeAnnotation, ctx *ImportContext, models ModelClassMap) (SchemaType, error)

ResolveSchemaType resolves a Python type annotation into a SchemaType. Unlike the legacy ResolveOutputType, this handles arbitrary nesting:

dict[str, list[dict[str, int]]]  →  SchemaDict{ValueType: SchemaArray{Items: SchemaDict{...}}}
list[dict[str, str]]             →  SchemaArray{Items: SchemaDict{ValueType: SchemaPrim(TypeString)}}

It also resolves BaseModel subclasses and cog iterators.

func SchemaAnyType

func SchemaAnyType() SchemaType

SchemaAnyType creates an opaque JSON object type.

func SchemaArrayOf

func SchemaArrayOf(elem SchemaType) SchemaType

SchemaArrayOf creates an array type with the given element type.

func SchemaConcatIteratorOf

func SchemaConcatIteratorOf() SchemaType

SchemaConcatIteratorOf creates a concatenate iterator type (always str).

func SchemaDictOf

func SchemaDictOf(value SchemaType) SchemaType

SchemaDictOf creates a dict type with string keys and the given value type.

func SchemaIteratorOf

func SchemaIteratorOf(elem SchemaType) SchemaType

SchemaIteratorOf creates an iterator type with the given element type.

func SchemaObjectOf

func SchemaObjectOf(fields *OrderedMap[string, SchemaField]) SchemaType

SchemaObjectOf creates an object type from an ordered map of fields.

func SchemaPrim

func SchemaPrim(p PrimitiveType) SchemaType

SchemaPrim creates a primitive SchemaType.

func (SchemaType) JSONSchema

func (s SchemaType) JSONSchema() map[string]any

JSONSchema converts a SchemaType to its JSON Schema representation. This is used for the "Output" component in the OpenAPI spec.

type SchemaTypeKind

type SchemaTypeKind int

SchemaTypeKind tags the active variant in SchemaType.

const (
	// SchemaPrimitive is a scalar type: bool, int, float, str, Path, File, Secret.
	SchemaPrimitive SchemaTypeKind = iota
	// SchemaAny is an opaque JSON value (unparameterized dict, Any, etc).
	SchemaAny
	// SchemaArray is a homogeneous list/array.
	SchemaArray
	// SchemaDict is a string-keyed dictionary with a typed value.
	SchemaDict
	// SchemaObject is a product type with named fields (BaseModel, TypedDict, dataclass).
	SchemaObject
	// SchemaIterator is a cog Iterator[T] — array with x-cog-array-type=iterator.
	SchemaIterator
	// SchemaConcatIterator is a cog ConcatenateIterator[str] — streaming text.
	SchemaConcatIterator
)

type TypeAnnotation

type TypeAnnotation struct {
	Kind TypeAnnotationKind
	Name string           // for Simple
	Args []TypeAnnotation // for Generic (outer=Name, args=Args) or Union (members=Args)
}

TypeAnnotation is a parsed Python type annotation (intermediate, before resolution).

func UnwrapOptional

func UnwrapOptional(ann TypeAnnotation) (TypeAnnotation, bool)

UnwrapOptional checks if a type annotation represents Optional[X] or Union[X, None]. If so, it returns the inner type and true. Otherwise it returns the original and false.

type TypeAnnotationKind

type TypeAnnotationKind int

TypeAnnotationKind tags the variant.

const (
	TypeAnnotSimple TypeAnnotationKind = iota
	TypeAnnotGeneric
	TypeAnnotUnion
)

Directories

Path Synopsis
Package python implements a tree-sitter based Python parser for extracting Cog predictor signatures.
Package python implements a tree-sitter based Python parser for extracting Cog predictor signatures.

Jump to

Keyboard shortcuts

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