AWS BedrockのAPIを実行してみた

Pocket

Amazon BedrockのAPIを実行してみた

AWS Bedrockのテスト環境を作ってもらったのでPythonを使ってAPIを使ってアクセスしてみました。
しかし、公式の手順だと上手くいかないところがあったので、実行までの道のりをまとめてみました。

環境について

環境については次の通りです。

  • 実行環境:Windows 11 pro
  • 実行言語:Python 3.11.4
  • AWSへのアクセス:IAMのアクセスキーによる管理

また、AWSのプロファイルにはdefaultも含めて3つ登録されています。

準備したこと

  • AWS Bedrockの準備
  • Boto3(PythonからAWSの各種サービスを実行するライブラリ)をインストールしました
    • pip install boto3
    • バージョンは1.28.70でした
  • AWS CLIをバージョンアップしました
    • aws-cli/2.13.8ではbedrockのコマンドが使用できませんでした
    • aws-cli/2.13.28にバージョンアップ後、bedrockのコマンドが実行できました
    • https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/getting-started-install.html

AWSのサンプルコードを実行してみた

まずは公式のサンプルコードをそのまま実行してみました。

  • https://docs.aws.amazon.com/bedrock/latest/userguide/api-methods-run-inference.html

あら…エラーです。
bedrock.invoke_modelを実行した際にトークンの認証で失敗していました。

An error occurred (UnrecognizedClientException) when calling the InvokeModel operation: The security token included in the request is invalid.

プロファイルを切り替えていないからですね…
次のように変更しました。

bedrock = boto3.client(service_name='bedrock-runtime')

↓ Bedrockテスト用アカウントのプロファイルを指定しました。

session = boto3.Session(profile_name='bedrock-test')
bedrock = session.client(service_name='bedrock-runtime')

もう一度実行してみましょう。

…別のエラーが出ました。

An error occurred (ResourceNotFoundException) when calling the InvokeModel operation: Could not resolve the foundation model from the provided model identifier.

んん?モデルIDが解決できなかった…?

コマンドプロンプトからAWS CLIを使ってモデル一覧を見てみます。

aws bedrock list-foundation-models --profile bedrock-test

すると…

{
    "modelSummaries": [
        {
            "modelArn": "arn:aws:bedrock:ap-northeast-1::foundation-model/amazon.titan-text-express-v1",
            "modelId": "amazon.titan-text-express-v1",
            "modelName": "Titan Text G1 - Express",
            "providerName": "Amazon",
            "inputModalities": [
                "TEXT"
            ],
            "outputModalities": [
                "TEXT"
            ],
            "responseStreamingSupported": true,
            "customizationsSupported": [],
            "inferenceTypesSupported": [
                "ON_DEMAND"
            ]
        },
        {
            "modelArn": "arn:aws:bedrock:ap-northeast-1::foundation-model/amazon.titan-embed-text-v1",
            "modelId": "amazon.titan-embed-text-v1",
            "modelName": "Titan Embeddings G1 - Text",
            "providerName": "Amazon",
            "inputModalities": [
                "TEXT"
            ],
            "outputModalities": [
                "EMBEDDING"
            ],
            "responseStreamingSupported": true,
            "customizationsSupported": [],
            "inferenceTypesSupported": [
                "ON_DEMAND"
            ]
        },
        {
            "modelArn": "arn:aws:bedrock:ap-northeast-1::foundation-model/anthropic.claude-instant-v1",
            "modelId": "anthropic.claude-instant-v1",
            "modelName": "Claude Instant",
            "providerName": "Anthropic",
            "inputModalities": [
                "TEXT"
            ],
            "outputModalities": [
                "TEXT"
            ],
            "responseStreamingSupported": true,
            "customizationsSupported": [],
            "inferenceTypesSupported": [
                "ON_DEMAND"
            ]
        }
    ]
}

どうやら claude-v2 は使用できずに claude-instant-v1 までのようです。
そういえば、モデルの準備をした際にclaude-v2は指定出来てませんでした。

公式のガイドを見てみますと
https://docs.aws.amazon.com/bedrock/latest/userguide/setting-up.html

また、米国東部 (バージニア北部)、米国西部 (オレゴン)、アジアパシフィック (シンガポール) の Amazon Bedrock コンソールにアクセスすることもできます。

とあります。

APIを使用する際にはリージョンを変更するか、デフォルトのリージョンで使用可能なモデルに変更することで動きそうです。

コードを修正してみよう

まず、リージョンを変更してみます。
clientメソッドの引数にregion_nameで指定します。

session = boto3.Session(profile_name='bedrock-test')
bedrock = session.client(service_name='bedrock-runtime')

session = boto3.Session(profile_name='bedrock-test')
bedrock = session.client(service_name='bedrock-runtime', region_name='us-east-1')

実行してみましょう。

Here is a simple explanation of black holes for 8th graders:

- A black hole is a region in space where gravity is so strong that nothing can escape from it, even light. This region is called the event horizon.

- Black holes form when massive stars run out of fuel and collapse. The gravity of the star gets so intense that it crushes the star down into a tiny point called a singularity.

- At the singularity, the gravity is infinitely strong. That's why nothing can escape once it crosses the event horizon.

- Black holes cannot be directly observed because they emit no light. But we can detect them by observing their gravitational effects on nearby stars and gas clouds.

- Matter spirals into a black hole and heats up, producing x-rays and other radiation that we can detect with telescopes. This is how we find some black holes.

- Black holes do not "suck" matter in. Things have to get very close to be captured by the black hole's gravity.

- There are different sizes of black holes. Stellar black holes form from collapsing stars. Supermassive black holes of millions to billions of solar masses exist at the center of most galaxies.

- Black holes themselves do not "destroy" matter. But the intense gravity can rip matter apart as it approaches the singularity.

- If you fell into a black hole, you would be stretched

レスポンスが返ってきました!

リージョンは戻して、モデル名を変更してみます。

modelId = 'anthropic.claude-v2'

modelId = 'anthropic.claude-instant-v1'

これで実行してみます。

Here is how I would explain black holes to 8th graders:

A black hole is a place in space where gravity is so strong that nothing, not even light, can escape from it. It forms when a very massive star dies and collapses inward upon itself.

Imagine a giant star, much bigger than our sun. As it runs out of fuel, its core starts to collapse under its own intense gravity. The star gets smaller and smaller, but its mass stays the same. This makes its gravity get stronger and stronger.

Eventually, the gravity becomes so powerful that it squeezes the core of the star down to an incredibly tiny size - smaller than a city! But even though it's now tiny, its mass and gravity are enormous. This tiny super-dense object is called a black hole.

Anything that gets too close to a black hole, including light itself, gets pulled inward by its powerful gravity. The gravity is so strong that not even light can escape. That's why it's called a "black" hole - because you can't see anything inside it or escaping from it.

Scientists think there could be many black holes out there in space. The intense gravity of a black hole warps space and time around it in strange ways. It's one of the weirdest and most extreme objects in the entire universe!

So in summary - a black hole is formed when a giant star collapses under

先ほどとは違う内容でレスポンスが返ってきました。
これで無事にAPIを実行することが出来ました。

まとめ

BedrockのAPIを実行する際には、

  • 実行するアカウントのプロファイルを確認し、必要なら指定すること
  • 実行するリージョンで使用可能なモデルを確認し、指定すること

以上の2点に注意してみてください。

Pocket

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です