RELLM
RELLM 是一个库,它为结构化解码封装了本地 Hugging Face 管道模型。
它通过一次生成一个标记来工作。在每一步中,它会屏蔽不符合提供的部分正则表达式的标记。
警告 - 此模块仍在实验阶段
%pip install --upgrade --quiet rellm langchain-huggingface > /dev/null
Hugging Face 基线
首先,让我们通过检查没有结构化解码的模型的输出,建立一个定性基线。
import logging
logging.basicConfig(level=logging.ERROR)
prompt = """Human: "What's the capital of the United States?"
AI Assistant:{
"action": "Final Answer",
"action_input": "The capital of the United States is Washington D.C."
}
Human: "What's the capital of Pennsylvania?"
AI Assistant:{
"action": "Final Answer",
"action_input": "The capital of Pennsylvania is Harrisburg."
}
Human: "What 2 + 5?"
AI Assistant:{
"action": "Final Answer",
"action_input": "2 + 5 = 7."
}
Human: 'What's the capital of Maryland?'
AI Assistant:"""
from langchain_huggingface import HuggingFacePipeline
from transformers import pipeline
hf_model = pipeline(
"text-generation", model="cerebras/Cerebras-GPT-590M", max_new_tokens=200
)
original_model = HuggingFacePipeline(pipeline=hf_model)
generated = original_model.generate([prompt], stop=["Human:"])
print(generated)
API 参考:HuggingFacePipeline
Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.
``````output
generations=[[Generation(text=' "What\'s the capital of Maryland?"\n', generation_info=None)]] llm_output=None
这并不令人印象深刻,是吗?它没有回答问题,也没有遵循 JSON 格式!让我们尝试使用结构化解码器。
RELLM LLM 包装器
让我们再试一次,现在提供一个正则表达式来匹配 JSON 结构化格式。
import regex # Note this is the regex library NOT python's re stdlib module
# We'll choose a regex that matches to a structured json string that looks like:
# {
# "action": "Final Answer",
# "action_input": string or dict
# }
pattern = regex.compile(
r'\{\s*"action":\s*"Final Answer",\s*"action_input":\s*(\{.*\}|"[^"]*")\s*\}\nHuman:'
)
from langchain_experimental.llms import RELLM
model = RELLM(pipeline=hf_model, regex=pattern, max_new_tokens=200)
generated = model.predict(prompt, stop=["Human:"])
print(generated)
API 参考:RELLM
{"action": "Final Answer",
"action_input": "The capital of Maryland is Baltimore."
}
瞧!没有解析错误。