feat(api): chore: pydantic & fastapi upgrade

Upgrade pydantic and fastapi to latest.

- pydantic~=2.4.2
- fastapi~=103.2
- fastapi-events~=0.9.1

**Big Changes**

There are a number of logic changes needed to support pydantic v2. Most changes are very simple, like using the new methods to serialized and deserialize models, but there are a few more complex changes.

**Invocations**

The biggest change relates to invocation creation, instantiation and validation.

Because pydantic v2 moves all validation logic into the rust pydantic-core, we may no longer directly stick our fingers into the validation pie.

Previously, we (ab)used models and fields to allow invocation fields to be optional at instantiation, but required when `invoke()` is called. We directly manipulated the fields and invocation models when calling `invoke()`.

With pydantic v2, this is much more involved. Changes to the python wrapper do not propagate down to the rust validation logic - you have to rebuild the model. This causes problem with concurrent access to the invocation classes and is not a free operation.

This logic has been totally refactored and we do not need to change the model any more. The details are in `baseinvocation.py`, in the `InputField` function and `BaseInvocation.invoke_internal()` method.

In the end, this implementation is cleaner.

**Invocation Fields**

In pydantic v2, you can no longer directly add or remove fields from a model.

Previously, we did this to add the `type` field to invocations.

**Invocation Decorators**

With pydantic v2, we instead use the imperative `create_model()` API to create a new model with the additional field. This is done in `baseinvocation.py` in the `invocation()` wrapper.

A similar technique is used for `invocation_output()`.

**Minor Changes**

There are a number of minor changes around the pydantic v2 models API.

**Protected `model_` Namespace**

All models' pydantic-provided methods and attributes are prefixed with `model_` and this is considered a protected namespace. This causes some conflict, because "model" means something to us, and we have a ton of pydantic models with attributes starting with "model_".

Forunately, there are no direct conflicts. However, in any pydantic model where we define an attribute or method that starts with "model_", we must tell set the protected namespaces to an empty tuple.

```py
class IPAdapterModelField(BaseModel):
    model_name: str = Field(description="Name of the IP-Adapter model")
    base_model: BaseModelType = Field(description="Base model")

    model_config = ConfigDict(protected_namespaces=())
```

**Model Serialization**

Pydantic models no longer have `Model.dict()` or `Model.json()`.

Instead, we use `Model.model_dump()` or `Model.model_dump_json()`.

**Model Deserialization**

Pydantic models no longer have `Model.parse_obj()` or `Model.parse_raw()`, and there are no `parse_raw_as()` or `parse_obj_as()` functions.

Instead, you need to create a `TypeAdapter` object to parse python objects or JSON into a model.

```py
adapter_graph = TypeAdapter(Graph)
deserialized_graph_from_json = adapter_graph.validate_json(graph_json)
deserialized_graph_from_dict = adapter_graph.validate_python(graph_dict)
```

**Field Customisation**

Pydantic `Field`s no longer accept arbitrary args.

Now, you must put all additional arbitrary args in a `json_schema_extra` arg on the field.

**Schema Customisation**

FastAPI and pydantic schema generation now follows the OpenAPI version 3.1 spec.

This necessitates two changes:
- Our schema customization logic has been revised
- Schema parsing to build node templates has been revised

The specific aren't important, but this does present additional surface area for bugs.

**Performance Improvements**

Pydantic v2 is a full rewrite with a rust backend. This offers a substantial performance improvement (pydantic claims 5x to 50x depending on the task). We'll notice this the most during serialization and deserialization of sessions/graphs, which happens very very often - a couple times per node.

I haven't done any benchmarks, but anecdotally, graph execution is much faster. Also, very larges graphs - like with massive iterators - are much, much faster.
This commit is contained in:
psychedelicious
2023-09-24 18:11:07 +10:00
parent 19c5435332
commit c238a7f18b
74 changed files with 2788 additions and 3116 deletions

View File

