跳到内容

自定义类型

Outlines 提供自定义 Pydantic 类型,让您可以专注于用例,而不是编写正则表达式

类别 类型 导入路径 描述
ISBN 10 & 13 outlines.types.ISBN 无法保证 校验位 正确
机场 IATA outlines.types.airports.IATA 有效的 机场 IATA 代码
国家 alpha-2 代码 outlines.types.airports.Alpha2 有效的 国家 alpha-2 代码
alpha-3 代码 outlines.types.countries.Alpha3 有效的 国家 alpha-3 代码
数字代码 outlines.types.countries.Numeric 有效的 国家数字代码
名称 outlines.types.countries.Name 有效的国家名称
旗帜 outlines.types.countries.Flag 有效的旗帜表情符号
电子邮件 outlines.types.Email 有效的电子邮件地址

某些类型需要本地化。我们目前仅支持美国类型,但请随时创建不同类型的本地化版本并提交 Pull Request。本地化类型使用 types.locale 按以下方式指定

from outlines import types

types.locale("us").ZipCode
types.locale("us").PhoneNumber

目前可用的本地化类型如下

类别 区域设置 导入路径 描述
邮政编码 美国 ZipCode 生成美国邮政编码(+4 位)
电话号码 美国 PhoneNumber 生成有效的美国电话号码

您可以在 Pydantic schema 中使用这些类型进行 JSON 结构化生成

from pydantic import BaseModel

from outlines import models, generate, types

# Specify the locale for types
locale = types.locale("us")

class Client(BaseModel):
    name: str
    phone_number: locale.PhoneNumber
    zip_code: locale.ZipCode


model = models.transformers("microsoft/Phi-3-mini-4k-instruct")
generator = generate.json(model, Client)
result = generator(
    "Create a client profile with the fields name, phone_number and zip_code"
)
print(result)
# name='Tommy' phone_number='129-896-5501' zip_code='50766'

或者直接使用 outlines.generate.format

from pydantic import BaseModel

from outlines import models, generate, types


model = models.transformers("microsoft/Phi-3-mini-4k-instruct")
generator = generate.format(model, types.locale("us").PhoneNumber)
result = generator(
    "Return a US Phone number: "
)
print(result)
# 334-253-2630

我们计划添加更多自定义类型。如果您发现自己需要编写正则表达式来生成特定类型的字段,或者如果您可以从更具体的类型中受益,请随时提交 PR开启 issue