跳到主要内容
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

要将 Outlines 作为 LangChain 中的 LLM 使用,您可以使用 Outlines 类:
from langchain_community.llms import Outlines

聊天模型

要将 Outlines 作为 LangChain 中的聊天模型使用,您可以使用 ChatOutlines 类:
from langchain_community.chat_models import 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 参数可以是:
  • 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 参数指定要使用的后端:
  • "transformers":用于 Hugging Face Transformers 模型(默认)
  • "llamacpp":用于使用 llama.cpp 的 GGUF 模型
  • "transformers_vision":用于视觉语言模型(例如 LLaVA)
  • "vllm":用于使用 vLLM 库的模型
  • "mlxlm":用于使用 MLX 框架的模型

结构化生成

Outlines 提供多种结构化生成方法:
  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 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)

聊天模型示例

from langchain_community.chat_models import ChatOutlines
from langchain.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.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)

附加功能

分词器访问

您可以访问模型的基础分词器:
tokenizer = llm.tokenizer
encoded = tokenizer.encode("Hello, world!")
decoded = tokenizer.decode(encoded)

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.