0


整合LlamaIndex与LangChain构建高级的查询处理系统

构建大型语言模型应用程序可能会颇具挑战,尤其是当我们在不同的框架(如Langchain和LlamaIndex)之间进行选择时。LlamaIndex在智能搜索和数据检索方面的性能令人瞩目,而LangChain则作为一个更加通用的应用程序框架,提供了更好的与各种平台的兼容性。

本篇文章将介绍如何将LlamaIndex和LangChain整合使用,创建一个既可扩展又可定制的代理RAG(Retrieval-Augmented Generation)应用程序,利用两种技术的强大功能,开发出能够处理复杂查询并提供精准答案的高效应用程序。

在我们继续实施之前,需要简单的介绍代理RAG的一些知识:

代理RAG是一种基于代理的RAG实现方式。与传统的一般RAG方法相比,代理RAG在自主性和决策能力方面有了显著提升。我们通过授权大型语言模型(LLM)访问多个RAG查询引擎来创建一个复杂的推理循环。每个查询引擎都作为一种工具,能根据需要被LLM调用。这种结构不仅使得执行复杂决策成为可能,还扩展了系统回答各种查询的能力,并能够更好地为用户提供最适宜的响应。

通过这种方式,代理RAG能够在提供答案的同时,考虑到信息的来源多样性和质量,从而在提供答案时实现更高的准确性和相关性。这种模型的实现,为处理复杂问题和提供创新解决方案提供了更强大的工具。

首先我们定义基本LLM和嵌入模型

  1. # LLM
  2. llm=ChatOpenAI(model_name="gpt-4-1106-preview", temperature=0, streaming=True)
  3. # Embedding Model
  4. embed_model=OpenAIEmbedding(
  5. model="text-embedding-3-small", embed_batch_size=100
  6. )
  7. # Set Llamaindex Configs
  8. Settings.llm=llm
  9. Settings.embed_model=embed_model

然后利用LlamaIndex的索引和检索功能为文档定义单独的查询引擎。

  1. #Building Indexes for each of the Documents
  2. try:
  3. storage_context=StorageContext.from_defaults(
  4. persist_dir="./storage/lyft"
  5. )
  6. lyft_index=load_index_from_storage(storage_context)
  7. storage_context=StorageContext.from_defaults(
  8. persist_dir="./storage/uber"
  9. )
  10. uber_index=load_index_from_storage(storage_context)
  11. index_loaded=True
  12. print("Index was already created. We just loaded it from the local storage.")
  13. except:
  14. index_loaded=False
  15. print("Index is not present. We need it to create it again.")
  16. ifnotindex_loaded:
  17. print("Creating Index..")
  18. # load data
  19. lyft_docs=SimpleDirectoryReader(
  20. input_files=["./data/10k/lyft_2021.pdf"]
  21. ).load_data()
  22. uber_docs=SimpleDirectoryReader(
  23. input_files=["./data/10k/uber_2021.pdf"]
  24. ).load_data()
  25. # build index
  26. lyft_index=VectorStoreIndex.from_documents(lyft_docs)
  27. uber_index=VectorStoreIndex.from_documents(uber_docs)
  28. # persist index
  29. lyft_index.storage_context.persist(persist_dir="./storage/lyft")
  30. uber_index.storage_context.persist(persist_dir="./storage/uber")
  31. index_loaded=True
  32. #Creating Query engines on top of the indexes
  33. lyft_engine=lyft_index.as_query_engine(similarity_top_k=3)
  34. uber_engine=uber_index.as_query_engine(similarity_top_k=3)
  35. print("LlamaIndex Query Engines created successfully.")

