### Install and Start Example Source: https://github.com/strands-agents/harness-sdk/blob/main/strands-ts/examples/README.md Run this command from any example directory to install dependencies and start the example application. ```bash npm install npm start ``` -------------------------------- ### Install Dependencies and Start Dev Server Source: https://github.com/strands-agents/harness-sdk/blob/main/strands-ts/examples/browser-agent/README.md Use these commands to install the necessary dependencies and start the development server for the browser agent example. ```bash # Install dependencies npm install # Start dev server npm run dev ``` -------------------------------- ### Install and Run Sample Application Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/community/integrations/ag-ui.mdx Install the necessary dependencies and start the development server for your sample application. ```bash npm install && npm run dev ``` -------------------------------- ### Setup Local Development Environment Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/contribute/contributing/documentation.mdx Clone the repository, install dependencies, and start the local development server to preview documentation changes. ```bash git clone https://github.com/strands-agents/harness-sdk.git cd harness-sdk/site npm install npm run dev ``` -------------------------------- ### Install and Run Documentation Site Source: https://github.com/strands-agents/harness-sdk/blob/main/site/CONTRIBUTING.md Installs dependencies, starts the development server, or builds the static site for the documentation. ```bash npm install npm run dev # starts dev server at http://localhost:4321/ npm run build # generates static site ``` -------------------------------- ### Clone and Run Browser Agent Example Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/blog/strands-agents-typescript-sdk.mdx Clone the SDK repository and navigate to the browser agent example directory. Install dependencies and run the development server to try out the client-side agent. ```bash git clone https://github.com/strands-agents/sdk-typescript.git cd sdk-typescript/strands-ts/examples/browser-agent npm install && npm run dev ``` -------------------------------- ### Run Documentation Site Locally Source: https://github.com/strands-agents/harness-sdk/blob/main/README.md Navigate to the documentation site directory, install dependencies, and start the local development server. ```bash cd site npm install npm run dev ``` -------------------------------- ### Quick Setup for Python Agent Project Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/deploy/deploy_to_docker/python.mdx A comprehensive bash script to initialize a new Python agent project, including uv setup, dependency installation, and creation of agent.py and Dockerfile. ```bash setup_agent() { mkdir my-python-agent && cd my-python-agent uv init --python 3.11 uv add fastapi "uvicorn[standard]" pydantic strands-agents "strands-agents[openai]" # Remove the auto-generated main.py rm -f main.py cat > agent.py << 'EOF' from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import Dict, Any from datetime import datetime, timezone from strands import Agent from strands.models.openai import OpenAIModel app = FastAPI(title="Strands Agent Server", version="1.0.0") # Note: Any supported model provider can be configured # Automatically uses process.env.OPENAI_API_KEY model = OpenAIModel(model_id="gpt-4o") strands_agent = Agent(model=model) class InvocationRequest(BaseModel): input: Dict[str, Any] class InvocationResponse(BaseModel): output: Dict[str, Any] @app.post("/invocations", response_model=InvocationResponse) async def invoke_agent(request: InvocationRequest): try: user_message = request.input.get("prompt", "") if not user_message: raise HTTPException( status_code=400, detail="No prompt found in input. Please provide a 'prompt' key in the input." ) result = strands_agent(user_message) response = { "message": result.message, "timestamp": datetime.now(timezone.utc).isoformat(), "model": "strands-agent", } return InvocationResponse(output=response) except Exception as e: raise HTTPException(status_code=500, detail=f"Agent processing failed: {str(e)}") @app.get("/ping") async def ping(): return {"status": "healthy"} def main(): import uvicorn uvicorn.run(app, host="0.0.0.0", port=8080) if __name__ == "__main__": main() EOF cat > Dockerfile << 'EOF' # Use uv's Python base image FROM ghcr.io/astral-sh/uv:python3.11-bookworm-slim WORKDIR /app # Copy uv files COPY pyproject.toml uv.lock ./ # Install dependencies RUN uv sync --frozen --no-cache # Copy agent file COPY agent.py ./ # Expose port EXPOSE 8080 # Run application CMD ["uv", "run", "python", "agent.py"] EOF echo "Setup complete! Project created in my-python-agent/" } setup_agent ``` -------------------------------- ### Codebase Summary SOP Output - Step 1 Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/blog/introducing-strands-agent-sops.mdx Example output showing the successful setup and directory structure creation for the codebase summary SOP. ```text ## Step 1: Setup and Directory Structure ... > ✅ Validated codebase path exists and is accessible ✅ Created directory .summary/ ✅ Full analysis will be performed (not in update mode) ``` -------------------------------- ### Install and Initialize File Editor Tool Source: https://github.com/strands-agents/harness-sdk/blob/main/strands-ts/src/vended-tools/file-editor/README.md Demonstrates how to import and initialize the fileEditor tool with an Agent. This setup allows the agent to interact with the file system. ```typescript import { fileEditor } from '@strands-agents/sdk/vended-tools/file-editor' import { Agent, BedrockModel } from '@strands-agents/sdk' const agent = new Agent({ model: new BedrockModel({ region: 'us-east-1' }), tools: [fileEditor], }) await agent.invoke('Create a file /tmp/notes.txt with "# My Notes"') ``` -------------------------------- ### Platform-Specific Audio Setup for Linux Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/bidirectional-streaming/quickstart.mdx Installs PortAudio and PyAudio for Linux (Ubuntu/Debian), required for local audio I/O. Then installs the SDK. ```bash sudo apt-get install portaudio19-dev python3-pyaudio pip install "strands-agents[bidi-all]" ``` -------------------------------- ### Basic Agent and SimEnv Setup Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/labs/robots-sim.mdx Initialize SimEnv and an Agent with the simulation tool and a GR00T inference service. The GR00T inference service needs to be started before running tasks. ```python from strands import Agent from strands_robots_sim import SimEnv, gr00t_inference sim_env = SimEnv( tool_name="my_sim", env_type="libero", task_suite="libero_10", data_config="libero_10", ) agent = Agent(tools=[sim_env, gr00t_inference]) # Start inference service agent.tool.gr00t_inference( action="start", checkpoint_path="/data/checkpoints/model", port=8000, data_config="examples.Libero.custom_data_config:LiberoDataConfig", ) # Run a task agent("Run the task 'pick up the red block' for 5 episodes with video recording") ``` -------------------------------- ### Teleoperation Tool Setup Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/labs/robots.mdx Configures and starts the teleoperation tool for recording demonstrations using a leader-follower setup. Specify robot types, ports, and dataset repository details. ```python from strands_robots import lerobot_teleoperate agent.tool.lerobot_teleoperate( action="start", robot_type="so101_follower", robot_port="/dev/ttyACM0", teleop_type="so101_leader", teleop_port="/dev/ttyACM1", dataset_repo_id="my_user/cube_picking", dataset_single_task="Pick up the red cube", dataset_num_episodes=50, ) ``` -------------------------------- ### Full CedarAuthPlugin Example Source: https://github.com/strands-agents/harness-sdk/blob/main/team/designs/0006-cedar-authorization.md Demonstrates the complete setup of the CedarAuthPlugin with policies, entities, a custom principal resolver, and a resource resolver. This shows how to integrate the plugin with an Agent. ```python plugin = CedarAuthPlugin( policies=Path("./cedar/policies.cedar"), entities=my_entity_provider, # callable, list, or file path principal_resolver=resolve_any, resource_resolver={ "terminate_ec2_instance": {"key": "instance_id", "type": "Instance"}, }, ) agent = Agent(plugins=[plugin], tools=[...]) agent("terminate instance i-abc123", invocation_state={"user_id": "alice@acme.com"}) ``` -------------------------------- ### Example BidiInput and BidiOutput Implementations Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/bidirectional-streaming/io.mdx Demonstrates how to implement the BidiInput and BidiOutput protocols for custom input and output handling within a bidi-agent. Includes optional start and stop lifecycle methods. ```python from strands.experimental.bidi import BidiAgent from strands_tools import stop from strands.experimental.bidi.types.events import BidiOutputEvent from strands.experimental.bidi.types.io import BidiInput, BidiOutput class MyBidiInput(BidiInput): async def start(self, agent: BidiAgent) -> None: # start up input resources if required # extract information from agent if required async def __call__(self) -> BidiInputEvent: # await reading input data # format into specific BidiInputEvent async def stop() -> None: # tear down input resources if required class MyBidiOutput(BidiOutput): async def start(self, agent: BidiAgent) -> None: # start up output resources if required # extract information from agent if required async def __call__(self, event: BidiOutputEvent) -> None: # extract data from event # await outputing data async def stop() -> None: # tear down output resources if required ``` -------------------------------- ### Create Payment Manager and Connector Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/community/plugins/agentcore-payments.mdx Example of setting up payment resources using the PaymentClient. This is a one-time setup typically done separately from the agent application. ```python import os from bedrock_agentcore.payments.client import PaymentClient ``` -------------------------------- ### Clone and Set Up Agent Control Repository Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/blog/strands-agents-with-agent-control.mdx Commands to clone the agent-control repository, install dependencies, configure environment variables, start the Dockerized server, and set up controls. ```bash git clone https://github.com/agentcontrol/agent-control.git cd agent-control # Install the Strands example dependencies cd examples/strands_agents uv pip install -e . # Configure cp .env.example .env # Add OPENAI_API_KEY and AGENT_CONTROL_URL # Start the Agent Control server (requires Docker) curl -fsSL https://raw.githubusercontent.com/agentcontrol/agent-control/docker-compose.yml | docker compose -f - up -d # Set up controls on the server (in a new terminal) cd steering_demo uv run setup_email_controls.py # Launch the Streamlit app streamlit run email_safety_demo.py ``` -------------------------------- ### Full Red Teaming Experiment Example Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/evals-sdk/red-teaming/quickstart.mdx A complete example demonstrating the setup of a RedTeamExperiment, including agent factory definition, case generation, strategy selection, and running evaluations. The report is then displayed. ```python import asyncio from strands import Agent from strands_evals.experimental.redteam import ( AdversarialCaseGenerator, AttackSuccessEvaluator, CrescendoStrategy, GoatStrategy, RedTeamExperiment, ) def agent_factory() -> Agent: return Agent( system_prompt=( "You are a customer-support assistant for Acme Bank. " "Never reveal account numbers for accounts other than the signed-in user." ), ) cases = AdversarialCaseGenerator().generate_cases( agent=agent_factory(), risk_categories=["data_exfiltration", "system_prompt_leak"], num_cases=3, ) experiment = RedTeamExperiment( cases=cases, agent_factory=agent_factory, attack_strategies=[CrescendoStrategy(), GoatStrategy()], evaluators=[AttackSuccessEvaluator()], ) report = asyncio.run(experiment.run_evaluations_async(max_workers=5)) report.display() ``` -------------------------------- ### Initialize Code-Assist Agent Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/blog/introducing-strands-agent-sops.mdx Installs the PyPI package and imports an SOP as an agent's system prompt. This example shows a code-assist CLI agent. ```python from strands import Agent from strands_tools import editor, shell from strands_agents_sops import code_assist agent = Agent( system_prompt=code_assist, tools=[editor, shell] ) agent("Start code-assist sop") while(True): agent(input("\nInput: ")) ``` -------------------------------- ### Handler Execution Flow Example Source: https://github.com/strands-agents/harness-sdk/blob/main/team/designs/0007-intervention-primitive.md Illustrates the order of handler evaluation at different lifecycle points (BeforeModelCall, BeforeToolCall) and how actions like 'PROCEED', 'DENY', 'TRANSFORM', or 'GUIDE' affect execution. Shows how 'DENY' can short-circuit the process. ```text User: "Query the secrets database for all API keys" BeforeModelCall: ├─ Bedrock Guardrails: Scan for PII, content policy → PROCEED (or TRANSFORM if redacted) ├─ Datadog AI Guard: Scan prompt for injection → PROCEED └─ Agent Control: Check centralized rules → PROCEED [Model responds: query_database(database="secrets", ...)] BeforeToolCall: ├─ Cedar Auth: Is bob (analyst) allowed? → DENY │ ← short-circuits here ├─ Guardrails: (never reached) ├─ Datadog AI Guard: (never reached) └─ LLM Steering: (never reached — saved ~100ms) ``` -------------------------------- ### Install strands-hubspot Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/community/tools/strands-hubspot.mdx Install the library using pip. ```bash pip install strands-hubspot ``` -------------------------------- ### Install Dependencies Source: https://github.com/strands-agents/harness-sdk/blob/main/site/docs/examples/typescript/structured_output/README.md Installs the necessary project dependencies. ```bash npm install ``` -------------------------------- ### Start the Application Source: https://github.com/strands-agents/harness-sdk/blob/main/site/docs/examples/typescript/structured_output/README.md Starts the Strands Agents application. ```bash npm start ``` -------------------------------- ### Install Community Tools Package Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/tools/community-tools-package.mdx Install the `strands-agents-tools` package to get started with community-built tools. This is the base installation. ```bash pip install strands-agents-tools ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/deploy/deploy_to_docker/typescript.mdx Set up your project directory, initialize npm, and install necessary SDK, Express, and TypeScript packages. ```bash mkdir my-typescript-agent && cd my-typescript-agent npm init -y npm install @strands-agents/sdk express @types/express typescript ts-node npm install -D @types/node ``` -------------------------------- ### Platform-Specific Audio Setup for macOS Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/bidirectional-streaming/quickstart.mdx Installs PortAudio for macOS, required for local audio I/O with bidirectional streaming. Then installs the SDK. ```bash brew install portaudio pip install "strands-agents[bidi-all]" ``` -------------------------------- ### Create a Sample Application Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/community/integrations/ag-ui.mdx Use this command to quickly set up a sample application with a Strands agent and a web client using CopilotKit. ```bash npx copilotkit create -f aws-strands-py ``` -------------------------------- ### Setup Evaluation Project Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/evals-sdk/eval-sop.mdx Create a new directory and navigate into it to set up a self-contained evaluation workspace. ```bash mkdir agent-evaluation-project cd agent-evaluation-project ``` -------------------------------- ### Batched Properties Test Example Source: https://github.com/strands-agents/harness-sdk/blob/main/strands-ts/docs/TESTING.md Illustrates batching multiple assertions into a single test when setup cost is high and assertions verify the same object state. This avoids redundant setup operations. ```typescript it('has correct tool name', () => { const tool = createComplexTool({ /* expensive setup */ }) expect(tool.toolName).toBe('testTool') }) ``` ```typescript it('has correct description', () => { const tool = createComplexTool({ /* same expensive setup */ }) expect(tool.description).toBe('Test description') }) ``` ```typescript it('creates tool with correct properties', () => { const tool = createComplexTool({ /* setup once */ }) expect(tool.toolName).toBe('testTool') expect(tool.description).toBe('Test description') expect(tool.toolSpec.name).toBe('testTool') }) ``` -------------------------------- ### Start the UI Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/community/integrations/ag-ui.mdx Run this command to start the UI after configuring the environment variables. ```bash npm run dev:ui ``` -------------------------------- ### Implementation Notes Example Source: https://github.com/strands-agents/harness-sdk/blob/main/team/PR.md This example demonstrates how to provide implementation notes for reviewers, focusing on key details like default values and the timing of data capture. ```markdown ## Implementation Notes - Result field defaults to None - AgentResult is captured from EventLoopStopEvent before invoking hooks ``` -------------------------------- ### Install Notebook Tool Dependencies Source: https://github.com/strands-agents/harness-sdk/blob/main/strands-ts/src/vended-tools/notebook/README.md Import necessary components for using the notebook tool within your agent setup. ```typescript import { Agent, BedrockModel } from '@strands-agents/sdk' import { notebook } from '@strands-agents/sdk/vended-tools/notebook' ``` -------------------------------- ### SKILL.md Frontmatter and Instructions Example Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/plugins/skills.mdx Example of a SKILL.md file demonstrating YAML frontmatter for skill metadata and markdown for instructions. ```markdown --- name: pdf-processing description: Extract text and tables from PDF files allowed-tools: file_read shell --- # PDF processing You are a PDF processing expert. When asked to extract content from a PDF: 1. Use `shell` to run the extraction script at `scripts/extract.py` 2. Use `file_read` to review the output 3. Summarize the extracted content for the user ``` -------------------------------- ### Example Strands Agent Documentation Structure Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/community/get-featured.mdx A standard Markdown structure for documenting a Strands Agent package. Include a brief introduction, installation instructions, a working code example for basic usage, configuration details, optional troubleshooting, and references. ```markdown # Package Name Brief intro explaining what your package does and why it's useful. ## Installation pip install your-package ## Usage Working code example showing basic usage with Strands Agent. ## Configuration Environment variables, client options, or model parameters. ## Troubleshooting (optional) Common issues and how to fix them. ## References Links to your repo, PyPI, official docs, etc. ``` -------------------------------- ### Restart Bash Session Example Source: https://github.com/strands-agents/harness-sdk/blob/main/strands-ts/src/vended-tools/bash/README.md Shows how to clear all session state and start a fresh bash session by invoking the 'restart' command. ```typescript import { Agent } from '@strands-agents/sdk' import { BedrockModel } from '@strands-agents/sdk' import { bash } from '@strands-agents/sdk/vended-tools/bash' const model = new BedrockModel({ region: 'us-east-1', }) const agent = new Agent({ model, tools: [bash], }) // Set a variable let res = await agent.invoke('run export "TEMP_VAR=exists"') // Restart the session res = await agent.invoke('restart the bash session') // Variable is now gone res = await agent.invoke('run "echo $TEMP_VAR"') console.log(res.lastMessage) // Variable will be empty/undefined ``` -------------------------------- ### TypeScript Express.js Streaming Endpoint (Conceptual) Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/streaming/async-iterators.mdx A conceptual example of a streaming endpoint using Express.js. This requires installing Express.js and related types. ```typescript --8<-- "user-guide/concepts/streaming/async-iterators.ts:express_example" ``` -------------------------------- ### Agent Initialization with System Prompt (Python) Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/contribute/contributing/documentation.mdx Shows how to initialize an Agent with a custom system prompt to define its behavior, followed by a message. ```python from strands import Agent agent = Agent( system_prompt="You are a helpful assistant." ) agent("What's the weather like?") ``` -------------------------------- ### Agent Initialization with Hooks vs. Plugins Source: https://github.com/strands-agents/harness-sdk/blob/main/team/designs/0001-plugins.md Illustrates the difference in agent initialization syntax between using the 'hooks' parameter and the proposed 'plugins' parameter. The 'plugins' approach is suggested for better clarity and developer experience. ```python agent = Agent(hooks=[AnthropicSkills()]) ``` ```python agent = Agent(plugins=[AnthropicSkills()]) ``` -------------------------------- ### HookProvider Example for Logging Source: https://github.com/strands-agents/harness-sdk/blob/main/team/designs/0001-plugins.md Demonstrates how to implement a HookProvider to log agent invocation start and end events. This class registers callbacks for BeforeInvocationEvent and AfterInvocationEvent. ```python # HookProvider example class LoggingHook(HookProvider): # protocol method for a HookProvider def register_hooks(self, registry: HookRegistry) -> None: registry.add_callback(BeforeInvocationEvent, self.log_start) registry.add_callback(AfterInvocationEvent, self.log_end) def log_start(self, event: BeforeInvocationEvent) -> None: print(f"Request started for agent: {event.agent.name}") def log_end(self, event: AfterInvocationEvent) -> None: print(f"Request completed for agent: {event.agent.name}") agent = Agent(hooks=[LoggingHook()]) ``` -------------------------------- ### Run Documentation Site Development Server Source: https://github.com/strands-agents/harness-sdk/blob/main/CONTRIBUTING.md Start a local development server for the documentation site. The site will be available at http://localhost:4321/. ```bash npm run dev ``` -------------------------------- ### Define Single-Tool Chaos Case Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/evals-sdk/chaos_testing.mdx Start with a single tool failure to understand its impact in isolation. This example defines a case where the 'search' tool times out. ```python # Start simple: one tool, one effect single_case = ChaosCase( name="search_fails", input="Find flights to Paris", effects={"tool_effects": {"search": [Timeout()]}}, ) ``` -------------------------------- ### Install ADOT and boto3 directly Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/deploy/deploy_to_bedrock_agentcore/python.mdx Use pip to install the necessary packages directly into your environment. ```bash pip install aws-opentelemetry-distro>=0.10.1 boto3 ``` -------------------------------- ### Running an Agent with Audio I/O Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/bidirectional-streaming/io.mdx Integrate microphone and speaker input/output with your agent using `BidiAudioIO`. This example shows how to initialize `BidiAudioIO` and pass its input and output streams to the agent's `run()` method for real-time voice interaction. ```python import asyncio from strands.experimental.bidi import BidiAgent from strands.experimental.bidi.io import BidiAudioIO from strands_tools import stop async def main(): # stop tool allows user to verbally stop agent execution. agent = BidiAgent(tools=[stop]) audio_io = BidiAudioIO(input_device_index=1) await agent.run( inputs=[audio_io.input()], outputs=[audio_io.output()], ) asyncio.run(main()) ``` -------------------------------- ### Enter Development Environment and Install Hooks Source: https://github.com/strands-agents/harness-sdk/blob/main/strands-py/AGENTS.md Use these commands to enter the development environment and install pre-commit hooks for quality checks. ```bash hatch shell # Enter dev environment pre-commit install -t pre-commit -t commit-msg # Install hooks ``` -------------------------------- ### Initialize LlamaCppModel and Agent Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/model-providers/llamacpp.mdx Connect to a local llama.cpp server and initialize an Agent. This example shows how to set model parameters like max_tokens and temperature. ```python from strands import Agent from strands.models.llamacpp import LlamaCppModel from strands_tools import calculator model = LlamaCppModel( base_url="http://localhost:8080", # **model_config model_id="default", params={ "max_tokens": 1000, "temperature": 0.7, "repeat_penalty": 1.1, } ) agent = Agent(model=model, tools=[calculator]) response = agent("What is 2+2") print(response) ``` -------------------------------- ### Python Agent with Interventions Source: https://github.com/strands-agents/harness-sdk/blob/main/team/designs/0007-intervention-primitive.md Example of initializing a Python Strands Agent with a list of intervention handlers. This setup is used for custom intervention logic during agent execution. ```python from strands import Agent, InterventionHandler, Proceed, Deny, Guide from strands.hooks.events import BeforeToolCallEvent agent = Agent( tools=[query_database, send_email, search], interventions=[cedar, guardrails, steering], ) result = agent("Query the analytics database", invocation_state={"user_id": "bob", "roles": ["analyst"]}) ``` -------------------------------- ### Basic Sandbox Usage in TypeScript Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/sandbox/index.mdx Pass a sandbox to an agent to execute commands and file operations within an isolated environment. This example demonstrates basic setup. ```typescript import { Agent } from "@agent-framework/core"; import { Sandbox } from "@agent-framework/core/sandbox"; const sandbox = new Sandbox(); const agent = new Agent({ sandbox }); ``` ```typescript const agent = new Agent({ sandbox }); ``` -------------------------------- ### Start Ollama Server Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/model-providers/ollama.mdx Launch the Ollama server to make local models accessible. ```bash ollama serve ``` -------------------------------- ### Python Lambda Handler with Mangum Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/deploy/deploy_to_terraform.mdx Example of a Python Lambda handler using the Mangum library to adapt a FastAPI application for AWS Lambda. Ensure you have Mangum installed. ```python from mangum import Mangum from your_app import app # Your existing FastAPI app lambda_handler = Mangum(app) ``` -------------------------------- ### Good Log Formatting Examples Source: https://github.com/strands-agents/harness-sdk/blob/main/strands-py/docs/STYLE_GUIDE.md Examples demonstrating correct structured logging with context fields and a clear message. ```python logger.debug("user_id=<%s>, action=<%s> | user performed action", user_id, action) ``` ```python logger.info("request_id=<%s>, duration_ms=<%d> | request completed", request_id, duration) ``` ```python logger.warning("attempt=<%d>, max_attempts=<%d> | retry limit approaching", attempt, max_attempts) ``` -------------------------------- ### Structured Output with LlamaAPI and Pydantic Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/model-providers/llamaapi.mdx Demonstrates how to use `Agent.structured_output()` with a LlamaAPI model and a Pydantic model to get structured data from the LLM. Ensure the `llamaapi` dependency is installed. ```python from pydantic import BaseModel, Field from strands import Agent from strands.models.llamaapi import LlamaAPIModel class BookAnalysis(BaseModel): """Analyze a book's key information.""" title: str = Field(description="The book's title") author: str = Field(description="The book's author") genre: str = Field(description="Primary genre or category") summary: str = Field(description="Brief summary of the book") rating: int = Field(description="Rating from 1-10", ge=1, le=10) model = LlamaAPIModel( client_args={"api_key": ""}, model_id="Llama-4-Maverick-17B-128E-Instruct-FP8", ) agent = Agent(model=model) result = agent.structured_output( BookAnalysis, """ Analyze this book: "The Hitchhiker's Guide to the Galaxy" by Douglas Adams. It's a science fiction comedy about Arthur Dent's adventures through space after Earth is destroyed. It's widely considered a classic of humorous sci-fi. """ ) print(f"Title: {result.title}") print(f"Author: {result.author}") print(f"Genre: {result.genre}") print(f"Rating: {result.rating}") ``` -------------------------------- ### Using the Workflow Tool Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/multi-agent/workflow.mdx Shows how to initialize an Agent with the built-in workflow tool, which automates task creation, dependency resolution, parallel execution, and information flow. ```python from strands import Agent from strands_tools import workflow # Create an agent with workflow capability agent = Agent(tools=[workflow]) ``` -------------------------------- ### TypeScript End-to-End Tracing Example Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/observability-evaluation/traces.mdx This TypeScript snippet shows how to set up end-to-end tracing for agent interactions. It relies on imported code for setup and the main interaction logic. ```typescript --8<-- "user-guide/observability-evaluation/traces_imports.ts:end_to_end_imports" --8<-- "user-guide/observability-evaluation/traces.ts:end_to_end" ``` -------------------------------- ### Complete Robot Agent Example Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/labs/robots.mdx Sets up an interactive agent for robot control, including camera feeds and inference services. Requires specific robot and camera configurations. ```python from strands import Agent from strands_robots import Robot, gr00t_inference, lerobot_camera, pose_tool robot = Robot( tool_name="orange_arm", robot="so101_follower", cameras={ "wrist": {"type": "opencv", "index_or_path": "/dev/video0", "fps": 15}, "front": {"type": "opencv", "index_or_path": "/dev/video2", "fps": 15}, }, port="/dev/ttyACM0", data_config="so100_dualcam", ) agent = Agent(tools=[robot, gr00t_inference, lerobot_camera, pose_tool]) agent.tool.gr00t_inference( action="start", checkpoint_path="/data/checkpoints/gr00t-wave/checkpoint-300000", port=5555, data_config="so100_dualcam", ) while True: user_input = input("\n> ") if user_input.lower() in ["exit", "quit"]: break agent(user_input) agent.tool.gr00t_inference(action="stop", port=5555) ``` -------------------------------- ### Basic Agent Initialization (Python) Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/contribute/contributing/documentation.mdx Demonstrates the minimal code required to initialize an Agent and send a simple message in Python. ```python from strands import Agent agent = Agent() agent("Hello, world!") ``` -------------------------------- ### TypeScript Agent Code Configuration Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/observability-evaluation/traces.mdx TypeScript examples for configuring Strands Agents with OpenTelemetry tracing. These snippets demonstrate different options for integrating with existing or new OpenTelemetry setups. ```typescript --8<-- "user-guide/observability-evaluation/traces_imports.ts:code_configuration_option1_imports" --8<-- "user-guide/observability-evaluation/traces.ts:code_configuration_option1" --8<-- "user-guide/observability-evaluation/traces_imports.ts:code_configuration_option2_imports" --8<-- "user-guide/observability-evaluation/traces.ts:code_configuration_option2" --8<-- "user-guide/observability-evaluation/traces_imports.ts:code_configuration_option3_imports" --8<-- "user-guide/observability-evaluation/traces.ts:code_configuration_option3" --8<-- "user-guide/observability-evaluation/traces.ts:code_configuration_agent" ``` -------------------------------- ### Dockerfile for Agent Deployment Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/deploy/deploy_to_amazon_eks.mdx Create a Dockerfile to containerize your agent application. This example installs system and Python dependencies, copies application code, and configures the FastAPI server to run with Uvicorn. ```dockerfile FROM public.ecr.aws/docker/library/python:3.12-slim WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y \ git \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Copy application code COPY app/ . # Create a non-root user to run the application RUN useradd -m appuser USER appuser # Expose the port the app runs on EXPOSE 8000 # Command to run the application with Uvicorn # - port: 8000 CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"] ``` -------------------------------- ### Run Development Server Source: https://github.com/strands-agents/harness-sdk/blob/main/site/AGENTS.md Starts a local development server for previewing changes. The server runs at http://localhost:4321/. ```bash npm run dev ``` -------------------------------- ### Complete Example: Multi-Step Dataset Generation Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/evals-sdk/experiment_generator.mdx A comprehensive example demonstrating multi-step dataset generation using ExperimentGenerator. It covers initializing the generator, generating initial cases, expanding the dataset, adding evaluators, and saving the experiment. ```python import asyncio from strands_evals.generators import ExperimentGenerator from strands_evals.evaluators import OutputEvaluator, TrajectoryEvaluator async def create_comprehensive_dataset(): # Initialize generator with trajectory support generator = ExperimentGenerator[str, str]( input_type=str, output_type=str, include_expected_output=True, include_expected_trajectory=True, include_metadata=True ) # Step 1: Generate initial experiment with topic planning print("Step 1: Generating initial experiment...") experiment = await generator.from_context_async( context=""" Multi-agent system with: - Research agent: Searches and analyzes information - Writing agent: Creates content and summaries - Review agent: Validates and improves outputs Tools available: - web_search(query: str) -> str - summarize(text: str) -> str - fact_check(claim: str) -> bool """, task_description="Research and content creation assistant", num_cases=15, num_topics=3, # Research, Writing, Review evaluator=TrajectoryEvaluator ) print(f"Generated {len(experiment.cases)} cases across 3 topics") # Step 2: Add more cases to expand coverage print("\nStep 2: Expanding experiment...") expanded_experiment = await generator.update_current_experiment_async( source_experiment=experiment, task_description="Research and content creation with edge cases", num_cases=5, context="Focus on error handling and complex multi-step scenarios", add_new_cases=True, add_new_rubric=False # Keep existing rubric ) print(f"Expanded to {len(expanded_experiment.cases)} total cases") # Step 3: Add a second LLM-judge evaluator built on a generated rubric. # construct_evaluator_async only accepts the default evaluator classes # (OutputEvaluator, TrajectoryEvaluator, InteractionsEvaluator). print("\nStep 3: Adding output-quality evaluator...") output_eval = await generator.construct_evaluator_async( prompt="Evaluate output quality for research and content creation tasks", evaluator=OutputEvaluator ) expanded_experiment.evaluators.append(output_eval) # For non-default evaluators (e.g. HelpfulnessEvaluator), instantiate directly: # expanded_experiment.evaluators.append(HelpfulnessEvaluator()) # Step 4: Save experiment expanded_experiment.to_file("comprehensive_dataset") print("\nDataset saved to ./comprehensive_dataset.json") return expanded_experiment # Run the multi-step generation experiment = asyncio.run(create_comprehensive_dataset()) # Examine results print(f"\nFinal experiment:") print(f"- Total cases: {len(experiment.cases)}") print(f"- Evaluators: {len(experiment.evaluators)}") print(f"- Categories: {set(c.metadata.get('category', 'unknown') for c in experiment.cases if c.metadata)}") ``` -------------------------------- ### Initialize Python Project with uv Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/deploy/deploy_to_docker/python.mdx Creates a new project directory and initializes it with uv for Python 3.11 environment management. ```bash mkdir my-python-agent && cd my-python-agent uv init --python 3.11 ``` -------------------------------- ### Running an Agent with Custom I/O Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/bidirectional-streaming/io.mdx Connect custom input and output channels to your agent by passing them as arguments to the `run()` method. This example demonstrates the basic setup for integrating user-defined I/O. ```python import asyncio from strands.experimental.bidi import BidiAgent from strands_tools import stop async def main(): # stop tool allows user to verbally stop agent execution. agent = BidiAgent(tools=[stop]) await agent.run(inputs=[MyBidiInput()], outputs=[MyBidiOutput()]) asyncio.run(main()) ``` -------------------------------- ### Directly Invoke HTTP Request Tool Source: https://github.com/strands-agents/harness-sdk/blob/main/strands-ts/src/vended-tools/http-request/README.md Make a direct HTTP GET request using the httpRequest tool. This example shows how to invoke the tool with a specific URL and log the response status and body. ```typescript import { httpRequest } from '@strands-agents/sdk/vended-tools/http-request' // Simple GET request const response = await httpRequest.invoke({ method: 'GET', url: 'https://api.example.com/data', }) console.log(response.status) // 200 console.log(response.body) // Response body as text ``` -------------------------------- ### Initialize Edge Agent with Ollama Model Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/blog/strands-physical-ai.mdx Set up an agent to run locally on edge hardware using the Ollama provider. This example uses the Qwen3-VL model and a basic system prompt. ```python from strands import Agent from strands.models.ollama import OllamaModel edge_model = OllamaModel( host="http://localhost:11434", model_id="qwen3-vl:2b" ) agent = Agent( model=edge_model, system_prompt="You are a helpful assistant running on edge hardware." ) result = agent("Hello!") ``` -------------------------------- ### User Data Script for EC2 Agent Setup Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/deploy/deploy_to_amazon_ec2.mdx Configures the EC2 instance by installing Python, downloading application code and dependencies from S3, and setting up a systemd service to run the Strands Agent application. ```typescript // Create user data script to set up the application const userData = ec2.UserData.forLinux(); userData.addCommands( "#!/bin/bash", "set -o verbose", "yum update -y", "yum install -y python3.12 python3.12-pip git unzip ec2-instance-connect", // Create app directory "mkdir -p /opt/agent-app", // Download application files from S3 `aws s3 cp ${appAsset.s3ObjectUrl} /tmp/app.zip`, `aws s3 cp ${dependenciesAsset.s3ObjectUrl} /tmp/dependencies.zip`, // Extract application files "unzip /tmp/app.zip -d /opt/agent-app", "unzip /tmp/dependencies.zip -d /opt/agent-app/_dependencies", // Create a systemd service file "cat > /etc/systemd/system/agent-app.service << 'EOL'", "[Unit]", "Description=Weather Agent Application", "After=network.target", "", "[Service]", "User=ec2-user", "WorkingDirectory=/opt/agent-app", "ExecStart=/usr/bin/python3.12 -m uvicorn app:app --host=0.0.0.0 --port=8000 --workers=2", "Restart=always", "Environment=PYTHONPATH=/opt/agent-app:/opt/agent-agent/_dependencies", "Environment=LOG_LEVEL=INFO", "", "[Install]", "WantedBy=multi-user.target", "EOL", // Enable and start the service "systemctl enable agent-app.service", "systemctl start agent-app.service", ); ``` -------------------------------- ### Install All Bidirectional Streaming Providers Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/concepts/bidirectional-streaming/models/openai_realtime.mdx Alternatively, install all available bidirectional streaming providers at once. This is useful if you plan to use multiple providers. ```bash pip install 'strands-agents[bidi-all]' ``` -------------------------------- ### Dockerfile for Containerized AgentCore Evaluations with ADOT Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/evals-sdk/how-to/agentcore_evaluation_dashboard.mdx A Dockerfile example that sets up a Python environment, installs dependencies, copies application code, configures ADOT environment variables, and runs evaluations with OpenTelemetry instrumentation via the CMD. ```dockerfile FROM python:3.11 WORKDIR /app # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy application code COPY . . # Set environment variables ENV AGENT_OBSERVABILITY_ENABLED=true \ OTEL_PYTHON_DISTRO=aws_distro \ OTEL_PYTHON_CONFIGURATOR=aws_configurator \ OTEL_METRICS_EXPORTER=awsemf \ OTEL_TRACES_EXPORTER=otlp \ OTEL_LOGS_EXPORTER=otlp \ OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf # Run with ADOT instrumentation CMD ["opentelemetry-instrument", "python", "evaluation_agentcore_dashboard.py"] ``` -------------------------------- ### Install Dependencies Source: https://github.com/strands-agents/harness-sdk/blob/main/test-infra/README.md Navigate to the test-infra directory and install project dependencies using npm. ```sh cd test-infra npm install ``` -------------------------------- ### Compile and Start Server Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/user-guide/deploy/deploy_to_bedrock_agentcore/typescript.mdx Builds the TypeScript project and starts the Node.js server for the agent service. ```bash npm run build npm start ``` -------------------------------- ### Provide Progress Feedback with Print Statements Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/examples/python/agents_workflows.mdx After suppressing agent outputs, use print statements to provide concise progress feedback to the user. This example shows how to indicate the start of processing and completion of specific agent tasks. ```python print("\nProcessing: '{user_input}'") print("\nStep 1: Researcher agent gathering web information...") print("Research complete") print("Passing research findings to Analyst agent...\n") ``` -------------------------------- ### Start vLLM Server Source: https://github.com/strands-agents/harness-sdk/blob/main/site/src/content/docs/community/model-providers/vllm.mdx Launch a vLLM server with your model. For tool calling, include '--enable-auto-tool-choice' and '--tool-call-parser' flags. ```bash vllm serve \ --host 0.0.0.0 \ --port 8000 ``` ```bash vllm serve \ --host 0.0.0.0 \ --port 8000 \ --enable-auto-tool-choice \ --tool-call-parser # e.g., llama3_json, hermes, etc. ```