跳到内容

安装 Instructor

Instructor 是一个 Python 库,可与各种 LLM 提供商协作提取结构化输出。本指南涵盖了针对不同提供商的安装和 API 密钥设置。

基本安装

使用 pip 安装核心 Instructor 包

pip install instructor

Instructor 需要 Pydantic 来定义数据模型

pip install pydantic

设置不同的 LLM 提供商

OpenAI

OpenAI 是默认提供商,开箱即用

pip install instructor

设置您的 OpenAI API 密钥

export OPENAI_API_KEY=your_openai_key

Anthropic (Claude)

与 Anthropic 的 Claude 模型一起使用

pip install "instructor[anthropic]"

设置您的 Anthropic API 密钥

export ANTHROPIC_API_KEY=your_anthropic_key

Google Gemini

与 Google 的 Gemini 模型一起使用

pip install "instructor[google-generativeai]"

设置您的 Google API 密钥

export GOOGLE_API_KEY=your_google_key

Cohere

与 Cohere 的模型一起使用

pip install "instructor[cohere]"

设置您的 Cohere API 密钥

export COHERE_API_KEY=your_cohere_key

Mistral

与 Mistral AI 的模型一起使用

pip install "instructor[mistralai]"

设置您的 Mistral API 密钥

export MISTRAL_API_KEY=your_mistral_key

LiteLLM (多种提供商)

使用 LiteLLM 访问多种提供商

pip install "instructor[litellm]"

为您想要使用的提供商设置 API 密钥。

验证您的安装

您可以通过运行一个简单的提取来验证您的安装

import instructor
from openai import OpenAI
from pydantic import BaseModel

class Person(BaseModel):
    name: str
    age: int

client = instructor.from_openai(OpenAI())
person = client.chat.completions.create(
    model="gpt-3.5-turbo",
    response_model=Person,
    messages=[
        {"role": "user", "content": "John Doe is 30 years old"}
    ]
)

print(f"Name: {person.name}, Age: {person.age}")

下一步

现在您已经安装了 Instructor,您可以

  1. 使用简单的模型创建您的第一个提取
  2. 了解可用的不同响应模型
  3. 为您首选的 LLM 提供商设置客户端

查看客户端设置指南,了解如何配置不同提供商的客户端。