StrandsAgentsに入門してみる
0. 対象読者
「StrandsAgents触ってみよう」っていうPythonユーザ
1. はじめに
こんにちは!なおずみです!
ここ数ヶ月、エージェントの波がなんかすごいので、置いてかれまいとStrandsAgentsに入門してみました!
2. 今回やること
- チュートリアル
- A2Aとtoolを使ってみる
3. 前提
- AWSのアカウントを持ってること
- poetryがインストールされていること
4. poetryで土台作り
プロジェクトと必要なライブラリの追加
poetry new tutorial
poetry add strands-agents
poetry add strands-agents-tools
5. AWSのセットアップ
- コンソール→Bedrock
- 左側のメニューから、「モデルアクセス」を選択し、今回使うClaude 3.7 Sonnetのアクセス権をリクエスト
(チュートリアルだし、3.7でいいかという気持ち) - 数分待つと、こんな感じでアクセス権が付与されるっぽい、良さそ〜
6. エージェント動かしてみる
コードは、ほぼチュートリアルのまんまで、モデルは3.7のやつを指定する
from strands import Agent
def main():
# Create an agent with default settings
agent = Agent(model="apac.anthropic.claude-3-7-sonnet-20250219-v1:0")
# Ask the agent a question
agent("Tell me about agentic AI")
if __name__ == "__main__":
main()
※ ちょっと詰まったポイント
モデルの名前が「apac.anthropic.claude-3-7-sonnet-20250219-v1:0」みたいにリージョンの情報が先頭につくことに注意
利用できるモデルの一覧を確認するコマンド
aws bedrock list-inference-profiles --query "inferenceProfileSummaries[].inferenceProfileId" --output table
7. 動作確認
実行してみる
poetry run python src/tutorial/main.py
おお〜!なんかそれっぽいの返ってきた!!
# Agentic AI
Agentic AI refers to artificial intelligence systems designed to act autonomously on behalf of users to achieve specified goals. Unlike passive AI systems that simply respond to queries, agentic AI can:
- Take initiative to complete tasks
- Make decisions with minimal human supervision
- Plan sequences of actions to achieve objectives
- Learn from interactions and improve over time
## Key characteristics:
- **Goal-oriented behavior**: Works toward completing specific objectives
- **Autonomy**: Operates independently within defined parameters
- **Planning abilities**: Can map out steps needed to accomplish tasks
- **Adaptation**: Adjusts strategies based on changing conditions or feedback
## Applications
Agentic AI is being developed for use cases like:
- Personal assistants that proactively manage schedules, make reservations, or handle correspondence
- Research agents that gather, synthesize, and present information
- Code generation assistants that can develop software components
- Business process automation systems
## Current limitations
Today's agentic AI systems remain limited by:
- Reliability concerns with autonomous decision-making
- Challenges in understanding nuanced human preferences
- Safety and alignment considerations
- Potential for unintended consequences when operating autonomously
The development of agentic AI raises important questions about appropriate levels of autonomy, oversight mechanisms, and how to ensure these systems act in accordance with human values and intentions.%
ちゃんと課題っぽいのも回答してくれるところが謙虚で良いな
ひとまずチュートリアル終わり!
8. 計算エージェントを作ってみる
A2Aを試したいので、計算エージェントを作成してみる
公式でサポートされているcalculatorで事足りそうなので、実装も楽ちん
from strands import Agent
from strands.multiagent.a2a import A2AServer
from strands_tools import calculator
def serve():
# Create a Strands agent
agent1 = Agent(
name="Calculator Agent",
model="apac.anthropic.claude-3-7-sonnet-20250219-v1:0",
description="A calculator agent that can perform basic arithmetic operations.",
tools=[calculator],
callback_handler=None
)
# Create A2A server (streaming enabled by default)
agent1_server = A2AServer(
agent=agent1,
port=9000
)
# Start the server
agent1_server.serve()
if __name__ == "__main__":
serve()
9. お天気エージェントを作ってみる
続いて、API使うパターンもやっておきたいので、公開されているお天気API(openweathermap)をツールにする
デコレータで簡単に実装できるのめっちゃ良き
from strands import Agent, tool
from strands.multiagent.a2a import A2AServer
import requests
# Define a tool to get weather information
@tool
def get_weather(location: str) -> str:
api_key = "your api key"
url = f"https://api.openweathermap.org/data/2.5/weather?q={location}&units=metric&appid={api_key}"
jsondata = requests.get(url).json()
return jsondata
def serve():
# Create a Strands agent
agent2 = Agent(
name="Get Weather Agent",
model="apac.anthropic.claude-3-7-sonnet-20250219-v1:0",
description="An agent that can provide weather information.",
tools=[get_weather],
callback_handler=None,
)
# Create A2A server (streaming enabled by default)
agent2_server = A2AServer(
agent=agent2,
port=9001
)
# Start the server
agent2_server.serve()
if __name__ == "__main__":
serve()
10. A2Aをやってみる
呼び出す子エージェントを2体作ったので、システムプロンプトで役割を教えてあげて、早速親エージェントから呼び出してみる。
from strands import Agent
from strands_tools.a2a_client import A2AClientToolProvider
def main():
# Create A2A client tool provider with known agent URLs
provider = A2AClientToolProvider(known_agent_urls=["http://localhost:9000", "http://localhost:9001"])
# Create an agent with default settings
agent = Agent(
model="apac.anthropic.claude-3-7-sonnet-20250219-v1:0",
tools=provider.tools,
system_prompt="あなたは司令塔です。あなたは、他のエージェントに質問を投げかけ、回答を集めて、最終的な答えを出す役割を持っています。",
)
# Ask the agent a question
agent(
f"""
以下の質問に日本語で答えて
・f(x) = 2x^2 + 3x + 1 を微分して
・東京の天気を教えてほしい
"""
)
if __name__ == "__main__":
main()
計算エージェントサーバーと、お天気エージェントサーバーを立ち上げて、A2AClientToolProviderで指定してあげれば良さそう
これだけでエージェント同士が繋がるのはめっちゃ簡単だな
11. 動作確認
それっぽい質問を投げてみる
poetry run python src/tutorial/main.py
結構時間かかるし、たまにこけるけど、、
ご質問にお答えするために、外部のエージェントを利用して情報を集めたいと思います。まず、利用可能なA2Aエージェントを確認しましょう。
Tool #1: a2a_list_discovered_agents
2つの質問に答えるために、それぞれのエージェントを利用します。
まず、f(x) = 2x^2 + 3x + 1 を微分する問題については、Calculator Agentを使用します:
Tool #2: a2a_send_message
次に、東京の天気について、Weather Agentを使用します:
Tool #3: a2a_send_message
それでは、収集した情報をもとに回答をまとめます:
# 回答
## f(x) = 2x^2 + 3x + 1 を微分した結果
f(x) = 2x^2 + 3x + 1 の微分は:
f'(x) = 4x + 3
これは微分のルールを使って次のように計算できます:
- 2x^2 の微分: 2・(2x^(2-1)) = 4x
- 3x の微分: 3
- 1 の微分: 0
これらを足すと f'(x) = 4x + 3 となります。
## 東京の天気
東京の現在の天気は「少し曇り(few clouds)」です。気温は28.72℃で、湿度が70%と高めなため、体感温度は32.13℃とかなり蒸し暑く感じます。
風は南から8.17m/sで吹いており、やや強めです。雲量は11%と少なく、視界は10kmと良好です。
気圧は1013hPaで安定しています。全体的に見ると、少し雲はあるものの、比較的穏やかな夜の天気となっています。
おぉ〜!!いい感じに返ってきた!
親エージェントが子エージェントを呼び出してるのが、出力でちゃんとわかるのいいね
12. まとめ
今回はstrands agentに入門してみましたが、めちゃくちゃ簡単にエージェントが構築できました!
エージェントを色々組み合わせて、複雑なエージェント(アイアンマンのジャービスみたいな)とか作ってみたいですね
誰かの何かの参考になれば幸いです〜
ソースコード載せとくので、よかったら覗いてください〜
Discussion