

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Jalankan contoh permintaan Amazon Bedrock API melalui AWS SDK for Python (Boto3)
<a name="getting-started-api-ex-python"></a>

Bagian ini memandu Anda untuk mencoba beberapa operasi umum di Amazon Bedrock dengan AWS Python menguji apakah izin dan otentikasi Anda diatur dengan benar. Sebelum Anda menjalankan contoh berikut, Anda harus memeriksa apakah Anda telah memenuhi prasyarat berikut:

**Prasyarat**
+ Anda memiliki Akun AWS dan pengguna atau peran dengan pengaturan otentikasi dan izin yang diperlukan untuk Amazon Bedrock. Jika tidak, ikuti langkah-langkahnya di[Memulai dengan API](getting-started-api.md).
+ Anda telah menginstal dan menyiapkan otentikasi untuk AWS SDK for Python (Boto3). Untuk menginstal Boto3, ikuti langkah-langkah di [Quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) dalam dokumentasi Boto3. Verifikasi bahwa Anda telah menyiapkan kredensional Anda untuk menggunakan Boto3 dengan mengikuti langkah-langkah di. [Dapatkan kredensil untuk memberikan akses terprogram](getting-started-api.md#gs-grant-program-access)

Uji apakah izin Anda diatur dengan benar untuk Amazon Bedrock, menggunakan pengguna atau peran yang Anda atur dengan izin yang tepat. 

Dokumentasi Amazon Bedrock juga menyertakan contoh kode untuk bahasa pemrograman lainnya. Untuk informasi selengkapnya, lihat [Contoh kode untuk Amazon Bedrock menggunakan AWS SDKs](service_code_examples.md).

**Topics**
+ [

## Buat daftar model fondasi yang ditawarkan Amazon Bedrock
](#getting-started-api-ex-python-listfm)
+ [

## Kirim prompt teks ke model dan hasilkan respons teks dengan InvokeModel
](#getting-started-api-ex-python-invoke-text)
+ [

## Kirim prompt teks ke model dan hasilkan respons teks dengan Converse
](#getting-started-api-ex-python-converse)

## Buat daftar model fondasi yang ditawarkan Amazon Bedrock
<a name="getting-started-api-ex-python-listfm"></a>

Contoh berikut menjalankan [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html)operasi menggunakan klien Amazon Bedrock. `ListFoundationModels`mencantumkan model dasar (FMs) yang tersedia di Amazon Bedrock di Wilayah Anda. Jalankan SDK berikut untuk skrip Python untuk membuat klien Amazon Bedrock dan menguji operasinya: [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html)

```
"""
Lists the available Amazon Bedrock models in an &AWS-Region;.
"""
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. Change aws_region to the &AWS-Region;
    that you want to use."""
   
    aws_region = "us-east-1"

    bedrock_client = boto3.client(service_name="bedrock", region_name=aws_region)
    
    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()
```

Jika skrip berhasil, respons mengembalikan daftar model dasar yang tersedia di Amazon Bedrock.

## Kirim prompt teks ke model dan hasilkan respons teks dengan InvokeModel
<a name="getting-started-api-ex-python-invoke-text"></a>

Contoh berikut menjalankan [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)operasi menggunakan klien Amazon Bedrock. `InvokeModel`memungkinkan Anda mengirimkan prompt untuk menghasilkan respons model. Jalankan skrip SDK for Python berikut untuk membuat klien runtime Amazon Bedrock dan menghasilkan respons teks dengan operasi: ``

```
# 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)
```

Jika perintah berhasil, respons mengembalikan teks yang dihasilkan oleh model sebagai respons terhadap prompt.

## Kirim prompt teks ke model dan hasilkan respons teks dengan Converse
<a name="getting-started-api-ex-python-converse"></a>

Contoh berikut menjalankan operasi [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) menggunakan klien Amazon Bedrock. Sebaiknya gunakan `Converse` operasi lebih `InvokeModel` saat didukung, karena ini menyatukan permintaan inferensi di seluruh model Amazon Bedrock dan menyederhanakan pengelolaan percakapan multi-putaran. Jalankan skrip SDK for Python berikut untuk membuat klien runtime Amazon Bedrock dan menghasilkan respons teks dengan operasi: `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)
```

Jika perintah berhasil, respons mengembalikan teks yang dihasilkan oleh model sebagai respons terhadap prompt.