Automatically extract a tool model from a json object. The tool model class can define fields with a source argument to specify the JSON pointer (RFC 6901) to the value. Example: class DummyModel(ToolModel): name: str version: str = Field(source='/versio
(json: dict, model_cls: Type[ToolModel])
| 22 | |
| 23 | |
| 24 | def autoextract(json: dict, model_cls: Type[ToolModel]) -> ToolModel: |
| 25 | """ |
| 26 | Automatically extract a tool model from a json object. |
| 27 | The tool model class can define fields with a source argument to specify the JSON pointer (RFC 6901) to the value. |
| 28 | |
| 29 | Example: |
| 30 | class DummyModel(ToolModel): |
| 31 | name: str |
| 32 | version: str = Field(source='/version/number') |
| 33 | |
| 34 | json = { |
| 35 | 'name': 'test', |
| 36 | 'version': { |
| 37 | 'number': '1.0.0', |
| 38 | 'build_date': '2023-04-19' |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | model = autoextract(json, DummyModel) |
| 43 | """ |
| 44 | attributes = {} |
| 45 | for field in model_cls.__fields__.values(): |
| 46 | pointer = field.field_info.extra.get('source') |
| 47 | |
| 48 | if pointer: |
| 49 | if field.required: |
| 50 | try: |
| 51 | value = resolve_pointer(json, pointer) |
| 52 | except JsonPointerException: |
| 53 | raise ValueError(f"Missing required value for field {field.name} at {pointer}") |
| 54 | else: |
| 55 | value = resolve_pointer(json, pointer, field.default) |
| 56 | else: |
| 57 | value = json.get(field.name) or json.get(field.alias) |
| 58 | attributes[field.name] = value |
| 59 | return model_cls(**attributes) |