名称: aws-strands 描述: 使用 Strands Agents SDK 构建 AI 代理。适用于开发模型无关代理、实施 ReAct 模式、创建多代理系统或在 AWS 上构建生产代理。触发词:Strands、Strands SDK、模型无关代理、ReAct 代理。
Strands Agents SDK
使用 Strands 框架构建模型无关的 AI 代理。
安装
pip install strands-agents strands-agents-tools
# 或使用 npm
npm install @strands-agents/sdk
快速开始
from strands import Agent
from strands.tools import tool
@tool
def get_weather(city: str) -> str:
"""获取城市的当前天气。"""
# 实现
return f"{city}的天气: 72°F, 晴"
agent = Agent(
model="anthropic.claude-3-sonnet",
tools=[get_weather]
)
response = agent("西雅图的天气如何?")
print(response)
TypeScript/JavaScript
import { Agent, tool } from '@strands-agents/sdk';
const getWeather = tool({
name: 'get_weather',
description: '获取城市的当前天气',
parameters: {
city: { type: 'string', description: '城市名称' }
},
handler: async ({ city }) => {
return `Weather in ${city}: 72°F, Sunny`;
}
});
const agent = new Agent({
model: 'anthropic.claude-3-sonnet',
tools: [getWeather]
});
const response = await agent.run('What\'s the weather in Seattle?');
模型无关
Strands 支持任何 LLM:
from strands import Agent
# Anthropic(默认)
agent = Agent(model="anthropic.claude-3-sonnet")
# OpenAI
agent = Agent(model="openai.gpt-4o")
# Amazon Bedrock
agent = Agent(model="amazon.titan-text-premier")
# 自定义端点
agent = Agent(
model="custom",
endpoint="https://your-model-endpoint.com",
api_key="..."
)
工具定义模式
装饰器风格
from strands.tools import tool
@tool
def search_database(query: str, limit: int = 10) -> list[dict]:
"""搜索产品数据库。
参数:
query: 搜索查询字符串
limit: 返回结果的最大数量
"""
# 实现
return results
类风格
from strands.tools import Tool
class DatabaseSearchTool(Tool):
name = "search_database"
description = "搜索产品数据库"
def parameters(self):
return {
"query": {"type": "string", "description": "搜索查询"},
"limit": {"type": "integer", "default": 10}
}
def run(self, query: str, limit: int = 10):
return self.db.search(query, limit)
ReAct 模式
内置 ReAct(推理 + 行动)支持:
from strands import Agent, ReActStrategy
agent = Agent(
model="anthropic.claude-3-sonnet",
tools=[search_tool, calculate_tool],
strategy=ReActStrategy(
max_iterations=10,
verbose=True
)
)
# 代理将推理复杂的多步骤任务
response = agent("""
在我们的数据库中查找前 3 个产品,
计算它们的平均价格,
并推荐我们是否应调整定价。
""")
多代理系统
from strands import Agent, MultiAgentOrchestrator
# 专家代理
researcher = Agent(
name="researcher",
model="anthropic.claude-3-sonnet",
tools=[web_search, document_reader],
system_prompt="您是一名研究专家。"
)
analyst = Agent(
name="analyst",
model="anthropic.claude-3-sonnet",
tools=[data_analyzer, chart_generator],
system_prompt="您是一名数据分析师。"
)
writer = Agent(
name="writer",
model="anthropic.claude-3-sonnet",
tools=[document_writer],
system_prompt="您是一名技术作家。"
)
# 编排器
orchestrator = MultiAgentOrchestrator(
agents=[researcher, analyst, writer],
routing="supervisor" # 或 "round_robin"、"intent"
)
response = orchestrator.run(
"研究 AI 趋势,分析数据,并撰写报告"
)
流式响应
from strands import Agent
agent = Agent(model="anthropic.claude-3-sonnet")
# 流式响应
for chunk in agent.stream("解释量子计算"):
print(chunk, end="", flush=True)
内存管理
from strands import Agent
from strands.memory import ConversationMemory, SemanticMemory
agent = Agent(
model="anthropic.claude-3-sonnet",
memory=[
ConversationMemory(max_turns=10),
SemanticMemory(embedding_model="text-embedding-3-small")
]
)
# 内存在调用间持久化
agent("我的名字是 Alice")
agent("我叫什么名字?") # 记得:"您的名字是 Alice"
AgentCore 集成
将 Strands 与 AWS Bedrock AgentCore 结合使用:
from strands import Agent
from strands.tools import tool
import boto3
agentcore_client = boto3.client('bedrock-agentcore')
@tool
def query_cloudwatch(metric_name: str, namespace: str) -> dict:
"""通过 AgentCore 网关查询 CloudWatch 指标。"""
return agentcore_client.invoke_tool(
tool_name="cloudwatch_query",
parameters={"metric": metric_name, "namespace": namespace}
)
agent = Agent(
model="anthropic.claude-3-sonnet",
tools=[query_cloudwatch]
)
官方用例
Strands 在 AWS AgentCore 示例中展示:
A2A 多代理事件响应:使用 Strands 进行监控代理
cd amazon-bedrock-agentcore-samples/02-use-cases/A2A-multi-agent-incident-response
# 监控代理使用 Strands SDK 进行 CloudWatch、日志、指标管理