LM StudioLM Studio

结构化响应

使用 Pydantic 模型或 JSON Schema 强制模型输出结构化响应

您可以通过向 .respond() 方法提供 JSON schema 来强制 LLM 采用特定的响应格式。这可以保证模型的输出符合您提供的 schema。

JSON schema 可以直接提供,也可以通过提供一个实现了 lmstudio.ModelSchema 协议的对象来提供,例如 pydantic.BaseModellmstudio.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 相同值的字符串字段)。

强制使用基于类的 Schema 定义

如果您希望模型生成满足给定 schema 的 JSON,建议使用 pydanticmsgspec 等库提供基于类的 schema 定义。

Pydantic 模型原生实现了 lmstudio.ModelSchema 协议,而 lmstudio.BaseModelmsgspec.Struct 的子类,它相应地实现了 .model_json_schema()

定义基于类的 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

您还可以使用 JSON schema 强制执行结构化响应。

定义 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 }
© . This site is unofficial and not affiliated with Element Labs, Inc.