跳到内容

使用 Ollama 实现结构化输出,Instructor 完整指南

本指南演示了如何将 Ollama 与 Instructor 结合使用以生成结构化输出。您将学习如何使用 JSON schema 模式配合本地 LLM 创建类型安全的响应。

开源 LLM 越来越受欢迎,而 Ollama 后续发布的 OpenAI 兼容性使其能够使用 JSON schema 获取结构化输出。

阅读完本博客文章后,您将学会如何有效地将 Instructor 与 Ollama 结合使用。但在继续之前,让我们先探讨一下“修补”(patching) 的概念。

修补

Instructor 的修补增强了 OpenAI API,增加了以下功能:

  • create 调用中的 `response_model`,返回一个 pydantic 模型
  • create 调用中的 `max_retries`,通过回退策略在调用失败时进行重试

了解更多

要了解更多信息,请参阅文档。要了解将 Pydantic 与 Instructor 结合使用的优势,请访问 为什么使用 Pydantic 页面的技巧和窍门部分。

Ollama

首先下载 Ollama,然后拉取一个模型,例如 Llama 2 或 Mistral。

确保您的 `ollama` 已更新到最新版本!

ollama pull llama2
from openai import OpenAI
from pydantic import BaseModel, Field
from typing import List

import instructor


class Character(BaseModel):
    name: str
    age: int
    fact: List[str] = Field(..., description="A list of facts about the character")


# enables `response_model` in create call
client = instructor.from_openai(
    OpenAI(
        base_url="http://localhost:11434/v1",
        api_key="ollama",  # required, but unused
    ),
    mode=instructor.Mode.JSON,
)

resp = client.chat.completions.create(
    model="llama2",
    messages=[
        {
            "role": "user",
            "content": "Tell me about the Harry Potter",
        }
    ],
    response_model=Character,
)
print(resp.model_dump_json(indent=2))
"""
{
  "name": "Harry James Potter",
  "age": 37,
  "fact": [
    "He is the chosen one.",
    "He has a lightning-shaped scar on his forehead.",
    "He is the son of James and Lily Potter.",
    "He attended Hogwarts School of Witchcraft and Wizardry.",
    "He is a skilled wizard and sorcerer.",
    "He fought against Lord Voldemort and his followers.",
    "He has a pet owl named Snowy."
  ]
}
"""