跳到正文
Instructor

框架与 SDK

在 Instructor 中使用 Shannon

用 Instructor 给指向 Shannon 的 OpenAI 客户端打补丁,即可从 Shannon 模型得到 Pydantic 对象,完整的或流式的都行。

  • 测试于 2026年11月7日
  • OpenAI Chat Completions
  • 约 1 分钟

关于 Instructor

Instructor 把模型的回答转换成经过校验的 Pydantic 对象:传入 response_model 即可拿回类型化数据,校验失败时会重试。它封装的是 OpenAI 客户端,因此把该客户端指向 Shannon,就能从 Shannon 模型获得结构化输出。

你需要准备

Shannon API 密钥
密钥与用量
基础 URL
https://api.shannon-ai.com/v1 端点: /v1/chat/completions
下面的所有代码示例都会随你的选择而变化。

设置步骤

  1. 安装 Instructor

    Shell
    pip install instructor openai
  2. 取回一个类型化对象

    Mode.TOOLS 通过工具调用来获取对象,Shannon 模型支持这种方式。

    Python
    import instructor
    from openai import OpenAI
    from pydantic import BaseModel
    
    client = instructor.from_openai(
        OpenAI(base_url="https://api.shannon-ai.com/v1", api_key="YOUR_API_KEY"),
        mode=instructor.Mode.TOOLS,
    )
    
    class Cat(BaseModel):
        name: str
        colour: str
        age_years: int
    
    cat = client.chat.completions.create(
        model="Kimi-K3-uncensored-NVFP4",
        response_model=Cat,
        messages=[{"role": "user", "content": "Tom is a grey cat, 4 years old."}],
    )
    print(cat)  # name='Tom' colour='grey' age_years=4
  3. 流式输出部分对象

    Python
    for partial in client.chat.completions.create_partial(
        model="Kimi-K3-uncensored-NVFP4",
        response_model=Cat,
        messages=[{"role": "user", "content": "Make up a cat: name, colour, age in years."}],
    ):
        print(partial)

检查是否正常工作

发送: 运行第一个示例。

你应该看到: name='Tom' colour='grey' age_years=4

适合 Instructor 的模型

下面的每个 id 都满足 Instructor 的要求。第一个是代码示例中的默认值。

模型 id上下文窗口最大输出图像输入
Kimi-K3-uncensored-NVFP4 1,022,976 262,144 是
Kimi-K3-uncensored-3BIT-REAP 225,280 225,280 是
shannon-3 196,608 65,536 是
shannon-coder-1 131,072 65,536 否

须知

  • 与 Shannon 搭配应使用 Mode.TOOLS;它依赖工具调用,选择器中的每个模型都支持。
  • 请像上面那样用 from_openai 封装你自己的客户端,这样基础 URL 和密钥才是 Shannon 的。

提示

  1. 在 create 上设置 max_retries=2,校验失败时会再次询问模型,代价是每次重试多一个请求。
  2. create_iterable 可从一个回答中返回对象列表,例如一段文字里的每只猫。
  3. Instructor 也能封装 Anthropic 客户端(instructor.from_anthropic),把它的 base_url="https://api.shannon-ai.com" 指向 Shannon 即可;我们测试的是 OpenAI 这条路线。

故障排查

现象原因解决办法
InstructorRetryException 重试之后,回答仍未通过校验。 放宽模型的字段类型,或调高 max_retries。
404 Not Found base_url 缺少 /v1。 使用 https://api.shannon-ai.com/v1。
401 Unauthorized 密钥缺失、输入有误或已被轮换。 从密钥与用量重新复制密钥;它以 sk- 开头。
报错 context_length_exceeded 或 “prompt is too long”(提示词过长) 对话长度超出了模型的上下文窗口。 开启新对话、让工具压缩对话,或选择窗口更大的模型。
insufficient_quota 你的余额不足以支付该请求。 充值或更换计划;该请求不会自动重试。

常见问题

Instructor 能与 Shannon 一起使用吗?

可以:用 instructor.from_openai 封装 OpenAI(base_url="https://api.shannon-ai.com/v1")。

流式输出能用吗?

能;create_partial 会在对象逐步填充时依次产出它,我们已测试过。

选择你的语言

所有语言一视同仁。请选择你想使用的语言。

欧洲

中东和北非

南亚

东南亚

东亚

中亚和高加索

非洲

大洋洲

人造语言和古典语言