集成:LM 格式强制器
使用 LM 格式强制器来强制您的本地模型的 JSON Schema / Regex 输出。
使用 LM Format Enforcer 来强制您在 haystack 管道中的本地模型的 JSON Schema / Regex 输出。
语言模型能够生成文本,但在要求精确的输出格式时,它们并不总是如指示的那样工作。已经引入了各种提示工程技术来提高生成文本的鲁棒性,但它们并不总是足够的。 LM Format Enforcer 通过在每个时间步过滤语言模型允许生成的 token 来解决这些问题,从而确保输出格式得到尊重,同时最大限度地减少对语言模型的限制。
什么是 LM 格式强制器?
安装
通过 pip 安装格式强制器:pip install lm-format-enforcer
使用
LMFormatEnforcerLocalGenerator:一个激活格式强制器的 Haystack Generator 组件。
重要提示:LM Format Enforcer 需要一个本地生成器 - 目前仅支持本地 HuggingFace transformers,vLLM 支持即将推出。
创建 CharacterLevelParser
CharacterLevelParser 是将输出解析连接到格式强制的类。有两种主要的解析器可用:用于 JSON Schemas 的 JsonSchemaParser,以及用于正则表达式的 RegexParser。
我们将首先定义我们想要解码的格式,无论 Haystack。
from pydantic import BaseModel
from lmformatenforcer import JsonSchemaParser
class AnswerFormat(BaseModel):
first_name: str
last_name: str
year_of_birth: int
num_seasons_in_nba: int
parser = JsonSchemaParser(AnswerFormat.schema())
Haystack 集成
要使用 Haystack V2 激活强制器,必须使用 LMFormatEnforcerLocalGenerator。
这是一个简单的例子
from haystack.components.generators.hugging_face.hugging_face_local import HuggingFaceLocalGenerator
from lmformatenforcer.integrations.haystackv2 import LMFormatEnforcerLocalGenerator
question = 'Please give me information about Michael Jordan. You MUST answer using the following json schema: '
schema_json_str = AnswerFormat.schema_json()
prompt = f'{question}{schema_json_str}'
model = HuggingFaceLocalGenerator(model="meta-llama/Llama-2-7b-chat-hf")
format_enforcer = LMFormatEnforcerLocalGenerator(model, character_level_parser)
pipeline = Pipeline()
pipeline.add_component(instance=format_enforcer, name='model')
result = pipeline.run({
"model": {"prompt": prompt}
})
print(result['model']['replies'][0])
模型将通过格式强制器进行推断,输出将如下所示
{
"first_name": "Michael",
"last_name": "Jordan",
"year_of_birth": 1963,
"num_seasons_in_nba": 15
}
有关完整示例,请参阅 示例 notebook
