Claude Info
AI-инструменты

Strands Agents Python SDK

strands-agents/sdk-python

Strands Agents — лёгкий и гибкий Python SDK для построения AI-агентов: от простых ассистентов до сложных автономных систем. Поддерживает Amazon Bedrock, Anthropic, Gemini, Ollama, OpenAI и другие провайдеры, а также нативную интеграцию с MCP-серверами.

Подключение

terminal
bash
git clone https://github.com/strands-agents/sdk-python.git

README

Strands Agents — простой, но мощный SDK, реализующий модельно-ориентированный подход к созданию и запуску AI-агентов. От простых разговорных ассистентов до сложных автономных рабочих процессов, от локальной разработки до продакшн-развёртывания — Strands Agents масштабируется под ваши задачи.

Обзор возможностей

  • Лёгкий и гибкий: простой цикл агента, который работает из коробки и полностью настраивается
  • Независимость от модели: поддержка Amazon Bedrock, Anthropic, Gemini, LiteLLM, Llama, Ollama, OpenAI, Writer и пользовательских провайдеров
  • Расширенные возможности: мультиагентные системы, автономные агенты и поддержка стриминга
  • Встроенная поддержка MCP: нативная интеграция с MCP-серверами, открывающая доступ к тысячам готовых инструментов

Быстрый старт

bash
# Установка Strands Agents
pip install strands-agents strands-agents-tools
py
from strands import Agent
from strands_tools import calculator
agent = Agent(tools=[calculator])
agent("What is the square root of 1764")

Примечание: Для провайдера по умолчанию (Amazon Bedrock) необходимо настроить AWS-учётные данные и включить доступ к модели Claude 4 Sonnet в регионе us-west-2. Подробнее о настройке других провайдеров — в Руководстве по быстрому старту.

Установка

Убедитесь, что установлен Python 3.10+, затем выполните:

bash
# Создание и активация виртуального окружения
python -m venv .venv
source .venv/bin/activate  # На Windows: .venv\Scripts\activate

# Установка Strands и инструментов
pip install strands-agents strands-agents-tools

Возможности в деталях

Инструменты на основе Python

Создавайте инструменты с помощью Python-декораторов:

py
from strands import Agent, tool

@tool
def word_count(text: str) -> int:
    """Count words in text.

    This docstring is used by the LLM to understand the tool's purpose.
    """
    return len(text.split())

agent = Agent(tools=[word_count])
response = agent("How many words are in this sentence?")

Горячая перезагрузка из директории: Включите автоматическую загрузку и перезагрузку инструментов из директории ./tools/:

py
from strands import Agent

# Агент будет отслеживать изменения в директории ./tools/
agent = Agent(load_tools_from_directory=True)
response = agent("Use any tools you find in the tools directory")

Поддержка MCP

Бесшовная интеграция с MCP-серверами:

py
from strands import Agent
from strands.tools.mcp import MCPClient
from mcp import stdio_client, StdioServerParameters

aws_docs_client = MCPClient(
    lambda: stdio_client(StdioServerParameters(command="uvx", args=["awslabs.aws-documentation-mcp-server@latest"]))
)

with aws_docs_client:
   agent = Agent(tools=aws_docs_client.list_tools_sync())
   response = agent("Tell me about Amazon Bedrock and how to use it with Python")

Несколько провайдеров моделей

Поддержка различных провайдеров моделей:

py
from strands import Agent
from strands.models import BedrockModel
from strands.models.ollama import OllamaModel
from strands.models.llamaapi import LlamaAPIModel
from strands.models.gemini import GeminiModel
from strands.models.llamacpp import LlamaCppModel

# Bedrock
bedrock_model = BedrockModel(
  model_id="us.amazon.nova-pro-v1:0",
  temperature=0.3,
  streaming=True, # Включить/отключить стриминг
)
agent = Agent(model=bedrock_model)
agent("Tell me about Agentic AI")

# Google Gemini
gemini_model = GeminiModel(
  client_args={
    "api_key": "your_gemini_api_key",
  },
  model_id="gemini-2.5-flash",
  params={"temperature": 0.7}
)
agent = Agent(model=gemini_model)
agent("Tell me about Agentic AI")

# Ollama
ollama_model = OllamaModel(
  host="http://localhost:11434",
  model_id="llama3"
)
agent = Agent(model=ollama_model)
agent("Tell me about Agentic AI")

# Llama API
llama_model = LlamaAPIModel(
    model_id="Llama-4-Maverick-17B-128E-Instruct-FP8",
)
agent = Agent(model=llama_model)
response = agent("Tell me about Agentic AI")

Встроенные провайдеры:

Мультиагентные системы

Создавайте сложные системы из нескольких агентов:

py
from strands import Agent

research_agent = Agent(
    system_prompt="You are a research specialist. Gather and analyze information thoroughly."
)

writing_agent = Agent(
    system_prompt="You are a technical writer. Create clear, concise documentation."
)

orchestrator = Agent(
    system_prompt="You coordinate research and writing tasks.",
    tools=[research_agent.as_tool(tool_name="researcher"), writing_agent.as_tool(tool_name="writer")]
)

orchestrator("Research quantum computing and write a technical summary")

Стриминг

Обработка ответов агента в режиме реального времени:

py
from strands import Agent
from strands.handlers import PrintingCallbackHandler

agent = Agent(callback_handler=PrintingCallbackHandler())
response = agent("Explain the theory of relativity")

Документация

Полная документация доступна на strandsagents.com, включая:

Участие в разработке

Мы приветствуем вклад сообщества! Ознакомьтесь с руководством по участию, чтобы узнать, как начать.

Безопасность

Если вы обнаружили уязвимость безопасности, пожалуйста, ознакомьтесь с нашей политикой безопасности.

Лицензия

Данный проект распространяется под лицензией Apache 2.0. Подробности — в файле LICENSE.

Похожие MCP-серверы