第十一章:JSON Schema 生成
每个模型都能自动生成标准的 JSON Schema——这是 FastAPI 自动文档、前后端契约、LLM 结构化输出的基础:
python
class User(BaseModel):
"""用户模型""" # docstring 会变成 schema 的 description
name: str = Field(description="姓名", min_length=1)
age: int = Field(ge=0, le=150)
schema = User.model_json_schema()
# {
# "title": "User",
# "description": "用户模型",
# "type": "object",
# "properties": {
# "name": {"type": "string", "minLength": 1, "description": "姓名"},
# "age": {"type": "integer", "minimum": 0, "maximum": 150}
# },
# "required": ["name", "age"]
# }现在你明白第四章的 description、examples 有什么用了吧——它们全都流进 Schema。让 AI 按固定格式输出时,把 model_json_schema() 的结果塞进 prompt,是最可靠的做法之一。