
如何高效爬取全球新闻网站 – 整合Scrapy、Selenium与Mediastack API实现自动化新闻采集
在当前的AI应用场景中,检索增强生成(RAG)已经成为处理和检索大规模文档的重要技术。然而,在处理包含大量表格的文档时,传统RAG方案往往会遇到准确性和效率方面的挑战。本文将深入探讨如何通过优化RAG实现高效搜索定位,特别是在处理复杂表格数据时的实践方案。
在处理表格丰富的文档时,传统RAG实现经常遇到以下问题:
为了解决上述问题,我们提出了一个完整的优化方案,包含四个关键步骤:
使用专业的文档解析工具进行表格提取是第一步。以下是具体实现代码:
!apt-get -qq install poppler-utils tesseract-ocr
%pip install -q --user --upgrade pillow
%pip install -q --upgrade unstructured["all-docs"]
%pip install langchain-openai
%pip install langchain
from unstructured.partition.pdf import partition_pdf
elements = partition_pdf('./doc.pdf',
strategy="hi_res",
chunking_strategy="by_title",
max_characters=2500,
new_after_n_chars=2300)
为每个表格生成语义丰富的描述,增加检索时的上下文信息:
def get_table_description(table_content, document_context):
prompt = f"""
Given the following table and its context from the original document,
provide a detailed description of the table. Then, include the table in markdown format.
Original Document Context:
{document_context}
Table Content:
{table_content}
"""
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant that describes tables and formats them in markdown."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
将处理后的表格内容进行向量化存储:
# 创建嵌入
embedding_encoder = OpenAIEmbeddingEncoder(
config=OpenAIEmbeddingConfig(
api_key=os.getenv("OPENAI_API_KEY"),
model_name="text-embedding-3-small"
)
)
elements = embedding_encoder.embed_documents(elements=elements)
# 存储到向量数据库
schema = {
'columns': [
{'name': 'id', 'pytype': 'str'},
{'name': 'text', 'pytype': 'str'},
{'name': 'metadata', 'pytype': 'dict'},
{'name': 'embedding', 'vectorIndex': {
'dims': 1536,
'type': 'flat',
'metric': 'L2'
}}
]
}
构建高效的检索链条:
# 设置检索链
qabot = RetrievalQA.from_chain_type(
chain_type="stuff",
llm=ChatOpenAI(model="gpt-4"),
retriever=vecdb_kdbai.as_retriever(search_kwargs=dict(k=5)),
return_source_documents=True
)
def RAG(query):
return qabot.invoke(dict(query=query))["result"]
通过实际案例测试,优化后的RAG系统在以下方面表现出显著提升:
示例查询:
RAG("what is the three month costs and expenses for 2023?")
# 输出:2023年第二季度的成本和支出为226.07亿美元。
在实际应用中,为实现RAG的高效搜索定位,建议注意以下几点:
通过实施上述优化方案,我们成功实现了RAG的高效搜索定位,特别是在处理表格丰富的文档时。该方案不仅提高了检索准确率,还显著改善了系统的响应质量。随着技术的不断发展,这种优化方案将继续演进,为更多应用场景提供更好的支持。
未来,我们还可以探索更多优化方向,如:
通过这些持续的优化努力,RAG技术将在文档处理和信息检索领域发挥更大的作用。