@ -1,5 +1,12 @@
import { isBoolean, isInteger, isNumber, isString } from 'lodash-es';
import { OpenAPIV3 } from 'openapi-types';
import {
isArray,
isBoolean,
isInteger,
isNumber,
isString,
startCase,
} from 'lodash-es';
import { OpenAPIV3_1 } from 'openapi-types';
import {
COLLECTION_MAP,
POLYMORPHIC_TYPES,
@ -72,6 +79,7 @@ import {
T2IAdapterCollectionInputFieldTemplate,
BoardInputFieldTemplate,
InputFieldTemplate,
OpenAPIV3_1SchemaOrRef,
} from '../types/types';
import { ControlField } from 'services/api/types';
@ -90,7 +98,7 @@ export type BuildInputFieldArg = {
* @example
* refObjectToFieldType({ "$ref": "#/components/schemas/ImageField" }) --> 'ImageField'
*/
export const refObjectToSchemaName = (refObject: OpenAPIV3.ReferenceObject) =>
export const refObjectToSchemaName = (refObject: OpenAPIV3_1.ReferenceObject) =>
refObject.$ref.split('/').slice(-1)[0];
const buildIntegerInputFieldTemplate = ({
@ -111,7 +119,10 @@ const buildIntegerInputFieldTemplate = ({
template.maximum = schemaObject.maximum;
}
if (schemaObject.exclusiveMaximum !== undefined) {
if (
schemaObject.exclusiveMaximum !== undefined &&
isNumber(schemaObject.exclusiveMaximum)
) {
template.exclusiveMaximum = schemaObject.exclusiveMaximum;
}
@ -119,7 +130,10 @@ const buildIntegerInputFieldTemplate = ({
template.minimum = schemaObject.minimum;
}
if (schemaObject.exclusiveMinimum !== undefined) {
if (
schemaObject.exclusiveMinimum !== undefined &&
isNumber(schemaObject.exclusiveMinimum)
) {
template.exclusiveMinimum = schemaObject.exclusiveMinimum;
}
@ -144,7 +158,10 @@ const buildIntegerPolymorphicInputFieldTemplate = ({
template.maximum = schemaObject.maximum;
}
if (schemaObject.exclusiveMaximum !== undefined) {
if (
schemaObject.exclusiveMaximum !== undefined &&
isNumber(schemaObject.exclusiveMaximum)
) {
template.exclusiveMaximum = schemaObject.exclusiveMaximum;
}
@ -152,7 +169,10 @@ const buildIntegerPolymorphicInputFieldTemplate = ({
template.minimum = schemaObject.minimum;
}
if (schemaObject.exclusiveMinimum !== undefined) {
if (
schemaObject.exclusiveMinimum !== undefined &&
isNumber(schemaObject.exclusiveMinimum)
) {
template.exclusiveMinimum = schemaObject.exclusiveMinimum;
}
@ -195,7 +215,10 @@ const buildFloatInputFieldTemplate = ({
template.maximum = schemaObject.maximum;
}
if (schemaObject.exclusiveMaximum !== undefined) {
if (
schemaObject.exclusiveMaximum !== undefined &&
isNumber(schemaObject.exclusiveMaximum)
) {
template.exclusiveMaximum = schemaObject.exclusiveMaximum;
}
@ -203,7 +226,10 @@ const buildFloatInputFieldTemplate = ({
template.minimum = schemaObject.minimum;
}
if (schemaObject.exclusiveMinimum !== undefined) {
if (
schemaObject.exclusiveMinimum !== undefined &&
isNumber(schemaObject.exclusiveMinimum)
) {
template.exclusiveMinimum = schemaObject.exclusiveMinimum;
}
@ -227,7 +253,10 @@ const buildFloatPolymorphicInputFieldTemplate = ({
template.maximum = schemaObject.maximum;
}
if (schemaObject.exclusiveMaximum !== undefined) {
if (
schemaObject.exclusiveMaximum !== undefined &&
isNumber(schemaObject.exclusiveMaximum)
) {
template.exclusiveMaximum = schemaObject.exclusiveMaximum;
}
@ -235,7 +264,10 @@ const buildFloatPolymorphicInputFieldTemplate = ({
template.minimum = schemaObject.minimum;
}
if (schemaObject.exclusiveMinimum !== undefined) {
if (
schemaObject.exclusiveMinimum !== undefined &&
isNumber(schemaObject.exclusiveMinimum)
) {
template.exclusiveMinimum = schemaObject.exclusiveMinimum;
}
return template;
@ -872,84 +904,106 @@ const buildSchedulerInputFieldTemplate = ({
};
export const getFieldType = (
schemaObject: InvocationFieldSchema
schemaObject: OpenAPIV3_1SchemaOrRef
): string | undefined => {
if (schemaObject?.ui_type) {
return schemaObject.ui_type;
} else if (!schemaObject.type) {
// if schemaObject has no type, then it should have one of allOf, anyOf, oneOf
if (isSchemaObject(schemaObject)) {
if (!schemaObject.type) {
// if schemaObject has no type, then it should have one of allOf, anyOf, oneOf
if (schemaObject.allOf) {
const allOf = schemaObject.allOf;
if (allOf && allOf[0] && isRefObject(allOf[0])) {
return refObjectToSchemaName(allOf[0]);
}
} else if (schemaObject.anyOf) {
const anyOf = schemaObject.anyOf;
/**
* Handle Polymorphic inputs, eg string | string[]. In OpenAPI, this is:
* - an `anyOf` with two items
* - one is an `ArraySchemaObject` with a single `SchemaObject or ReferenceObject` of type T in its `items`
* - the other is a `SchemaObject` or `ReferenceObject` of type T
*
* Any other cases we ignore.
*/
let firstType: string | undefined;
let secondType: string | undefined;
if (isArraySchemaObject(anyOf[0])) {
// first is array, second is not
const first = anyOf[0].items;
const second = anyOf[1];
if (isRefObject(first) && isRefObject(second)) {
firstType = refObjectToSchemaName(first);
secondType = refObjectToSchemaName(second);
} else if (
isNonArraySchemaObject(first) &&
isNonArraySchemaObject(second)
) {
firstType = first.type;
secondType = second.type;
if (schemaObject.allOf) {
const allOf = schemaObject.allOf;
if (allOf && allOf[0] && isRefObject(allOf[0])) {
return refObjectToSchemaName(allOf[0]);
}
} else if (isArraySchemaObject(anyOf[1])) {
// first is not array, second is
const first = anyOf[0];
const second = anyOf[1].items;
if (isRefObject(first) && isRefObject(second)) {
firstType = refObjectToSchemaName(first);
secondType = refObjectToSchemaName(second);
} else if (
isNonArraySchemaObject(first) &&
isNonArraySchemaObject(second)
) {
firstType = first.type;
secondType = second.type;
} else if (schemaObject.anyOf) {
// ignore null types
const anyOf = schemaObject.anyOf.filter((i) => {
if (isSchemaObject(i)) {
if (i.type === 'null') {
return false;
}
}
return true;
});
if (anyOf.length === 1) {
if (isRefObject(anyOf[0])) {
return refObjectToSchemaName(anyOf[0]);
} else if (isSchemaObject(anyOf[0])) {
return getFieldType(anyOf[0]);
}
}
/**
* Handle Polymorphic inputs, eg string | string[]. In OpenAPI, this is:
* - an `anyOf` with two items
* - one is an `ArraySchemaObject` with a single `SchemaObject or ReferenceObject` of type T in its `items`
* - the other is a `SchemaObject` or `ReferenceObject` of type T
*
* Any other cases we ignore.
*/
let firstType: string | undefined;
let secondType: string | undefined;
if (isArraySchemaObject(anyOf[0])) {
// first is array, second is not
const first = anyOf[0].items;
const second = anyOf[1];
if (isRefObject(first) && isRefObject(second)) {
firstType = refObjectToSchemaName(first);
secondType = refObjectToSchemaName(second);
} else if (
isNonArraySchemaObject(first) &&
isNonArraySchemaObject(second)
) {
firstType = first.type;
secondType = second.type;
}
} else if (isArraySchemaObject(anyOf[1])) {
// first is not array, second is
const first = anyOf[0];
const second = anyOf[1].items;
if (isRefObject(first) && isRefObject(second)) {
firstType = refObjectToSchemaName(first);
secondType = refObjectToSchemaName(second);
} else if (
isNonArraySchemaObject(first) &&
isNonArraySchemaObject(second)
) {
firstType = first.type;
secondType = second.type;
}
}
if (firstType === secondType && isPolymorphicItemType(firstType)) {
return SINGLE_TO_POLYMORPHIC_MAP[firstType];
}
}
if (firstType === secondType && isPolymorphicItemType(firstType)) {
return SINGLE_TO_POLYMORPHIC_MAP[firstType];
} else if (schemaObject.enum) {
return 'enum';
} else if (schemaObject.type) {
if (schemaObject.type === 'number') {
// floats are "number" in OpenAPI, while ints are "integer" - we need to distinguish them
return 'float';
} else if (schemaObject.type === 'array') {
const itemType = isSchemaObject(schemaObject.items)
? schemaObject.items.type
: refObjectToSchemaName(schemaObject.items);
if (isArray(itemType)) {
// This is a nested array, which we don't support
return;
}
if (isCollectionItemType(itemType)) {
return COLLECTION_MAP[itemType];
}
return;
} else if (!isArray(schemaObject.type)) {
return schemaObject.type;
}
}
} else if (schemaObject.enum) {
return 'enum';
} else if (schemaObject.type) {
if (schemaObject.type === 'number') {
// floats are "number" in OpenAPI, while ints are "integer" - we need to distinguish them
return 'float';
} else if (schemaObject.type === 'array') {
const itemType = isSchemaObject(schemaObject.items)
? schemaObject.items.type
: refObjectToSchemaName(schemaObject.items);
if (isCollectionItemType(itemType)) {
return COLLECTION_MAP[itemType];
}
return;
} else {
return schemaObject.type;
}
} else if (isRefObject(schemaObject)) {
return refObjectToSchemaName(schemaObject);
}
return;
};
@ -1025,7 +1079,15 @@ export const buildInputFieldTemplate = (
name: string,
fieldType: FieldType
) => {
const { input, ui_hidden, ui_component, ui_type, ui_order } = fieldSchema;
const {
input,
ui_hidden,
ui_component,
ui_type,
ui_order,
ui_choice_labels,
item_default,
} = fieldSchema;
const extra = {
// TODO: Can we support polymorphic inputs in the UI?
@ -1035,11 +1097,13 @@ export const buildInputFieldTemplate = (
ui_type,
required: nodeSchema.required?.includes(name) ?? false,
ui_order,
ui_choice_labels,
item_default,
};
const baseField = {
name,
title: fieldSchema.title ?? '',
title: fieldSchema.title ?? (name ? startCase(name) : ''),
description: fieldSchema.description ?? '',
fieldKind: 'input' as const,
...extra,

View File

@ -1,7 +1,7 @@
import { logger } from 'app/logging/logger';
import { parseify } from 'common/util/serialize';
import { reduce } from 'lodash-es';
import { OpenAPIV3 } from 'openapi-types';
import { reduce, startCase } from 'lodash-es';
import { OpenAPIV3_1 } from 'openapi-types';
import { AnyInvocationType } from 'services/events/types';
import {
FieldType,
@ -60,7 +60,7 @@ const isNotInDenylist = (schema: InvocationSchemaObject) =>
!invocationDenylist.includes(schema.properties.type.default);
export const parseSchema = (
openAPI: OpenAPIV3.Document,
openAPI: OpenAPIV3_1.Document,
nodesAllowlistExtra: string[] | undefined = undefined,
nodesDenylistExtra: string[] | undefined = undefined
): Record<string, InvocationTemplate> => {
@ -110,7 +110,7 @@ export const parseSchema = (
return inputsAccumulator;
}
const fieldType = getFieldType(property);
const fieldType = property.ui_type ?? getFieldType(property);
if (!isFieldType(fieldType)) {
logger('nodes').warn(
@ -209,7 +209,7 @@ export const parseSchema = (
return outputsAccumulator;
}
const fieldType = getFieldType(property);
const fieldType = property.ui_type ?? getFieldType(property);
if (!isFieldType(fieldType)) {
logger('nodes').warn(
@ -222,7 +222,8 @@ export const parseSchema = (
outputsAccumulator[propertyName] = {
fieldKind: 'output',
name: propertyName,
title: property.title ?? '',
title:
property.title ?? (propertyName ? startCase(propertyName) : ''),
description: property.description ?? '',
type: fieldType,
ui_hidden: property.ui_hidden ?? false,