本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
本節將引導您嘗試使用 Amazon Bedrock 中的一些常見操作Python, AWS 以測試您的許可和身分驗證是否設定正確。執行下列範例之前,您應該檢查您是否符合下列先決條件:
先決條件
-
您有 AWS 帳戶 和具有身分驗證設定的使用者或角色,以及 Amazon Bedrock 的必要許可。否則,請遵循 中的步驟 API 入門。
-
您已請求存取Amazon Titan Text G1 - Express模型。否則,請遵循 中的步驟請求存取 Amazon Bedrock 基礎模型。
-
您已安裝並設定適用於 Python 的 AWS SDK (Boto3) 的身分驗證。若要安裝 Boto3,請遵循 Boto3 文件中的 Quickstart
步驟。請遵循 中的步驟,驗證您已設定登入資料以使用 Boto3取得憑證以授予程式設計存取。
測試您的許可是否已針對 Amazon Bedrock 正確設定,並使用您透過適當許可設定的使用者或角色。
Amazon Bedrock 文件也包含其他程式設計語言的程式碼範例。如需詳細資訊,請參閱使用 AWS SDKs Amazon Bedrock 程式碼範例。
列出 Amazon Bedrock 必須提供的基礎模型
下列範例使用 Amazon Bedrock 用戶端執行 ListFoundationModels 操作。 ListFoundationModels
會列出您區域中 Amazon Bedrock 中可用的基礎模型 (FMs)。執行下列適用於 Python 的 SDK 指令碼來建立 Amazon Bedrock 用戶端,並測試 ListFoundationModels 操作:
"""
Lists the available Amazon Bedrock models.
"""
import logging
import json
import boto3
from botocore.exceptions import ClientError
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def list_foundation_models(bedrock_client):
"""
Gets a list of available Amazon Bedrock foundation models.
:return: The list of available bedrock foundation models.
"""
try:
response = bedrock_client.list_foundation_models()
models = response["modelSummaries"]
logger.info("Got %s foundation models.", len(models))
return models
except ClientError:
logger.error("Couldn't list foundation models.")
raise
def main():
"""Entry point for the example. Uses the AWS SDK for Python (Boto3)
to create an Amazon Bedrock client. Then lists the available Bedrock models
in the region set in the callers profile and credentials.
"""
bedrock_client = boto3.client(service_name="bedrock")
fm_models = list_foundation_models(bedrock_client)
for model in fm_models:
print(f"Model: {model['modelName']}")
print(json.dumps(model, indent=2))
print("---------------------------\n")
logger.info("Done.")
if __name__ == "__main__":
main()
如果指令碼成功,回應會傳回 Amazon Bedrock 中可用的基礎模型清單。
將文字提示提交至模型,並使用 InvokeModel 產生文字回應
下列範例使用 Amazon Bedrock 用戶端執行 InvokeModel 操作。 InvokeModel
可讓您提交提示以產生模型回應。執行下列適用於 Python 的 SDK 指令碼來建立 Amazon Bedrock 執行期用戶端,並使用 操作產生文字回應:
# Use the native inference API to send a text message to Amazon Titan Text G1 - Express.
import boto3
import json
from botocore.exceptions import ClientError
# Create an Amazon Bedrock Runtime client.
brt = boto3.client("bedrock-runtime")
# Set the model ID, e.g., Amazon Titan Text G1 - Express.
model_id = "amazon.titan-text-express-v1"
# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."
# Format the request payload using the model's native structure.
native_request = {
"inputText": prompt,
"textGenerationConfig": {
"maxTokenCount": 512,
"temperature": 0.5,
"topP": 0.9
},
}
# Convert the native request to JSON.
request = json.dumps(native_request)
try:
# Invoke the model with the request.
response = brt.invoke_model(modelId=model_id, body=request)
except (ClientError, Exception) as e:
print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
exit(1)
# Decode the response body.
model_response = json.loads(response["body"].read())
# Extract and print the response text.
response_text = model_response["results"][0]["outputText"]
print(response_text)
如果命令成功,回應會傳回模型所產生的文字,以回應提示。
將文字提示提交至模型,並使用 Converse 產生文字回應
下列範例使用 Amazon Bedrock 用戶端執行 Converse 操作。我們建議在支援InvokeModel
時使用 Converse
操作,因為它會統一跨 Amazon Bedrock 模型的推論請求,並簡化多轉對話的管理。執行下列適用於 Python 的 SDK 指令碼來建立 Amazon Bedrock 執行期用戶端,並使用 Converse
操作產生文字回應:
# Use the Conversation API to send a text message to Amazon Titan Text G1 - Express.
import boto3
from botocore.exceptions import ClientError
# Create an Amazon Bedrock Runtime client.
brt = boto3.client("bedrock-runtime")
# Set the model ID, e.g., Amazon Titan Text G1 - Express.
model_id = "amazon.titan-text-express-v1"
# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
{
"role": "user",
"content": [{"text": user_message}],
}
]
try:
# Send the message to the model, using a basic inference configuration.
response = brt.converse(
modelId=model_id,
messages=conversation,
inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
)
# Extract and print the response text.
response_text = response["output"]["message"]["content"][0]["text"]
print(response_text)
except (ClientError, Exception) as e:
print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
exit(1)
如果命令成功,回應會傳回模型所產生的文字,以回應提示。