### Install Steel SDK and Playwright Source: https://docs.steel.dev/overview/sessions-api/quickstart Installs the necessary Steel SDK and Playwright packages using npm. This is a prerequisite for using Steel.dev with Playwright. ```bash npm install steel-sdk playwright ``` -------------------------------- ### Project Setup with npm and TypeScript Source: https://docs.steel.dev/overview/integrations/agentkit/quickstart Initializes a new TypeScript project, installs necessary dependencies including Steel SDK, AgentKit, Playwright, and dotenv, and sets up a start script for execution. ```bash mkdir steel-agentkit-hn && \ cd steel-agentkit-hn && \ npm init -y && \ npm install -D typescript @types/node ts-node && \ npx tsc --init && \ npm pkg set scripts.start="ts-node index.ts" && \ touch index.ts .env npm install steel-sdk @inngest/agent-kit zod playwright dotenv ``` -------------------------------- ### Complete Steel and Agno Integration Example Source: https://docs.steel.dev/overview/integrations/agno/quickstart A comprehensive Python script that integrates Steel and Agno for advanced web automation. It includes necessary imports, API key management, agent setup with specific instructions, and the execution of a task. This script is intended to be pasted directly into a main.py file for a complete functional example. ```python import json import os from typing import Any, Dict, List, Optional from agno.tools import Toolkit from agno.utils.log import log_debug, logger from agno.agent import Agent from playwright.sync_api import sync_playwright from steel import Steel from dotenv import load_dotenv load_dotenv() # Replace with your own API keys STEEL_API_KEY = os.getenv("STEEL_API_KEY") or "your-steel-api-key-here" ``` -------------------------------- ### Project Setup with npm and TypeScript Source: https://docs.steel.dev/overview/integrations/magnitude Initializes a new TypeScript project for the Steel and Magnitude integration. This includes installing necessary development dependencies like TypeScript and ts-node, and configuring npm scripts for easy execution. ```bash mkdir steel-magnitude && \ cd steel-magnitude && \ npm init -y && \ npm install -D typescript @types/node ts-node && \ npx tsc --init && \ npm pkg set scripts.start="ts-node index.ts" && \ touch index.ts .env ``` -------------------------------- ### Setup Environment and Install Packages Source: https://docs.steel.dev/overview/integrations/browser-use/quickstart This snippet demonstrates setting up a project directory, creating and activating a virtual environment, and installing necessary Python packages for Steel and browser-use. It assumes Python 3.11 or higher is installed. ```bash # Create a project directory mkdir steel-browser-use-agent cd steel-browser-use-agent # Recommended: Create and activate a virtual environment uv venv source .venv/bin/activate # On Windows, use: .venv\Scripts\activate # Install required packages pip install steel-sdk browser-use python-dotenv ``` -------------------------------- ### Install Steel SDK and Dependencies (Bash) Source: https://docs.steel.dev/overview/integrations/claude-computer-use/quickstart-python Installs the necessary Python packages for Steel, Anthropic, Playwright, and dotenv. This includes creating a project directory and setting up a virtual environment for dependency management. ```bash # Create a project directory mkdir steel-claude-computer-use cd steel-claude-computer-use # Recommended: Create and activate a virtual environment python -m venv venv source venv/bin/activate # On Windows, use: venv\Scripts\activate # Install required packages pip install steel-sdk anthropic playwright python-dotenv pillow ``` -------------------------------- ### Python Setup and Dependencies (Python) Source: https://docs.steel.dev/overview/integrations/claude-computer-use/quickstart-python Imports necessary libraries for interacting with Steel, Anthropic, environment variables, image processing, and web scraping. It also loads API keys from a .env file. ```python import os import time import base64 import json import re from typing import List, Dict from urllib.parse import urlparse from dotenv import load_dotenv from PIL import Image from io import BytesIO from playwright.sync_api import sync_playwright, Error as PlaywrightError from steel import Steel from anthropic import Anthropic from anthropic.types.beta import BetaMessageParam load_dotenv(override=True) # Replace with your own API keys STEEL_API_KEY = os.getenv("STEEL_API_KEY") or "your-steel-api-key-here" ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY") or "your-anthropic-api-key-here" ``` -------------------------------- ### Install Steel Agno Dependencies with Pip Source: https://docs.steel.dev/overview/integrations/agno/quickstart Installs necessary Python packages for the Steel Agno starter project, including agno, steel-sdk, python-dotenv, and playwright. This ensures all required libraries are available for running the agent and interacting with Steel. ```bash # Create project mkdir steel-agno-starter cd steel-agno-starter # (Recommended) Create & activate a virtual environment python3 -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate # Create files touch main.py .env # Install dependencies pip install agno steel-sdk python-dotenv playwright ``` -------------------------------- ### Execute npm script Source: https://docs.steel.dev/overview/integrations/agentkit/quickstart This command initiates the execution of the application using npm. It assumes that the 'start' script is defined in the project's `package.json` file, typically configured to run the main entry point of the application. ```bash npm run start ``` -------------------------------- ### Python Setup and Helper Functions for Steel and OpenAI Integration Source: https://docs.steel.dev/overview/integrations/openai-computer-use/quickstart-python This snippet sets up necessary Python imports, environment variables for API keys, and defines basic helper functions for interacting with Steel and OpenAI. It requires Python 3.8+ and valid API keys for both services. Dependencies include requests, python-dotenv, Pillow, and typing. ```python import os import time import base64 import json import re from typing import List, Dict from urllib.parse import urlparse import requests from dotenv import load_dotenv from PIL import Image from io import BytesIO load_dotenv(override=True) # Replace with your own API keys STEEL_API_KEY = os.getenv("STEEL_API_KEY") or "your-steel-api-key-here" OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "your-openai-api-key-here" ``` -------------------------------- ### Python ClaudeAgent Class Initialization and Setup Source: https://docs.steel.dev/overview/integrations/claude-computer-use/quickstart-python Initializes the ClaudeAgent class, setting up the Anthropic client, storing computer dimensions, and configuring system prompts and tools based on the provided model and computer details. It raises a ValueError for unsupported models. ```python class ClaudeAgent: def __init__(self, computer = None, model: str = "claude-3-5-sonnet-20241022"): self.client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) self.computer = computer self.messages: List[BetaMessageParam] = [] self.model = model if computer: width, height = computer.get_dimensions() self.viewport_width = width self.viewport_height = height self.system_prompt = SYSTEM_PROMPT.replace( '', f'\n* The browser viewport dimensions are {width}x{height} pixels\n* The browser viewport has specific dimensions that you must respect' ) if model not in MODEL_CONFIGS: raise ValueError(f"Unsupported model: {model}. Available models: {list(MODEL_CONFIGS.keys())}") self.model_config = MODEL_CONFIGS[model] self.tools = [{ "type": self.model_config["tool_type"], "name": "computer", "display_width_px": width, "display_height_px": height, "display_number": 1, }] else: self.viewport_width = 1024 self.viewport_height = 768 self.system_prompt = SYSTEM_PROMPT ``` -------------------------------- ### Install Node.js Dependencies for Steel & Claude Source: https://docs.steel.dev/overview/integrations/claude-computer-use/quickstart-tsnode Installs necessary Node.js packages including the Steel SDK, Anthropic SDK, Playwright, and development tools for TypeScript projects. ```bash # Create a project directory mkdir steel-claude-computer-use cd steel-claude-computer-use # Initialize package.json npm init -y # Install required packages npm install steel-sdk @anthropic-ai/sdk playwright dotenv npm install -D @types/node typescript ts-node ``` -------------------------------- ### Python Agent Class Initialization and Tool Setup Source: https://docs.steel.dev/overview/integrations/openai-computer-use/quickstart-python Defines the Agent class constructor, which initializes agent properties, configures the system prompt based on computer dimensions, and adds essential tools like 'computer-preview', 'goto', and 'back'. It handles default viewport dimensions if no computer is provided. Dependencies include `List` from `typing` and `SYSTEM_PROMPT` (assumed to be a globally defined string). ```python class Agent: def __init__( self, model: str = "computer-use-preview", computer = None, tools: List[dict] = None, auto_acknowledge_safety: bool = True, ): self.model = model self.computer = computer self.tools = tools or [] self.auto_acknowledge_safety = auto_acknowledge_safety self.print_steps = True self.debug = False self.show_images = False if computer: scaled_width, scaled_height = computer.get_dimensions() self.viewport_width = scaled_width self.viewport_height = scaled_height # Create dynamic system prompt with viewport dimensions self.system_prompt = SYSTEM_PROMPT.replace( '', f'\n* The browser viewport dimensions are {scaled_width}x{scaled_height} pixels\n* The browser viewport has specific dimensions that you must respect' ) self.tools.append({ "type": "computer-preview", "display_width": scaled_width, "display_height": scaled_height, "environment": computer.get_environment(), }) # Add goto function tool for direct URL navigation self.tools.append({ "type": "function", "name": "goto", "description": "Navigate directly to a specific URL.", "parameters": { "type": "object", "properties": { "url": { "type": "string", "description": "Fully qualified URL to navigate to (e.g., https://example.com).", }, }, "additionalProperties": False, "required": ["url"], }, }) # Add back function tool for browser navigation self.tools.append({ "type": "function", "name": "back", "description": "Go back to the previous page.", "parameters": {}, }) else: self.viewport_width = 1024 self.viewport_height = 768 self.system_prompt = SYSTEM_PROMPT ``` -------------------------------- ### Create Steel Session with Advanced Options Source: https://docs.steel.dev/overview/sessions-api/quickstart Illustrates creating a Steel session with additional configurations such as enabling proxy usage, automatic CAPTCHA solving, setting a custom timeout, and specifying a user agent. ```typescript const session = await client.sessions.create({ useProxy: true, // Use Steel's residential proxy network solveCaptcha: true, // Enable automatic CAPTCHA solving timeout: 1800000, // Set 30-minute timeout (default is 5 minutes) userAgent: 'custom-ua' // Set a custom user agent }); ``` -------------------------------- ### Install Dependencies with npm Source: https://docs.steel.dev/overview/integrations/stagehand/quickstart-tsnode Installs the necessary Node.js packages for Stagehand and Steel SDK, along with development dependencies for TypeScript compilation. ```bash # Create a project directory mkdir steel-stagehand-starter cd steel-stagehand-starter # Initialize npm project npm init -y # Install required packages npm install @browserbasehq/stagehand dotenv steel-sdk typescript zod # Install dev dependencies npm install --save-dev @types/node ts-node ``` -------------------------------- ### Complete Steel Browser Automation Example Source: https://docs.steel.dev/overview/integrations/browser-use/quickstart This consolidated Python script integrates all the previous steps: environment setup, Steel session creation, browser-use integration, AI agent definition, and execution. It serves as a full example for automating browser interactions with an AI agent powered by Steel and browser-use. ```python """ AI-powered browser automation using browser-use library with Steel browsers. https://github.com/steel-dev/steel-cookbook/tree/main/examples/steel-browser-use-starter """ import os import time import asyncio from dotenv import load_dotenv from steel import Steel from browser_use import Agent, BrowserSession from browser_use.llm import ChatOpenAI load_dotenv() STEEL_API_KEY = os.getenv("STEEL_API_KEY") or "your-steel-api-key-here" OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "your-openai-api-key-here" TASK = os.getenv("TASK") or "Go to Wikipedia and search for machine learning" # Validate API keys (basic check) if STEEL_API_KEY == "your-steel-api-key-here": print("⚠️ WARNING: Please replace with your actual Steel API key") print(" Get your API key at: https://app.steel.dev/settings/api-keys") exit() if OPENAI_API_KEY == "your-openai-api-key-here": print("⚠️ WARNING: Please replace with your actual OpenAI API key") print(" Get your API key at: https://platform.openai.com/api-keys") exit() async def main(): client = None session = None try: # Step 2: Create a Steel browser session print("Starting Steel browser session...") client = Steel(steel_api_key=STEEL_API_KEY) session = client.sessions.create() print(f"✅ Steel browser session started! View live session at: {session.session_viewer_url}") # Step 3: Define Your Browser Session cdp_url = f"wss://connect.steel.dev?apiKey={STEEL_API_KEY}&sessionId={session.id}" browser_session = BrowserSession(cdp_url=cdp_url) print("Connected browser-use to Steel session.") # Step 4: Define your AI Agent model = ChatOpenAI( model="gpt-4o", temperature=0.3, api_key=OPENAI_API_KEY ) agent = Agent( task=TASK, llm=model, browser_session=browser_session, ) print("AI Agent defined.") # Step 5: Run your Agent start_time = time.time() print(f"\n🎯 Executing task: {TASK}") print("=" * 60) result = await agent.run() duration = f"{(time.time() - start_time):.1f}" print("\n" + "=" * 60) print("🎉 TASK EXECUTION COMPLETED") print("=" * 60) print(f"⏱️ Duration: {duration} seconds") print(f"🎯 Task: {TASK}") if result: print(f"📋 Result:\n{result}") print("=" * 60) except Exception as e: print(f"❌ Task execution failed: {e}") finally: # Clean up resources if session and client: print("Releasing Steel session...") try: client.sessions.release(session.id) print(f"Session completed. View replay at {session.session_viewer_url}") except Exception as release_e: print(f"Error releasing session: {release_e}") print("Done!") if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### TypeScript: Example Task Definitions for Claude Agent Source: https://docs.steel.dev/overview/integrations/claude-computer-use/quickstart-tsnode This snippet provides examples of different task definitions that can be used with the Claude agent. It illustrates how to instruct the agent to perform web research, e-commerce comparisons, and information gathering from documentation. ```typescript // Research specific topics const TASK = "Go to https://arxiv.org, search for 'machine learning', and summarize the latest papers."; // E-commerce tasks const TASK = "Go to https://www.amazon.com, search for 'wireless headphones', and compare the top 3 results."; // Information gathering const TASK = "Go to https://docs.anthropic.com, find information about Claude's capabilities, and provide a summary."; ``` -------------------------------- ### Example Production Docker Compose Source: https://docs.steel.dev/overview/self-hosting/docker A sample `docker-compose.yml` file tailored for production environments. It includes recommendations like using specific image versions, restart policies, and resource limits. ```yaml services: api: image: ghcr.io/steel-dev/steel-browser-api:sha256:... restart: always ports: - "3000:3000" deploy: resources: limits: memory: 2G volumes: - ./data/.cache:/app/.cache networks: - steel-network ui: image: ghcr.io/steel-dev/steel-browser-ui:sha256:... restart: always ports: - "5173:80" networks: - steel-network networks: steel-network: name: steel-network driver: bridge ``` -------------------------------- ### Example Agent Tasks for Steel (Plaintext) Source: https://docs.steel.dev/overview/integrations/agno/quickstart Illustrates different task definitions for the Steel agent, provided as comments in a '.env' file format. These examples show how to specify web scraping actions like extracting product details, capturing screenshots, and performing multi-step navigation within a web page. These tasks are intended to be set in the TASK environment variable. ```plaintext # Crawl a product page and extract specs TASK=Go to https://example.com/product/123 and extract the product name, price, and 5 key specs. # Capture a screenshot-only workflow TASK=Go to https://news.ycombinator.com, take a full-page screenshot, and return the page title. # Multi-step navigation TASK=Open https://docs.steel.dev, search for "session lifecycle", and summarize the key steps with anchors. ``` -------------------------------- ### Full Steel.dev + CrewAI Example Code (Python) Source: https://docs.steel.dev/overview/integrations/crewai/quickstart This is the complete `main.py` file demonstrating the integration of Steel.dev tools with CrewAI. It includes all necessary imports, agent and task definitions, and the main execution logic. Ensure you have set your `STEEL_API_KEY` in your `.env` file to run this code. ```python import os import warnings from datetime import datetime from textwrap import dedent from typing import List, Optional, Type from crewai import Agent, Process, Task from crewai import Crew as CrewAI from crewai.agents.agent_builder.base_agent import BaseAgent from crewai.project import CrewBase, agent, crew, task from crewai.tools import BaseTool, EnvVar from dotenv import load_dotenv from pydantic import BaseModel, ConfigDict, Field, PrivateAttr from steel import Steel warnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd") load_dotenv() # Replace with your own API keys STEEL_API_KEY = os.getenv('STEEL_API_KEY') or "your-steel-api-key-here" class SteelScrapeWebsiteTool(BaseTool): """Tool to scrape website content using Steel.dev.""" name: str = Field("steel_scrape_website", description="The name of the tool") description: str = Field("Scrape content from a given website URL.", description="The tool's description") steel_client: Steel = PrivateAttr() def __init__(self, **kwargs): super().__init__(**kwargs) self.steel_client = Steel(api_key=STEEL_API_KEY) def _run(self, url: str) -> str: """Scrapes the website and returns the content.""" try: result = self.steel_client.scrape_website(url=url) return result.content except Exception as e: return f"Error scraping website {url}: {e}" model_config = ConfigDict(arbitrary_types_allowed=True) TASK = os.getenv("TASK") or "Research AI LLMs and summarize key developments" @CrewBase class Crew(): """Steel + CrewAI example crew""" agents: List[BaseAgent] tasks: List[Task] @agent def researcher(self) -> Agent: return Agent( role="Instruction-Following Web Researcher", goal="Understand and execute: {task}. Find, verify, and extract the most relevant information using the web.", backstory=( "You specialize in decomposing and executing complex instructions like '{task}', " "using web research, verification, and synthesis to produce precise, actionable findings." ), tools=[SteelScrapeWebsiteTool()], verbose=True, ) @agent def reporting_analyst(self) -> Agent: return Agent( role="Instruction-Following Reporting Analyst", goal="Transform research outputs into a clear, complete report that fulfills: {task}", backstory=( "You convert research into exhaustive, well-structured reports that directly address " "the original instruction '{task}', ensuring completeness and clarity." ), tools=[SteelScrapeWebsiteTool()], verbose=True, ) @task def research_task(self) -> Task: return Task( description=dedent(""" Interpret and execute the following instruction: {task} Use the web as needed. Cite and include key sources. Consider the current year: {current_year}. """), expected_output="A structured set of findings and sources that directly satisfy the instruction: {task}", agent=self.researcher(), ) @task def reporting_task(self) -> Task: return Task( description=dedent(""" Review the research context and produce a complete report that fulfills the instruction. Ensure completeness, accuracy, and clear structure. Include citations. """), expected_output=( "A comprehensive markdown report that satisfies the instruction: {task}. " "Formatted as markdown without '```'" ), agent=self.reporting_analyst(), ) @crew def crew(self) -> CrewAI: """Creates the sequential crew pipeline""" return CrewAI( agents=self.agents, tasks=self.tasks, process=Process.sequential, verbose=True, ) def main(): print("🚀 Steel + CrewAI Starter") print("=" * 60) if not os.getenv("STEEL_API_KEY") or os.getenv("STEEL_API_KEY") == "your-steel-api-key-here": print("⚠️ WARNING: Please set STEEL_API_KEY in your .env") print(" Get your key at: https://app.steel.dev/settings/api-keys") return inputs = { "task": TASK, "current_year": str(datetime.now().year), } try: print("Running crew...") Crew().crew().kickoff(inputs=inputs) print("\n✅ Done. (If your task wrote to a file, check your project folder.)") except Exception as e: print(f"❌ Error while running the crew: {e}") if __name__ == "__main__": main() ``` -------------------------------- ### Simulating Drag and Drop with Playwright Source: https://docs.steel.dev/overview/integrations/openai-computer-use/quickstart-python Performs a drag-and-drop operation by moving the mouse from a starting point through a series of points to a final destination. ```python def drag(self, path: List[Dict[str, int]]) -> None: if not path: return start_x, start_y = path[0]["x"], path[0]["y"] self._page.mouse.move(start_x, start_y) self._page.mouse.down() for point in path[1:]: scaled_x, scaled_y = point["x"], point["y"] self._page.mouse.move(scaled_x, scaled_y) self._page.mouse.up() ``` -------------------------------- ### Browser Session Management and Cleanup Source: https://docs.steel.dev/overview/integrations/openai-computer-use/quickstart-python Handles the setup and teardown of browser sessions using Playwright. It ensures resources like the browser, page, and Playwright instance are properly closed, and releases the Steel session, printing its viewer URL upon completion. ```python def __exit__(self, exc_type, exc_val, exc_tb): if self._page: self._page.close() if self._browser: self._browser.close() if self._playwright: self._playwright.stop() if self.session: print("Releasing Steel session...") self.client.sessions.release(self.session.id) print(f"Session completed. View replay at {self.session.session_viewer_url}") ``` -------------------------------- ### Python Environment Setup and Helper Functions Source: https://docs.steel.dev/overview/integrations/openai-computer-use/quickstart-python This snippet includes utility functions for pretty-printing JSON and displaying base64 encoded images, commonly used in development and debugging environments. It also contains a function to sanitize messages by removing sensitive image data for specific output types. ```python import json import base64 from io import BytesIO from PIL import Image def pp(obj): print(json.dumps(obj, indent=4)) def show_image(base_64_image): image_data = base64.b64decode(base_64_image) image = Image.open(BytesIO(image_data)) image.show() def sanitize_message(msg: dict) -> dict: """Return a copy of the message with image_url omitted for computer_call_output messages.""" if msg.get("type") == "computer_call_output": output = msg.get("output", {}) if isinstance(output, dict): # Potentially add logic here to remove image_url if it exists pass return msg.copy() ``` -------------------------------- ### Initialize Steel Browser Integration (Python) Source: https://docs.steel.dev/overview/integrations/openai-computer-use/quickstart-python Initializes the SteelBrowser class with various configuration options. It sets up parameters for browser dimensions, proxy usage, CAPTCHA solving, ad blocking, session timeout, and the starting URL. Dependencies include the 'Steel' client and 'os' for environment variables. ```Python class SteelBrowser: def __init__( self, width: int = 1024, height: int = 768, proxy: bool = False, solve_captcha: bool = False, virtual_mouse: bool = True, session_timeout: int = 900000, # 15 minutes ad_blocker: bool = True, start_url: str = "https://www.google.com", ): self.client = Steel( steel_api_key=os.getenv("STEEL_API_KEY"), ) self.dimensions = (width, height) self.proxy = proxy self.solve_captcha = solve_captcha self.virtual_mouse = virtual_mouse self.session_timeout = session_timeout self.ad_blocker = ad_blocker self.start_url = start_url self.session = None self._playwright = None self._browser = None self._page = None ``` -------------------------------- ### Python: Create and Configure Steel Browser Session Source: https://docs.steel.dev/overview/integrations/claude-computer-use/quickstart-python This snippet demonstrates the initialization and setup of a `SteelBrowser` instance. It configures session parameters such as dimensions, proxy, CAPTCHA solving, ad blocking, and timeout. It also establishes a connection to the Steel session using the provided API key and launches a Playwright browser instance. ```python import os from steel import Steel from playwright.sync_api import sync_playwright def check_blocklisted_url(url): # Placeholder for actual blocklist checking logic blocklisted_domains = ["example.com"] if any(domain in url for domain in blocklisted_domains): raise ValueError(f"URL is blocklisted: {url}") class SteelBrowser: def __init__( self, width: int = 1024, height: int = 768, proxy: bool = False, solve_captcha: bool = False, virtual_mouse: bool = True, session_timeout: int = 900000, ad_blocker: bool = True, start_url: str = "https://www.google.com", ): self.client = Steel( steel_api_key=os.getenv("STEEL_API_KEY"), ) self.dimensions = (width, height) self.proxy = proxy self.solve_captcha = solve_captcha self.virtual_mouse = virtual_mouse self.session_timeout = session_timeout self.ad_blocker = ad_blocker self.start_url = start_url self.session = None self._playwright = None self._browser = None self._page = None self._last_mouse_position = None def get_dimensions(self): return self.dimensions def get_current_url(self) -> str: return self._page.url if self._page else "" def __enter__(self): width, height = self.dimensions session_params = { "use_proxy": self.proxy, "solve_captcha": self.solve_captcha, "api_timeout": self.session_timeout, "block_ads": self.ad_blocker, "dimensions": {"width": width, "height": height} } self.session = self.client.sessions.create(**session_params) print("Steel Session created successfully!") print(f"View live session at: {self.session.session_viewer_url}") self._playwright = sync_playwright().start() browser = self._playwright.chromium.connect_over_cdp( f"{self.session.websocket_url}&apiKey={os.getenv('STEEL_API_KEY')}", timeout=60000 ) self._browser = browser context = browser.contexts[0] def handle_route(route, request): url = request.url try: check_blocklisted_url(url) route.continue_() except ValueError: print(f"Blocking URL: {url}") route.abort() if self.virtual_mouse: context.add_init_script(""" if (window.self === window.top) { function initCursor() { const CURSOR_ID = '__cursor__'; if (document.getElementById(CURSOR_ID)) return; const cursor = document.createElement('div'); cursor.id = CURSOR_ID; Object.assign(cursor.style, { position: 'fixed', top: '0px', left: '0px', width: '20px', height: '20px', backgroundImage: 'url("data:image/svg+xml;utf8,"') , backgroundSize: 'cover', pointerEvents: 'none', zIndex: '99999', transform: 'translate(-2px, -2px)', }); document.body.appendChild(cursor); document.addEventListener("mousemove", (e) => { cursor.style.top = e.clientY + "px"; cursor.style.left = e.clientX + "px"; }); } requestAnimationFrame(function checkBody() { if (document.body) { initCursor(); } else { requestAnimationFrame(checkBody); } }); } ") self._page = context.pages[0] self._page.route("**/*", handle_route) self._page.set_viewport_size({"width": width, "height": height}) self._page.goto(self.start_url) return self def __exit__(self, exc_type, exc_val, exc_tb): if self._page: # Placeholder for cleanup logic if needed pass if self._playwright): self._playwright.stop() if self.session): self.session.close() ``` -------------------------------- ### Initialize Steel SDK and Load Environment Variables Source: https://docs.steel.dev/overview/integrations/magnitude Initializes the Steel SDK client using the provided API key and loads environment variables for application configuration. This is the foundational setup for interacting with Steel's services. ```typescript // index.ts import * as dotenv from "dotenv"; import { Steel } from "steel-sdk"; import { startBrowserAgent } from "magnitude-core"; import { z } from "zod"; dotenv.config(); const STEEL_API_KEY = process.env.STEEL_API_KEY || "your-steel-api-key-here"; const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY || "your-anthropic-api-key-here"; const client = new Steel({ steelAPIKey: STEEL_API_KEY }); ``` -------------------------------- ### Initialize and Get Page Content (Python) Source: https://docs.steel.dev/overview/integrations/agno/quickstart Initializes a Steel browser session and retrieves the content of the current page. It handles potential exceptions during initialization or content retrieval, ensuring cleanup is performed and any errors are re-raised. Dependencies include internal methods `_initialize_browser` and `_cleanup`. ```python try: self._initialize_browser(connect_url) return self._page.content() if self._page else "" except Exception as e: self._cleanup() raise e ``` -------------------------------- ### Create and Release a Steel Session (Typescript/Playwright) Source: https://docs.steel.dev/overview/sessions-api/quickstart Demonstrates how to create a new cloud browser session using the Steel SDK and then release it. It utilizes environment variables for API key authentication and logs session details. ```typescript import Steel from 'steel-sdk'; import { chromium } from 'playwright'; import dotenv from 'dotenv'; dotenv.config(); const client = new Steel({ steelAPIKey: process.env.STEEL_API_KEY, }); async function main() { // Create a session const session = await client.sessions.create(); console.log('Session created:', session.id); console.log(`View live session at: ${session.sessionViewerUrl}`); // Your session is now ready to use! // When done, release the session await client.sessions.release(session.id); console.log('Session released'); } main().catch(console.error); ``` -------------------------------- ### Steel and Stagehand Python Starter Script Source: https://docs.steel.dev/overview/integrations/stagehand/quickstart-python This is a complete Python script for AI-powered browser automation using Stagehand with Steel browsers. It requires setting up environment variables for API keys (Steel and OpenAI) and installing necessary libraries like `steel`, `stagehand`, `python-dotenv`, and `pydantic`. ```python """ AI-powered browser automation using Stagehand with Steel browsers. https://github.com/steel-dev/steel-cookbook/tree/main/examples/steel-stagehand-python-starter """ import asyncio import os from dotenv import load_dotenv from pydantic import BaseModel, Field from steel import Steel from stagehand import StagehandConfig, Stagehand # Load environment variables load_dotenv() # Replace with your own API keys STEEL_API_KEY = os.getenv("STEEL_API_KEY") or "your-steel-api-key-here" OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "your-openai-api-key-here" ``` -------------------------------- ### Define SteelTools Toolkit for Agno Agent Source: https://docs.steel.dev/overview/integrations/agno/quickstart This Python code defines a custom `SteelTools` class that inherits from `agno.tools.Toolkit`. It initializes Steel and Playwright, manages browser sessions, and exposes methods for navigating to URLs, taking screenshots, and getting page content. Dependencies include `os`, `json`, `typing`, `agno.tools`, `agno.utils.log`, `playwright.sync_api`, and `steel`. ```python import os import json from typing import Any, Dict, List, Optional from agno.tools import Toolkit from agno.utils.log import log_debug, logger from playwright.sync_api import sync_playwright from steel import Steel class SteelTools(Toolkit): def __init__( self, api_key: Optional[str] = None, **kwargs, ): """Initialize SteelTools. Args: api_key (str, optional): Steel API key (defaults to STEEL_API_KEY env var). """ self.api_key = api_key or os.getenv("STEEL_API_KEY") if not self.api_key: raise ValueError( "STEEL_API_KEY is required. Please set the STEEL_API_KEY environment variable." ) self.client = Steel(steel_api_key=self.api_key) self._playwright = None self._browser = None self._page = None self._session = None self._connect_url = None tools: List[Any] = [] tools.append(self.navigate_to) tools.append(self.screenshot) tools.append(self.get_page_content) tools.append(self.close_session) super().__init__(name="steel_tools", tools=tools, **kwargs) def _ensure_session(self): """Ensures a Steel session exists, creating one if needed.""" if not self._session: try: self._session = self.client.sessions.create() # type: ignore if self._session: self._connect_url = f"{self._session.websocket_url}&apiKey={self.api_key}" # type: ignore log_debug(f"Created new Steel session with ID: {self._session.id}") except Exception as e: logger.error(f"Failed to create Steel session: {str(e)}") raise def _initialize_browser(self, connect_url: Optional[str] = None): """ Initialize browser connection if not already initialized. Use provided connect_url or ensure we have a session with a connect_url """ if connect_url: self._connect_url = connect_url if connect_url else "" # type: ignore elif not self._connect_url: self._ensure_session() if not self._playwright: self._playwright = sync_playwright().start() # type: ignore if self._playwright: self._browser = self._playwright.chromium.connect_over_cdp(self._connect_url) context = self._browser.contexts[0] if self._browser else "" self._page = context.pages[0] or context.new_page() # type: ignore def _cleanup(self): """Clean up browser resources.""" if self._browser: self._browser.close() self._browser = None if self._playwright: self._playwright.stop() self._playwright = None self._page = None def _create_session(self) -> Dict[str, str]: """Creates a new Steel browser session. Returns: Dictionary containing session details including session_id and connect_url. """ self._ensure_session() return { "session_id": self._session.id if self._session else "", "connect_url": self._connect_url or "", } def navigate_to(self, url: str, connect_url: Optional[str] = None) -> str: """Navigates to a URL. Args: url (str): The URL to navigate to connect_url (str, optional): The connection URL from an existing session Returns: JSON string with navigation status """ try: self._initialize_browser(connect_url) if self._page: self._page.goto(url, wait_until="networkidle") result = {"status": "complete", "title": self._page.title() if self._page else "", "url": url} return json.dumps(result) except Exception as e: self._cleanup() raise e def screenshot(self, path: str, full_page: bool = True, connect_url: Optional[str] = None) -> str: """Takes a screenshot of the current page. Args: path (str): Where to save the screenshot full_page (bool): Whether to capture the full page connect_url (str, optional): The connection URL from an existing session Returns: JSON string confirming screenshot was saved """ try: self._initialize_browser(connect_url) if self._page: self._page.screenshot(path=path, full_page=full_page) return json.dumps({"status": "success", "path": path}) except Exception as e: self._cleanup() raise e def get_page_content(self, connect_url: Optional[str] = None) -> str: ``` -------------------------------- ### Install Project Dependencies with Pip Source: https://docs.steel.dev/overview/integrations/crewai/quickstart Installs necessary Python packages including crewai with tools, steel-sdk, python-dotenv, and pydantic. Ensure you have Python 3.11+ installed and a virtual environment activated. ```bash pip install crewai[tools] steel-sdk python-dotenv pydantic ``` -------------------------------- ### View Organization Extensions (API, Bash, TypeScript, Python) Source: https://docs.steel.dev/overview/extensions-api/overview Retrieve a list of all installed extensions for your organization using the GET /v1/extensions endpoint. This operation requires authentication with your API key. The examples show how to call this endpoint using cURL, and programmatically via Bash, TypeScript, and Python client libraries. ```bash curl -X GET https://api.steel.dev/v1/extensions \ -H "Content-Type: application/json" \ -H "steel-api-key: YOUR_API_KEY_HERE" ``` ```typescript const extensions = await client.extensions.list(); ``` ```python extensions = client.extensions.list() ``` -------------------------------- ### Install Python Packages with Pip Source: https://docs.steel.dev/overview/integrations/stagehand/quickstart-python Installs the necessary Python packages for Steel and Stagehand development. This includes the steel-sdk, stagehand, pydantic, and python-dotenv libraries. ```bash pip install steel-sdk stagehand pydantic python-dotenv ``` -------------------------------- ### Main Execution Flow with Steel Agent (Python) Source: https://docs.steel.dev/overview/integrations/agno/quickstart Sets up and runs an agent using the Steel SDK to perform a defined task. It checks for a valid API key, initializes the SteelTools and Agent, executes the agent's run method with a specific task, prints the response content, and ensures the browser session is closed afterward. Dependencies include `SteelTools`, `Agent`, and environment variables `STEEL_API_KEY` and `TASK`. ```python def main(): print("🚀 Steel + Agno Starter") print("=" * 60) if STEEL_API_KEY == "your-steel-api-key-here": print("⚠️ WARNING: Please replace 'your-steel-api-key-here' with your actual Steel API key") print(" Get your API key at: https://app.steel.dev/settings/api-keys") return tools = SteelTools(api_key=STEEL_API_KEY) agent = Agent( name="Web Scraper", tools=[tools], instructions=[ "Extract content clearly and format nicely", "Always close sessions when done", ], markdown=True, ) try: response = agent.run(TASK) print("\nResults:\n") print(response.content) except Exception as e: print(f"An error occurred: {e}") finally: tools.close_session() print("Done!") if __name__ == "__main__": main() ```