跳到内容

使用 Anyscale 和 Zod 的结构化输出

开源大型语言模型(LLM)正变得越来越受欢迎,Anyscale 的 Mistral 模型的发布使得使用 JSON schema 在任何规模下获取结构化输出成为可能。你可以利用 JSON schema 来获取结构化输出,而不是依赖模型的默认输出模式。这种方法是一种节省时间的选择,可以替代大量的提示工程(prompt engineering)。

通过阅读这篇博文,你将学会如何有效地将 instructor 与 Anyscale 结合使用。但在我们继续之前,让我们先探讨一下 patching 的概念。

理解模式

Instructor 的 patch 增强了一个 OpenAI API 客户端,使其具备以下功能。你可以在此处了解更多信息。对于 Anyscale,他们支持 JSON_SCHEMATOOLS 模式。有了 instructor,我们将能够使用以下功能:

  • create 调用中使用 response_model,它返回一个 Zod schema
  • create 调用中使用 max_retries,如果调用失败,它会使用指数退避策略进行重试

Anyscale

好消息是 Anyscale 采用了与 OpenAI 相同的客户端,并且其模型也支持其中的一些输出模式!

获取访问权限

如果你想亲自尝试一下,请访问 Anyscale 网站。你可以在此处开始使用。

让我们来探索一下 Anyscale 丰富模型集合中的一个模型吧!

import Instructor from "@/instructor"
import OpenAI from "openai"
import { z } from "zod"

const property = z.object({
  name: z.string(),
  value: z.string()
}).describe("A property defined by a name and value")

const UserSchema = z.object({
  age: z.number(),
  name: z.string(),
  properties: z.array(property)
})

const oai = new OpenAI({
  baseURL: "https://api.endpoints.anyscale.com/v1",
  apiKey: process.env.ANYSCALE_API_KEY ?? undefined,
})

const client = Instructor({
  client: oai,
  mode: "JSON_SCHEMA"
})

const user = await client.chat.completions.create({
  messages: [{ role: "user", content: "Harry Potter" }],
  model: "mistralai/Mixtral-8x7B-Instruct-v0.1",
  response_model: { schema: UserSchema },
  max_retries: 3
})

console.log(user)
/**
 * {
  age: 17,
  name: "Harry Potter",
  properties: [
    {
      name: "House",
      value: "Gryffindor",
    }, {
      name: "Wand",
      value: "Holly and Phoenix feather",
    }
  ],
}
 */

你可以在此处找到有关 Anyscale 输出模式支持的更多信息。