当我在 Amazon Bedrock 中使用大型语言模型 (LLM) 生成文本时,我收到了读取超时错误。
解决方案
**注意:**如果您在运行 AWS 命令行界面 (AWS CLI) 命令时收到错误,请参阅 AWS CLI 错误故障排除。此外,请确保您使用的是最新版本的 AWS CLI。
当您在 Amazon Bedrock 中使用大型语言模型 (LLM) 生成文本时,您可能会收到读取超时错误。当 AWS SDK for Python (Boto3) 客户端查询 LLM,但在 botocore 的默认读取超时期限内没有收到响应时,将会出现超时错误。要解决读取超时错误,请增加读取超时时间或使用流式传输 API。
增加读取超时时间
最佳做法是将 read_timeout 值设置为足够大,以允许您的查询完成。从较大的值(例如 3,600 秒)开始,然后调整此持续时间,直到不再出现超时错误为止。要增加 read_timeout 值,请运行类似于以下示例代码的代码。有关详细信息,请参阅 botocore.config 中的 read_timeout 参数。
from boto3 import client
from botocore.config import Config
config = Config(read_timeout=1000)
client = client(service_name='bedrock-runtime',
config=config)
**注意:**请将 1000 替换为您的超时值。
如果您使用第三方库,请先使用 botocore 配置实例化 SDK for Python (Boto3) 客户端。然后,将此配置作为客户端参数传递给可调用模型类。
要在将 Boto3 客户端传递给第三方库时增加读取超时值,请运行类似于以下示例的代码:
from boto3 import client
from botocore.config import Config
from langchain_aws import ChatBedrock
config = Config(read_timeout=1000)
client = client(service_name='bedrock-runtime',
config=config)
llm = ChatBedrock(model_id="anthropic.claude-3-5-sonnet-20240620-v1:0",
client=client)
上述示例显示读取超时时间设置为 1,000 秒。读取超时期限指定了 botocore 在返回读取超时异常之前等待服务器响应的时间。
**注意:**诸如 Anthropic Claude 3.7 Sonnet 之类的 LLM 可能需要超过 60 秒才能返回响应。对于 Anthropic Claude 3.7 Sonnet,最佳做法是将超时值设置为至少 3,600 秒。
使用 ConverseStream 流式传输响应
如果需要处理长响应或向用户提供部分结果,请使用 ConverseStream API 操作来接收生成的令牌。ConverseStream API 操作会在令牌生成时返回令牌,这有助于避免长响应导致的超时。
要使用 ConverseStream API 操作,请运行类似于以下示例的代码:
import json
from boto3 import client
from botocore.config import Config
# Configure the client
config = Config()
client = client(service_name='bedrock-runtime', config=config)
# Create request parameters
request = {
"modelId": "anthropic.claude-3-5-sonnet-20240620-v1:0",
"messages": [
{
"role": "user",
"content": [
{
"text": "Could you write very long story?"
}
]
}
]
}
# Call the streaming API
response = client.converse_stream(
modelId=request["modelId"],
messages=request["messages"]
)
# Process the streaming response
for event in response['stream']:
if 'contentBlockDelta' in event:
print(event['contentBlockDelta']['delta']['text'], end='')
**注意:**请将 modelID 替换为您的模型 ID,将输入 text 替换为您的文本。