Outlines
Outlines is a Python library for constrained language generation. It provides a unified interface to various language models and allows for structured generation using techniques like regex matching, type constraints, JSON schemas, and context-free grammars.
大纲支持多个后端,包括:
- Hugging Face 变压器模型
- llama.cpp
- vLLM
- MLX
此集成允许您将 Outlines 模型与 LangChain 一起使用,同时提供 LLM 和聊天模型接口。
安装与设置
要将 Outlines 与 LangChain 一起使用,你需要安装 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用作大型语言模型,您可以使用Outlines类:
from langchain_community.llms import Outlines
聊天模型
要在LangChain中将Outlines用作聊天模型,您可以使用ChatOutlines类:
from langchain_community.chat_models import 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/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 提供了多种结构化生成的方法:
-
正则表达式匹配:
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 地址)。
-
类型约束:
model = Outlines(
model="meta-llama/Llama-2-7b-chat-hf",
type_constraints=int
)这将输出限制为有效的 Python 类型(int、float、bool、datetime.date、datetime.time、datetime.datetime)。
-
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 模型。
-
上下文无关语法:
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 格式表示)的文本。
使用示例
大型语言模型示例
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_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)
附加功能
分词器访问
你可以访问模型的底层分词器:
tokenizer = llm.tokenizer
encoded = tokenizer.encode("Hello, world!")
decoded = tokenizer.decode(encoded)