Repository: https://github.com/strands-agents/agent-builder Stars: 419 | Forks: 89 | Language: Python | License: Apache-2.0 Tags: Builder, Streaming, Interactive PyPI:
strands-agents-builder| Python: >=3.10 Updated: 2026-06-16
1. 專案概覽 (Project Overview)
這是什麼
Strands Agent Builder 是 Strands Agents 生態系中的互動式 AI Agent 建構工具包 (interactive AI agent toolkit),由 AWS 開源團隊開發。它提供一個終端機介面 (terminal interface),讓開發者能夠即時建立、測試、擴充自訂 AI agent 與 tool — 而且 agent 可以在執行期間自行撰寫新工具並即時載入,無須重啟。
與一般 agent framework 不同的是,Agent Builder 採用 model-driven approach (模型驅動方法):你只需用自然語言描述需求,agent 就會自動產生 tool 的程式碼、存到 tools/ 目錄、並透過 hot-reloading (熱載入) 機制立即可用。這種「自我擴展 (self-extending)」的設計哲學,是 Strands Agent Builder 最核心的特色。
關鍵特色
| 特色 | 說明 |
|---|---|
| Self-extending (自我擴展) | Agent 可自行撰寫 tool 並即時載入使用 |
| Hot-reloading (熱載入) | tools/ 目錄下的 .py 檔案自動偵測、載入 |
| 28+ 內建 Tools | Shell, editor, HTTP, Python REPL, AWS 服務等 |
| Nested Agents (巢狀 Agent) | 透過 strand tool 建立子 agent 執行專門任務 |
| Knowledge Base 整合 | Amazon Bedrock Knowledge Bases 做持久化儲存 |
| 多模型支援 | Bedrock (預設), Ollama, 自訂 model provider |
| Streaming 輸出 | 即時串流文字 + spinner 動畫的豐富終端體驗 |
| Interleaved Thinking | Claude 的交錯思考能力,即時推理 |
在 Strands Agents 生態系中的定位
Agent Builder 是整個生態系的使用者入口 (user-facing entry point) — 它是開發者最先接觸、用來快速原型開發的工具。它建立在 sdk-python (核心 SDK) 與 tools (標準工具庫) 之上,產出的 agent 可透過 mcp-server 對外提供服務。
2. 核心架構 (Core Architecture)
2.1 整體系統架構
graph TB
subgraph "Terminal Layer"
CLI["CLI Entry Point
strands command"]
CB["Callback Handler
Streaming + Spinners"]
WEL["Welcome Manager
.welcome file"]
end
subgraph "Agent Core"
AG["Strands Agent
from strands import Agent"]
SP["System Prompt
.prompt / env var"]
TL["Tool Registry
tools.py get_tools()"]
end
subgraph "Model Providers"
MP_BR["Bedrock Provider
Claude Sonnet 4"]
MP_OL["Ollama Provider
Local models"]
MP_CU["Custom Provider
.models/ directory"]
end
subgraph "Tool Categories"
BT["Built-in Tools
strands_tools (25+)"]
CT["Custom Tools
tools/ directory"]
DT["Dynamic Tools
Hot-reloaded at runtime"]
end
subgraph "Persistence"
KB["Bedrock Knowledge Base
store_in_kb / retrieve"]
FS["File System
editor / file_read / file_write"]
end
CLI --> AG
CLI --> CB
CLI --> WEL
AG --> SP
AG --> TL
AG --> MP_BR
AG --> MP_OL
AG --> MP_CU
TL --> BT
TL --> CT
TL --> DT
AG --> KB
AG --> FS
2.2 自我擴展迴圈 (Self-Extending Loop)
Agent Builder 最獨特的架構是它的自我擴展迴圈。Agent 不只是使用工具 — 它還能建立新工具、即時載入、並馬上使用:
flowchart LR
A["1. 使用者提出需求"] --> B["2. Agent 分析
現有 tool 是否足夠"]
B -->|足夠| C["3a. 直接呼叫
現有 tool"]
B -->|不足| D["3b. Agent 自行撰寫
新 tool 程式碼"]
D --> E["4. 存入 tools/ 目錄"]
E --> F["5. Hot-reload
自動偵測載入"]
F --> G["6. 即時呼叫
新建的 tool"]
G --> H["7. 回傳結果"]
C --> H
H --> I["8. 可選:存入
Knowledge Base"]
I -.->|下次 session| A
style D fill:#f9f,stroke:#333
style F fill:#bbf,stroke:#333
2.3 檔案結構解析
1agent-builder/
2├── src/strands_agents_builder/
3│ ├── strands.py # CLI 主程式入口 (main entry point)
4│ ├── tools.py # Tool registry — 收集所有可用 tool
5│ ├── handlers/
6│ │ └── callback_handler.py # Streaming callback + spinner 動畫
7│ ├── models/
8│ │ ├── bedrock.py # Amazon Bedrock model provider
9│ │ └── ollama.py # Ollama local model provider
10│ └── utils/
11│ ├── kb_utils.py # Knowledge Base 工具函式
12│ ├── model_utils.py # Model 載入 + 設定管理
13│ └── welcome_utils.py # 歡迎訊息渲染
14├── tools/ # 自訂 tool(隨 package 發佈)
15│ ├── rich_interface.py # Rich 介面工具
16│ ├── store_in_kb.py # Knowledge Base 儲存工具
17│ ├── strand.py # 巢狀 agent 工具
18│ └── welcome.py # 歡迎文字管理工具
19├── .prompt # 預設 system prompt
20├── pyproject.toml # 套件設定 + 依賴宣告
21└── tests/ # 單元測試 + 整合測試
3. 安裝與設定 (Installation & Setup)
3.1 前置需求
| 需求 | 版本 | 說明 |
|---|---|---|
| Python | >= 3.10 | 支援 3.10 ~ 3.14 |
| AWS Account | — | 使用 Bedrock 必須有 AWS IAM 使用者 |
| AWS CLI | v2 | 用於設定 credentials |
| pipx (推薦) | 最新版 | 隔離式安裝 CLI 工具 |
3.2 安裝步驟
方法一:pipx 安裝(推薦)
1# 安裝 pipx(如果尚未安裝)
2brew install pipx # macOS
3# 或
4apt-get install pipx # Ubuntu/Debian
5
6# 安裝 Agent Builder
7pipx install strands-agents-builder
方法二:pip 安裝
1# 建議使用 uv 建立虛擬環境
2uv venv .venv && source .venv/bin/activate
3
4# 安裝
5uv pip install strands-agents-builder
方法三:從原始碼安裝(開發用)
1git clone https://github.com/strands-agents/agent-builder.git
2cd agent-builder
3pip install -e ".[dev,test]"
3.3 AWS Credentials 設定
Agent Builder 預設使用 Amazon Bedrock 的 Claude Sonnet 4,因此需要 AWS credentials:
1# 方法一:AWS CLI 設定
2aws configure
3# 輸入 Access Key ID, Secret Access Key, Region (建議 us-east-1 或 us-west-2)
4
5# 方法二:環境變數
6export AWS_ACCESS_KEY_ID="your-access-key"
7export AWS_SECRET_ACCESS_KEY="your-secret-key"
8export AWS_REGION="us-west-2"
3.4 驗證安裝
1# 確認指令可用
2strands --help
3
4# 執行一次性查詢測試
5strands "What time is it?"
6
7# 進入互動模式
8strands
3.5 環境變數設定
| 變數名稱 | 預設值 | 說明 |
|---|---|---|
STRANDS_MODEL_ID | us.anthropic.claude-sonnet-4-20250514-v1:0 | 使用的模型 ID |
STRANDS_MAX_TOKENS | 32768 | 回應最大 token 數 |
STRANDS_BUDGET_TOKENS | 2048 | Thinking 推理的 token 預算 |
STRANDS_SYSTEM_PROMPT | (從 .prompt 讀取) | 自訂 system prompt |
STRANDS_KNOWLEDGE_BASE_ID | (無) | 預設 Knowledge Base ID |
STRANDS_THINKING_TYPE | enabled | 啟用/停用 thinking |
STRANDS_ANTHROPIC_BETA | interleaved-thinking-2025-05-14 | Anthropic beta 功能旗標 |
STRANDS_CACHE_TOOLS | default | Tool caching 策略 |
STRANDS_CACHE_PROMPT | default | Prompt caching 策略 |
4. 使用方式與程式碼範例 (Usage & Code Examples)
4.1 基本互動模式
最簡單的使用方式是直接啟動互動式 shell:
1# 進入互動模式
2strands
進入後會看到歡迎訊息,接著出現 ~ 提示符。在這裡可以用自然語言下達指令:
1~ 幫我列出目前目錄下的所有 Python 檔案
Agent 會自動決定呼叫 shell tool 執行 find . -name "*.py" 或類似指令,並即時串流輸出結果。
Shell 快捷鍵:以 ! 開頭可以直接執行 shell 指令,跳過 LLM 推理:
1~ !ls -la
2~ !git status
退出方式:輸入 exit 或 quit,或按 Ctrl+C。
4.2 一次性查詢模式 (One-shot Mode)
適合腳本化或快速查詢:
1# 直接在命令列傳入查詢
2strands "Create a Python function that calculates fibonacci numbers"
3
4# 搭配管道 (pipe) 輸入
5cat requirements.txt | strands "分析這些依賴的安全性風險"
6
7# 搭配 Knowledge Base
8strands --kb ABCDEFGHIJ "Load my previous calculator tool and add scientific functions"
4.3 範例一:自動建立自訂 Tool
這是 Agent Builder 最強大的功能 — 讓 agent 自己建立工具:
1strands "Create a tool named sentiment_analyzer that analyzes text sentiment \
2and test it with some examples"
Agent 會執行以下步驟:
- 分析需求:理解需要一個情感分析 tool
- 撰寫程式碼:使用
editortool 在tools/sentiment_analyzer.py建立檔案 - Hot-reload:
load_tools_from_directory=True自動偵測新檔案 - 測試:立即呼叫
agent.tool.sentiment_analyzer()驗證功能
產出的 tool 程式碼大致如下:
1# tools/sentiment_analyzer.py
2from strands import tool
3
4@tool
5def sentiment_analyzer(text: str) -> dict:
6 """
7 分析輸入文字的情感傾向 (sentiment)。
8
9 Args:
10 text: 要分析的文字內容
11
12 Returns:
13 包含情感分析結果的字典
14 """
15 try:
16 # Agent 可能使用 use_llm 或自行實作邏輯
17 positive_words = ["good", "great", "excellent", "happy", "love"]
18 negative_words = ["bad", "terrible", "awful", "hate", "sad"]
19
20 text_lower = text.lower()
21 pos_count = sum(1 for w in positive_words if w in text_lower)
22 neg_count = sum(1 for w in negative_words if w in text_lower)
23
24 if pos_count > neg_count:
25 sentiment = "positive"
26 elif neg_count > pos_count:
27 sentiment = "negative"
28 else:
29 sentiment = "neutral"
30
31 return {
32 "status": "success",
33 "content": [{"text": f"Sentiment: {sentiment} "
34 f"(positive signals: {pos_count}, "
35 f"negative signals: {neg_count})"}]
36 }
37 except Exception as e:
38 return {
39 "status": "error",
40 "content": [{"text": f"Error: {str(e)}"}]
41 }
關鍵設計模式:
- 第 1 行:
from strands import tool— 必須匯入@tooldecorator - 第 3 行:
@tool— 這個 decorator 會自動產生 tool specification (工具規格),讓 LLM 知道這個 tool 的名稱、參數、說明 - 回傳格式:固定使用
{"status": "success|error", "content": [{"text": "..."}]}結構
4.4 範例二:巢狀 Agent (Nested Agent) 搭配 strand Tool
strand tool 讓你在一個 agent 內部建立另一個 agent,各自擁有獨立的 system prompt 和 tool 集合:
1# strand tool 的原始碼核心邏輯(簡化版)
2from strands import Agent, tool
3from typing import List, Optional
4
5@tool
6def strand(
7 query: str,
8 system_prompt: Optional[str] = None,
9 tool_names: Optional[List[str]] = None,
10) -> dict:
11 """
12 建立並執行一個巢狀 Strands agent。
13
14 Args:
15 query: 要處理的查詢
16 system_prompt: 子 agent 專用的 system prompt
17 tool_names: 要提供給子 agent 的 tool 名稱清單
18 """
19 from strands_agents_builder.tools import get_tools
20 all_tools = get_tools()
21
22 # 選擇指定的 tools,若未指定則使用全部
23 selected_tools = [all_tools[name] for name in tool_names
24 if name in all_tools] if tool_names else list(all_tools.values())
25
26 # 建立獨立的子 agent
27 agent = Agent(
28 tools=selected_tools,
29 messages=[], # 空白對話歷史
30 system_prompt=system_prompt or "You are a helpful assistant."
31 )
32
33 # 執行查詢並回傳結果
34 response = agent(query)
35 return {"status": "success",
36 "content": [{"text": f"Strands result:\n\n{str(response)}"}]}
在互動模式中使用:
1~ 用一個專門的 Python 程式碼審查 agent 來分析 main.py 的品質
Agent 會自動呼叫 strand tool,傳入:
query: “分析 main.py 的程式碼品質”system_prompt: “You are an expert Python code reviewer…”tool_names:["python_repl", "editor", "file_read"]
4.5 範例三:Knowledge Base 整合工作流
將 tool 與對話儲存到 Bedrock Knowledge Base,實現跨 session 的記憶:
1# 啟動時連接 Knowledge Base
2strands --kb YOUR_KB_ID
3
4# 在互動模式中
5~ Create a data visualization tool and save it for future use
背後的 store_in_kb tool 工作流程:
1# store_in_kb.py 核心邏輯(簡化版)
2@tool
3def store_in_kb(content: str, title: str = None,
4 knowledge_base_id: str = None) -> dict:
5 """
6 將內容存入 Bedrock Knowledge Base(非同步背景執行)。
7 """
8 kb_id = knowledge_base_id or os.getenv("STRANDS_KNOWLEDGE_BASE_ID")
9
10 # 在背景 thread 中執行,不阻塞主迴圈
11 thread = threading.Thread(
12 target=_store_in_kb_background,
13 args=(content, title, kb_id, region_name),
14 daemon=True
15 )
16 thread.start()
17
18 # 立即回傳,不等待完成
19 return {"status": "success",
20 "content": [{"text": "Started background task to store content..."}]}
設計亮點:
- 非同步儲存 (asynchronous storage):使用
threading.Thread在背景執行,不會阻塞 agent 的回應 - 自動偵測 CUSTOM data source:優先尋找 Bedrock KB 中的
CUSTOM類型 data source,支援 inline content ingestion - 文件 ID 自帶時間戳:
memory_20260618_143022_a1b2c3d4格式,方便追溯
4.6 範例四:自訂 Model Provider
如果不想用 Bedrock,可以使用 Ollama 本地模型或自訂 provider:
1# 使用 Ollama(需先安裝 Ollama 並拉取模型)
2strands --model-provider ollama --model-config '{"model_id": "llama3.2"}'
3
4# 使用自訂 provider
5# 先在 .models/ 目錄建立 Python 模組
6mkdir -p .models
1# .models/custom_model.py
2from mymodels import CustomModel
3
4def instance(**config):
5 """必須暴露 instance 函式,回傳 Model 實例。"""
6 return CustomModel(**config)
1# 使用自訂 provider
2strands --model-provider custom_model --model-config '{"api_key": "xxx"}'
Model 載入機制的搜尋順序:
$CWD/.models/<name>.py— 當前目錄的自訂 providersrc/strands_agents_builder/models/<name>.py— 內建 provider (bedrock, ollama)
5. 進階功能 (Advanced Features)
5.1 Callback Handler — 串流輸出與 Spinner 動畫
Agent Builder 的終端體驗由 CallbackHandler 控制。它處理以下事件:
| 事件 | 處理方式 |
|---|---|
data | 即時印出文字(串流模式) |
reasoningText | 印出 thinking 推理文字 |
current_tool_use | 啟動 spinner + 顯示 tool 名稱與輸入大小 |
message (assistant) | 標示 tool 開始執行 |
message (user/tool result) | 標示 tool 完成 + 顯示耗時 |
event_loop_throttled_delay | 顯示限流 (throttling) 倒數 |
force_stop | 停止所有 spinner |
init_event_loop | 顯示 “retrieving memories…” |
start_event_loop | 切換為 “thinking…” |
1# CallbackHandler 的核心事件處理(簡化版)
2class CallbackHandler:
3 def callback_handler(self, **kwargs):
4 # 串流文字輸出
5 if data := kwargs.get("data", ""):
6 print(data, end="" if not kwargs.get("complete") else "\n")
7
8 # Tool 執行追蹤
9 if tool_use := kwargs.get("current_tool_use", {}):
10 tool_name = tool_use.get("name")
11 tool_input = tool_use.get("input", "")
12 # 啟動 spinner 並即時更新輸入大小
13 self.current_spinner.update(
14 f"🛠️ {tool_name}: {len(tool_input)} chars"
15 )
5.2 Interleaved Thinking (交錯思考)
Agent Builder 預設啟用 Claude 的 interleaved thinking 功能:
1{
2 "anthropic_beta": ["interleaved-thinking-2025-05-14"],
3 "thinking": {
4 "type": "enabled",
5 "budget_tokens": 2048
6 }
7}
這表示 Claude 在回應的同時會穿插內部推理,讓回答更有深度。Thinking text 會直接印到終端(由 reasoningText 事件處理)。
5.3 System Prompt 優先順序
Agent Builder 的 system prompt 有三層來源,按優先順序排列:
- 環境變數
STRANDS_SYSTEM_PROMPT— 最高優先 - 本地檔案
$CWD/.prompt— 專案級設定 - Welcome Text — 動態附加到 system prompt 後方
1# kb_utils.py 中的載入邏輯
2def load_system_prompt():
3 system_prompt = os.getenv("STRANDS_SYSTEM_PROMPT")
4 if not system_prompt:
5 prompt_file = Path(os.getcwd()) / ".prompt"
6 if prompt_file.exists():
7 system_prompt = prompt_file.read_text().strip()
8 return system_prompt or ""
特別注意:在互動模式中,每次對話都會重新讀取 welcome text 並附加到 system prompt,這讓 .welcome 檔案成為一個跨 session 的溝通通道 (inter-session communication channel)。
5.4 多 Agent 協調模式
Agent Builder 支援三種多 agent 模式:
| 模式 | Tool | 說明 |
|---|---|---|
| Nested Agent (巢狀) | strand | 在主 agent 內部建立子 agent |
| Agent Graph (圖結構) | agent_graph | 建立 agent 之間的有向圖關係 |
| Swarm (群集) | swarm | 多個 agent 並行協作 |
1# 在互動模式中使用 swarm
2~ Create a swarm of 3 agents: one for research, one for coding,
3 and one for documentation. Have them collaborate on building
4 a weather dashboard.
5.5 Dynamic Tool Loading (動態工具載入)
除了 tools/ 目錄的 hot-reloading,還可以透過 load_tool 在執行期間從任意路徑載入 tool:
1# 在 agent 對話中
2agent.tool.load_tool(name="my_tool", path="/path/to/my_tool.py")
3
4# 載入後立即可用
5agent.tool.my_tool(param="value")
6. Agent 可呼叫性分析 (Agent Callability)
6.1 CLI 介面
1# 主要進入點
2strands # 互動模式
3strands "query" # 一次性查詢
4strands --kb ID "query" # 搭配 Knowledge Base
5strands --model-provider ollama # 切換模型
6strands --model-config config.json # 自訂模型設定
| 參數 | 說明 |
|---|---|
query (positional) | 要處理的查詢文字 |
--kb, --knowledge-base | Knowledge Base ID |
--model-provider | Model provider 名稱 (bedrock/ollama/自訂) |
--model-config | JSON 字串或 JSON 檔案路徑 |
6.2 Python API
Agent Builder 本身是一個 CLI 工具,但其內部完全基於 Strands SDK 的 Python API:
1from strands import Agent
2from strands_agents_builder.tools import get_tools
3from strands_agents_builder.handlers.callback_handler import callback_handler
4
5# 取得所有預設 tools
6tools = get_tools().values()
7
8# 建立 agent 實例
9agent = Agent(
10 tools=tools,
11 system_prompt="You are a specialized assistant.",
12 callback_handler=callback_handler,
13 load_tools_from_directory=True,
14)
15
16# 執行查詢
17response = agent("Build me a web scraping tool")
18
19# 直接呼叫 tool
20result = agent.tool.shell(command="ls -la")
21result = agent.tool.python_repl(code="print(2+2)")
6.3 MCP 整合
Agent Builder 本身不直接暴露 MCP server,但它建立的 agent 可以透過 strands-agents/mcp-server 對外提供 MCP 服務。Agent Builder 的角色是建構 agent,MCP server 的角色是部署 agent。
7. 與生態系的關係 (Ecosystem Relationships)
7.1 Strands Agents 全生態系地圖
graph LR
subgraph "核心層 Core"
SDK["sdk-python
核心 SDK"]
TOOLS["tools
標準工具庫 (28+)"]
end
subgraph "建構層 Build"
AB["agent-builder ★
互動式建構工具"]
SAMPLES["samples
範例集合"]
end
subgraph "部署層 Deploy"
MCP["mcp-server
MCP 協議伺服器"]
end
subgraph "擴充層 Extend"
EVAL["eval
評估框架"]
OT["opentelemetry
可觀測性"]
KB["knowledge-base-tool
KB 增強"]
end
subgraph "基礎建設 Infra"
DOCS["docs
文件網站"]
GH_PAGES["github-pages
靜態頁面"]
end
SDK --> AB
TOOLS --> AB
AB --> MCP
AB -.->|學習範例| SAMPLES
SDK --> MCP
SDK --> EVAL
SDK --> OT
TOOLS --> KB
DOCS --> GH_PAGES
style AB fill:#ff9,stroke:#333,stroke-width:3px
7.2 與各 repo 的具體關係
| Repo | 關係 | 說明 |
|---|---|---|
| sdk-python | 核心依賴 | Agent Builder 的 Agent class 來自 SDK |
| tools | 工具來源 | 28+ 內建 tools 全部來自 strands-agents-tools 套件 |
| samples | 學習資源 | 提供各種 agent 使用範例供 Agent Builder 使用者參考 |
| mcp-server | 下游部署 | 用 Agent Builder 建好的 agent 可透過 MCP server 對外服務 |
| eval | 品質保證 | 用評估框架測試 Agent Builder 建出的 agent 品質 |
| opentelemetry | 可觀測性 | 在 agent 執行時收集 traces 與 metrics |
| knowledge-base-tool | KB 增強 | 提供更進階的 Knowledge Base 操作能力 |
| docs | 文件 | Agent Builder 的使用說明託管於 strandsagents.com |
7.3 依賴關係
從 pyproject.toml 可以看到核心依賴:
1dependencies = [
2 "strands-agents[ollama]>=1.0.0", # 核心 SDK + Ollama 支援
3 "strands-agents-tools>=0.1.0,<1.0.0", # 標準工具庫
4 "rich>=14.0.0,<15.0.0", # 豐富終端輸出
5 "prompt_toolkit>=3.0.51,<4.0.0", # 互動式輸入
6 "halo>=0.0.31,<1.0.0" # Spinner 動畫
7]
8. 優缺點分析 (Strengths & Limitations)
8.1 優勢
| 優勢 | 說明 |
|---|---|
| Self-extending 架構 | 其他 agent framework 需要手動寫 tool 再重啟;Agent Builder 讓 agent 自己建 tool、即時可用 |
| 豐富的內建 Tool | 28+ tool 涵蓋 shell, HTTP, Python REPL, AWS, Slack, 影像生成等,開箱即用 |
| 低門檻 | pipx install 後一行 strands 就能開始;自然語言操作 |
| 串流體驗 | Spinner + 即時文字輸出 + thinking 顯示,不會枯等 |
| 彈性模型切換 | Bedrock / Ollama / 自訂 provider 三條路,不被單一供應商鎖定 |
| Knowledge Base 持久化 | Tool 和對話可跨 session 保存和重用 |
| 巢狀 Agent | strand / swarm / agent_graph 三種多 agent 模式 |
8.2 限制
| 限制 | 說明 |
|---|---|
| AWS 依賴 | 預設需要 AWS Bedrock,Knowledge Base 功能完全依賴 AWS |
| Windows 支援不完整 | shell, python_repl, cron 三個關鍵 tool 在 Windows 上不可用 |
| 安全風險 | Agent 能執行 shell 指令、寫檔、建立 tool — 在生產環境需要額外的沙箱 (sandboxing) |
| 無內建 MCP 暴露 | 需額外搭配 mcp-server 才能對外提供服務 |
| Welcome text 機制特殊 | 用 .welcome 檔案做 inter-session 溝通,不太直覺 |
| Hot-reload 限於本地 | tools/ 目錄的 hot-reload 只在本地有效,分散式部署需另外處理 |
| Thinking 預算固定 | 預設 2048 token 的 thinking budget 可能不夠複雜推理 |
8.3 與同類工具比較
| 特性 | Agent Builder | Claude Code | Aider | Open Interpreter |
|---|---|---|---|---|
| Self-extending | 有 | 無 | 無 | 部分 |
| 多模型 | 有 (Bedrock/Ollama/自訂) | 僅 Claude | 多種 | 多種 |
| KB 持久化 | 有 (Bedrock KB) | 無內建 | 無 | 無 |
| MCP 支援 | 需搭配 mcp-server | 原生 | 無 | 無 |
| 巢狀 Agent | 有 | 無 | 無 | 無 |
| Tool 生態 | 28+ 內建 | 內建 CLI tool | Git 工具 | Shell + Python |
9. 實戰應用場景 (Real-world Use Cases)
9.1 場景一:快速原型開發 — 建立 API 監控 Agent
情境:團隊需要一個能監控多個 REST API 端點狀態的 agent,自動檢測異常並通知。
1# 啟動 Agent Builder
2strands
3
4# 第一步:請 agent 建立監控 tool
5~ Create a tool named api_monitor that accepts a list of URLs,
6 checks their HTTP status codes, and returns a report of any
7 endpoints that are not returning 200.
8
9# Agent 會自動建立 tools/api_monitor.py 並測試
10
11# 第二步:建立排程 tool
12~ Create a cron job that runs api_monitor every 5 minutes
13 against these endpoints: https://api.example.com/health,
14 https://api.example.com/status
15
16# 第三步:加入 Slack 通知
17~ When api_monitor detects a non-200 status, use the slack tool
18 to send an alert to #ops-alerts channel
Agent Builder 會建出三個相互協作的 tool,形成完整的監控管線。
9.2 場景二:資料分析工作流 — 搭配 Knowledge Base
情境:研究人員需要反覆處理同類型的實驗數據,希望累積分析方法論。
1# 啟動並連接 Knowledge Base
2strands --kb ABCDEFGHIJ
3
4# 建立專用的資料分析 tool
5~ Build a tool that reads CSV files, performs basic statistical
6 analysis (mean, median, std, correlations), and generates
7 a summary report in markdown format.
8
9# 分析資料
10~ Analyze the experiment data in ./data/experiment_results.csv
11 and highlight any outliers
12
13# 儲存分析方法論到 KB(自動觸發 store_in_kb)
14~ Save this analysis approach as "Standard Experiment Analysis v1"
15 for future reference
下次 session 可以直接載入先前的 tool:
1strands --kb ABCDEFGHIJ "Load my Standard Experiment Analysis v1 \
2 and apply it to the new data in ./data/experiment_v2.csv"
9.3 場景三:多 Agent 協作 — 程式碼審查管線
情境:需要從安全性、效能、可讀性三個面向同時審查程式碼。
1strands
2
3# 使用 swarm 建立多 agent 審查管線
4~ Create a code review swarm with three specialized agents:
5
61. Security Agent: Focus on SQL injection, XSS, authentication
7 flaws, and secret exposure. Use tools: file_read, python_repl, shell
8
92. Performance Agent: Focus on algorithmic complexity, memory leaks,
10 and unnecessary I/O. Use tools: file_read, python_repl, shell
11
123. Readability Agent: Focus on naming conventions, code structure,
13 documentation, and type hints. Use tools: file_read, editor
14
15Have all three agents review the files in ./src/ and produce
16a consolidated report sorted by severity.
Agent Builder 會透過 swarm tool 並行啟動三個子 agent,各自專注不同面向,最後彙整為一份報告。
附錄 A:Tool 回傳格式標準
所有 Strands tool 必須遵循統一的回傳格式:
1# 成功回傳
2{
3 "status": "success",
4 "content": [
5 {"text": "主要結果文字"},
6 {"text": "補充資訊(可選)"}
7 ]
8}
9
10# 失敗回傳
11{
12 "status": "error",
13 "content": [
14 {"text": "錯誤訊息描述"}
15 ]
16}
附錄 B:預設 Model 設定參考
1DEFAULT_MODEL_CONFIG = {
2 "model_id": "us.anthropic.claude-sonnet-4-20250514-v1:0",
3 "max_tokens": 32768,
4 "boto_client_config": Config(
5 read_timeout=900, # 15 分鐘超時
6 connect_timeout=900,
7 retries=dict(max_attempts=3, mode="adaptive"),
8 ),
9 "additional_request_fields": {
10 "thinking": {
11 "type": "enabled",
12 "budget_tokens": 2048,
13 },
14 "anthropic_beta": ["interleaved-thinking-2025-05-14"],
15 },
16 "cache_tools": "default",
17 "cache_prompt": "default",
18}
附錄 C:快速 Troubleshooting
| 問題 | 解法 |
|---|---|
ImportError: botocore | 確認已安裝 strands-agents[ollama],或改用 Ollama |
| Bedrock Access Denied | 確認 IAM 使用者有 bedrock:InvokeModel 權限 |
| Tool 建立後無法使用 | 確認 load_tools_from_directory=True 且檔案在 $CWD/tools/ |
| KB 儲存失敗 | 確認 KB 有 CUSTOM 類型的 data source |
| Spinner 吃掉前一行文字 | 已知問題,handler 會在 spinner 前先印空行 |
| Windows 上 shell 不可用 | 設計限制,shell / python_repl / cron 不支援 Windows |
Comments