Closed4
Strands Agents SDKを触ってみる

AWSお手製のAgents作成ツールであるStrands Agents SDK
を触ってみる。

触ってみる
まずは環境構築。
poetry init
poerty add strands-agents
poetry install
agent.py
を作成し、以下のコードを記載する。
from strands import Agent
# Create an agent with default settings
agent = Agent()
# Ask the agent a question
agent("Tell me about agentic AI")
コードを記載したらpoetry run python agent.py
を実行。
そうすると以下の結果が返ってくる。
# Agentic AI
Agentic AI refers to artificial intelligence systems designed to act autonomously toward achieving specified goals. Unlike more passive AI systems that simply respond to queries or perform specific tasks when prompted, agentic AI can:
- Take initiative and make decisions
- Plan sequences of actions to accomplish objectives
- Adapt strategies based on environmental feedback
- Persist in pursuing goals over time
## Key characteristics
- **Goal-directed behavior**: Operates with explicit or implicit objectives
- **Autonomy**: Can operate with minimal human intervention
- **Planning capability**: Creates multi-step approaches to solving problems
- **Environmental awareness**: Perceives and models its operational context
## Examples and applications
- AI assistants that proactively schedule meetings and follow up on tasks
- Autonomous research agents that search, synthesize, and produce findings
- Systems that manage complex processes like supply chains or IT infrastructure
- Creative agents that can generate and refine content based on goals
## Current limitations and challenges
- Alignment with human intentions and values
- Predictability and safety of autonomous decision-making
- Appropriate levels of initiative vs. waiting for human direction
- Transparency in how goals are interpreted and pursued
The field continues to evolve rapidly, with significant research focused on making agentic AI systems more reliable, beneficial, and aligned with human needs.
ストリーミングレスポンスだったので、すごい!!

Strands エージェント
触ってみる
思った以上に早く終わったので、Strands エージェントを試してみる。
strands-agentsをインストールする。
poetry add strands-agents strands-agents-tools strands-agents-builder
poetry install
その後、以下のコマンドでファイルを作成していく。
mkdir my_agent
touch my_agent/agent.py
echo 'from . import agent' > my_agent/__init__.py
agent.py
に以下のコードを添付する。
from strands import Agent, tool
from strands_tools import calculator, current_time, python_repl
# Define a custom tool as a Python function using the @tool decorator
@tool
def letter_counter(word: str, letter: str) -> int:
"""
Count occurrences of a specific letter in a word.
Args:
word (str): The input word to search in
letter (str): The specific letter to count
Returns:
int: The number of occurrences of the letter in the word
"""
if not isinstance(word, str) or not isinstance(letter, str):
return 0
if len(letter) != 1:
raise ValueError("The 'letter' parameter must be a single character")
return word.lower().count(letter.lower())
# Create an agent with tools from the strands-tools example tools package
# as well as our custom letter_counter tool
agent = Agent(tools=[calculator, current_time, python_repl, letter_counter])
# Ask the agent a question that uses the available tools
message = """
I have 4 requests:
1. What is the time right now?
2. Calculate 3111696 / 74088
3. Tell me how many letter R's are in the word "strawberry" 🍓
4. Output a script that does what we just spoke about!
Use your python tools to confirm that the script works before outputting it
"""
agent(message)
記載したらpoetry run python agent.py
で実行する。
実行したら以下の結果が返ってくる。
I'll help you with each of your requests one by one.
### 1. Getting the current time
Let me check the current time for you:
Tool #1: current_time
The current time is 2025-05-19T04:51:37.022592+00:00 (UTC).
### 2. Calculating 3111696 / 74088
I'll calculate this division for you:
Tool #2: calculator
The result of 3111696 / 74088 is 42.
### 3. Counting letter R's in "strawberry"
Let me count how many R's are in the word "strawberry":
Tool #3: letter_counter
There are 3 letter R's in the word "strawberry" 🍓.
### 4. Creating a Python script for these tasks
I'll create a Python script that performs all three tasks we just discussed and test it:
Tool #4: python_repl
Do you want to proceed with Python code execution? [y/*] y
1. Current time: 2025-05-19T04:52:12.583207+00:00
2. 3111696 / 74088 = 42.0
3. Number of 'r' in 'strawberry': 3
Additional tests:
Division of 100/5: 20.0
Letter 'a' in 'banana': 3
The Python script works correctly! Here's the final script that performs all three tasks:
import datetime
import pytz
def get_current_time(timezone='UTC'):
"""Get the current time in ISO 8601 format."""
try:
tz = pytz.timezone(timezone)
current_time = datetime.datetime.now(tz).isoformat()
return current_time
except Exception as e:
return f"Error getting time: {str(e)}"
def calculate_division(numerator, denominator):
"""Calculate division of two numbers."""
try:
result = numerator / denominator
return result
except ZeroDivisionError:
return "Error: Division by zero"
except Exception as e:
return f"Error in calculation: {str(e)}"
def count_letter_occurrences(word, letter):
"""Count occurrences of a specific letter in a word."""
return word.lower().count(letter.lower())
# Task 1: Get current time
current_time = get_current_time()
print(f"1. Current time: {current_time}")
# Task 2: Calculate 3111696 / 74088
calculation_result = calculate_division(3111696, 74088)
print(f"2. 3111696 / 74088 = {calculation_result}")
# Task 3: Count R's in strawberry
word = "strawberry"
letter = "r"
count = count_letter_occurrences(word, letter)
print(f"3. Number of '{letter}' in '{word}': {count}")
The script successfully performs all three tasks:
1. Gets and displays the current time in ISO format
2. Calculates and displays the result of 3111696 / 74088 (which is 42)
3. Counts and displays the number of 'r's in "strawberry" (which is 3)
The script also includes error handling and can work with different inputs as shown in the test.
中を見てみる
calculator(計算)
, current_time(現在の日付)
, python_repl(pythonシェル)
は既に用意されているライブラリ。
letter_counter
は自作した関数で、@tool
でラップすることで、Agentのtoolsで使用できるようになる。
エージェントのmessageを日本語にすると以下の通りである。
message = """
4つのリクエストがあります:
1. 現在の時刻は何時ですか?
2. 3111696 ÷ 74088 を計算してください
3. "strawberry"(いちご)🍓という単語に「R」の文字が何個あるか教えてください
4. 今話し合ったことを実行するスクリプトを出力してください!
出力する前に、そのスクリプトが動作することをPythonツールで確認してください
"""
この4つのリクエストを設定したtoolsを使って、実行してくれている。
デバックしてみる
Agentでデバックログを有効化するために、以下のコードをagent.py
の先頭に記載する。
import logging
# Enables Strands debug log level
logging.getLogger("strands").setLevel(logging.DEBUG)
# Sets the logging format and streams logs to stderr
logging.basicConfig(
format="%(levelname)s | %(name)s | %(message)s",
handlers=[logging.StreamHandler()]
)
すると、ログが出力される。

まとめ
ADKやOpenAI Agents SDK同様、簡単にAgentを作成することができた。
このスクラップは4ヶ月前にクローズされました