Strands Agents: Model-drivenアプローチでAIエージェント開発を簡素化

Strands Agentsのチュートリアルへようこそ!Strandsは、AIエージェントの作成を簡素化するAWS提供の強力なオープンソースPython SDKです。これはモデルに依存しない設計となっており、Amazon Bedrock、OpenAI、Anthropic、さらにはローカルモデルなど、さまざまなLarge Language Models (LLMs) を使用することができます。

このノートブックでは、Strands Agentsの基本概念を学び、タスクを実行するためにツールを使用できるシンプルで機能的なエージェントを構築します。

学べる内容:

  • コア概念: Strands Agentの主要コンポーネントであるAgent、Model、Toolsを理解する。
  • 基本的なエージェント作成: シンプルなエージェントを作成し、Amazon Bedrockを使用して対話する。
  • ツールの使用: 組み込みツールやカスタムツールをエージェントに装備して、その機能を拡張する。
  • 環境変数: .envファイルを使用してAWSクレデンシャルを安全に管理する。
  • 実践例: ウェブ検索が可能な「リサーチアシスタント」エージェントを構築する。

さあ、始めましょう!🚀

# First, let's install the necessary packages.
# - strands-agents: The core SDK.
# - strands-agents-tools: A collection of pre-built tools.
# - python-dotenv: To load our API keys from a .env file.
# - boto3: The AWS SDK for Python, required for Amazon Bedrock.

#%pip install strands-agents strands-agents-tools python-dotenv boto3 -q

AWS認証情報の設定

Amazon Bedrockモデルを使用するには、AWS認証情報が必要です。これらの認証情報をコード内に含めないことがベストプラクティスです。.envファイルを使用して安全に保存します。

  1. .envという名前のファイルを作成し、このノートブックと同じディレクトリに配置します。

  2. AWS認証情報を追加し、以下の形式で.envファイルに記述します:

    AWS_ACCESS_KEY_ID="your_aws_access_key_id"
    AWS_SECRET_ACCESS_KEY="your_aws_secret_access_key"
    AWS_DEFAULT_REGION="us-west-2"  # またはお好みのリージョン
    

このチュートリアルでは、Amazon BedrockをClaude 3 Haikuとともに使用します。AWS認証情報はAWS IAMコンソールから取得できます。

import os
from dotenv import load_dotenv

# Load the environment variables from the .env file
load_dotenv()

# We'll check if the AWS credentials are loaded.
if "AWS_ACCESS_KEY_ID" in os.environ and "AWS_SECRET_ACCESS_KEY" in os.environ:
    print("✅ AWS credentials loaded successfully!")
else:
    print("⚠️ AWS credentials not f ound. Please check your .env file.")
✅ AWS credentials loaded successfully!

Core Concepts: The Agent, Model, and Tools

Strands Agentは、以下の3つの主要な部分で構成されています:

  1. Model: エージェントの推論と意思決定を支えるLLM。Strandsはモデルに依存しない設計になっているため、異なるプロバイダーのモデル間を簡単に切り替えることができます。
  2. Tools: エージェントが外部世界とやり取りするために使用できる関数。例えば、ウェブ検索、計算機の使用、データベースへのアクセスなどがあります。
  3. Prompt: エージェントに何をすべきか指示する一連の指示。

最初のエージェントを作成してみましょう。まず、まだツールを持たないシンプルなエージェントから始めます。BedrockModelを使用し、Amazon BedrockのClaudeモデルを指定します。

from strands import Agent
from strands.models.bedrock import BedrockModel
import os

# 1. Define the model
# We are using the BedrockModel with Claude 3 Sonnet.
# You must have model access enabled for this model ID in your AWS account's Bedrock console.
model = BedrockModel(
    model_id="anthropic.claude-3-5-haiku-20241022-v1:0",
    region_name=os.environ.get("AWS_DEFAULT_REGION", "us-west-2") # Uses the region from .env or defaults to us-west-2
)

# 2. Define the agent
# We'll give it a system prompt to define its personality.
agent = Agent(
    model=model,
    system_prompt="You are a friendly and helpful assistant."
)

# 3. Interact with the agent
response = agent("Hello! What can you do?")
Hi there! I'm Claude, an AI created by Anthropic to be helpful, honest, and harmless. I can help with all sorts of tasks like:

- Writing and editing
- Analysis and research
- Math and coding
- Answering questions
- Creative brainstorming
- Problem-solving

I aim to be direct, substantive, and ethical in my responses. I won't help with anything harmful, and I'll be upfront if I'm unsure about something. What would you like assistance with today?

Extending Capabilities with Tools

私たちのエージェントは、会話以外のことができないため、まだあまり役に立ちません。ツールを追加してみましょう!Strands は、strands-agents-tools パッケージ内でさまざまな事前構築されたツールを提供しています。ここでは、エージェントに calculator と current_time を取得する機能を追加します。

