ITADN
nlmatics/llmsherpa
nlmatics/llmsherpa · 文件 下载 ZIP
文件最后提交记录最后更新时间
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈

LLM Sherpa

LLM Sherpa 提供战略级 API,以加速大型语言模型(LLM)用例。

新增内容

[!IMPORTANT] llmsherpa 后端服务现已在 Apache 2.0 许可证下完全开源。参见 https://github.com/nlmatics/nlm-ingestor

  • 现在您可以使用 docker 镜像运行自己的服务器!
  • 支持不同的文件格式:DOCX、PPTX、HTML、TXT、XML
  • 内置 OCR 支持
  • 块(Blocks)现在具有坐标 - 使用块(如章节)的 bbox 属性
  • 新的缩进解析器,以便更好地将文档中的所有标题与其对应的级别对齐
  • 免费服务器和付费服务器未使用最新代码更新,建议用户按照 nlm-ingestor 中的说明自行启动服务器

LayoutPDFReader

大多数 PDF 转文本解析器不提供布局信息。通常,即使句子也被任意 CR/LF 分割,这使得查找段落边界变得非常困难。这为在索引/向量化 PDF 以用于检索增强生成(RAG)等 LLM 应用时,进行分块以及添加长程上下文信息(如章节标题)带来了各种挑战。

LayoutPDFReader 通过解析 PDF 及其层次结构布局信息来解决此问题,例如:

  1. 章节和子章节及其层级。
  2. 段落 - 合并行。
  3. 章节和段落之间的链接。
  4. 表格及其所在的章节。
  5. 列表和嵌套列表。
  6. 合并跨页的内容。
  7. 移除重复的页眉和页脚。
  8. 移除水印。

使用 LayoutPDFReader,开发人员可以找到用于向量化的最佳文本块,并解决 LLM 有限上下文窗口大小的问题。

您可以直接在 Google Colab此处 实验该库。

这是一篇 文章,解释了该问题及我们的方法。

这是一篇 LlamaIndex 博客,解释了智能分块的需求。

API 参考: https://llmsherpa.readthedocs.io/

如何使用 Google Gemini Pro 如何使用 Cohere Embed3

重要说明

  • LayoutPDFReader 已在多种 PDF 上进行测试。尽管如此,正确解析每个 PDF 仍然具有挑战性。
  • 目前不支持 OCR。仅支持带有文本层的 PDF。

[!NOTE] LLMSherpa 使用一个免费且开放的 API 服务器。该服务器不会存储您的 PDF,除非在解析期间进行临时存储。该服务器即将停用。 使用 https://github.com/nlmatics/nlm-ingestor 中的说明自行托管私有服务器。

[!IMPORTANT] 私有版本可在 Microsoft Azure Marketplace 即将停止服务。请按照 https://github.com/nlmatics/nlm-ingestor 中的说明迁移到自托管实例。

安装

pip install llmsherpa

读取 PDF 文件

使用 LayoutPDFReader 的第一步是向其提供 url 或文件路径,并获取一个文档对象。

from llmsherpa.readers import LayoutPDFReader

llmsherpa_api_url = "https://readers.llmsherpa.com/api/document/developer/parseDocument?renderFormat=all"
pdf_url = "https://arxiv.org/pdf/1910.13461.pdf" # also allowed is a file path e.g. /home/downloads/xyz.pdf
pdf_reader = LayoutPDFReader(llmsherpa_api_url)
doc = pdf_reader.read_pdf(pdf_url)

安装 LlamaIndex

在以下示例中,为简洁起见,我们将使用 LlamaIndex。如果尚未安装,请安装该库。

pip install llama-index

设置 OpenAI

import openai
openai.api_key = #<Insert API Key>

使用智能分块进行向量搜索和检索增强生成

LayoutPDFReader 通过智能分块,根据文档结构将相关文本保持在一起:

  • 所有列表项都在一起,包括列表前面的段落。
  • 表格中的项目被分块在一起
  • 包含来自章节标题和嵌套章节标题的上下文信息

以下代码从 LayoutPDFReader 文档分块创建一个 LlamaIndex 查询引擎

from llama_index.core import Document
from llama_index.core import VectorStoreIndex

index = VectorStoreIndex([])
for chunk in doc.chunks():
    index.insert(Document(text=chunk.to_context_text(), extra_info={}))
query_engine = index.as_query_engine()

让我们运行一个查询:

response = query_engine.query("list all the tasks that work with bart")
print(response)

我们得到以下响应:

BART works well for text generation, comprehension tasks, abstractive dialogue, question answering, and summarization tasks.

让我们尝试另一个需要从表格中获取答案的查询:

response = query_engine.query("what is the bart performance score on squad")
print(response)

我们得到的响应如下:

The BART performance score on SQuAD is 88.8 for EM and 94.6 for F1.

使用提示词总结章节

LayoutPDFReader 提供了强大的方法,可从大型文档中选取章节和子章节,并利用 LLM 从章节中提取见解。

以下代码查找文档中的 Fine-tuning 章节:

from IPython.core.display import display, HTML
selected_section = None
# find a section in the document by title
for section in doc.sections():
    if section.title == '3 Fine-tuning BART':
        selected_section = section
        break
# use include_children=True and recurse=True to fully expand the section. 
# include_children only returns at one sublevel of children whereas recurse goes through all the descendants
HTML(section.to_html(include_children=True, recurse=True))

运行上述代码将产生以下 HTML 输出:

3 Fine-tuning BART

The representations produced by BART can be used in several ways for downstream applications.

3.1 Sequence Classification Tasks

