Documentation
¶
Index ¶
- func Generate(predictRef string, sourceDir string, mode Mode, parse Parser) ([]byte, error)
- func GenerateCombined(sourceDir string, predictRef string, trainRef string, parse Parser) ([]byte, error)
- func GenerateFromSource(source []byte, predictRef string, mode Mode, parse Parser) ([]byte, error)
- func GenerateOpenAPISchema(info *PredictorInfo) ([]byte, error)
- func MergeSchemas(predict, train map[string]any) map[string]any
- func TitleCase(s string) string
- func TitleCaseSingle(s string) string
- type DefaultKind
- type DefaultValue
- type FieldType
- type ImportContext
- type ImportEntry
- type InputField
- type Mode
- type ModelClassMap
- type ModelField
- type ObjectField
- type OrderedMap
- type OutputKind
- type OutputType
- type Parser
- type PredictorInfo
- type PrimitiveType
- type Repetition
- type SchemaError
- type SchemaErrorKind
- type TypeAnnotation
- type TypeAnnotationKind
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Generate ¶
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 ¶
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). 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 ¶
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 TitleCaseSingle ¶
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.
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 ¶
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 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 ObjectField ¶
type ObjectField struct {
FieldType FieldType
Default *DefaultValue
}
ObjectField represents a field in a BaseModel output type.
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 OutputKind ¶
type OutputKind int
OutputKind describes the shape of the output type.
const ( OutputSingle OutputKind = iota OutputList OutputIterator OutputConcatenateIterator OutputObject )
type OutputType ¶
type OutputType struct {
Kind OutputKind
Primitive *PrimitiveType // for Single/List/Iterator/ConcatIterator
Fields *OrderedMap[string, ObjectField]
}
OutputType describes the return type of predict/train.
func ResolveOutputType ¶
func ResolveOutputType(ann TypeAnnotation, ctx *ImportContext, models ModelClassMap) (OutputType, error)
ResolveOutputType resolves an output type annotation.
func (OutputType) JSONType ¶
func (o OutputType) JSONType() map[string]any
JSONType returns the JSON Schema fragment for this output type.
type Parser ¶
type Parser func(source []byte, predictRef string, mode Mode) (*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.
type PredictorInfo ¶
type PredictorInfo struct {
Inputs *OrderedMap[string, InputField]
Output OutputType
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 ErrOther )
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).
type TypeAnnotationKind ¶
type TypeAnnotationKind int
TypeAnnotationKind tags the variant.
const ( TypeAnnotSimple TypeAnnotationKind = iota TypeAnnotGeneric TypeAnnotUnion )