また、Python 関数を @tool でデコレートするだけで、独自のカスタムツールを作成することもできます。これが実際にどのように機能するか見てみましょう。

from strands import tool
from strands_tools import calculator, current_time
import datetime

# Let's create a custom tool to say hello.
@tool
def say_hello(name: str) -> str:
    """A tool to say hello to a person."""
    return f"Hello, {name}!"

# Create a new agent with the built-in and custom tools.
agent_with_tools = Agent(
    model=model,
    system_prompt="You are a helpful assistant that can use tools.",
    tools=[calculator, current_time, say_hello]
)

# Now, let's ask the agent a question that requires a tool.
response_calculator = agent_with_tools("What is 25 * 8?")

print("-" * 20)

# And another one that uses our custom tool.
response_hello = agent_with_tools("Say hello to the world.")

print("-" * 20)

# And one that uses the current_time tool.
response_time = agent_with_tools("What time is it?")
I'll help you calculate that using the calculator tool.
Tool #1: calculator
╭────────────────────────────────────────────── Calculation Result ───────────────────────────────────────────────╮
│                                                                                                                 │
│  ╭───────────┬─────────────────────╮                                                                            │
│  │ Operation │ Evaluate Expression │                                                                            │
│  │ Input     │ 25 * 8              │                                                                            │
│  │ Result    │ 200                 │                                                                            │
│  ╰───────────┴─────────────────────╯                                                                            │
│                                                                                                                 │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
The result of 25 * 8 is 200.--------------------
I'll use the say_hello tool to greet the world.
Tool #2: say_hello
There you go! A friendly hello to the world.--------------------
I'll retrieve the current time using the current_time tool. Since no specific timezone was mentioned, it will default to UTC.
Tool #3: current_time
The current time in UTC is 2025-08-20T15:16:46.884773+00:00. This is in ISO 8601 format, which includes the date, time, and timezone offset.

Would you like me to show the time in a specific timezone?

実践的な例: リサーチアシスタント

次に、より実践的なエージェントを構築してみましょう。「リサーチアシスタント」を作成し、ウェブを検索して質問に答えることができるようにします。このために、エージェントがウェブから情報を取得するためのHTTPリクエストを行うことができるhttp_requestツールを使用します。

また、エージェントが複数のツールを順番に使用して、リサーチと計算の両方を必要とするより複雑な質問に答える方法も見ていきます。

from strands_tools import http_request

# Create our Research Assistant agent
research_assistant = Agent(
    model=model,
    system_prompt="You are a research assistant. Your job is to use the web search tool to answer questions accurately.",
    tools=[http_request, calculator] # Give it the web search and calculator tools
)

# Let's ask a research question.
research_response = research_assistant("What is the latest news about Strands Agents?")

print("-" * 20)

# A more complex question that might require search and calculation.
complex_response = research_assistant("If a product costs $199 and is on a 15% discount, what is the final price?")
Let me search for the latest information about Strands Agents.
Tool #1: http_request
╭───────────────────────────────────── 🚀 HTTP Request Preview: GET /search ──────────────────────────────────────╮
│                                                                                                                 │
│   Method    GET                                                                                                 │
│   URL       https://www.google.com/search?q=Strands+Agents+latest+news                                          │
│   Headers   {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)    │
│             Chrome/91.0.4472.124 Safari/537.36'}                                                                │
│                                                                                                                 │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Sending request...
╭───────────────────────────────────────────── ❌ HTTP Response: 0  ──────────────────────────────────────────────╮
│                                                                                                                 │
│                                                                                                                 │
│     Status         429 Too Many Requests                                                                        │
│     URL            https://www.google.com/sorry/index?continue=https://www.google.com/search%3Fq%3DStrands…     │
│     Content-Type   text/html                                                                                    │
│     Size           3,217 bytes (3.1 KB)                                                                         │
│                                                                                                                 │
│                                                                                                                 │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─────── Redirect Information ───────╮
│                                    │
│ Followed 1 redirect(s): 302 -> 429 │
│                                    │
╰────────────────────────────────────╯
I apologize, but I encountered a search restriction. Let me try another approach.
Tool #2: http_request
╭───────────────────────────────────── 🚀 HTTP Request Preview: GET /search ──────────────────────────────────────╮
│                                                                                                                 │
│   Method    GET                                                                                                 │
│   URL       https://news.google.com/search?q=Strands%20Agents&hl=en-US&gl=US&ceid=US%3Aen                       │
│   Headers   {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)    │
│             Chrome/91.0.4472.124 Safari/537.36'}                                                                │
│                                                                                                                 │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Sending request...
╭─────────────────────────────────────────── ✅ HTTP Response: 200 OK ────────────────────────────────────────────╮
│                                                                                                                 │
│                                                                                                                 │
│     Status         200 OK                                                                                       │
│     URL            https://news.google.com/search?q=Strands%20Agents&hl=en-US&gl=US&ceid=US%3Aen                │
│     Content-Type   text/html; charset=utf-8                                                                     │
│     Size           1,872,725 bytes (1828.8 KB)                                                                  │
│                                                                                                                 │
│                                                                                                                 │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
                                                 Response Headers                                                  