For sequence classification tasks, the same input is fed into the encoder and decoder, and the final hidden state of the final decoder token is fed into new multi-class linear classifier.\nThis approach is related to the CLS token in BERT; however we add the additional token to the end so that representation for the token in the decoder can attend to decoder states from the complete input (Figure 3a).

3.2 Token Classification Tasks

For token classification tasks, such as answer endpoint classification for SQuAD, we feed the complete document into the encoder and decoder, and use the top hidden state of the decoder as a representation for each word.\nThis representation is used to classify the token.

3.3 Sequence Generation Tasks

Because BART has an autoregressive decoder, it can be directly fine tuned for sequence generation tasks such as abstractive question answering and summarization.\nIn both of these tasks, information is copied from the input but manipulated, which is closely related to the denoising pre-training objective.\nHere, the encoder input is the input sequence, and the decoder generates outputs autoregressively.

3.4 Machine Translation

We also explore using BART to improve machine translation decoders for translating into English.\nPrevious work Edunov et a

l.\n(2019) 表明,通过引入预训练编码器可以改进模型,但在解码器中使用预训练语言模型带来的收益有限。\n我们展示了如何将整个 BART 模型(包括编码器和解码器)作为单个预训练解码器用于机器翻译,方法是添加一组从平行语料中学习的新编码器参数(见图 3b)。

更具体地说,我们用一个新的随机初始化的编码器替换了 BART 的编码器嵌入层。\n模型采用端到端训练,这训练新的编码器将外语单词映射为 BART 可以去噪为英语的输入。\n新编码器可以使用与原始 BART 模型不同的词汇表。

我们在两个步骤中训练源编码器,在这两种情况下都从 BART 模型的输出反向传播交叉熵损失。\n在第一步中,我们冻结 BART 的大部分参数,仅更新随机初始化的源编码器、BART 的位置嵌入以及 BART 编码器第一层的自注意力输入投影矩阵。\n在第二步中,我们训练所有模型参数,迭代次数较少。

现在,让我们使用提示词来创建此文本的自定义摘要:

from llama_index.llms import OpenAI
context = selected_section.to_html(include_children=True, recurse=True)
question = "list all the tasks discussed and one line about each task"
resp = OpenAI().complete(f"read this text and answer question: {question}:\n{context}")
print(resp.text)

上述代码产生以下输出:

Tasks discussed in the text:

1. Sequence Classification Tasks: The same input is fed into the encoder and decoder, and the final hidden state of the final decoder token is used for multi-class linear classification.
2. Token Classification Tasks: The complete document is fed into the encoder and decoder, and the top hidden state of the decoder is used as a representation for each word for token classification.
3. Sequence Generation Tasks: BART can be fine-tuned for tasks like abstractive question answering and summarization, where the encoder input is the input sequence and the decoder generates outputs autoregressively.
4. Machine Translation: BART can be used to improve machine translation decoders by incorporating pre-trained encoders and using the entire BART model as a single pretrained decoder. The new encoder parameters are learned from bitext.

使用提示词分析表格

借助 LayoutPDFReader,您可以遍历文档中的所有表格,并利用 LLM 的强大功能来分析表格 让我们查看本文档中的第 6 个表格。如果您正在使用 notebook,可以按以下方式显示该表格:

from IPython.core.display import display, HTML
HTML(doc.tables()[5].to_html())

输出的表格结构如下所示:

SQuAD 1.1 EM/F1SQuAD 2.0 EM/F1MNLI m/mmSST AccQQP AccQNLI AccSTS-B AccRTE AccMRPC AccCoLA Mcc
BERT84.1/90.979.0/81.886.6/-93.291.392.390.070.488.060.6
UniLM-/-80.5/83.487.0/85.994.5-92.7-70.9-61.1
XLNet89.0/94.586.1/88.889.8/-95.691.893.991.883.889.263.6
RoBERTa88.9/94.686.5/89.490.2/90.296.492.294.792.486.690.968.0
BART88.8/94.686.1/89.289.9/90.196.692.594.991.287.090.462.8

现在,让我们提出一个问题来分析此表格:

from llama_index.llms import OpenAI
context = doc.tables()[5].to_html()
resp = OpenAI().complete(f"read this table and answer question: which model has the best performance on squad 2.0:\n{context}")
print(resp.text)

上述问题将产生以下输出:

The model with the best performance on SQuAD 2.0 is RoBERTa, with an EM/F1 score of 86.5/89.4.

就是这样!LayoutPDFReader 还支持带有嵌套标题和标题行的表格。

以下是带有嵌套标题的示例:

from IPython.core.display import display, HTML
HTML(doc.tables()[6].to_html())
CNN/DailyMailXSum-
R1R2RLR1R2RL
---------------------
Lead-340.4217.6236.6716.301.6011.95
PTGEN (See et al., 2017)36.4415.6633.4229.709.2123.24
PTGEN+COV (See et al., 2017)39.5317.2836.3828.108.0221.72
UniLM43.3320.2140.51---
BERTSUMABS (Liu & Lapata, 2019)41.7219.3938.7638.7616.3331.15
BERTSUMEXTABS (Liu & Lapata, 2019)42.1319.6039.1838.8116.5031.27
BART44.1621.2840.9045.1422.2737.25

现在让我们问一个有趣的问题:

from llama_index.llms import OpenAI
context = doc.tables()[6].to_html()
question = "tell me about R1 of bart for different datasets"
resp = OpenAI().complete(f"read this table and answer question: {question}:\n{context}")
print(resp.text)

我们得到以下答案:

R1 of BART for different datasets:

- For the CNN/DailyMail dataset, the R1 score of BART is 44.16.
- For the XSum dataset, the R1 score of BART is 45.14.

获取原始 JSON

要获取 llmsherpa 服务返回的完整 json 并以不同方式处理它,只需获取 json 属性

doc.json