Skip to main content
在 GitHub 上打开

Outlines

Outline 是一个用于生成约束语言的 Python 库。它为各种语言模型提供了统一的接口,并允许使用正则表达式匹配、类型约束、JSON 架构和无上下文语法等技术进行结构化生成。

Outline 支持多个后端,包括:

  • Hugging Face 变压器
  • llama.cpp
  • vLLM
  • MLX 系列

此集成允许您将 Outline 模型与 LangChain 一起使用,从而提供 LLM 和聊天模型接口。

安装和设置

要将 Outline 与 LangChain 一起使用,您需要安装 Outlines 库:

pip install outlines

根据您选择的后端,您可能需要安装其他依赖项:

  • 对于变压器:pip install transformers torch datasets
  • 对于 llama.cpp:pip install llama-cpp-python
  • 对于 vLLM:pip install vllm
  • 对于 MLX:pip install mlx

LLM

要在 LangChain 中将 Outline 用作 LLM,您可以使用Outlines类:

from langchain_community.llms import Outlines
API 参考:概述

聊天模型

要在 LangChain 中使用 Outline 作为聊天模型,您可以使用ChatOutlines类:

from langchain_community.chat_models import ChatOutlines
API 参考:ChatOutline

模型配置

OutlinesChatOutlines类共享类似的配置选项:

model = Outlines(
model="meta-llama/Llama-2-7b-chat-hf", # Model identifier
backend="transformers", # Backend to use (transformers, llamacpp, vllm, or mlxlm)
max_tokens=256, # Maximum number of tokens to generate
stop=["\n"], # Optional list of stop strings
streaming=True, # Whether to stream the output
# Additional parameters for structured generation:
regex=None,
type_constraints=None,
json_schema=None,
grammar=None,
# Additional model parameters:
model_kwargs={"temperature": 0.7}
)

型号标识符

modelparameter 可以是:

  • Hugging Face 模型名称(例如,“meta-llama/Llama-2-7b-chat-hf”)
  • 模型的局部路径
  • 对于 GGUF 模型,格式为“repo_id/file_name”(例如,“TheBloke/Llama-2-7B-Chat-GGUF/llama-2-7b-chat.Q4_K_M.gguf”)

后端选项

backendparameter 指定要使用的后端:

  • "transformers":对于 Hugging Face Transformers 模型(默认)
  • "llamacpp":对于使用 llama.cpp 的 GGUF 模型
  • "transformers_vision": 对于视觉语言模型(例如 LLaVA)
  • "vllm":对于使用 vLLM 库的模型
  • "mlxlm":对于使用 MLX 框架的模型

结构化生成

Outline 提供了几种结构化生成方法:

  1. 正则表达式匹配

    model = Outlines(
    model="meta-llama/Llama-2-7b-chat-hf",
    regex=r"((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)"
    )

    这将确保生成的文本与指定的正则表达式模式匹配(在本例中为有效的 IP 地址)。

  2. 类型约束

    model = Outlines(
    model="meta-llama/Llama-2-7b-chat-hf",
    type_constraints=int
    )

    这会将输出限制为有效的 Python 类型(int、float、bool、datetime.date、datetime.time、datetime.datetime)。

  3. JSON 架构

    from pydantic import BaseModel

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

    model = Outlines(
    model="meta-llama/Llama-2-7b-chat-hf",
    json_schema=Person
    )

    这可确保生成的输出符合指定的 JSON 架构或 Pydantic 模型。

  4. 上下文无关语法

    model = Outlines(
    model="meta-llama/Llama-2-7b-chat-hf",
    grammar="""
    ?start: expression
    ?expression: term (("+" | "-") term)*
    ?term: factor (("*" | "/") factor)*
    ?factor: NUMBER | "-" factor | "(" expression ")"
    %import common.NUMBER
    """
    )

    这将生成符合 EBNF 格式的指定上下文无关语法的文本。

使用示例

LLM 示例

from langchain_community.llms import Outlines

llm = Outlines(model="meta-llama/Llama-2-7b-chat-hf", max_tokens=100)
result = llm.invoke("Tell me a short story about a robot.")
print(result)
API 参考:概述

聊天模型示例

from langchain_community.chat_models import ChatOutlines
from langchain_core.messages import HumanMessage, SystemMessage

chat = ChatOutlines(model="meta-llama/Llama-2-7b-chat-hf", max_tokens=100)
messages = [
SystemMessage(content="You are a helpful AI assistant."),
HumanMessage(content="What's the capital of France?")
]
result = chat.invoke(messages)
print(result.content)

流式处理示例

from langchain_community.chat_models import ChatOutlines
from langchain_core.messages import HumanMessage

chat = ChatOutlines(model="meta-llama/Llama-2-7b-chat-hf", streaming=True)
for chunk in chat.stream("Tell me a joke about programming."):
print(chunk.content, end="", flush=True)
print()

结构化输出示例

from langchain_community.llms import Outlines
from pydantic import BaseModel

class MovieReview(BaseModel):
title: str
rating: int
summary: str

llm = Outlines(
model="meta-llama/Llama-2-7b-chat-hf",
json_schema=MovieReview
)
result = llm.invoke("Write a short review for the movie 'Inception'.")
print(result)
API 参考:概述

附加功能

Tokenizer 访问

您可以访问模型的底层分词器:

tokenizer = llm.tokenizer
encoded = tokenizer.encode("Hello, world!")
decoded = tokenizer.decode(encoded)