0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[AWS]StrandsAgentをとりあえず使ってみた

Posted at

はじめに

AIエージェント開発の複雑さに悩んでいませんか?Strands Agents SDKを使えば、わずか数行のコードで強力なAIエージェントを作成できます。このブログでは、テキスト操作機能を持つシンプルなエージェントを実装した例を紹介します。

Strands Agents SDKとは?

Strands Agents SDKは、AIエージェント開発のためのPythonライブラリです。モデル駆動型アプローチを採用し、以下の特徴があります:

  • 軽量&柔軟:シンプルでカスタマイズ可能なエージェントループ
  • モデルに依存しない:Amazon Bedrock、Anthropic、OpenAIなど多様なモデルプロバイダーをサポート
  • 高度な機能:マルチエージェントシステム、自律型エージェント、ストリーミングサポート

サンプルコードの解説

今回紹介するサンプルコードでは、テキスト処理ツールを持つAIエージェントを作成します。

1. カスタムツールの定義

@tool
def word_count(text: str) -> int:
    """テキスト内の単語数をカウントします。"""
    return len(text.split())

@tool
def character_count(text: str) -> int:
    """テキスト内の文字数をカウントします(スペースを除く)。"""
    return len(text.replace(" ", ""))

@tool
def reverse_text(text: str) -> str:
    """テキストを逆順にします。"""
    return text[::-1]

@toolデコレータを使って、AIエージェントが使用するツールを簡単に定義できます。ドキュメント文字列はAIがツールの目的を理解するために使われます。

2. エージェントの作成

def create_simple_agent() -> Optional[Agent]:
    # 試すモデル(inference profileを含む)
    models_to_try = [
        ("us.anthropic.claude-3-7-sonnet-20250219-v1:0", "Claude 3.7 Sonnet"),
        ("us.anthropic.claude-3-5-sonnet-20241022-v2:0", "Claude 3.5 Sonnet v2"),
        ("us.anthropic.claude-3-haiku-20240307-v1:0", "Claude 3 Haiku"),
        ("us.amazon.nova-micro-v1:0", "Nova Micro"),
    ]

    for model_id, model_name in models_to_try:
        try:
            # Bedrockモデルを設定
            bedrock_model = BedrockModel(
                model_id=model_id,
                region_name="us-east-1",
                temperature=0.3,
                max_tokens=1000,
                streaming=True,
            )

            # エージェントを作成
            agent = Agent(
                model=bedrock_model,
                tools=[word_count, character_count, reverse_text],
            )

            # 動作確認
            agent("Hello")
            return agent

        except Exception as e:
            continue

    return None

このコードは複数のモデルを順番に試み、最初に成功したモデルでエージェントを作成します。これにより、利用可能なモデルに自動的に適応します。

3. エージェントの実行

# サンプルクエリ
queries = [
    "Hello world from Strands Agents の単語数を教えて",
    "Python is awesome の文字数は?(スペースを除く)",
    "Strands Agents SDK というテキストを逆順にして",
    "AI agents are the future という文の単語数と文字数を両方教えて",
]

for query in queries:
    response = agent(query)
    print(f"🤖 回答: {response}")

エージェントは自然言語で指示を受け、適切なツールを選択して実行します。日本語と英語の混合クエリにも対応可能です。

実行結果例

📝 質問 1: Hello world from Strands Agents の単語数を教えて
🤖 回答: "Hello world from Strands Agents"の単語数は5です。

📝 質問 2: Python is awesome の文字数は?(スペースを除く)
🤖 回答: "Python is awesome"のスペースを除いた文字数は15文字です。

📝 質問 3: Strands Agents SDK というテキストを逆順にして
🤖 回答: "Strands Agents SDK"を逆順にすると "KDS stnegA sdnartS" になります。

📝 質問 4: AI agents are the future という文の単語数と文字数を両方教えて
🤖 回答: "AI agents are the future"の単語数は5語、スペースを除いた文字数は16文字です。

使い方のポイント

  1. コマンドライン引数でのクエリpython simple_example.py "あなたのクエリ" で直接質問できます
  2. モデルの選択:複数のモデルを定義し、利用可能なものから自動選択
  3. ストリーミングサポートstreaming=True でリアルタイムレスポンスが可能

まとめ

Strands Agents SDKを使えば、わずか数十行のコードで機能的なAIエージェントを作成できます。カスタムツールの定義からモデル選択、エージェント作成まで、すべてがシンプルで直感的です。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?