文档
您可以通过向 .respond() 方法提供 JSON schema 来强制 LLM 采用特定的响应格式。这保证了模型的输出符合您提供的 schema。
JSON schema 既可以直接提供,也可以通过提供实现了 lmstudio.ModelSchema 协议的对象来提供,例如 pydantic.BaseModel 或 lmstudio.BaseModel。
lmstudio.ModelSchema 协议的定义如下
@runtime_checkable class ModelSchema(Protocol): """Protocol for classes that provide a JSON schema for their model.""" @classmethod def model_json_schema(cls) → DictSchema: """Return a JSON schema dict describing this model.""" ...
当提供 schema 时,预测结果的 parsed 字段将包含一个符合给定 schema 的字符串键字典(对于非结构化结果,该字段是一个包含与 content 相同值的字符串字段)。
如果您希望模型生成的 JSON 满足给定的 schema,建议使用 pydantic 或 msgspec 等库提供基于类的 schema 定义。
Pydantic 模型原生实现了 lmstudio.ModelSchema 协议,而 lmstudio.BaseModel 是 msgspec.Struct 的子类,并适当地实现了 .model_json_schema()。
from pydantic import BaseModel
# A class based schema for a book
class BookSchema(BaseModel):
title: str
author: str
year: int
result = model.respond("Tell me about The Hobbit", response_format=BookSchema)
book = result.parsed
print(book)
# ^
# Note that `book` is correctly typed as { title: string, author: string, year: number }
您还可以使用 JSON schema 强制执行结构化响应。
# A JSON schema for a book schema = { "type": "object", "properties": { "title": { "type": "string" }, "author": { "type": "string" }, "year": { "type": "integer" }, }, "required": ["title", "author", "year"], }
result = model.respond("Tell me about The Hobbit", response_format=schema)
book = result.parsed
print(book)
# ^
# Note that `book` is correctly typed as { title: string, author: string, year: number }
此页面的源码可在 GitHub 上获取
本页内容
使用基于类的 Schema 定义进行强制
- 定义基于类的 Schema
- 生成结构化响应
使用 JSON Schema 进行强制
- 定义 JSON Schema
- 生成结构化响应