Skip to main content
Open on GitHub

Outlines

Outlines 是一个 Python 库,用于约束语言生成。它提供了一个统一的接口来访问各种语言模型,并且允许通过正则表达式匹配、类型约束、JSON 模式和无_CONTEXT_文法等技术进行结构化的生成。

Outlines 支持多种后端,包括:

  • Hugging Face 模型库
  • llama.cpp
  • vLLM
  • MLX

此集成允许您使用 Outlines 模型与 LangChain 结合使用,提供语言模型和聊天模型接口。

安装与设置

要使用 Outlines 与 LangChain 集成,您需要安装 Outlines 库:<br>

pip install outlines

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

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

LLM

使用 Outlines 作为 LangChain 中的 LLM,可以使用 Outlines 类:

from langchain_community.llms import Outlines
API 参考:大纲

聊天模型

使用LangChain中的Outlines作为聊天模型,您可以使用ChatOutlines类:

from langchain_community.chat_models import ChatOutlines
API 参考:ChatOutlines

模型配置

两者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}
)

Model Identifier

The model 参数可以是:

  • 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")

Backend Options

The backend 参数指定使用哪个后端:

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

结构化生成

大纲提供了几种结构化生成的方法:

  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类型(整数、浮点数、布尔值、datetime日期、datetime时间、datetime时刻)。

  3. JSON Schema:

    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 参考:大纲

Chat Model Example

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)

Streaming Example

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 Access

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

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