文档
结构化响应
您可以通过向 .respond()
方法提供 JSON 模式来强制 LLM 输出特定的响应格式。这保证了模型的输出符合您提供的模式。
JSON 模式可以直接提供,也可以通过提供实现 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.""" ...
当提供模式时,预测结果的 parsed
字段将包含一个符合给定模式的字符串键字典(对于非结构化结果,此字段是一个字符串字段,其值与 content
相同)。
如果您希望模型生成符合给定模式的 JSON,建议使用 pydantic
或 msgspec
等库提供基于类的模式定义。
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 模式来强制实现结构化响应。
# 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 }
本页内容
强制使用基于类的模式定义
- 定义基于类的模式
- 生成结构化响应
强制使用 JSON 模式
- 定义 JSON 模式
- 生成结构化响应