9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Bedrockの開発体験をバク上げするツールを発見しました(画像多め)

Posted at

ここにBedrockのConverse APIを呼び出すサンプルがあります。

モデル名とメッセージをセットしてリクエストを送信しています。

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Claude 3 Haiku.
model_id = "anthropic.claude-3-haiku-20240307-v1:0"

# 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 = client.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)

サンプルはシンプルですので、コールドリーディングは難しくないと思います。

ただ、

このコードを何も見ずに書けますか??

残念ながら私は無理です。毎回サンプルコードを検索して、コピペしながら作ってました。

この開発体験をどうにかできないかなぁと思っていたところ、良いツールを発見しましたのでご紹介します。

boto3-stubs

boto3のコード補完を便利にする「boto3-stubs」というツールを使用します。

ドキュメントの冒頭には以下のように記載されています。型アノテーションを行うツールで、まさに私が求めていたものでした。

Auto-generated documentation for boto3 type annotations package boto3-stubs.

Generated by mypy-boto3-builder.

Bedrock専用ではなく、boto3で提供されている様々なAWSサービスに対応しています。

使い方の解説

導入

まずは専用の仮想環境を用意し、boto3とboto3-stubsをインストールします。

Shell
python3 -m venv .venv
source .venv/bin/activate

pip3 install boto3 boto3-stubs[bedrock-runtime]

boto3-stubsはサービスごとに分割されてインストールすることができます。BedrockやBedrockAgent、BedrockAgentRuntimeも別に用意されているのでこれらもインストールする場合は以下のようになります。

Shell
pip3 install boto3 boto3-stubs[bedrock,bedrock-runtime,bedrock-agent,bedrock-agent-runtime]

導入は以上です。

リクエストを構築

では、まず以下のように記述してみましょう。

import boto3

client = boto3.client("bedrock-runtime")

この状態で.clientの部分にマウスカーソルを合わせると形の定義が表示されます。

image.png

もし、ライブラリーの検出がうまく行っていない場合は、Python拡張機能がインストールされているか確認してください。

そのうえでコマンドパレットに「pytthon: select interpreter」と入力し、ライブラリーを導入した環境を選択してください。

「client」変数にマウスカーソルを合わせると「BedrockRuntimeClient」という型が検出されていることがわかります。

image.png

「client.」まで記述し、補完(Ctrl + スペース)を入力すると、関数が表示されます。

image.png

❗️❗️❗️

最高です。

試しにConverse APIを呼び出してみましょう。
パラメーターが確認できます。

image.png

modelIdに指定するモデルIDは残念ながら補完されませんので、頑張って手入力します。

そして、「messages=」を補完を活用して入力し、マウスカーソルを「messages」の上に合わせると、パラメーターの型が「Sequence[MessageUnionTypeDef]」であることが確認できます。

image.png

Sequenceなので、「[]」とその中にオブジェクトを意味する「{}」を入力します。

image.png

ここで補完(Ctrl + スペース)を入力すると、指定可能なオブジェクトのキーが表示されます。

image.png

❗️❗️❗️

キーだけではなく値も補完が効きます。

image.png

この調子で記述できるので、「サンプルコードを探してコピペ」をしなくてもリクエストを作成できます!!!

image.png

「content」のタイプも選ぶだけ

image.png

テキストメッセージを指定するだけ

image.png

ドキュメントの場合、指定できるファイルタイプもわかっちゃいます。

image.png

これは、便利!!

レスポンスの値を取得

リクエストだけではなく、レスポンスも型が利用できます。

converse APIの呼び出し結果を受け取る「response」は「ConverseResponseTypeDef」という型が適用されます。

image.png

キーが一覧でリストアップされます。

image.png

補完を頼りにtextを取得する事ができました。

image.png

ストリームレスポンスの場合も正しく型が認識されます。

image.png

ストリームを処理する作法は少しわかっておく必要はありますが、forループの中でも型補完が行えます。

image.png

こちらも無事、textを取得することができました。

image.png

まとめ

これは必須ですね!Converse APIとの相性も抜群です!!


私が知らなかっただけで、すでにいろいろなところで紹介されていました。

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?