然后使用LlamaIndex的QueryEngineTool抽象类将查询引擎转换为工具,这些工具将稍后提供给LLM使用。

  1. #creating tools for each of our query engines
  2. query_engine_tools= [
  3. QueryEngineTool(
  4. query_engine=lyft_engine,
  5. metadata=ToolMetadata(
  6. name="lyft_10k",
  7. description=(
  8. "Provides information about Lyft financials for year 2021. "
  9. "Use a detailed plain text question as input to the tool."
  10. ),
  11. ),
  12. ),
  13. QueryEngineTool(
  14. query_engine=uber_engine,
  15. metadata=ToolMetadata(
  16. name="uber_10k",
  17. description=(
  18. "Provides information about Uber financials for year 2021. "
  19. "Use a detailed plain text question as input to the tool."
  20. ),
  21. ),
  22. ),
  23. ]

然后我们将LlamaIndex工具转换为与Langchain代理兼容的格式,这样就可以和Langchain 进行对接了。

  1. llamaindex_to_langchain_converted_tools= [t.to_langchain_tool() fortinquery_engine_tools]

除此以外我们还定义了一个附加的带有Web搜索功能的Langchain工具。这样可以进行页面搜索

  1. search=DuckDuckGoSearchRun()
  2. duckduckgo_tool=Tool(
  3. name='DuckDuckGoSearch',
  4. func=search.run,
  5. description='Use for when you need to perform an internet search to find information that another tool can not provide.'
  6. )
  7. langchain_tools= [duckduckgo_tool]
  8. #Combine to create final list of tools
  9. tools=llamaindex_to_langchain_converted_tools+langchain_tools

下面就是Langchain的工作了,初始化调用代理。

  1. system_context="You are a stock market expert.\
  2. You will answer questions about Uber and Lyft companies as in the persona of a veteran stock market investor."
  3. prompt=ChatPromptTemplate.from_messages(
  4. [
  5. (
  6. "system",
  7. system_context,
  8. ),
  9. ("placeholder", "{chat_history}"),
  10. ("human", "{input}"),
  11. ("placeholder", "{agent_scratchpad}"),
  12. ]
  13. )
  14. # Construct the Tools agent
  15. agent=create_tool_calling_agent(llm, tools, prompt,)
  16. # Create an agent executor by passing in the agent and tools
  17. agent_executor=AgentExecutor(agent=agent, tools=tools, verbose=True, return_intermediate_steps=True, handle_parsing_errors=True, max_iterations=10)

然就就可以进行测试了。

测试1:

  1. question = "What was Lyft's revenue growth in 2021?"
  2. response = agent_executor.invoke({"input": question})
  3. print("\nFinal Response:", response['output'])

代理正确地调用了lyft_10k查询引擎工具。

测试2:

  1. question = "Is Uber profitable?"
  2. response = agent_executor.invoke({"input": question})
  3. print("\nFinal Response:", response['output'])

代理正确调用了uber_10k查询引擎工具。

测试3:

  1. question = "List me the names of Uber's board of directors."
  2. response = agent_executor.invoke({"input": question})
  3. print("\nFinal Response:", response['output'])

我们这个信息超出了任何检索工具的范围,所以代理决定调用外部搜索工具,然后返回结果。

可以看到,我们的例子完美的结合了2者的优势,通过引入多个代理可以进一步提高系统的效率和精准度。每个代理可以专门处理同一领域内的不同文档子集,使得信息检索更为精细和专业。

我们可以设定一名代理来担任这些代理的协调者或主管。这名负责监控和调节各个代理的活动,确保信息流动的协调一致,并对整体查询过程进行优化。这种层次化的管理结构不仅优化了数据处理流程,也提高了响应速度和准确性,使得整个系统在处理复杂查询时更加高效和可靠。

通过这种方法,我们可以实现一个更加动态和适应性强的RAG系统,能够更好地满足不断变化的用户需求和应对多样化的信息挑战。希望本文能帮助你了解如何有效地整合LlamaIndex和LangChain,以构建一个高效、可扩展的代理RAG应用程序。

“整合LlamaIndex与LangChain构建高级的查询处理系统”的评论:

还没有评论