提升LangChain查询分析器性能的秘诀:使用示例指导LLM
随着查询分析的复杂性增加,语言模型(LLM)在某些场景下可能难以准确理解需要如何响应。为了提高性能,我们可以在提示中添加示例,以引导LLM的输出。本文将详细介绍如何为我们在快速入门中构建的LangChain YouTube视频查询分析器添加示例。
1. 引言
在复杂的查询分析任务中,LLM可能会遇到难以准确理解用户问题的情况。通过在提示中加入示例,我们可以显著提高模型的响应质量。本篇文章将介绍在LangChain框架下,通过添加示例来优化查询分析器的步骤。
2. 主要内容
2.1 设置环境
首先,安装所需的依赖包:
# %pip install -qU langchain-core langchain-openai
接着,设置环境变量。这里我们使用OpenAI接口:
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()
# Optional, uncomment to trace runs with LangSmith. Sign up here: https://smith.langchain.com.
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()
2.2 定义查询架构
我们定义一个查询架构来输出模型结果,并且增加一个sub_queries字段,其中包含从顶层问题派生出来的更具体的问题。
from typing import List, Optional
from langchain_core.pydantic_v1 import BaseModel, Field
sub_queries_description = """\
If the original question contains multiple distinct sub-questions, \
or if there are more generic questions that would be helpful to answer in \
order to answer the original question, write a list of all relevant sub-questions. \
Make sure this list is comprehensive and covers all parts of the original question. \
It's ok if there's redundancy in the sub-questions. \
Make sure the sub-questions are as narrowly focused as possible."""
class Search(BaseModel):
"""Search over a database of tutorial videos about a software library."""
query: str = Field(
...,
description="Primary similarity search query applied to video transcripts.",
)
sub_queries: List[str] = Field(
default_factory=list, description=sub_queries_description
)
publish_year: Optional[int] = Field(None, description="Year video was published")
2.3 查询生成
以下是如何使用LangChain创建查询分析器的代码:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
system = """You are an expert at converting user questions into database queries. \
You have access to a database of tutorial videos about a software library for building LLM-powered applications. \
Given a question, return a list of database queries optimized to retrieve the most relevant results.
If there are acronyms or words you are not familiar with, do not try to rephrase them."""
prompt = ChatPromptTemplate.from_messages(
[
("system", system),
MessagesPlaceholder("examples", optional=True),
("human", "{question}"),
]
)
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
structured_llm = llm.with_structured_output(Search)
query_analyzer = {"question": RunnablePassthrough()} | prompt | structured_llm
# 使用API代理服务提高访问稳定性
query_analyzer.invoke(
"what's the difference between web voyager and reflection agents? do both use langgraph?"
)
2.4 添加示例和调优提示
添加示例以引导LLM生成更精细的查询:
examples = []
question = "What's chat langchain, is it a langchain template?"
query = Search(
query="What is chat langchain and is it a langchain template?",
sub_queries=["What is chat langchain", "What is a langchain template"],
)
examples.append({"input": question, "tool_calls": [query]})
# 更多示例...
import uuid
from typing import Dict
from langchain_core.messages import (
AIMessage,
BaseMessage,
HumanMessage,
SystemMessage,
ToolMessage,
)
def tool_example_to_messages(example: Dict) -> List[BaseMessage]:
messages: List[BaseMessage] = [HumanMessage(content=example["input"])]
openai_tool_calls = []
for tool_call in example["tool_calls"]:
openai_tool_calls.append(
{
"id": str(uuid.uuid4()),
"type": "function",
"function": {
"name": tool_call.__class__.__name__,
"arguments": tool_call.json(),
},
}
)
messages.append(
AIMessage(content="", additional_kwargs={"tool_calls": openai_tool_calls})
)
tool_outputs = example.get("tool_outputs") or [
"You have correctly called this tool."
] * len(openai_tool_calls)
for output, tool_call in zip(tool_outputs, openai_tool_calls):
messages.append(ToolMessage(content=output, tool_call_id=tool_call["id"]))
return messages
example_msgs = [msg for ex in examples for msg in tool_example_to_messages(ex)]
from langchain_core.prompts import MessagesPlaceholder
query_analyzer_with_examples = (
{"question": RunnablePassthrough()}
| prompt.partial(examples=example_msgs)
| structured_llm
)
# 使用API代理服务提高访问稳定性
query_analyzer_with_examples.invoke(
"what's the difference between web voyager and reflection agents? do both use langgraph?"
)
3. 常见问题和解决方案
在尝试添加示例时,你可能会遇到以下问题:
- 示例不够具体:确保示例能够涵盖多种输入场景,避免简单概括。
- API调用失败:考虑使用API代理服务来提高访问稳定性。
4. 总结和进一步学习资源
通过在提示中加入示例,我们可以显著提高查询分析器的准确性和有效性。想要进一步提升查询分析能力,建议持续调整和测试示例内容。
推荐资源
5. 参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---