Skip to main content
Open on GitHub

大纲

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

Outlines 支持多个后端,包括:

  • Hugging Face Transformers
  • llama.cpp
  • vLLM
  • MLX

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

安装与设置

要使用LangChain的Outlines,你需要安装Outlines库:

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

要在LangChain中使用Outlines作为LLM,你可以使用Outlines类:

from langchain_community.llms import Outlines
API Reference:Outlines

聊天模型

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

from langchain_community.chat_models import ChatOutlines
API Reference:ChatOutlines

模型配置

无论是 Outlines 还是 ChatOutlines 类,它们都共享相似的配置选项:

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 参数可以是:

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

后端选项

backend 参数指定要使用的后端:

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

结构化生成

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

  1. Regex Matching:

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

    This will ensure the generated text matches the specified regex pattern (in this case, a valid IP address).

  2. Type Constraints:

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

    This restricts the output to valid Python types (int, float, bool, datetime.date, datetime.time, 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
    )

    This ensures the generated output adheres to the specified JSON schema or Pydantic model.

  4. Context-Free Grammar:

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

    This generates text that adheres to the specified context-free grammar in EBNF format.

使用示例

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 Reference:Outlines

聊天模型示例

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()
API Reference:ChatOutlines | HumanMessage

结构化输出示例

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 Reference:Outlines

附加功能

分词器访问

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

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

这个页面有帮助吗?