╭──────────────────────────────┬──────────────────────────────────────────────────────────────────────────────────╮
│ Header                       │ Value                                                                            │
├──────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────┤
│ Content-Type                 │ text/html; charset=utf-8                                                         │
│ Vary                         │ Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site                                   │
│ x-ua-compatible              │ IE=edge                                                                          │
│ Cache-Control                │ no-cache, no-store, max-age=0, must-revalidate                                   │
│ Pragma                       │ no-cache                                                                         │
│ Expires                      │ Mon, 01 Jan 1990 00:00:00 GMT                                                    │
│ Date                         │ Wed, 20 Aug 2025 15:20:47 GMT                                                    │
│ P3P                          │ CP="This is not a P3P policy! See g.co/p3phelp for more info."                   │
│ Strict-Transport-Security    │ max-age=31536000                                                                 │
│ Permissions-Policy           │ ch-ua-arch=*, ch-ua-bitness=*, ch-ua-full-version=*, ch-ua-full-version-list=*,  │
│                              │ ch-ua-model=*, ch-ua...                                                          │
│ Content-Security-Policy      │ require-trusted-types-for 'script';report-uri /_/DotsSplashUi/cspreport,         │
│                              │ script-src 'report-sample' ...                                                   │
│ Cross-Origin-Resource-Policy │ same-site                                                                        │
│ Cross-Origin-Opener-Policy   │ same-origin-allow-popups                                                         │
│ Accept-CH                    │ Sec-CH-UA-Arch, Sec-CH-UA-Bitness, Sec-CH-UA-Full-Version,                       │
│                              │ Sec-CH-UA-Full-Version-List, Sec-CH-UA-Mo...                                     │
│ reporting-endpoints          │ default="/_/DotsSplashUi/web-reports?context=eJzjCtDikmJw05Bi-LxjBmvrzXOsU4HYUO… │
│ Content-Encoding             │ gzip                                                                             │
│ Server                       │ ESF                                                                              │
│ X-XSS-Protection             │ 0                                                                                │
│ X-Frame-Options              │ SAMEORIGIN                                                                       │
│ X-Content-Type-Options       │ nosniff                                                                          │
│ Set-Cookie                   │ NID=525=NSo5kQFb7PWES_-_tdnOE2IPqhzD7gSB80f96ntDH5Rhqe9zzlMw-2QBpZ4QAQUj0nm0krj… │
│ Alt-Svc                      │ h3=":443"; ma=2592000,h3-29=":443"; ma=2592000                                   │
│ Transfer-Encoding            │ chunked                                                                          │
╰──────────────────────────────┴──────────────────────────────────────────────────────────────────────────────────╯
bedrock threw context window overflow error
I apologize, but I'm unable to retrieve current news about Strands Agents through web search at the moment. This could be due to several reasons:

1. Strands Agents might be a relatively niche or specialized topic.
2. There might be recent changes or restrictions in web searching.
3. The search terms might be too specific or not yielding recent results.

To provide you with accurate information, I recommend:
- Checking the official Strands Agents website
- Looking for recent press releases or company announcements
- Consulting industry-specific news sources or forums
- Directly contacting the company for the most up-to-date information

If you have more context about Strands Agents (such as what industry they're in, what type of company or service they provide), I can help you refine the search strategy or suggest specific sources to check for the latest news.--------------------
I'll help you calculate the final price using the calculator.
Tool #3: calculator
╭────────────────────────────────────────────── Calculation Result ───────────────────────────────────────────────╮
│                                                                                                                 │
│  ╭───────────┬─────────────────────╮                                                                            │
│  │ Operation │ Evaluate Expression │                                                                            │
│  │ Input     │ 199 * (1 - 0.15)    │                                                                            │
│  │ Result    │ 169.1500000004      │                                                                            │
│  ╰───────────┴─────────────────────╯                                                                            │
│                                                                                                                 │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Let me break down the calculation:
- Original price: $199
- Discount percentage: 15%
- Discount amount: $199 * 0.15 = $29.85
- Final price: $199 - $29.85 = $169.15

So the final price after the 15% discount is $169.15.

Congratulations!

あなたは Amazon Bedrock を使用して初めての Strands Agents を無事に構築しました!

このチュートリアルでは、以下を学びました:

  • 指定された Bedrock model を使用して Strands Agent を作成する方法。
  • 組み込みツールを使用し、独自のカスタムツールを作成する方法。
  • .env ファイルを使用して AWS credentials を安全に管理する方法。
  • 実用的な「Research Assistant」エージェントを構築する方法。

これは Strands Agents でできることのほんの始まりに過ぎません。公式ドキュメントでは、マルチエージェントのオーケストレーションや状態管理など、より高度な概念を探求することができます。

楽しい構築を!🚀