快速入门
在安装 Outlines 后,快速熟悉此库的最佳方法是了解其几个核心元素。我们建议您快速浏览此页面,了解 Outlines 的全部功能,然后再深入研究文档。
核心元素
模型
使用 Outlines 编写程序的第一步是初始化模型。模型权重将在此时加载到设备上
import outlines
model = outlines.models.transformers(
"microsoft/Phi-3-mini-4k-instruct",
device="cuda" # optional device argument, default is cpu
)
Outlines 支持多种推理引擎和模型权重类型。有关不同模型的更多详细信息,请参阅Outlines 模型文档页面。
生成
模型初始化后,您可以构建一个 outlines.generate
生成器。可以直接使用 prompt 调用此生成器。
generator = outlines.generate.text(model)
result = generator("Question: What's 2+2? Answer:", max_tokens=100)
print(result)
# The answer is 4
# Outlines also supports streaming output
stream = generator.stream("What's 2+2?", max_tokens=4)
for i in range(5):
token = next(stream)
print(repr(token))
# '2'
# '+'
# '2'
# ' equals'
# '4'
除了通过 outlines.generate.text
实现的典型语言模型生成行为外,Outlines 还支持结构化生成,这保证了模型生成的 token 将遵循预定义的结构。结构可以通过正则表达式模式、JSON schema、Python 对象类型或定义可解析语言(如 SQL 或 Python)的 Lark 语法来定义。
示例:使用 pydantic 强制执行 JSON schema
from enum import Enum
from pydantic import BaseModel, constr, conint
class Character(BaseModel):
name: constr(max_length=10)
age: conint(gt=18, lt=99)
armor: (Enum('Armor', {'leather': 'leather', 'chainmail': 'chainmail', 'plate': 'plate'}))
strength: conint(gt=1, lt=100)
generator = outlines.generate.json(model, Character)
character = generator(
"Generate a new character for my awesome game: "
+ "name, age (between 1 and 99), armor and strength. "
)
print(character)
# Character(name='Zara', age=25, armor=<Armor.leather: 'leather'>, strength=85)
使用 vLLM 和 FastAPI 部署
Outlines 可以使用 vLLM 和 FastAPI 部署为 LLM 服务。该服务器支持对传入请求的异步处理,并得益于 vLLM 的性能优势。
首先启动服务器
或者您可以使用 Outlines 的官方 Docker 镜像启动服务器
默认情况下,这将启动一个位于 http://127.0.0.1:8000
的服务器(不过请检查控制台输出)。如果未设置 --model
参数,则使用 OPT-125M 模型。
然后您可以在 shell 中查询模型,方法是传递一个 prompt 和用于指定输出结构的 JSON Schema。
curl http://127.0.0.1:8000/generate \
-d '{
"prompt": "Question: What is a language model? Answer:",
"schema": {"type": "string"}
}'
或者在另一个 Python 程序中使用 requests 库。您可以阅读 vLLM 文档了解更多详细信息。
工具
Prompt 模板
编写 Prompt 可能会导致代码混乱。Outlines 的 prompt 函数是 Python 函数,其 docstring 中包含 Prompt 模板。我们使用强大的模板语言,允许您直接在 Prompt 中循环遍历列表、字典、添加条件等。调用时,prompt 函数返回渲染后的模板。
from outlines import Template
few_shots = Template.from_string(
"""{{ instructions }}
Examples
--------
{% for example in examples %}
Q: {{ example.question }}
A: {{ example.answer }}
{% endfor %}
Question
--------
Q: {{ question }}
A:
"""
)
instructions = "Please answer the following question following the examples"
examples = [
{"question": "2+2=?", "answer":4},
{"question": "3+3=?", "answer":6}
]
question = "4+4 = ?"
prompt = few_shots(instructions, examples, question)
print(prompt)
# Please answer the following question following the examples
# Examples
# --------
# Q: 2+2=?
# A: 4
# Q: 3+3=?
# A: 6
# Question
# --------
# Q: 4+4 = ?
# A:
Outlines 函数
在完成 Prompt 和输出结构的实验后,将所有这些封装在一个可以从程序其他部分调用的函数中是非常有用的。这就是 outlines.Function
所允许您做到的。
深入了解
如果您需要更多灵感,可以查看实用指南或观看Remi Louf 在 AI Engineer World’s Fair 上关于 Outlines 的演示。如果您有任何问题或文档需求,请通过 GitHub、Twitter 或 Discord 联系我们。