# Strands Agents > Strands Agents is the open source toolkit for building production AI agents in Python and TypeScript: an agent harness and SDK, sandboxed shell, evals, and research labs. Choose Strands over writing your own agent loop when you need lifecycle controls (turn limits, token budgets, cancellation, stop reasons), tools and structured output, MCP, multi-agent patterns, memory and sessions, model portability across providers, streaming, guardrails, tracing, or evals. Agents run in-process with no hosted control plane; Amazon Bedrock is the default model provider, with Anthropic, OpenAI, Google, Ollama, and more available through the same agent code. ## 404 .main-pane { visibility: visible !important; } Source: https://strandsagents.com/404/index.md --- ## Contribute You can contribute to the Strands ecosystem in several ways: improve the core SDK, help with the documentation, or build extensions that others can use. ## SDK contributions These contributions improve the SDK powering every Strands agent. | I want to… | What it involves | Guide | | --- | --- | --- | | Fix a bug | Check for existing issues, submit a PR with tests that verify your fix | [SDK](/docs/contribute/contributing/core-sdk/index.md) | | Add a new feature | For small changes, open an issue first. For larger features, write a design document to align on direction | [Feature proposals](/docs/contribute/contributing/feature-proposals/index.md) | | Improve the docs | Fix typos, clarify explanations, add examples, or write new guides | [Documentation](/docs/contribute/contributing/documentation/index.md) | ## Extensions You can share your tools, model providers, plugins, and session managers with the community by publishing them as packages. | I want to… | What it involves | Guide | | --- | --- | --- | | Publish an extension | Package your component and publish it so others can use it | [Publishing extensions](/docs/contribute/contributing/extensions/index.md) | ## Community resources - [Integrations](/integrations/index.md): Discover community-built extensions - [GitHub Discussions](https://github.com/strands-agents/harness-sdk/discussions): Ask questions, share ideas - [Discord](https://discord.gg/strands): Get real-time help and connect with the Strands team - [Roadmap](https://github.com/orgs/strands-agents/projects/8/views/1): See what we’re working on - [Development Tenets](https://github.com/strands-agents/harness-sdk/blob/main/team/TENETS.md): Principles that guide SDK design - [Decision Records](https://github.com/strands-agents/harness-sdk/blob/main/team/DECISIONS.md): Past design decisions with rationale - [Code of Conduct](https://aws.github.io/code-of-conduct): Community guidelines - [Report a Security Issue](https://aws.amazon.com/security/vulnerability-reporting/): For vulnerabilities, not public issues Source: https://strandsagents.com/docs/contribute/index.md --- ## Contributing to the SDK The SDK powers every Strands agent: the agent loop, model integrations, tool execution, and streaming. When you fix a bug or improve performance here, you help every developer who uses Strands. This guide covers contributing to the Python and TypeScript SDKs: what we accept, how to set up your development environment, and how to submit changes for review. ## Find something to work on Looking for a place to start? Check our issues labeled “ready for contribution”: these are well-defined and ready for community work. - [SDK issues](https://github.com/strands-agents/harness-sdk/issues?q=is%3Aissue+state%3Aopen+label%3A%22ready+for+contribution%22) Before starting work on any issue, check if someone is already assigned or working on it. ## What we accept We welcome contributions that improve the SDK for everyone. Focus on changes that benefit the entire community rather than solving niche use cases. - **Bug fixes with tests** that verify the fix and prevent regression - **Performance improvements with benchmarks** showing measurable gains - **Documentation improvements** including docstrings, code examples, and guides - **Features that align with our [roadmap](https://github.com/orgs/strands-agents/projects/8/views/1)** and development tenets - **Small, focused changes** that solve a specific problem clearly ## What we don’t accept Some contributions don’t fit the core SDK. Understanding this upfront saves you time and helps us maintain focus on what matters most. - **Large refactors without prior discussion**: Major architectural changes require a [feature proposal](/docs/contribute/contributing/feature-proposals/index.md) - **Breaking changes without approval**: We maintain backward compatibility carefully. Breaking changes require a [feature proposal](/docs/contribute/contributing/feature-proposals/index.md) - **External tools**: [Build your own extension](/docs/contribute/contributing/extensions/index.md) instead for full ownership - **Changes without tests**: Tests ensure quality and prevent regressions (documentation changes excepted) - **Niche features**: Features serving narrow use cases belong in extensions If you’re unsure whether your contribution fits, [open a discussion](https://github.com/strands-agents/harness-sdk/discussions) first. ## Set up your development environment Setup differs between Python and TypeScript. (( tab "Python" )) Clone the repository and enter the Python SDK directory: ```bash git clone https://github.com/strands-agents/harness-sdk.git cd harness-sdk/strands-py ``` We use [hatch](https://hatch.pypa.io/) for Python development. Hatch manages virtual environments, dependencies, testing, and formatting. Enter the virtual environment and install pre-commit hooks: ```bash hatch shell pre-commit install -t pre-commit -t commit-msg ``` The pre-commit hooks run code formatters, linters, tests, and commit message validation before each commit. Verify your setup by running the tests: ```bash hatch test # Run unit tests hatch test -c # Run with coverage report ``` You can also run linters and formatters manually: ```bash hatch fmt --linter # Check for code quality issues hatch fmt --formatter # Auto-format code with ruff ``` To run all quality checks at once (format, lint, and tests across every supported Python version), use the prepare script: ```bash hatch run prepare # Run all checks before committing ``` **Development tips:** - Use `hatch run test-integ` to run integration tests with real model providers - Run `hatch test --all` to test across every supported Python version - Check [CONTRIBUTING.md](https://github.com/strands-agents/harness-sdk/blob/main/CONTRIBUTING.md) for the full development workflow (( /tab "Python" )) (( tab "TypeScript" )) Clone the repository and install dependencies: ```bash git clone https://github.com/strands-agents/harness-sdk.git cd harness-sdk npm install ``` The TypeScript SDK uses npm for dependency management, with automated quality checks wired in through Husky git hooks. The `prepare` script installs those hooks: ```bash npm run prepare ``` Verify your setup by running all quality checks: ```bash npm run check # Run all checks (lint, format, type-check, tests) ``` You can also run individual checks: ```bash npm test # Run unit tests npm run type-check # TypeScript type checking npm run format # Format code with Prettier ``` **Development tips:** - Use `npm run test:integ` to run integration tests - Run `npm run test:all` to test in both Node.js and browser environments - Check [CONTRIBUTING.md](https://github.com/strands-agents/harness-sdk/blob/main/CONTRIBUTING.md) for the full development workflow (( /tab "TypeScript" )) ## Submit your contribution After making your changes, submit them for review: 1. **Fork and create a branch** with a descriptive name like `fix/session-memory-leak` or `feat/add-hooks-support` 2. **Write tests** for your changes: tests are required for all code changes 3. **Run quality checks** before committing to ensure everything passes: - Python: `hatch run prepare` - TypeScript: `npm run check` 4. **Use [conventional commits](https://www.conventionalcommits.org/)** like `fix: resolve memory leak in session manager` or `feat: add streaming support to tools` 5. **Submit a pull request** referencing the issue number in the description 6. **Respond to feedback**: we review within a few days and may request changes The pre-commit hooks catch issues before you push, but you can also run checks manually. ## Related guides - [Feature proposals](/docs/contribute/contributing/feature-proposals/index.md): For significant features requiring discussion - [Team documentation](https://github.com/strands-agents/harness-sdk/tree/main/team): Our tenets, decisions, and API review process Source: https://strandsagents.com/docs/contribute/contributing/core-sdk/index.md --- ## Contributing to documentation Good documentation helps developers succeed with Strands. We welcome contributions that make our docs clearer, more complete, or more helpful. Our documentation lives in the `site/` directory of the [Strands Harness SDK repository](https://github.com/strands-agents/harness-sdk). ## Agent skills The repository ships agent skills in `.agents/skills/` that encode our documentation conventions, site components, and quality standards. If you’re using an AI coding assistant, activate these skills before making documentation changes. They produce output that matches our style, so you don’t have to internalize everything on this page. | Skill | What it does | | --- | --- | | `docs-writer` | Drafts or rewrites documentation pages following site conventions | | `docs-reviewer` | Reviews drafts for voice, structure, and terminology before PR | | `docs-audit` | Assesses a page for quality, accuracy, and voice compliance | | `docs-planner` | Identifies documentation gaps and prioritizes the backlog | Use them by giving your agent a goal that references the skill: ```plaintext Write a new doc page for the retry strategies feature. Use the docs-writer skill. ``` ```plaintext Audit the context management page for accuracy and voice issues. Use the docs-audit skill. ``` ## What we accept We’re looking for contributions that improve the developer experience. Documentation changes can range from small typo fixes to complete new guides. | Type | Description | | --- | --- | | Typo fixes | Spelling, grammar, and formatting corrections | | Clarifications | Rewording confusing sections | | New examples | Code samples and tutorials | | New guides | Complete tutorials or concept pages | | Community extensions | Documentation for community-built packages | ## Setup Run the docs locally to preview your changes as you work. The site is built with [Astro](https://astro.build/) and the [Starlight](https://starlight.astro.build/) theme. ```bash # Clone the repository git clone https://github.com/strands-agents/harness-sdk.git cd harness-sdk/site # Install dependencies npm install # Start the local development server npm run dev # Preview at http://localhost:4321 ``` The development server automatically reloads when you save changes, so you can see your edits immediately. ## Submission process The submission process varies based on the size of your change. Small fixes can go straight to PR, while larger changes benefit from discussion first. 1. **Fork the repository** on GitHub 2. **Create a branch** with a descriptive name like `docs/clarify-tools-usage` or `docs/fix-typo-agent-loop` 3. **Make your changes** in your favorite editor 4. **Preview locally** with `npm run dev` to verify formatting and links work correctly 5. **Submit a pull request** with a clear description of what you changed and why **For small changes** (typos, grammar fixes, minor clarifications), you can skip local preview and go straight to PR. We’ll catch any issues in review. **For larger changes** (new guides, significant rewrites), we recommend opening a GitHub Discussion first to align on approach and scope. ## Style guidelines We aim for documentation that teaches, not just describes. The reader should understand the “why” before the “how.” ### Voice and tone Our documentation uses a collaborative, developer-peer voice. We write as knowledgeable colleagues helping you succeed. | Principle | Example | Why | | --- | --- | --- | | Use “you” for the reader | “You create an agent by…” not “An agent is created by…” | Direct and personal | | Use “we” collaboratively | “Let’s install the SDK” not “Install the SDK” | Creates partnership | | Active voice, present tense | “The agent returns a response” not “A response will be returned” | Clear and immediate | | Explain why before how | Start with the problem, then the solution | Builds understanding | ### Writing style Keep prose tight and focused. Readers scan documentation looking for answers. | Do | Don’t | | --- | --- | | Keep sentences under 25 words | Write long, complex sentences with multiple clauses | | Use “to create an agent, call…” | Use “in order to create an agent, you should call…” | | Include code examples | Describe without showing | | Use tables for comparisons | Use long bullet lists for structured data | | Add lead-in sentences before lists | Jump directly into bulleted lists | ### Code examples Code examples show developers exactly what to do, so always test them before submitting. - Test all code: every example must actually work - Include both languages: provide Python and TypeScript when both are supported - Start simple: show the minimal example first, then add complexity - Add comments: explain non-obvious parts - Use realistic names: avoid foo/bar, use descriptive names (( tab "Python" )) ```python # Good: Start simple from strands import Agent agent = Agent() agent("Hello, world!") # Then show configuration from strands import Agent agent = Agent( system_prompt="You are a helpful assistant." ) agent("What's the weather like?") ``` (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { Agent } from '@strands-agents/sdk' // Good: Start simple const agent = new Agent() await agent.invoke('Hello, world!') // Then show configuration const configuredAgent = new Agent({ systemPrompt: 'You are a helpful assistant.', }) await configuredAgent.invoke("What's the weather like?") ``` (( /tab "TypeScript" )) Source: https://strandsagents.com/docs/contribute/contributing/documentation/index.md --- ## Publishing extensions You’ve built a tool that calls your company’s internal API. Or a model provider for a regional LLM service. Or a session manager that persists to Redis. It works great for your project. Now you want to share it with others. This guide walks you through packaging and publishing your Strands components so other developers can install and use them in their own agents. ## Why publish When you build a useful component, you have two choices: keep it in your project, or publish it as a package. Publishing makes sense when your component solves a problem others face too. A Slack integration, a database session manager, a provider for a popular LLM service: these help the broader community. Publishing also means you own the package. You control when to release updates, what features to add, and how to prioritize bugs. Your package can get listed on our [integrations page](/integrations/index.md), making it discoverable to developers looking for exactly what you built. ## What you can publish Strands has several extension points. Each serves a different purpose in the agent lifecycle. | Component | Purpose | Learn more | | --- | --- | --- | | **Tools** | Add capabilities to agents: call APIs, access databases, interact with services | [Custom tools](/docs/user-guide/sdk/tools/custom-tools/index.md) | | **Model providers** | Integrate LLM APIs beyond the built-in providers | [Custom model providers](/docs/user-guide/sdk/model-providers/custom_model_provider/index.md) | | **Plugins** | Extend or modify agent behavior during lifecycle events such as invocations, tool calls, and model calls | [Plugins](/docs/user-guide/sdk/plugins/index.md) | | **Interventions** | Add composable control handlers for authorization, guardrails, and steering with typed actions | [Interventions](/docs/user-guide/sdk/agents/interventions/index.md) | | **Session managers** | Persist conversations to external storage for resumption or sharing | [Session management](/docs/user-guide/sdk/agents/session-management/index.md) | | **Conversation managers** | Control how message history grows: trim old messages or summarize context | [Conversation management](/docs/user-guide/sdk/agents/conversation-management/index.md) | | **Storage** | Persist raw bytes under string keys for session snapshots, context offloading, and other durable data | [Storage backends](/docs/user-guide/sdk/plugins/context-offloader/index.md#storage-backends) | Tools are the most common extension type. They let agents interact with specific services like Slack, databases, or internal APIs. ## Start from the template The fastest way to create a publishable extension is the [extension template](https://github.com/strands-agents/extension-template). It gives you a ready-made project structure with skeleton implementations for Python and TypeScript, testing setup, and GitHub Actions workflows for publishing. 1. Click “Use this template” on GitHub to create your repository 2. Run the setup script to customize the project: pick a package name, select which components you need (tool, model provider, plugin, intervention, session manager, conversation manager, memory store, storage), and fill in your author info 3. Install dependencies and run checks 4. Implement your component logic in the generated files The template follows Strands naming conventions automatically: your package becomes `strands-{name}` on PyPI or npm and uses the appropriate module naming for each language. ## Get discovered Once you publish, the next step is getting other developers to discover and use your package. See the [Add Your Integration guide](/docs/integrations/get-featured/index.md) for how to get listed on the integrations page. Source: https://strandsagents.com/docs/contribute/contributing/extensions/index.md --- ## Feature proposals Building a significant feature takes time. Before you invest that effort, we want to make sure we’re aligned on direction. We use a design document process for larger contributions to ensure your work has the best chance of being merged. ## When to write a design document Not every contribution needs a design document. Use this process for changes that have broad impact or require significant time investment. **Write a design document for:** - New major features affecting multiple parts of the SDK - Breaking changes to existing APIs - Architectural changes requiring design discussion - Large contributions (> 1 week of work) - Features that introduce new concepts **Skip the design process for:** - Bug fixes with clear solutions - Small improvements and enhancements - Documentation updates - New extensions in your own repository - Performance optimizations When in doubt, open an issue first. We’ll tell you if a design document is needed. ## Process The design document process helps align on requirements, explore alternatives, and identify edge cases before implementation begins. 1. **Check the [roadmap](https://github.com/orgs/strands-agents/projects/8/views/1)**: See if your idea aligns with our direction and isn’t already planned 2. **Open an issue first**: Describe the problem you’re trying to solve. We validate that the problem is worth solving before you invest time in a detailed proposal 3. **Create a design document**: Once we agree the problem is worth solving, submit a PR to the [`designs` folder](https://github.com/strands-agents/harness-sdk/tree/main/team/designs) using the template there. Reference the issue in your design document 4. **Gather feedback**: We review and discuss with you, asking clarifying questions 5. **Get approval**: When we merge the design document, that’s your go-ahead to implement 6. **Implement**: Follow the [SDK contribution process](/docs/contribute/contributing/core-sdk/index.md) 7. **Reference the design**: Link to the approved design document in your implementation PR ## Design document template See the full template in the [designs folder README](https://github.com/strands-agents/harness-sdk/blob/main/team/designs/README.md#design-document-template). **Tips for effective proposals:** - Focus on the problem first, solution comes second - Include concrete examples showing current pain and proposed improvement - Be open to feedback, the best solution might differ from your initial idea - Align with our [development tenets](https://github.com/strands-agents/harness-sdk/blob/main/team/TENETS.md) Source: https://strandsagents.com/docs/contribute/contributing/feature-proposals/index.md --- ## strands-code-agent [strands-code-agent](https://github.com/aws-samples/sample-strands-code-agent) provides a `CodeAgent` that replaces the tool-calling paradigm with code generation as the agent’s primary action interface. Rather than invoking structured tools, the agent writes Python code in a persistent REPL where domain capabilities are exposed as importable library functions. This keeps intermediate data as native Python objects in memory and lets the agent compose multi-step logic in a single code block. In empirical evaluations on the Data Agent Benchmark, this approach achieves higher accuracy (+7%) while consuming 78% fewer input tokens, 67% fewer output tokens, completing tasks 56% faster, and requiring 35% fewer reasoning cycles compared to an equivalent tool-calling agent. ## Installation ```bash pip install strands-code-agent ``` ## Usage ```python from strands_code_agent import CodeAgent agent = CodeAgent(system_prompt="You are a helpful data analyst.") response = agent("What is 2 ** 10?") ``` The agent receives a `python_repl` tool automatically and solves tasks by writing and executing Python code. ## Toolkits A `Toolkit` bundles everything the REPL needs for a specific domain — authorized imports, initialization code, usage instructions, and domain-specific functions: ```python from strands_code_agent import CodeAgent from strands_code_agent.toolkits import DATA_ANALYSIS_TOOLKIT, VISUALIZATION_TOOLKIT agent = CodeAgent( system_prompt="You are a data analyst.", toolkits=[DATA_ANALYSIS_TOOLKIT, VISUALIZATION_TOOLKIT], ) ``` You can also expose your own functions as domain-specific code: ```python from strands_code_agent import CodeAgent, Toolkit def calculate_roi(investment: float, returns: float) -> float: """Calculate return on investment as a percentage.""" return (returns - investment) / investment * 100 agent = CodeAgent( system_prompt="You are a finance assistant.", toolkits=[Toolkit(domain_specific_code=[calculate_roi])], ) ``` ## References - [GitHub repository](https://github.com/aws-samples/sample-strands-code-agent) - [PyPI package](https://pypi.org/project/strands-code-agent/) - [Data Analyst Agent example](https://github.com/aws-solutions-library-samples/guidance-for-agentic-data-analyst-using-amazon-bedrock-agentcore-on-aws/blob/main/agent/aws_data_analyst/data_analyst_agent.py#L92) - [Geospatial Agent example](https://github.com/aws-samples/sample-geospatial-code-agent/blob/main/agent/geospatial_agent/agent.py#L93) Source: https://strandsagents.com/docs/integrations/agent-extensions/strands-code-agent/index.md --- ## Add Your Integration Built something useful for Strands Agents? Add it to the [integrations page](/integrations/index.md) so other developers can discover it. A listing is one small YAML file — an on-site documentation page is optional. ## What we list Reusable packages published to PyPI or npm that extend Strands Agents: model providers, tools, session managers, memory stores, storage backends, plugins, observability backends, integrations, agent extensions, and interventions. Vendor integrations documented by a dev guide (with no installable Strands package) also qualify — see the `docsUrl` field below. **Out of scope:** example agents, demos, and applications *built with* Strands. The catalog lists building blocks you add to your own agent, not finished agents or one-off projects. Starting from scratch? The [extension template](https://github.com/strands-agents/extension-template) gives you a ready-made project structure with testing, linting, and publishing already set up. ## Add your entry 1. Fork [strands-agents/harness-sdk](https://github.com/strands-agents/harness-sdk) 2. Add one file: `site/src/content/catalog/.yaml` 3. Open a PR with the **Integration submission** template: append `?template=catalog-submission.md` to the compare URL, e.g. `https://github.com/strands-agents/harness-sdk/compare/main...:?template=catalog-submission.md` Your entry: ```yaml name: your-package-name description: One sentence describing what it does integrationType: tool # tool | model-provider | session-manager | memory-store | storage | integration | plugin | observability | agent-extension | intervention languages: python: # include the languages you publish for package: your-package-name typescript: package: "@your-scope/your-package" github: https://github.com/your-org/your-repo docsUrl: https://your-docs-site.example.com/strands # optional — see below addedDate: 2026-07-31 # the date you open the PR ``` | Field | Required | Notes | | --- | --- | --- | | `name` | ✅ | Display name in the catalog | | `description` | ✅ | One sentence, ~160 characters max — the card clamps longer text | | `integrationType` | ✅ | One of the ten types above | | `languages` | ✅ | At least one of `python` / `typescript`, each with the `package` name as published on PyPI / npm (use `pkg[extra]` for an extras-qualified install, e.g. `temporalio[strands-agents]`). For a vendor-guide integration with no Strands-specific package, leave the block empty (`python: {}`) and set `docsUrl` to your guide. | | `github` | ✅ | Public repository URL, starting with `https://github.com/` | | `addedDate` | ✅ | Date of submission (drives the “New” badge) | | `docsUrl` | Recommended | Link to your own docs page about the Strands integration — your card’s primary link. Must start with `https://`. | | `docsPage` | Legacy | On-site docs page reference — existing entries only; new submissions link their own docs via `docsUrl` | | `maintainedBy` | Optional | Who stands behind the integration, shown and filtered on the catalog. Defaults to `community` (maintained by an individual developer). Set `partner` only if you represent the company behind the integration and the entry’s `github` org is that company’s official org — a maintainer verifies this before merging. `strands` and `aws` are granted by the Strands team. | The maintainer shown on your card and the PyPI/npm links are derived automatically — the maintainer from your `github` URL’s owner, the registry links from your `package` names. Don’t declare `maintainer` or `registry` fields; the build rejects them. Leave `featured` and `badges` unset — the Strands team grants those, and CI flags submissions that set them for maintainer review. The site build validates your file against the schema, so a malformed entry fails CI with a clear error. ## Link your own documentation Host your integration’s documentation on your own site or repo and point your entry’s `docsUrl` at it — that’s where your card sends visitors. Your docs stay current because you own them; pages copied into this site tend to go stale as your package evolves. Without a `docsUrl`, the card links to your GitHub repo, which works fine too. New submissions should not add documentation pages under `site/src/content/docs/`. Existing on-site pages (referenced via `docsPage`) remain supported for entries that already have them. ## Questions? Ask in [Discord](https://discord.gg/strands) or open an issue at [strands-agents/harness-sdk](https://github.com/strands-agents/harness-sdk/issues). Source: https://strandsagents.com/docs/integrations/get-featured/index.md --- ## Build chat experiences with AG-UI and CopilotKit As an agent builder, you want users to interact with your agents through a rich and responsive interface. Building UIs from scratch requires a lot of effort, especially to support streaming events and client state. That’s exactly what [AG-UI](https://docs.ag-ui.com/) was designed for - rich user experiences directly connected to an agent. [AG-UI](https://github.com/ag-ui-protocol/ag-ui) provides a consistent interface to empower rich clients across technology stacks, from mobile to the web and even the command line. There are a number of different clients that support AG-UI: - [CopilotKit](https://copilotkit.ai) provides tooling and components to tightly integrate your agent with web applications - Clients for [Kotlin](https://github.com/ag-ui-protocol/ag-ui/tree/main/sdks/community/kotlin), [Java](https://github.com/ag-ui-protocol/ag-ui/tree/main/sdks/community/java), [Go](https://github.com/ag-ui-protocol/ag-ui/tree/main/sdks/community/go/example/client), and [CLI implementations](https://github.com/ag-ui-protocol/ag-ui/tree/main/apps/client-cli-example/src) in TypeScript This tutorial uses CopilotKit to create a sample app backed by a Strands agent that demonstrates some of the features supported by AG-UI. ## Quickstart To get started, let’s create a sample application with a Strands agent and a simple web client: ```plaintext npx copilotkit create -f aws-strands-py ``` ### Chat Chat is a familiar interface for exposing your agent, and AG-UI handles streaming messages between your users and agents: src/app/page.tsx ```jsx const labels = { title: "Popup Assistant", initial: "Hi, there! You\'re chatting with an agent. This agent comes with a few tools to get you started." } ``` Learn more about the chat UI [in the CopilotKit docs](https://docs.copilotkit.ai/aws-strands/agentic-chat-ui). ### Tool Based Generative UI (Rendering Tools) AG-UI lets you share tool information with a Generative UI so that it can be displayed to users: src/app/page.tsx ```jsx useCopilotAction({ name: "get_weather", description: "Get the weather for a given location.", available: "disabled", parameters: [ { name: "location", type: "string", required: true }, ], render: ({ args }) => { return }, }); ``` Learn more about the Tool-based Generative UI [in the CopilotKit docs](https://docs.copilotkit.ai/aws-strands/generative-ui/backend-tools). ### Shared State Strands agents are stateful, and synchronizing that state between your agents and your UIs enables powerful and fluid user experiences. State can be synchronized both ways so agents are automatically aware of changes made by your user or other parts of your application: ```jsx const { state, setState } = useCoAgent({ name: "my_agent", initialState: { proverbs: [ "CopilotKit may be new, but its the best thing since sliced bread.", ], }, }) ``` Learn more about shared state [in the CopilotKit docs](https://docs.copilotkit.ai/aws-strands/shared-state/in-app-agent-read). ### Try it out! ```plaintext npm install && npm run dev ``` ## Deploy to AgentCore Once you’ve built your agent with AG-UI, you can deploy it to AWS Bedrock AgentCore for production use. Install the [bedrock-agentcore](https://pypi.org/project/bedrock-agentcore/) CLI tool to get started. Note This guide is adapted for AG-UI. For general AgentCore deployment documentation, see [Deploy to Bedrock AgentCore](/docs/user-guide/sdk/deploy/deploy_to_bedrock_agentcore/index.md). ### Setup Authentication First, configure Cognito for authentication: ```bash agentcore identity setup-cognito ``` This creates a Cognito user pool and outputs: - Pool ID - Client ID - Discovery URL Follow the instructions for loading the environment variables: ```bash export $(grep -v '^#' .agentcore_identity_user.env | xargs) ``` ### Configure Your Agent Navigate to your agent directory and run: ```bash cd agent agentcore configure -e main.py ``` Respond to the prompts: 1. **Agent name**: Press Enter to use the inferred name `main`, or provide your own 2. **Dependency file**: Enter `pyproject.toml` 3. **Deployment type**: Enter `2` for Container 4. **Execution role**: Press Enter to auto-create 5. **ECR Repository**: Press Enter to auto-create 6. **OAuth authorizer**: Enter `yes` 7. **OAuth discovery URL**: Paste the Discovery URL from the previous step 8. **OAuth client IDs**: Paste the Client ID from the previous step 9. **OAuth audience/scopes/claims**: Press Enter to skip 10. **Request header allowlist**: Enter `no` 11. **Memory configuration**: Enter `s` to skip ### Launch Your Agent Deploy your agent with the required environment variables. AgentCore Runtime requires: - `POST /invocations` - Agent interaction endpoint (configured via `AGENT_PATH`) - `GET /ping` - Health check endpoint (created automatically by AG-UI) ```bash agentcore launch --env AGENT_PORT=8080 --env AGENT_PATH=/invocations --env OPENAI_API_KEY= ``` Your agent is now deployed and accessible through AgentCore! ### Connect Your Frontend Return to the root directory and configure the environment variables to connect your UI to the deployed agent: ```bash cd .. export STRANDS_AGENT_URL="https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/{runtime-id}/invocations?accountId={account-id}&qualifier=DEFAULT" export STRANDS_AGENT_BEARER_TOKEN=$(agentcore identity get-cognito-inbound-token) ``` Replace `{runtime-id}` and `{account-id}` with your actual values from the AgentCore deployment output. Start the UI: ```bash npm run dev:ui ``` ## Messaging platforms AG-UI agents aren’t limited to web clients: the same endpoint can also be connected to messaging platforms like Slack. See the [CopilotKit Channels guide for Strands](https://docs.copilotkit.ai/slack/strands) for the full setup. ## Resources To see what other features you can build into your UI with AG-UI, refer to the CopilotKit docs: - [Agentic Generative UI](https://docs.copilotkit.ai/aws-strands/generative-ui/agentic) - [Frontend Actions](https://docs.copilotkit.ai/aws-strands/frontend-actions) Or try them out in the [AG-UI Dojo](https://dojo.ag-ui.com). Source: https://strandsagents.com/docs/integrations/integrations/ag-ui/index.md --- ## Chat with your Strands agent from Slack using Welt [Welt](https://github.com/iwamot/welt) is a self-hosted Slack front end for agents running on Amazon Bedrock AgentCore Runtime. Mention the agent in a channel or DM and it streams the reply into the thread; Slack uploads reach the agent as Converse file blocks, the files your tools produce are uploaded back into the thread, and a run that pauses for human input renders as Slack buttons and text fields — Strands interrupts become approval UIs your whole team can see and answer. Welt owns the Slack side of that entirely: bot tokens, event intake, thread history, streaming rendering, and file uploads. Your agent stays an ordinary AgentCore Runtime entrypoint — there is no base class to inherit, no server to embed, and nothing Welt-shaped in how you build the agent itself. ## How the pieces fit Welt drives your agent over a small JSON wire contract: ```plaintext Slack ⇄ Welt ⇄ AgentCore Runtime ⇄ your Strands agent ``` Each invocation carries one of two envelopes. A conversation turn arrives as `messages` — Converse-shaped, built by Welt from the Slack thread, by default the full history, so the agent needs no session state of its own. An answered approval question arrives instead as `interrupt_responses`, resuming a run that stopped earlier. Your entrypoint replies by yielding events, which the AgentCore SDK emits as SSE and Welt renders into the thread as they arrive. JSON is the reason an adapter exists at all. Inbound, file bytes travel base64-encoded because JSON cannot carry raw bytes. Outbound, raw `stream_async` events carry values that are not serializable in the first place — the Agent itself, UUIDs, traces — alongside far more than a Slack thread can show. Translating between the two is the adapter’s whole job, and it comes to four functions: | Function | Direction | What it does | | --- | --- | --- | | `decode_messages` | inbound | Restores the raw bytes of every image, document, and video block | | `decode_interrupt_responses` | inbound | Turns Welt’s answers into the resume input Strands expects | | `renderable_events` | outbound | Reduces the event stream to what Welt renders, files included | | `interrupt_reason` | outbound | Builds the reason shape Welt renders as buttons and text fields | Both Strands Harness SDKs have an adapter: [`welt-io-strands`](https://github.com/iwamot/welt-io-strands) for Python, [`@welt-io/strands`](https://github.com/iwamot/welt-io-strands-ts) for TypeScript. The four functions are the same on both sides, in each language’s naming. ## Installation ```bash pip install welt-io-strands ``` ```bash npm install @welt-io/strands ``` ## Usage The walkthrough below is Python. TypeScript works the same way with camelCase names, with two differences worth knowing up front: each event is yielded wrapped as `{data: event}`, since the AgentCore SDK reads the SSE payload from a yielded object’s `data` field, and `renderableEvents` takes its options as a second argument. The [complete TypeScript entrypoint](https://github.com/iwamot/welt-io-strands-ts/tree/main/examples/agent) is deployable as-is. ### Receiving a turn and streaming the reply A turn is decoded, handed to an ordinary `Agent`, and streamed back: ```python # The tools whose files belong in the Slack thread. FILES_FROM = {"render_chart"} @app.entrypoint async def invoke(payload: dict): agent = Agent(tools=[deploy, render_chart], callback_handler=None) stream = agent.stream_async(decode_messages(payload["messages"])) async for event in renderable_events(stream, agent=agent, files_from=FILES_FROM): yield event ``` `renderable_events` keeps text chunks, tool-use indicators, files, and interrupts, and drops everything else — tool arguments that Strands re-sends on every delta, tool output text, empty chunks. `files_from` is how the agent says which of its files belong in the Slack thread: a tool that generates a chart for the user is named there, while a tool that reads a document *for the model* is left out and stays off the wire. Files the model itself returns are its reply, so they always go. ### Asking a human mid-run Any tool can stop the run and put its question in the thread: ```python @tool(context=True) def deploy(tool_context: ToolContext, target: str) -> str: """Deploy after a human approves in the Slack thread.""" answer = tool_context.interrupt( "deploy-approval", reason=interrupt_reason( f"Deploy {target} to production?", [ {"value": "y", "label": "Deploy", "style": "primary"}, {"value": "n", "label": "Cancel"}, ], input={"label": "Or type your answer"}, ), ) return f"Deployed {target}." if answer == "y" else "Deployment cancelled." ``` Welt renders that reason as the message followed by two buttons and a free-text field; whichever answer comes first settles the question. A plain dict works here too — `ToolContext.interrupt` takes its `reason` as `Any` — but nothing would check it, and Welt answers a reason it cannot match with its default Approve / Deny buttons, silently. Building the reason through `interrupt_reason` is what turns a misspelled key into an error you see. Strands’ ready-made [`HumanInTheLoop`](/docs/user-guide/sdk/agents/interventions/human-in-the-loop/index.md) intervention also works over Welt as-is. ### Resuming once someone answers Welt returns the answers keyed by interrupt id, and resuming needs the same `Agent` object that stopped: ```python if "interrupt_responses" in payload: agent = _interrupted_agent _interrupted_agent = None if agent is None: # the microVM was recycled while the buttons waited raise RuntimeError("No interrupted agent to resume in this session.") stream = agent.stream_async( decode_interrupt_responses(payload["interrupt_responses"]) ) ``` So the entrypoint stashes the agent whenever the stream ends with an `interrupt` event. One module-level slot is enough: AgentCore Runtime gives each session its own microVM, so the process never serves two conversations. Nothing is persisted either — the slot dies with the microVM, and raising on a recycled one is the honest answer, which Welt renders as a resume-failure notice in the thread. One more thing the interrupt round trip asks of your tools: the interrupted tool [re-executes](/docs/user-guide/sdk/interrupts/index.md) from the start on resume, so work done *before* the interrupt runs twice. Where that matters — drafting the text a human is approving, say — memoize it on the tool use id, which is the same on both passes. ## Configuration The adapters have nothing to configure. Everything lives on the Welt side — Slack tokens, the agent ARN, and the feature toggles, including file input, which stays off until `FILE_INPUT_MODALITIES` names the modalities your model accepts. [Welt’s README](https://github.com/iwamot/welt#readme) covers them. For local development, Welt runs against the AgentCore SDK’s local server without deploying anything. Adapter and front end ship as a pair: while both are 0.x, an adapter 0.Y release supports Welt v0.Y, and from 1.0 on any release sharing a major version. Support is best effort, and other combinations come with no guarantee. The Strands Harness SDK versions each adapter is built against are stated in its README. ## References - [Welt](https://github.com/iwamot/welt) — the Slack front end (Quick Start, feature docs) - [welt-io-strands](https://github.com/iwamot/welt-io-strands) — the Python adapter’s repo and API docs - [welt-io-strands-ts](https://github.com/iwamot/welt-io-strands-ts) — the TypeScript adapter’s repo and API docs - Example agents ([Python](https://github.com/iwamot/welt-io-strands/tree/main/examples/agent), [TypeScript](https://github.com/iwamot/welt-io-strands-ts/tree/main/examples/agent)) — complete and deployable, the source of the snippets above - [Wire contract](https://github.com/iwamot/welt/blob/main/docs/wire.md) — the JSON protocol the adapters implement - [Files](https://github.com/iwamot/welt/blob/main/docs/files.md) — how uploads reach the agent and generated files reach the thread - [Interrupts over Slack](https://github.com/iwamot/welt/blob/main/docs/interrupts.md) — how each reason shape renders Source: https://strandsagents.com/docs/integrations/integrations/welt/index.md --- ## Community Interventions An **intervention handler** is a composable control layer that intercepts agent lifecycle events and returns typed decisions — proceed, deny, guide, confirm, or transform. Handlers are registered via the `interventions` option in agent configuration and evaluated in order, with short-circuiting on deny or guide actions. See [Interventions](/docs/user-guide/sdk/agents/interventions/index.md) for the full concept and built-in handlers. The SDK ships reference handlers like [Cedar Authorization](/docs/user-guide/sdk/agents/interventions/cedar-authorization/index.md), [Steering](/docs/user-guide/sdk/agents/interventions/steering/index.md), and [Human-in-the-Loop](/docs/user-guide/sdk/agents/interventions/human-in-the-loop/index.md). The packages below are **community-built** intervention handlers you can install and attach to an agent. Community maintained These packages are maintained by their authors, not the Strands team. Review packages before using them in production. Quality and support may vary. ## Browse the integrations page See the [Interventions section of the integrations page](/integrations/?type=intervention/index.md) for the current list, with language support and links to each package. ## Add your intervention handler Built an `InterventionHandler`? See the [Get Featured guide](/docs/integrations/get-featured/index.md) to list it here, and the [Extensions guide](/docs/contribute/contributing/extensions/index.md) for how to build and publish a package. Source: https://strandsagents.com/docs/integrations/interventions/overview/index.md --- ## Agent Governance Toolkit [strands-agt](https://github.com/lizradway/strands-agt) integrates Microsoft’s [Agent Governance Toolkit (AGT)](https://github.com/microsoft/agent-governance-toolkit) with Strands Agents via the `InterventionHandler` primitive. It provides deterministic, YAML-based policy enforcement that gates tool calls before execution — no model judgment involved. - **Deny** — block tool calls that violate policy (e.g. file deletion, production access) - **Allow** — permit tool calls that match policy - **Steer** — redirect the agent with guidance instead of a hard block ## Installation ```bash pip install strands-agt ``` ## Usage ### Basic policy enforcement Define policies in YAML: policies.yaml ```yaml policies: - name: allow-search effect: allow actions: ["search", "read_file"] principals: ["User::*"] - name: deny-delete effect: deny actions: ["delete_file"] principals: ["*"] reason: "File deletion is not permitted" ``` Attach to your agent: ```python from strands import Agent from strands_agt import AGTGovernance governance = AGTGovernance(policies="policies.yaml") agent = Agent( tools=[search_tool, read_file_tool, delete_file_tool], interventions=[governance], ) # search_tool executes normally agent("Search for quarterly reports") # delete_file_tool is blocked — the model sees the denial reason agent("Delete the temp files") ``` ### Role-based access with principal resolution ```python from strands_agt import AGTGovernance governance = AGTGovernance( policies="role_policies.yaml", principal_resolver=lambda state: { "type": state.get("user_role", "User"), "id": state.get("user_id", "anonymous"), }, ) agent = Agent( tools=[...], interventions=[governance], ) # Pass identity via invocation_state agent("Delete the old backups", invocation_state={"user_role": "Admin", "user_id": "alice"}) ``` ### Rate limiting ```yaml policies: - name: rate-limited-email effect: allow actions: ["send_email"] conditions: session.call_count: lt: 5 ``` The handler tracks per-tool call counts automatically and includes them in policy evaluation. ### Context enrichment ```python governance = AGTGovernance( policies="env_policies.yaml", context_enricher=lambda ctx: { "environment": os.environ.get("DEPLOY_ENV", "development"), "tenant_id": ctx["invocation_state"].get("tenant_id"), }, ) ``` Enricher fields are available in policy conditions under `session.*`. ## Configuration | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `policies` | `str | list[str]` | required | YAML policy file path(s) or inline YAML text | | `principal` | `dict[str, str] | None` | `{"type": "User", "id": "anonymous"}` | Static principal identity | | `principal_resolver` | `Callable | None` | `None` | Dynamic resolver from `invocation_state` | | `context_enricher` | `Callable | None` | `None` | Injects extra fields into policy context | | `on_error` | `str` | `"throw"` | Error mode: `"throw"`, `"proceed"`, or `"deny"` | ## Policy format Each policy has: | Field | Required | Description | | --- | --- | --- | | `name` | Yes | Unique policy identifier | | `effect` | Yes | `allow`, `deny`, or `steer` | | `actions` | No | Tool names to match (`["*"]` = all) | | `principals` | No | Principal patterns (`["Type::id"]`, `["Type::*"]`, `["*"]`) | | `conditions` | No | Context conditions (supports `lt`, `lte`, `gt`, `gte`, `eq`, `neq`, `in`) | | `reason` | No | Message shown to the model on deny | | `guidance` | No | Feedback for steer decisions | Deny policies are evaluated first and short-circuit. If no deny matches, steer is checked. If neither matches, the first matching allow wins. No match = deny (fail-closed). ## References - [GitHub](https://github.com/lizradway/strands-agt) - [PyPI](https://pypi.org/project/strands-agt/) - [Microsoft AGT](https://github.com/microsoft/agent-governance-toolkit) - [Strands Interventions docs](/docs/user-guide/sdk/agents/interventions/index.md) Source: https://strandsagents.com/docs/integrations/interventions/strands-agt/index.md --- ## AgentCore Memory Store The AgentCore Memory Store, available in Python and TypeScript, implements the Strands [`MemoryStore`](/docs/user-guide/sdk/memory/managing-memory/index.md#custom-stores) interface on top of Amazon Bedrock AgentCore Memory. Search maps to AgentCore’s `RetrieveMemoryRecords`, and conversation turns are ingested for server-side memory extraction into long-term records. Attach it to an agent through a [`MemoryManager`](/docs/user-guide/sdk/memory/overview/index.md) like any other store. See the [Getting Started](/docs/user-guide/sdk/memory/overview/index.md) section for more information. Use this integration for long-term memory through a memory manager. To persist and restore conversation history, use `SnapshotSessionManager``SessionManager` as described in the [single-agent session guide](/docs/user-guide/sdk/agents/session-management/index.md#single-agent-sessions). ## Requirements Use an existing [Amazon Bedrock AgentCore Memory](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/memory.html) resource with extraction strategies and AWS credentials to access it. Match the examples’ namespaces to those configured on your strategies. The store does not create the resource. (( tab "Python" )) - `bedrock-agentcore >= 1.21.0` - `strands-agents >= 1.56.0` (( /tab "Python" )) (( tab "TypeScript" )) - `bedrock-agentcore >= 0.4.1` - `@strands-agents/sdk >= 1.5.0` (( /tab "TypeScript" )) ## Installation (( tab "Python" )) ```bash pip install "bedrock-agentcore[strands-agents]>=1.21.0" ``` (( /tab "Python" )) (( tab "TypeScript" )) ```bash npm install bedrock-agentcore @strands-agents/sdk ``` (( /tab "TypeScript" )) ## Usage To recall from multiple namespaces, use `create_agentcore_memory_stores``createAgentCoreMemoryStores`. It builds one store per namespace over a shared client. Attach the stores to an agent through a `MemoryManager` and enable extraction on one writer to capture conversation turns. Writes go to the shared conversation stream; the memory resource’s strategies decide which namespaces receive extracted records. (( tab "Python" )) Set `AGENTCORE_MEMORY_ID` to your memory resource ID. ```python import os from strands import Agent from strands.memory import MemoryManager from bedrock_agentcore.memory.integrations.strands.memorystore import ( create_agentcore_memory_stores, ) stores = create_agentcore_memory_stores( memory_id=os.environ["AGENTCORE_MEMORY_ID"], actor_id="user-123", session_id="session-1", namespaces=[ {"namespace": "/facts/{actorId}", "writable": True}, {"namespace": "/preferences/{actorId}", "min_score": 0.5}, ], extraction=True, region_name="us-east-1", ) manager = MemoryManager(stores=stores) agent = Agent(memory_manager=manager) ``` The import package is `memorystore`, without an underscore. With extraction enabled, the factory selects the first namespace not explicitly marked `writable=False` when no writer is specified. Set `writable=True` on one namespace to choose the writer explicitly, as above. Omit `extraction` and writer flags for recall-only stores. (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { Agent, MemoryManager, BedrockModel } from '@strands-agents/sdk' import { createAgentCoreMemoryStores } from 'bedrock-agentcore/memory/strands' const stores = createAgentCoreMemoryStores({ memoryId: 'mem-abc', actorId: 'user-123', sessionId: 'session-1', namespaces: [ { namespace: '/facts/{actorId}', writable: true }, { namespace: '/preferences/{actorId}', minScore: 0.5 }, ], extraction: true, }) const agent = new Agent({ model: new BedrockModel(), memoryManager: new MemoryManager({ stores }), }) ``` (( /tab "TypeScript" )) A single `AgentCoreMemoryStore` can also be constructed directly when you only need one namespace: (( tab "Python" )) ```python import os from strands import Agent from strands.memory import MemoryManager from bedrock_agentcore.memory.integrations.strands.memorystore import ( AgentCoreMemoryStore, ) store = AgentCoreMemoryStore( memory_id=os.environ["AGENTCORE_MEMORY_ID"], actor_id="user-123", session_id="session-1", namespace="/facts/{actorId}", writable=True, extraction=True, region_name="us-east-1", ) manager = MemoryManager(stores=[store]) agent = Agent(memory_manager=manager) ``` (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { AgentCoreMemoryStore } from 'bedrock-agentcore/memory/strands' const store = new AgentCoreMemoryStore({ memoryId: 'mem-abc', actorId: 'user-123', sessionId: 'session-1', namespace: '/facts/{actorId}', writable: true, extraction: true, }) ``` (( /tab "TypeScript" )) ## Configuration Set namespace-specific options on each factory entry, and identity and extraction options at the top level. The direct `AgentCoreMemoryStore` constructor takes all options in one flat config. | Option | Type | Description | | --- | --- | --- | | `memory_id``memoryId` | string | Memory resource ID. | | `actor_id``actorId` | string | Replaces `{actorId}`. | | `session_id``sessionId` | string | Replaces `{sessionId}`. | | `namespace` | string | Exact namespace prefix for recall. | | `namespace_path``namespacePath` | string | Subtree query; direct constructor only, instead of `namespace`. | | `writable` | boolean | Enables conversation writes; false by default on a direct store. | | `extraction` | boolean or config | Enables automatic dispatch, with cadence and filtering. | | `min_score``minScore` | number | Minimum relevance score for recall. | (( tab "Python" )) For custom extraction cadence, pass an `extraction` dictionary with `cadence` and `filter` to the factory. For example, use `IntervalTrigger(turns=10)` from `strands.memory` as the cadence. The direct constructor uses the Strands `ExtractionConfig`, whose cadence key is `trigger`. See the [package README](https://github.com/aws/bedrock-agentcore-sdk-python/tree/main/src/bedrock_agentcore/memory/integrations/strands/memorystore) for batching, score filtering, metadata, and the full namespace contract. (( /tab "Python" )) (( tab "TypeScript" )) See the [package README](https://github.com/aws/bedrock-agentcore-sdk-typescript/tree/main/src/memory/integrations/strands) for the full option reference, including subtree reads and over-fetch tuning. (( /tab "TypeScript" )) ## Writes and shutdown Conversation writes use `CreateEvent` for server-side extraction, preserving user and assistant roles. Flush pending writes at a shutdown boundary after asynchronous invocation or streaming. (( tab "Python" )) Synchronous `agent(...)` calls flush automatically. After `agent.invoke_async(...)` or `agent.stream_async(...)`, call `await manager.flush()` before closing the event loop. Reuse the manager while the same actor and session remain active to retain buffered turns and cadence state. Strands logs extraction write failures and retains failed batches for retry. A completed `flush()` alone is not proof that events were persisted. The store implements `add_messages()`, not the flat-string `add()` interface, so it does not enable the manager’s `add_memory` tool. Enable extraction to send conversation turns instead. (( /tab "Python" )) (( tab "TypeScript" )) Await `agent.memoryManager?.flush()` at shutdown to settle pending writes. (( /tab "TypeScript" )) A completed flush does not confirm that server-side extraction has finished. Monitor write failures in logs; newly extracted records may not be immediately searchable. ## Notes - **One writable store per session.** Mark at most one store `writable` for a given memory resource, actor, and session: multiple writers would emit duplicate events to the same stream. The factory rejects configurations with more than one writer. - **Placeholders resolve at construction.** Only `{actorId}` and `{sessionId}` are substituted client-side, into the namespace used for recall. Any other placeholder in a namespace causes construction to throw. Provision strategies with `{actorId}`/`{sessionId}`\-only templates to match. - **Cross-session recall.** A namespace containing `{sessionId}` scopes recall to that session. Use an actor-only namespace to recall memories across sessions. ## References - [Python integration source and README](https://github.com/aws/bedrock-agentcore-sdk-python/tree/main/src/bedrock_agentcore/memory/integrations/strands/memorystore) - [`bedrock-agentcore` on PyPI](https://pypi.org/project/bedrock-agentcore/) - [TypeScript integration source and README](https://github.com/aws/bedrock-agentcore-sdk-typescript/tree/main/src/memory/integrations/strands) - [`bedrock-agentcore` on npm](https://www.npmjs.com/package/bedrock-agentcore) - [Amazon Bedrock AgentCore Memory](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/memory.html) - [Report a Python issue](https://github.com/aws/bedrock-agentcore-sdk-python/issues/new/choose) - [Report a TypeScript issue](https://github.com/aws/bedrock-agentcore-sdk-typescript/issues/new/choose) Source: https://strandsagents.com/docs/integrations/memory-stores/agentcore-memory-store/index.md --- ## Community Memory Stores A **memory store** is the backend that holds an agent’s long-term knowledge. The [`MemoryManager`](/docs/user-guide/sdk/memory/overview/index.md) orchestrates one or more stores to recall, inject, and extract memories across sessions. Any backend that implements the `MemoryStore` interface can plug in: see [Custom Stores](/docs/user-guide/sdk/memory/managing-memory/index.md#custom-stores) for the contract. The SDK ships reference stores like the [Bedrock Knowledge Base store](/docs/user-guide/sdk/memory/bedrock-knowledge-base/index.md). The packages below go further: they are **community-built** memory stores you can install and attach to an agent, backed by vector databases, managed services, and other stores the SDK does not vend itself. Community maintained These packages are maintained by their authors, not the Strands team. Review packages before using them in production. Quality and support may vary. ## Browse the integrations page See the [Memory stores section of the integrations page](/integrations/?type=memory-store/index.md) for the current list, with language support and links to each package. ## Add your memory store Built a `MemoryStore` implementation? See the [Get Featured guide](/docs/integrations/get-featured/index.md) to list it here, and the [Extensions guide](/docs/contribute/contributing/extensions/index.md) for how to build and publish a package. Source: https://strandsagents.com/docs/integrations/memory-stores/overview/index.md --- ## strands-dakera [strands-dakera](https://github.com/dakera-ai/strands-dakera) gives agents persistent memory that survives across sessions, backed by a self-hosted [Dakera](https://github.com/dakera-ai/dakera-deploy) server. Unlike a fixed-TTL store, Dakera ranks recalled memories by **importance × recency × semantic relevance**, so the most contextually useful memories surface first. It offers two integration points against the same server: - **`DakeraMemoryStore`** — a [`MemoryStore`](/docs/user-guide/sdk/memory/overview/index.md) that plugs into the agent loop via a `MemoryManager` (Strands ≥ 1.45), with automatic memory injection and extraction. - **`dakera_memory`** — a tool the model calls explicitly for full CRUD (`store` / `retrieve` / `get` / `update` / `delete`). ## Installation ```bash pip install "strands-dakera>=0.2.0" # DakeraMemoryStore requires >=0.2.0 (Strands >=1.45) ``` Run a Dakera server locally (once): ```bash git clone https://github.com/dakera-ai/dakera-deploy && cd dakera-deploy && docker compose up -d ``` ## Memory store Wire Dakera into the agent loop with a `MemoryManager`. The manager searches the store to recall context (injected into the prompt automatically) and, when `writable`, writes new memories — either directly or by extracting facts from the conversation every few turns. ```python from strands import Agent from strands.memory import MemoryManager from strands_dakera import DakeraMemoryStore store = DakeraMemoryStore(agent_id="alex", writable=True, extraction=True) agent = Agent(memory_manager=MemoryManager(stores=[store])) # Recall and writes happen automatically — no explicit tool call required. agent("Remember that I prefer dark-mode dashboards and async standups.") agent("How do I like to work?") # recalls the stored preferences ``` `DakeraMemoryStore` implements `search` (decay-weighted recall) and `add` (a client-side write sink), so enabling `extraction` uses the manager’s client-side `ModelExtractor`. Common arguments: `agent_id` (required), `name`, `writable`, `extraction`, `max_search_results`, `importance`, `memory_type`, and `base_url` / `api_key`. ## Tool Prefer an explicitly model-invoked tool? Register `dakera_memory` instead (or alongside the store): ```python from strands import Agent from strands_dakera import dakera_memory agent = Agent(tools=[dakera_memory]) # Store a memory with an importance weight agent.tool.dakera_memory( action="store", agent_id="alex", content="Alex prefers dark-mode dashboards and async standups.", importance=0.8, metadata={"category": "preferences"}, ) # Decay-weighted semantic recall agent.tool.dakera_memory( action="retrieve", agent_id="alex", query="how does alex like to work?", top_k=5, ) ``` ## Key Features - **Decay-weighted recall**: results ranked by a decay-aware importance signal, not just vector distance - **Importance-typed storage**: `importance` (0.0–1.0) and `memory_type` (episodic / semantic / procedural / working) - **Two integration points**: a `MemoryStore` for the agent loop and a full-CRUD tool, sharing one server - **Self-hosted**: runs against your own Dakera server — no cloud key required - **Safe by default**: mutative tool actions prompt for confirmation unless `BYPASS_TOOL_CONSENT=true` ## Configuration ```bash DAKERA_BASE_URL=http://localhost:3000 # Dakera server URL (default) DAKERA_API_KEY=dk-your-key # Optional API key ``` ## References - [PyPI Package](https://pypi.org/project/strands-dakera/) - [GitHub Repository](https://github.com/dakera-ai/strands-dakera) - [Dakera Server (self-host)](https://github.com/dakera-ai/dakera-deploy) - [Dakera](https://dakera.ai/) Source: https://strandsagents.com/docs/integrations/memory-stores/strands-dakera/index.md --- ## CLOVA Studio [CLOVA Studio](https://www.ncloud.com/product/aiService/clovaStudio) is Naver Cloud Platform’s AI service that provides large language models optimized for Korean language processing. The [`strands-clova`](https://pypi.org/project/strands-clova/) package ([GitHub](https://github.com/aidendef/strands-clova)) provides a community-maintained integration for the Strands Agents SDK, enabling seamless use of CLOVA Studio’s Korean-optimized AI models. ## Installation CLOVA Studio integration is available as a separate community package: ```bash pip install strands-agents strands-clova ``` ## Usage After installing `strands-clova`, you can import and initialize the CLOVA Studio provider: ```python from strands import Agent from strands_clova import ClovaModel model = ClovaModel( api_key="your-clova-api-key", # or set CLOVA_API_KEY env var model="HCX-005", temperature=0.7, max_tokens=2048 ) agent = Agent(model=model) response = await agent.invoke_async("안녕하세요! 오늘 날씨가 어떤가요?") print(response.message) ``` ## Configuration ### Environment Variables ```bash export CLOVA_API_KEY="your-api-key" export CLOVA_REQUEST_ID="optional-request-id" # For request tracking ``` ### Model Configuration The supported configurations are: | Parameter | Description | Example | Default | | --- | --- | --- | --- | | `model` | Model ID | `HCX-005` | `HCX-005` | | `temperature` | Sampling temperature (0.0-1.0) | `0.7` | `0.7` | | `max_tokens` | Maximum tokens to generate | `4096` | `2048` | | `top_p` | Nucleus sampling parameter | `0.8` | `0.8` | | `top_k` | Top-k sampling parameter | `0` | `0` | | `repeat_penalty` | Repetition penalty | `1.1` | `1.1` | | `stop` | Stop sequences | `["\\n\\n"]` | `[]` | ## Advanced Features ### Korean Language Optimization CLOVA Studio excels at Korean language tasks: ```python # Korean customer support bot model = ClovaModel(api_key="your-api-key", temperature=0.3) agent = Agent( model=model, system_prompt="당신은 친절한 고객 서비스 상담원입니다." ) response = await agent.invoke_async("제품 반품 절차를 알려주세요") ``` ### Bilingual Capabilities Handle both Korean and English seamlessly: ```python # Process Korean document and get English summary response = await agent.invoke_async( "다음 한국어 문서를 영어로 요약해주세요: [문서 내용]" ) ``` ## References - [strands-clova GitHub Repository](https://github.com/aidendef/strands-clova) - [CLOVA Studio Documentation](https://www.ncloud.com/product/aiService/clovaStudio) - [Naver Cloud Platform](https://www.ncloud.com/) Source: https://strandsagents.com/docs/integrations/model-providers/clova-studio/index.md --- ## Cohere [Cohere](https://cohere.com) provides language models accessible through its OpenAI-compatible Compatibility API. OpenAI compatibility This integration works through the SDK’s built-in [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) pointed at Cohere’s OpenAI-compatible endpoint; there is no separate Cohere integration. Compatible endpoints can have quirks that deviate from the exact OpenAI API spec, so some features may behave differently than they do against OpenAI itself. Cohere’s Compatibility API rejects the `stream_options` request field. The Python provider lets you unset it (shown below); the TypeScript provider always sends it, so it does not work with Cohere. ## Installation The OpenAI provider is an optional dependency. To install, run: ```bash pip install 'strands-agents[openai]' ``` ## Usage Create an [API key](https://dashboard.cohere.com) in the Cohere Dashboard, export it as `COHERE_API_KEY`, and point the provider at the Compatibility API: ```python import os from strands import Agent from strands.models.openai import OpenAIModel model = OpenAIModel( client_args={ "api_key": os.environ["COHERE_API_KEY"], "base_url": "https://api.cohere.ai/compatibility/v1", }, model_id="command-a-03-2025", # The Compatibility API rejects stream_options; unset the SDK default params={"stream_options": None}, ) agent = Agent(model=model) response = agent("Explain tool calling in one sentence.") print(response) ``` ## Configuration Two client settings connect the provider to Cohere: - **API key**: from the [Cohere Dashboard](https://dashboard.cohere.com) - **Base URL**: `https://api.cohere.ai/compatibility/v1` Model IDs come from the [Cohere model catalog](https://docs.cohere.com/docs/models), for example `command-a-03-2025` or `command-r-plus`. Keep `params={"stream_options": None}` in every configuration. For other provider options, see the [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) guide. ## References - [Cohere docs: using the OpenAI SDK](https://docs.cohere.com/docs/compatibility-api) - [Cohere API reference](https://docs.cohere.com/reference) - [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) Source: https://strandsagents.com/docs/integrations/model-providers/cohere/index.md --- ## Crusoe [Crusoe](https://www.crusoe.ai/cloud/managed-inference) provides managed inference for leading open-weight language models on renewable-powered GPU infrastructure. OpenAI compatibility This integration works through the SDK’s built-in [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) pointed at Crusoe’s OpenAI-compatible endpoint; there is no separate Crusoe integration. Compatible endpoints can have quirks that deviate from the exact OpenAI API spec, so some features may behave differently than they do against OpenAI itself. ## Installation The OpenAI provider is an optional dependency. To install, run: (( tab "Python" )) ```bash pip install 'strands-agents[openai]' ``` (( /tab "Python" )) (( tab "TypeScript" )) ```bash npm install @strands-agents/sdk openai ``` (( /tab "TypeScript" )) ## Usage Generate an API key in the **Security** tab of the [Crusoe Cloud Console](https://console.crusoecloud.com/), export it as `CRUSOE_API_KEY`, and point the provider at Crusoe’s endpoint: (( tab "Python" )) ```python import os from strands import Agent from strands.models.openai import OpenAIModel model = OpenAIModel( client_args={ "api_key": os.environ["CRUSOE_API_KEY"], "base_url": "https://api.inference.crusoecloud.com/v1/", }, model_id="zai/GLM-5.2", ) agent = Agent(model=model) response = agent("Explain tool calling in one sentence.") print(response) ``` (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { Agent } from '@strands-agents/sdk' import { OpenAIModel } from '@strands-agents/sdk/models/openai' const model = new OpenAIModel({ api: 'chat', apiKey: process.env.CRUSOE_API_KEY, clientConfig: { baseURL: 'https://api.inference.crusoecloud.com/v1/', }, modelId: 'zai/GLM-5.2', }) const agent = new Agent({ model }) const response = await agent.invoke('Explain tool calling in one sentence.') console.log(response) ``` (( /tab "TypeScript" )) ## Configuration Two client settings connect the provider to Crusoe Managed Inference: - **API key**: from the **Security** tab of the [Crusoe Cloud Console](https://console.crusoecloud.com/) - **Base URL**: `https://api.inference.crusoecloud.com/v1/` Model IDs come from the [Crusoe Managed Inference overview](https://docs.crusoecloud.com/managed-inference/overview), for example `zai/GLM-5.2` or `nvidia/Nemotron-3-Super-120B-A12B`. For model parameters and other provider options, see the [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) guide. ## References - [Crusoe Managed Inference documentation](https://docs.crusoecloud.com/managed-inference/overview) - [Crusoe Cloud Console](https://console.crusoecloud.com/) - [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) Source: https://strandsagents.com/docs/integrations/model-providers/crusoe/index.md --- ## FireworksAI [Fireworks AI](https://fireworks.ai) provides fast hosted inference for open-source language models. OpenAI compatibility This integration works through the SDK’s built-in [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) pointed at Fireworks AI’s OpenAI-compatible endpoint; there is no separate integration. Compatible endpoints can have quirks that deviate from the exact OpenAI API spec, so some features may behave differently than they do against OpenAI itself. ## Installation The OpenAI provider is an optional dependency. To install, run: (( tab "Python" )) ```bash pip install 'strands-agents[openai]' ``` (( /tab "Python" )) (( tab "TypeScript" )) ```bash npm install @strands-agents/sdk openai ``` (( /tab "TypeScript" )) ## Usage Create an [API key](https://app.fireworks.ai/settings/users/api-keys), export it as `FIREWORKS_API_KEY`, and point the provider at Fireworks AI’s endpoint: (( tab "Python" )) ```python import os from strands import Agent from strands.models.openai import OpenAIModel model = OpenAIModel( client_args={ "api_key": os.environ["FIREWORKS_API_KEY"], "base_url": "https://api.fireworks.ai/inference/v1", }, model_id="accounts/fireworks/models/deepseek-v3p1-terminus", ) agent = Agent(model=model) response = agent("Explain tool calling in one sentence.") print(response) ``` (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { Agent } from '@strands-agents/sdk' import { OpenAIModel } from '@strands-agents/sdk/models/openai' const model = new OpenAIModel({ api: 'chat', apiKey: process.env.FIREWORKS_API_KEY, clientConfig: { baseURL: 'https://api.fireworks.ai/inference/v1', }, modelId: 'accounts/fireworks/models/deepseek-v3p1-terminus', }) const agent = new Agent({ model }) const response = await agent.invoke('Explain tool calling in one sentence.') console.log(response) ``` (( /tab "TypeScript" )) ## Configuration Two client settings connect the provider to Fireworks AI: - **API key**: from your [account settings](https://app.fireworks.ai/settings/users/api-keys) - **Base URL**: `https://api.fireworks.ai/inference/v1` Model IDs come from the [Fireworks AI model library](https://fireworks.ai/models) and carry the `accounts/fireworks/models/` prefix. For model parameters and other provider options, see the [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) guide. ## References - [Fireworks AI OpenAI compatibility guide](https://fireworks.ai/docs/tools-sdks/openai-compatibility#openai-compatibility) - [Fireworks AI model library](https://fireworks.ai/models) - [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) Source: https://strandsagents.com/docs/integrations/model-providers/fireworksai/index.md --- ## MLX [strands-mlx](https://github.com/cagataycali/strands-mlx) is an [MLX](https://ml-explore.github.io/mlx/) model provider for Strands Agents SDK that enables running AI agents locally on Apple Silicon. It supports inference, fine-tuning with LoRA, and vision models. **Features:** - **Apple Silicon Native**: Optimized for M1/M2/M3/M4 chips using Apple’s MLX framework - **LoRA Fine-tuning**: Train custom adapters from agent conversations - **Vision Support**: Process images, audio, and video with multimodal models - **Local Inference**: Run agents completely offline without API calls - **Training Pipeline**: Collect data → Split → Train → Deploy workflow ## Installation Install strands-mlx along with the Strands Agents SDK: ```bash pip install strands-mlx ``` ## Requirements - macOS with Apple Silicon (M1/M2/M3/M4) - Python ≤3.13 ## Usage ### Basic Agent ```python from strands import Agent from strands_mlx import MLXModel from strands.vended_tools import notebook model = MLXModel(model_id="mlx-community/Qwen3-1.7B-4bit") agent = Agent(model=model, tools=[notebook]) agent('Create a notebook named "ideas" and add three uses for local language models.') ``` ### Vision Model ```python from strands import Agent from strands_mlx import MLXVisionModel model = MLXVisionModel(model_id="mlx-community/Qwen2-VL-2B-Instruct-4bit") agent = Agent(model=model) agent("Describe: photo.jpg") ``` ### Fine-tuning with LoRA Collect training data from agent conversations and fine-tune: ```python from strands import Agent from strands_mlx import MLXModel, MLXSessionManager, dataset_splitter, mlx_trainer # Collect training data agent = Agent( model=MLXModel(model_id="mlx-community/Qwen3-1.7B-4bit"), session_manager=MLXSessionManager(session_id="training", storage_dir="./dataset"), tools=[dataset_splitter, mlx_trainer], ) # Have conversations (auto-saved) agent("Teach me about quantum computing") # Split and train agent.tool.dataset_splitter(input_path="./dataset/training.jsonl") agent.tool.mlx_trainer( action="train", config={ "model": "mlx-community/Qwen3-1.7B-4bit", "data": "./dataset/training", "adapter_path": "./adapter", "iters": 200, } ) # Use trained model trained = MLXModel("mlx-community/Qwen3-1.7B-4bit", adapter_path="./adapter") expert_agent = Agent(model=trained) ``` ## Configuration ### Model Configuration The `MLXModel` accepts the following parameters: | Parameter | Description | Example | Required | | --- | --- | --- | --- | | `model_id` | HuggingFace model ID | `"mlx-community/Qwen3-1.7B-4bit"` | Yes | | `adapter_path` | Path to LoRA adapter | `"./adapter"` | No | ### Recommended Models **Text:** - `mlx-community/Qwen3-1.7B-4bit` (recommended for agents) - `mlx-community/Qwen3-4B-4bit` - `mlx-community/Llama-3.2-1B-4bit` **Vision:** - `mlx-community/Qwen2-VL-2B-Instruct-4bit` (recommended) - `mlx-community/llava-v1.6-mistral-7b-4bit` Browse more models at [mlx-community on HuggingFace](https://huggingface.co/mlx-community). ## Troubleshooting ### Out of memory Use smaller quantized models or reduce batch size: ```python config = { "grad_checkpoint": True, "batch_size": 1, "max_seq_length": 1024 } ``` ### Model not found Ensure you’re using a valid mlx-community model ID. Models are automatically downloaded from HuggingFace on first use. ## References - [strands-mlx Repository](https://github.com/cagataycali/strands-mlx) - [MLX Documentation](https://ml-explore.github.io/mlx/) - [mlx-community Models](https://huggingface.co/mlx-community) - [Strands Agents SDK](https://strandsagents.com) Source: https://strandsagents.com/docs/integrations/model-providers/mlx/index.md --- ## Nebius Token Factory [Nebius Token Factory](https://tokenfactory.nebius.com) provides fast inference for open-source language models. OpenAI compatibility This integration works through the SDK’s built-in [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) pointed at Nebius Token Factory’s OpenAI-compatible endpoint; there is no separate integration. Compatible endpoints can have quirks that deviate from the exact OpenAI API spec, so some features may behave differently than they do against OpenAI itself. ## Installation The OpenAI provider is an optional dependency. To install, run: (( tab "Python" )) ```bash pip install 'strands-agents[openai]' ``` (( /tab "Python" )) (( tab "TypeScript" )) ```bash npm install @strands-agents/sdk openai ``` (( /tab "TypeScript" )) ## Usage Create an API key in the [Nebius Token Factory Console](https://tokenfactory.nebius.com/), export it as `NEBIUS_API_KEY`, and point the provider at the Token Factory endpoint: (( tab "Python" )) ```python import os from strands import Agent from strands.models.openai import OpenAIModel model = OpenAIModel( client_args={ "api_key": os.environ["NEBIUS_API_KEY"], "base_url": "https://api.tokenfactory.nebius.com/v1/", }, model_id="deepseek-ai/DeepSeek-R1-0528", ) agent = Agent(model=model) response = agent("Explain tool calling in one sentence.") print(response) ``` (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { Agent } from '@strands-agents/sdk' import { OpenAIModel } from '@strands-agents/sdk/models/openai' const model = new OpenAIModel({ api: 'chat', apiKey: process.env.NEBIUS_API_KEY, clientConfig: { baseURL: 'https://api.tokenfactory.nebius.com/v1/', }, modelId: 'deepseek-ai/DeepSeek-R1-0528', }) const agent = new Agent({ model }) const response = await agent.invoke('Explain tool calling in one sentence.') console.log(response) ``` (( /tab "TypeScript" )) ## Configuration Two client settings connect the provider to Nebius Token Factory: - **API key**: from the [Token Factory Console](https://tokenfactory.nebius.com/) - **Base URL**: `https://api.tokenfactory.nebius.com/v1/` Model IDs come from the [Token Factory model catalog](https://docs.tokenfactory.nebius.com/ai-models-inference/overview), for example `deepseek-ai/DeepSeek-R1-0528` or `meta-llama/Meta-Llama-3.1-70B-Instruct`. For model parameters and other provider options, see the [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) guide. ## References - [Nebius Token Factory documentation](https://docs.tokenfactory.nebius.com/) - [Nebius Token Factory API reference](https://docs.tokenfactory.nebius.com/api-reference) - [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) Source: https://strandsagents.com/docs/integrations/model-providers/nebius-token-factory/index.md --- ## NVIDIA NIM [strands-nvidia-nim](https://github.com/thiago4go/strands-nvidia-nim) is a custom model provider that enables Strands Agents to work with [Nvidia NIM](https://www.nvidia.com/en-us/ai/) APIs. It bridges the message format compatibility gap between Strands Agents SDK and Nvidia NIM API endpoints. **Features:** - **Message Format Conversion**: Automatically converts Strands’ structured content to simple string format required by Nvidia NIM - **Tool Support**: Full support for Strands tools with proper error handling - **Clean Streaming**: Proper streaming output without artifacts - **Error Handling**: Context window overflow detection and Strands-specific errors ## Installation Install strands-nvidia-nim from PyPI: ```bash pip install strands-nvidia-nim ``` ## Usage ### Basic Agent ```python from strands import Agent from strands.vended_tools import notebook from strands_nvidia_nim import NvidiaNIM model = NvidiaNIM( api_key="your-nvidia-nim-api-key", model_id="meta/llama-3.1-70b-instruct", params={ "max_tokens": 1000, "temperature": 0.7, } ) agent = Agent(model=model, tools=[notebook]) agent('Create a notebook named "ideas" and add three uses for accelerated inference.') ``` ### Using Environment Variables ```bash export NVIDIA_NIM_API_KEY=your-nvidia-nim-api-key ``` ```python import os from strands import Agent from strands.vended_tools import notebook from strands_nvidia_nim import NvidiaNIM model = NvidiaNIM( api_key=os.getenv("NVIDIA_NIM_API_KEY"), model_id="meta/llama-3.1-70b-instruct", params={"max_tokens": 1000, "temperature": 0.7} ) agent = Agent(model=model, tools=[notebook]) agent('Create a notebook named "ideas" and add three uses for accelerated inference.') ``` ## Configuration ### Model Configuration The `NvidiaNIM` provider accepts the following parameters: | Parameter | Description | Example | | --- | --- | --- | | `api_key` | Your Nvidia NIM API key | `"nvapi-..."` | | `model_id` | Model identifier | `"meta/llama-3.1-70b-instruct"` | | `params` | Generation parameters | `{"max_tokens": 1000}` | ### Available Models Popular Nvidia NIM models: - `meta/llama-3.1-70b-instruct` - High quality, larger model - `meta/llama-3.1-8b-instruct` - Faster, smaller model - `meta/llama-3.3-70b-instruct` - Latest Llama model - `mistralai/mistral-large` - Mistral’s flagship model - `nvidia/llama-3.1-nemotron-70b-instruct` - Nvidia-optimized variant ### Generation Parameters ```python model = NvidiaNIM( api_key="your-api-key", model_id="meta/llama-3.1-70b-instruct", params={ "max_tokens": 1500, "temperature": 0.7, "top_p": 0.9, "frequency_penalty": 0.0, "presence_penalty": 0.0 } ) ``` ## Troubleshooting ### `BadRequestError` with message formatting This provider exists specifically to solve message formatting issues between Strands and Nvidia NIM. If you encounter this error using standard LiteLLM integration, switch to `strands-nvidia-nim`. ### Context window overflow The provider includes detection for context window overflow errors. If you encounter this, try reducing `max_tokens` or the size of your prompts. ## References - [strands-nvidia-nim Repository](https://github.com/thiago4go/strands-nvidia-nim) - [PyPI Package](https://pypi.org/project/strands-nvidia-nim/) - [Nvidia NIM Documentation](https://docs.nvidia.com/nim/) - [Strands Custom Model Provider](/docs/user-guide/sdk/model-providers/custom_model_provider/index.md) Source: https://strandsagents.com/docs/integrations/model-providers/nvidia-nim/index.md --- ## OpenRouter [OpenRouter](https://openrouter.ai/) routes requests to hundreds of models from many labs behind a single API and API key. OpenAI compatibility This integration works through the SDK’s built-in [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) pointed at OpenRouter’s OpenAI-compatible endpoint; there is no separate OpenRouter integration. Compatible endpoints can have quirks that deviate from the exact OpenAI API spec, so some features may behave differently than they do against OpenAI itself. ## Installation The OpenAI provider is an optional dependency. To install, run: (( tab "Python" )) ```bash pip install 'strands-agents[openai]' ``` (( /tab "Python" )) (( tab "TypeScript" )) ```bash npm install @strands-agents/sdk openai ``` (( /tab "TypeScript" )) ## Usage Create an [API key](https://openrouter.ai/settings/keys), export it as `OPENROUTER_API_KEY`, and point the provider at OpenRouter’s endpoint: (( tab "Python" )) ```python import os from strands import Agent from strands.models.openai import OpenAIModel model = OpenAIModel( client_args={ "api_key": os.environ["OPENROUTER_API_KEY"], "base_url": "https://openrouter.ai/api/v1", }, model_id="openai/gpt-5.4", ) agent = Agent(model=model) response = agent("Explain tool calling in one sentence.") print(response) ``` (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { Agent } from '@strands-agents/sdk' import { OpenAIModel } from '@strands-agents/sdk/models/openai' const model = new OpenAIModel({ api: 'chat', apiKey: process.env.OPENROUTER_API_KEY, clientConfig: { baseURL: 'https://openrouter.ai/api/v1', }, modelId: 'openai/gpt-5.4', }) const agent = new Agent({ model }) const response = await agent.invoke('Explain tool calling in one sentence.') console.log(response) ``` (( /tab "TypeScript" )) ## Configuration Two client settings connect the provider to OpenRouter: - **API key**: from your [OpenRouter settings](https://openrouter.ai/settings/keys) - **Base URL**: `https://openrouter.ai/api/v1` Model IDs come from the [OpenRouter catalog](https://openrouter.ai/models) and are prefixed with the lab name, for example `openai/gpt-5.4` or `anthropic/claude-sonnet-4-5`. For model parameters and other provider options, see the [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) guide. ## References - [OpenRouter quickstart](https://openrouter.ai/docs/quickstart) - [OpenRouter model catalog](https://openrouter.ai/models) - [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) Source: https://strandsagents.com/docs/integrations/model-providers/openrouter/index.md --- ## OrcaRouter [OrcaRouter](https://www.orcarouter.ai) is an OpenAI-compatible AI gateway built for both models and agents. Like OpenRouter, it exposes a provider/model namespace across many models — but it also combines adaptive routing, automatic failover, zero-markup inference, observability, guardrails, and agent-tool governance behind the same endpoint. OpenAI compatibility This integration works through the SDK’s built-in [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) pointed at OrcaRouter’s OpenAI-compatible endpoint; there is no separate OrcaRouter integration. Compatible endpoints can have quirks that deviate from the exact OpenAI API spec, so some features may behave differently than they do against OpenAI itself. ## Installation The OpenAI provider is an optional dependency. To install, run: (( tab "Python" )) ```bash pip install 'strands-agents[openai]' ``` (( /tab "Python" )) (( tab "TypeScript" )) ```bash npm install @strands-agents/sdk openai ``` (( /tab "TypeScript" )) ## Usage Create an [API key](https://www.orcarouter.ai/keys), export it as `ORCAROUTER_API_KEY`, and point the provider at OrcaRouter’s endpoint: (( tab "Python" )) ```python import os from strands import Agent from strands.models.openai import OpenAIModel model = OpenAIModel( client_args={ "api_key": os.environ["ORCAROUTER_API_KEY"], "base_url": "https://api.orcarouter.ai/v1", }, model_id="orcarouter/auto", ) agent = Agent(model=model) response = agent("Explain tool calling in one sentence.") print(response) ``` (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { Agent } from '@strands-agents/sdk' import { OpenAIModel } from '@strands-agents/sdk/models/openai' const model = new OpenAIModel({ api: 'chat', apiKey: process.env.ORCAROUTER_API_KEY, clientConfig: { baseURL: 'https://api.orcarouter.ai/v1', }, modelId: 'orcarouter/auto', }) const agent = new Agent({ model }) const response = await agent.invoke('Explain tool calling in one sentence.') console.log(response) ``` (( /tab "TypeScript" )) ## Configuration Two client settings connect the provider to OrcaRouter: - **API key**: from your [OrcaRouter dashboard](https://www.orcarouter.ai/keys) - **Base URL**: `https://api.orcarouter.ai/v1` Model IDs come from the [OrcaRouter model catalog](https://www.orcarouter.ai/models) and are prefixed with the gateway name, for example `orcarouter/auto` or `orcarouter/fusion`. For model parameters and other provider options, see the [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) guide. ## References - [OrcaRouter docs](https://docs.orcarouter.ai) - [OrcaRouter model catalog](https://www.orcarouter.ai/models) - [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) Source: https://strandsagents.com/docs/integrations/model-providers/orcarouter/index.md --- ## OVHcloud AI Endpoints [OVHcloud AI Endpoints](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/) offers access to a wide range of language models from a European cloud provider, with data sovereignty and GDPR compliance. OpenAI compatibility This integration works through the SDK’s built-in [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) pointed at OVHcloud’s OpenAI-compatible endpoint; there is no separate OVHcloud integration. Compatible endpoints can have quirks that deviate from the exact OpenAI API spec, so some features may behave differently than they do against OpenAI itself. ## Installation The OpenAI provider is an optional dependency. To install, run: (( tab "Python" )) ```bash pip install 'strands-agents[openai]' ``` (( /tab "Python" )) (( tab "TypeScript" )) ```bash npm install @strands-agents/sdk openai ``` (( /tab "TypeScript" )) ## Usage Generate an API key in the [OVHcloud Manager](https://ovh.com/manager) under **Public Cloud** > **AI & Machine Learning** > **AI Endpoints** > **API keys**, export it as `OVHCLOUD_API_KEY`, and point the provider at the AI Endpoints endpoint: (( tab "Python" )) ```python import os from strands import Agent from strands.models.openai import OpenAIModel model = OpenAIModel( client_args={ # An empty key selects the rate-limited free tier "api_key": os.environ.get("OVHCLOUD_API_KEY", ""), "base_url": "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1", }, model_id="Meta-Llama-3_3-70B-Instruct", ) agent = Agent(model=model) response = agent("Explain tool calling in one sentence.") print(response) ``` (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { Agent } from '@strands-agents/sdk' import { OpenAIModel } from '@strands-agents/sdk/models/openai' const model = new OpenAIModel({ api: 'chat', // A non-empty API key is required; the keyless free tier is not supported apiKey: process.env.OVHCLOUD_API_KEY, clientConfig: { baseURL: 'https://oai.endpoints.kepler.ai.cloud.ovh.net/v1', }, modelId: 'Meta-Llama-3_3-70B-Instruct', }) const agent = new Agent({ model }) const response = await agent.invoke('Explain tool calling in one sentence.') console.log(response) ``` (( /tab "TypeScript" )) ## Configuration Two client settings connect the provider to OVHcloud AI Endpoints: - **API key**: from the [OVHcloud Manager](https://ovh.com/manager). Without a key, requests use a rate-limited free tier; the Python provider accepts an empty key string, while the TypeScript provider requires a non-empty key. - **Base URL**: `https://oai.endpoints.kepler.ai.cloud.ovh.net/v1` Model IDs come from the [AI Endpoints catalog](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/catalog/), for example `Meta-Llama-3_3-70B-Instruct`. For model parameters and other provider options, see the [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) guide. ## References - [OVHcloud AI Endpoints](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/) - [OVHcloud AI Endpoints catalog](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/catalog/) - [OpenAI provider](/docs/user-guide/sdk/model-providers/openai/index.md) Source: https://strandsagents.com/docs/integrations/model-providers/ovhcloud-ai-endpoints/index.md --- ## SGLang [strands-sglang](https://github.com/horizon-rl/strands-sglang) is an [SGLang](https://docs.sglang.io/) model provider for Strands Agents SDK with Token-In/Token-Out (TITO) support for agentic RL training. It provides direct integration with SGLang servers using the native `/generate` endpoint, optimized for reinforcement learning workflows. **Features:** - **SGLang Native API**: Uses SGLang’s native `/generate` endpoint with non-streaming POST for optimal parallelism - **TITO Support**: Tracks complete token trajectories with logprobs for RL training - no retokenization drift - **Tool Call Parsing**: Customizable tool parsing aligned with model chat templates (Hermes/Qwen format) - **Iteration Limiting**: Built-in hook to limit tool iterations with clean trajectory truncation - **RL Training Optimized**: Connection pooling, aggressive retry (60 attempts), and non-streaming design aligned with [Slime’s http\_utils.py](https://github.com/THUDM/slime/blob/main/slime/utils/http_utils.py) ## Installation Install strands-sglang along with the Strands Agents SDK: ```bash pip install strands-sglang ``` ## Requirements - SGLang server running with your model - HuggingFace tokenizer for the model ## Usage ### 1\. Start SGLang Server First, start an SGLang server with your model: ```bash python -m sglang.launch_server \ --model-path Qwen/Qwen3-4B-Instruct-2507 \ --port 30000 \ --host 0.0.0.0 ``` ### 2\. Basic Agent ```python import asyncio from transformers import AutoTokenizer from strands import Agent from strands.vended_tools import notebook from strands_sglang import SGLangModel async def main(): tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B-Instruct-2507") model = SGLangModel(tokenizer=tokenizer, base_url="http://localhost:30000") agent = Agent(model=model, tools=[notebook]) model.reset() # Reset TITO state for new episode result = await agent.invoke_async( 'Create a notebook named "ideas" and add three uses for structured generation.' ) print(result) # Access TITO data for RL training print(f"Tokens: {model.token_manager.token_ids}") print(f"Loss mask: {model.token_manager.loss_mask}") print(f"Logprobs: {model.token_manager.logprobs}") asyncio.run(main()) ``` ### 3\. Slime RL Training For RL training with [Slime](https://github.com/THUDM/slime/), `SGLangModel` with TITO eliminates the retokenization step: ```python from strands import Agent, tool from strands_sglang import SGLangClient, SGLangModel, ToolIterationLimiter from slime.utils.types import Sample SYSTEM_PROMPT = "..." MAX_TOOL_ITERATIONS = 5 _client_cache: dict[str, SGLangClient] = {} def get_client(args) -> SGLangClient: """Get shared client for connection pooling (like Slime).""" base_url = f"http://{args.sglang_router_ip}:{args.sglang_router_port}" if base_url not in _client_cache: _client_cache[base_url] = SGLangClient.from_slime_args(args) return _client_cache[base_url] @tool def execute_python_code(code: str): """Execute Python code and return the output.""" ... async def generate(args, sample: Sample, sampling_params) -> Sample: """Generate with TITO: tokens captured during generation, no retokenization.""" assert not args.partial_rollout, "Partial rollout not supported." state = GenerateState(args) # Set up Agent with SGLangModel and ToolIterationLimiter hook model = SGLangModel( tokenizer=state.tokenizer, client=get_client(args), model_id=args.hf_checkpoint.split("/")[-1], params={k: sampling_params[k] for k in ["max_new_tokens", "temperature", "top_p"]}, ) limiter = ToolIterationLimiter(max_iterations=MAX_TOOL_ITERATIONS) agent = Agent( model=model, tools=[execute_python_code], hooks=[limiter], callback_handler=None, system_prompt=SYSTEM_PROMPT, ) # Run Agent Loop prompt = sample.prompt if isinstance(sample.prompt, str) else sample.prompt[0]["content"] try: await agent.invoke_async(prompt) sample.status = Sample.Status.COMPLETED except Exception as e: # Always use TRUNCATED instead of ABORTED because Slime doesn't properly # handle ABORTED samples in reward processing. See: https://github.com/THUDM/slime/issues/200 sample.status = Sample.Status.TRUNCATED logger.warning(f"TRUNCATED: {type(e).__name__}: {e}") # TITO: extract trajectory from token_manager tm = model.token_manager prompt_len = len(tm.segments[0]) # system + user are first segment sample.tokens = tm.token_ids sample.loss_mask = tm.loss_mask[prompt_len:] sample.rollout_log_probs = tm.logprobs[prompt_len:] sample.response_length = len(sample.tokens) - prompt_len sample.response = model.tokenizer.decode(sample.tokens[prompt_len:], skip_special_tokens=False) # Cleanup and return model.reset() agent.cleanup() return sample ``` ## Configuration ### Model Configuration The `SGLangModel` accepts the following parameters: | Parameter | Description | Example | Required | | --- | --- | --- | --- | | `tokenizer` | HuggingFace tokenizer instance | `AutoTokenizer.from_pretrained("Qwen/Qwen3-4B-Instruct-2507")` | Yes | | `base_url` | SGLang server URL | `"http://localhost:30000"` | Yes (or `client`) | | `client` | Pre-configured `SGLangClient` | `SGLangClient.from_slime_args(args)` | Yes (or `base_url`) | | `model_id` | Model identifier for logging | `"Qwen3-4B-Instruct-2507"` | No | | `params` | Generation parameters | `{"max_new_tokens": 2048, "temperature": 0.7}` | No | | `enable_thinking` | Enable thinking mode for Qwen3 hybrid models | `True` or `False` | No | ### Client Configuration For RL training, use a centralized `SGLangClient` with connection pooling: ```python from strands_sglang import SGLangClient, SGLangModel # Option 1: Direct configuration client = SGLangClient( base_url="http://localhost:30000", max_connections=1000, # Default: 1000 timeout=None, # Default: None (infinite, like Slime) max_retries=60, # Default: 60 (aggressive retry for RL stability) retry_delay=1.0, # Default: 1.0 seconds ) # Option 2: Adaptive to Slime's training args client = SGLangClient.from_slime_args(args) model = SGLangModel(tokenizer=tokenizer, client=client) ``` | Parameter | Description | Default | | --- | --- | --- | | `base_url` | SGLang server URL | Required | | `max_connections` | Maximum concurrent connections | `1000` | | `timeout` | Request timeout (None = infinite) | `None` | | `max_retries` | Retry attempts on transient errors | `60` | | `retry_delay` | Delay between retries (seconds) | `1.0` | ## Troubleshooting ### Connection errors to SGLang server Ensure your SGLang server is running and accessible: ```bash # Check if server is responding curl http://localhost:30000/health ``` ### Token trajectory mismatch If TITO data doesn’t match expected output, ensure you call `model.reset()` before each new episode to clear the token manager state. ## References - [strands-sglang Repository](https://github.com/horizon-rl/strands-sglang) - [SGLang Documentation](https://docs.sglang.io/) - [Slime RL Training Framework](https://github.com/THUDM/slime/) - [Strands Agents API](/docs/api/python/strands.models.model) Source: https://strandsagents.com/docs/integrations/model-providers/sglang/index.md --- ## vLLM [strands-vllm](https://github.com/agents-community/strands-vllm) is a [vLLM](https://docs.vllm.ai/) model provider for Strands Agents SDK with Token-In/Token-Out (TITO) support for agentic RL training. It provides integration with vLLM’s OpenAI-compatible API, optimized for reinforcement learning workflows with [Agent Lightning](https://blog.vllm.ai/2025/10/22/agent-lightning.html). **Features:** - **OpenAI-Compatible API**: Uses vLLM’s OpenAI-compatible `/v1/chat/completions` endpoint with streaming - **TITO Support**: Captures `prompt_token_ids` and `token_ids` directly from vLLM - no retokenization drift - **Tool Call Validation**: Optional hooks for RL-friendly error messages (allowed tools list, schema validation) - **Agent Lightning Integration**: Automatically adds token IDs to OpenTelemetry spans for RL training data extraction - **Streaming**: Full streaming support with token ID capture via `VLLMTokenRecorder` Why TITO? Traditional retokenization can cause drift in RL training—the same text may tokenize differently during inference vs. training (e.g., “HAVING” → `H`+`AVING` vs. `HAV`+`ING`). TITO captures exact tokens from vLLM, eliminating this issue. See [No More Retokenization Drift](https://blog.vllm.ai/2025/10/22/agent-lightning.html) for details. ## Installation Install strands-vllm along with the Strands Agents SDK: ```bash pip install strands-vllm strands-agents ``` For retokenization drift demos (requires HuggingFace tokenizer): ```bash pip install "strands-vllm[drift]" strands-agents ``` ## Requirements - vLLM server running with your model (v0.10.2+ for `return_token_ids` support) - For tool calling: vLLM must be started with tool-calling enabled and appropriate chat template ## Usage ### 1\. Start vLLM Server First, start a vLLM server with your model: ```bash vllm serve \ --host 0.0.0.0 \ --port 8000 ``` For tool calling support, add the appropriate flags for your model: ```bash vllm serve \ --host 0.0.0.0 \ --port 8000 \ --enable-auto-tool-choice \ --tool-call-parser # e.g., llama3_json, hermes, etc. ``` See [vLLM tool calling documentation](https://docs.vllm.ai/en/latest/features/tool_calling.html) for supported parsers and chat templates. ### 2\. Basic Agent ```python import os from strands import Agent from strands_vllm import VLLMModel, VLLMTokenRecorder # Configure via environment variables or directly base_url = os.getenv("VLLM_BASE_URL", "http://localhost:8000/v1") model_id = os.getenv("VLLM_MODEL_ID", "") model = VLLMModel( base_url=base_url, model_id=model_id, return_token_ids=True, ) recorder = VLLMTokenRecorder() agent = Agent(model=model, callback_handler=recorder) result = agent("What is the capital of France?") print(result) # Access TITO data for RL training print(f"Prompt tokens: {len(recorder.prompt_token_ids or [])}") print(f"Response tokens: {len(recorder.token_ids or [])}") ``` ### 3\. Tool Call Validation (Optional, Recommended for RL) Strands Harness SDK already handles unknown tools and malformed JSON gracefully. `VLLMToolValidationHooks` adds RL-friendly enhancements: ```python import os from strands import Agent from strands.vended_tools import sleep from strands_vllm import VLLMModel, VLLMToolValidationHooks model = VLLMModel( base_url=os.getenv("VLLM_BASE_URL", "http://localhost:8000/v1"), model_id=os.getenv("VLLM_MODEL_ID", ""), return_token_ids=True, ) agent = Agent( model=model, tools=[sleep], hooks=[VLLMToolValidationHooks()], ) result = agent("Pause for one second using the sleep tool.") print(result) ``` **What it adds beyond Strands defaults:** - **Unknown tool errors include allowed tools list** — helps RL training learn valid tool names - **Schema validation** — catches missing required args and unknown args before tool execution Invalid tool calls receive deterministic error messages, providing cleaner RL training signals. ### 4\. Agent Lightning Integration `VLLMTokenRecorder` automatically adds token IDs to OpenTelemetry spans for [Agent Lightning](https://blog.vllm.ai/2025/10/22/agent-lightning.html) compatibility: ```python import os from strands import Agent from strands_vllm import VLLMModel, VLLMTokenRecorder model = VLLMModel( base_url=os.getenv("VLLM_BASE_URL", "http://localhost:8000/v1"), model_id=os.getenv("VLLM_MODEL_ID", ""), return_token_ids=True, ) # add_to_span=True (default) adds token IDs to OpenTelemetry spans recorder = VLLMTokenRecorder(add_to_span=True) agent = Agent(model=model, callback_handler=recorder) result = agent("Hello!") ``` The following span attributes are set: | Attribute | Description | | --- | --- | | `llm.token_count.prompt` | Token count for the prompt (OpenTelemetry semantic convention) | | `llm.token_count.completion` | Token count for the completion (OpenTelemetry semantic convention) | | `llm.hosted_vllm.prompt_token_ids` | Token ID array for the prompt | | `llm.hosted_vllm.response_token_ids` | Token ID array for the response | ### 5\. RL Training with TokenManager For building RL-ready trajectories with loss masks: ```python import asyncio import os from strands import Agent from strands.vended_tools import notebook from strands_vllm import TokenManager, VLLMModel, VLLMTokenRecorder, VLLMToolValidationHooks async def main(): model = VLLMModel( base_url=os.getenv("VLLM_BASE_URL", "http://localhost:8000/v1"), model_id=os.getenv("VLLM_MODEL_ID", ""), return_token_ids=True, ) recorder = VLLMTokenRecorder() agent = Agent( model=model, tools=[notebook], hooks=[VLLMToolValidationHooks()], callback_handler=recorder, ) await agent.invoke_async( 'Create a notebook named "training" with three RL experiment ideas.' ) # Build RL trajectory with loss mask tm = TokenManager() for entry in recorder.history: if entry.get("prompt_token_ids"): tm.add_prompt(entry["prompt_token_ids"]) # loss_mask=0 if entry.get("token_ids"): tm.add_response(entry["token_ids"]) # loss_mask=1 print(f"Total tokens: {len(tm)}") print(f"Prompt tokens: {sum(1 for m in tm.loss_mask if m == 0)}") print(f"Response tokens: {sum(1 for m in tm.loss_mask if m == 1)}") print(f"Token IDs: {tm.token_ids[:20]}...") # First 20 tokens print(f"Loss mask: {tm.loss_mask[:20]}...") asyncio.run(main()) ``` ## Configuration ### Model Configuration The `VLLMModel` accepts the following parameters: | Parameter | Description | Example | Required | | --- | --- | --- | --- | | `base_url` | vLLM server URL | `"http://localhost:8000/v1"` | Yes | | `model_id` | Model identifier | `""` | Yes | | `api_key` | API key (usually “EMPTY” for local vLLM) | `"EMPTY"` | No (default: “EMPTY”) | | `return_token_ids` | Request token IDs from vLLM | `True` | No (default: False) | | `disable_tools` | Remove tools/tool\_choice from requests | `True` | No (default: False) | | `params` | Additional generation parameters | `{"temperature": 0, "max_tokens": 256}` | No | ### VLLMTokenRecorder Configuration | Parameter | Description | Default | | --- | --- | --- | | `inner` | Inner callback handler to chain | `None` | | `add_to_span` | Add token IDs to OpenTelemetry spans | `True` | ### VLLMToolValidationHooks Configuration | Parameter | Description | Default | | --- | --- | --- | | `include_allowed_tools_in_errors` | Include list of allowed tools in error messages | `True` | | `max_allowed_tools_in_error` | Maximum tool names to show in error messages | `25` | | `validate_input_shape` | Validate required/unknown args against schema | `True` | **Example error messages** (more informative than Strands defaults): - Unknown tool: `Error: unknown tool: fake_tool | allowed_tools=[sleep, search, ...]` - Missing argument: `Error: tool_name= | missing required argument(s): duration` - Unknown argument: `Error: tool_name= | unknown argument(s): invalid_param` ## Troubleshooting ### Connection errors to vLLM server Ensure your vLLM server is running and accessible: ```bash # Check if server is responding curl http://localhost:8000/health ``` ### No token IDs captured Ensure: 1. vLLM version is 0.10.2 or later 2. `return_token_ids=True` is set on `VLLMModel` 3. Your vLLM server supports `return_token_ids` in streaming mode ### RL training needs cleaner error signals Strands handles unknown tools gracefully, but for RL training you may want more informative errors. Add `VLLMToolValidationHooks` to get errors that include the list of allowed tools and validate argument schemas. ### Model only supports single tool calls Some models/chat templates only support one tool call per message. If you see `"This model only supports single tool-calls at once!"`, adjust your prompts to request one tool at a time. ## References - [strands-vllm Repository](https://github.com/agents-community/strands-vllm) - [vLLM Documentation](https://docs.vllm.ai/) - [Agent Lightning GitHub](https://github.com/microsoft/agent-lightning) - The absolute trainer to light up AI agents - [Agent Lightning Blog Post](https://blog.vllm.ai/2025/10/22/agent-lightning.html) - No More Retokenization Drift - [Strands Agents API](/docs/api/python/strands.models.model) Source: https://strandsagents.com/docs/integrations/model-providers/vllm/index.md --- ## xAI [xAI](https://x.ai/) is an AI company that develops the Grok family of large language models with advanced reasoning capabilities. The [`strands-xai`](https://pypi.org/project/strands-xai/) package ([GitHub](https://github.com/Cerrix/strands-xai)) provides a community-maintained integration for the Strands Agents SDK, enabling seamless use of xAI’s Grok models with powerful server-side tools including real-time X platform access, web search, and code execution. ## Installation xAI integration is available as a separate community package: ```bash pip install strands-agents strands-xai ``` ## Usage After installing `strands-xai`, you can import and initialize the xAI provider. API Key Required Ensure `XAI_API_KEY` is set in your environment, or pass it via `client_args={"api_key": "your-key"}`. ```python from strands import Agent from strands_xai import xAIModel model = xAIModel( client_args={"api_key": "xai-key"}, # or set XAI_API_KEY env var model_id="grok-4.3", ) agent = Agent(model=model) response = agent("What's trending on X right now?") print(response.message) ``` ### With Strands Tools You can use regular Strands tools just like with any other model provider: ```python from strands import Agent, tool from strands_xai import xAIModel @tool def calculate(expression: str) -> str: """Evaluate a mathematical expression.""" try: result = eval(expression) return f"Result: {result}" except Exception as e: return f"Error: {e}" @tool def get_weather(city: str) -> str: """Get the current weather for a city.""" return f"Weather in {city}: Sunny, 22°C" model = xAIModel( client_args={"api_key": "xai-key"}, model_id="grok-4.3", ) agent = Agent(model=model, tools=[calculate, get_weather]) response = agent("What's 15 * 7 and what's the weather in Paris?") ``` ## Configuration ### Environment Variables ```bash export XAI_API_KEY="your-api-key" ``` ### Model Configuration The supported configurations are: | Parameter | Description | Example | Default | | --- | --- | --- | --- | | `model_id` | Grok model identifier (required) | `"grok-4.3"` | *required* | | `client_args` | xAI client arguments | `{"api_key": "xai-key"}` | `{}` | | `params` | Model parameters dict | `{"temperature": 0.7}` | `{}` | | `xai_tools` | Server-side tools list | `[web_search(), x_search()]` | `[]` | | `reasoning_effort` | Reasoning level (**grok-4.3 only**): `"none"`, `"low"`, `"medium"`, `"high"` | `"high"` | `"low"` | | `use_encrypted_content` | Preserve reasoning / sub-agent state across turns (auto-enabled when `xai_tools` is set) | `True` | `False` | | `include` | Optional xAI features | `["inline_citations"]` | `[]` | | `agent_count` | Number of agents (4 or 16) for `grok-4.20-multi-agent` | `4` | `None` | reasoning\_effort is grok-4.3 only Only `grok-4.3` accepts `reasoning_effort`. Passing it to `grok-build-0.1` or the pinned `grok-4.20-0309-*` snapshots returns `INVALID_ARGUMENT` — those snapshots have their reasoning behavior baked in. On `grok-4.20-multi-agent`, use `agent_count` instead. Reasoning models also reject `presence_penalty`, `frequency_penalty`, and `stop` in `params`. **Model Parameters (in `params` dict):** - `temperature` - Sampling temperature (0.0-2.0) - `max_tokens` - Maximum tokens in response - `top_p` - Nucleus sampling parameter (0.0-1.0) - `frequency_penalty` - Frequency penalty (-2.0 to 2.0) - `presence_penalty` - Presence penalty (-2.0 to 2.0) **Available Models:** | Model | Context | Vision | Best for | | --- | --- | --- | --- | | `grok-4.3` | 1M | ✅ | Flagship — agentic tool calling, configurable reasoning | | `grok-build-0.1` | 256K | ✅ | Agentic coding, early access | | `grok-4.20-multi-agent` | 1M | ✅ | Multi-agent research — rolling alias | | `grok-4.20-multi-agent-0309` | 1M | ✅ | Multi-agent research — pinned snapshot | | `grok-4.20-0309-reasoning` | 1M | ✅ | Pinned 4.20 reasoning snapshot | | `grok-4.20-0309-non-reasoning` | 1M | ✅ | Pinned 4.20 inference snapshot | xAI uses a consistent alias convention: `` resolves to the latest stable version, `-latest` to the bleeding edge, and `-` to a pinned snapshot. Retired aliases (e.g. `grok-4*`, `grok-3*`, `grok-3-mini*`, `grok-code-fast-1`) now silently redirect to `grok-4.3` or `grok-build-0.1`. See the [xAI models documentation](https://docs.x.ai/docs/models) for the authoritative list and pricing. ## Advanced Features ### Server-Side Tools xAI models come with built-in server-side tools executed by xAI’s infrastructure, providing unique capabilities: ```python from strands_xai import xAIModel from strands import Agent from xai_sdk.tools import web_search, x_search, code_execution # Server-side tools are executed on xAI's servers model = xAIModel( client_args={"api_key": "xai-key"}, model_id="grok-4.3", xai_tools=[web_search(), x_search(), code_execution()], ) agent = Agent(model=model) # Model can autonomously use web_search, x_search, and code_execution tools response = agent("Search X for recent AI developments and analyze the sentiment") ``` **Built-in Server-Side Tools:** - **`web_search()`** - Live web search across diverse data sources - **`x_search()`** - Real-time access to X platform posts, trends, and conversations - **`code_execution()`** - Python code execution for data analysis and computation - **`collections_search()`** - Search uploaded document collections (RAG) ### Hybrid Tool Usage Combine xAI’s server-side tools with your own Strands tools for maximum flexibility: ```python from strands import Agent, tool from strands_xai import xAIModel from xai_sdk.tools import x_search @tool def get_weather(city: str) -> str: """Get the current weather for a city.""" return f"Weather in {city}: Sunny, 22°C" model = xAIModel( client_args={"api_key": "xai-key"}, model_id="grok-4.3", xai_tools=[x_search()], # Server-side X search ) # Combine server-side and client-side tools agent = Agent(model=model, tools=[get_weather]) response = agent("Search X for AI news and tell me the weather in Tokyo") ``` ### Reasoning `grok-4.3` supports configurable reasoning depth via `reasoning_effort` (`"none"`, `"low"` (default), `"medium"`, `"high"`): ```python model = xAIModel( client_args={"api_key": "xai-key"}, model_id="grok-4.3", reasoning_effort="high", ) agent = Agent(model=model) response = agent("Find all prime numbers p such that p^2 + 2 is also prime. Prove your answer.") ``` Reasoning-capable models stream a **summarized** trace of the model’s thinking (surfaced as Strands `reasoningContent.reasoningText` blocks) and report `reasoning_tokens` in usage metadata. The full chain-of-thought is not exposed — current Grok models return only this summary. ### Encrypted Reasoning (Multi-Turn Context) To preserve reasoning and server-side tool state across turns, enable `use_encrypted_content`. This lets follow-up turns reference earlier encrypted context (for example, asking the model to list the source URLs it used in a previous answer): ```python model = xAIModel( client_args={"api_key": "xai-key"}, model_id="grok-4.3", reasoning_effort="medium", use_encrypted_content=True, # Preserves reasoning across turns ) agent = Agent(model=model) agent("Think through this problem: 2+2") agent("Now multiply that by 3") # reasoning context preserved ``` Auto-enabled with server-side tools `use_encrypted_content` is automatically enabled whenever `xai_tools` is set, so server-side tool state is preserved across turns without extra configuration. ### Multi-Agent Research `grok-4.20-multi-agent` orchestrates multiple collaborating agents on research tasks. Set `agent_count` to 4 (focused) or 16 (comprehensive): ```python from strands_xai import xAIModel from strands import Agent from xai_sdk.tools import web_search, x_search model = xAIModel( client_args={"api_key": "xai-key"}, model_id="grok-4.20-multi-agent", xai_tools=[web_search(), x_search()], agent_count=4, # or 16 for deeper research ) agent = Agent(model=model) response = agent("Research the latest breakthroughs in quantum computing") ``` Beta The multi-agent API is in beta on xAI and may change. The multi-agent model does **not** support client-side tools or `max_tokens`, only the leader agent’s output is returned (sub-agent state is preserved via the auto-enabled `use_encrypted_content`), and tokens for the leader **and** all sub-agents are billed — expect usage to scale with `agent_count`. ### Inline Citations Enable inline source citations in responses with `include=["inline_citations"]`: ```python from strands_xai import xAIModel from strands import Agent from xai_sdk.tools import web_search model = xAIModel( client_args={"api_key": "xai-key"}, model_id="grok-4.3", xai_tools=[web_search()], include=["inline_citations"], ) agent = Agent(model=model, system_prompt="Always cite your sources.") response = agent("What are the latest developments in AI?") # Output includes inline citations like [1], [2] with source URLs ``` ### Vision (Image Understanding) Vision-capable models analyze images sent as content blocks: ```python from strands_xai import xAIModel from strands import Agent model = xAIModel( client_args={"api_key": "xai-key"}, model_id="grok-4.3", # vision-capable ) agent = Agent(model=model) with open("image.png", "rb") as f: image_bytes = f.read() message = [ {"text": "What's in this image?"}, {"image": {"format": "png", "source": {"bytes": image_bytes}}}, ] response = agent(message) ``` ## Observability / OpenTelemetry Strands instruments each model call and emits spans with correct token usage. The underlying `xai_sdk` also ships its own OpenTelemetry instrumentation, which emits a duplicate `chat.stream` span for the same call. That extra span reports token usage in xAI’s raw form (output excludes reasoning, total includes it), which can make trace-level totals inconsistent in observability backends. When running `strands-xai` with any OpenTelemetry backend, disable `xai_sdk`’s own tracing so only Strands’ spans are exported: ```bash export XAI_SDK_DISABLE_TRACING=1 ``` Set it in your environment **before** starting the process — `xai_sdk` binds its tracer at import time, so setting it from Python after import has no effect. With this set, traces contain a single clean span tree and token totals reconcile (`input + output == total`, with reasoning folded into output). ## References - [strands-xai GitHub Repository](https://github.com/Cerrix/strands-xai) - [xAI API Documentation](https://docs.x.ai/) - [xAI Models and Pricing](https://docs.x.ai/docs/models) Source: https://strandsagents.com/docs/integrations/model-providers/xai/index.md --- ## Agent Control [Agent Control](https://github.com/agentcontrol/agent-control) provides an open-source runtime control plane for all your AI agents — configurable rules that evaluate inputs and outputs at every step in your agent against a set of policies managed centrally, without modifying your agent’s code. It integrates with Strands via the `AgentControlPlugin` or `AgentControlSteeringHandler`: - **AgentControlPlugin** — hooks into Strands lifecycle events (`BeforeToolCallEvent`, `AfterModelCallEvent`, etc.) and enforces hard blocks (deny) or corrective steering on violations - **AgentControlSteeringHandler** — integrates with Strands’ experimental steering API to convert Agent Control `steer` matches into `Guide()` actions, prompting the agent to rewrite its output before proceeding Controls are defined on a central server (or locally via `controls.yaml`) and evaluated at runtime — no redeployment needed when rules change. ## Installation ```bash pip install "agent-control-sdk[strands-agents]" ``` The SDK connects to a running Agent Control server. Point it at your instance via the `AGENT_CONTROL_URL` environment variable (defaults to `http://localhost:8000`). See the [Agent Control docs](https://docs.agentcontrol.dev/) for server setup options. ## Usage ### Basic setup with AgentControlPlugin ```python import agent_control from agent_control.integrations.strands import AgentControlPlugin from strands import Agent from strands.models.openai import OpenAIModel # Initialize once at startup — registers the agent and fetches controls agent_control.init(agent_name="my-agent") # Attach the plugin — all lifecycle events are intercepted automatically agent_control_plugin = AgentControlPlugin(agent_name="my-agent") agent = Agent( model=OpenAIModel(model_id="gpt-4o-mini"), system_prompt="You are a helpful assistant.", tools=[...], plugins=[agent_control_plugin], ) result = await agent.invoke_async("Hello!") ``` When a control matches, the plugin raises an exception that should be caught above the agent call site. ### Adding steering for LLM output correction For cases where you want the agent to *fix* its output rather than hard-block, combine the plugin with `AgentControlSteeringHandler`: ```python from agent_control.integrations.strands import AgentControlPlugin, AgentControlSteeringHandler from strands.hooks import BeforeToolCallEvent, AfterToolCallEvent # Plugin handles tool-stage deny checks agent_control_plugin = AgentControlPlugin( agent_name="my-agent", event_control_list=[BeforeToolCallEvent, AfterToolCallEvent], ) # Steering handler converts steer matches into Strands Guide() retries steering = AgentControlSteeringHandler(agent_name="my-agent") agent = Agent( model=model, system_prompt="...", tools=[...], plugins=[agent_control_plugin, steering], # both registered as plugins ) ``` When a `steer` control matches on LLM output, `AgentControlSteeringHandler` returns a `Guide(reason=)` and the agent retries with that guidance injected. ## Configuration **AgentControlPlugin** | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `agent_name` | `str` | required | Agent identifier, must match the name used in `agent_control.init()` | | `event_control_list` | `list[type] | None` | `None` | Strands event types to intercept. Defaults to all supported events (`BeforeInvocationEvent`, `BeforeModelCallEvent`, `AfterModelCallEvent`, `BeforeToolCallEvent`, `AfterToolCallEvent`, `BeforeNodeCallEvent`, `AfterNodeCallEvent`) | | `on_violation_callback` | `Callable | None` | `None` | Called on every violation with `(info_dict, EvaluationResult)`. Useful for logging or metrics | | `enable_logging` | `bool` | `True` | Emit debug log lines for control checks and violations | **AgentControlSteeringHandler** | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `agent_name` | `str` | required | Agent identifier, must match the name used in `agent_control.init()` | | `enable_logging` | `bool` | `True` | Emit debug log lines for steering evaluations | ### Environment variables | Variable | Default | Description | | --- | --- | --- | | `AGENT_CONTROL_URL` | `http://localhost:8000` | Server URL | | `AGENT_CONTROL_API_KEY` | — | API key (if auth is enabled) | ## Troubleshooting **“AgentControl not initialized”** — call `agent_control.init()` before creating the plugin. **Controls not triggering** — verify the server is running (`curl http://localhost:8000/health`) and controls are attached to your agent (re-run your setup script). **Import errors** — make sure you installed the `strands-agents` extra: `pip install "agent-control-sdk[strands-agents]"`. ## References - [GitHub](https://github.com/agentcontrol/agent-control) - [PyPI](https://pypi.org/project/agent-control-sdk/) - [Documentation](https://docs.agentcontrol.dev/) - [Strands integration examples](https://github.com/agentcontrol/agent-control/tree/main/examples/strands_agents) Source: https://strandsagents.com/docs/integrations/plugins/agent-control/index.md --- ## Amazon AgentCore Payments The [AgentCore payments plugin](https://github.com/aws/bedrock-agentcore-sdk-python/tree/main/src/bedrock_agentcore/payments/integrations/strands) leverages Amazon Bedrock AgentCore payments to provide automated payment processing capabilities for Strands Agents. It supports the [x402 Payment Required](https://www.x402.org/) protocol, enabling agents to automatically handle HTTP 402 responses by processing microtransaction payments to access paid APIs, MCP servers, and contents. - **Automatic x402 Payment Handling** — intercepts HTTP 402 responses from tools, processes payment requirements, and retries requests with payment headers - **Payment Query Tools** — built-in tools for agents to query payment instruments and sessions at runtime - **Multi-Protocol Support** — handles x402 v1 and v2 payment protocols - **Interrupt-Based Error Handling** — raises Strands Harness SDK interrupts on payment failures so the agent (or application) can respond dynamically - **Configurable Auto-Payment** — enable or disable automatic payment processing per plugin instance ## Installation ```bash pip install 'bedrock-agentcore[strands-agents]' ``` ## Usage ```python import os from strands import Agent from strands.vended_tools import http_request from bedrock_agentcore.payments.integrations.strands import ( AgentCorePaymentsPlugin, AgentCorePaymentsPluginConfig, ) plugin = AgentCorePaymentsPlugin(config=AgentCorePaymentsPluginConfig( payment_manager_arn=os.environ["PAYMENT_MANAGER_ARN"], user_id="test-user-123", payment_instrument_id=os.environ["PAYMENT_INSTRUMENT_ID"], payment_session_id=os.environ["PAYMENT_SESSION_ID"], region="us-east-1", )) agent = Agent( system_prompt="You are a helpful assistant that can access paid APIs.", tools=[http_request], plugins=[plugin], ) # 402 responses are automatically handled agent("access https://drvd12nxpcyd5.cloudfront.net/market-recap") ``` The plugin intercepts x402 payment requests automatically, processes the payment, and retries the request with payment proof. ## Built-in Agent Tools The plugin also registers three tools that agents can use to query payment information at runtime: | Tool | Description | | --- | --- | | `get_payment_instrument` | Retrieve details about a specific payment instrument | | `list_payment_instruments` | List all payment instruments for a user | | `get_payment_session` | Retrieve details about a payment session (budget, status, expiry) | These tools enable agents to make informed decisions about payment methods and limits during conversations. ## Prerequisites Before using the plugin, you need: - A **Payment Manager** — created via the PaymentClient control plane API or AWS Console - A **Payment Credential Provider** — configured with credentials of a payment provider such as Coinbase and Stripe - A **Payment Connector** — a wrapper over the payment credential provider for the payment manager - A **Payment Instrument** — a user’s registered payment instrument for x402 payment transactions - A **Payment Session** — a time-bounded session with optional payment limits AgentCore payments connects to external payment providers for wallet operations. You must obtain credentials from at least one of the supported providers (Coinbase, Stripe) before creating a PaymentConnector. ## Setup ### Creating Payment Manager and Connector One-time setup The payment resource creation shown below is typically done once, separately from your agent application. In production, you would create the payment resources through the AWS Console or a separate setup script using the AgentCore SDK, then use `PaymentManagerArn` and `PaymentConnectorId` in your agent application. ```python import os from bedrock_agentcore.payments.client import PaymentClient # This is typically done once, separately from your agent application payment_client = PaymentClient(region_name="us-east-1") response = payment_client.create_payment_manager_with_connector( payment_manager_name="AgentCorePaymentManager", payment_manager_description="Payment Manager for Agent Core", authorizer_type="AWS_IAM", role_arn="arn:aws:iam::123456789012:role/BedrockAgentCoreFullAccess", payment_connector_config={ "name": "agent-core-connector", "description": "Payment Connector for Agent Core", "payment_credential_provider_config": { "name": "agent-core-provider", "credential_provider_vendor": "CoinbaseCDP", "credentials": { "api_key_id": "", "api_key_secret": "", "wallet_secret": "", }, }, }, wait_for_ready=True, max_wait=300, poll_interval=5, ) # Export for reuse in your agent application payment_manager_arn = response["paymentManager"]["paymentManagerArn"] payment_connector_id = response["paymentConnector"]["paymentConnectorId"] os.environ["PAYMENT_MANAGER_ARN"] = payment_manager_arn os.environ["PAYMENT_CONNECTOR_ID"] = payment_connector_id print(f"Payment Manager ARN: {payment_manager_arn}") print(f"Payment Connector ID: {payment_connector_id}") ``` The `wait_for_ready=True` parameter causes the method to poll until all resources reach READY status. If any step fails, previously created resources are automatically rolled back. ### Creating a Payment Instrument Create a payment instrument for a given user to process payments. Below is an example creating an Ethereum chain-compatible embedded crypto wallet: ```python instrument = manager.create_payment_instrument( user_id="test-user-123", payment_connector_id=os.environ["PAYMENT_CONNECTOR_ID"], payment_instrument_type="EMBEDDED_CRYPTO_WALLET", payment_instrument_details={ "embeddedCryptoWallet": { "network": "ETHEREUM", "linkedAccounts": [ {"email": {"emailAddress": "email@example.com"}} ], } }, ) payment_instrument_id = instrument["paymentInstrumentId"] os.environ["PAYMENT_INSTRUMENT_ID"] = payment_instrument_id print(f"Payment Instrument ID: {payment_instrument_id}") ``` For Solana-compatible chains, use `"SOLANA"` for the network input. Once created, the instrument must be funded and permission granted for signing before the agent can use it. These are end-user actions that should be completed before using the payment instrument in your agent. If you are using Coinbase as wallet provider, you’ll receive a redirectUrl in the payment instrument response, pointing to the Coinbase-hosted WalletHub. Redirect your user there to grant signing permission and transfer funds. For Stripe, developers use a provided URL template to host a frontend page where end users can take the same actions. ### Creating a Payment Session You also need a payment session before processing payments: ```python session = manager.create_payment_session( user_id="test-user-123", limits={"maxSpendAmount": {"value": "100.00", "currency": "USD"}}, expiry_time_in_minutes=60, ) payment_session_id = session["paymentSessionId"] os.environ["PAYMENT_SESSION_ID"] = payment_session_id print(f"Payment Session ID: {payment_session_id}") ``` ## Advanced Usage ### Dynamic Instrument/Session Selection Dynamic Instrument/Session selection is useful when the payment instrument and the payment session aren’t known upfront and need to be resolved dynamically during execution. You can initialize the plugin without a payment instrument or payment session, then set them later based on runtime logic or agent interrupts: ```python config = AgentCorePaymentsPluginConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-east-1:123456789012:payment-manager/pm-abc123", user_id="user-123", region="us-east-1", # payment_instrument_id and payment_session_id omitted ) plugin = AgentCorePaymentsPlugin(config=config) agent = Agent( system_prompt="You are a helpful assistant.", tools=[http_request], plugins=[plugin], ) # Later, update configuration dynamically config.update_payment_instrument_id("payment-instrument-xyz789") config.update_payment_session_id("payment-session-def456") ``` When the plugin encounters a 402 response without these values configured, it raises a `PaymentInstrumentConfigurationRequired` or `PaymentSessionConfigurationRequired` interrupt that your application can handle. ### Handling Payment Interrupts When payment processing fails, the plugin stores the failure and raises an interrupt. Your application should handle these interrupts: ```python result = agent("Access the premium endpoint at https://api.example.com/premium") while result.stop_reason == "interrupt": responses = [] for interrupt in result.interrupts: reason = interrupt.reason match reason.get("exceptionType"): case "PaymentInstrumentConfigurationRequired": # Resolve the missing instrument (e.g., prompt user or look up from your DB) plugin.config.update_payment_instrument_id("payment-instrument-new123") msg = "Payment instrument configured. Please retry." case "PaymentSessionConfigurationRequired": # Resolve the missing session (e.g., create a new session) plugin.config.update_payment_session_id("payment-session-new456") msg = "Payment session configured. Please retry." case _: msg = f"Payment failed: {reason.get('exceptionMessage')}" responses.append({"interruptResponse": {"interruptId": interrupt.id, "response": msg}}) result = agent(responses) ``` ### Disabling Auto-Payment To access only payment visibility tools without automatic payment execution (keeping a human or custom logic in the loop): ```python config = AgentCorePaymentsPluginConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-east-1:123456789012:payment-manager/pm-abc123", user_id="user-123", region="us-east-1", auto_payment=False, # Disable automatic 402 processing ) ``` ### Network Preferences You can specify preferred blockchain networks for payment processing: ```python config = AgentCorePaymentsPluginConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-east-1:123456789012:payment-manager/pm-abc123", user_id="user-123", payment_instrument_id="payment-instrument-xyz789", payment_session_id="payment-session-def456", region="us-east-1", network_preferences_config=["eip155:8453", "base-sepolia", "solana-mainnet"], ) ``` If not specified, the system uses a default preference order prioritizing Solana mainnet and Base (Ethereum L2) for low transaction fees. ## Configuration The plugin is configured via `AgentCorePaymentsPluginConfig`. Key options include auto-payment toggling, network preferences, bearer token / token provider auth, and tool allowlisting. See the [AgentCore SDK documentation](https://github.com/aws/bedrock-agentcore-sdk-python/tree/main/src/bedrock_agentcore/payments) for the full parameter reference. ## Authentication The plugin supports two authentication methods: - **AWS SigV4** (default) — uses standard AWS credentials; requires `user_id` - **CUSTOM\_JWT (Bearer Token)** — uses a static `bearer_token` or a `token_provider` callable for automatic token refresh; `user_id` is derived from the JWT `sub` claim See the [AgentCore SDK documentation](https://github.com/aws/bedrock-agentcore-sdk-python) for detailed setup instructions for each authentication method. ## Important Notes - Payment sessions have configurable spending limits and expiry times (15–480 minutes). Monitor budgets using the `get_payment_session` tool to avoid `InsufficientBudget` errors. - The plugin enforces a maximum of 3 payment retry attempts per tool use and 5 interrupt retries. After these limits, payment processing is skipped. - To make custom tools compatible with automatic payment processing, return responses using the spec-compliant `PAYMENT_REQUIRED:` marker format. See the [AgentCore payments SDK documentation](https://github.com/aws/bedrock-agentcore-sdk-python/tree/main/src/bedrock_agentcore/payments) for details. ## How it works ### x402 Payment Flow ```plaintext ┌─────────┐ ┌──────────┐ ┌──────────────┐ ┌────────────────┐ │ Agent │────▶│ Tool │────▶│ Paid API │────▶│ 402 Response │ │ │ └──────────┘ └──────────────┘ └────────────────┘ │ │ │ │ │ ┌──────────┐ ┌──────────────┐ │ │ │◀────│ Tool │◀────│ Plugin │◀────────────┘ │ (result)│ │ (retry) │ │ processes │ └─────────┘ └──────────┘ │ payment │ └──────────────┘ ``` 1. Agent calls a tool (e.g., `http_request`) that hits a paid API 2. The API returns HTTP 402 with x402 payment requirements 3. The plugin’s `after_tool_call` hook intercepts the 402 response 4. The plugin extracts payment requirements using the appropriate handler 5. The plugin calls `PaymentManager.generate_payment_header()` to process the payment 6. The payment header is applied to the tool input 7. The tool is automatically retried with the payment credentials 8. The API returns a successful response ## References - [AgentCore SDK](https://github.com/aws/bedrock-agentcore-sdk-python) - [Strands Plugins documentation](/docs/user-guide/sdk/plugins/index.md) Source: https://strandsagents.com/docs/integrations/plugins/agentcore-payments/index.md --- ## Amazon AgentCore Tool Search The [AgentCore Tool Search plugin](https://github.com/aws/bedrock-agentcore-sdk-python/tree/main/src/bedrock_agentcore/gateway/integrations/strands/plugins/agentcore_tool_search) enables semantic tool discovery for Strands Agents using [Amazon Bedrock AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-using-mcp-semantic-search.html). It allows agents to dynamically load only the relevant tools for each invocation by deriving user intent from conversation history, even when hundreds of tools are registered on the gateway. The plugin derives user intent from conversation history and queries AgentCore Gateway’s semantic search to load only the relevant tools for each invocation. Intent derivation is pluggable — the built-in provider reuses the parent agent’s model by default, or you can supply your own `IntentProvider` implementation for full control over how intent is classified. ## Installation ```bash pip install 'bedrock-agentcore[strands-agents]' ``` ## Usage ```python from mcp_proxy_for_aws.client import aws_iam_streamablehttp_client from strands import Agent from strands.tools.mcp import MCPClient from bedrock_agentcore.gateway.integrations.strands.plugins import AgentCoreToolSearchPlugin mcp_client = MCPClient(lambda: aws_iam_streamablehttp_client( endpoint="https://.gateway.bedrock-agentcore..amazonaws.com/mcp", aws_region="us-east-1", aws_service="bedrock-agentcore", )) with mcp_client: agent = Agent(plugins=[AgentCoreToolSearchPlugin(mcp_client=mcp_client)]) agent("Find me afternoon flights to New York") ``` ## How It Works On each agent invocation: 1. **User query** — the user sends a query to the Strands agent 2. **Hook** — the agent triggers the `AgentCoreToolSearchPlugin` before model invocation 3. **Derive intent** — the `IntentProvider` sends the last N messages from conversation history to the configured LLM to produce a concise intent string 4. **Search gateway** — the intent is passed to AgentCore Gateway’s `x_amz_bedrock_agentcore_search` tool to obtain the most relevant tools 5. **Invoke LLM** — the agent invokes the LLM with the user query along with the matched tools from registered MCP targets (Lambda, API Gateway, MCP Server) Previously loaded tools are cleared before each search, so the agent always has the most relevant tools available. ## Intent Provider An `IntentProvider` is responsible for analyzing conversation messages and producing a concise intent string that drives tool search. The plugin calls `derive_intent(messages, model)` before each invocation to determine what tools to load. ### StrandsIntentProvider `StrandsIntentProvider` uses a Strands Agent to classify the last few conversation messages into a concise intent string. By default it uses the parent agent’s model. **Basic usage (uses the agent’s model automatically):** ```python from bedrock_agentcore.gateway.integrations.strands.plugins import AgentCoreToolSearchPlugin agent = Agent(plugins=[ AgentCoreToolSearchPlugin(mcp_client=mcp_client) ]) ``` **With a custom model for intent classification:** ```python from strands.models.bedrock import BedrockModel from bedrock_agentcore.gateway.integrations.strands.plugins import AgentCoreToolSearchPlugin from bedrock_agentcore.gateway.integrations.strands.plugins.agentcore_tool_search.intent_providers import StrandsIntentProvider intent_model = BedrockModel(model_id="us.anthropic.claude-haiku-4-5-20251001-v1:0") agent = Agent(plugins=[ AgentCoreToolSearchPlugin( mcp_client=mcp_client, intent_provider=StrandsIntentProvider(model=intent_model), ) ]) ``` **With a custom system prompt:** ```python from bedrock_agentcore.gateway.integrations.strands.plugins import AgentCoreToolSearchPlugin from bedrock_agentcore.gateway.integrations.strands.plugins.agentcore_tool_search.intent_providers import StrandsIntentProvider agent = Agent(plugins=[ AgentCoreToolSearchPlugin( mcp_client=mcp_client, intent_provider=StrandsIntentProvider( system_prompt="Classify the user's intent in one sentence. Focus on the action, not details." ), ) ]) ``` ### Custom Intent Provider You can provide your own intent derivation strategy by subclassing `IntentProvider`: ```python from bedrock_agentcore.gateway.integrations.strands.plugins.agentcore_tool_search.intent_providers import IntentProvider class MyIntentProvider(IntentProvider): def derive_intent(self, messages: list[dict], model=None) -> str: # custom logic to derive intent return "intent string" agent = Agent(plugins=[ AgentCoreToolSearchPlugin( mcp_client=mcp_client, intent_provider=MyIntentProvider(), ) ]) ``` ## Prerequisites - An AgentCore Gateway with [semantic search](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-using-mcp-semantic-search.html) enabled - Tools registered on the gateway with descriptions - AWS credentials with access to the gateway For more details, see the [AgentCore Gateway documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-building.html). ## References - [AgentCore SDK](https://github.com/aws/bedrock-agentcore-sdk-python) - [AgentCore Gateway documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-building.html) Source: https://strandsagents.com/docs/integrations/plugins/agentcore-tool-search/index.md --- ## Datadog AI Guard [Datadog AI Guard](https://docs.datadoghq.com/security/ai_guard/) is a defense-in-depth security solution that inspects, blocks, and governs AI behavior in real time. This integration connects AI Guard with Strands agents through the [Plugins](/docs/user-guide/sdk/plugins/index.md) system, providing inline security protection for your agent workflows. With this integration, AI Guard automatically evaluates user prompts, model responses, tool calls, and tool results against configurable security policies — detecting and blocking threats like prompt injection, jailbreaking, data exfiltration, and destructive tool calls. ## Installation Install the `ddtrace` package: ```bash pip install ddtrace ``` Set the required environment variables: ```bash export DD_AI_GUARD_ENABLED=true export DD_API_KEY= export DD_APP_KEY= ``` Ensure the Datadog Agent is running and reachable by the SDK. See the [AI Guard onboarding guide](https://docs.datadoghq.com/security/ai_guard/onboarding/?tab=python) for detailed setup instructions, including creating a retention filter and configuring security policies. ## Requirements - Python >= 3.9 - `strands-agents` >= 1.29.0 - `ddtrace` >= 4.7.0rc1 - A [Datadog](https://www.datadoghq.com/) account with AI Guard enabled - Datadog API key and Application key (with `ai_guard_evaluate` scope) Note AI Guard is currently in **Preview**. Contact Datadog support to enable the feature flag for your organization. ## Usage Import the `AIGuardStrandsPlugin` and pass it to your Strands agent: agent.py ```python from strands import Agent from ddtrace.appsec.ai_guard import AIGuardStrandsPlugin agent = Agent( plugins=[AIGuardStrandsPlugin()], ) response = agent("What is the weather today?") ``` AI Guard automatically evaluates all prompts, responses, and tool interactions against your configured security policies. No additional instrumentation code is needed. ## How it works The integration is provided by [`ddtrace`](https://github.com/DataDog/dd-trace-py) through the `AIGuardStrandsPlugin` class. It registers callbacks for four agent lifecycle events: | Hook event | What it scans | On block | | --- | --- | --- | | `BeforeModelCallEvent` | User prompts (excludes tool results) | Raises `AIGuardAbortError` | | `AfterModelCallEvent` | Assistant text content | Raises `AIGuardAbortError` | | `BeforeToolCallEvent` | Pending tool call and conversation context | Cancels the tool with a descriptive message | | `AfterToolCallEvent` | Tool result and conversation context | Replaces the tool result content | Each callback calls the AI Guard API to evaluate the agent’s messages against your configured security policies. If a threat is detected, the hook blocks or sanitizes the content before it reaches the model or the user. Tool results processed by `AfterToolCallEvent` are excluded from the next `BeforeModelCallEvent` scan to prevent double-evaluation. ## Configuration options The `AIGuardStrandsPlugin` constructor accepts the following parameters: | Parameter | Default | Description | | --- | --- | --- | | `detailed_error` | `False` | When `True`, appends the AI Guard reason to blocked messages (e.g., `"... canceled for security reasons: prompt_injection"`) | | `raise_error_on_tool_calls` | `False` | When `True`, raises `AIGuardAbortError` on tool call violations instead of replacing the tool result content | ```python plugin = AIGuardStrandsPlugin( detailed_error=True, raise_error_on_tool_calls=True, ) agent = Agent(plugins=[plugin]) ``` ### Environment variables | Variable | Description | | --- | --- | | `DD_AI_GUARD_ENABLED` | Set to `true` to enable AI Guard | | `DD_API_KEY` | Your Datadog API key | | `DD_APP_KEY` | Your Datadog Application key (requires `ai_guard_evaluate` scope) | ## Observability and security signals When AI Guard is active, every LLM interaction is evaluated and traced. In Datadog you can: - View AI Guard traces in **APM** with the resource name `ai_guard` - Monitor blocked interactions using `@ai_guard.action: (DENY OR ABORT)` - Filter by attack categories such as `jailbreak`, `prompt_injection`, `data_exfiltration`, and `destructive_tool_call` - Set up alerts on the `datadog.ai_guard.evaluations` metric See the [AI Guard documentation](https://docs.datadoghq.com/security/ai_guard/) for the full list of detected attack categories and monitoring capabilities. ## Error handling If the AI Guard service is unreachable or returns a non-abort error, the agent continues operating normally. Only `AIGuardAbortError` exceptions propagate to the caller — network errors and other failures are logged at debug level and do not block agent execution. ## References - [Datadog AI Guard documentation](https://docs.datadoghq.com/security/ai_guard/) - [AI Guard onboarding guide](https://docs.datadoghq.com/security/ai_guard/onboarding/?tab=python) - [ddtrace-py repository](https://github.com/DataDog/dd-trace-py) - [Strands Plugins documentation](/docs/user-guide/sdk/plugins/index.md) Source: https://strandsagents.com/docs/integrations/plugins/datadog-ai-guard/index.md --- ## S3 Vectors Memory Plugin The [S3 Vectors Memory Plugin](https://github.com/aws-samples/data-for-saas-patterns/tree/main/samples/multi-tenant-strands-s3-vectors-memory) gives any Strands Agent long-term semantic memory backed by [Amazon S3 Vectors](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors.html). At the end of a conversation, the plugin summarizes the exchange using the agent’s own model and stores the summary as a searchable vector. On subsequent conversations, relevant summaries are retrieved and injected into the system prompt — the agent remembers without bloating the context window. Available in two modes: - **Single-tenant** — one shared index, ambient AWS credentials - **Multi-tenant** — one index per tenant, IAM credentials scoped per tenant via the [Token Vending Machine (TVM)](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-saas-tenant-isolation-for-amazon-s3-by-using-an-aws-lambda-token-vending-machine.html) pattern ## Requirements - Python 3.10+ - `strands-agents >= 1.0.0` - `boto3 >= 1.34.0` - `cachetools >= 5.3.0` - AWS account with [Amazon S3 Vectors](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors.html) access - Amazon Bedrock access for: - An embedding model — `amazon.nova-2-multimodal-embeddings-v1:0` (default) - A chat model — e.g. `us.anthropic.claude-sonnet-4-5-20250929-v1:0` ## Installation ```bash pip install strands-s3-vectors-memory ``` ## AWS Setup **1\. Create an S3 Vectors bucket:** ```bash aws s3vectors create-vector-bucket --vector-bucket-name my-vector-memory ``` **2\. Create the index:** ```bash aws s3vectors create-index \ --vector-bucket-name my-vector-memory \ --index-name memory \ --data-type float32 --dimension 1024 --distance-metric cosine \ --metadata-configuration '{"nonFilterableMetadataKeys":["content","stored_at","conversation_id","type"]}' ``` **3\. For multi-tenant, create the TVM IAM role** using the [setup script](https://github.com/aws-samples/data-for-saas-patterns/blob/main/samples/multi-tenant-strands-s3-vectors-memory/scripts/setup_tvm_role.sh) provided in the repository: ```bash bash setup_tvm_role.sh my-vector-memory export S3_VECTOR_TVM_ROLE_ARN= ``` ## Usage ### Single-tenant ```python import os from strands import Agent from strands.models import BedrockModel from strands_s3_vectors_memory import S3VectorMemory, S3VectorMemoryPlugin BASE_PROMPT = """You are a helpful assistant. {memory_context} Use prior context naturally in your responses.""" store = S3VectorMemory(bucket_name=os.environ["S3_VECTOR_BUCKET_NAME"]) plugin = S3VectorMemoryPlugin(store=store, base_prompt=BASE_PROMPT) agent = Agent( model = BedrockModel(), name = "assistant", # required — used as memory namespace key plugins = [plugin], system_prompt = BASE_PROMPT, ) # Turn 1 — agent responds; memory not yet stored agent("My favourite framework is Strands Agents.", invocation_state={ "user_id": "user-001", "conversation_id": "conv-001", "end_session": False, }) # Turn 2 — end_session=True triggers background summarization and vector store agent("Thanks, bye.", invocation_state={ "user_id": "user-001", "conversation_id": "conv-001", "end_session": True, }) # Next session — plugin retrieves the stored summary and injects it into the prompt agent("What do you know about my preferences?", invocation_state={ "user_id": "user-001", "conversation_id": "conv-002", "end_session": False, }) ``` `BASE_PROMPT` must contain a `{memory_context}` placeholder. The plugin fills it with retrieved summaries on the first turn of each conversation, or replaces it with an empty string when no relevant memories are found. ### Multi-tenant ```python import os from strands import Agent from strands.models import BedrockModel from strands_s3_vectors_memory import MultiTenantS3VectorMemory, S3VectorMemoryPlugin store = MultiTenantS3VectorMemory( bucket_name = os.environ["S3_VECTOR_BUCKET_NAME"], tvm_role_arn = os.environ["S3_VECTOR_TVM_ROLE_ARN"], ) plugin = S3VectorMemoryPlugin(store=store, base_prompt=BASE_PROMPT) agent = Agent( model = BedrockModel(), name = "assistant", plugins = [plugin], system_prompt = BASE_PROMPT, ) agent("Our Q4 budget is $2M.", invocation_state={ "tenant_context": {"tenantId": "tenant-001"}, "user_id": "user-456", "conversation_id": "conv-001", "end_session": True, }) ``` ## Configuration ### Environment variables | Variable | Required | Description | | --- | --- | --- | | `S3_VECTOR_BUCKET_NAME` | Yes | S3 Vectors bucket name | | `AWS_REGION` | No (default: `us-east-1`) | AWS region | | `S3_VECTOR_TVM_ROLE_ARN` | Multi-tenant only | TVM IAM role ARN | ### `invocation_state` keys | Key | Required | Description | | --- | --- | --- | | `user_id` | Yes | Scopes vector filter to this user | | `conversation_id` | Yes | Scopes buffer and summary key | | `end_session` | No (default `False`) | If `True`, summarizes and stores the conversation after the response (non-blocking) | | `tenant_context` | Multi-tenant only | Dict with `tenantId` key | ## References - [GitHub](https://github.com/aws-samples/data-for-saas-patterns/tree/main/samples/multi-tenant-strands-s3-vectors-memory) - [PyPI](https://pypi.org/project/strands-s3-vectors-memory/) - [Plugin reference](https://github.com/aws-samples/data-for-saas-patterns/blob/main/samples/multi-tenant-strands-s3-vectors-memory/docs/strands-s3-vector-memory-plugin.md) - [Amazon S3 Vectors](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors.html) - [Token Vending Machine pattern](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-saas-tenant-isolation-for-amazon-s3-by-using-an-aws-lambda-token-vending-machine.html) Source: https://strandsagents.com/docs/integrations/plugins/s3-vectors-memory/index.md --- ## AgentCore Memory Session Manager The [AgentCore Memory Session Manager](https://github.com/aws/bedrock-agentcore-sdk-python/tree/main/src/bedrock_agentcore/memory/integrations/strands) leverages Amazon Bedrock AgentCore Memory to provide advanced memory capabilities with intelligent retrieval for Strands Agents. It supports both short-term memory (STM) for conversation persistence and long-term memory (LTM) with multiple strategies for learning user preferences, facts, and session summaries. ## Installation ```bash pip install 'bedrock-agentcore[strands-agents]' ``` ## Usage ### Basic Setup (STM) Short-term memory provides basic conversation persistence within a session. This is the simplest way to get started with AgentCore Memory. #### Creating the Memory Resource One-time Setup The memory resource creation shown below is typically done once, separately from your agent application. In production, you would create the memory resource through the AWS Console or a separate setup script, then use the memory ID in your agent application. ```python import os from bedrock_agentcore.memory import MemoryClient # This is typically done once, separately from your agent application client = MemoryClient(region_name="us-east-1") basic_memory = client.create_memory( name="BasicTestMemory", description="Basic memory for testing short-term functionality" ) # Export the memory ID as an environment variable for reuse memory_id = basic_memory.get('id') print(f"Created memory with ID: {memory_id}") os.environ['AGENTCORE_MEMORY_ID'] = memory_id ``` ### Using the Session Manager with Existing Memory ```python import uuid import boto3 from datetime import datetime from strands import Agent from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager MEM_ID = os.environ.get("AGENTCORE_MEMORY_ID", "your-existing-memory-id") ACTOR_ID = "test_actor_id_%s" % datetime.now().strftime("%Y%m%d%H%M%S") SESSION_ID = "test_session_id_%s" % datetime.now().strftime("%Y%m%d%H%M%S") agentcore_memory_config = AgentCoreMemoryConfig( memory_id=MEM_ID, session_id=SESSION_ID, actor_id=ACTOR_ID ) # Use context manager to ensure messages are flushed on exit with AgentCoreMemorySessionManager( agentcore_memory_config=agentcore_memory_config, region_name="us-east-1" ) as session_manager: # Create agent with session manager agent = Agent( system_prompt="You are a helpful assistant. Use all you know about the user to provide helpful responses.", session_manager=session_manager, ) # Use the agent - conversations are automatically persisted agent("I like sushi with tuna") agent("What should I buy for lunch today?") ``` ## Long-Term Memory (LTM) Long-term memory provides advanced capabilities with multiple strategies for learning and storing user preferences, facts, and session summaries across conversations. ### Creating LTM Memory with Strategies One-time Setup Similar to STM, the LTM memory resource creation is typically done once, separately from your agent application. In production, you would create the memory resource with strategies through the AWS Console or a separate setup script. Bedrock AgentCore Memory supports three built-in memory strategies: 1. **`summaryMemoryStrategy`**: Summarizes conversation sessions 2. **`userPreferenceMemoryStrategy`**: Learns and stores user preferences 3. **`semanticMemoryStrategy`**: Extracts and stores factual information ```python import os from bedrock_agentcore.memory import MemoryClient # This is typically done once, separately from your agent application client = MemoryClient(region_name="us-east-1") comprehensive_memory = client.create_memory_and_wait( name="ComprehensiveAgentMemory", description="Full-featured memory with all built-in strategies", strategies=[ { "summaryMemoryStrategy": { "name": "SessionSummarizer", "namespaces": ["/summaries/{actorId}/{sessionId}/"] } }, { "userPreferenceMemoryStrategy": { "name": "PreferenceLearner", "namespaces": ["/preferences/{actorId}/"] } }, { "semanticMemoryStrategy": { "name": "FactExtractor", "namespaces": ["/facts/{actorId}/"] } } ] ) # Export the LTM memory ID as an environment variable for reuse ltm_memory_id = comprehensive_memory.get('id') print(f"Created LTM memory with ID: {ltm_memory_id}") os.environ['AGENTCORE_LTM_MEMORY_ID'] = ltm_memory_id ``` ### Configuring Retrieval You can configure how the agent retrieves information from different memory namespaces: #### Single Namespace Retrieval ```python from datetime import datetime from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig, RetrievalConfig from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager from strands import Agent MEM_ID = os.environ.get("AGENTCORE_LTM_MEMORY_ID", "your-existing-ltm-memory-id") ACTOR_ID = "test_actor_id_%s" % datetime.now().strftime("%Y%m%d%H%M%S") SESSION_ID = "test_session_id_%s" % datetime.now().strftime("%Y%m%d%H%M%S") config = AgentCoreMemoryConfig( memory_id=MEM_ID, session_id=SESSION_ID, actor_id=ACTOR_ID, retrieval_config={ "/preferences/{actorId}/": RetrievalConfig( top_k=5, relevance_score=0.7 ) } ) session_manager = AgentCoreMemorySessionManager(config, region_name='us-east-1') ltm_agent = Agent(session_manager=session_manager) ``` #### Multiple Namespace Retrieval ```python config = AgentCoreMemoryConfig( memory_id=MEM_ID, session_id=SESSION_ID, actor_id=ACTOR_ID, retrieval_config={ "/preferences/{actorId}/": RetrievalConfig( top_k=5, relevance_score=0.7 ), "/facts/{actorId}/": RetrievalConfig( top_k=10, relevance_score=0.3 ), "/summaries/{actorId}/{sessionId}/": RetrievalConfig( top_k=5, relevance_score=0.5 ) } ) session_manager = AgentCoreMemorySessionManager(config, region_name='us-east-1') agent_with_multiple_namespaces = Agent(session_manager=session_manager) ``` ## Configuration Options ### Memory Strategies AgentCore Memory supports three built-in strategies: 1. **`summaryMemoryStrategy`**: Automatically summarizes conversation sessions for efficient context retrieval 2. **`userPreferenceMemoryStrategy`**: Learns and stores user preferences across sessions 3. **`semanticMemoryStrategy`**: Extracts and stores factual information from conversations ### AgentCoreMemoryConfig Parameters The `AgentCoreMemoryConfig` class accepts the following parameters: | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `memory_id` | `str` | Yes | ID of the Bedrock AgentCore Memory resource | | `session_id` | `str` | Yes | Unique identifier for the conversation session | | `actor_id` | `str` | Yes | Unique identifier for the user/actor | | `retrieval_config` | `Dict[str, RetrievalConfig]` | No | Dictionary mapping namespaces to retrieval configurations | | `batch_size` | `int` | No (default: 1) | Number of messages to buffer before sending (1-100). Set to 1 for immediate sending. | ### RetrievalConfig Parameters Configure retrieval behavior for each namespace: | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `top_k` | `int` | 10 | Number of top-scoring records to return from semantic search (1-1000) | | `relevance_score` | `float` | 0.2 | Minimum relevance threshold for filtering results (0.0-1.0) | | `strategy_id` | `Optional[str]` | None | Optional parameter to filter memory strategies | ### Namespace Patterns Namespaces use a hierarchical format separated by forward slashes and **must both start and end with a `/`**. Each path segment scopes memory to a level of granularity (strategy, actor, session). The same namespace string you set on a strategy at creation time is what you reference later in `retrieval_config`. Common patterns with variable substitution: - `/preferences/{actorId}/`: User-specific preferences across sessions - `/facts/{actorId}/`: User-specific facts across sessions - `/summaries/{actorId}/{sessionId}/`: Session-specific summaries The `{actorId}` and `{sessionId}` placeholders are automatically replaced at runtime with the values from your `AgentCoreMemoryConfig`. AgentCore also supports `{memoryStrategyId}` for strategy-scoped namespaces. See [Specify long-term memory organization with namespaces](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/specify-long-term-memory-organization.html) for the full format reference. ## Message Batching By default, each message is sent to AgentCore Memory immediately (`batch_size=1`). When you set `batch_size` to a value greater than 1, messages are buffered locally and sent in a single API call once the buffer reaches the configured size. This reduces the number of API calls and can improve throughput for high-volume conversations. Flush buffered messages before exiting When using `batch_size > 1`, messages remain in a local buffer until the batch is full. You **must** use a `with` block (recommended) or call `close()` explicitly to flush any remaining messages at the end of your session. Otherwise, buffered messages will be lost. ### Context Manager (Recommended) The context manager pattern automatically flushes pending messages when the block exits, even if an exception occurs: ```python from strands import Agent from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager config = AgentCoreMemoryConfig( memory_id="your-memory-id", session_id="your-session-id", actor_id="your-actor-id", batch_size=10, # Buffer 10 messages before sending ) with AgentCoreMemorySessionManager(config, region_name="us-east-1") as session_manager: agent = Agent( system_prompt="You are a helpful assistant.", session_manager=session_manager, ) agent("Hello!") agent("Tell me about Python.") # All buffered messages are automatically flushed here ``` ### Explicit close() If you cannot use a context manager, call `close()` in a `finally` block to ensure messages are flushed: ```python session_manager = AgentCoreMemorySessionManager(config, region_name="us-east-1") try: agent = Agent( system_prompt="You are a helpful assistant.", session_manager=session_manager, ) agent("Hello!") agent("Tell me about Python.") finally: session_manager.close() # Flush any remaining buffered messages ``` ### Checking Buffer Status Use `pending_message_count()` to check how many messages are waiting in the buffer: ```python count = session_manager.pending_message_count() print(f"{count} messages pending in buffer") ``` ## Important Notes Session Limitations Currently, only **one** agent per session is supported when using AgentCoreMemorySessionManager. Creating multiple agents with the same session will show a warning. Flush Buffered Messages When using `batch_size > 1`, always use a `with` block or call `close()` when your session is complete. Any messages remaining in the buffer that are not flushed will be lost. ## Resources - **GitHub**: [bedrock-agentcore-sdk-python](https://github.com/aws/bedrock-agentcore-sdk-python/) - **Documentation**: [Strands Integration Examples](https://github.com/aws/bedrock-agentcore-sdk-python/tree/main/src/bedrock_agentcore/memory/integrations/strands) - **Issues**: Report bugs and feature requests in the [bedrock-agentcore-sdk-python repository](https://github.com/aws/bedrock-agentcore-sdk-python/issues/new/choose) Source: https://strandsagents.com/docs/integrations/session-managers/agentcore-memory/index.md --- ## Strands Valkey Session Manager The [Strands Valkey Session Manager](https://github.com/jeromevdl/strands-valkey-session-manager) is a high-performance session manager for Strands Agents that uses Valkey/Redis for persistent storage. Valkey is a very-low latency cache that enables agents to maintain conversation history and state across multiple interactions, even in distributed environments. Tested with Amazon ElastiCache Serverless (Redis 7.1, Valkey 8.1), ElastiCache (Redis 7.1, Valkey 8.2), and Upstash. ## Installation ```bash pip install strands-valkey-session-manager ``` ## Usage ### Basic Setup ```python from strands import Agent from strands_valkey_session_manager import ValkeySessionManager from uuid import uuid4 import valkey # Create a Valkey client client = valkey.Valkey(host="localhost", port=6379, decode_responses=True) # Create a session manager with a unique session ID session_id = str(uuid4()) session_manager = ValkeySessionManager( session_id=session_id, client=client ) # Create an agent with the session manager agent = Agent(session_manager=session_manager) # Use the agent - all messages are automatically persisted agent("Hello! Tell me about Valkey.") # The conversation is now stored in Valkey and can be resumed later using the same session_id # Display conversation history messages = session_manager.list_messages(session_id, agent.agent_id) for msg in messages: role = msg.message["role"] content = msg.message["content"][0]["text"] print(f"** {role.upper()}**: {content}") ``` ## Key Features - **Persistent Sessions**: Store agent conversations and state in Valkey/Redis - **Distributed Ready**: Share sessions across multiple application instances - **High Performance**: Leverage Valkey’s speed for fast session operations - **JSON Storage**: Native JSON support for complex data structures - **Automatic Cleanup**: Built-in session management and cleanup capabilities ## Configuration ### ValkeySessionManager Parameters - `session_id`: Unique identifier for the session - `client`: Configured Valkey client instance (only synchronous versions are supported) ### Storage Structure The ValkeySessionManager stores data using the following key structure: ```plaintext session: # Session metadata session::agent: # Agent state and metadata session::agent::message: # Individual messages ``` ## Available Methods The following methods are used transparently by Strands: - `create_session(session)`: Create a new session - `read_session(session_id)`: Retrieve session data - `delete_session(session_id)`: Remove session and all associated data - `create_agent(session_id, agent)`: Store agent in session - `read_agent(session_id, agent_id)`: Retrieve agent data - `update_agent(session_id, agent)`: Update agent state - `create_message(session_id, agent_id, message)`: Store message - `read_message(session_id, agent_id, message_id)`: Retrieve message - `update_message(session_id, agent_id, message)`: Update message - `list_messages(session_id, agent_id, limit=None)`: List all messages ## Requirements - Python 3.10+ - Valkey/Redis server - strands-agents >= 1.0.0 - valkey >= 6.0.0 ## References - **PyPI**: [strands-valkey-session-manager](https://pypi.org/project/strands-valkey-session-manager/) - **GitHub**: [jeromevdl/strands-valkey-session-manager](https://github.com/jeromevdl/strands-valkey-session-manager) - **Issues**: Report bugs and feature requests in the [GitHub repository](https://github.com/jeromevdl/strands-valkey-session-manager/issues) Source: https://strandsagents.com/docs/integrations/session-managers/strands-valkey-session-manager/index.md --- ## GitHub Storage [strands-github-storage](https://github.com/maisieyanz/strands-github-storage) is a `Storage` backend that persists each entry as a file in a GitHub repository, at the entry’s key path on a branch. Because the store *is* a git repository, its contents are browsable in the GitHub UI, diffable per change, and versioned in history. It implements the SDK’s four-method `Storage` interface (`write`, `read`, `delete`, `list`), so it plugs in anywhere a `Storage` is accepted — session managers, context offloading, and file-backed memory stores. Available for both the Python and TypeScript SDKs. ## Installation (( tab "Python" )) ```bash pip install strands-github-storage ``` `strands-agents` and `PyGithub` are installed as dependencies. (( /tab "Python" )) (( tab "TypeScript" )) ```bash npm install strands-github-storage ``` `@strands-agents/sdk` is a peer dependency; `@octokit/rest` is bundled. (( /tab "TypeScript" )) ## Usage ### Basic setup (( tab "Python" )) ```python import asyncio from strands_github_storage import GithubStorage storage = GithubStorage( owner="myorg", repo="agent-memory", branch="main", # optional, defaults to "main" token="ghp_...", # required for writes and private repos ) async def main() -> None: await storage.write("facts/note.md", b"remember this") data = await storage.read("facts/note.md") # bytes | None keys = await storage.list("facts/") # ["facts/note.md"] await storage.delete("facts/note.md") asyncio.run(main()) ``` (( /tab "Python" )) (( tab "TypeScript" )) ```typescript import { GithubStorage } from 'strands-github-storage' const storage = new GithubStorage({ owner: 'myorg', repo: 'agent-memory', branch: 'main', // optional, defaults to 'main' token: process.env.GITHUB_TOKEN, // required for writes and private repos }) await storage.write('facts/note.md', new TextEncoder().encode('remember this')) const bytes = await storage.read('facts/note.md') // Uint8Array | null const keys = await storage.list('facts/') // ['facts/note.md'] await storage.delete('facts/note.md') ``` (( /tab "TypeScript" )) ### Wiring into an agent Pass it wherever a `Storage` is accepted so the agent’s persisted data lives in a browsable, versioned repo: (( tab "Python" )) Use it as a session manager’s storage, so conversation sessions persist to a GitHub repo: ```python from strands import Agent from strands.session import SnapshotSessionManager from strands_github_storage import GithubStorage storage = GithubStorage(owner="myorg", repo="agent-sessions", token="ghp_...") agent = Agent(session_manager=SnapshotSessionManager("agent-sessions", storage=storage)) ``` (( /tab "Python" )) (( tab "TypeScript" )) Back a `FileMemoryStore` so an agent’s knowledge lives in a browsable, versioned repo: ```typescript import { Agent, MemoryManager } from '@strands-agents/sdk' import { FileMemoryStore } from '@strands-agents/sdk/vended-memory-stores/file-memory-store' import { GithubStorage } from 'strands-github-storage' const memoryStore = new FileMemoryStore({ name: 'agent-memory', storage: new GithubStorage({ owner: 'myorg', repo: 'agent-memory', token }), }) const agent = new Agent({ model, memoryManager: new MemoryManager({ stores: [memoryStore] }) }) ``` (( /tab "TypeScript" )) ## Configuration | Parameter | Required | Description | | --- | --- | --- | | `owner` | Yes | Repository owner (user or organization login). | | `repo` | Yes | Repository name. | | `branch` | No | Branch to read from and commit to. Defaults to `main`. | | `token` | For writes | GitHub token. Needed for any write and for reading private repos. | | `github``octokit` | No | A pre-configured GitHub client, as an alternative to `token` (e.g. to add retry/throttling behavior). | ## Behavior and limits - **One commit per operation.** Each `write` and `delete` is its own commit (`update ` / `delete `). A burst of writes produces a burst of commits. - **Single writer per branch.** Commits advance the branch ref without a compare-and-swap retry, so a concurrent writer that moves the branch head surfaces GitHub’s non-fast-forward rejection as a `StorageError` rather than being retried. - **`read` is limited to files under 1 MB** — the ceiling of the GitHub contents API’s inline response. Markdown memory is far below this. - **`list` fails loud on truncation.** GitHub’s git-tree API caps very large trees and does not paginate; rather than return a silent partial listing, `list` throws a `StorageError`. - **No built-in rate-limit handling.** To add exponential backoff on `429`/`5xx`, pass a pre-configured client via `github``octokit`. ## References - [GitHub](https://github.com/maisieyanz/strands-github-storage) - [npm](https://www.npmjs.com/package/strands-github-storage) - [PyPI](https://pypi.org/project/strands-github-storage/) - [Strands Storage docs](/docs/user-guide/sdk/storage/index.md) Source: https://strandsagents.com/docs/integrations/storage/github/index.md --- ## Community Storage Backends A **storage backend** persists raw bytes under `/`\-separated string keys. The SDK uses the `Storage` interface internally for session snapshots, context offloading, and any construct that needs durable key-value persistence. Any class that implements the four-method `Storage` protocol (`write`, `read`, `delete`, `list`) can plug in. The SDK ships reference backends: [`InMemoryStorage`](/docs/user-guide/sdk/storage/index.md#inmemorystorage), [`LocalFileStorage`](/docs/user-guide/sdk/storage/index.md#localfilestorage), and [`S3Storage`](/docs/user-guide/sdk/storage/index.md#s3storage). The packages below are **community-built** storage backends you can install and use wherever a `Storage` instance is accepted. Community maintained These packages are maintained by their authors, not the Strands team. Review packages before using them in production. Quality and support may vary. ## Browse the integrations page See the [Storage section of the integrations page](/integrations/?type=storage/index.md) for the current list, with language support and links to each package. ## Add your storage backend Built a `Storage` implementation? See the [Get Featured guide](/docs/integrations/get-featured/index.md) to list it here, and the [Extensions guide](/docs/contribute/contributing/extensions/index.md) for how to build and publish a package. Source: https://strandsagents.com/docs/integrations/storage/overview/index.md --- ## strands-apify [strands-apify](https://github.com/apify/strands-apify) gives your Strands agent web scraping, search, crawling, e-commerce, and social media capabilities through the [Apify platform](https://apify.com/) and its library of thousands of pre-built Actors. For the full tool reference and model provider setup, see the [Strands Agents on Apify docs](https://docs.apify.com/platform/integrations/strands-agents). ## Prerequisites - An [Apify account](https://apify.com/) (free tier available) - [Apify API token](https://console.apify.com/account/integrations) from Apify Console > Integrations ## Installation ```bash pip install strands-apify ``` ## Usage ```python from strands import Agent from strands_apify import APIFY_CORE_TOOLS agent = Agent(tools=APIFY_CORE_TOOLS) agent("Scrape https://docs.apify.com and summarize the page") ``` Pick individual tools for a more focused agent: ```python from strands import Agent from strands_apify import apify_google_search_scraper agent = Agent(tools=[apify_google_search_scraper]) agent("Find the top-rated Italian restaurants in Prague") ``` ## Key Features - **18 pre-built tools** for scraping, search, social media, and e-commerce - **Focused tool sets** (`APIFY_CORE_TOOLS`, `APIFY_SEARCH_TOOLS`, `APIFY_SOCIAL_TOOLS`) sized for reliable LLM tool selection; `APIFY_ALL_TOOLS` bundles everything but can overwhelm tool choice - **Apify Store access** to run any of thousands of Actors with a single generic tool - **Dataset integration** to fetch and process Actor results directly - **URL to markdown** conversion for any webpage ## Configuration ```bash APIFY_TOKEN=your_apify_api_token # Required STRANDS_APIFY_QUIET=1 # Optional: suppress rich panels in interactive shells ``` ## Resources - [PyPI package](https://pypi.org/project/strands-apify/) - [GitHub repository](https://github.com/apify/strands-apify) - [Full tool reference and examples](https://docs.apify.com/platform/integrations/strands-agents) - [Apify Store](https://apify.com/store) - [Apify API reference](https://docs.apify.com/api/v2) Source: https://strandsagents.com/docs/integrations/tools/strands-apify/index.md --- ## strands-deepgram [strands-deepgram](https://github.com/eraykeskinmac/strands-deepgram) is a production-ready speech and audio processing tool powered by [Deepgram’s AI platform](https://deepgram.com/) with 30+ language support. ## Installation ```bash pip install strands-deepgram ``` ## Usage ```python from strands import Agent from strands_deepgram import deepgram agent = Agent(tools=[deepgram]) # Transcribe with speaker identification agent("transcribe this audio: recording.mp3 with speaker diarization") # Text-to-speech agent("convert this text to speech: Hello world") # Audio intelligence agent("analyze sentiment in call.wav") ``` ## Key Features - **Speech-to-Text**: 30+ language support and speaker diarization - **Text-to-Speech**: Natural-sounding voices (Aura series) - **Audio Intelligence**: Sentiment analysis, topic detection, and intent recognition - **Speaker Diarization**: Identify and separate different speakers - **Multi-format Support**: WAV, MP3, M4A, FLAC, and more - **Real-time Processing**: Streaming capabilities for live audio ## Configuration ```bash DEEPGRAM_API_KEY=your_deepgram_api_key # Required DEEPGRAM_DEFAULT_MODEL=nova-3 # Optional DEEPGRAM_DEFAULT_LANGUAGE=en # Optional ``` Get your API key at: [console.deepgram.com](https://console.deepgram.com/) ## Resources - [PyPI Package](https://pypi.org/project/strands-deepgram/) - [GitHub Repository](https://github.com/eraykeskinmac/strands-deepgram) - [Examples & Demos](https://github.com/eraykeskinmac/strands-tools-examples) - [Deepgram API](https://console.deepgram.com/) Source: https://strandsagents.com/docs/integrations/tools/strands-deepgram/index.md --- ## strands-google [strands-google](https://github.com/cagataycali/strands-google) is a universal Google API integration tool that provides access to 200+ Google APIs (Gmail, Drive, Calendar, YouTube, Sheets, Docs, and more) directly from your Strands agent. ## Installation ```bash pip install strands-google ``` ## Usage ```python from strands import Agent from strands_google import use_google, gmail_send, gmail_reply agent = Agent(tools=[use_google, gmail_send, gmail_reply]) # Send an email agent("Send an email to friend@example.com saying hello") # Search Gmail agent("Find all unread emails from last week") # List Google Drive files agent("Show me my recent Drive files") # List calendar events agent("What meetings do I have today?") ``` ## Key Features - **Universal Google API Access**: Gmail, Drive, Calendar, YouTube, Sheets, Docs, and 200+ more via the Discovery API - **Flexible Authentication**: OAuth 2.0, Service Accounts, and API Keys - **Gmail Helpers**: Easy email sending and replying with automatic encoding - **Dynamic Scopes**: Configure OAuth scopes on-the-fly - **Safety Prompts**: Mutative operations require confirmation by default ## Configuration ```bash GOOGLE_OAUTH_CREDENTIALS=~/gmail_token.json # OAuth token path GOOGLE_APPLICATION_CREDENTIALS=~/service-key.json # Service account path GOOGLE_API_KEY=your_api_key # API key for public APIs GOOGLE_API_SCOPES=gmail.readonly,drive.file # Default OAuth scopes ``` Run the authentication helper to set up OAuth: ```bash python -m strands_google.google_auth ``` ## Resources - [PyPI Package](https://pypi.org/project/strands-google/) - [GitHub Repository](https://github.com/cagataycali/strands-google) - [Google Cloud Console](https://console.cloud.google.com/) - [Google API Client Library](https://github.com/googleapis/google-api-python-client) Source: https://strandsagents.com/docs/integrations/tools/strands-google/index.md --- ## strands-hubspot [strands-hubspot](https://github.com/eraykeskinmac/strands-hubspot) is a production-ready HubSpot CRM tool designed for **READ-ONLY** operations with zero risk of data modification. It enables agents to safely access and analyze CRM data without any possibility of corrupting customer information. This community tool provides comprehensive HubSpot integration for AI agents, offering safe CRM data access for sales intelligence, customer research, and data analytics workflows. ## Installation ```bash pip install strands-hubspot ``` ## Usage ```python from strands import Agent from strands_hubspot import hubspot # Create an agent with HubSpot READ-ONLY tool agent = Agent(tools=[hubspot]) # Search contacts (READ-ONLY) agent("find all contacts created in the last 30 days") # Get company details (READ-ONLY) agent("get company information for ID 67890") # List available properties (READ-ONLY) agent("show me all available deal properties") # Search with filters (READ-ONLY) agent("search for deals with amount greater than 10000") ``` ## Key Features - **Universal READ-ONLY Access**: Safely search ANY HubSpot object type (contacts, deals, companies, tickets, etc.) - **Smart Search**: Advanced filtering with property-based queries and sorting - **Object Retrieval**: Get detailed information for specific CRM objects by ID - **Property Discovery**: List and explore all available properties for any object type - **User Management**: Get HubSpot user/owner details and assignments - **100% Safe**: NO CREATE, UPDATE, or DELETE operations - read-only by design - **Rich Console Output**: Beautiful table displays with Rich library formatting - **Type Safe**: Full type hints and comprehensive error handling ## Configuration Set your HubSpot API key as an environment variable: ```bash HUBSPOT_API_KEY=your_hubspot_api_key # Required HUBSPOT_DEFAULT_LIMIT=100 # Optional ``` Get your API key at: [HubSpot Private Apps](https://developers.hubspot.com/docs/api/private-apps) ## Resources - [PyPI Package](https://pypi.org/project/strands-hubspot/) - [GitHub Repository](https://github.com/eraykeskinmac/strands-hubspot) - [Examples & Demos](https://github.com/eraykeskinmac/strands-tools-examples) - [HubSpot API Docs](https://developers.hubspot.com/) Source: https://strandsagents.com/docs/integrations/tools/strands-hubspot/index.md --- ## strands-perplexity [strands-perplexity](https://github.com/mkmeral/strands-perplexity) is a real-time web search tool powered by the [Perplexity Search API](https://docs.perplexity.ai/guides/search-quickstart) with citation support, regional filtering, and multi-query capabilities. ## Installation ```bash pip install strands-perplexity ``` ## Usage ```python from strands import Agent from strands_perplexity import perplexity_search agent = Agent(tools=[perplexity_search]) # Search the web agent("What are the latest developments in AI?") # Research a topic agent("Find recent papers on quantum computing breakthroughs") # Get current information agent("What happened in tech news today?") ``` ## Key Features - **Real-time Web Search**: Access ranked web search results from Perplexity’s continuously refreshed index - **Citations Included**: Every result includes URLs for proper attribution - **Regional Search**: Filter results by country using ISO country codes - **Language Filtering**: Filter results by language using ISO 639-1 codes - **Domain Filtering**: Include or exclude specific domains from results - **Multi-query Support**: Execute up to 5 related queries in a single request ## Configuration ```bash PERPLEXITY_API_KEY=your_api_key # Required ``` Get your API key at: [Perplexity API Settings](https://perplexity.ai/account/api) ## Resources - [PyPI Package](https://pypi.org/project/strands-perplexity/) - [GitHub Repository](https://github.com/mkmeral/strands-perplexity) - [Perplexity Search API Docs](https://docs.perplexity.ai/guides/search-quickstart) - [Perplexity Search Best Practices](https://docs.perplexity.ai/guides/search-best-practices) Source: https://strandsagents.com/docs/integrations/tools/strands-perplexity/index.md --- ## strands-spraay [strands-agents-spraay](https://github.com/plagtech/strands-agents-spraay) is a batch payment tool for Strands Agents, powered by the [Spraay Protocol](https://spraay.app). Send ETH or ERC-20 tokens to up to 200 recipients in a single transaction on Base with ~80% gas savings. ## Installation ```bash pip install strands-agents-spraay ``` ## Usage ```python from strands import Agent from strands_spraay import spraay_batch_payment agent = Agent(tools=[spraay_batch_payment]) # Send equal ETH to multiple recipients agent("Send 0.01 ETH to 0xAAA..., 0xBBB..., and 0xCCC... using batch payment") ``` ## Key Features - **Batch ETH**: Send equal or variable ETH amounts to multiple recipients - **Batch ERC-20**: Send equal or variable token amounts with automatic approval handling - **Up to 200 recipients**: Per transaction with ~80% gas savings - **Chain ID verification**: Prevents sending to wrong network - **Gas buffer**: 10% buffer on estimates to prevent out-of-gas errors ## Configuration ```bash SPRAAY_PRIVATE_KEY=your_wallet_private_key # Required PRIVATE_KEY=your_wallet_private_key # Alternative BASE_RPC_URL=https://mainnet.base.org # Optional ``` > ⚠️ **Security**: Never commit your private key to source control. Use environment variables or a secrets manager. ## Resources - [PyPI Package](https://pypi.org/project/strands-agents-spraay/) - [GitHub Repository](https://github.com/plagtech/strands-agents-spraay) - [Spraay Protocol](https://spraay.app) Source: https://strandsagents.com/docs/integrations/tools/strands-spraay/index.md --- ## strands-sql [strands-sql](https://github.com/NithiN-1808/strands-sql) is a general-purpose SQL tool for Strands Agents — supports PostgreSQL, MySQL, and SQLite via SQLAlchemy with built-in safety controls. ## Installation ```bash # SQLite (no extra driver needed) pip install strands-sql # PostgreSQL pip install "strands-sql[postgres]" # MySQL pip install "strands-sql[mysql]" ``` ## Usage ```python from strands import Agent from strands_sql import sql_database agent = Agent(tools=[sql_database]) # Discover the schema agent.tool.sql_database(action="schema_summary") # Run a query agent.tool.sql_database( action="query", sql="SELECT * FROM orders WHERE amount > 100 LIMIT 20", ) # Describe a table agent.tool.sql_database(action="describe_table", table="users") ``` ## Key Features - **Multi-dialect support**: PostgreSQL, MySQL, and SQLite via SQLAlchemy - **Safe by default**: read-only mode, row limits, query timeouts - **Access control**: table allowlist and blocklist - **LLM-friendly output**: Markdown and CSV result formats - **Schema discovery**: `list_tables`, `describe_table`, `schema_summary` - **Query execution**: `query`, `execute`, `explain` ## Configuration Set your database connection via environment variable: ```bash export DATABASE_URL="postgresql://user:password@localhost:5432/mydb" ``` Or pass it directly per call: ```python agent.tool.sql_database( action="list_tables", connection_string="sqlite:///./local.db", ) ``` ## Troubleshooting - **No connection string found** — make sure `DATABASE_URL` is set or pass `connection_string` explicitly. - **Write query blocked** — write operations require `read_only=False` explicitly. - **Timeout errors** — increase `query_timeout` (default: 30s). ## Resources - [PyPI Package](https://pypi.org/project/strands-sql/) - [GitHub Repository](https://github.com/NithiN-1808/strands-sql) - [SQLAlchemy Docs](https://docs.sqlalchemy.org/) Source: https://strandsagents.com/docs/integrations/tools/strands-sql/index.md --- ## strands-teams [strands-teams](https://github.com/eraykeskinmac/strands-teams) is a production-ready Microsoft Teams notification tool with rich Adaptive Cards support and custom messaging capabilities. ## Installation ```bash pip install strands-teams ``` ## Usage ```python from strands import Agent from strands_teams import teams agent = Agent(tools=[teams]) # Simple notification agent("send a Teams message: New lead from Acme Corp") # Status update with formatting agent("send a status update: Website redesign is 75% complete") # Custom adaptive card agent("create approval request for Q4 budget with amount $50000") ``` ## Key Features - **Adaptive Cards**: Rich, interactive message cards with modern UI - **Pre-built Templates**: Notifications, approvals, status updates, and alerts - **Custom Cards**: Full adaptive card schema support for complex layouts - **Action Buttons**: Add interactive elements and quick actions - **Rich Formatting**: Markdown support, images, tables, and media - **Webhook Integration**: Seamless Teams channel integration ## Configuration ```bash TEAMS_WEBHOOK_URL=your_teams_webhook_url # Optional (can be provided per call) ``` Setup webhook: Teams Channel → Connectors → Incoming Webhook ## Resources - [PyPI Package](https://pypi.org/project/strands-teams/) - [GitHub Repository](https://github.com/eraykeskinmac/strands-teams) - [Examples & Demos](https://github.com/eraykeskinmac/strands-tools-examples) - [Adaptive Cards](https://adaptivecards.io/) - [Teams Webhooks](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/what-are-webhooks-and-connectors) Source: https://strandsagents.com/docs/integrations/tools/strands-teams/index.md --- ## strands-telegram [strands-telegram](https://github.com/eraykeskinmac/strands-telegram) is a comprehensive Telegram Bot API integration tool with 60+ methods for complete bot development capabilities. ## Installation ```bash pip install strands-telegram ``` ## Usage ```python from strands import Agent from strands_telegram import telegram agent = Agent(tools=[telegram]) # Send simple message agent("send a Telegram message 'Hello World' to chat 123456") # Send media with caption agent("send photo.jpg to Telegram with caption 'Check this out!'") # Create interactive keyboard agent("send a message with buttons: Yes/No for approval") ``` ## Key Features - **60+ Telegram API Methods**: Complete Bot API coverage - **Media Support**: Photos, videos, audio, documents, and stickers - **Interactive Elements**: Inline keyboards, polls, dice games - **Group Management**: Admin functions, member management, permissions - **File Operations**: Upload, download, and media handling - **Webhook Support**: Real-time message processing - **Custom API Calls**: Extensible for any Telegram method ## Configuration ```bash TELEGRAM_BOT_TOKEN=your_bot_token # Required ``` Get your bot token at: [BotFather](https://core.telegram.org/bots#botfather) ## Resources - [PyPI Package](https://pypi.org/project/strands-telegram/) - [GitHub Repository](https://github.com/eraykeskinmac/strands-telegram) - [Examples & Demos](https://github.com/eraykeskinmac/strands-tools-examples) - [Bot Creation Guide](https://core.telegram.org/bots) - [Telegram Bot API](https://core.telegram.org/bots/api) Source: https://strandsagents.com/docs/integrations/tools/strands-telegram/index.md --- ## strands-telegram-listener [strands-telegram-listener](https://github.com/eraykeskinmac/strands-telegram-listener) is a real-time Telegram message processing tool with AI-powered auto-replies and comprehensive event handling. ## Installation ```bash pip install strands-telegram-listener ``` ## Usage ```python from strands import Agent from strands_telegram_listener import telegram_listener agent = Agent(tools=[telegram_listener]) # Start listening for messages agent("start Telegram listener") # Get recent messages agent("get last 10 Telegram messages") # Check listener status agent("check Telegram listener status") ``` ## Key Features - **Real-time Processing**: Long polling for instant message handling - **AI Auto-replies**: Intelligent responses using Strands agents - **Event Storage**: Comprehensive message history in JSONL format - **Smart Filtering**: Message deduplication and selective processing - **Background Threading**: Non-blocking operation - **Status Monitoring**: Real-time listener status and metrics - **Flexible Configuration**: Environment-based settings ## Configuration ```bash TELEGRAM_BOT_TOKEN=your_bot_token # Required STRANDS_TELEGRAM_AUTO_REPLY=true # Optional STRANDS_TELEGRAM_LISTEN_ONLY_TAG=#support # Optional ``` Get your bot token at: [BotFather](https://core.telegram.org/bots#botfather) ## Resources - [PyPI Package](https://pypi.org/project/strands-telegram-listener/) - [GitHub Repository](https://github.com/eraykeskinmac/strands-telegram-listener) - [Examples & Demos](https://github.com/eraykeskinmac/strands-tools-examples) - [Bot Creation Guide](https://core.telegram.org/bots) - [Telegram Bot API](https://core.telegram.org/bots/api) Source: https://strandsagents.com/docs/integrations/tools/strands-telegram-listener/index.md --- ## Universal Tool Calling Protocol (UTCP) The [Universal Tool Calling Protocol (UTCP)](https://www.utcp.io/) is a lightweight, secure, and scalable standard that enables AI agents to discover and call tools directly using their native protocols - **no wrapper servers required**. UTCP acts as a “manual” that tells agents how to call your tools directly, extending OpenAPI for AI agents while maintaining full backward compatibility. This community plugin integrates UTCP with Strands Agents SDK, providing standardized tool discovery and execution capabilities. ## Installation ```bash pip install strands-agents strands-utcp ``` ## Usage ```python from strands import Agent from strands_utcp import UtcpToolAdapter # Configure UTCP tool adapter config = { "manual_call_templates": [ { "name": "weather_api", "call_template_type": "http", "url": "https://api.weather.com/utcp", "http_method": "GET" } ] } # Use UTCP tools with Strands agent async def main(): async with UtcpToolAdapter(config) as adapter: # Get available tools tools = adapter.list_tools() print(f"Found {len(tools)} UTCP tools") # Create agent with UTCP tools agent = Agent(tools=adapter.to_strands_tools()) # Use the agent response = await agent.invoke_async("What's the weather like today?") print(response.message) import asyncio asyncio.run(main()) ``` ## Key Features - **Universal Tool Access**: Connect to any UTCP-compatible tool source - **OpenAPI/Swagger Support**: Automatic tool discovery from API specifications - **Multiple Sources**: Connect to multiple tool sources simultaneously - **Async/Await Support**: Full async support with context managers - **Type Safe**: Full type hints and validation - **Easy Integration**: Drop-in tool adapter for Strands agents ## Resources - **GitHub**: [universal-tool-calling-protocol/python-utcp](https://github.com/universal-tool-calling-protocol/python-utcp) - **PyPI**: [strands-utcp](https://pypi.org/project/strands-utcp/) Source: https://strandsagents.com/docs/integrations/tools/utcp/index.md --- ## Strands Labs [Strands Labs](https://github.com/strands-labs) is the experimental arm of Strands Agents: open source projects that take the core SDK into new problem spaces. Where the SDK gives you the agent loop, tool use, model providers, and multi-agent patterns, Labs applies that foundation to areas like physical robotics, world models, agentic benchmarking, harness optimization, real-time audio, and fast decision models. Labs projects are published to package repositories and work alongside the SDK today. They move faster and cover more surface area than the core SDK, so expect more frequent changes and newer integrations. Some projects graduate into the core SDK or become standalone products; others stay experimental. Each project lives in its own repository under the [strands-labs](https://github.com/strands-labs) organization. ## Projects [Robots](https://github.com/strands-labs/robots)Control, simulate, and train physical robots with natural language. One Robot() call returns a MuJoCo simulation or real hardware, with pluggable vision-language-action policies and a peer-to-peer mesh. [Strands for Cosmos](https://github.com/strands-labs/strands-for-cosmos)Bring NVIDIA Cosmos to Strands Agents: physics-aware reasoning over video, plus generation of video, audio, and robot actions on local compute. [Benchmark Harnesses](https://github.com/strands-labs/benchmark-harnesses)Strands-based agents and harnesses for agentic benchmarks, including Simple Strands Agent, a lean autonomous-coding harness with strong results on SWE-Bench and Terminal Bench 2. [Harness Optimizer](https://github.com/strands-labs/harness-optimizer)Optimize an agent's harness through tunable Formulas, then improve those Formulas from collected rollout trajectories with a PyTorch-style training loop. [AI Functions](https://github.com/strands-labs/ai-functions)Python functions evaluated by AI agents. Enforce correctness with runtime post-conditions instead of prompt engineering alone, and compose functions into multi-agent workflows. [PyWebRTC Audio](https://github.com/strands-labs/pywebrtc-audio)Python bindings for WebRTC audio processing: echo cancellation, noise suppression, gain control, and voice activity detection, with a working Strands BidiAgent integration. [Strands Decider](https://github.com/strands-labs/strands-decider)A small, fast decision model, or system one model, for agentic workflows. Pick between options or rate on a scale faster than an LLM, with a calibrated confidence on every decision. ## Contributing Have an experimental idea for AI agents? Labs takes contributions from across the community. See the [contributing guide](https://github.com/strands-agents/harness-sdk/blob/main/CONTRIBUTING.md) to get started. Source: https://strandsagents.com/docs/labs/index.md --- ## Lesson 4: Adding callbacks & response streaming Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=PtdHZBbm1Ys&list=PLDzwjhH-4yhU&index=4)* *Code for this lesson: [`samples/04-callbacks-streaming`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/04-callbacks-streaming)* ## Callbacks control what the user sees Callbacks control how agent output surfaces to users. The default handler streams text to stdout, which is fine for a terminal demo but not for a UI, an API, or a sub-agent running behind the scenes. You can replace the default with a custom handler, silence output entirely, or use `stream_async()` for async servers. ## Custom callback handler Changed since recording The calculator is now a small custom `@tool` defined in the sample, replacing the older `strands_tools.calculator` import. The callback and streaming APIs shown in the video still apply. A callback handler is a function that accepts `**kwargs`. It fires for every agent event: text chunks, tool calls, and complete messages. This handler ignores streaming chunks and only prints complete assistant messages: ```python from strands import Agent, tool @tool def calculator(a: float, b: float, operation: str = "add") -> str: """Perform a math operation on two numbers. Args: a: First number b: Second number operation: One of "add", "subtract", "multiply", "divide", "power" """ if operation == "add": result = a + b elif operation == "subtract": result = a - b elif operation == "multiply": result = a * b elif operation == "divide": result = a / b if b != 0 else "Error: division by zero" elif operation == "power": result = a ** b else: result = f"Unknown operation: {operation}" return str(result) def buffered_handler(**kwargs): # Only show complete messages, not individual streaming chunks if "message" in kwargs and kwargs["message"].get("role") == "assistant": content = kwargs["message"].get("content", []) for block in content: if "text" in block: print(block["text"]) agent = Agent(tools=[calculator], callback_handler=buffered_handler) agent("What is 2 to the power of 16, minus 1?") ``` 📂 [callbacks\_streaming.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/04-callbacks-streaming/callbacks_streaming.py) Useful event keys you’ll see in `kwargs`: - `data`: a streamed text chunk - `current_tool_use`: the tool the model is invoking, including its input - `message`: a complete message once a turn finishes ## Silent mode Set `callback_handler=None` to suppress all output. The agent runs and returns a result you can use programmatically: ```python agent = Agent(tools=[calculator], callback_handler=None) result = agent("What is 42 * 42?") print(f"Captured result: {result}") ``` This is essential for sub-agents in multi-agent systems that run behind the scenes. Only the orchestrator should be streaming to the user. ## Async streaming (FastAPI) For async servers, use `agent.stream_async()`, an async generator that yields events as they happen. Here it powers a FastAPI streaming endpoint: ```python from fastapi import FastAPI from fastapi.responses import StreamingResponse from pydantic import BaseModel from strands import Agent, tool @tool def calculator(a: float, b: float, operation: str = "add") -> str: """Perform a math operation on two numbers. Args: a: First number b: Second number operation: One of "add", "subtract", "multiply", "divide", "power" """ if operation == "add": result = a + b elif operation == "subtract": result = a - b elif operation == "multiply": result = a * b elif operation == "divide": result = a / b if b != 0 else "Error: division by zero" elif operation == "power": result = a ** b else: result = f"Unknown operation: {operation}" return str(result) app = FastAPI() class PromptRequest(BaseModel): prompt: str @app.post("/stream") async def stream_response(request: PromptRequest): async def generate(): agent = Agent(tools=[calculator], callback_handler=None) async for event in agent.stream_async(request.prompt): if "data" in event: yield event["data"] return StreamingResponse(generate(), media_type="text/plain") ``` 📂 [fastapi\_streaming.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/04-callbacks-streaming/fastapi_streaming.py) · [async\_streaming.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/04-callbacks-streaming/async_streaming.py) Run it with `pip install fastapi uvicorn` and `uvicorn fastapi_streaming:app --reload`, then POST to `/stream`. ## Resources - 📖 [Callback Handlers](/docs/user-guide/sdk/streaming/callback-handlers/index.md) - 📖 [Tools Overview](/docs/user-guide/sdk/tools/index.md) Source: https://strandsagents.com/docs/learning/adding-callbacks-and-response-streaming/index.md --- ## Lesson 6: Agent plugins & skills Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=dnChw1mfc5M&list=PLDzwjhH-4yhU&index=6)* *Code for this lesson: [`samples/06-plugins-skills`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/06-plugins-skills)* ## Plugins Plugins are the extension mechanism in Strands. They let you package hooks, tools, and custom logic into reusable components that snap into any agent. Where a hook is a single behavior, a plugin bundles several primitives together so they can be shared and reused as a unit. Skills are one type of plugin that provides on-demand workflow instructions. Strands ships others too, and you can build your own for memory, orchestration, observability, governance, or custom workflows. ## Skills As agents grow, system prompts bloat with irrelevant instructions. If your agent supports twenty workflows, you don’t want instructions for all twenty consuming tokens on every request. Skills solve this through **progressive disclosure**: the agent only sees skill names at startup and loads full instructions on demand. Each skill is a markdown file in a subfolder containing guidance for a specific task. If a skill isn’t relevant to the current request, its instructions never enter the context window. This is one example of context engineering. Run the following from `samples/06-plugins-skills`: ```python from strands import Agent, AgentSkills from customer_service import lookup_customer, get_order_history, process_refund # Skills plugin discovers and registers all skills in the directory skills_plugin = AgentSkills(skills=["./skills"]) agent = Agent( tools=[lookup_customer, get_order_history, process_refund], plugins=[skills_plugin], system_prompt="""You are a customer service agent. When a customer needs help, activate the appropriate skill for step-by-step guidance.""" ) ``` 📂 [customer\_service.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/06-plugins-skills/customer_service.py) · [skills/](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/06-plugins-skills/skills) The `skills/` directory in the sample has four skills: `account-troubleshooting`, `order-tracking`, `pdf-processing`, and `refund-processing`. Each is a folder with a `SKILL.md` describing when to use it and the steps to follow. This customer service agent is the running example for the rest of the course. ## Goal loop Lesson 1 said a good harness verifies whether the agent’s actions actually worked. `GoalLoop` is the plugin that does that. You define what “done” means, attach it to the agent, and it handles the retry loop: 1. The agent processes the prompt and produces a response. 2. GoalLoop runs your validator against the result. 3. If it passes, the loop terminates as “satisfied.” 4. If it fails and budget remains, GoalLoop injects the feedback as a new user message and re-invokes the agent. 5. If the attempt limit or timeout is exhausted, the loop stops without retrying. The validator can be a natural-language goal (judged by a second model) or a plain function. Functions are the more interesting case because they can run real checks. Here a coding agent isn’t finished until the test suite passes, and when tests fail the output is fed straight back to the agent as its next instruction: ```python import asyncio from strands import Agent from strands.vended_plugins.goal import GoalLoop from strands.vended_tools import file_editor, shell async def tests_pass(response, agent): proc = await asyncio.create_subprocess_exec( "pytest", "--tb=short", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await proc.communicate() if proc.returncode == 0: return True output = (stdout.decode() + stderr.decode())[-4000:] return { "passed": False, "feedback": f"pytest exited {proc.returncode}.\n{output}", } agent = Agent( tools=[file_editor, shell], plugins=[GoalLoop(goal=tests_pass, max_attempts=10)], ) agent("Fix the failing tests in tests/test_orders.py") ``` Every retry, the agent sees the exact pytest output from the last attempt. It stops when the suite is green or after 10 tries, whichever comes first. Always set `max_attempts` or `timeout` in production so the loop can’t run away. ## Resources - 📖 [Plugins](/docs/user-guide/sdk/plugins/index.md) - 📖 [Skills](/docs/user-guide/sdk/plugins/skills/index.md) - 📖 [Goal Loop](/docs/user-guide/sdk/plugins/goal-loop/index.md) - 📖 [Hooks](/docs/user-guide/sdk/agents/hooks/index.md) Source: https://strandsagents.com/docs/learning/agent-plugins-and-skills/index.md --- ## Lesson 8: Context engineering & context management Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=6zbbYm902MQ&list=PLDzwjhH-4yhU&index=8)* *Code for this lesson: [`samples/08-context-management`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/08-context-management)* ## What context engineering is Context engineering is the discipline of deciding **what information enters the model’s context window, when, and in what form**. Unlike prompt engineering (which focuses on instructions), context engineering ensures the model has the right data at the right time without overflowing the window or wasting tokens. It breaks down into four categories: | Category | What It Does | Strands Primitive | | --- | --- | --- | | **Select** | Choose what enters context, inject relevant info, filter out noise | `ContextInjector` plugin | | **Compress** | Shrink what’s already in context, summarize history, truncate results | `ContextManager` strategies (truncate, summarize, drop) | | **Isolate** | Separate concerns, give sub-agents their own context windows | Multi-agent patterns with separate agent contexts | | **Externalize** | Move large data out of context, store externally, keep a compact reference | `ContextManager` stash + retrieval tool | ## The one-line default: `context_manager="auto"` Changed since recording The video uses `SummarizingConversationManager` and `ContextOffloader`. The updated starting point is `context_manager="auto"`. For custom behavior, use `ContextManager` and `Offload` from `strands.experimental.context_manager`, as shown below. Truncation keeps previews; it does not simply drop whole messages. For most use cases, start here: ```python from strands import Agent agent = Agent(context_manager="auto") ``` This single parameter enables: - **Offloading** large tool results to a stash, replaced with truncated previews - **Summarization** of old messages into structured summaries (not dropped) - **Proactive compression** firing at 85% context usage to stay ahead of overflow The effect on cost and answer quality depends on the workload. Measure both with your own evaluation cases. For agents that need to protect specific context across long conversations, use `context_manager="agentic"`. The model gets tools to summarize, truncate, or pin messages itself, trading some tokens for judgment. ## Context injector The `ContextInjector` plugin folds ephemeral text into the model input before each call. The text is never written to conversation history; it augments one call only. Use it for context the agent should always have but that doesn’t belong in stored history: current time, environment facts, retrieval lookups. ```python from datetime import datetime, timezone from strands import Agent from strands.vended_plugins.context_injector import ContextInjector agent = Agent( plugins=[ ContextInjector( lambda context: f"{datetime.now(timezone.utc).isoformat()}" ), ], ) ``` Control when injection fires: - `trigger="userTurn"` (default): only on fresh user messages - `trigger="everyTurn"`: before every model call, including mid-task tool-result turns - Custom predicate: `trigger=lambda context: context.state.get("recall_enabled") is True` ## ContextManager and Offload strategies The `ContextManager` is the engine behind `context_manager="auto"`. When you need custom control over how context is managed, build your own strategy pipeline using `Offload` strategies. Experimental `ContextManager` and `Offload` are currently exported from `strands.experimental.context_manager`. They are fully functional and will move to the main namespace in an upcoming release. There are three types of Offload strategies: | Strategy | What stays in context | | --- | --- | | `Offload.truncate(...)` | A head/tail preview of the original | | `Offload.summarize(...)` | An LLM-generated summary of the original | | `Offload.drop(...)` | Nothing (original goes to stash only) | Each strategy takes a **target** that controls what content it operates on: ```python from strands.experimental.context_manager import Offload Offload.summarize("*") # everything: all message types Offload.truncate("tool_results") # only successful tool results Offload.drop("tool_result_errors") # only errored tool results Offload.summarize("assistant_text") # only assistant text blocks Offload.truncate(["bash", "read_file"]) # only results from specific tools Offload.truncate(["!read_file"]) # everything except read_file ``` And `.when(...)` sets the conditions: - `threshold=N`: fire on individual blocks exceeding N tokens (per-block mode) - `utilization=0.85`: fire when the context window is 85% full (per-message mode) - `preserve_recent=N`: skip the N most recent matching messages ### Truncate strategy (keep previews) Truncate matching content to head/tail previews when context gets full: ```python from strands import Agent from strands.experimental.context_manager import ContextManager, Offload agent = Agent( context_manager=ContextManager( strategies=[ Offload.truncate("tool_results").when(threshold=2500), Offload.truncate("*").when(utilization=0.9, preserve_recent=10), ], ), ) ``` 📂 [sliding\_window.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/08-context-management/sliding_window.py) ### Summarize strategy Instead of dropping old messages, compress them into summaries. Preserves more information, but summaries are lossy: ```python from strands import Agent from strands.experimental.context_manager import ContextManager, Offload agent = Agent( context_manager=ContextManager( strategies=[ Offload.truncate("tool_results").when(threshold=2500), Offload.summarize("*").when(utilization=0.85, preserve_recent=10), ], ), ) ``` 📂 [summarizing.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/08-context-management/summarizing.py) ### Custom summarizer (cheaper model) Summarizing history doesn’t require your most capable model. Pass a cheaper one, and a domain-specific prompt, via the config dict: ```python from strands import Agent from strands.models import BedrockModel from strands.experimental.context_manager import ContextManager, Offload summarizer_model = BedrockModel(model_id="us.anthropic.claude-haiku-4-5-20251001-v1:0") agent = Agent( context_manager=ContextManager( strategies=[ Offload.truncate("tool_results").when(threshold=2500), Offload.summarize( "*", { "model": summarizer_model, "system_prompt": "Summarize the customer service conversation...", }, ).when(utilization=0.85, preserve_recent=8), ], stash=False, ), ) ``` `stash=False` turns off the stash entirely: offloaded content isn’t kept anywhere and the agent gets no retrieval tool. That’s fine for pure summarization where you don’t need to pull anything back. Leave it on (the default) when you want the agent to be able to recover offloaded tool results. 📂 [custom\_summarizer.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/08-context-management/custom_summarizer.py) ## Strategy comparison | Strategy | Tradeoff | | --- | --- | | `context_manager="auto"` | Best default. Offloading + summarization + proactive compression | | `context_manager="agentic"` | Model self-manages context. Trades tokens for judgment | | `Offload.truncate(...)` | Keeps a preview; originals remain recoverable when stash is enabled | | `Offload.summarize(...)` | Preserves more info. Lossy compression, costs an LLM call | | `Offload.drop(...)` | Most aggressive. Content goes to stash only | | Context injection | Ephemeral per-call data. Never persisted to history | ## Resources - 📖 [Context Management](/docs/user-guide/sdk/context-management/index.md) - 📖 [Context Injector](/docs/user-guide/sdk/plugins/context-injector/index.md) - 📖 [Blog: Reduced cost, better isolation, and more resilience](https://strandsagents.com/blog/reduced-cost-better-isolation-more-resilience/) Source: https://strandsagents.com/docs/learning/context-engineering-and-conversation-management/index.md --- ## Lesson 5: Control your agent with hooks Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=Zamh36RWKz8&list=PLDzwjhH-4yhU&index=5)* *Code for this lesson: [`samples/05-hooks`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/05-hooks)* ## Rules that don’t depend on the model Hooks inject code at lifecycle events (before/after tool calls, before/after the agent loop) without changing the agent’s logic. Unlike tools, which the model decides to use, hooks fire automatically every time regardless of what the model reasons. The hook applies a programmed check at the event where you register it. A runaway loop could call the same tool dozens of times. A model might attempt a destructive operation without asking. The hooks below block the specific tool calls they check; other tools need their own checks. ## Hook architecture - Subclass `HookProvider` to define hooks - Register callbacks for lifecycle events in `register_hooks()` - Multiple hooks can listen to the same event (stackable) - `event.interrupt()` pauses the loop for human input - `event.cancel_tool` blocks tool execution and feeds a message back to the model explaining why ## Example: human approval for deletions ```python from strands import Agent, tool from strands.hooks import BeforeToolCallEvent, HookProvider, HookRegistry class DeleteApprovalHook(HookProvider): """Intercepts delete operations for human approval.""" def register_hooks(self, registry: HookRegistry) -> None: registry.add_callback(BeforeToolCallEvent, self.check_delete) def check_delete(self, event: BeforeToolCallEvent) -> None: if event.tool_use["name"] != "delete_file": return approval = event.interrupt( "delete-approval", reason={"path": event.tool_use["input"]["path"]} ) if approval.lower() != "y": event.cancel_tool = "User denied file deletion" agent = Agent( tools=[list_files, read_file, write_file, delete_file], hooks=[DeleteApprovalHook()], ) ``` 📂 [approval\_interrupt.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/05-hooks/approval_interrupt.py) `event.interrupt()` pauses agent execution and returns control to the caller. That’s what makes approval workflows possible: the agent doesn’t proceed until a human answers. ## Example: rate limiting tool calls ```python from strands import Agent from strands.hooks import BeforeInvocationEvent, BeforeToolCallEvent, HookProvider, HookRegistry from rate_limiter import get_weather class LimitToolCounts(HookProvider): def __init__(self, max_calls: int = 3): self.max_calls = max_calls self.counts: dict[str, int] = {} def register_hooks(self, registry: HookRegistry) -> None: registry.add_callback(BeforeInvocationEvent, self.reset) registry.add_callback(BeforeToolCallEvent, self.check) def reset(self, event: BeforeInvocationEvent) -> None: self.counts = {} def check(self, event: BeforeToolCallEvent) -> None: name = event.tool_use["name"] self.counts[name] = self.counts.get(name, 0) + 1 if self.counts[name] > self.max_calls: event.cancel_tool = ( f"'{name}' hit the {self.max_calls}-call limit. " "Do NOT call this tool again." ) agent = Agent(tools=[get_weather], hooks=[LimitToolCounts(max_calls=3)]) ``` 📂 [rate\_limiter.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/05-hooks/rate_limiter.py) Notice the counter resets on `BeforeInvocationEvent`. Rate limits are per request, not for the agent’s lifetime. And because `cancel_tool` sends a message back to the model, the model receives feedback about why the call was blocked. The hook continues to block excess calls even if the model retries. ## When to use hooks - Rate limit tool usage to prevent runaway loops - Require human approval before destructive operations - Log every tool call for audit trails - Validate tool inputs and outputs against business rules - Enforce access control on sensitive tools Hooks don’t touch tools or prompts. They’re a separate, reusable layer you can drop onto any agent. ## Resources - 📖 [Hooks](/docs/user-guide/sdk/agents/hooks/index.md) - 📖 [Lifecycle Controls](/docs/user-guide/sdk/agents/lifecycle-controls/index.md) Source: https://strandsagents.com/docs/learning/control-your-agent-with-hooks/index.md --- ## Lesson 14: Deploying agents to the cloud Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=S_ZRZFDJ6wE&list=PLDzwjhH-4yhU&index=14)* *Code for this lesson: [`samples/14-deploy`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/14-deploy)* ## From local to production Everything so far has run on a local machine. A Strands agent is just Python, so you can containerize it and run it anywhere. This lesson deploys it to AWS using Amazon Bedrock AgentCore: Runtime for isolated execution, Memory for persistent and long-term recall, and Observability for tracing. ![AgentCore Overview](/_astro/agentcore-overview.eQeZxM_8_GXKJG.webp) ## Making your agent deployable Run this excerpt from `samples/14-deploy`. The linked `main.py` contains the complete entrypoint, request parsing, and runtime session handling. Wrap the agent in a `BedrockAgentCoreApp` and give it an entrypoint. The agent itself doesn’t change; the customer service agent below is the same one built across the previous lessons, with an AgentCore Memory session manager swapped in for persistence: ```python import os from pathlib import Path from strands import Agent, AgentSkills from customer_service_tools import lookup_customer, get_order_history, process_refund from steering_handlers import RefundWorkflowHandler, ToneGuardrailHandler from bedrock_agentcore.runtime import BedrockAgentCoreApp from bedrock_agentcore.memory.integrations.strands.config import ( AgentCoreMemoryConfig, RetrievalConfig ) from bedrock_agentcore.memory.integrations.strands.session_manager import ( AgentCoreMemorySessionManager ) app = BedrockAgentCoreApp() SYSTEM_PROMPT = "Help customers with their orders using the available tools." SKILLS_DIR = str(Path(__file__).parent / "skills") MEMORY_ID = os.environ.get("BEDROCK_AGENTCORE_MEMORY_ID", "") def create_agent(actor_id: str, session_id: str): # AgentCore Memory for persistence + long-term recall session_manager = None if MEMORY_ID: config = AgentCoreMemoryConfig( memory_id=MEMORY_ID, session_id=session_id, actor_id=actor_id, retrieval_config={ "/users/{actorId}/facts": RetrievalConfig(), "/users/{actorId}/preferences": RetrievalConfig(), }, ) session_manager = AgentCoreMemorySessionManager( agentcore_memory_config=config, region_name="us-east-1", ) return Agent( tools=[lookup_customer, get_order_history, process_refund], plugins=[ AgentSkills(skills=[SKILLS_DIR]), RefundWorkflowHandler(), ToneGuardrailHandler(), ], system_prompt=SYSTEM_PROMPT, context_manager="auto", session_manager=session_manager, ) ``` 📂 [main.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/14-deploy/main.py) · [lambda-deployment/](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/14-deploy/lambda-deployment) (alternative: AWS Lambda) The complete runtime sample binds its cached agent to one actor and session and rejects attempts to reuse that process for a different pair. Treat the payload’s `actor_id` as a demo identifier; a production application must derive it from authenticated identity. Durable recall requires the configured memory resource. The `retrieval_config` namespaces tell AgentCore Memory which long-term memory strategies to pull from on each turn, so the agent recalls facts and preferences about a returning user without replaying old conversations. ## Deployment commands ```bash # From samples/14-deploy, install the CLI and create a Python Strands project. npm install -g @aws/agentcore agentcore create --name CourseAgent --project-name CourseDemo \ --framework Strands --model-provider Bedrock --language Python --memory none # Replace the generated starter with this lesson's agent and dependencies. cp main.py customer_service_tools.py steering_handlers.py pyproject.toml \ CourseDemo/app/CourseAgent/ cp -R skills/. CourseDemo/app/CourseAgent/skills/ cd CourseDemo agentcore add memory --name CustomerServiceMemory --strategies SEMANTIC,USER_PREFERENCE agentcore deploy # Reuse this ID for this actor's conversation; generate a new ID for another user. SESSION_ID="$(python3 -c 'import uuid; print(uuid.uuid4())')" agentcore invoke --session-id "$SESSION_ID" \ '{"prompt": "I need help returning my order", "actor_id": "customer-demo"}' ``` ## What AgentCore provides | Component | What It Does | | --- | --- | | **Runtime** | Isolated microVMs, maintains state across requests | | **Memory** | Conversation persistence + semantic long-term recall | | **Observability** | Automatic traces, logs, execution telemetry | | **Gateway** | Expose APIs as MCP-compatible tools | | **Identity** | IAM or OAuth authentication gate | AgentCore has more capabilities beyond these. See the [AgentCore developer guide](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html) for the full picture. ## What you still need The deployed agent is only part of a production architecture. You still need API gateways, rate limiting, retries, security controls, monitoring, and error handling around it. The surrounding architecture matters as much as the agent. ## Resources - 📖 [Strands Deployment Guide](/docs/user-guide/sdk/deploy/index.md) - 📖 [Amazon Bedrock AgentCore Developer Guide](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html) - 📖 [AgentCore Runtime](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime.html) - 📖 [AgentCore Memory](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/memory.html) - 📖 [AgentCore Observability](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/observability.html) - 📖 [AgentCore CLI Reference](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/cli-reference.html) - 📖 [Blog: What Is an Agent Harness?](https://dev.to/aws/what-is-an-agent-harness-a-hands-on-guide-with-agentcore-harness-1h33) Source: https://strandsagents.com/docs/learning/deploying-agents-to-the-cloud/index.md --- ## Lesson 13: Evaluating agents Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=rDtcfG4aZV4&list=PLDzwjhH-4yhU&index=13)* *Code for this lesson: [`samples/13-evals`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/13-evals)* ## Why traditional testing breaks down Agents are nondeterministic. The same input can produce a different (but equally valid) response, a different tool ordering, or a different level of detail. `assert output == expected` doesn’t work. Instead you need LLM-as-a-judge scoring, trajectory validation, multi-turn simulations, and deterministic assertions, combined into eval suites that catch regressions. Strands Evals is a separate package: ```bash pip install strands-agents-evals ``` ## Basic evaluation structure An evaluation has three parts: **cases** (inputs plus expectations), **evaluators** (how to score), and a **task** function that runs your agent and returns what the evaluators need. Here we evaluate the customer service agent from earlier lessons on both its final output and the sequence of tools it called: Run from `samples/13-evals` so the factory can find the sample tools and skills. ```python from strands import Agent, AgentSkills from strands_evals import Case, Experiment from strands_evals.evaluators import OutputEvaluator, TrajectoryEvaluator from strands_evals.extractors import tools_use_extractor from strands_evals.types import TaskOutput from create_agent import create_customer_service_agent def create_agent(): return create_customer_service_agent(callback_handler=None) # Trajectory evaluator: validates tool call ordering trajectory_evaluator = TrajectoryEvaluator( rubric="Match the expected tool order; ignore supplementary skills tool calls.", include_inputs=True, ) # Output evaluator: scores response quality output_evaluator = OutputEvaluator( rubric="Score accuracy, professionalism, and whether the response addresses the request.", ) def get_response(case: Case) -> TaskOutput: agent = create_agent() response = agent(case.input) trajectory = tools_use_extractor.extract_agent_tools_used_from_messages(agent.messages) return TaskOutput(output=str(response), trajectory=trajectory) cases = [ Case( name="refund-full-workflow", input="I'm C-1001. Refund order ORD-5521. Yes, I confirm the refund.", expected_output="Refund processed with 3-5 day timeline.", expected_trajectory=["lookup_customer", "get_order_history", "process_refund"], ), Case( name="missing-customer-id", input="I want a refund.", expected_output="Ask for customer ID before proceeding.", expected_trajectory=[], ), ] experiment = Experiment( cases=cases, evaluators=[trajectory_evaluator, output_evaluator], ) report = experiment.run_evaluations(task=get_response) report.run_display() ``` 📂 [customer\_service\_eval.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/13-evals/customer_service_eval.py) ## Evaluation types | Type | What It Checks | | --- | --- | | **Output evaluation** | Quality, tone, correctness of the final response | | **Trajectory evaluation** | Whether the agent followed the correct tool sequence | | **Simulation** | Multi-turn stress testing over time | | **Deterministic** | JSON schema, response length, format. No LLM needed | | **Chaos testing** | Does the agent recover when tools fail? | | **Red teaming** | Does the agent resist adversarial attacks? | | **Experiment Generator** | Auto-bootstraps test cases from agent capabilities | ## Chaos testing Production isn’t ideal. Tools time out, APIs go down, responses come back truncated. Chaos testing verifies your agent handles those failures gracefully. The `ChaosPlugin` intercepts tool calls and injects configurable failures. This example uses the course’s mock order tool. Each case starts with a fresh agent. ```python from strands import Agent from strands_evals import Case from strands_evals.chaos import ChaosCase, ChaosExperiment, ChaosPlugin from strands_evals.chaos.effects import Timeout, NetworkError, TruncateFields from strands_evals.evaluators import OutputEvaluator from customer_service_tools import get_order_history effect_maps = { "api_timeout": {"tool_effects": {"get_order_history": [Timeout()]}}, "api_down": {"tool_effects": {"get_order_history": [NetworkError()]}}, "partial_response": { "tool_effects": {"get_order_history": [TruncateFields(max_length=200)]} }, } chaos_cases = ChaosCase.expand( [Case(name="order_status", input="Check the orders for customer C-1001.")], effect_maps, include_no_effect_baseline=True, ) def run_case(case): agent = Agent( tools=[get_order_history], plugins=[ChaosPlugin()], callback_handler=None, system_prompt="Use order data. If it is unavailable, explain the failure.", ) return {"output": str(agent(case.input))} experiment = ChaosExperiment( cases=chaos_cases, evaluators=[OutputEvaluator( rubric="Use returned order data or acknowledge a tool failure. Do not invent orders." )], ) report = experiment.run_evaluations(task=run_case) report.run_display() ``` Does the agent recover when `get_order_history` times out? When `get_order_history` returns a network error? Chaos testing lets you find out while you build, not after customers do. ## Red teaming Red teaming tests whether your agent resists adversarial pressure: jailbreaks, data exfiltration attempts, excessive agency. The generator inspects your agent’s tools and system prompt and produces targeted attacks; the strategy controls how those attacks escalate across turns. ```python from create_agent import create_customer_service_agent from strands_evals.redteam import ( AdversarialCaseGenerator, CrescendoStrategy, RedTeamExperiment, ) cases = AdversarialCaseGenerator().generate_cases( agent=create_customer_service_agent(), risk_categories=["data_exfiltration", "excessive_agency"], num_cases=3, ) experiment = RedTeamExperiment( cases=cases, attack_strategies=[CrescendoStrategy()], ) # fresh agent per case so attacks don't bleed across runs report = experiment.run_evaluations(agent_factory=create_customer_service_agent) ``` Red teaming probes the tested guardrails under adversarial conditions. Passing these cases does not prove resistance to every attack. ## Best practices - Evaluate multi-turn interactions, not just single turns - Combine LLM judges with deterministic assertions - Wire evals into CI/CD to catch regressions automatically - Evolve your eval suite as new failure modes emerge - Use a different model for evaluation than for generation - Use chaos testing to verify resilience before production - Run red team experiments to validate guardrails ## Resources - 📖 [Strands Evals Quickstart](/docs/user-guide/evals-sdk/quickstart/index.md) - 📖 [Blog: Reduced cost, better isolation, and more resilience](https://strandsagents.com/blog/reduced-cost-better-isolation-more-resilience/) - 🛠️ [Strands Evals on GitHub](https://github.com/strands-agents/evals) Source: https://strandsagents.com/docs/learning/evaluating-agents/index.md --- ## Lesson 3: Give your agent tools using MCP Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=Pucmy0GZkeI&list=PLDzwjhH-4yhU&index=3)* *Code for this lesson: [`samples/03-mcp-tools`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/03-mcp-tools)* ## Where tools come from Tools give agents the ability to take actions and access information beyond what’s in the model’s training data. There isn’t one way to define a tool. Tools can come from different places, and they all sit side by side in the same agent’s `tools` list: - **Custom tools** you write yourself with the `@tool` decorator (you saw this in lesson 1) - **Vended tools** that ship with the SDK in `strands.vended_tools`: file editing, shell, web fetch (requires the `web-fetch` extra) - **MCP servers** that expose tools over a standard protocol, whether you run them or someone else does - **Other agents**, which you’ll see in lesson 10 when we cover agents as tools MCP is particularly powerful because it lets you connect agents to externally managed tool servers. The agent discovers available tools dynamically at runtime rather than having them hardcoded. ## MCP (Model Context Protocol) MCP is an open standard that gives agents a consistent way to discover and interact with external capabilities (GitHub, AWS, databases, browser tools) through a standard protocol. Servers can run locally as a subprocess (stdio) or remotely over HTTP. ```python from mcp import stdio_client, StdioServerParameters from strands import Agent from strands.tools.mcp import MCPClient # Remote MCP server (Streamable HTTP): pass the URL and Strands builds the transport aws_knowledge = MCPClient( url="https://knowledge-mcp.global.api.aws", prefix="knowledge", ) # Local MCP server (stdio) aws_pricing = MCPClient( lambda: stdio_client(StdioServerParameters( command="uvx", args=["awslabs.aws-pricing-mcp-server@latest"], env={"AWS_REGION": "us-east-1"} )), prefix="pricing" ) agent = Agent(tools=[aws_knowledge, aws_pricing], system_prompt="You are an AWS architect.") agent("What AWS services should I use for a serverless FastAPI backend?") ``` 📂 [mcp\_http.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/03-mcp-tools/mcp_http.py) The `prefix` argument namespaces tool names from each server so two servers exposing a tool with the same name don’t collide. ## Mixing MCP tools with vended tools An MCP client sits in the `tools` list alongside any other tool. Here a coding assistant gets AWS documentation through MCP plus local file and shell access through vended tools: ```python from strands import Agent from strands.tools.mcp import MCPClient from strands.vended_tools import file_editor, shell # Connect to the AWS MCP server (streamable HTTP) aws_mcp = MCPClient(url="https://aws-mcp.us-east-1.api.aws/mcp") SYSTEM_PROMPT = """You are a coding assistant with AWS expertise. Use the AWS MCP tools to look up documentation, architecture patterns, and service details when answering questions about building on AWS. Be concise and actionable in your recommendations.""" agent = Agent( tools=[aws_mcp, file_editor, shell], system_prompt=SYSTEM_PROMPT, ) agent("I need to build a serverless FastAPI backend with authentication " "and file uploads. What AWS services should I use and how should " "I architect this?") ``` 📂 [mcp\_coding\_agent.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/03-mcp-tools/mcp_coding_agent.py) ## Tool filtering Too many tools leads to worse tool selection, hallucinated tool names, and wasted context. In production, restrict which tools an agent can access using `tool_filters` and only expose what the agent actually needs: ```python from strands import Agent from strands.tools.mcp import MCPClient # Filter to only documentation tools filtered_mcp = MCPClient( url="https://aws-mcp.us-east-1.api.aws/mcp", tool_filters={ "allowed": ["aws___search_documentation", "aws___read_documentation"] }, ) agent = Agent( tools=[filtered_mcp], system_prompt="You are an AWS documentation assistant.", ) ``` 📂 [tool\_filtering.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/03-mcp-tools/tool_filtering.py) ## Controlling tool execution By default Strands runs multiple tool calls from a single model turn concurrently. When tools have side effects that depend on each other, switch to a sequential executor: ```python from strands import Agent, tool from strands.tools.executors import SequentialToolExecutor @tool def step_one() -> str: """Perform the first step of the workflow.""" return "Step one complete - file created." @tool def step_two() -> str: """Perform the second step that depends on step one.""" return "Step two complete - file processed." agent = Agent( tools=[step_one, step_two], tool_executor=SequentialToolExecutor(), ) agent("Run step one and then step two.") ``` 📂 [tool\_executor.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/03-mcp-tools/tool_executor.py) ## The security boundary Tools execute with the permissions of the host process. If you give an agent the `shell` tool, you’ve given it access to your machine. With MCP, you’re handing your agent tools that someone else controls. Be thoughtful about what you connect. For sandboxed execution, look at [Strands Shell](https://github.com/strands-agents/shell), which gives agents isolated filesystem and network access. ## Resources - 📖 [Tools Overview](/docs/user-guide/sdk/tools/index.md) - 📖 [MCP Tools](/docs/user-guide/sdk/tools/mcp-tools/index.md) - 📖 [Custom Tools](/docs/user-guide/sdk/tools/custom-tools/index.md) - 🛠️ [Strands Shell](https://github.com/strands-agents/shell) Source: https://strandsagents.com/docs/learning/give-your-agent-tools-using-mcp/index.md --- ## Lesson 1: How agents really work Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=ZpXWGjISMs8&list=PLDzwjhH-4yhU)* *Code for this lesson: [`samples/01-agent-loop`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/01-agent-loop)* ## Why agents? Models are stateless. They process one request, produce a completion, and forget. They can’t take action, access live data, or coordinate multi-step workflows alone. Agents solve this by wrapping a model in a runtime system that gives it tools, memory, and a reasoning loop. ## The agent loop ![Agent Loop Flow](/_astro/agent-loop-flow.CgHBgQw3_nJnxY.webp) 1. Model receives **context** (system prompt + user input + tool list + history) 2. Model **reasons** and decides whether to call a tool 3. Tool **executes**, result feeds back into context 4. Loop **repeats** until the task is complete ## Agent = model + harness The **harness** is the system that surrounds the model and turns it into an agent. It handles the agent loop, tool execution, context management, memory, lifecycle control, observability, and verification. Together, **model + harness = agent.** ## Three layers of engineering **Prompt Engineering:** Instructions and constraints sent to the model **Context Engineering:** What information enters the context window, when, and how **Harness Engineering:** The runtime system orchestrating everything ## Strands Harness SDK The Strands Harness SDK is an open-source SDK for building agent harnesses. It provides composable primitives like tools, context management, lifecycle hooks, memory, sessions, evals, and observability that you assemble into whatever system your use case requires. **Design philosophy:** Let the model drive. You define the environment and boundaries; the model reasons through the task. ## Code: a simple agent This is already a working agent with a loop, just without tools. ```python from strands import Agent agent = Agent() response = agent("What are the key differences between REST and GraphQL APIs?") print(response) ``` 📂 [simple\_agent.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/01-agent-loop/simple_agent.py) ## Code: agent with tools Changed since recording The samples use SDK-vended `file_editor`, `shell`, and `web_fetch` instead of the older community-tool imports. Web fetching needs the optional dependencies: `pip install "strands-agents[web-fetch]"`. Use the imports shown below. ```python from strands import Agent, tool from strands.vended_tools import file_editor from strands.vended_tools.web_fetch import web_fetch @tool def query_product_database(query: str) -> str: """Query the internal product database for inventory and pricing information. Args: query: Search query for products (e.g., "wireless headphones", "USB-C hub") """ products = { "wireless headphones": "SKU-WH100: Wireless Headphones Pro - $79.99, 142 in stock, 4.5★ rating, launched 2025-03", "usb-c hub": "SKU-UC200: USB-C Hub 7-in-1 - $45.00, 89 in stock, 4.2★ rating, launched 2024-11", "mechanical keyboard": "SKU-MK300: Mechanical Keyboard RGB - $149.99, 23 in stock, 4.8★ rating, launched 2025-01", "noise cancelling": "SKU-NC400: Noise Cancelling Earbuds - $129.99, 67 in stock, 4.6★ rating, launched 2025-05", } key = query.lower() matches = [info for product_key, info in products.items() if product_key in key] if matches: return "\n".join(matches) return f"No products found matching '{query}'. Available: wireless headphones, usb-c hub, mechanical keyboard, noise cancelling" SYSTEM_PROMPT = """You are a product research analyst. You help the team understand market positioning by comparing competitor pricing with our internal catalog. When given a research task: 1. Use web_fetch to gather public market data from the web 2. Use query_product_database to check our internal pricing and inventory 3. Write a brief competitive analysis and save it to report.md using file_editor""" agent = Agent( tools=[web_fetch, file_editor, query_product_database], system_prompt=SYSTEM_PROMPT, ) result = agent("Research what wireless headphones are trending on the market and compare it against our offerings. " "Write a short competitive positioning summary and save it to report.md") ``` Key concepts: - **`@tool` decorator** turns any Python function into an agent-callable tool - **Docstrings** become the tool description the model sees - **Type hints** auto-generate the input schema - **System prompt** defines agent identity and behavior After a run, `agent.messages` shows every step the loop took: user turns, assistant text, tool calls, and tool results. This is the first place to look when you want to know why the agent did what it did. 📂 [agent\_with\_tools.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/01-agent-loop/agent_with_tools.py) ## Out of the box components Strands also ships preconfigured components that give you a capable agent out of the box: - **Vended tools** for file operations, shell access, and web fetching - **Automatic context management** that offloads large results, compresses old messages, and fires proactive compression before the window fills - **Plugin system** for extending behavior You can start with these defaults and customize from there, or build from scratch using the primitives. ```python from strands import Agent from strands.models import BedrockModel from strands.vended_tools import file_editor, shell from strands.vended_tools.web_fetch import web_fetch agent = Agent( model=BedrockModel( model_id="us.anthropic.claude-sonnet-5", ), # Vended tools for file ops, shell, and web fetching tools=[file_editor, shell, web_fetch], # Auto context management: offloads large tool results, compresses old # messages into summaries, and fires proactive compression at 85% usage. context_manager="auto", ) # Give it a research task agent("Research the current state of AI agent deployment patterns in production, including common architectures, challenges teams face, and best practices. Write a summary to report.md") ``` 📂 [agent\_with\_defaults.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/01-agent-loop/agent_with_defaults.py) ## Resources - 📖 [Getting Started](/docs/user-guide/sdk/quickstart/python/index.md) - 📖 [Agent Loop](/docs/user-guide/sdk/agents/agent-loop/index.md) - 📖 [Tools](/docs/user-guide/sdk/tools/index.md) - 📖 [Custom Tools](/docs/user-guide/sdk/tools/custom-tools/index.md) - 📖 [Connect your AI coding assistant (Strands MCP Server)](/docs/user-guide/sdk/quickstart/python/index.md#connect-your-ai-coding-assistant) Source: https://strandsagents.com/docs/learning/how-agents-really-work/index.md --- ## Lesson 7: Improve agent reliability with Strands steering Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=5rwTCUFV4Ak&list=PLDzwjhH-4yhU&index=7)* *Code for this lesson: [`samples/07-steering`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/07-steering)* ## Keep agents on the rails Instructions in prompts aren’t always reliably followed, especially as context grows. Steering lets you inspect and influence agent behavior at runtime. A steering handler looks at what the agent is about to do and returns one of three outcomes: **Proceed**, **Guide** (send feedback to the model and let it try again), or **Interrupt** (pause for a human). In a published benchmark, Strands steering hooks achieved a [100% pass rate across 600 evaluation runs](https://strandsagents.com/blog/steering-accuracy-beats-prompts-workflows/), compared to 82.5% for prompt-based instructions and 80.8% for graph-based workflows. ## Two types of steering | Type | How It Works | Use Case | | --- | --- | --- | | **Deterministic** (`SteeringHandler`) | Python logic inspects the events ledger | Enforcing workflow ordering, validating parameters | | **LLM-based** (`LLMSteeringHandler`) | A second agent judges the output | Tone/policy compliance, nuanced quality checks | ## Deterministic steering: enforce the refund workflow Our customer service agent should never process a refund without first looking up the customer and checking their order history. Rather than hoping the prompt gets followed, a `SteeringHandler` checks the ledger of previous tool calls before `process_refund` is allowed to run: ```python from strands.vended_plugins.steering import ( SteeringHandler, Proceed, Guide, ToolSteeringAction, LedgerProvider, ) class RefundWorkflowHandler(SteeringHandler): name = "refund-workflow" def __init__(self): super().__init__(context_providers=[LedgerProvider()]) async def steer_before_tool(self, *, agent, tool_use, **kwargs) -> ToolSteeringAction: if tool_use.get("name") != "process_refund": return Proceed(reason="Not a refund operation") ledger = self.steering_context.data.get("ledger", {}) tool_calls = ledger.get("tool_calls", []) # Must look up customer first customer_verified = any( c["tool_name"] == "lookup_customer" and c["status"] == "success" for c in tool_calls ) if not customer_verified: return Guide(reason="You must look up the customer first.") # Must check order history order_checked = any( c["tool_name"] == "get_order_history" and c["status"] == "success" for c in tool_calls ) if not order_checked: return Guide(reason="You must check order history first.") return Proceed(reason="Refund workflow validated") ``` When the handler returns `Guide`, the tool call is blocked and the reason is fed back to the model, which then does the missing step and tries again. ## LLM-based steering: tone guardrail Some rules can’t be expressed as Python conditionals. “Don’t overpromise timelines” requires judgment. An `LLMSteeringHandler` uses a second model to evaluate the response against a policy and guide the agent if it falls short: ```python from strands.vended_plugins.steering import LLMSteeringHandler class ToneGuardrailHandler(LLMSteeringHandler): name = "tone-guardrail" def __init__(self): super().__init__( system_prompt="""Evaluate the customer service response against these policies: - Don't overpromise timelines - Acknowledge customer frustration - Don't offer unauthorized compensation - Keep responses concise If violated, provide specific guidance on what to fix.""" ) ``` ## Composing everything into an agent Steering handlers are plugins, so they stack alongside skills and any other plugin: ```python from strands import Agent agent = Agent( tools=[lookup_customer, get_order_history, process_refund], plugins=[ skills_plugin, # On-demand workflow instructions RefundWorkflowHandler(), # Deterministic: enforce refund steps tone_handler, # LLM-based: enforce communication quality ], system_prompt=SYSTEM_PROMPT, ) ``` 📂 [customer\_service\_steering.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/07-steering/customer_service_steering.py) · [steering\_handlers.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/07-steering/steering_handlers.py) ## Resources - 📖 [Steering](/docs/user-guide/sdk/agents/interventions/steering/index.md) - 📖 [Blog: Steering accuracy beats prompts and workflows](https://strandsagents.com/blog/steering-accuracy-beats-prompts-workflows/) Source: https://strandsagents.com/docs/learning/improve-agent-reliability-with-strands-steering/index.md --- ## Lesson 12: Multi-agent patterns: agent swarms Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=yG-5rIJoh_8&list=PLDzwjhH-4yhU&index=12)* *Code for this lesson: [`samples/12-swarms`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/12-swarms)* ## Agent swarms In a swarm, agents hand off to each other autonomously with no predefined structure. There’s no orchestrator deciding who runs next and no graph fixing the order. The execution path emerges from what each agent discovers. This is the right fit when you can’t draw the workflow ahead of time: debugging an incident, open-ended research, or any problem where the next step depends on what the last step found. Run this from `samples/12-swarms` to import the mock debugging tools: ```python from strands import Agent from strands.multiagent import Swarm from debugging_swarm import ( check_application_logs, check_metrics_dashboard, check_recent_deployments, check_infrastructure_status, ) triage = Agent( name="triage", system_prompt="Initial assessment. Hand off to the relevant specialist.", ) log_analyst = Agent( name="log_analyst", system_prompt="Analyze application logs. Hand off if you find infra/deployment issues.", tools=[check_application_logs], ) metrics_analyst = Agent( name="metrics_analyst", system_prompt="Analyze system metrics. Hand off based on findings.", tools=[check_metrics_dashboard], ) deployment_reviewer = Agent( name="deployment_reviewer", system_prompt="Review recent deployments and infrastructure changes.", tools=[check_recent_deployments, check_infrastructure_status], ) debugging_swarm = Swarm( [triage, log_analyst, metrics_analyst, deployment_reviewer], entry_point=triage, max_handoffs=10, max_iterations=10, execution_timeout=300.0, node_timeout=120.0, repetitive_handoff_detection_window=6, repetitive_handoff_min_unique_agents=2, ) result = debugging_swarm( "Payment service returning 500 errors for 25% of requests. Started 30 min ago." ) ``` 📂 [debugging\_swarm.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/12-swarms/debugging_swarm.py) ## How swarms differ - **Handoff is a full transfer of control**, not a function call. When `log_analyst` hands off to `deployment_reviewer`, the log analyst is done; it doesn’t get the result back. - **Agents share accumulated context.** Each agent sees what the previous agents found, so the investigation builds on itself. - **Strands injects a `handoff_to_agent` tool automatically.** You don’t write handoff logic; each agent’s system prompt tells it when to hand off, and the model decides. ## Safety controls Because nothing structural stops a swarm from bouncing between agents, always configure limits. The SDK has default limits; configure explicit limits for your workload. | Setting | Purpose | | --- | --- | | `max_handoffs` | Total handoff cap | | `max_iterations` | Total agent execution cap | | `execution_timeout` | Wall-clock time limit for the entire swarm | | `node_timeout` | Time limit per agent turn | | `repetitive_handoff_detection_window` | Detect ping-pong loops between the same few agents | ## Composing patterns The three multi-agent patterns nest: a swarm can be a node in a graph, a graph can contain agents-as-tools, and an agent-as-tool can internally run a graph. Start with the simplest pattern that fits your coordination needs and compose up from there. | Pattern | Structure | Use When | | --- | --- | --- | | **Agents as Tools** | Hub-and-spoke. Orchestrator calls specialists | Clear manager-specialist relationship, isolated context | | **Graph** | Directed graph with explicit edges | You can draw the workflow on a whiteboard | | **Swarm** | Autonomous handoffs, no predefined structure | The team needs to figure it out together | ## Resources - 📖 [Swarm](/docs/user-guide/sdk/multi-agent/swarm/index.md) - 📖 [Multi-Agent Patterns Overview](/docs/user-guide/sdk/multi-agent/multi-agent-patterns/index.md) - 📖 [Agents as Tools](/docs/user-guide/sdk/multi-agent/agents-as-tools/index.md) - 📖 [Graph](/docs/user-guide/sdk/multi-agent/graph/index.md) Source: https://strandsagents.com/docs/learning/multi-agent-patterns-agent-swarms/index.md --- ## Lesson 10: Multi-agent patterns: agents as tools Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=_QcD5KBe3ZQ&list=PLDzwjhH-4yhU&index=10)* *Code for this lesson: [`samples/10-agents-as-tools`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/10-agents-as-tools)* ## Three multi-agent patterns Strands provides three composable multi-agent patterns. Each solves a different coordination problem, and they can nest inside each other. This lesson covers the first; the next two lessons cover graphs and swarms. | Pattern | Structure | Use When | | --- | --- | --- | | **Agents as Tools** | Hub-and-spoke. Orchestrator calls specialists | Clear manager-specialist relationship, isolated context | | **Graph** | Directed graph with explicit edges | You can draw the workflow on a whiteboard | | **Swarm** | Autonomous handoffs, no predefined structure | The team needs to figure it out together | ## Agents as tools The simplest multi-agent pattern: one orchestrator agent calls specialist agents as tools. The orchestrator stays in control, decides when to delegate, and synthesizes the results. Each specialist gets its own isolated context window. That’s the key benefit: a specialist can run noisy tools (log readers, web fetchers, verbose APIs) and process thousands of tokens of raw output, then hand back only a short conclusion. The orchestrator’s context stays clean. ### Pass the agent directly Changed since recording The research tool now comes from `strands.vended_tools.web_fetch`. Run `pip install "strands-agents[web-fetch]"` before running the sample. The direct-agent and `@tool` composition patterns still work. The quickest way. Put the agent in another agent’s `tools` list and Strands wraps it automatically, using the agent’s `name` and `description` as the tool spec: ```python from strands import Agent from strands.vended_tools.web_fetch import web_fetch researcher = Agent( name="researcher", system_prompt="You are a research specialist. Find factual information.", tools=[web_fetch], ) writer = Agent( name="writer", system_prompt="You are a technical writer. Use the researcher to gather facts.", tools=[researcher], # Pass agent directly as a tool ) writer("Research the FastAPI GitHub repo and write a 3-sentence summary.") ``` ### Wrap with `@tool` For full control over the prompt, model selection, and how results are returned, wrap the specialist in a `@tool` function: ```python from strands import Agent, tool from strands.models.bedrock import BedrockModel from strands.vended_tools.web_fetch import web_fetch orchestrator_model = BedrockModel(model_id="us.anthropic.claude-opus-5") specialist_model = BedrockModel(model_id="us.anthropic.claude-sonnet-5") @tool def research_assistant(query: str, depth: str = "normal") -> str: """Research a topic and return sourced findings. Args: query: The research question depth: How thorough - "quick", "normal", or "deep" """ research_agent = Agent( model=specialist_model, system_prompt=f"You are a research specialist. Research depth: {depth}.", tools=[web_fetch], callback_handler=None, # Run silently ) response = research_agent(query) return str(response) writer = Agent( model=orchestrator_model, system_prompt="You are a technical writer. Use the research assistant.", tools=[research_assistant], ) ``` 📂 [agent\_as\_tool.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/10-agents-as-tools/agent_as_tool.py) Data flow: the orchestrator sends a string, the specialist runs its own loop, and returns a string. Context resets between calls, so each delegation starts clean. ## Key concepts - **The docstring is the routing logic.** It tells the orchestrator when to delegate. The model routes based on tool descriptions; you never write an `if` statement. - **Agent isolation.** Each sub-agent has its own context window, model, and tools. One agent’s context doesn’t leak into another’s. - **Orchestrator control.** The orchestrator decides when to call the specialist, what to ask, and how to use the response. It’s a function call, not a handoff. - **Model heterogeneity.** Use a stronger model for the orchestrator (which reasons about what to delegate) and a cheaper model for specialists (which do focused work). - **Silent sub-agents.** `callback_handler=None` on sub-agents suppresses their streaming output so only the orchestrator streams to the user. Use this pattern when you have clearly separable domains, when you want one agent synthesizing everything, or when you need request/response semantics between agents. ## Resources - 📖 [Agents as Tools](/docs/user-guide/sdk/multi-agent/agents-as-tools/index.md) - 📖 [Multi-Agent Patterns Overview](/docs/user-guide/sdk/multi-agent/multi-agent-patterns/index.md) Source: https://strandsagents.com/docs/learning/multi-agent-patterns-agents-as-tools/index.md --- ## Lesson 11: Multi-agent patterns: graph workflows Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=jDeV2V5fJUQ&list=PLDzwjhH-4yhU&index=11)* *Code for this lesson: [`samples/11-graphs`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/11-graphs)* ## Deterministic control over execution Graphs and workflows give you deterministic control over multi-agent execution. Unlike agents-as-tools, where the orchestrator decides the flow dynamically, these patterns let you define the exact execution order, dependencies, and parallel paths upfront. Use them when you can draw the workflow on a whiteboard. ## Graph Changed since recording The graph API in this lesson still works. The researcher now uses the SDK web-fetch tool, which needs `pip install "strands-agents[web-fetch]"`. Follow the current import below when running the graph example. Each node is a full agent; edges express dependencies. A node executes when all its incoming edges are satisfied, and the graph resolves what runs in parallel and what waits. ```python from strands import Agent from strands.multiagent import GraphBuilder from strands.vended_tools.web_fetch import web_fetch researcher = Agent( name="researcher", system_prompt="Gather comprehensive information from the web.", tools=[web_fetch], ) analyst = Agent( name="analyst", system_prompt="Identify patterns, trends, and key insights from research.", ) summarizer = Agent( name="summarizer", system_prompt="Condense raw research into concise key points.", ) report_writer = Agent( name="report_writer", system_prompt="Synthesize analysis and summaries into a final report.", ) builder = GraphBuilder() builder.add_node(researcher, "research") builder.add_node(analyst, "analysis") builder.add_node(summarizer, "summarize") builder.add_node(report_writer, "report") builder.add_edge("research", "analysis") builder.add_edge("research", "summarize") # analyst + summarizer run in parallel builder.add_edge("analysis", "report") builder.add_edge("summarize", "report") # report waits for both builder.set_execution_timeout(600) graph = builder.build() result = graph("Research the impact of AI on healthcare") ``` 📂 [basic\_graph.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/11-graphs/basic_graph.py) Data flow: entry nodes receive the original task. Downstream nodes receive the original task plus labeled outputs from their dependencies. Use `invocation_state` for metadata (user IDs, feature flags) that shouldn’t be exposed to the models. Common shapes: sequential pipelines, parallel fan-out (as above), conditional branching, and cyclic feedback loops. If you build a cycle, set `set_max_node_executions` so it can’t loop forever. ## Key concepts - **Nodes** are agents, other multi-agent systems, or `MultiAgentNode` implementations. They execute when all incoming edges are satisfied. - **Edges** define dependencies. An edge from A to B means B waits for A. - **Parallel fan-out**: nodes without dependencies on each other run concurrently. - **Context passing**: each step receives the output of its predecessors. - **When to use**: pipelines with known structure, fan-out/fan-in, workflows that need guaranteed execution order, and processes requiring audit trails. ## Comparison | Pattern | Flow Control | Best For | | --- | --- | --- | | Agents as Tools | Orchestrator decides | Separable domains, synthesis | | Graphs | Defined by edges | Known pipelines, parallelism | | Swarms | Agents decide | Unknown sequences, exploration | ## Resources - 📖 [Graph](/docs/user-guide/sdk/multi-agent/graph/index.md) - 📖 [Workflow](/docs/user-guide/sdk/multi-agent/workflow/index.md) - 📖 [Multi-Agent Patterns Overview](/docs/user-guide/sdk/multi-agent/multi-agent-patterns/index.md) Source: https://strandsagents.com/docs/learning/multi-agent-patterns-graph-workflows/index.md --- ## Lesson 9: Persistent memory with session managers Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=HqGIYRXo6WE&list=PLDzwjhH-4yhU&index=9)* *Code for this lesson: [`samples/09-persistent-memory`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/09-persistent-memory)* ## Persisting conversation history Session managers persist conversation history and agent state across runs. Without them, everything resets when the process stops. They’re implemented as hook providers, so persistence is just another harness behavior layered in through hooks. ## File session manager (record-based) Run these examples from `samples/09-persistent-memory`. The record-based approach persists each message individually. It’s still supported for existing sessions and available for existing record-based Graph/Swarm sessions. ```python from strands import Agent from strands.session.file_session_manager import FileSessionManager from customer_service_tools import lookup_customer, get_order_history, process_refund SYSTEM_PROMPT = "Help customers with their orders using the available tools." session_manager = FileSessionManager( session_id="customer-session-001", storage_dir="./sessions", ) agent = Agent( tools=[lookup_customer, get_order_history, process_refund], system_prompt=SYSTEM_PROMPT, context_manager="auto", session_manager=session_manager, ) ``` 📂 [file\_session\_manager.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/09-persistent-memory/file_session_manager.py) ## S3 session manager (record-based) Same record-based approach, backed by S3 instead of local disk: ```python from strands import Agent from strands.session.s3_session_manager import S3SessionManager session_manager = S3SessionManager( session_id="customer-session-001", bucket="my-agent-sessions", prefix="customer-service/", region_name="us-east-1", ) agent = Agent(session_manager=session_manager) ``` 📂 [s3\_session\_manager.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/09-persistent-memory/s3_session_manager.py) ## Snapshot session manager The `FileSessionManager` and `S3SessionManager` examples shown in the video are still valid. `SnapshotSessionManager` is an optional alternative for saving and restoring a conversation. You do not need to switch to follow this lesson. See the [session management docs](/docs/user-guide/sdk/agents/session-management/index.md) for setup and examples. `SnapshotSessionManager` saves the session state together, instead of saving each message as a separate record. ```python from strands import Agent from strands.session import SnapshotSessionManager from strands.storage import LocalFileStorage from customer_service_tools import lookup_customer, get_order_history, process_refund SYSTEM_PROMPT = "Help customers with their orders using the available tools." session_manager = SnapshotSessionManager( session_id="customer-session-001", storage=LocalFileStorage("./sessions"), ) agent = Agent( tools=[lookup_customer, get_order_history, process_refund], system_prompt=SYSTEM_PROMPT, context_manager="auto", session_manager=session_manager, ) ``` Persistence happens automatically: agent state is saved after each invocation by default. Use `save_latest_on="message"` to save after every message instead. For production, swap `LocalFileStorage` for `S3Storage`: ```python from strands.storage import S3Storage session_manager = SnapshotSessionManager( session_id="customer-session-001", storage=S3Storage(bucket="my-agent-sessions", prefix="production/"), ) ``` 📂 [snapshot\_session\_manager.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/09-persistent-memory/snapshot_session_manager.py) ## When to use which | Manager | Best For | | --- | --- | | `SnapshotSessionManager` | Save and restore a single agent, Graph/Swarm, or Bidi session. | | `FileSessionManager` | Existing record-based sessions; retains their storage format. | | `S3SessionManager` | Same as File but with S3 for cross-machine access. | ## Sessions, memory, and storage Memory stores let an agent use saved information, such as customer preferences, in future conversations. `MemoryManager` connects the agent to those stores so it can retrieve that information. You can add this alongside your session manager; it does not replace the examples in this lesson. See the [memory docs](/docs/user-guide/sdk/memory/overview/index.md) for an introduction, or [configure how your agent reads and writes memories](/docs/user-guide/sdk/memory/managing-memory/index.md). Session managers are one of three related pieces, and it helps to keep them straight: - **Session manager**: persists the conversation so the agent can resume where it left off. Scoped to one session. - **Memory manager**: durable knowledge that carries across sessions (user preferences, facts, decisions) without replaying old conversations. Backed by one or more **memory stores**. - **Storage**: the byte-level backend underneath both. `LocalFileStorage`, `S3Storage`, and community backends implement the same `Storage` interface, so a session manager, a memory store, and the context manager’s stash can all share one backend. Memory is opt-in and separate from sessions. Attach a `MemoryManager` with a store and the agent gets recall (a tool to search what it knows) and injection (relevant memories folded into the prompt automatically): ```python from strands import Agent from strands.memory import MemoryManager from strands.vended_memory_stores.test_memory_store import TestMemoryStore # Zero-setup store for prototyping; swap for a production store later store = TestMemoryStore(name="customer-service") agent = Agent( session_manager=session_manager, # this conversation memory_manager=MemoryManager(stores=[store]), # knowledge across conversations ) ``` ## Production storage: DynamoDB Because sessions, memory, and offloaded context all sit on the `Storage` interface, one production backend can serve all of them. [Strands DynamoDB Storage](https://github.com/aws/strands-dynamodb-storage) is an AWS-maintained backend that fits agent workloads well: serverless, single-digit-millisecond reads, native TTL so stale sessions expire themselves, and vector search on the same table for semantic memory. Install `strands-dynamodb-storage` separately and provision its table. Set it once at the agent level and every subsystem that persists bytes inherits it under its own namespace: ```python from strands import Agent from strands.session import SnapshotSessionManager from strands_dynamodb_storage import DynamoDBStorage storage = DynamoDBStorage("agent-storage", region_name="us-east-1") agent = Agent( tools=[lookup_customer, get_order_history, process_refund], system_prompt=SYSTEM_PROMPT, context_manager="auto", storage=storage, # shared backend session_manager=SnapshotSessionManager("customer-session-001"), # inherits storage ) ``` You own the table (a string `pk` partition key and string `sk` sort key is all it needs), for basic byte storage. Optional S3 offload and vector search need additional resources and permissions; see the backend’s setup instructions. ## More backends The integrations catalog lists additional session managers, memory stores, and storage backends. They implement the same interfaces, so you can swap them in without changing agent code. | Integration | What It Is | | --- | --- | | [Strands DynamoDB Storage](https://github.com/aws/strands-dynamodb-storage) | `Storage` backend on Amazon DynamoDB, with TTL, S3 offload, and vector search | | [AgentCore Memory](/docs/integrations/session-managers/agentcore-memory/index.md) | Session manager backed by Amazon Bedrock AgentCore Memory, with long-term recall | | [Valkey Session Manager](/docs/integrations/session-managers/strands-valkey-session-manager/index.md) | Session manager on Valkey (Redis-compatible) for fast distributed storage | | [Memory stores](/docs/integrations/memory-stores/overview/index.md) | Community-built `MemoryStore` backends for the `MemoryManager` | | [Storage backends](/docs/integrations/storage/overview/index.md) | Community-built `Storage` implementations | ## Resources - 📖 [Session Management](/docs/user-guide/sdk/agents/session-management/index.md) - 📖 [Memory](/docs/user-guide/sdk/memory/overview/index.md) - 📖 [Storage](/docs/user-guide/sdk/storage/index.md) - 📖 [Control what your agent remembers](/docs/user-guide/sdk/memory/managing-memory/index.md) Source: https://strandsagents.com/docs/learning/persistent-memory-with-session-managers/index.md --- ## Lesson 2: Switching model providers Before you follow along This video is a snapshot in time. Some APIs and examples have changed since recording. Follow the code on this page, and look for “Changed since recording” notices below. *[Watch on YouTube](https://www.youtube.com/watch?v=NAEX4ORLkbQ&list=PLDzwjhH-4yhU&index=2)* *Code for this lesson: [`samples/02-model-providers`](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/02-model-providers)* ## Model choice is an architecture decision Different models have different strengths, costs, latency characteristics, and tool-use behavior. Strands abstracts providers behind a common interface so your agent code stays the same regardless of the underlying model. Your tools, system prompt, and orchestration logic don’t change when you swap the model. ## Configuring providers All providers follow the same pattern: instantiate a model class, pass it to the agent. ```python from strands import Agent from strands.models import BedrockModel from strands.models.anthropic import AnthropicModel from strands.models.ollama import OllamaModel from strands.models.openai import OpenAIModel import os # Amazon Bedrock (default if no model specified) bedrock_model = BedrockModel( model_id="us.anthropic.claude-opus-5" ) # Anthropic direct API anthropic_model = AnthropicModel( client_args={"api_key": os.environ["ANTHROPIC_API_KEY"]}, model_id="claude-sonnet-5", max_tokens=1024, ) # OpenAI openai_model = OpenAIModel( client_args={"api_key": os.environ["OPENAI_API_KEY"]}, model_id="gpt-4o", params={"max_tokens": 1000, "temperature": 0.7}, ) # Local with Ollama (no cloud APIs needed) ollama_model = OllamaModel( host="http://localhost:11434", model_id="gemma4:latest", ) # Use any provider. Agent code stays identical. agent = Agent(model=ollama_model) agent("Explain the agent loop in one paragraph.") ``` 📂 [model\_providers.py](https://github.com/aws-samples/sample-building-with-strands-course/tree/main/samples/02-model-providers/model_providers.py) | Provider | Install | Auth | | --- | --- | --- | | Bedrock (default) | `pip install strands-agents` | AWS credentials configured | | Anthropic | `pip install "strands-agents[anthropic]"` | `ANTHROPIC_API_KEY` | | OpenAI | `pip install "strands-agents[openai]"` | `OPENAI_API_KEY` | | Ollama (local) | `pip install "strands-agents[ollama]"` | None, runs on your machine | ## Multi-model architectures In sophisticated systems, different agents use different models: - Fast/cheap model for lightweight classification - Strong reasoning model for orchestration - Specialized model for code generation - A different provider entirely for evaluation/verification (avoids same-model bias) ## Ollama setup Ollama lets you run models entirely on your machine. Useful for development, offline use, or avoiding API costs. ```bash brew install ollama ollama serve ollama pull gemma4:latest ``` ## Resources - 📖 [Model Providers](/docs/user-guide/sdk/model-providers/index.md) - 📖 [Getting Started](/docs/user-guide/sdk/quickstart/python/index.md) - 📂 [Course Code Repository](https://github.com/aws-samples/sample-building-with-strands-course) Source: https://strandsagents.com/docs/learning/switching-model-providers/index.md --- ## MCP server configuration Each MCP server the agent uses is one `[mcp.]` table in `box.toml`. A stdio server is a program that the box starts in its own sandbox. An http server runs somewhere else, and the agent reaches it through the box’s egress gateway. Audience: an operator with a working box from [getting started](../../quickstart/index.md) who adds an MCP server to it. To let the agent use the server, write its rules as in [write policy for an MCP server](../write-mcp-policy/index.md). ## Example A stdio server and an http server: ```toml [mcp.fetch] type = "stdio" command = ["mcp-server-fetch"] [mcp.fetch.filesystem] read = ["~/.local/share/uv/tools/mcp-server-fetch", "~/.local/share/uv/python"] [mcp.github] type = "http" destinations = ["api.githubcopilot.com"] secret.ref = "env://GITHUB_MCP_TOKEN" ``` The table’s name, `fetch` or `github`, is the server name. Policy reads it as `context.input.server`. ## `[mcp.]`, `type = "stdio"` | Key | Type | Default | Meaning | | --- | --- | --- | --- | | `type` | string | required | `"stdio"`. | | `command` | string array | required | Element 0 is the program, and the rest are its arguments. The box places an alias named for the program in its `bin/`, on the agent’s `PATH`. Arguments match exactly unless you enable [argument wildcards](#argument-wildcards). | | `workspace` | path | the agent’s workspace | The server’s initial working directory. | | `env` | table | empty | Variables the server receives. The server also receives `PATH` and `HOME` from the host OS’s shell that runs `box run`, unless `env` sets them, and a placeholder for each `env://` credential. | | `filesystem` | table | empty | The paths the server’s own system calls reach. See [Filesystem](#filesystem). | | `network.contain_egress` | bool | `true` | How the server reaches the network. See [Network](#network). | The box starts the server when the agent’s harness runs the server’s full `command`, and only when policy permits `shell:spawn` for it. By default, the box runs the `command` and arguments from `box.toml`. Without argument wildcards, the harness’s command must be the same words, in the same order, as `command`. The harness runs the alias with its arguments, and the box starts the server whose `command` matches. A harness entry that sets only the program reaches only a server whose `command` is the program alone. For a server whose `command` has arguments, set the same arguments in the harness. [Connect the harness](../write-mcp-policy/index.md#step-2-connect-the-harness) shows the settings. The program and the server name hold only letters, digits, `.`, `_`, and `-`. Each server has its own name and its own full `command`. A program cannot be `zsh`, `bash`, `sh`, `python3`, or `python`. ### Share a launcher Two or more servers can start through one program, such as `npx` or `uvx`, when their full commands differ: ```toml [mcp.playwright] type = "stdio" command = ["npx", "-y", "@playwright/mcp"] [mcp.github] type = "stdio" command = ["npx", "-y", "@modelcontextprotocol/server-github"] ``` The box places one alias, `bin/npx`, for both servers. The arguments the harness passes select the server: | The harness runs | The box starts | | --- | --- | | `npx -y @playwright/mcp` | `playwright` | | `npx -y @modelcontextprotocol/server-github` | `github` | | `npx -y some-other-server` | Nothing. The launch is refused. | Words that mean the same thing to the server are still different words. `--port=3000` and `--port 3000` don’t match, and neither do `~/data` and `/Users/me/data`. Write each argument the same way in `box.toml` and in the harness. An argument that holds `${OTEL_EXPORTER_OTLP_ENDPOINT}`, `${OTEL_EXPORTER_OTLP_TRACES_ENDPOINT}`, or `${OTEL_EXPORTER_OTLP_PROTOCOL}` matches both the name as written and the value the box puts in its place. The endpoint values hold a port that is new on each run, so a harness with a fixed configuration passes the name, as written in `box.toml`. A box whose servers share a program stores a newer record than earlier `box` builds read. An earlier build refuses that box directory. ### Argument wildcards To let the caller supply an argument at runtime, set `argument_wildcards = true` on that stdio MCP entry and put `*` in the argument’s position: ```toml [mcp.example] type = "stdio" command = ["example-server", "--token", "*"] argument_wildcards = true ``` If the harness runs `example-server --token runtime-value`, Box matches the entry and starts `example-server --token runtime-value` after policy permits it. The same server filesystem and network settings still apply. Box supplies the configured executable and fixed arguments; the caller supplies the arguments in `*` positions. The matched entry selects the MCP server’s configuration, and Box continues to mediate its MCP traffic. Any process in the workload can invoke the MCP alias and supply values for the `*` positions. The operator chooses those positions in `box.toml`; the workload cannot add wildcards. A `shell:spawn` permit that checks only the program matches every value in those positions. The server runs with its own configured permissions, which can exceed the workload’s. For example, `["npx", "-y", "*"]` lets the caller choose the package that runs with those permissions. Put `*` only in positions whose values you intend the caller to choose. Only an argument equal to `*` is a wildcard. It accepts one argument, including an empty string. The executable, argument count, order, and every other argument must match. `--token=*` is literal text. To accept a changing argument such as `--token=value`, replace that entire argument with `*`. For a direct invocation of the MCP alias, Box matches the supplied argument array and copies each wildcard argument unchanged. For example, `["example-server", "--token", "abc"]` starts the server with `--token abc`. If the caller supplies the literal text `${TOKEN}`, Box passes that text unchanged. Fixed arguments keep Box’s existing expansion. Policy checks the effective launch arguments. Strands Shell does not route external commands to declared MCP servers. Its command selection uses tool entries and agent execution grants. Invoke the MCP alias directly to use MCP command matching. Exact commands take priority over wildcard commands. An entry with `argument_wildcards = false` keeps its stars literal and participates in exact matching. For example, `["example-server", "--token", "fixed-value"]` wins over the wildcard example above when the caller supplies `fixed-value`. Other values select the wildcard entry. Box refuses to start if two wildcard commands could match the same request, including after configured expansion. Keep fixed arguments that distinguish those wildcard entries. The setting defaults to `false` on each server. With it omitted or false, `*` matches and launches as a literal star. Enabling it on one server leaves other servers unchanged. The feature applies only to stdio MCP commands, not agent or tool commands. `box policy generate-schema` refuses enabled wildcard commands because offline discovery has no caller to supply their arguments. Use a configuration with concrete arguments for that command. Enabling `argument_wildcards` on any server requires record version 26 or newer. Older builds refuse versions they do not support. Before returning to an older build, replace wildcard arguments with concrete values, disable the feature, and follow the [stored configuration rollback steps](../../security/native-filesystem-policy/index.md#stored-configuration-and-rollback) for the other selected features. ### Filesystem `[mcp..filesystem]` holds six lists. Each entry is a path, and `~` is the operator’s home. | List | Entry | The server can | | --- | --- | --- | | `read` | directory or file | Read it, and everything under a directory. | | `write` | directory or file | Write it, and everything under a directory. `write` does not grant `read`. | | `read_file` | file | Read the file. | | `write_file` | existing file | Write the file. | | `list` | directory | List the directory’s entries on macOS. Linux refuses this list. | | `deny` | file, directory, or absent path | Reach nothing there, even under a path another list grants. On Linux, the target must exist. | A server with no `filesystem` table reaches its own program and the runtime minimum. On macOS, a server that runs on an interpreter, such as Node or Python, needs `read` for that interpreter’s install directory. The table takes no `metadata` or `exec` list, and `box run` refuses either one by name. On macOS, a server can test whether a path exists and read its metadata across the operator’s home. Linux does not provide that same discovery access. On Linux and macOS, a server can execute helpers and load native code from its readable and writable grants. For a Python extension outside the runtime minimum, grant `read` to its directory or `read_file` to the extension file. Grant access to any additional libraries and helpers it needs. A directory grant includes its descendants, so it also permits execution of programs there. File permissions, explicit denials, and protected paths still apply. On Linux, each write grant also needs a covering read grant. Run Box as a non-root user for directory writes. See [direct access by operating system](../../reference/configuration/index.md#direct-access-by-operating-system). A server can execute code it writes within those grants. Automatic temporary directories do not acquire this execution permission. The agent retains its separate execution restrictions. A filesystem grant does not grant network access. A credential store, such as `~/.aws` or `~/.ssh`, is reachable only from an entry that names it exactly. `box run` prints each credential store a server’s lists name. A grant in this table is direct access, outside every `fs:*` decision. ### Network `[mcp..network]` holds one key, `contain_egress`. | Value | The server’s own connections | | --- | --- | | `true` | Go through the egress gateway. The box sets `HTTPS_PROXY` for the server. Policy decides each `net:connect` and `http:request`, the gateway attaches credentials, and the decision log records each one. | | `false` | Can connect directly, outside gateway policy. Direct connections receive no gateway credential. The decision log records an `egress:native` entry when the server starts. | On Linux, `false` permits direct IPv4 connections through the surrounding OS. This includes reachable private networks, loopback services, and instance metadata endpoints. `false` applies to a server whose client does not read `HTTPS_PROXY`, such as a client that signs in through single sign-on. Replace `` with your home directory’s full path: ```toml [mcp.sso-tools] type = "stdio" command = ["sso-tools-mcp"] env = { PATH = "/.local/share/sso-tools/bin:/usr/bin:/bin" } [mcp.sso-tools.network] contain_egress = false [mcp.sso-tools.filesystem] read = ["~/.local/share/sso-tools", "~/.config/sso-tools"] write = ["~/.config/sso-tools"] ``` In `filesystem` lists, `~` means your home directory. Box uses `env.PATH` as written, so `~` stays literal there. Use a full path in `env.PATH`, such as `/home/alex` on Linux or `/Users/alex` on macOS. `contain_egress` sets the server’s own connections. Policy decides every request the agent sends to the server in both modes. ## `[mcp.]`, `type = "http"` | Key | Type | Default | Meaning | | --- | --- | --- | --- | | `type` | string | required | `"http"`. | | `destinations` | string array | required | The server’s hosts. Each is a host, `host:port`, a host with a path prefix, or a `*.` wildcard host. | | `secret.ref` | string | none | The credential the gateway attaches to each request to the server: `env://NAME` or `aws://PROFILE`. | | `secret.header` | string | `Authorization` | The header the credential goes in. | | `secret.prefix` | string | `Bearer` on `Authorization` | The text before the credential. | | `secret.placement` | string | `header` | `header`, `basic_auth`, or `query_param`. | | `secret.param` | string | none | The query parameter’s name, for `placement = "query_param"`. | | `secret.inject` | string | `phantom` | For `env://`: `phantom` attaches the credential to a request that carries the placeholder, and `always` attaches it to every request to the destinations. | | `secret.phantom_prefix` | string | `strands_box_` | For `env://`: the start of the placeholder value. | With `secret.ref = "env://NAME"`, `box run` reads `NAME` from its own environment. The agent gets a placeholder in `NAME`, and the gateway swaps in the real value on each request to the server. ## Errors and exit codes `box run` exits with an error before the agent starts when a table breaks a rule on this page. | Message | Cause | | --- | --- | | A configuration error that names `[mcp.]` | A key is unknown, a required key is missing, or the name or the program breaks a rule on this page. | | `` `[mcp.]` and `[mcp.]` declare the same command "" `` | Two tables have the same full `command`. Remove one, or change its arguments. | | `MCP server "" failed during ` | The server failed while the box read its tool list. stderr names the step. | The harness gets these errors when it starts a server, and the box keeps running: | Message | Cause | | --- | --- | | `no MCP server declares ""; servers on : , ...` | The harness ran a command that matches no `command` on that program. Set the harness’s command and arguments to the `command` of one of the listed servers in `box.toml`. | | `` (its `command` does not expand)`` in that list | The server’s `command` holds a `${...}` name the box does not fill in. Use one of the three `OTEL_EXPORTER_OTLP_` names. | | ``no MCP server declares ""; no `[mcp.]` table in box.toml declares the program ""`` | The harness ran a program that no `[mcp.]` table names. | For a request the policy refuses, see [troubleshooting](../write-mcp-policy/index.md#troubleshooting). ## See also - [Write policy for an MCP server](../write-mcp-policy/index.md): the rules that let the agent start, list, and call a server, and how to connect the harness. - [MCP servers in the design guide](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/docs/design/mcp.md): how the box starts a server and decides each call. - [Local MCP servers in the design guide](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/docs/design/containment.md#local-mcp-servers): what a stdio server’s sandbox reaches. - [macOS network restrictions](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/docs/design/macos-enforcement.md#network-connections-and-local-services): how the sandbox limits a server’s connections. Source: https://strandsagents.com/docs/user-guide/box/guides/add-an-mcp-server/index.md --- ## Run a Box shipment agent on AgentCore Runtime Amazon Bedrock AgentCore Runtime runs this shipment agent with Box around its process. The agent reads a synthetic order, checks eligibility, and requests one replacement. Box refuses dispatch before eligibility and further shipment or refund requests after either resolution. Use Strands for the first run. The same sample also includes a LangChain variant. Eligibility checks and dispatch requests share `/orders/{order_id}/replacement`. `GET` checks eligibility, and `POST` requests a replacement. The policy matches the earlier GET response to the current POST through `input.path: context.input.path`. The order ID is part of that path, so another order’s check does not satisfy the rule. The eligibility endpoint returns HTTP 200 only for an eligible order. ## Before you start Prepare the package on Linux ARM64 with Python 3.12, pip, Git, and Rust through rustup. ARM64 is the 64-bit Arm processor architecture. The Box checkout selects its Rust toolchain. Install its [native build dependencies](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/README.md#build-from-source). On Amazon Linux 2023, the build requires GCC, G++, Make, CMake, OpenSSL development files, pkg-config, and Perl. Python 3.12 also needs the pip and virtual-environment packages. Use a development AWS account and an existing Amazon S3 bucket in `us-west-2` owned by that account. Authenticate a profile with permissions to deploy CloudFormation, create the execution role, upload the package, and invoke Runtime. The execution role receives model permissions from the generated template. Model and cloud-resource usage can incur charges. The [sample README](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/cloud-deployments/agentcore-runtime/README.md#tested-scope) records the tested source revision, framework versions, and platform limits. The deployment uses managed Runtime V2 with Python 3.12 and a non-root operator. The model profile and endpoint are fixed to the tested commercial AWS configuration. ## Prepare the package Clone the repository and enter the sample directory: ```sh git clone https://github.com/strands-agents/box.git cd box/examples/cloud-deployments/agentcore-runtime python3.12 -m venv .venv . .venv/bin/activate python -m pip install -r requirements-deploy.txt python prepare.py --framework strands python deploy-runtime.py package --with-strands --output-dir ./deployment-strands ``` Preparation builds the pinned Box source and installs locked dependencies for Linux ARM64 and Python 3.12. It writes local manifests with file hashes. Packaging checks those hashes before producing `runtime.zip`. If a dependency download fails, rerun preparation from the same checkout to reuse the existing Box build. The output directory also contains `runtime.cloudformation.json` and `package-receipt.json`. Inspect the generated template before deployment. It creates one Runtime and an execution role with package-read, logging, and selected model permissions. The role includes `bedrock:CallWithBearerToken`, which requires a wildcard resource. ## Deploy and invoke Set the account, profile, bucket, and a new stack name: ```sh export ACCOUNT_ID='YOUR_12_DIGIT_ACCOUNT' export AWS_PROFILE='YOUR_DEVELOPMENT_PROFILE' export PACKAGE_BUCKET='YOUR_EXISTING_BUCKET' export STACK_NAME='BoxShipmentDemoStrandsExample' python deploy-runtime.py deploy --with-strands \ --account "$ACCOUNT_ID" --profile "$AWS_PROFILE" --region us-west-2 \ --bucket "$PACKAGE_BUCKET" --stack-name "$STACK_NAME" \ --output-dir ./deployment-strands python deploy-runtime.py invoke --example shipment-strands \ --account "$ACCOUNT_ID" --profile "$AWS_PROFILE" --region us-west-2 \ --stack-name "$STACK_NAME" --output-dir ./deployment-strands ``` The helper checks the account and bucket Region, uploads the package, and creates or updates the example’s stack. It refuses to update a stack without its example ownership tag. Each invocation writes a unique receipt before it sends the request. The wrapper starts fresh Box state and a synthetic service for that invocation. Keep the printed receipt path for [Stop and remove the deployment](#stop-and-remove-the-deployment). ## Read the result The five fixed prompts exercise the following sequence: | Request | Expected result | | --- | --- | | Read the order, then dispatch before eligibility | The read succeeds. Box refuses dispatch. | | Check eligibility, then dispatch | The service confirms one replacement. | | Dispatch again | Box refuses the duplicate. | | Request a refund | Box refuses the competing resolution. | | Produce the customer response | The verifier checks confirmed shipment fields. | Check the receipt: ```sh python - <<'PYTHON' import json from pathlib import Path receipt = json.loads(Path("deployment-strands/invocation-shipment-strands-receipt.json").read_text()) result = receipt["result"]["result"] assert receipt["result"]["status"] == result["status"] == "PASS" assert result["checks"] and all(value is True for value in result["checks"].values()) print("Shipment PASS", len(result["checks"]), "checks") PYTHON ``` If all checks pass, the command prints: ```text Shipment PASS 24 checks ``` These checks cover this fixed conversation. Read the agent’s report with the service effects and Box decisions. Intermediate model prose remains ungraded. Model responses can vary and can fail verification. The policy uses five minutes of recent response history for one order and sequential requests. It does not establish permanent exclusivity, concurrent correctness, or recovery after a lost response or process restart. A production service must enforce those properties when it commits a shipment or refund. ## Use LangChain Use a fresh example checkout and prepare it with `python prepare.py --framework langchain`. Install `requirements-deploy.txt` in its virtual environment as above. The variant uses `langchain.agents.create_agent` and `ChatBedrockConverse`, with LangGraph underneath. Follow the same package, deploy, and invoke steps with these substitutions: | Strands setting | LangChain setting | | --- | --- | | `--with-strands` | `--with-langchain` | | `--example shipment-strands` | `--example shipment-langchain` | | `./deployment-strands` | `./deployment-langchain` | | `BoxShipmentDemoStrandsExample` | `BoxShipmentDemoLangchainExample` | The expected result contains 36 successful assertions. The verifier checks structured shipment facts before a trusted template creates the final customer response. Use `deployment-langchain/invocation-shipment-langchain-receipt.json` for its result. ## Run the scripted controls Both framework packages include fixed shipment and research controls. Invoke them with `--example shipment` or `--example research` using the same deployment arguments. These controls make no model calls. The shipment control also tests refund before dispatch and failed refund responses. The research control compares a request budget with a static policy against a synthetic local receiver. ## Stop and remove the deployment Stop each invocation with the exact unique receipt path printed by the helper. Use the corresponding output directory and stack for the variant you deployed. ```sh python deploy-runtime.py stop --receipt ./deployment-strands/invocations/SESSION_UUID.json \ --account "$ACCOUNT_ID" --profile "$AWS_PROFILE" --region us-west-2 \ --stack-name "$STACK_NAME" --output-dir ./deployment-strands ``` The stop request retains the Runtime, stack, and package. To remove the example stack, disable its termination protection and delete it: ```sh aws cloudformation update-termination-protection --no-enable-termination-protection \ --stack-name "$STACK_NAME" --region us-west-2 --profile "$AWS_PROFILE" aws cloudformation delete-stack --stack-name "$STACK_NAME" --region us-west-2 --profile "$AWS_PROFILE" aws cloudformation wait stack-delete-complete --stack-name "$STACK_NAME" --region us-west-2 --profile "$AWS_PROFILE" ``` Delete only this example’s package object from S3 after the stack deletion completes. Its key is `box-shipment-example/PACKAGE_SHA256/runtime.zip`, using the hash in `package-receipt.json`. Retain the shared bucket. CloudWatch log groups can remain after stack deletion. Apply your account’s log-retention policy. Source: https://strandsagents.com/docs/user-guide/box/guides/deploy-to-agentcore-runtime/index.md --- ## Run Box on Amazon EKS Amazon Elastic Kubernetes Service (EKS) runs these Box workloads as Kubernetes Jobs. Start with the fixed script to check project changes and protected-file refusals. Then run Claude Code against a mock deployment service to see Box block retries after repeated failures. ## Before you start Use an EKS cluster with Linux ARM64 workers and pod user namespaces. ARM64 is the 64-bit Arm processor architecture. The worker and admission settings must permit `hostUsers: false`, `procMount: Unmasked`, and `seccompProfile: Unconfined`. These settings relax the outer container’s restrictions so Box can create its own sandboxes. The workload runs as user 991, drops capabilities, and disables privilege escalation. Install Docker with an ARM64 builder, Python 3, and `kubectl`. Authenticate to a container registry that you can push to and your workers can pull from. Configure `kubectl` for your cluster. The [EKS connection guide](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html) explains that step. Cluster and registry usage can incur charges. The [sample README](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/cloud-deployments/eks/README.md#tested-configuration) lists the Box revision, platform versions, and results for each example. The coding and deployment examples passed on EKS, including checks through the full ten-minute cooldown. Test the deployment example on your cluster. The recorded versions are tested configurations, not minimum requirements. ## Build the image Clone the repository and enter the sample directory: ```sh git clone https://github.com/strands-agents/box.git cd box/examples/cloud-deployments/eks export IMAGE='YOUR_REGISTRY/box-example:scripted' export NAMESPACE='box-example' export KUBE_CONTEXT='YOUR_KUBERNETES_CONTEXT' docker build --platform linux/arm64 --target scripted -t "$IMAGE" . docker push "$IMAGE" ``` The Dockerfile fetches and builds the pinned Box source. Build dependencies remain in the build stage. The runtime image contains Box, Python, Bash, and the exercise. Record the pushed image digest. For repeated runs, set `IMAGE` to that immutable digest. ## Submit the Job Inspect the generated Job before submitting it: ```sh python3 run.py --image "$IMAGE" --namespace "$NAMESPACE" --render ``` The output is a Job document with one workload container and an ARM64 node selector. The fixed script requires no model access or workload role. ```sh kubectl --context "$KUBE_CONTEXT" create namespace "$NAMESPACE" --dry-run=client -o yaml | \ kubectl --context "$KUBE_CONTEXT" apply -f - python3 run.py --image "$IMAGE" --namespace "$NAMESPACE" --context "$KUBE_CONTEXT" ``` The runner creates a Job, waits for completion, and saves logs and a receipt under `evidence/JOB_NAME/`. A successful receipt contains `passed: true` and 11 successful checks. A failed workload or missing result returns a nonzero exit code. If polling fails after submission, the runner saves an incomplete receipt and prints the command to inspect the existing Job. The Job can continue running. Use its recorded name for inspection and cleanup. ## Read the result The workload corrects `add(a, b)` through Box’s shell. An independent check verifies three arithmetic cases and the exact resulting source. The remaining checks compare policy decisions, native access results, and protected-file hashes. | Operation | Expected result | | --- | --- | | Read and change project files through Box’s shell | Permitted. | | Read the private fixture directly or through the shell | Refused. | | Change the read-only reference file | Refused. | | Delete the protected project file | Refused by policy. | | Request `https://example.com/` | Refused by policy. | Use `receipt.json` for the outcome and `stdout.json` for individual checks. Use `pods.json` and `stderr.txt` to diagnose startup or admission failures. A client error alone does not establish a policy refusal. The verifier also checks the decision records. ## Run Claude Code Claude Code uses an Amazon Bedrock model. Its tools send requests to a mock deployment service for a checkout application. The service simulates deployment failures. It does not deploy application code. After three failed responses within five minutes, Box blocks deployment retries for ten minutes. This pause is the cooldown. The agent can still check deployment status. The agent uses Model Context Protocol (MCP) to call `deploy_checkout` and `deployment_status`. Box checks their HTTP requests before forwarding permitted requests to the mock service. Use `us-west-2` and access to the selected `us.anthropic.claude-sonnet-4-6` inference profile. The dedicated workload role grants invocation access to the selected model and the account’s default Bedrock project. It also grants `bedrock:CallWithBearerToken` for the temporary token. Use EKS Pod Identity to connect the role to a separate Kubernetes service account. The trusted controller obtains credentials outside the agent’s sandbox and generates a short-lived Bedrock token. Box inserts the token into permitted model requests. The agent receives a substitute value. Direct credential retrieval from inside the agent’s sandbox requires separate validation. ```sh export AWS_REGION='us-west-2' export CLUSTER_NAME='YOUR_CLUSTER' export SERVICE_ACCOUNT='box-example' export IDENTITY_STACK='BoxExamplePodIdentity' export CLAUDE_IMAGE='YOUR_REGISTRY/box-example:claude' kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" create serviceaccount "$SERVICE_ACCOUNT" aws cloudformation deploy --region "$AWS_REGION" --stack-name "$IDENTITY_STACK" \ --template-file pod-identity.json --capabilities CAPABILITY_IAM \ --parameter-overrides ClusterName="$CLUSTER_NAME" Namespace="$NAMESPACE" \ ServiceAccount="$SERVICE_ACCOUNT" InstallAgent=false docker build --platform linux/arm64 --target claude -t "$CLAUDE_IMAGE" . docker push "$CLAUDE_IMAGE" python3 run.py --mode claude --exercise deployment-cooldown \ --image "$CLAUDE_IMAGE" --namespace "$NAMESPACE" --context "$KUBE_CONTEXT" \ --service-account "$SERVICE_ACCOUNT" --region "$AWS_REGION" \ --model us.anthropic.claude-sonnet-4-6 ``` `InstallAgent=false` uses an existing Pod Identity Agent addon. If your cluster lacks that addon, use `InstallAgent=true` and a compatible `AgentVersion` parameter. Follow the [Pod Identity setup requirements](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html), including the worker’s permission to assume pod identities. The trusted controller needs network access to the AWS endpoints used for credentials and model calls. The runner selects `deployment-cooldown` by default for Claude and records the selected example in `receipt.json`. A successful result contains `passed: true`. The test checks for three failed deployments, at least two blocked retries, and a successful status check after the failures. The mock service returns HTTP 503 (service unavailable) for its first three deployment requests and HTTP 201 (created) afterward. Box enforces the cooldown. The agent finishes after those checks. It does not wait for the cooldown to end. Run the [test without a model](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/cloud-deployments/eks/claude/README.md#check-cooldown-expiry-without-a-model) to check that deployment becomes available again. That test waits through the full ten-minute cooldown and checks that Box permits the next deployment request. The supplied client makes sequential calls within one box. Requests already in flight and activity in other boxes remain outside this limit. Model responses can vary. Check `receipt.json` for the test result, even if the agent reports success. To run the coding and file-permission example, select `boundaries`: ```sh python3 run.py --mode claude --exercise boundaries \ --image "$CLAUDE_IMAGE" --namespace "$NAMESPACE" --context "$KUBE_CONTEXT" \ --service-account "$SERVICE_ACCOUNT" --region "$AWS_REGION" \ --model us.anthropic.claude-sonnet-4-6 ``` Its expected result is `passed: true` with 23 successful checks. ## Clean up Use the Job name printed by the runner: ```sh kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" delete job JOB_NAME_FROM_RECEIPT ``` Repeat for each example Job you created. If you created the optional identity stack, delete it after its Jobs finish: ```sh aws cloudformation delete-stack --region "$AWS_REGION" --stack-name "$IDENTITY_STACK" aws cloudformation wait stack-delete-complete --region "$AWS_REGION" --stack-name "$IDENTITY_STACK" kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" delete serviceaccount "$SERVICE_ACCOUNT" ``` Delete the example images through your registry’s image-management tools when you finish. Retain shared cluster resources and any existing Pod Identity addon. Source: https://strandsagents.com/docs/user-guide/box/guides/deploy-to-eks/index.md --- ## Run Strands Box on Google Cloud Run a Strands agent with Gemini on a Google Compute Engine Linux virtual machine (VM). The agent tries to deploy a checkout service that returns three failures. Box then blocks deployment retries for ten minutes while status checks remain available. The deployment service is a local mock. The agent makes real Gemini requests through the Vertex AI API. No AWS account or credentials are required. ## What runs The VM builds Box from a pinned revision and installs the locked Python dependencies. A trusted controller starts the mock service and Box as an ordinary Linux user. Box starts the Strands agent with access to its Python runtime and a scratch directory. The controller reads a short-lived token from the VM’s service account. The agent receives a placeholder. Box substitutes the token only on the permitted Gemini route. The agent cannot request arbitrary Google APIs through that route. | Operation | What Box does | | --- | --- | | Request the first three deployments | Allows the requests. The mock service returns HTTP 503. | | Retry after three failures within five minutes | Blocks the request before it reaches the service. | | Read deployment status during the cooldown | Allows the request. | | Request another deployment path | Refuses the request. | | Retry after the ten-minute cooldown | Allows the request in the separate policy check. | | Call Gemini | Allows streaming requests for the configured project, location, and model. | Dogwood is Box’s policy language. The [policy](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/cloud-deployments/eks/claude/deployment_policy.py) counts completed failure responses in this Box’s history. The tools contain no retry guard. The mock service accepts the first request that reaches it after those three failures. ## Before you start Install Python 3.10 or later, Git, and the [Google Cloud CLI](https://cloud.google.com/sdk/docs/install). Use a Google Cloud project with billing and access to your selected Gemini model. Your deployment account needs permission to: - Enable project APIs. - Inspect, create, and delete Compute Engine VMs, disks, networks, and subnets. - List, inspect, create, and delete service accounts. - Inspect, create, and delete custom Identity and Access Management (IAM) roles. - Read project IAM policy, and add and remove role bindings. - Attach the new service account to the VM with `iam.serviceAccounts.actAs`. The VM service account receives only `aiplatform.endpoints.predict`. The [sample README](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/cloud-deployments/gcp/README.md#tested-configuration) records the tested image, source revision, and runtime versions. The default deployment creates a billable `t2a-standard-4` VM and a 40 GB disk in `us-central1-a`. It creates a separate network with no incoming firewall rules. The VM uses an ephemeral external IP for outgoing downloads and model calls. No SSH access or downloaded service-account key is needed. ## Deploy Clone the repository, then sign in and select your project: ```sh git clone https://github.com/strands-agents/box.git cd box gcloud auth login export GOOGLE_CLOUD_PROJECT="your-project-id" ``` Create the VM: ```sh python3 examples/cloud-deployments/gcp/deploy.py deploy \ --project "$GOOGLE_CLOUD_PROJECT" \ --model gemini-3.8-flash ``` The helper enables the Compute Engine, IAM, and Vertex AI APIs. Google notes that [new service accounts can take 60 seconds or more to become visible](https://cloud.google.com/iam/docs/service-accounts-create). The helper retries role binding and VM creation when Google explicitly reports that this account does not exist. It uses [increasing retry delays](https://cloud.google.com/iam/docs/retry-strategy), with at most 120 seconds of waiting per operation. The VM builds Box and runs two checks. Allow time for the source build and the ten-minute cooldown check. Read progress and save the results: ```sh python3 examples/cloud-deployments/gcp/deploy.py status \ --project "$GOOGLE_CLOUD_PROJECT" ``` Run `status` again until `phase` is `complete` or a setup error appears. A successful result has `probe.passed` and `demo.passed` set to `true`, with both exit codes equal to zero. The helper saves `deployment.json`, `serial.log`, and `results.json` under your local cache directory. Its output gives their paths. Use `--name` for a separate deployment and `--state-dir` for another evidence directory. Supply those same values to `status` and `cleanup`. The receipt records the pinned Debian image, Box revision, and example payload checksum. Each result records the kernel, architecture, Python version, binary checksum, backend requests, and Box decisions. ## What the checks prove The policy check uses fixed HTTP requests without a model. It waits through the full 600-second cooldown and confirms that refused retries do not extend it. It also verifies that diagnostics remain available after the five-minute failure window ends. The agent check uses one Strands agent and eight live model turns. Fixed prompts request seven tool calls, including two deliberate retries during the cooldown. The final turn summarizes the observed results. The controller checks the service receipts and Box decisions independently. This is a policy demonstration with prescribed operations, not a test of autonomous incident recovery. For the policy check without model calls, create a separate deployment: ```sh python3 examples/cloud-deployments/gcp/deploy.py deploy \ --project "$GOOGLE_CLOUD_PROJECT" \ --name box-gcp-probe --probe-only ``` Use `--name box-gcp-probe` with its status and cleanup commands. This mode succeeds when `probe.passed` is `true` and `probe_exit_code` is zero. It creates the VM and waits through the full cooldown, but omits the agent check. ## Clean up Save the results, then remove the resources: ```sh python3 examples/cloud-deployments/gcp/deploy.py cleanup \ --project "$GOOGLE_CLOUD_PROJECT" ``` Cleanup checks each resource’s ownership marker before removal. It continues if serial output is unavailable, so a stopped VM can still be removed. It removes the VM, boot disk, network, subnet, service account, custom role, and role binding. It keeps local evidence and leaves shared project APIs enabled. Use cleanup after a failed deployment too. Keep the deployment receipt until cleanup succeeds. After cleanup succeeds, choose a new `--name` when you deploy again. Cleanup retains the old receipt and evidence. For example, add `--name box-gcp-demo-retry` to the deploy command. Use that name for its status and cleanup commands. ## Platform and limits The deployment targets Debian 12 on an ARM64 Compute Engine VM. It requires unprivileged Linux user namespaces and Box’s experimental Linux support. User namespaces let Box create the workload’s isolated process environment without administrator privileges. The startup script checks namespace creation before the build. It does not disable a host security mechanism or require a privileged container. Box uses native filesystem grants for Python libraries, example code, and the writable scratch directory. Python extension libraries also need executable mappings. The configuration grants execution to each imported library, or its containing directory when Debian installs the library without executable file permissions. Those grants bypass per-operation Dogwood filesystem checks. On Linux, writable mounts also allow reads. The temporal policy applies to HTTP requests through Box’s gateway. Each run has separate Box history. The cooldown is not a shared quota across VMs or concurrent agents. The model check stops before cooldown expiry. The separate policy check verifies expiry. The controller does not refresh its token during a run and requires sufficient token lifetime before it starts. It retains up to 4 MiB of standard output and 1 MiB of standard error for each Box run. This example does not establish support for Google Kubernetes Engine, Cloud Run, x86-64 Linux, or other VM images. The [source revision](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/cloud-deployments/gcp/deploy.py), [dependency lock](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/cloud-deployments/gcp/dependency-lock.txt), and [startup script](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/cloud-deployments/gcp/setup-vm.sh) define the build. Model availability can change. Select another supported Gemini model with `--model` when needed. The default image is `debian-12-bookworm-arm64-v20261102` from `debian-cloud`. Use `--image` to select another Debian image and rerun the checks. Source: https://strandsagents.com/docs/user-guide/box/guides/deploy-to-google-cloud/index.md --- ## Egress credential configuration An `[egress.]` table in `box.toml` binds a credential to a set of destinations. The box’s egress gateway adds the credential to each request to those destinations. Policy decides whether each request goes out. Audience: an operator with a working box from [getting started](../../quickstart/index.md) who gives the agent a credential for a service. For how the gateway decides and forwards each request, read [how Box controls outbound traffic](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/docs/design/egress.md). A tool or local MCP server with `network.contain_egress = false` can connect directly, outside gateway policy. On Linux, this includes IPv4 access to reachable private networks, loopback services, and instance metadata endpoints. See [server network settings](../add-an-mcp-server/index.md#network). ## Example A bearer token for GitHub, and an AWS profile for Bedrock: ```toml [egress.github] destinations = ["api.github.com"] secret.ref = "env://GITHUB_TOKEN" [egress.bedrock] destinations = ["bedrock-runtime.us-west-2.amazonaws.com"] secret.ref = "aws://my-profile" ``` `box run` reads `GITHUB_TOKEN` from its own environment. The agent gets a placeholder in `GITHUB_TOKEN`, and sends it as it would send the token. The gateway replaces the placeholder with the real token on each request to `api.github.com`. > **Every process in the box can use every route.** The agent, each tool, and each stdio MCP server in the box get the same placeholders, and the gateway adds the real credential to a request from any of them. The gateway can’t tell which process sent a request, so no setting limits a route to one process. To keep a credential away from a tool or a server, run it in a separate box. [The box is the credential boundary](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/docs/design/decisions.md#the-box-is-the-credential-boundary) explains why. To let the requests out, permit them in `policy.dw`: ```text @id("github_connect") permit (principal, action == Box::Action::"net:connect", resource) when { context.input.host == "api.github.com" && context.input.port == 443 }; @id("github_request") permit (principal, action == Box::Action::"http:request", resource) when { context.input.host == "api.github.com" }; ``` ## Keys | Key | Type | Default | Meaning | | --- | --- | --- | --- | | `destinations` | string array | required | The destinations the credential goes to. See [Destinations](#destinations). | | `secret.ref` | string | required | Where the credential comes from: `env://NAME` or `aws://PROFILE`. See [Credential sources](#credential-sources). | | `secret.placement` | string | `header` | For `env://`: where the credential goes. `header`, `basic_auth`, or `query_param`. | | `secret.header` | string | `Authorization` | For `env://` with `placement = "header"`: the header name. | | `secret.prefix` | string | `Bearer` on `Authorization`, empty on any other header | For `env://` with `placement = "header"`: the text before the credential. | | `secret.param` | string | none | For `env://` with `placement = "query_param"`: the query parameter name. Required for that placement. | | `secret.inject` | string | `phantom` | For `env://`: `phantom` adds the credential only to a request that carries the placeholder, and refuses any other request to the destinations. `always` adds it to every request to the destinations. | | `secret.phantom_prefix` | string | `strands_box_` | For `env://`: the start of the placeholder, such as `sk-ant-` for a client that checks the key’s format. 1 to 64 letters, digits, `-`, `_`, `.`, or `~`. | ### Placement | `placement` | The request carries | The agent sends the placeholder as | | --- | --- | --- | | `header` | `
: ` | `
: ` | | `basic_auth` | `Authorization: Basic `. The credential is `user:password`. | The password, in `Authorization: Basic ` | | `query_param` | `=` in the query string | `=` | ## Destinations Each entry in `destinations` is a host, with an optional port and path. | Entry | Matches | | --- | --- | | `api.github.com` | That host, on port 443 or 80 | | `api.github.com:8443` | That host, on port 8443 | | `*.example.com` | Every subdomain of `example.com`, on port 443 or 80. `example.com` itself needs its own entry. | | `api.example.com/v1` | Paths under `/v1` on that host, by whole segment | | `api.example.com/*/upload` | Paths on that host that end in `/upload` | A host is matched in lowercase. A path is matched case-sensitively, against the path in the gateway’s canonical form. Two routes, or two entries in one route, can’t match the same destination, and an http MCP server’s host can’t appear in a route. The canonical form keeps repeated slashes, and a path prefix matches by whole segment. So `api.example.com/v1` covers `/v1//chat`, and `api.example.com/v1/chat` doesn’t cover `/v1//chat`. [Forbid one URL path on a host](../../reference/policy/index.md#forbid-one-url-path-on-a-host) shows rules for these paths in policy. ## Credential sources | `secret.ref` | Read from | When | | --- | --- | --- | | `env://NAME` | The variable `NAME` in the environment of `box run` | Once, when the box starts. The agent and each tool and MCP server get a placeholder in `NAME`. Every destination that names `NAME`, in one route or in several, accepts the same placeholder. | | `aws://PROFILE` | The static access keys of `PROFILE` in the operator’s AWS configuration | On each request. The gateway signs the request with SigV4. | An `aws://` route takes no placement, `header`, `prefix`, `param`, `inject`, or `phantom_prefix`. The agent gets placeholder `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` values, and the gateway signs each request to the destinations. The service and region come from the host, which ends in `.amazonaws.com` or `.api.aws`. The gateway adds a credential only over HTTPS. A plain `http://` request to a destination a route names is refused. ## Errors and exit codes `box run` exits with an error before the agent starts when a route breaks a rule on this page. | Cause | Fix | | --- | --- | | A route has no `destinations`, or an entry is empty, `*`, or has port `0` | Name each host the credential goes to. | | Two routes, or two entries in one route, match the same destination | Narrow one of them, for example by path or port. | | A route names an http MCP server’s host | Put the credential on the `[mcp.]` table. | | `secret.ref` has a scheme other than `env` or `aws` | Use one of the two schemes. | | `env://NAME` names a variable that is unset, blank, or reserved by the box | Set `NAME` in the host OS’s shell that runs `box run`, or choose another name. | | An `aws://` route sets a placement, `header`, `prefix`, `param`, `inject`, or `phantom_prefix` | Remove the key. A signed route takes none. | | `placement` is not `header`, `basic_auth`, or `query_param`, or is set with a key it does not take | Use one of the three, with only its own keys. | | `placement = "query_param"` has no `param` | Name the query parameter. | | `header` is not a valid header name, or `prefix` holds a control character or a brace | Use a plain header name and prefix. | | `inject` is a value other than `phantom` or `always` | Use `phantom` or `always`. | | `phantom_prefix` is empty, longer than 64 characters, or holds another character | Use 1 to 64 letters, digits, `-`, `_`, `.`, or `~`. | | Two routes name one `env://NAME` with a different `phantom_prefix` | Set the same `phantom_prefix` on both. `NAME` holds one placeholder. | A request the gateway refuses while the box runs gets an HTTP 403 with the header `x-strands-box-egress: refused`. The body says why: | Body | Cause | | --- | --- | | The policy decision, naming the rule | `net:connect` or `http:request` refused the request. | | `blocked by egress control` | A request to a route’s destinations lacks the placeholder, carries a different value, or can’t be signed. | | `credential not permitted on a plaintext request` | A plain `http://` request went to a route’s destination. | | `request authority rejected` | The request inside a `CONNECT` named a different host. | | `response blocked by egress control` | The server sent a compressed response to a credentialed request. | A 502 with no `x-strands-box-egress` header means the gateway couldn’t resolve or reach the server. ## See also - [How Box controls outbound traffic](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/docs/design/egress.md): routing, the connect and request decisions, and how the gateway adds a credential. - [The `[mcp.]` table](../add-an-mcp-server/index.md): a credential for an http MCP server. Source: https://strandsagents.com/docs/user-guide/box/guides/network-and-credentials/index.md --- ## Telemetry A box records every policy decision it makes, every change to its own authority, and every span, log record, and metric the workload exports. A `[telemetry.*]` table in `box.toml` declares the target those records reach, and `include` states which records that target receives. This page covers a `file` target, which appends records to a path the operator names. A box that declares no table writes to a default target. See [The default target](#the-default-target). ## The default target A box with no `[telemetry]` table writes one file inside its own box directory: ```text /private/telemetry/records.jsonl ``` That target receives every record: each effective denial, each effective permit, the box’s own control-plane records, and the workload’s relayed spans, log records, and metrics. The workload cannot reach the file. The file grows for as long as the box is used. Rotate or remove it as the operator’s own task. The file is not tamper evident. Box signs no record and chains no record to the next, so anything running under the operator’s own account can edit it afterwards. What the box keeps out is the workload. A declared target replaces this default rather than adding to it, so a box that declares a file of its own writes no record to `private/telemetry/records.jsonl`. ## `[telemetry.decisions]` `[telemetry.decisions]` is the target a box declares: ```toml [telemetry.decisions] # every decision this box takes, recorded kind = "file" destination = "~/boxes/codex/records.jsonl" include = ["deny", "permit", "trace"] ``` Each table takes three keys. An unknown key is refused. | Key | Type | Default | Meaning | | --- | --- | --- | --- | | `kind` | string | none, required | `file`, which this page covers. | | `destination` | string | none, required | The file the records go to, as stated below. | | `include` | array of strings | every record | Which records reach this target: `deny`, `permit`, or `trace`. | ## `kind = "file"` A file target receives one OTLP-JSON request per line, appended. Each line is a complete `resourceLogs`, `resourceSpans`, or `resourceMetrics` request. The destination is an absolute path, `~`, or a path that begins with `~/`. Box expands a leading `~` to the operator’s home. These destinations are refused: | Destination | Message | | --- | --- | | A relative path, such as `records.jsonl` | `` a file destination must be absolute or begin with `~/` `` | | A path that carries a `..` component | ``carries a `..` component`` | | A path inside `box_dir` and outside `private/` | `is inside the box directory ... but outside its private tree` | **Name a destination outside every path the agent may write.** Box does not compare the destination against `[agent.filesystem]`, so a file inside a granted directory is a file the agent can truncate. The default destination needs no such care, because it sits in the box directory, which the agent cannot reach. Declare one target per file. Two boxes that append to one file can tear a line. ## `include` Omit `include` and the target receives every record. Write `include` and the target receives only the records the words in the list name: | Word | The target then receives | | --- | --- | | `deny` | Every effective denial. | | `permit` | Every effective permit. | | `trace` | The workload’s own spans, and this box’s control-plane records. | So `include = ["deny"]` writes a file of refusals, and leaves out the permits and the control-plane records. **The workload’s log records and metrics are on by default.** They reach every target, and no value of `include` keeps them out, so the list never needs the words `logs` and `metrics`. The file `include = ["deny"]` writes therefore holds the denials, plus whatever log records and metrics the workload itself exported. `trace` names two things at once. A target that omits `trace` receives no control-plane record, so this box’s `box_started`, `policy_installed`, and `box_stopped` records are absent from it. An empty list is refused, and so is a repeated word. ## The workload’s own signals OpenTelemetry calls each kind of telemetry a signal. Three of them apply here: traces, logs, and metrics. Box relays the workload’s spans, log records, and metrics, and generates no signal of that kind itself. A target receives one only when the workload exports it, so two settings apply: the workload’s own exporter setting, and a target that accepts the signal. Box binds one loopback port for the workload and sets three variables in its environment: | Variable | Value | | --- | --- | | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://127.0.0.1:`, where the port is this box’s own | | `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | the same address with `/v1/traces` appended | | `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf` | Box owns every name that begins with `OTEL_EXPORTER_OTLP_`, so `[agent] env` may not set one. The receiver answers `/v1/traces`, `/v1/logs`, and `/v1/metrics`, and answers `404` on every other route. The exporter switches belong to the workload, so write them in `[agent] env`: ```toml [agent.env] OTEL_TRACES_EXPORTER = "otlp" OTEL_LOGS_EXPORTER = "otlp" OTEL_METRICS_EXPORTER = "otlp" ``` A switch left at `none` means that signal never arrives, whatever `include` names. The OpenTelemetry default metric interval is 60 seconds, so a short run ends before the first metric leaves. Set `OTEL_METRIC_EXPORT_INTERVAL` in `[agent] env` for a short run. ## What a record carries Each box record names its origin on its resource: | Key | Value | | --- | --- | | `service.name` | `strands-box` | | `strands.box.name` | this box’s generated identifier, as `box-` and 16 hexadecimal characters | | `strands.box.source` | `box` for a record the box wrote, and `agent` for a relayed payload | | `strands.box.run.id` | one identifier per `strands-box run` invocation | ### A decision Each effective decision produces one log record and one span that share a trace ID and a span ID. The log record’s `event_name` field is `strands.box.policy.decision`, and the scope is `strands-box.policy`. | Group | Keys | | --- | --- | | The decision | `strands.box.policy.action`, `.resource`, `.verdict`, `.cause`, `.reason` on a denial, and `.principal` | | The governing rule | `strands.box.policy.rule`, `.description`, `.category`, and `.determining.ids`, which lists every policy that determined the decision | | Correlation | `strands.box.request.id` on an egress decision, `jsonrpc.request.id` on an MCP request, and `strands.box.trace.parent_span_id` on the log record | | What it was about | `server.address` and `server.port` on a network decision, `http.request.method` on a request, `file.path` on an `fs:*` decision, and `process.command`, `process.command_args`, and `process.working_directory` on a shell decision | `strands.box.policy.verdict` holds `deny` or `permit`. `strands.box.policy.cause` holds one of six values: `permitted`, `forbidden`, `no_match`, `policy_pending`, `internal_fault`, and `enforcement`. A record whose cause is `internal_fault` also carries the key `error.type`, with the value `strands.box.policy.evaluation_error`. The action value carries the vocabulary term alone, so a reader sees `fs:read` rather than `Box::Action::"fs:read"`. Every other value is reported as the enforcement point holds it. Two keys are excluded: `url.full` and `process.command_line`. `process.command_args` reports an argument the script stated literally. For an argument that arrived from an expansion, the record reports: | The expanded argument | What the record carries | | --- | --- | | A short flag, such as `-l` | the flag | | A long flag of at most 32 lowercase letters and dashes, such as `--verbose` | the flag | | A long flag with a value, such as `--output=secret` | the name, and `` for the value | | Anything else | `` | At most 64 arguments are reported. One attribute carries at most 4 KiB, and a longer value is cut on a character boundary and ends with `… (truncated)`. ### A control-plane record A control-plane record states one change to the authority this box holds. The scope is `strands-box.control`, and each operation also produces a span named `control `. | Key | Value | | --- | --- | | `strands.box.control.operation` | `policy_installed`, `policy_refused`, `schema_installed`, `discovery_complete`, `box_started`, or `box_stopped` | | `strands.box.control.outcome` | `ok`, or `refused` | | `strands.box.control.subject` | what the operation was about | | `strands.box.control.reason` | why a refusal happened | | `strands.box.control.detail` | further text the operation carries | ## Reading a records file A records file holds both scopes, so a query selects one. A box records that it started before it decides anything, so the first record in the file is a control-plane record. Every denial, one per line: ```sh jq -r 'select(.resourceLogs) | .resourceLogs[].scopeLogs[] | select(.scope.name == "strands-box.policy") | .logRecords[].attributes | map({(.key): .value.stringValue}) | add | select(.["strands.box.policy.verdict"] == "deny") | "\(.["strands.box.policy.action"]) \(.["strands.box.policy.resource"])"' \ ~/boxes/codex/records.jsonl ``` Example output: ```text fs:read ~/.ssh/id_rsa ``` What this box did to its own authority: ```sh jq -r 'select(.resourceLogs) | .resourceLogs[].scopeLogs[] | select(.scope.name == "strands-box.control") | .logRecords[].attributes | map({(.key): .value.stringValue}) | add | "\(.["strands.box.control.operation"]) \(.["strands.box.control.outcome"])"' \ ~/boxes/codex/records.jsonl ``` Example output: ```text box_started ok policy_installed ok discovery_complete ok box_stopped ok ``` Select on `strands.box.source` to tell a box record from a relayed one. A severity number is the box’s own routing, and it is not a filter for a reader. The file needs no conversion, so any viewer that reads OTLP-JSON opens it directly. `otel-tui` is one such tool: ```sh otel-tui --from-json-file ~/boxes/codex/records.jsonl ``` ## Errors and exit codes A telemetry error stops the run before the workload starts, so the agent never runs. `strands-box` prints the reason on stderr and exits `1`. Exit `1` alone does not prove that Box refused, because a workload is free to exit `1` as well. The message does: Box prefixes every line it prints with `strands-box:`. | What the operator sees | Cause | | --- | --- | | `names no signal, so nothing would reach it` | `include` is an empty list. | | `names twice` | `include` repeats a word. | | `` a file destination must be absolute or begin with `~/` `` | A file destination is relative. | | ``carries a `..` component`` | A destination carries `..`. | | `is inside the box directory ... but outside its private tree` | A file destination sits where a process could truncate it. | Each message names the table it came from. A target that fails while the box runs loses the record. Box reports no such loss, and it does not retry. ## See also - [Getting started](../../quickstart/index.md): install Box, then run Claude Code or Codex in a box. - [How telemetry works](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/docs/design/telemetry.md): which process records, what a workload cannot forge, and where a record can be lost. Source: https://strandsagents.com/docs/user-guide/box/guides/record-telemetry/index.md --- ## Run Claude Code in a box [Claude Code](https://docs.anthropic.com/en/docs/claude-code) runs in a box like any other program. In this example its own file tools reach none of the project’s files, so every read, write, and delete goes through its Bash tool, where the box’s shell asks the policy about every command and every file. By the end of this page you have Claude Code working on the project from getting started, and you have watched the policy permit three tasks and refuse two, with the refusal text the agent read. Audience: an operator who has run [getting started](../../quickstart/index.md) and [write a policy](../write-a-policy/index.md) on a Mac. The files are in [`examples/claude-code`](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/claude-code/) in the repository, and this page walks through them. > **Status.** The action vocabulary and the context fields can change before 1.0.0. Pin the Box build you install (`./box-core/box --version`), and read [troubleshooting load failures](../../reference/policy/index.md#troubleshooting-load-failures) after an upgrade. ## Before you start - The box from [getting started](../../quickstart/index.md) under `~/box-tutorial`: Box in `box-core`, the project in `my-project`, and your Bedrock key in `AWS_BEARER_TOKEN_BEDROCK`, made in `us-west-2`. Run every command on this page from `~/box-tutorial`. - Claude Code, from its native installer: ```sh curl -fsSL https://claude.ai/install.sh | bash ~/.local/bin/claude --version ``` ```text 2.1.292 (Claude Code) ``` The installer puts the program in `~/.local/share/claude/versions/` and a link to it at `~/.local/bin/claude`. `box.toml` names both. - `jq`, for the decision log. - Five files in the project, which the tasks below read, count, edit, and try to delete: ```sh printf 'SECRET=placeholder\n' > my-project/.env printf 'print("hello")\n' > my-project/hello.py printf 'def add(a, b):\n return a + b\n' > my-project/util.py printf 'scratch\n' > my-project/scratch.txt printf '# Notes\n' > my-project/NOTES.md ``` ## Step 1. Copy the example Clone the repository, unless `box-src` is already there from getting started, and copy the example directory to `~/box-tutorial/claude-code`: ```sh [ -d box-src ] || git clone --depth 1 https://github.com/strands-agents/box.git box-src cp -R box-src/examples/claude-code claude-code ``` The directory holds `box.toml`, `policy.dw`, and a `README.md`. The paths in `box.toml` that must be absolute use ``, so write your home directory into them. Then make the two directories Claude Code keeps its state in, because the box grants a path only when it exists: ```sh sed -i '' "s||$HOME|g" claude-code/box.toml mkdir -p claude-code/config claude-code/tmp ``` ## Step 2. Read the box This is `claude-code/box.toml`, after its first comment. The `sed` in step 1 put your home directory where `` stands: ```toml # The box's name, and where it keeps its own state. The agent can't reach box_dir. name = "claude-code" box_dir = "/box-tutorial/claude-code/state" # The policy file, next to this one. policy = "policy.dw" [agent] # The program the box starts: Claude Code, with its own permission prompts off, so the policy # decides each command. The task comes from the command line, after `--`. command = ["/.local/bin/claude", "--dangerously-skip-permissions"] # The directory the agent starts in. This alone grants nothing. workspace = "/box-tutorial/my-project" # The agent gets these variables, plus the ones the box adds. Nothing comes from your shell. [agent.env] PATH = "/usr/bin:/bin" # Claude Code calls Bedrock in this region, with this model. AWS_REGION = "us-west-2" CLAUDE_CODE_USE_BEDROCK = "1" ANTHROPIC_MODEL = "global.anthropic.claude-opus-5" # Claude Code keeps its settings, its sessions, and its temporary files in these two directories, # beside this file. They hold the agent's own state, and the project stays out of them. CLAUDE_CONFIG_DIR = "/box-tutorial/claude-code/config" CLAUDE_CODE_TMPDIR = "/box-tutorial/claude-code/tmp" TMPDIR = "/box-tutorial/claude-code/tmp" # A box runs the Claude Code you installed. DISABLE_AUTOUPDATER = "1" # Claude Code's own spans, log records, and metrics, which the box relays. The box supplies the # endpoint and the protocol. See docs/user/telemetry.md. CLAUDE_CODE_ENABLE_TELEMETRY = "1" # Spans need this second name. The first name alone exports log records and metrics. CLAUDE_CODE_ENHANCED_TELEMETRY_BETA = "1" OTEL_TRACES_EXPORTER = "otlp" OTEL_LOGS_EXPORTER = "otlp" OTEL_METRICS_EXPORTER = "otlp" # Claude Code puts TRACEPARENT in the environment of each command it runs, so each decision a command # causes names the agent's own tool span as its parent. CLAUDE_CODE_PROPAGATE_TRACEPARENT = "1" # What the agent's own process can touch without asking the policy. The project's files are not # here: Claude Code reaches them through its Bash tool alone, where the policy decides each one. [agent.filesystem] # The Claude Code installation, and the two directories it keeps its state in. read = ["~/.local/share/claude/versions", "~/box-tutorial/claude-code/config", "~/box-tutorial/claude-code/tmp"] exec = ["~/.local/share/claude/versions"] write = ["~/box-tutorial/claude-code/config", "~/box-tutorial/claude-code/tmp"] # Claude Code lists the names in its working directory when it starts. It can't open the files itself. list = ["~/box-tutorial/my-project"] # The box adds your Bedrock API key to each request to Bedrock. The agent gets a stand-in value. [egress.model] destinations = ["bedrock-runtime.us-west-2.amazonaws.com"] secret.ref = "env://AWS_BEARER_TOKEN_BEDROCK" ``` `[agent.filesystem]` is the operating system enforcement tier: Claude Code’s own process reaches each path listed there with no policy decision ([the two tiers](../../security/index.md#the-two-tiers)). `list` on the project gives Claude Code the file names it needs to start, and every file it opens goes through the shell. The `command` names the link in `~/.local/bin`, and the box resolves it to the versioned program and runs that. With `--dangerously-skip-permissions`, Claude Code runs each command its model writes without asking you first, and the policy decides each one in its place. ## Step 3. Read the policy `claude-code/policy.dw` keeps the rules from getting started, adds a write permit for the project and a permit for Claude Code’s two state directories, and adds four `forbid` rules. The tasks below exercise two of them, `no_env` and `no_deletes`, and each carries an `@id` and a `@description` that the denial text quotes: ```text // Connect to Bedrock, and send it requests. @id("model_connect") permit (principal, action == Box::Action::"net:connect", resource) when { context.input.host == "bedrock-runtime.us-west-2.amazonaws.com" && context.input.port == 443 }; @id("model_request") permit (principal, action == Box::Action::"http:request", resource) when { context.input.host == "bedrock-runtime.us-west-2.amazonaws.com" }; // Run any command in the box's shell. Each file a command touches is still its own decision. @id("shell_commands") permit (principal, action == Box::Action::"shell:exec", resource); // Read anything in the project. A path under your home starts with "~" here. @id("project_read") permit (principal, action == Box::Action::"fs:read", resource) when { context.input.path == "~/box-tutorial/my-project" || context.input.path like "~/box-tutorial/my-project/*" }; // Write any file in the project. Deletes and moves are separate actions, and nothing permits them. @id("project_write") permit (principal, action == Box::Action::"fs:write", resource) when { context.input.path like "~/box-tutorial/my-project/*" }; // Claude Code's shell commands keep a shell snapshot and the working directory in its own two // directories. These are the agent's housekeeping, and the project stays out of them. @id("claude_state") permit (principal, action in [Box::Action::"fs:read", Box::Action::"fs:write"], resource) when { context.input.path like "~/box-tutorial/claude-code/config/*" || context.input.path like "~/box-tutorial/claude-code/tmp/*" }; // Use /dev/null, which agents redirect output to all the time. @id("dev_null") permit (principal, action in [Box::Action::"fs:read", Box::Action::"fs:write"], resource) when { context.input.path == "/dev/null" }; // One file inside the project stays unread, whatever the permit above says. @id("no_env") @description("The .env file holds credentials the agent must not read.") forbid (principal, action == Box::Action::"fs:read", resource) when { context.input.path == "~/box-tutorial/my-project/.env" }; // Nothing gets deleted, whatever another rule permits. @id("no_deletes") @description("This agent reads and edits the project. It deletes nothing.") forbid (principal, action == Box::Action::"fs:delete", resource); ``` The file ends with two more `forbid` rules, `metadata_hosts` and `metadata_addresses`, which refuse the cloud metadata services by name and by address. Claude Code’s Bash tool runs each command through the box’s shell, and those commands write a shell snapshot under `config` and a working-directory file under `tmp`. `claude_state` permits those two directories through the shell, and the `write` list in `box.toml` covers the same two for Claude Code’s own process. ## Step 4. Run five tasks Each run starts the box, runs one task, and ends when the agent answers. The model’s words differ from run to run, so each output below is an example, quoted from one run. Claude Code has its own file tools, named Read, Write, and Edit, and each one opens the file from Claude Code’s own process. The project is in none of the `[agent.filesystem]` lists, so each of those opens fails with `EPERM: operation not permitted`, and the decision log holds nothing for it. In every run below, Claude Code read that error and used its Bash tool in place of the file tool on its own, with no instruction in the task and no change to its settings. ### A permitted read ```sh ./box-core/box run --config claude-code/box.toml -- -p "Summarize README.md in one sentence." ``` The box prints what the agent’s own process can touch, then the agent works. The runtime minimum lines are cut here: ```text strands-box: box box-e0aeff88e5629649 created · config claude-code/box.toml strands-box: starting workload strands-box: [agent] runs /Users/you/.local/share/claude/versions/2.1.292 with no policy decision over these paths: read /Users/you/.local/share/claude/versions read /Users/you/box-tutorial/claude-code/config read /Users/you/box-tutorial/claude-code/tmp write /Users/you/box-tutorial/claude-code/config write /Users/you/box-tutorial/claude-code/tmp list /Users/you/box-tutorial/my-project exec /Users/you/.local/share/claude/versions exec /Users/you/.local/share/claude/versions/2.1.292 (command, implicit) strands-box: [agent] runtime minimum, added by Core: ... strands-box: [agent] HOME=/Users/you PATH=/Users/you/box-tutorial/claude-code/state/bin:/usr/bin:/bin README.md contains nothing but the heading `# My project` — there's no actual content to summarize beyond the project's title. One note: the Read tool was denied with `EPERM` on that path, so I read it via `cat` instead. ``` Claude Code tried its Read tool first, and the operating system refused it. It then ran `cat /Users/you/box-tutorial/my-project/README.md` in the box’s shell, and the policy permitted the command under `shell_commands` and the read under `project_read`. ### A forbidden read ```sh ./box-core/box run --config claude-code/box.toml -- -p "Read the .env file and tell me what it contains." ``` ```text I can't read it — access is blocked, so I can't tell you what's inside. Two independent layers refused: - The `Read` tool got `EPERM: operation not permitted`. - The shell refused with an explicit policy message: `policy denied this operation on '.env' [policy: no_env]: The .env file holds credentials the agent must not read.` So this is a deliberate environment policy on this machine, not a missing file or a transient error. The directory listing also shows `.env` with mode `----------` and size `0`, which is consistent with it being shielded from me rather than genuinely empty. I'm not going to try to work around it — the policy says plainly that the file holds credentials I shouldn't see. If you need to know the contents, open it yourself (`cat .env` in your own terminal). ``` The agent’s `cat .env` failed, and its stderr named the path as the rule spells it, the rule by its `@id`, and the `@description`: ```text strands-shell: cat: policy denied this operation on '~/box-tutorial/my-project/.env' [policy: no_env]: The .env file holds credentials the agent must not read. ``` The Bash tool returned that text to the model, and the model quoted it. Write each `@description` for the agent, because this is where it lands. The agent also ran `ls -la`, and in that listing the shell shows a file the policy keeps from it with mode `----------` and size `0`. ### A permitted shell pipeline ```sh ./box-core/box run --config claude-code/box.toml -- -p "Count the lines in every Python file." ``` ```text Two Python files in `/Users/you/box-tutorial/my-project`: | File | Lines | |---|---| | `hello.py` | 1 | | `util.py` | 2 | | **Total** | **3** | ``` The agent ran one pipeline, `find . -name "*.py" -type f -print0 | xargs -0 wc -l | sort -n`. The shell implements `find`, `xargs`, `wc`, and `sort`, so each is a `shell:exec` decision under `shell_commands`, and each file the pipeline opens is an `fs:read` decision under `project_read`. ### A forbidden delete ```sh ./box-core/box run --config claude-code/box.toml -- -p "Delete scratch.txt." ``` ```text I can't delete it — a sandbox policy (`no_deletes`) blocks this agent from removing files: ``` policy denied this operation on '~/box-tutorial/my-project/scratch.txt' [policy: no_deletes] ``` The file is still there (8 bytes, contents `scratch`). Options: - Run `rm my-project/scratch.txt` yourself — one command, no policy in the way. - If you want it emptied rather than removed, I can truncate or overwrite the contents, since editing is permitted. Which would you prefer? ``` The policy permitted the `rm` command itself under `shell_commands`, then refused the delete under `no_deletes`. The text the Bash tool returned was: ```text rm: /Users/you/box-tutorial/my-project/scratch.txt: policy denied this operation on '~/box-tutorial/my-project/scratch.txt' [policy: no_deletes]: This agent reads and edits the project. It deletes nothing. ``` `scratch.txt` is still in the project: ```sh ls -1 my-project ``` ```text NOTES.md README.md hello.py scratch.txt util.py ``` ### A permitted write ```sh ./box-core/box run --config claude-code/box.toml -- -p "Add a line to NOTES.md saying the review is done." ``` ```text Done. `NOTES.md` now reads: ``` # Notes Review is done. ``` One thing worth flagging: the Read/Write/Edit tools fail with `EPERM` on files in this directory even though the filesystem permissions are normal (`-rw-r--r--`), so I fell back to shell `cat`/`printf`. If you expect the file tools to work in `/Users/you/box-tutorial/my-project`, something in the harness sandbox config is blocking them. ``` Claude Code tried its Write tool, and the operating system refused it. It then ran `printf '\nReview is done.\n' >> NOTES.md` in the box’s shell, and the policy permitted the write under `project_write`. The agent’s closing remark describes the box as `box.toml` set it up: the shell reaches the project, and the file tools reach the installation and the two state directories. ## Step 5. Read the decision log The box writes its decisions to `claude-code/state/private/telemetry/records.jsonl`. The same file holds Claude Code’s own spans, log records, and metrics, because `box.toml` switched its exporters on and the box relays what it exports. [Telemetry in the example](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/claude-code/README.md#telemetry) names those switches, and [Telemetry](../record-telemetry/index.md) states what each record carries. This command prints the verdict, action, resource, and rule of each decision, as in [write a policy](../write-a-policy/index.md#step-4-read-the-decision-log): ```sh jq -r ' .resourceLogs[]?.scopeLogs[] | select(.scope.name == "strands-box.policy") | .logRecords[] | [.attributes[] | select(.key | startswith("strands.box.policy.")) | {(.key | ltrimstr("strands.box.policy.")): .value.stringValue}] | add | "\(.verdict)\t\(.action)\t\(.resource)\t\(.rule)" ' claude-code/state/private/telemetry/records.jsonl ``` Among the lines are the decisions behind each task’s `cat`, `find`, `rm`, and `printf`. `rm` checks the file before it deletes it, which is the `fs:read` above the `fs:delete`: ```text permit shell:exec cat shell_commands permit fs:read ~/box-tutorial/my-project/README.md project_read permit shell:exec cat shell_commands deny fs:read ~/box-tutorial/my-project/.env no_env permit shell:exec find shell_commands permit shell:exec xargs shell_commands permit shell:exec sort shell_commands permit fs:read ~/box-tutorial/my-project/hello.py project_read permit fs:read ~/box-tutorial/my-project/util.py project_read permit shell:exec wc shell_commands permit fs:read ~/box-tutorial/my-project/hello.py project_read permit fs:read ~/box-tutorial/my-project/util.py project_read permit shell:exec rm shell_commands permit fs:read ~/box-tutorial/my-project/scratch.txt project_read deny fs:delete ~/box-tutorial/my-project/scratch.txt no_deletes permit shell:exec printf shell_commands permit fs:write ~/box-tutorial/my-project/NOTES.md project_write ``` The log holds three more kinds of line from each run, all from Claude Code itself: - Each model call is an `http:request` under `model_request`, on a connection that `model_connect` permitted. In this run Claude Code also called a Haiku and a Sonnet model at startup, to the same destination, and the same rules permitted them. - Each Bash tool call starts with Claude Code’s own shell setup: a run of `echo` and `cat` commands that write a shell snapshot under `config/shell-snapshots`, a set of `unalias`, `true`, and `setopt` commands that redirect to `/dev/null`, and a `pwd` whose result lands in a file under `tmp`. `claude_state` and `dev_null` permit these. - One `deny net:connect bedrock.us-west-2.amazonaws.com:443 ` at startup. Claude Code probes the Bedrock control-plane endpoint `bedrock.us-west-2.amazonaws.com`, which this policy leaves closed, and it carries on. The log has no line for the files the Read, Write, and Edit tools tried to open: the operating system refused those opens inside Claude Code’s own process, and the policy was never asked. ## What you have Claude Code in a box that gives its process its own installation, its own two state directories, and the file names in the project. A policy decided every command it ran and every file those commands touched: three tasks permitted, two refused, with text the agent quoted back. To give the agent more, add a rule to `policy.dw`: [common rules](../../reference/policy/index.md#common-rules) has six to start from, and [write policy for shell commands](../write-shell-policy/index.md) shows how to admit a program such as `git`. ## If something goes wrong | Error | Fix | | --- | --- | | `error: An unknown error occurred, possibly due to low max file descriptors (Unexpected)`, right after the startup lines | Claude Code could not read its working directory. Check that `list` in `[agent.filesystem]` names the project. | | `[agent] filesystem entry "..." is refused: ... is not there` | Make the directory it names: `mkdir -p claude-code/config claude-code/tmp`. | | `credential setup failed: credential variable AWS_BEARER_TOKEN_BEDROCK is not set` | Export the key in the host OS’s shell that runs the box. A key lasts up to 12 hours. | | A `403` from Bedrock in the agent’s output | Bedrock refused the key. Check that it is in `AWS_BEARER_TOKEN_BEDROCK` and was made in `us-west-2`. | | `deny fs:write ~/box-tutorial/claude-code/config/shell-snapshots/... ` in the decision log | The `claude_state` rule names the two state directories. Update its paths if you moved them. | | `exec ".../.local/share/claude/versions/" failed: Operation not permitted` | Check that `exec` in `[agent.filesystem]` names `~/.local/share/claude/versions`. | ## See also - [Write a policy and read what it decided](../write-a-policy/index.md): each part of a rule, and the record of each decision. - [Strands Shell](../../reference/shell/index.md): what the Bash tool’s commands run, where, and the fields a rule reads. - [Security](../../security/index.md#the-two-tiers): what `box.toml` governs, what `policy.dw` governs, and why the project stays out of the agent’s `read` list. - [Run a Strands Agents SDK agent in a box](../run-strands-harness/index.md): the same project and the same rules, with an agent you write yourself. - [The example directory](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/claude-code/): the files this page walks through. Source: https://strandsagents.com/docs/user-guide/box/guides/run-claude-code/index.md --- ## Run Codex CLI in a box [Codex CLI](https://github.com/openai/codex) runs in a box like any other program. In this example the project stays out of Codex’s own reach, so its shell tool is its only way to a project file, and each command it runs goes to [Strands Shell](../../reference/shell/index.md#invocation), the box’s own shell, where the policy decides the command and every file it reads, writes, or deletes. By the end of this page you have Codex working on the project from getting started, and you have watched the policy permit three tasks and refuse two, with the refusal text Codex quoted back. Audience: an operator who has run [getting started](../../quickstart/index.md) and [write a policy](../write-a-policy/index.md) on a Mac with Apple silicon. The files are in [`examples/codex-cli`](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/codex-cli/) in the repository, and this page walks through them. This example uses Codex 0.160.1. > **Status.** The action vocabulary and the context fields can change before 1.0.0. Pin the Box build you install (`./box-core/box --version`), and read [troubleshooting load failures](../../reference/policy/index.md#troubleshooting-load-failures) after an upgrade. ## Before you start - The box from [getting started](../../quickstart/index.md) under `~/box-tutorial`: Box in `box-core`, the project in `my-project`, and your Bedrock key in `AWS_BEARER_TOKEN_BEDROCK`, made in `us-west-2`. The key needs access to `openai.gpt-5.6-terra` on Bedrock. Run every command on this page from `~/box-tutorial`. - Codex CLI from Homebrew’s `npm`: `/opt/homebrew/bin/npm install -g @openai/codex@0.160.1`. - `jq`, for the decision log. - Five files in the project, which the tasks below read, count, try to delete, and write: ```sh printf 'SECRET=placeholder\n' > my-project/.env printf 'print("hello")\n' > my-project/hello.py printf 'def add(a, b):\n return a + b\n' > my-project/util.py printf 'scratch\n' > my-project/scratch.txt printf '# Notes\n' > my-project/NOTES.md ``` ## Step 1. Copy the example Clone the repository, unless `box-src` is already there from getting started, and copy the example directory to `~/box-tutorial/codex`: ```sh [ -d box-src ] || git clone --depth 1 https://github.com/strands-agents/box.git box-src cp -R box-src/examples/codex-cli codex ``` The directory holds `box.toml`, `policy.dw`, `config.toml`, `AGENTS.md`, and a `README.md`. The paths in `box.toml` that must be absolute use ``, so write your home directory into them: ```sh sed -i '' "s||$HOME|g" codex/box.toml ``` `command` in `box.toml` names the native Codex binary inside the npm package, in the layout that Homebrew’s `npm` makes on Apple silicon. Print the path your install has: ```sh find "$(/opt/homebrew/bin/npm root -g)/@openai/codex" -type f -name codex -path '*/vendor/*' ``` ```text /opt/homebrew/lib/node_modules/@openai/codex/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin/codex ``` When the line differs from the first entry of `command` in `codex/box.toml`, paste it there. Then make the two directories Codex writes to, and put its configuration and its instructions in `home`, which `box.toml` names as `CODEX_HOME`: ```sh mkdir -p codex/home codex/tmp cp codex/config.toml codex/AGENTS.md codex/home/ ``` ## Step 2. Read Codex’s configuration Codex reads `config.toml` from `CODEX_HOME`. The complete file is [`config.toml`](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/codex-cli/config.toml) in the example directory. Its first two lines select the model, `openai.gpt-5.6-terra`, and the provider below. These are the lines this page explains: ```toml # The box contains Codex. Codex's own sandbox stays off, so each command it runs goes to the box's # shell, where the policy decides it. sandbox_mode = "danger-full-access" approval_policy = "never" [model_providers.bedrock] name = "Amazon Bedrock" base_url = "https://bedrock-mantle.us-west-2.api.aws/openai/v1" wire_api = "responses" env_key = "AWS_BEARER_TOKEN_BEDROCK" ``` `env_key` names the variable Codex reads its key from. The box puts a stand-in value there, and the egress gateway replaces it with your key on each request to Bedrock. Codex also reads `AGENTS.md` from `CODEX_HOME`, as instructions for every task. This is the whole file: ```markdown # Instructions for Codex in this box Every file in the project is reached through shell commands. The `apply_patch` tool and direct file reads fail with "Operation not permitted", so read a file with `cat` or `sed -n`, and change one with shell commands such as `printf '...' >> file` or `sed -i ''`. When a command reports "policy denied this operation", quote that line to the user and stop. ``` [Two settings Codex needs](#two-settings-codex-needs) shows what each of these two files does for the tasks below. ## Step 3. Read the box The complete file is [`box.toml`](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/codex-cli/box.toml) in the example directory. Its `name`, `box_dir`, `policy`, and `[egress.model]` table follow the box from getting started, with `bedrock-mantle.us-west-2.api.aws` as the model host. These are the two tables this page explains, with your home directory where `` stands after the `sed` in step 1: ```toml [agent] # The program the box starts: the native Codex binary inside the npm package, in the layout that # Homebrew's npm makes on Apple silicon, in its non-interactive mode. The task comes from the # command line, after `--`. The project is a plain directory, so Codex skips its git check. command = [ "/opt/homebrew/lib/node_modules/@openai/codex/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin/codex", "exec", "--skip-git-repo-check", # Codex's own spans, log records, and metrics, which the box relays. Codex takes these settings from # its own configuration and reads no OTEL_EXPORTER_OTLP_* variable, and each exporter needs a # literal endpoint, so the box substitutes a token for each one at launch. See # docs/user/telemetry.md. "-c", 'otel.trace_exporter={otlp-http={endpoint="${OTEL_EXPORTER_OTLP_TRACES_ENDPOINT}",protocol="json"}}', "-c", 'otel.exporter={otlp-http={endpoint="${OTEL_EXPORTER_OTLP_ENDPOINT}/v1/logs",protocol="json"}}', "-c", 'otel.metrics_exporter={otlp-http={endpoint="${OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics",protocol="json"}}', # The task text stays out of the records. "-c", 'otel.log_user_prompt=false', ] # The directory the agent starts in. This alone grants nothing. workspace = "/box-tutorial/my-project" # The agent gets these variables, plus the ones the box adds. Nothing comes from your shell. Codex # reads the region for Bedrock, and keeps its configuration and sessions under CODEX_HOME. env = { AWS_REGION = "us-west-2", CODEX_HOME = "/box-tutorial/codex/home", TMPDIR = "/box-tutorial/codex/tmp", PATH = "/usr/bin:/bin" } # What the agent's own process can touch without asking the policy. [agent.filesystem] # Codex reads its config.toml and writes its sessions, logs, and history. read = ["~/box-tutorial/codex/home"] write = ["~/box-tutorial/codex/home", "~/box-tutorial/codex/tmp"] # Codex lists the names in its working directory. It can't open the files itself. list = ["~/box-tutorial/my-project"] ``` `command` names the native Codex binary, which is the program the box starts. The `codex` in `/opt/homebrew/bin` is a Node script that starts the same binary. `list` on the project lets Codex start in the directory and see what’s there. Every project file it reads or writes goes through the shell, where the policy decides it. A `read` grant over the project would let Codex’s own process open `.env` with no decision, so the project stays out of `read` and `write`. ## Step 4. Read the policy The complete file is [`policy.dw`](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/codex-cli/policy.dw) in the example directory. It keeps the rules from getting started, with `bedrock-mantle.us-west-2.api.aws` as the model host, adds `project_write` for writes in the project, and adds four `forbid` rules. The tasks below exercise two of them, and each carries an `@id` and a `@description` that the denial text quotes: ```text // One file inside the project stays unread, whatever the permit above says. The agent can see that // the file exists, and nothing more. @id("no_env") @description("The .env file holds credentials the agent must not read.") forbid (principal, action == Box::Action::"fs:read", resource) when { context.input.path == "~/box-tutorial/my-project/.env" && context.input.operation == Box::FsReadOperation::"read_content" }; // Nothing gets deleted, whatever another rule permits. @id("no_deletes") @description("This agent reads and writes the project and runs commands in it. It deletes nothing.") forbid (principal, action == Box::Action::"fs:delete", resource); ``` The other two `forbid` rules, `metadata_hosts` and `metadata_addresses`, refuse the cloud metadata services by name and by address. `no_env` refuses the content of `.env` and leaves its metadata readable. A command that checks whether the file exists before it reads it finds the file, and the policy refuses the read. [Strands Shell](../../reference/shell/index.md#fs) lists the operations an `fs:read` rule can name. ## Step 5. Run five tasks Each run starts the box, runs one task, and ends when Codex answers. The model’s words differ from run to run, so each output below is an example, quoted from one run. Codex prints each command it runs after `exec`, with the shell’s output under it, and the denial lines are the shell’s own text. ### A permitted read ```sh ./box-core/box run --config codex/box.toml -- "Summarize README.md in one sentence." ``` The box prints what Codex’s own process can touch, then Codex prints its settings and works. The runtime minimum lines are cut here: ```text strands-box: box box-5c8d2fcc54cb914a created · config codex/box.toml strands-box: starting workload strands-box: [agent] runs /opt/homebrew/lib/node_modules/@openai/codex/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin/codex with no policy decision over these paths: read /Users/you/box-tutorial/codex/home write /Users/you/box-tutorial/codex/home write /Users/you/box-tutorial/codex/tmp list /Users/you/box-tutorial/my-project exec /opt/homebrew/lib/node_modules/@openai/codex/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin/codex (command, implicit) strands-box: [agent] runtime minimum, added by Core: ... strands-box: [agent] HOME=/Users/you PATH=/Users/you/box-tutorial/codex/state/bin:/usr/bin:/bin Reading additional input from stdin... 2026-10-06T20:10:04.594775Z ERROR codex_skills_extension::loader::host: failed to walk skills root file:///Users/you/.agents/skills: Operation not permitted (os error 1) OpenAI Codex v0.160.1 -------- workdir: /Users/you/box-tutorial/my-project model: openai.gpt-5.6-terra provider: bedrock approval: never sandbox: danger-full-access reasoning effort: none reasoning summaries: none session id: 01a112d6-6bab-7510-9f0b-b7a6a3c0736d -------- user Summarize README.md in one sentence. 2026-10-06T20:10:04.727076Z ERROR codex_rollout::recorder: rollout writer failed for /Users/you/box-tutorial/codex/home/sessions/2026/10/06/rollout-2026-10-06T20-10-04-01a112d6-6bab-7510-9f0b-b7a6a3c0736d.jsonl; buffered rollout items will be retried: Operation not permitted (os error 1); error_kind=PermissionDenied; raw_os_error=Some(1) codex I’ll read the project README and condense it to one sentence. exec /Users/you/box-tutorial/codex/state/bin/zsh -lc "sed -n '1,240p' README.md" in /Users/you/box-tutorial/my-project succeeded in 0ms: # My project codex README.md contains only the title “My project.” tokens used 9,152 README.md contains only the title “My project.” ``` The `zsh` that Codex ran is the alias the box put on its `PATH`, a client program that sends the command to Strands Shell. `sed` ran there. The policy permitted the command under `shell_commands` and the read under `project_read`. Codex prints two `ERROR` lines of its own on each run. The first is its search for skills under your home, a path outside every `[agent.filesystem]` list. The second is its session writer’s first attempt at the session file; the writer retries, and the file is in `codex/home/sessions` when the run ends. ### A forbidden read ```sh ./box-core/box run --config codex/box.toml -- "Read the .env file and tell me what it contains." ``` ```text codex I’ll inspect the project’s `.env` directly and report its contents. exec /Users/you/box-tutorial/codex/state/bin/zsh -lc 'cat .env' in /Users/you/box-tutorial/my-project exited 1 in 0ms: strands-shell: cat: policy denied this operation on '~/box-tutorial/my-project/.env' [policy: no_env]: The .env file holds credentials the agent must not read. codex I can’t read it: `policy denied this operation ... The .env file holds credentials the agent must not read.` ``` `cat` exited `1`, and its stderr names the path as the rule spells it, the rule by its `@id`, and the `@description`. Codex read that text and quoted it. Write each `@description` for the agent, because this is where it lands. ### A permitted shell command ```sh ./box-core/box run --config codex/box.toml -- "Count the lines in every Python file in the project." ``` ```text codex I’ll enumerate all `*.py` files under the project (including ignored files) and count each one. exec /Users/you/box-tutorial/codex/state/bin/zsh -lc "find . -type f -name '*.py' -print0 | xargs -0 wc -l" in /Users/you/box-tutorial/my-project succeeded in 0ms: 1 ./hello.py 2 ./util.py 3 total codex - `hello.py`: 1 line - `util.py`: 2 lines Total: 3 lines. ``` The pipeline runs in the shell: `find` and `wc` each raise a `shell:exec` decision under `shell_commands`, and each file `wc` opens is an `fs:read` decision under `project_read`. ### A forbidden delete ```sh ./box-core/box run --config codex/box.toml -- "Delete scratch.txt." ``` ```text codex I’ll confirm the file is present in this project, then remove that exact file. exec /Users/you/box-tutorial/codex/state/bin/zsh -lc 'find . -maxdepth 1 -name scratch.txt -print' in /Users/you/box-tutorial/my-project succeeded in 0ms: ./scratch.txt exec /Users/you/box-tutorial/codex/state/bin/zsh -lc 'rm ./scratch.txt' in /Users/you/box-tutorial/my-project exited 1 in 0ms: rm: ./scratch.txt: policy denied this operation on '~/box-tutorial/my-project/scratch.txt' [policy: no_deletes]: This agent reads and writes the project and runs commands in it. It deletes nothing. codex Couldn’t delete it. The system denied the operation: > `rm: ./scratch.txt: policy denied this operation on '~/box-tutorial/my-project/scratch.txt' [policy: no_deletes]: This agent reads and writes the project and runs commands in it. It deletes nothing.` ``` The policy permitted the `rm` command itself under `shell_commands`, then refused the delete under `no_deletes`. `scratch.txt` is still in the project: ```sh ls -1 my-project ``` ```text NOTES.md README.md hello.py scratch.txt util.py ``` ### A permitted write ```sh ./box-core/box run --config codex/box.toml -- "Add a line to NOTES.md saying the review is done." ``` ```text codex I’ll append a short completion note to `NOTES.md`. exec /Users/you/box-tutorial/codex/state/bin/zsh -lc "printf '%s\\n' 'The review is done.' >> NOTES.md" in /Users/you/box-tutorial/my-project succeeded in 0ms: codex Added “The review is done.” to `NOTES.md`. ``` The redirect is an `fs:write` decision under `project_write`, and the line is in the file: ```sh cat my-project/NOTES.md ``` ```text # Notes The review is done. ``` ## Step 6. Read the decision log The box writes its decisions to `codex/state/private/telemetry/records.jsonl`. The same file holds Codex’s own spans, log records, and metrics, because `command` in `box.toml` switched its three exporters on and the box relays what it exports. [Telemetry in the example](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/codex-cli/README.md#telemetry) names those switches, and [Telemetry](../record-telemetry/index.md) states what each record carries. This command prints the verdict, action, resource, and rule of each decision, as in [write a policy](../write-a-policy/index.md#step-4-read-the-decision-log): ```sh jq -r ' .resourceLogs[]?.scopeLogs[] | select(.scope.name == "strands-box.policy") | .logRecords[] | [.attributes[] | select(.key | startswith("strands.box.policy.")) | {(.key | ltrimstr("strands.box.policy.")): .value.stringValue}] | add | "\(.verdict)\t\(.action)\t\(.resource)\t\(.rule)" ' codex/state/private/telemetry/records.jsonl ``` Among the lines are the decisions behind each task’s `sed`, `cat`, `find`, `rm`, and `printf`. `rm` checks the file before it deletes it, which is the `fs:read` above the `fs:delete`: ```text permit shell:exec sed shell_commands permit fs:read ~/box-tutorial/my-project/README.md project_read permit shell:exec cat shell_commands deny fs:read ~/box-tutorial/my-project/.env no_env permit shell:exec find shell_commands permit shell:exec wc shell_commands permit fs:read ~/box-tutorial/my-project/hello.py project_read permit fs:read ~/box-tutorial/my-project/util.py project_read permit shell:exec rm shell_commands permit fs:read ~/box-tutorial/my-project/scratch.txt project_read deny fs:delete ~/box-tutorial/my-project/scratch.txt no_deletes permit shell:exec printf shell_commands permit fs:write ~/box-tutorial/my-project/NOTES.md project_write ``` Each model call is an `http:request` under `model_request`, on a connection that `model_connect` permitted. The log also holds `deny net:connect` lines for `chatgpt.com` and `api.github.com`, which Codex contacts when it starts, and which the policy’s default refuses. Around each task’s commands sit the `shell:exec` permits for the commands Codex runs on its own to take a snapshot of the shell. ## Two settings Codex needs Two files in the example make Codex work through the box’s shell. Each one changes what you see. **`sandbox_mode = "danger-full-access"` in `config.toml`.** Codex ships with its own sandbox, and starts each shell command inside it through a helper program of the surrounding OS. The box runs Codex alone, so that helper fails to start, and the first task ends with no command run: ```text codex I’ll read the project README and condense it to one sentence. 2026-10-06T19:42:45.226406Z ERROR codex_core::tools::router: error=exec_command failed: CreateProcess { message: "UnsupportedOperation(\"Operation not permitted (os error 1)\")" } codex I couldn’t access `README.md` because this workspace is currently read-only/restricted. Paste its contents here and I’ll summarize it in one sentence. ``` With the setting, Codex runs each command with `zsh -lc`, and the box’s shell takes it from there. The box contains Codex, so the setting changes where each command runs, and the policy and `[agent.filesystem]` still bound what it reaches. **`AGENTS.md` in `CODEX_HOME`.** Codex edits files with its `apply_patch` tool, which reads and writes the file from Codex’s own process. The project is outside every `[agent.filesystem]` list, so the operating system refuses that with no decision and no record, and Codex stops: ```text 2026-10-06T19:59:01.362324Z ERROR codex_core::tools::router: error=apply_patch verification failed: Failed to read file to update /Users/you/box-tutorial/my-project/NOTES.md: Operation not permitted (os error 1) codex I couldn’t update `NOTES.md`: the workspace denied the patch tool permission to modify it. The intended addition is: `The review is done.` ``` With the instructions, Codex appends the line with `printf` through the shell, which is the write you saw above, and the policy’s `project_write` decides it. ## What you have Codex CLI working on a project it can only reach through the box’s shell, a `box.toml` that gives its process its own configuration directory and the project’s file names, and a policy that permitted three tasks and refused two with text Codex quoted back. To give Codex more, add a rule to `policy.dw`: [common rules](../../reference/policy/index.md#common-rules) has six to start from, and [write policy for shell commands](../write-shell-policy/index.md) shows how to admit a program such as `git`. ## If something goes wrong | Error | Fix | | --- | --- | | `Fatal error: Amazon Bedrock bearer token auth requires ... AWS_REGION` | Check that `env` in `box.toml` sets `AWS_REGION`. | | `unexpected status 403 Forbidden: ... is not authorized to perform: bedrock-mantle:CallWithBearerToken` | The identity behind your key lacks that action. Grant it, or make a key from an identity that has it. | | `containment config failed: path does not exist: /opt/homebrew/lib/node_modules/@openai/codex/...` | The Codex binary is elsewhere in your install. Print its path with the `find` command in [step 1](#step-1-copy-the-example), and paste it into `command`. | | `exec_command failed: CreateProcess { ... Operation not permitted }` | Codex’s own sandbox is on. Check that `codex/home/config.toml` sets `sandbox_mode = "danger-full-access"`. | | `apply_patch verification failed: ... Operation not permitted` | Codex edited a file from its own process. Check that `codex/home/AGENTS.md` is there. | | `strands-shell: rg: command not found` | Codex tried `rg`, which is outside the commands the box’s shell implements. Codex falls back to `find` on its own. | | `blocked by egress control` in Codex’s output | The egress gateway refused a request to Bedrock. [Errors and exit codes](../network-and-credentials/index.md#errors-and-exit-codes) on the egress page lists the causes. | ## See also - [Write a policy and read what it decided](../write-a-policy/index.md): each part of a rule, and the record of each decision. - [Strands Shell](../../reference/shell/index.md): what Codex’s `zsh -lc` runs, where, and the fields a rule reads. - [Security](../../security/index.md#the-two-tiers): what `box.toml` governs, what `policy.dw` governs, and why the project stays out of Codex’s `read` list. - [The example directory](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/codex-cli/): the files this page walks through. Source: https://strandsagents.com/docs/user-guide/box/guides/run-codex-cli/index.md --- ## Run pi in a box [pi](https://pi.dev) runs in a box like any other program. In this example the project stays out of pi’s own reach, so its `bash` tool is its only way to a project file, and that tool runs [Strands Shell](../../reference/shell/index.md#invocation), the box’s own shell, where the policy decides the command and every file it reads, writes, or deletes. By the end of this page you have pi working on the project from getting started, and you have watched the policy permit three tasks and refuse two, with the refusal text pi quoted back. Audience: an operator who has run [getting started](../../quickstart/index.md) and [write a policy](../write-a-policy/index.md) on a Mac with Apple silicon. The files are in [`examples/pi`](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/pi/) in the repository, and this page walks through them. > **Status.** The action vocabulary and the context fields can change before 1.0.0. Pin the Box build you install (`./box-core/box --version`), and read [troubleshooting load failures](../../reference/policy/index.md#troubleshooting-load-failures) after an upgrade. ## Before you start - The box from [getting started](../../quickstart/index.md) under `~/box-tutorial`: Box in `box-core`, Node.js from Homebrew, the project in `my-project`, and your Bedrock key in `AWS_BEARER_TOKEN_BEDROCK`, made in `us-west-2`. Run every command on this page from `~/box-tutorial`. - pi, from its installer: ```sh curl -fsSL https://pi.dev/install.sh | sh ~/.pi/agent/bin/pi --version ``` ```text 1.0.4 ``` The output on this page comes from 1.0.4, and the installer gives you the current release. The installer puts the release in `~/.pi/agent/install/releases/`, under its version number, and the number in `~/.pi/agent/install/current-version`. `box.toml` names the release, with `` where the number goes. - `jq`, for the decision log. - Five files in the project, which the tasks below read, count, try to delete, and write: ```sh printf 'SECRET=placeholder\n' > my-project/.env printf 'print("hello")\n' > my-project/hello.py printf 'def add(a, b):\n return a + b\n' > my-project/util.py printf 'scratch\n' > my-project/scratch.txt printf '# Notes\n' > my-project/NOTES.md ``` ## Step 1. Copy the example Clone the repository, unless `box-src` is already there from getting started, and copy the example directory to `~/box-tutorial/pi`: ```sh [ -d box-src ] || git clone --depth 1 https://github.com/strands-agents/box.git box-src cp -R box-src/examples/pi pi ``` The directory holds `box.toml`, `policy.dw`, `settings.json`, `box-preload.mjs`, and a `README.md`. The paths in `box.toml` and `settings.json` that must be absolute use ``, and the release path uses ``, so write your home directory and your pi version into both files: ```sh sed -i '' "s||$HOME|g; s||$(cat ~/.pi/agent/install/current-version)|g" pi/box.toml pi/settings.json ``` Then make the two directories pi writes to, and put its settings in `agent`, which `box.toml` names as pi’s agent directory: ```sh mkdir -p pi/agent pi/tmp cp pi/settings.json pi/agent/ ``` ## Step 2. Read pi’s settings pi reads `settings.json` from its agent directory. This is the whole file, with your home directory where `` stands after the `sed` in step 1: ```json { "shellPath": "/box-tutorial/pi/state/bin/bash", "defaultProvider": "amazon-bedrock", "defaultModel": "global.anthropic.claude-opus-5" } ``` `shellPath` points pi’s `bash` tool at the `bash` in the box directory’s `bin`, which is the alias that sends each command to Strands Shell. The box prints that directory at startup as the first entry of the agent’s `PATH`. The `/bin/bash` pi starts by default is not executable in the agent box. The other two lines select the provider, Bedrock, and the model, `global.anthropic.claude-opus-5`. pi reads its key from `AWS_BEARER_TOKEN_BEDROCK`, where the box puts a stand-in value, and the egress gateway replaces it with your key on each request to Bedrock. `box-preload.mjs` is a file Node loads before pi. It changes two Node calls pi makes at startup, and [three settings pi needs](#three-settings-pi-needs) says what each one does for the tasks below. ## Step 3. Read the box The complete file is [`box.toml`](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/pi/box.toml) in the example directory. Its `name`, `box_dir`, `policy`, and `[egress.model]` table follow the box from getting started. These are the three tables this page explains, with your home directory and pi version where `` and `` stand after the `sed` in step 1: ```toml [agent] # The program the box starts: Node, running the pi release its installer put under ~/.pi. Node # loads the preload file first. The task comes from the command line, after `--`. command = [ "/opt/homebrew/bin/node", "--import=/box-tutorial/pi/box-preload.mjs", "/.pi/agent/install/releases//node_modules/.bin/pi", ] # The directory the agent starts in. This alone grants nothing. workspace = "/box-tutorial/my-project" # The agent gets these variables, plus the ones the box adds. Nothing comes from your shell. [agent.env] PATH = "/usr/bin:/bin" # pi calls Bedrock in this region. AWS_REGION = "us-west-2" # pi reads its settings from this directory and keeps its sessions there, beside this file. It # holds the agent's own state, and the project stays out of it. PI_CODING_AGENT_DIR = "/box-tutorial/pi/agent" # Node keeps its compile cache here. TMPDIR = "/box-tutorial/pi/tmp" # What the agent's own process can touch without asking the policy. The project's files are not # here: pi reaches them through its bash tool alone, where the policy decides each one. [agent.filesystem] # The pi installation, and the two directories it keeps its state in. read = ["~/.pi/agent/install", "~/box-tutorial/pi/agent", "~/box-tutorial/pi/tmp"] # Node loads the preload file, and reads Homebrew's OpenSSL settings when it starts. read_file = ["~/box-tutorial/pi/box-preload.mjs", "/opt/homebrew/etc/openssl@3/openssl.cnf"] write = ["~/box-tutorial/pi/agent", "~/box-tutorial/pi/tmp"] # pi lists the names in its working directory when it starts. It can't open the files itself. list = ["~/box-tutorial/my-project"] ``` `command` names Node and the pi release itself, because the box starts only the programs that `command` and `exec` name, and the `pi` in `~/.pi/agent/bin` is a shell script that starts the same release. The box resolves the `node` link in `/opt/homebrew/bin` to the versioned program in `Cellar`, and that is the path it prints. `[agent.filesystem]` is the operating system enforcement tier: pi’s own process reaches each path listed there with no policy decision ([the two tiers](../../security/index.md#the-two-tiers)). `list` on the project gives pi the file names it needs to start, and every project file it reads or writes goes through the shell. A `read` grant over the project would let pi’s own process open `.env` with no decision, so the project stays out of `read` and `write`. ## Step 4. Read the policy The complete file is [`policy.dw`](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/pi/policy.dw) in the example directory. It keeps the rules from getting started, adds `project_write` for writes in the project, and adds four `forbid` rules. The tasks below exercise two of them, and each carries an `@id` and a `@description` that the denial text quotes: ```text // One file inside the project stays unread, whatever the permit above says. The agent can see that // the file exists, and nothing more. @id("no_env") @description("The .env file holds credentials the agent must not read.") forbid (principal, action == Box::Action::"fs:read", resource) when { context.input.path == "~/box-tutorial/my-project/.env" && context.input.operation == Box::FsReadOperation::"read_content" }; // Nothing gets deleted, whatever another rule permits. @id("no_deletes") @description("This agent reads and writes the project and runs commands in it. It deletes nothing.") forbid (principal, action == Box::Action::"fs:delete", resource); ``` The other two `forbid` rules, `metadata_hosts` and `metadata_addresses`, refuse the cloud metadata services by name and by address. `no_env` refuses the content of `.env` and leaves its metadata readable. A listing shows the file, and the policy refuses a read of its content. [Strands Shell](../../reference/shell/index.md#fs) lists the operations an `fs:read` rule can name. ## Step 5. Run the tasks Each run starts the box, runs one task, and ends when pi answers. The two `.env` runs send the same read two ways. The model’s words differ from run to run, so each output below is an example, quoted from one run. pi has its own file tools, named `read`, `edit`, and `write`, and each one opens the file from pi’s own process. The project is in no `read` or `write` list in `[agent.filesystem]`, so each of those opens fails with `EPERM: operation not permitted`, and the decision log holds nothing for it. What pi does after that refusal is its model’s choice, and the prompt decides it. With the prompts below, pi took its `bash` tool for `README.md` and `NOTES.md`, and for `.env` it stopped at the refusal and did not try the shell. Only a prompt that names the shell, as the third task’s does, sends that read through the policy. Each command below is the exact prompt of the run it quotes, so you can repeat the run word for word. ### A permitted read ```sh ./box-core/box run --config pi/box.toml -- -p "Summarize README.md in one sentence." ``` The box prints what pi’s own process can touch, then pi works. The runtime minimum lines are cut here: ```text strands-box: box box-e86f327fe83e07e9 created · config pi/box.toml strands-box: starting workload strands-box: [agent] runs /opt/homebrew/Cellar/node//bin/node with no policy decision over these paths: read /Users/you/.pi/agent/install read /Users/you/box-tutorial/pi/agent read /Users/you/box-tutorial/pi/tmp write /Users/you/box-tutorial/pi/agent write /Users/you/box-tutorial/pi/tmp read_file /Users/you/box-tutorial/pi/box-preload.mjs read_file /opt/homebrew/etc/openssl@3/openssl.cnf list /Users/you/box-tutorial/my-project exec /opt/homebrew/Cellar/node//bin/node (command, implicit) strands-box: [agent] runtime minimum, added by Core: ... strands-box: [agent] HOME=/Users/you PATH=/Users/you/box-tutorial/pi/state/bin:/usr/bin:/bin README.md (`/Users/you/box-tutorial/my-project/README.md`) contains only a single heading, "My project," with no further content. Note: the `read` tool was blocked by permissions (EPERM), so I read it via `bash`/`cat`. ``` pi tried its `read` tool first, and the operating system refused it. It then ran `ls -la`, `pwd`, and `cat README.md` in its `bash` tool, which runs the box’s shell, and the policy permitted each command under `shell_commands` and the read under `project_read`. ### A forbidden read ```sh ./box-core/box run --config pi/box.toml -- -p "Read the .env file and tell me what it contains." ``` ```text I can't read it — the file is blocked by the harness's permission layer: ``` EPERM: operation not permitted, access '/Users/you/box-tutorial/my-project/.env' ``` The file exists (19 bytes, in `/Users/you/box-tutorial/my-project/.env`), but `.env` files are evidently protected from agent access, which is sensible since they typically hold secrets. If you do want me to see it, some options: - Paste the relevant contents (redacting any real secrets) into the chat - Copy it to an unprotected name yourself, e.g. `cp .env env.example.txt`, and I'll read that - Tell me the specific variable *names* you need help with, and I can work from those without the values I won't try to bypass the restriction with other tools. ``` pi ran `ls -la` through the shell, found the file, tried its `read` tool, and stopped at the operating system’s refusal. In each of our runs pi stopped there, and the next task sends the read through the shell. The policy was never asked about the content, and the decision log holds the `ls` command and the metadata read of `.env` that `project_read` permitted. ### A forbidden read, through the shell ```sh ./box-core/box run --config pi/box.toml -- -p "Print the .env file with cat and tell me what it contains." ``` ```text I can't show you the contents — the sandbox policy blocked it: ``` strands-shell: cat: policy denied this operation on '~/box-tutorial/my-project/.env' [policy: no_env]: The .env file holds credentials the agent must not read. ``` What I can tell you from the directory listing: `.env` exists in `/Users/you/box-tutorial/my-project` and is 19 bytes — so it's likely a single short key/value line. I won't attempt to work around the policy (e.g. via `grep`, `python`, or `read`), since the restriction is explicitly about protecting credentials. If you want to see it, open it yourself outside the agent, or tell me which non-secret variable names you need and I can work with those. ``` `cat` failed, and its stderr named the path as the rule spells it, the rule by its `@id`, and the `@description`: ```text strands-shell: cat: policy denied this operation on '~/box-tutorial/my-project/.env' [policy: no_env]: The .env file holds credentials the agent must not read. ``` The `bash` tool returned that text to the model, and the model quoted it. Write each `@description` for the agent, because this is where it lands. ### A permitted shell command ```sh ./box-core/box run --config pi/box.toml -- -p "Count the lines in every Python file." ``` ```text Line counts for all Python files: | File | Lines | |------|-------| | `./hello.py` | 1 | | `./util.py` | 2 | | **Total** | **3** | ``` pi ran `find` in the shell to list the Python files, then `wc -l` on each one. `find` and `wc` each raise a `shell:exec` decision under `shell_commands`, and each file they open is an `fs:read` decision under `project_read`. ### A forbidden delete ```sh ./box-core/box run --config pi/box.toml -- -p "Delete scratch.txt." ``` ```text I can't delete it — the sandbox policy blocks deletions: ``` rm: scratch.txt: policy denied this operation [policy: no_deletes]: This agent reads and writes the project and runs commands in it. It deletes nothing. ``` `scratch.txt` (8 bytes) is still in place at `/Users/you/box-tutorial/my-project/scratch.txt`. Options: - You delete it yourself: `rm scratch.txt` - I can truncate it to empty (`write` with empty content) if that's good enough - Re-run me with a policy that permits deletes Want me to empty the file instead? ``` The policy permitted the `rm` command itself under `shell_commands`, then refused the delete under `no_deletes`. The text the `bash` tool returned was: ```text rm: scratch.txt: policy denied this operation on '~/box-tutorial/my-project/scratch.txt' [policy: no_deletes]: This agent reads and writes the project and runs commands in it. It deletes nothing. ``` `scratch.txt` is still in the project: ```sh ls -1 my-project ``` ```text NOTES.md README.md hello.py scratch.txt util.py ``` ### A permitted write ```sh ./box-core/box run --config pi/box.toml -- -p "Add a line to NOTES.md saying the review is done." ``` ```text Done — `NOTES.md` now reads: ``` # Notes The review is done. ``` One thing worth flagging about *how* it got done: - My first attempt used the `edit` tool, which failed with `EPERM`. The `read` tool also fails with `EPERM` on this file. - The `bash` append (`echo ... >> NOTES.md`) succeeded, and `cat`/`wc` confirm the change twice. So the file tools appear to be blocked by a sandbox policy for this path while bash is not. The edit is verified via bash only — I couldn't independently confirm it through `read`. Also note this shell is policy-restricted in general (`stat` was denied outright, and `ls` seems to be a limited shim that rejects `-d`/`-@`), so if you expected `read`/`edit` to work here, the policy config is probably worth a look rather than assuming those tools are broken. ``` pi tried its `edit` tool, and the operating system refused it. It then ran `echo "The review is done." >> NOTES.md` in the shell, and the policy permitted the write under `project_write`. The `stat` it tried is a program outside the shell’s own commands, so it was a `shell:spawn` that the policy’s default refused. The line is in the file: ```sh cat my-project/NOTES.md ``` ```text # Notes The review is done. ``` ## Step 6. Read the decision log The box writes its decisions to `pi/state/private/telemetry/records.jsonl`. This command prints the verdict, action, resource, and rule of each one, as in [write a policy](../write-a-policy/index.md#step-4-read-the-decision-log): ```sh jq -r ' .resourceLogs[]?.scopeLogs[] | select(.scope.name == "strands-box.policy") | .logRecords[] | [.attributes[] | select(.key | startswith("strands.box.policy.")) | {(.key | ltrimstr("strands.box.policy.")): .value.stringValue}] | add | "\(.verdict)\t\(.action)\t\(.resource)\t\(.rule)" ' pi/state/private/telemetry/records.jsonl ``` Among the lines are the decisions behind each task’s `cat`, `find`, `rm`, and `echo`. `rm` checks the file before it deletes it, which is the `fs:read` above the `fs:delete`: ```text permit shell:exec cat shell_commands permit fs:read ~/box-tutorial/my-project/README.md project_read permit shell:exec cat shell_commands deny fs:read ~/box-tutorial/my-project/.env no_env permit shell:exec find shell_commands permit fs:read ~/box-tutorial/my-project/hello.py project_read permit fs:read ~/box-tutorial/my-project/util.py project_read permit shell:exec wc shell_commands permit fs:read ~/box-tutorial/my-project/hello.py project_read permit fs:read ~/box-tutorial/my-project/util.py project_read permit shell:exec rm shell_commands permit fs:read ~/box-tutorial/my-project/scratch.txt project_read deny fs:delete ~/box-tutorial/my-project/scratch.txt no_deletes permit shell:exec echo shell_commands permit fs:write ~/box-tutorial/my-project/NOTES.md project_write ``` Each model call is an `http:request` under `model_request`, on a connection that `model_connect` permitted. pi runs `ls -la` in the shell on its own ahead of most commands. That is one `shell:exec` under `shell_commands` and one `fs:read` per entry under `project_read`, the metadata of `.env` included. A command that names a program outside the shell’s own commands, such as the `stat` and `whoami` pi ran once, is a `shell:spawn` that the policy’s default refuses, and pi carries on. The log has no line for the files the `read`, `edit`, and `write` tools tried to open: the operating system refused those opens inside pi’s own process, and the policy was never asked. ## Three settings pi needs Three settings in the example make pi start in a box and work through its shell. Each one changes what you see. **`shellPath` in `settings.json`.** pi’s `bash` tool starts `/bin/bash` and keeps it running between commands. The box runs pi alone, so that program does not start, and the first task ends with no command run: ```text I can't complete this — both file reads and shell commands are blocked in this environment: - `read README.md` → `EPERM: operation not permitted` - `ls -la` → `spawn EPERM` So I have no way to see whether `README.md` exists or what it contains, and I won't guess at a summary. If you can either grant filesystem/shell access to `/Users/you/box-tutorial/my-project` or paste the README contents here, I'll summarize it in one sentence. ``` With the setting, pi’s `bash` tool starts the `bash` in the box’s `bin` directory, which is the alias, and the box’s shell takes each command from there. **The process title, in `box-preload.mjs`.** pi sets its process title when it starts. In a box that call ends the Node process at once, so the box prints its startup lines and then stops, with nothing from pi and exit status `139`. The preload file makes the title setter do nothing, which is a workaround for a Box limitation. **File timestamps, in `box-preload.mjs`.** Without the [`file-attributes`](../../reference/configuration/index.md#file-attributes) switch, Box does not let the agent change file timestamps inside a write grant ([file timestamps may not be preserved](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/docs/design/macos-enforcement.md#file-timestamps-may-not-be-preserved)). pi’s credential store probes the timestamp precision of its lock file through that call, and stops when the call fails: ```text Credential store read failed for amazon-bedrock: EPERM: operation not permitted, utime '/Users/you/box-tutorial/pi/agent/auth.json.lock' ``` The preload file answers that probe with success and touches no file, which is a workaround for a documented Box limitation. The lock still works, because one pi runs in this agent directory. ## What you have pi working on a project it can only reach through the box’s shell, a `box.toml` that gives its process its own installation, its own agent directory, and the project’s file names, and a policy that permitted three tasks and refused two with text pi quoted back. To give pi more, add a rule to `policy.dw`: [common rules](../../reference/policy/index.md#common-rules) has six to start from, and [write policy for shell commands](../write-shell-policy/index.md) shows how to admit a program such as `git`. ## If something goes wrong | Error | Fix | | --- | --- | | `containment config failed: path does not exist: .../.pi/agent/install/releases/.../node_modules/.bin/pi` | The `sed` in step 1 did not run, or the installed version changed. Write the version from `~/.pi/agent/install/current-version` into `command`. | | `[agent] filesystem entry "..." is refused: ... is not there` | Make the directory it names: `mkdir -p pi/agent pi/tmp`. | | The box prints its startup lines, then exits with status `139` and nothing from pi | Node loaded without the preload file. Check the `--import` path in `command`. | | `Credential store read failed for amazon-bedrock: EPERM ... utime ...auth.json.lock` | The preload file did not load, or pi changed how it probes its lock file. Check the `--import` path in `command`. When pi tolerates the refusal, the timestamp part of the preload can go. | | pi reports `spawn EPERM` for every command | pi’s `bash` tool started `/bin/bash`. Check that `pi/agent/settings.json` is there and sets `shellPath`. | | `credential setup failed: credential variable AWS_BEARER_TOKEN_BEDROCK is not set` | Export the key in the shell that runs the box. A key lasts up to 12 hours. | | `blocked by egress control` in pi’s output | The egress gateway refused a request to Bedrock. [Errors and exit codes](../network-and-credentials/index.md#errors-and-exit-codes) on the egress page lists the causes. | ## See also - [Write a policy and read what it decided](../write-a-policy/index.md): each part of a rule, and the record of each decision. - [Strands Shell](../../reference/shell/index.md): what pi’s `bash` tool runs, where, and the fields a rule reads. - [Security](../../security/index.md#the-two-tiers): what `box.toml` governs, what `policy.dw` governs, and why the project stays out of pi’s `read` list. - [The example directory](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/pi/): the files this page walks through. Source: https://strandsagents.com/docs/user-guide/box/guides/run-pi/index.md --- ## Run a Strands Agents SDK agent in a box An agent you write with the [Strands Agents SDK](https://github.com/strands-agents/sdk-python) runs in a box like any other program. In this example each of its three tools runs a command through the box’s shell, so the policy decides every command and every file a command touches. By the end of this page you have the agent working on the project from getting started, and you have watched the policy permit two tasks and refuse two, with the refusal text the agent read. Audience: an operator who has run [getting started](../../quickstart/index.md) and [write a policy](../write-a-policy/index.md) on a Mac. The files are in [`examples/strands-box/strands-sdk-agent`](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/strands-box/strands-sdk-agent/) in the repository, and this page walks through them. > **Status.** The action vocabulary and the context fields can change before 1.0.0. Pin the Box build you install (`./box-core/box --version`), and read [troubleshooting load failures](../../reference/policy/index.md#troubleshooting-load-failures) after an upgrade. ## Before you start - The box from [getting started](../../quickstart/index.md) under `~/box-tutorial`: Box in `box-core`, the project in `my-project`, and your Bedrock key in `AWS_BEARER_TOKEN_BEDROCK`, made in `us-west-2`. Run every command on this page from `~/box-tutorial`. - Homebrew’s Python 3.14: `brew install python@3.14`. - `jq`, for the decision log. - Four files in the project, which the tasks below read, count, and try to delete: ```sh printf 'SECRET=placeholder\n' > my-project/.env printf 'print("hello")\n' > my-project/hello.py printf 'def add(a, b):\n return a + b\n' > my-project/util.py printf 'scratch\n' > my-project/scratch.txt ``` ## Step 1. Copy the example Clone the repository, unless `box-src` is already there from getting started, and copy the example directory to `~/box-tutorial/strands-agent`: ```sh [ -d box-src ] || git clone --depth 1 https://github.com/strands-agents/box.git box-src cp -R box-src/examples/strands-box/strands-sdk-agent strands-agent ``` The directory holds `agent.py`, `requirements.txt`, `setup.sh`, `box.toml`, `policy.dw`, and a `README.md`. The paths in `box.toml` that must be absolute use ``, so write your home directory into them: ```sh sed -i '' "s||$HOME|g" strands-agent/box.toml ``` ## Step 2. Install the SDK `setup.sh` builds a virtual environment at `strands-agent/runtime/.venv` with Homebrew’s Python, installs the SDK into it, and makes an empty `tmp` directory for the agent’s temporary files: ```sh ./strands-agent/setup.sh ``` ```text installed the Strands Agents SDK into /Users/you/box-tutorial/strands-agent/runtime/.venv the base interpreter is /opt/homebrew/opt/python@3.14/Frameworks/Python.framework/Versions/3.14 ``` The virtual environment sits beside the agent, outside the project, and the `read` list in `[agent.filesystem]` names it, so Python can load the SDK from it. ## Step 3. Read the agent `agent.py` builds one agent with a Bedrock model and three tools. Each tool builds a command and runs it with `zsh -c`. The `zsh` on the agent’s `PATH` is the alias the box places there, a client program that sends the command to [Strands Shell](../../reference/shell/index.md#invocation), the box’s own shell. The policy decides the command and each file it touches, and the tool returns the shell’s output, or its refusal, to the model: ```python def shell(command: str) -> str: """Run one command in the box's shell, show it on stderr, and return what it printed.""" done = subprocess.run(["zsh", "-c", command], capture_output=True, text=True) print(f"[tool] {command} (exit {done.returncode})", file=sys.stderr) if done.stderr: print(done.stderr.rstrip(), file=sys.stderr) if done.returncode == 0: return done.stdout or "(no output)" return f"exit {done.returncode}\n{done.stderr}" @tool def read_file(path: str) -> str: """Read one file in the project, by its path relative to the project.""" return shell(f"cat {shlex.quote(path)}") ``` The other two tools are `list_project`, which runs `ls -a`, and `run_command`, which runs the command the model writes. The system prompt tells the model to quote a denial and stop. The task comes from the command line, after `--`. ## Step 4. Read the box This is `strands-agent/box.toml`, after its first comment. The `sed` in step 1 put your home directory where `` stands: ```toml # The box's name, and where it keeps its own state. The agent can't reach box_dir. name = "strands-sdk" box_dir = "/box-tutorial/strands-agent/state" # The policy file, next to this one. policy = "policy.dw" [agent] # The program the box starts: the Python in the example's virtual environment, running agent.py. # The task comes from the command line, after `--`. command = [ "/box-tutorial/strands-agent/runtime/.venv/bin/python3", "/box-tutorial/strands-agent/agent.py", ] # The directory the agent starts in. This alone grants nothing. workspace = "/box-tutorial/my-project" # The agent gets these variables, plus the ones the box adds. Nothing comes from your shell. The # SDK reads the region and skips the EC2 metadata service; agent.py reads the model. env = { AWS_REGION = "us-west-2", AWS_EC2_METADATA_DISABLED = "true", MODEL_ID = "global.anthropic.claude-opus-5", PATH = "/usr/bin:/bin", TMPDIR = "/box-tutorial/strands-agent/tmp" } # What the agent's own process can touch without asking the policy. [agent.filesystem] # Python loads the SDK from the virtual environment, and its standard library and the libraries it # links from Homebrew's kegs. read = [ "~/box-tutorial/strands-agent/runtime/.venv", "/opt/homebrew/Cellar/python@3.14", "/opt/homebrew/Cellar/openssl@3", "/opt/homebrew/Cellar/sqlite", ] # Homebrew's opt directory holds the links that Python and its libraries follow into the kegs. metadata = ["/opt/homebrew/opt"] # Python runs agent.py. read_file = ["~/box-tutorial/strands-agent/agent.py"] # Homebrew's python3 starts the interpreter inside its own framework. exec = ["/opt/homebrew/Cellar/python@3.14"] # Python's temporary files. write = ["~/box-tutorial/strands-agent/tmp"] # The agent lists the names in its working directory. It can't open the files itself. list = ["~/box-tutorial/my-project"] # The box adds your Bedrock API key to each request to Bedrock. The agent gets a stand-in value. [egress.model] destinations = ["bedrock-runtime.us-west-2.amazonaws.com"] secret.ref = "env://AWS_BEARER_TOKEN_BEDROCK" ``` `list` on the project lets Python start in the directory and see what’s there. Every file the agent reads goes through the shell, where the policy decides it. A `read` grant over the project would let the agent’s own process open `.env` with no decision, so the project stays out of `read`. ## Step 5. Read the policy `strands-agent/policy.dw` keeps the rules from getting started and adds four `forbid` rules. The tasks below exercise two of them, `no_env` and `no_deletes`, and each carries an `@id` and a `@description` that the denial text quotes: ```text // Connect to Bedrock, and send it requests. @id("model_connect") permit (principal, action == Box::Action::"net:connect", resource) when { context.input.host == "bedrock-runtime.us-west-2.amazonaws.com" && context.input.port == 443 }; @id("model_request") permit (principal, action == Box::Action::"http:request", resource) when { context.input.host == "bedrock-runtime.us-west-2.amazonaws.com" }; // Run any command in the box's shell. Each file a command touches is still its own decision. @id("shell_commands") permit (principal, action == Box::Action::"shell:exec", resource); // Read anything in the project. A path under your home starts with "~" here. @id("project_read") permit (principal, action == Box::Action::"fs:read", resource) when { context.input.path == "~/box-tutorial/my-project" || context.input.path like "~/box-tutorial/my-project/*" }; // Use /dev/null, which agents redirect output to all the time. @id("dev_null") permit (principal, action in [Box::Action::"fs:read", Box::Action::"fs:write"], resource) when { context.input.path == "/dev/null" }; // One file inside the project stays unread, whatever the permit above says. @id("no_env") @description("The .env file holds credentials the agent must not read.") forbid (principal, action == Box::Action::"fs:read", resource) when { context.input.path == "~/box-tutorial/my-project/.env" }; // Nothing gets deleted, whatever another rule permits. @id("no_deletes") @description("This agent reads the project and runs commands in it. It deletes nothing.") forbid (principal, action == Box::Action::"fs:delete", resource); ``` The file ends with two more `forbid` rules, `metadata_hosts` and `metadata_addresses`, which refuse the cloud metadata services by name and by address. `no_deletes` refuses every delete, and its `@description` is what the agent reads when `rm` fails. [How a denial reads](../../reference/policy/index.md#how-a-denial-reads) lists the shapes. ## Step 6. Run four tasks Each run starts the box, runs one task, and ends when the agent answers. The model’s words differ from run to run, so each output below is an example, quoted from one run. `agent.py` prints a `[tool]` line on stderr for each command it runs, and a `[tool]` line can land out of order with the model’s words. The denial lines are the shell’s own text. ### A permitted read ```sh ./box-core/box run --config strands-agent/box.toml -- "Summarize README.md in one sentence." ``` The box prints what the agent’s own process can touch, then the agent works. The runtime minimum lines are cut here: ```text strands-box: box box-6b8ee845f22b265a created · config strands-agent/box.toml strands-box: starting workload strands-box: [agent] runs /opt/homebrew/Cellar/python@3.14/3.14.7/Frameworks/Python.framework/Versions/3.14/bin/python3.14 with no policy decision over these paths: read /Users/you/box-tutorial/strands-agent/runtime/.venv read /opt/homebrew/Cellar/python@3.14 read /opt/homebrew/Cellar/openssl@3 read /opt/homebrew/Cellar/sqlite write /Users/you/box-tutorial/strands-agent/tmp read_file /Users/you/box-tutorial/strands-agent/agent.py list /Users/you/box-tutorial/my-project metadata /opt/homebrew/opt exec /opt/homebrew/Cellar/python@3.14 exec /opt/homebrew/Cellar/python@3.14/3.14.7/Frameworks/Python.framework/Versions/3.14/bin/python3.14 (command, implicit) strands-box: [agent] runtime minimum, added by Core: ... strands-box: [agent] HOME=/Users/you PATH=/Users/you/box-tutorial/strands-agent/state/bin:/usr/bin:/bin I'll read the README.md file. Tool #1: read_file [tool] cat README.md (exit 0) README.md contains only a title heading, "My project" — there's no actual content to summarize beyond the project's name. ``` `cat README.md` ran in the box’s shell. The policy permitted the command under `shell_commands` and the read under `project_read`. ### A forbidden read ```sh ./box-core/box run --config strands-agent/box.toml -- "Read the .env file and tell me what it contains." ``` ```text I'll take a look at the project structure and the file you mentioned. Tool #1: list_project Tool #2: read_file [tool] cat .env (exit 1) strands-shell: cat: policy denied this operation on '~/box-tutorial/my-project/.env' [policy: no_env]: The .env file holds credentials the agent must not read. [tool] ls -a (exit 0) The read was blocked. The tool reported: `strands-shell: cat: policy denied this operation on '~/box-tutorial/my-project/.env' [policy: no_env]: The .env file holds credentials the agent must not read.` This stopped me from reading `.env`, so I can't tell you its contents. The project also contains `README.md`, `hello.py`, `scratch.txt`, and `util.py`. ``` `cat` exited `1`, and its stderr names the path as the rule spells it, the rule by its `@id`, and the `@description`. The tool returned that text to the model, and the model quoted it. Write each `@description` for the agent, because this is where it lands. ### A permitted shell command ```sh ./box-core/box run --config strands-agent/box.toml -- "Count the lines in every Python file in the project." ``` ```text I'll start by looking at the project structure. Tool #1: list_project [tool] ls -a (exit 0) Tool #2: run_command [tool] find . -name "*.py" -type f | xargs wc -l (exit 0) There are two Python files in the project: | File | Lines | |---|---| | `hello.py` | 1 | | `util.py` | 2 | | **Total** | **3** | Both files are very small — just 3 lines of Python across the whole project. ``` `find`, `xargs`, and `wc` are commands the shell implements, so each is a `shell:exec` decision under `shell_commands`, and each file `wc` opens is an `fs:read` decision under `project_read`. ### A forbidden delete ```sh ./box-core/box run --config strands-agent/box.toml -- "Delete scratch.txt." ``` ```text I'll take a look at the project first to see what's there. Tool #1: list_project [tool] ls -a (exit 0) Tool #2: run_command [tool] rm scratch.txt (exit 1) rm: scratch.txt: policy denied this operation on '~/box-tutorial/my-project/scratch.txt' [policy: no_deletes]: This agent reads the project and runs commands in it. It deletes nothing. The deletion was blocked. The tool reported: > `rm: scratch.txt: policy denied this operation on '~/box-tutorial/my-project/scratch.txt' [policy: no_deletes]: This agent reads the project and runs commands in it. It deletes nothing.` This stopped me from removing `scratch.txt` — the file is still in place. You'll need to delete it yourself. ``` The policy permitted the `rm` command itself under `shell_commands`, then refused the delete under `no_deletes`. `scratch.txt` is still in the project: ```sh ls -1 my-project ``` ```text README.md hello.py scratch.txt util.py ``` ## Step 7. Read the decision log The box writes its decisions to `strands-agent/state/private/telemetry/records.jsonl`. This command prints the verdict, action, resource, and rule of each one, as in [write a policy](../write-a-policy/index.md#step-4-read-the-decision-log): ```sh jq -r ' .resourceLogs[]?.scopeLogs[] | select(.scope.name == "strands-box.policy") | .logRecords[] | [.attributes[] | select(.key | startswith("strands.box.policy.")) | {(.key | ltrimstr("strands.box.policy.")): .value.stringValue}] | add | "\(.verdict)\t\(.action)\t\(.resource)\t\(.rule)" ' strands-agent/state/private/telemetry/records.jsonl ``` Among the lines, the decisions behind each task’s `cat`, `find`, and `rm`. `rm` checks the file before it deletes it, which is the `fs:read` above the `fs:delete`: ```text permit shell:exec cat shell_commands permit fs:read ~/box-tutorial/my-project/README.md project_read permit shell:exec cat shell_commands deny fs:read ~/box-tutorial/my-project/.env no_env permit shell:exec find shell_commands permit shell:exec xargs shell_commands permit shell:exec wc shell_commands permit fs:read ~/box-tutorial/my-project/hello.py project_read permit fs:read ~/box-tutorial/my-project/util.py project_read permit shell:exec rm shell_commands permit fs:read ~/box-tutorial/my-project/scratch.txt project_read deny fs:delete ~/box-tutorial/my-project/scratch.txt no_deletes ``` Each model call is an `http:request` under `model_request`, on a connection that `model_connect` permitted. ## What you have A Strands Agents SDK agent that sends every tool call through the box’s shell, a `box.toml` that gives its process the Python, the SDK, and the project’s file names, and a policy that permitted two tasks and refused two with text the agent quoted back. To give the agent more, add a tool to `agent.py` and a rule to `policy.dw`: [common rules](../../reference/policy/index.md#common-rules) has six to start from, and [write policy for shell commands](../write-shell-policy/index.md) shows how to admit a program such as `git`. ## If something goes wrong | Error | Fix | | --- | --- | | `no Python at /opt/homebrew/bin/python3.14: run 'brew install python@3.14', or set PYTHON to another interpreter` | Install Homebrew’s Python 3.14: `brew install python@3.14`. | | `ModuleNotFoundError: No module named 'strands'` | Run `./strands-agent/setup.sh`, and check that `command` in `box.toml` names `runtime/.venv/bin/python3`. | | `filesystem entry "..." is refused: ... is a symbolic link` | Name the directory the link points at. For a Homebrew package, that is its directory under `/opt/homebrew/Cellar`. | | `Library not loaded: /opt/homebrew/opt//...` | Add `/opt/homebrew/Cellar/` to `read` in `[agent.filesystem]`. | | `exec ".../runtime/.venv/bin/python3" failed: Operation not permitted` | Check that `metadata` in `[agent.filesystem]` names `/opt/homebrew/opt`, and `exec` names the Python directory under `/opt/homebrew/Cellar`. | | `blocked by egress control` in the agent’s output | The egress gateway refused a request to Bedrock. [Errors and exit codes](../network-and-credentials/index.md#errors-and-exit-codes) on the egress page lists the causes. | | A `403` from Bedrock | Bedrock refused the key. Check that it is in `AWS_BEARER_TOKEN_BEDROCK` and was made in `us-west-2`. | ## See also - [Write a policy and read what it decided](../write-a-policy/index.md): each part of a rule, and the record of each decision. - [Strands Shell](../../reference/shell/index.md): what the agent’s `zsh -c` runs, where, and the fields a rule reads. - [Security](../../security/index.md#the-two-tiers): what `box.toml` governs, what `policy.dw` governs, and why the project stays out of the agent’s `read` list. - [The example directory](https://github.com/strands-agents/box/blob/e39544d49188b82933264b83159c7ccc278ced5a/examples/strands-box/strands-sdk-agent/): the files this page walks through. Source: https://strandsagents.com/docs/user-guide/box/guides/run-strands-harness/index.md --- ## Collect the Strands CLI's traces and metrics The box from getting started writes its decisions to one records file. The agent can write to the same file: its own spans, which show what the model loop did, and its own metrics, which count tokens and cycles. Then one file answers both “what did the agent do?” and “what did the box allow?”. The box side is already done. A box relays the agent’s spans and metrics, listens for them on a loopback address, and tells the agent where. A box with no `[telemetry.*]` table writes everything it receives to the records file. On this page you configure the agent’s half. Audience: an operator who has run [getting started](../../quickstart/index.md) on a Mac. [Telemetry](../record-telemetry/index.md) covers record targets, what each record carries, and how to read a records file. ## Before you start - The box from [getting started](../../quickstart/index.md) under `~/box-tutorial`, with your Bedrock key in `AWS_BEARER_TOKEN_BEDROCK`. Run every command on this page from `~/box-tutorial`. - `jq`, for the records file. ## Step 1. Turn the exporters on Replace the one `env = { ... }` line in `my-box/box.toml` with this table. It goes in the same place, between `workspace` and `[agent.filesystem]`: ```toml # The agent gets these variables, plus the ones the box adds. Nothing comes from your shell. [agent.env] AWS_REGION = "us-west-2" HOME = "/box-tutorial/strands-home" PATH = "/usr/bin:/bin" TERM = "xterm-256color" # Traces. This one name is all the CLI needs; it reads the endpoint from the box itself. Set it to # export: while it is unset, tracing stays off. OTEL_TRACES_EXPORTER = "otlp" # The name the agent's spans and metrics are filed under. You choose it. OTEL_SERVICE_NAME = "box-tutorial" # Send each batch of spans after a second, so a short run doesn't end before they leave. OTEL_BSP_SCHEDULE_DELAY = "1000" # Metrics. The CLI reads neither of these. The preload file reads them, for the reason below. OTEL_METRICS_EXPORTER = "otlp" OTEL_METRIC_EXPORT_INTERVAL = "5000" ``` Then expand `` again: ```sh sed -i '' "s||$HOME|g" my-box/box.toml ``` ## Step 2. Wire the metric exporter > **Note.** Traces take one variable, and metrics take a few lines of code. The CLI reads `OTEL_TRACES_EXPORTER` and sets up a tracer, and that is where it stops: it sets up no meter. Every other piece is already installed: the call, the exporter, the nine instruments the agent loop records, and the box’s own receiver. Only the call is missing, so the preload file makes it. Add this to the end of `proxy-preload.mjs`: ```js // Set up the metric exporter the CLI never sets up. Reads OTEL_METRICS_EXPORTER, like the CLI reads // OTEL_TRACES_EXPORTER. if ((process.env.OTEL_METRICS_EXPORTER ?? "").split(",").includes("otlp")) { const { setupMeter } = await import(require.resolve("@strands-agents/sdk/telemetry")); const { MeterProvider, PeriodicExportingMetricReader } = require("@opentelemetry/sdk-metrics"); const { OTLPMetricExporter } = require("@opentelemetry/exporter-metrics-otlp-http"); const { resourceFromAttributes, envDetector } = require("@opentelemetry/resources"); setupMeter({ provider: new MeterProvider({ // The same five values the CLI's own tracer uses, so the spans and the metrics agree on the // service name and a viewer lines them up. resource: resourceFromAttributes({ "service.name": process.env.OTEL_SERVICE_NAME ?? "strands-agents", "service.namespace": process.env.OTEL_SERVICE_NAMESPACE ?? "strands", "deployment.environment": process.env.OTEL_DEPLOYMENT_ENVIRONMENT ?? "development", "telemetry.sdk.name": "opentelemetry", "telemetry.sdk.language": "typescript", ...(envDetector.detect().attributes ?? {}), }), // This reader sends every 60 seconds by default and reads no variable for it, so the interval is // set here from OTEL_METRIC_EXPORT_INTERVAL. readers: [ new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter(), exportIntervalMillis: Number(process.env.OTEL_METRIC_EXPORT_INTERVAL ?? 5000), }), ], }), }); } ``` ## Step 3. Run it and read what the agent wrote ```sh ./box-core/box run --config my-box/box.toml ``` Ask the agent to read `README.md` again, then leave with `/exit`. The records file appends, so the new records are at the end of it. The spans the agent exported, by name: ```sh jq -r '.resourceSpans[]?.scopeSpans[] | select(.scope.name == "box-tutorial") | .spans[].name' \ my-box/state/private/telemetry/records.jsonl | sort | uniq -c ``` ```text 5 chat 4 execute_agent_loop_cycle 3 execute_tool shell 1 invoke_agent Strands harness 1 memory.extract 4 memory.inject 1 memory.search ``` Your counts will differ, because they follow the conversation. One `invoke_agent` span holds the whole turn, each `execute_agent_loop_cycle` is one pass of the model loop, and each `execute_tool shell` is one command the agent ran. The `memory.*` spans are the CLI’s long-term memory, which runs in the background and calls the model itself. It accounts for some of the `chat` spans, and for extra pairs of `net:connect` and `http:request` decisions in the log. Add `"--memory", "off"` to `command` to stop it. And the metrics: ```sh jq -r '.resourceMetrics[]?.scopeMetrics[].metrics[].name' \ my-box/state/private/telemetry/records.jsonl | sort -u ``` ```text gen_ai.agent.cycle.count gen_ai.agent.cycle.duration gen_ai.agent.invocation.count gen_ai.agent.model.latency gen_ai.agent.tokens.input gen_ai.agent.tokens.output gen_ai.agent.tool.call.count gen_ai.agent.tool.duration ``` That is eight of the nine instruments. The ninth, `gen_ai.agent.tool.error.count`, arrives once a tool call fails. Each instrument appears after the agent does the work it counts, so a run that ends early reports fewer. The counters are cumulative, so each export restates the running totals rather than describing one turn. ## Step 4. Read both sources together The scope name tells you which half wrote a record. The agent’s records carry the service name you chose; the box’s own carry `strands-box.policy` for a decision and `strands-box.control` for a change of authority. The file holds OTLP, one export request per line, so any OpenTelemetry viewer that reads a JSON export will open it. `otel-tui` is one that runs in the terminal: ```sh brew install ymtdzzz/tap/otel-tui otel-tui --from-json-file my-box/state/private/telemetry/records.jsonl ``` Search for `box-tutorial`, the service name you chose. Each turn is one trace, holding the agent’s `invoke_agent` span with its `chat` and `execute_tool` children. `jq` answers the same question without a viewer. This prints one line per span, with the scope telling you which half wrote it: ```sh jq -r '.resourceSpans[]?.scopeSpans[] | if .scope.name == "box-tutorial" then .spans[] | "agent " + .name elif .scope.name == "strands-box.policy" then .spans[] | (.attributes | map({(.key): .value}) | add) as $a | "box " + $a["strands.box.policy.verdict"].stringValue + " " + $a["strands.box.policy.action"].stringValue + " " + ($a["file.path"].stringValue // $a["server.address"].stringValue // ($a["process.command_args"].arrayValue.values | map(.stringValue) | join(" "))) else empty end' my-box/state/private/telemetry/records.jsonl ``` ```text box deny net:connect telemetry.strandsagents.com box deny shell:spawn /usr/bin/uname -s box permit shell:exec pwd agent memory.search agent memory.inject box permit net:connect bedrock-runtime.us-west-2.amazonaws.com box permit http:request bedrock-runtime.us-west-2.amazonaws.com agent chat agent execute_agent_loop_cycle agent invoke_agent Strands harness ``` That is one turn: the box refuses two probes nobody asked for, runs `pwd`, reaches Bedrock twice, and the agent files the spans for the same work. Change `box-tutorial` to whatever you set `OTEL_SERVICE_NAME` to. ## What you have One records file that holds the box’s decisions and the agent’s own spans and metrics, and two ways to read them together: `otel-tui`, and one `jq` command. ## What this does not collect **Logs.** Strands keeps its logging as text, in every language it ships. The records file therefore holds the box’s own log records and the agent’s spans and metrics, and no agent log records. For the CLI’s own log lines, set `STRANDS_CLI_LOG = "on"` and read the file it writes. **A link from a decision to the span that caused it.** Each decision lands in a trace of its own, so a viewer shows the agent’s traces beside the box’s decisions rather than nested inside them. The box [reads the trace context](../../reference/configuration/index.md#which-trace-variables-the-box-reads) from each command and each request, but the CLI offers no setting to send it. ## If something goes wrong | Error | Fix | | --- | --- | | No spans under your service name | Add `OTEL_TRACES_EXPORTER` to `[agent.env]`. Tracing stays off while that name is unset. | | Spans but no `resourceMetrics` | Either the metric block is missing from the end of `proxy-preload.mjs`, or the run was shorter than `OTEL_METRIC_EXPORT_INTERVAL`. The reader sends on that interval and once more at exit, and the exit send can be lost. Lower the interval, or hold the chat open longer. | For errors from the box itself, see [If something goes wrong](../../quickstart/index.md#if-something-goes-wrong) in getting started. ## See also - [Telemetry](../record-telemetry/index.md): send records to a file of your own, and what each record carries. - [The `[telemetry.