跳至內容

當我在 Amazon Bedrock 中使用 LLM 時,如何防止 Python 中的讀取逾時?

2 分的閱讀內容
0

當我使用 Amazon Bedrock 中的大型語言模型 (LLM) 來產生文字時,出現讀取逾時錯誤。

解決方法

**注意:**如果您在執行 AWS Command Line Interface (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 組態來執行個體化 Python (Boto3) 用戶端的 SDK。然後,將此組態作為用戶端參數傳遞給可呼叫模型類別。

若要增加將 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 在回傳讀取逾時異常前,等待伺服器回應的時間長度。

**注意:**LLM (如 Anthropic Claude 3.7 Sonnet) 回傳回應可能需要超過 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,將輸入文字替換為您的文字。