{"record":{"id":"5385a9e20790cb80","repo":"run-llama/llama_index","slug":"unknown-schema-type-schema-type","errorCode":null,"errorMessage":"Unknown schema type {schema_type}","messagePattern":"Unknown schema type (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"llama-index-core/llama_index/core/prompts/guidance_utils.py","lineNumber":125,"sourceCode":"        )\n    elif schema[\"type\"] == \"string\":\n        if key is None:\n            raise ValueError(\"key should not be None\")\n        return \"\\\"{{gen '\" + key + \"' stop='\\\"'}}\\\"\"\n    elif schema[\"type\"] in [\"integer\", \"number\"]:\n        if key is None:\n            raise ValueError(\"key should not be None\")\n        if use_pattern_control:\n            return \"{{gen '\" + key + \"' pattern='[0-9\\\\.]' stop=','}}\"\n        else:\n            return \"\\\"{{gen '\" + key + \"' stop='\\\"'}}\\\"\"\n    elif schema[\"type\"] == \"boolean\":\n        if key is None:\n            raise ValueError(\"key should not be None\")\n        return \"{{#select '\" + key + \"'}}True{{or}}False{{/select}}\"\n    else:\n        schema_type = schema[\"type\"]\n        raise ValueError(f\"Unknown schema type {schema_type}\")\n\n\nModel = TypeVar(\"Model\", bound=BaseModel)\n\n\ndef parse_pydantic_from_guidance_program(\n    response: str, cls: Type[Model], verbose: bool = False\n) -> Model:\n    \"\"\"\n    Parse output from guidance program.\n\n    This is a temporary solution for parsing a pydantic object out of an executed\n    guidance program.\n\n    NOTE: right now we assume the output is the last markdown formatted json block\n\n    NOTE: a better way is to extract via Program.variables, but guidance does not\n          support extracting nested objects right now.","sourceCodeStart":107,"sourceCodeEnd":143,"githubUrl":"https://github.com/run-llama/llama_index/blob/afd0fef371831f9bda13e5af7167cf4e981278ab/llama-index-core/llama_index/core/prompts/guidance_utils.py#L107-L143","documentation":"The final else branch of json_schema_to_guidance_output_template: the schema node's 'type' is not one of object/array/string/integer/number/boolean, so the walker has no guidance command to emit and raises ValueError(f\"Unknown schema type {schema_type}\"). Values like 'null', 'any', or missing/type-less nodes (e.g. pydantic v2 anyOf/Optional unions collapsed by .model_json_schema()) land here.","triggerScenarios":"Passing a pydantic model to GuidancePydanticProgram where some field's JSON schema has no plain 'type': Optional[...] rendered as anyOf, Union types, Any-typed fields, null-typed fields, or a hand-written JSON schema using '$ref'/'allOf' that the walker does not resolve.","commonSituations":"Pydantic v2 migrations (Optional fields now emit anyOf instead of a nullable type), models with Union or Any fields, or schemas imported from FastAPI/OpenAPI specs. The guidance utility is a shallow schema compiler and only understands a flat type field.","solutions":["Flatten the model: replace Optional/Union fields with a single concrete type (or str with a validator), so every node has a literal 'type' in its schema.","Remove Any-typed and None-default fields that serialize as typeless/anyOf nodes.","If the union is genuinely needed, move the guidance program to an object model with simple fields and do the union parsing in your own pydantic validator after extraction.","Migrate off the guidance integration to a maintained structured-output path (provider JSON mode / function calling)."],"exampleFix":"// before\nfrom typing import Optional, Union\nfrom pydantic import BaseModel\nclass Info(BaseModel):\n    value: Optional[int] = None      # anyOf -> no 'type' -> Unknown schema type\n    tag: Union[str, int] | None = None\n\n// after\nfrom pydantic import BaseModel, field_validator\nclass Info(BaseModel):\n    value: int = 0                   # concrete type; default replaces None\n    tag: str = \"\"                    # single type; coerce in a validator if needed\n    @field_validator(\"tag\", mode=\"before\")\n    @classmethod\n    def _cast(cls, v):\n        return str(v)","handlingStrategy":"validation","validationCode":"SUPPORTED_TYPES = {\"object\", \"array\", \"string\", \"integer\", \"number\", \"boolean\"}\n\ndef assert_schema_types_supported(cls) -> None:\n    schema = cls.model_json_schema()\n    stack = [schema]\n    while stack:\n        node = stack.pop()\n        if isinstance(node, dict):\n            if \"type\" in node and node[\"type\"] not in SUPPORTED_TYPES:\n                raise TypeError(f\"Unsupported schema type {node['type']!r} in {cls.__name__}\")\n            if \"anyOf\" in node or \"allOf\" in node or \"$ref\" in node:\n                raise TypeError(\n                    f\"{cls.__name__} contains anyOf/allOf/$ref nodes; \"\n                    \"flatten Optional/Union fields to single concrete types.\"\n                )\n            stack.extend(v for v in node.values() if isinstance(v, (dict, list)))\n        elif isinstance(node, list):\n            stack.extend(node)\n\nassert_schema_types_supported(Info)","typeGuard":"def is_flat_guidance_schema(cls) -> bool:\n    \"\"\"True when every schema node carries a supported literal 'type'.\"\"\"\n    stack = [cls.model_json_schema()]\n    while stack:\n        node = stack.pop()\n        if isinstance(node, dict):\n            if node.get(\"type\") not in SUPPORTED_TYPES and \"type\" in node:\n                return False\n            if any(k in node for k in (\"anyOf\", \"allOf\", \"$ref\")):\n                return False\n            stack.extend(v for v in node.values() if isinstance(v, (dict, list)))\n        elif isinstance(node, list):\n            stack.extend(node)\n    return True","tryCatchPattern":null,"preventionTips":["Avoid Optional/Union/Any fields in models used with the guidance compiler; pydantic v2 turns Optional into anyOf.","Validate the model's JSON schema in unit tests before wiring it into GuidancePydanticProgram.","Keep guidance output models intentionally boring: flat objects of str/int/float/bool/list."],"tags":["llama-index","guidance","pydantic","json-schema","union-types","pydantic-v2"],"backgroundTag":null,"analyzedSha":"afd0fef371831f9bda13e5af7167cf4e981278ab","analyzedAt":"2026-08-15T05:42:58.429Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}