Repository: https://github.com/strands-agents/samples Stars: 793 | Forks: 420 | Language: Python | License: Apache-2.0 Tags: Examples, Python, Demos, agentic-ai, multi-agent-systems, mcp, opentelemetry, bedrock, llm Official Site: https://strandsagents.com Last Updated: 2026-06-17
1. 專案概覽 (Project Overview)
1.1 這是什麼
Strands Agents Samples 是 Strands Agents 生態系的官方範例庫 (official sample repository),由 AWS 團隊維護。它收錄了超過 50 個實作範例,涵蓋從「三行程式碼建立第一個 Agent」到「多 Agent Swarm 協作」、「邊緣裝置機器人控制」等完整應用場景。
Strands Agents 的核心理念是 model-driven approach (模型驅動方法)——讓 LLM 自己決定使用哪些工具、何時呼叫、如何組合,開發者只需定義 Agent 的系統提示詞 (system prompt) 和可用工具即可。這與傳統的 workflow-driven (工作流驅動) 框架形成鮮明對比:
| 特性 | Model-driven (Strands) | Workflow-driven (傳統) |
|---|---|---|
| 控制邏輯 | LLM 自主決策 | 開發者預定義流程 |
| 彈性 | 高——可動態應對意外狀況 | 低——只能走預設路徑 |
| 開發複雜度 | 低——幾行程式碼 | 高——需設計 DAG / state machine |
| 可預測性 | 中——需 guardrail 補強 | 高——行為確定性強 |
1.2 誰做的,為什麼重要
Strands Agents 由 AWS 內部團隊開發並開源,原先在 Amazon 內部用於生產環境。2025 年中以 Apache 2.0 授權釋出後,迅速成長為 GitHub 上最活躍的 Agent framework 之一。
其重要性在於:
- AWS 原生整合 (native integration):與 Amazon Bedrock、Lambda、Fargate、AgentCore 深度整合
- 多模型支援 (multi-model support):Anthropic Claude、Meta Llama、OpenAI、Ollama 均可透過 LiteLLM 接入
- MCP 一等公民 (MCP first-class citizen):完整支援 Model Context Protocol (模型上下文協定)
- 生產就緒 (production-ready):內建 observability (可觀測性)、guardrails (安全護欄)、session management (會話管理)
1.3 Samples Repo 在生態系中的角色
這個 samples repo 是整個 Strands Agents 生態系的 學習入口 (learning gateway) 和 參考實作 (reference implementation)。它不包含 SDK 原始碼,而是展示如何組合 SDK + Tools + 外部服務來建構完整應用。
2. 核心架構 (Core Architecture)
2.1 Samples 目錄結構
整個 repo 分為 Python 和 TypeScript 兩大語言分支,各自包含從學習到部署的完整教學序列:
1strands-agents/samples/
2├── python/
3│ ├── 01-learn/ # 18 個基礎教學
4│ │ ├── 01-first-agent/ # 第一個 Agent
5│ │ ├── 02-tools-and-mcp/ # 工具與 MCP
6│ │ ├── 03-model-providers/ # 模型供應商切換
7│ │ ├── 04-streaming/ # 串流處理
8│ │ ├── 05-guardrails/ # 安全護欄
9│ │ ├── 06-memory/ # 記憶系統
10│ │ ├── 07-aws-services/ # AWS 服務整合
11│ │ ├── 08-observability/ # 可觀測性
12│ │ ├── 09-bidi-streaming/ # 雙向串流
13│ │ ├── 10-agents-as-tools/ # Agent 作為工具
14│ │ ├── 11-swarm/ # Swarm 多 Agent 協作
15│ │ ├── 12-graph/ # Graph 拓撲 Agent
16│ │ ├── 13-human-in-the-loop/ # 人在迴圈中
17│ │ ├── 14-plugins/ # 外掛系統
18│ │ ├── 15-skills/ # 技能模組
19│ │ ├── 16-hooks-lifecycle/ # Hook 生命週期
20│ │ ├── 17-conversation-management/ # 對話管理
21│ │ └── 18-self-improving-agents/ # 自我改進 Agent
22│ ├── 02-deploy/ # 部署模式(Lambda / Fargate / AgentCore)
23│ ├── 03-integrate/ # 整合範例
24│ ├── 04-industry-use-cases/ # 產業應用(金融 / 醫療 / 物流 / 行銷)
25│ ├── 05-technical-use-cases/ # 技術應用(RAG / steering)
26│ ├── 06-evaluate/ # 評估與測試
27│ ├── 07-ux-demos/ # 全端 UI 展示
28│ └── 08-edge/ # 邊緣裝置 / 機器人
29└── typescript/
30 ├── 01-learn/ # TypeScript 基礎教學
31 │ ├── 01-first-agent/ # 第一個 Agent
32 │ ├── 02-custom-tools/ # 自訂工具
33 │ ├── 03-model-providers/ # 模型供應商
34 │ ├── 04-streaming/ # 串流處理
35 │ ├── 05-agent-state/ # Agent 狀態管理
36 │ └── 06-browser-agent/ # 瀏覽器 Agent
37 └── 02-deploy/ # 部署模式(AgentCore)
2.2 Agent 核心運作流程
以下 Mermaid 圖展示 Strands Agent 的核心 agentic loop (代理迴圈)——這是所有範例的基礎運作邏輯:
flowchart TD
A["使用者輸入
(User Input)"] --> B["Agent 接收請求"]
B --> C["System Prompt
+ 對話歷史注入"]
C --> D["呼叫 Model Provider
(Bedrock / OpenAI / Ollama)"]
D --> E{"LLM 回應類型判斷"}
E -->|"text 回應"| F["回傳文字給使用者"]
E -->|"tool_use 請求"| G["執行 Tool Call"]
G --> H["Tool 回傳結果"]
H --> D
E -->|"end_turn"| I["結束迴圈"]
subgraph HOOKS ["Hook 生命週期 (Lifecycle Hooks)"]
direction TB
H1["BeforeInvocationEvent"]
H2["BeforeModelCallEvent"]
H3["AfterModelCallEvent"]
H4["BeforeToolCallEvent"]
H5["AfterToolCallEvent"]
H6["AfterInvocationEvent"]
end
B -.-> H1
C -.-> H2
D -.-> H3
G -.-> H4
H -.-> H5
I -.-> H6
style HOOKS fill:#f0f4ff,stroke:#4a90d9
style A fill:#e8f5e9,stroke:#4caf50
style I fill:#fff3e0,stroke:#ff9800
2.3 多 Agent 協作架構
Strands Agents 提供三種多 Agent 編排模式 (orchestration patterns),在 samples 中各有對應範例:
flowchart LR
subgraph TOOL ["模式一:Agent-as-Tool
(10-agents-as-tools)"]
direction TB
T1["Orchestrator Agent"]
T2["Sub-Agent A
(作為 tool)"]
T3["Sub-Agent B
(作為 tool)"]
T1 -->|"tool call"| T2
T1 -->|"tool call"| T3
end
subgraph SWARM ["模式二:Swarm
(11-swarm)"]
direction TB
S1["Agent 1
researcher"]
S2["Agent 2
coder"]
S3["Agent 3
reviewer"]
S1 <-->|"handoff"| S2
S2 <-->|"handoff"| S3
S3 <-->|"handoff"| S1
end
subgraph GRAPH ["模式三:Graph
(12-graph)"]
direction TB
G1["Node A"]
G2["Node B"]
G3["Node C"]
G4["Node D"]
G1 --> G2
G1 --> G3
G2 --> G4
G3 --> G4
end
style TOOL fill:#e3f2fd,stroke:#1565c0
style SWARM fill:#fce4ec,stroke:#c62828
style GRAPH fill:#e8f5e9,stroke:#2e7d32
三種模式的差異:
| 模式 | 控制方式 | 適用場景 | 對應範例 |
|---|---|---|---|
| Agent-as-Tool | 階層式 (hierarchical):主 Agent 呼叫子 Agent | 明確的指揮鏈關係 | 10-agents-as-tools/ |
| Swarm | 自組織 (self-organizing):Agent 之間互相 handoff | 需要多專家動態協作 | 11-swarm/ |
| Graph | 拓撲式 (topological):預定義 Node 和 Edge | 有明確步驟順序的管線 | 12-graph/ |
3. 安裝與設定 (Installation & Setup)
3.1 前置需求 (Prerequisites)
| 項目 | 最低需求 | 建議版本 |
|---|---|---|
| Python | 3.10+ | 3.12 |
| Node.js (TypeScript 範例) | 18+ | 20 LTS |
| pip / uv | 任一 | uv (推薦) |
| AWS CLI | v2 | 最新版 |
| Git | 2.x | 最新版 |
3.2 安裝步驟
步驟一:Clone Repository
1git clone https://github.com/strands-agents/samples.git
2cd samples
步驟二:建立 Python 虛擬環境
1# 使用 uv(推薦)
2uv venv
3source .venv/bin/activate
4
5# 或使用 venv
6python -m venv venv
7source venv/bin/activate
步驟三:安裝核心套件
1# 安裝 Strands Agents SDK 和官方工具集
2pip install strands-agents strands-agents-tools
3
4# 若使用 TypeScript 範例
5cd typescript/01-learn/01-first-agent
6npm install
步驟四:安裝個別範例的依賴
每個範例目錄都有自己的 requirements.txt:
1cd python/01-learn/01-first-agent
2pip install -r requirements.txt
3.3 模型供應商設定 (Model Provider Configuration)
Strands Agents 預設使用 Amazon Bedrock,但支援多種供應商:
方式一:Amazon Bedrock (預設)
1# 確保 AWS credentials 已設定
2aws configure
3# 或使用環境變數
4export AWS_ACCESS_KEY_ID="your-key"
5export AWS_SECRET_ACCESS_KEY="your-secret"
6export AWS_REGION="us-east-1"
方式二:OpenAI (透過 LiteLLM)
1export OPENAI_API_KEY="sk-..."
1from strands import Agent
2from strands.models.litellm import LiteLLMModel
3
4model = LiteLLMModel(model_id="openai/gpt-4o")
5agent = Agent(model=model)
方式三:Ollama (本地模型)
1# 先啟動 Ollama
2ollama serve
3ollama pull llama3.1
1from strands import Agent
2from strands.models.ollama import OllamaModel
3
4model = OllamaModel(model_id="llama3.1")
5agent = Agent(model=model)
4. 使用方式與程式碼範例 (Usage & Code Examples)
4.1 範例一:最簡 Agent — 三行程式碼上手
檔案位置:python/01-learn/01-first-agent/
1from strands import Agent
2
3# 建立一個 Agent — 只需一行
4agent = Agent()
5
6# 與 Agent 對話 — 只需呼叫
7response = agent("Hello! Tell me a joke.")
8
9# 印出回應
10print(response)
逐行解析:
- 第 1 行:從
strands套件匯入Agent類別。這是整個框架的核心進入點。 - 第 4 行:建立 Agent 實例。不帶參數時,使用預設模型 (Amazon Bedrock 上的 Claude Sonnet 4.5)、無自訂工具、無 system prompt。
- 第 7 行:直接用函式呼叫語法
agent("...")發送訊息。Agent 會進入 agentic loop,直到 LLM 回傳end_turn才返回。 - 第 10 行:
response是一個AgentResult物件,print()時會自動轉為字串輸出。
4.2 範例二:帶自訂工具的互動式 Agent
檔案位置:python/01-learn/01-first-agent/02-simple-interactive-usecase/recipe_bot.py
1import logging
2from ddgs import DDGS
3from ddgs.exceptions import DDGSException, RatelimitException
4from strands import Agent, tool
5
6# 設定 logging 等級 — 追蹤 Agent 內部行為
7logging.getLogger("strands").setLevel(logging.INFO)
8
9# 使用 @tool 裝飾器定義自訂工具
10@tool
11def websearch(
12 keywords: str,
13 region: str = "us-en",
14 max_results: int | None = None
15) -> str:
16 """Search the web to get updated information.
17
18 Args:
19 keywords (str): The search query keywords.
20 region (str): The search region: wt-wt, us-en, uk-en, ru-ru, etc..
21 max_results (int | None): The maximum number of results to return.
22
23 Returns:
24 List of dictionaries with search results.
25 """
26 try:
27 results = DDGS().text(keywords, region=region, max_results=max_results)
28 return results if results else "No results found."
29 except RatelimitException:
30 return "RatelimitException: Please try again after a short delay."
31 except DDGSException as d:
32 return f"DuckDuckGoSearchException: {d}"
33 except Exception as e:
34 return f"Exception: {e}"
35
36# 建立帶有 system prompt 和工具的 Agent
37recipe_agent = Agent(
38 system_prompt="""You are RecipeBot, a helpful cooking assistant.
39 Help users find recipes based on ingredients and answer cooking questions.
40 Use the websearch tool to find recipes when users mention ingredients
41 or to look up cooking information.""",
42 tools=[websearch],
43)
44
45if __name__ == "__main__":
46 print("\nRecipeBot: Ask me about recipes or cooking! Type 'exit' to quit.\n")
47 while True:
48 user_input = input("\nYou > ")
49 if user_input.lower() == "exit":
50 print("Happy cooking!")
51 break
52 response = recipe_agent(user_input)
53 print(f"\nRecipeBot > {response}")
逐行解析重點:
@tool裝飾器 (decorator):這是 Strands 定義自訂工具的核心機制。只要用@tool標註一個函式,框架會自動從 docstring 提取工具描述和參數 schema,生成 LLM 可理解的 tool definition (工具定義)。- Type hints (型別提示) 是必要的:
keywords: str、max_results: int | None = None這些會直接轉換為 JSON Schema,讓 LLM 知道該傳什麼參數。 tools=[websearch]:將工具清單傳給 Agent。Agent 會把這些工具的 schema 注入給 LLM,讓模型自行決定何時呼叫。- 互動迴圈 (interactive loop):
while True搭配input()形成持續對話。每次呼叫recipe_agent(user_input)都會帶著對話歷史,實現多輪對話 (multi-turn conversation)。
4.3 範例三:自我擴展 Agent (Self-Extending Agent)
檔案位置:python/01-learn/18-self-improving-agents/code/step-01-tools/agent.py
這是 Samples 中最具實驗性的範例——Agent 可以在執行時自行創建新工具:
1from strands import Agent
2from strands_tools import shell, file_write
3
4MODEL_ID = "global.anthropic.claude-opus-4-8"
5
6SYSTEM_PROMPT = """You are a self-extending research agent.
7
8You can CREATE new tools by writing Python files to ./tools/. Each file should
9define one or more functions decorated with `@tool` from the strands package.
10Tools become available instantly after the file is saved.
11
12Template for a new tool:
13
14```python
15from strands import tool
16
17@tool
18def my_tool(argument: str) -> str:
19 \"\"\"Short description of what this tool does.
20
21 Args:
22 argument: What this argument means.
23
24 Returns:
25 A string result.
26 \"\"\"
27 return f"result for {argument}"
When a user asks for a capability you don’t have, CREATE the tool, then USE it. Be concise in your replies. """
def main(): agent = Agent( model=MODEL_ID, tools=[shell, file_write], load_tools_from_directory=True, # 關鍵參數! system_prompt=SYSTEM_PROMPT, ) print(“Self-extending agent. Type ’exit’ to quit.\n”) while True: try: q = input("> “).strip() except (EOFError, KeyboardInterrupt): print() break if q.lower() in (“exit”, “quit”, “q”, “”): break agent(q)
if name == “main”: main()
1
2**逐行解析重點:**
3
4- **`load_tools_from_directory=True`**:這是 Strands SDK 的獨特功能。啟用後,Agent 會監控 `./tools/` 目錄,任何新增的 Python 檔案只要包含 `@tool` 裝飾器的函式,就會自動載入成為可用工具。
5- **自我擴展邏輯 (self-extension logic)**:system prompt 告訴 Agent「當你沒有需要的能力時,自己寫一個工具」。Agent 透過 `file_write` 工具將新 Python 檔案寫入 `./tools/`,框架自動偵測並載入。
6- **安全注意事項 (security note)**:這種模式賦予 Agent 執行任意程式碼的能力,僅適用於開發和實驗環境。生產環境必須搭配 sandbox (沙箱) 和 guardrails (安全護欄)。
7
8### 4.4 範例四:Swarm 多 Agent 協作
9
10**檔案位置**:`python/01-learn/11-swarm/`
11
12```python
13import logging
14from strands import Agent
15from strands.multiagent import Swarm
16
17# 啟用除錯日誌 — 觀察 Agent 之間的 handoff
18logging.getLogger("strands.multiagent").setLevel(logging.DEBUG)
19logging.basicConfig(
20 format="%(levelname)s | %(name)s | %(message)s",
21 handlers=[logging.StreamHandler()]
22)
23
24# 建立專業化的 Agent 團隊
25researcher = Agent(
26 name="researcher",
27 system_prompt="You are a research specialist. "
28 "Find relevant information and facts."
29)
30coder = Agent(
31 name="coder",
32 system_prompt="You are a coding specialist. "
33 "Write clean, well-documented code."
34)
35reviewer = Agent(
36 name="reviewer",
37 system_prompt="You are a code review specialist. "
38 "Review code for bugs and improvements."
39)
40architect = Agent(
41 name="architect",
42 system_prompt="You are a system architecture specialist. "
43 "Design scalable system architectures."
44)
45
46# 建立 Swarm — 設定安全參數
47swarm = Swarm(
48 [researcher, coder, reviewer, architect],
49 max_handoffs=20, # 最多 20 次 handoff
50 max_iterations=20, # 最多 20 次迭代
51 execution_timeout=900.0, # 總時限 15 分鐘
52 node_timeout=300.0, # 每個 Agent 最多 5 分鐘
53 repetitive_handoff_detection_window=8, # 偵測乒乓行為
54 repetitive_handoff_min_unique_agents=3 # 最近 8 次必須有 3 個不同 Agent
55)
56
57# 執行 Swarm 任務
58result = swarm("Design and implement a simple REST API for a todo app")
59
60# 查看結果
61print(f"Status: {result.status}")
62print(f"Node history: {[node.node_id for node in result.node_history]}")
63print(f"Total iterations: {result.execution_count}")
64print(f"Execution time: {result.execution_time}ms")
65print(f"Token usage: {result.accumulated_usage}")
逐行解析重點:
Swarm類別:接收一個 Agent 列表和多個安全參數。每個 Agent 有獨立的name和system_prompt,Swarm 會自動為每個 Agent 注入handoff_to_agent工具。- Handoff 機制 (交接機制):Agent 可以透過
handoff_to_agent(agent_name, message, context)將控制權轉移給團隊中的另一個 Agent。這是一種 去中心化 (decentralized) 的協作模式。 - 安全機制 (safety mechanisms):
max_handoffs防止無限交接、execution_timeout限制總執行時間、repetitive_handoff_detection_window偵測 Agent 互相踢皮球。 SwarmResult物件:包含完整的執行歷史,可查看每個 Agent 的參與時序、token 使用量等。
5. 進階功能 (Advanced Features)
5.1 Hook 生命週期系統 (Lifecycle Hook System)
對應範例:python/01-learn/16-hooks-lifecycle/
Hooks 是 Strands Agents 最強大的擴展機制之一。它提供 7 種事件類型 (event types),讓開發者在 Agent 執行的每個階段插入自訂邏輯:
1Agent 建構 ──> AgentInitializedEvent(一次性)
2
3agent("問題")
4│
5├─ BeforeInvocationEvent # 可修改 messages
6│ └─ MessageAddedEvent # 使用者輸入加入歷史
7│
8├─ BeforeModelCallEvent # 每次呼叫模型前
9│ └─ AfterModelCallEvent # 可設定 retry
10│ └─ MessageAddedEvent # 模型回應加入歷史
11│
12├─ BeforeToolCallEvent # 可設定 cancel_tool
13│ └─ AfterToolCallEvent # 可設定 retry / 修改 result
14│ └─ MessageAddedEvent # 工具結果加入歷史
15│
16└─ AfterInvocationEvent # 可設定 resume(自動重啟)
可寫入欄位 (writable fields) 是 Hook 的核心功能:
| Event | 可寫入欄位 | 用途 |
|---|---|---|
BeforeInvocationEvent | messages | 輸入修改 / 敏感資訊遮蔽 (redaction) |
BeforeToolCallEvent | cancel_tool | 阻擋特定工具呼叫 |
AfterToolCallEvent | retry, result | 失敗重試 / 結果覆寫 |
AfterInvocationEvent | resume | 觸發新一輪 invocation |
HookProvider 封裝模式:可將多個 Hook 封裝成可重用的元件:
1from strands.hooks import HookProvider, AgentInitializedEvent, BeforeToolCallEvent
2
3class SafetyGuard(HookProvider):
4 """封裝安全相關的多個 Hook 為可重用元件"""
5
6 def register_hooks(self, agent):
7 agent.add_hook(AgentInitializedEvent, self.on_init)
8 agent.add_hook(BeforeToolCallEvent, self.on_before_tool)
9
10 def on_init(self, event: AgentInitializedEvent):
11 print("Safety guard initialized")
12
13 def on_before_tool(self, event: BeforeToolCallEvent):
14 # 阻擋危險工具
15 if event.tool_name in ["shell", "file_write"]:
16 event.cancel_tool = True
17 event.cancel_reason = "This tool is blocked by safety policy"
5.2 Human-in-the-Loop 中斷機制 (HITL Interrupts)
對應範例:python/01-learn/13-human-in-the-loop/
Strands 的 interrupt (中斷) 系統允許 Agent 在執行過程中暫停,等待人類審核或輸入後再繼續:
- Hook-based interrupts:在
BeforeToolCallEvent中觸發中斷,攔截工具呼叫前要求人類確認 - Tool-based interrupts:在工具函式內部透過
tool_context.interrupt()主動暫停 - Session persistence (會話持久化):中斷狀態可透過
FileSessionManager跨 session 保存
這在需要人類審核的場景(如金融交易確認、醫療決策覆核)中至關重要。
5.3 Skills 模組化系統
對應範例:python/01-learn/15-skills/
Skills 是 Strands 的指令模組化機制 (modular instruction system)。與其把所有指令塞進一個巨大的 system prompt,Skills 讓 Agent 按需載入特定領域的指令:
1skills/
2├── returns-policy/
3│ ├── SKILL.md # 技能描述 + 指令
4│ └── references/
5│ └── returns-checklist.md # 參考文件
6└── technical-troubleshooting/
7 ├── SKILL.md
8 └── references/
9 └── escalation-guide.md
AgentSkillsplugin:掃描 skills 目錄,自動注入可用技能摘要到 system prompt- 按需載入 (on-demand loading):Agent 呼叫內建的
skillstool 來載入完整指令 - Runtime 更新:
set_available_skills()可在執行中動態新增或替換技能
5.4 Graph Agent 拓撲編排
對應範例:python/01-learn/12-graph/
Agent Graph 提供預定義拓撲的 Agent 協作模式:
- Nodes (節點):各自獨立的 Agent,有自己的 system prompt 和工具
- Edges (邊):Agent 之間的通訊路徑
- Conditional Edges (條件邊):根據執行結果動態選擇下一步
Graph 模式適合需要嚴格步驟順序但又想保留每個步驟彈性的管線場景。
5.5 自我修改 Agent (Self-Modifying Agent)
對應範例:python/01-learn/18-self-improving-agents/code/step-02-system-prompt/
Agent 可以在執行時修改自己的 system prompt,實現 self-improvement (自我改進):
1@tool
2def system_prompt(action: str, prompt: str | None = None) -> dict:
3 """Manage the agent's own system prompt at runtime.
4
5 Args:
6 action: One of "view", "update", "add_context", "reset".
7 prompt: The new prompt text (required for update / add_context).
8 """
9 if action == "update":
10 os.environ["SYSTEM_PROMPT"] = prompt
11 Path(".prompt").write_text(prompt)
12 return {"status": "success", "content": [{"text": f"Prompt updated"}]}
13
14 if action == "add_context":
15 existing = os.environ.get("SYSTEM_PROMPT", "")
16 merged = f"{existing}\n\n{prompt}"
17 os.environ["SYSTEM_PROMPT"] = merged
18 Path(".prompt").write_text(merged)
19 return {"status": "success", "content": [{"text": "Context appended."}]}
20 # ... 其他 action
這種模式讓 Agent 能根據使用經驗動態調整自己的行為——接近 meta-learning (元學習) 的概念。
5.6 雙向串流 (Bidirectional Streaming)
對應範例:python/01-learn/09-bidi-streaming/
支援語音輸入/輸出的即時雙向串流,可搭配:
- Amazon Nova Sonic:AWS 原生語音模型
- OpenAI Realtime API:GPT-4o 語音
- Google Gemini:Gemini 即時串流
範例包含 WebSocket client HTML 和伺服器端 Python 實作。
6. Agent 可呼叫性分析 (Agent Callability Analysis)
6.1 CLI 使用
Samples 中的範例主要透過 Python script 或 Jupyter Notebook 執行:
1# 執行 Python script 範例
2cd python/01-learn/01-first-agent/02-simple-interactive-usecase
3python recipe_bot.py
4
5# 執行 Jupyter Notebook 範例
6cd python/01-learn/11-swarm
7jupyter notebook swarm.ipynb
8
9# TypeScript 範例
10cd typescript/01-learn/01-first-agent
11npm install && npx ts-node src/firstAgent.ts
6.2 MCP 整合
Strands Agents 原生支援 MCP (Model Context Protocol; 模型上下文協定):
1from strands import Agent
2from strands.tools.mcp import MCPClient
3
4# 連接 MCP server
5mcp_client = MCPClient("npx -y @modelcontextprotocol/server-filesystem /tmp")
6
7# 將 MCP 工具注入 Agent
8with mcp_client:
9 tools = mcp_client.list_tools()
10 agent = Agent(tools=tools)
11 agent("List files in /tmp")
在 strands-agents 生態系中,mcp-server repo 本身就是一個 MCP server,提供 Strands 文件查詢能力給其他 AI 工具使用。
6.3 API / 部署模式
對應範例:python/02-deploy/
| 部署方式 | 範例路徑 | 適用場景 |
|---|---|---|
| AWS Lambda | 02-deploy/01-lambda/ | Serverless (無伺服器) API 端點 |
| AWS Fargate | 02-deploy/02-fargate/ | 長時間執行的容器化 Agent |
| AgentCore | 02-deploy/03-agentcore/ | AWS 原生 Agent 託管服務 |
| AgentCore Multi-Agent | 02-deploy/04-agentcore-multi-agent/ | A2A 協定的分散式 Agent |
部署範例使用 AWS CDK (Cloud Development Kit) 管理基礎設施,包含完整的 Dockerfile、CDK Stack 和前置部署腳本。
7. 與生態系的關係 (Ecosystem Relationships)
7.1 Strands Agents 生態系全景
Strands Agents 組織下共有 12 個 repo,形成完整的 Agent 開發平台:
| Repo | Stars | 角色 | 與 Samples 的關係 |
|---|---|---|---|
| harness-sdk | 6,187 | 核心 Python SDK | Samples 的所有範例都依賴此 SDK |
| tools | 1,092 | 官方工具集 | Samples 中大量使用 strands_tools |
| agent-sop | 1,015 | 自然語言 SOP 工作流 | Samples 展示如何使用 SOP 模式 |
| samples | 793 | 範例與教學 | 本 repo |
| sdk-typescript | 699 | TypeScript SDK | Samples 的 TS 範例依賴此 SDK |
| agent-builder | 419 | 終端機 Agent 建構器 | Samples 的互動式替代入口 |
| mcp-server | 286 | MCP 文件伺服器 | 可搭配 Samples 使用的輔助工具 |
| docs | 197 | 文件站台 | Samples 中的連結指向此文件 |
| evals | 144 | 評估框架 | Samples 06-evaluate 使用此框架 |
| shell | 103 | 安全 Shell 工具 | Samples 中的 shell 工具來源 |
| devtools | 13 | CI/CD 共用工具 | 內部開發用 |
| extension-template | 2 | 擴展模板 | 自訂擴展的起始模板 |
7.2 依賴關係圖
1 ┌─────────────┐
2 │ harness-sdk │ ◄── 核心 SDK
3 │ (Python) │
4 └──────┬──────┘
5 │
6 ┌────────────┼────────────┐
7 │ │ │
8 ┌─────▼─────┐ ┌───▼───┐ ┌──────▼──────┐
9 │ tools │ │ shell │ │ agent-sop │
10 │ (工具集) │ │(安全) │ │ (SOP 工作流)│
11 └─────┬─────┘ └───┬───┘ └──────┬──────┘
12 │ │ │
13 └────────────┼────────────┘
14 │
15 ┌──────▼──────┐
16 │ ★ samples │ ◄── 組合所有元件的範例
17 │ (本 repo) │
18 └──────┬──────┘
19 │
20 ┌────────────┼────────────┐
21 │ │ │
22 ┌─────▼─────┐ ┌───▼────┐ ┌─────▼─────┐
23 │ docs │ │ evals │ │mcp-server │
24 │ (文件) │ │(評估) │ │(MCP 輔助) │
25 └───────────┘ └────────┘ └───────────┘
7.3 與其他 Agent 框架的對比
| 特性 | Strands Agents | LangGraph | CrewAI | AutoGen |
|---|---|---|---|---|
| 驅動方式 | Model-driven | Workflow-driven | Role-driven | Conversation-driven |
| AWS 整合 | 原生 | 需自行接入 | 需自行接入 | 需自行接入 |
| MCP 支援 | 原生 | 有限 | 無 | 有限 |
| 多 Agent | Swarm + Graph + Agent-as-Tool | Graph | Crew | GroupChat |
| 學習曲線 | 低 | 中 | 低 | 中 |
| 維護者 | AWS | LangChain | CrewAI | Microsoft |
8. 優缺點分析 (Strengths & Limitations)
8.1 優勢 (Strengths)
完整的學習路徑 (comprehensive learning path)
Samples 從最簡單的「三行 Agent」循序漸進到「邊緣裝置機器人」,覆蓋 18 個基礎教學 + 4 個部署模式 + 多個產業應用。初學者可以按編號順序學習,進階開發者可以直接跳到特定主題。
產業級參考實作 (industry-grade reference implementations)
金融 Swarm Agent、醫療文件處理 Agent、物流自訂編排 Agent 等產業範例,不只是 Hello World,而是包含前置部署腳本、清理腳本、架構圖的完整應用。
雙語言支援 (dual language support)
Python 和 TypeScript 範例並行,TypeScript SDK 已有瀏覽器端 Agent 範例 (06-browser-agent),適合前端開發者。
先進的 Agent 模式 (advanced agent patterns)
自我擴展 Agent、自我修改 system prompt、Human-in-the-Loop 中斷恢復——這些在其他框架中很少以如此結構化的教學呈現。
內建安全機制 (built-in safety mechanisms)
Swarm 的防乒乓偵測、Guardrails 整合、Hook 攔截機制——都是生產環境必需但其他框架常忽略的。
8.2 限制 (Limitations)
AWS 偏向 (AWS bias)
大部分範例預設使用 Amazon Bedrock、Lambda、Fargate 等 AWS 服務。雖然可透過 LiteLLM 切換到 OpenAI / Ollama,但部署相關範例強依賴 AWS 基礎設施。
Notebook 為主的呈現方式 (notebook-centric presentation)
多數教學以 Jupyter Notebook (.ipynb) 而非純 Python script 呈現。Notebook 適合互動式學習,但不利於直接複製到生產專案。
TypeScript 範例較少 (fewer TypeScript samples)
TypeScript 目前只有 6 個學習教學和 1 個部署範例,遠少於 Python 的 50+ 個範例。TypeScript SDK 仍標注為 NEW。
缺乏端對端測試範例 (lacking E2E test examples)
06-evaluate/ 目錄的內容相對薄弱,缺少完整的 Agent 行為測試和回歸測試最佳實作。
部分範例需要 AWS 帳號 (AWS account requirement)
許多範例需要有效的 AWS 帳號和 Bedrock 模型存取權限才能執行,增加了嘗試門檻。
9. 實戰應用場景 (Real-world Use Cases)
9.1 場景一:金融 Swarm Agent — 股票分析團隊
對應範例:python/04-industry-use-cases/finance/finance-assistant-swarm-agent/
問題描述:投資分析師需要快速獲取一家公司的股價、財務指標和營運分析,但這些資訊分散在不同的資料來源。
解決方案:建立一個 Swarm,包含三個專業 Agent:
stock_price_agent:負責即時股價查詢和技術指標financial_metrics_agent:負責財務報表分析(PE ratio、revenue growth 等)company_analysis_agent:負責彙整前兩者資訊並產出綜合分析報告
Swarm 的優勢:各 Agent 可以主動 handoff 給有相關專業的夥伴,不需要預先定義固定流程。例如 company_analysis_agent 在分析中發現需要更細的財務數據,可以直接 handoff 給 financial_metrics_agent 取得後再繼續。
9.2 場景二:醫療文件處理 Agent
對應範例:python/04-industry-use-cases/healthcare/medical-document-processing-assistant/
問題描述:醫療院所需要處理大量非結構化的醫療文件(病歷、檢驗報告、診斷書),從中提取 ICD codes (國際疾病分類代碼) 和 CPT codes (醫療行為代碼)。
解決方案:建立帶有自訂 medical_coding_tools 的 Agent,能夠:
- 讀取上傳的醫療文件
- 識別診斷和處置項目
- 自動對應 ICD-10 / CPT 代碼
- 產出結構化的 coding report (編碼報告)
技術亮點:使用 @tool 裝飾器包裝醫療編碼邏輯,讓 LLM 在理解文件語意後,自行決定呼叫哪些編碼工具。這比傳統的 NLP pipeline (自然語言處理管線) 更彈性,因為 LLM 能處理非標準格式和同義詞。
9.3 場景三:邊緣裝置機器人控制
對應範例:python/08-edge/strands-spot-agent/
問題描述:需要用自然語言指揮 Boston Dynamics Spot 機器狗執行巡檢任務。
解決方案:在邊緣裝置上部署 Strands Agent,整合 Spot SDK 的控制 API 為工具:
- 移動控制 (walk, turn, sit, stand)
- 感測器讀取 (camera, lidar, battery status)
- 任務執行 (patrol route, take photo, report status)
技術亮點:這是 Physical AI (實體 AI) 的展示。Agent 不只處理文字,還能透過工具呼叫控制實體機器人。Strands 的 model-driven approach 讓開發者不需要寫複雜的狀態機——只要定義工具和 system prompt,LLM 自行決定動作序列。
附錄:快速參考表
範例索引表
| 編號 | 主題 | 難度 | 關鍵概念 |
|---|---|---|---|
| 01 | First Agent | 入門 | Agent 建立、基本對話 |
| 02 | Tools & MCP | 入門 | @tool、MCP 整合 |
| 03 | Model Providers | 入門 | Bedrock、OpenAI、Ollama 切換 |
| 04 | Streaming | 中級 | 串流回應處理 |
| 05 | Guardrails | 中級 | Bedrock Guardrails 安全護欄 |
| 06 | Memory | 中級 | OpenSearch、Mem0 記憶系統 |
| 07 | AWS Services | 中級 | DynamoDB、Knowledge Base 整合 |
| 08 | Observability | 中級 | OpenTelemetry 追蹤 |
| 09 | Bidi Streaming | 進階 | 雙向語音串流 |
| 10 | Agents as Tools | 進階 | Agent 階層式協作 |
| 11 | Swarm | 進階 | 多 Agent 自組織協作 |
| 12 | Graph | 進階 | 拓撲式 Agent 編排 |
| 13 | Human-in-the-Loop | 進階 | 中斷與人類審核 |
| 14 | Plugins | 進階 | 外掛系統 |
| 15 | Skills | 進階 | 模組化指令管理 |
| 16 | Hooks Lifecycle | 進階 | 完整生命週期 Hook |
| 17 | Conversation Mgmt | 進階 | 對話管理與持久化 |
| 18 | Self-Improving | 專家 | 自我擴展與修改 |
常用指令速查
1# 安裝核心依賴
2pip install strands-agents strands-agents-tools
3
4# 執行特定範例
5cd python/01-learn/01-first-agent
6pip install -r requirements.txt
7python 02-simple-interactive-usecase/recipe_bot.py
8
9# 啟動 Jupyter Notebook
10jupyter notebook python/01-learn/11-swarm/swarm.ipynb
11
12# TypeScript 範例
13cd typescript/01-learn/01-first-agent
14npm install && npx ts-node src/firstAgent.ts
Comments