### Basic Browser and Agent Setup Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Sets up a Browser instance with specific window size and headless mode, and an Agent for performing tasks using an LLM. This is a fundamental example for starting automated browser interactions. ```python from browser_use import Agent, Browser, ChatOpenAI browser = Browser( headless=False, # Show browser window window_size={'width': 1000, 'height': 700}, # Set window size ) agent = Agent( task='Search for Browser Use', browser=browser, llm=ChatOpenAI(model='gpt-4.1-mini'), ) async def main(): await agent.run() ``` -------------------------------- ### Run Browser Use Helper Scripts Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Execute helper scripts for common development tasks such as setup, linting, and running tests. The setup script installs uv, creates a virtual environment, and installs dependencies. ```bash # Complete setup script - installs uv, creates a venv, and installs dependencies ./bin/setup.sh # Run all pre-commit hooks (formatting, linting, type checking) ./bin/lint.sh # Run the core test suite that's executed in CI ./bin/test.sh ``` -------------------------------- ### Environment Setup Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ms/08-multi-agent/code_samples/workflows-agent-framework/python/04.python-agent-framework-workflow-aifoundry-condition.ipynb This snippet provides instructions for setting up your environment by copying the example environment file. This is a crucial step before running the agent framework. ```text requirements.txt & constraints.txt - dalam ./Installation sila salin .env.examples sebagai .env ``` -------------------------------- ### Agent Observability Setup Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/14-microsoft-agent-framework/README.md Initializes OpenTelemetry tracer and meter for agent observability. Demonstrates starting a custom span and creating a counter. ```python from agent_framework.observability import get_tracer, get_meter tracer = get_tracer() meter = get_meter() with tracer.start_as_current_span("my_custom_span"): # do something pass counter = meter.create_counter("my_custom_counter") counter.add(1, {"key": "value"}) ``` -------------------------------- ### Install Agent Framework Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/lt/08-multi-agent/code_samples/workflows-agent-framework/python/02.python-agent-framework-workflow-ghmodel-sequential.ipynb Install the agent-framework library. This is typically handled by a repository-level requirements.txt. ```python # Already covered by repo-level requirements.txt; left for reference. # !pip install agent-framework -U ``` -------------------------------- ### Run Browser Use Examples Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Execute example Python scripts using the uv run command. ```bash uv run examples/simple.py ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/AGENTS.md Copy the example environment file and edit it with your specific API keys and endpoints. ```bash cp .env.example .env # Edit .env with your API keys and endpoints ``` -------------------------------- ### Commented out NuGet Package Installation Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fi/08-multi-agent/code_samples/workflows-agent-framework/dotNET/01.dotnet-agent-framework-workflow-ghmodel-basic.ipynb An example of a commented-out NuGet package installation, likely for a previous version or alternative. ```csharp // #r "nuget: Microsoft.Extensions.AI.OpenAI, 9.9.0-preview.1.25458.4" ``` -------------------------------- ### Specific Task Prompting Example Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Example of a specific and recommended task prompt that guides the agent through a series of precise actions. ```python task = """ 1. Go to https://quotes.toscrape.com/ 2. Use extract_structured_data action with the query "first 3 quotes with their authors" 3. Save results to quotes.csv using write_file action 4. Do a google search for the first quote and find when it was written """ ``` -------------------------------- ### Run Sample with .NET CLI Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/08-multi-agent/code_samples/08-dotnet-agent-framework.md Execute the C# sample file using the .NET CLI. ```bash dotnet run 08-dotnet-agent-framework.cs ``` -------------------------------- ### Install Agent Framework Dependencies Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/12-context-engineering/code_samples/12-chat_summarization.ipynb Installs necessary libraries for the agent framework, Azure AI projects, and Azure identity management. Use this at the beginning of your project setup. ```python %pip install agent-framework azure-ai-projects azure-identity --quiet ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ms/AGENTS.md Copies the example environment file and instructs to edit it with your API keys and endpoints. Required for Azure AI Foundry and Azure AI Search. ```bash cp .env.example .env # Sunting .env dengan kunci API dan titik akhir anda ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ro/AGENTS.md Copy the example environment file and edit it with your specific API keys and endpoints. This is crucial for connecting to Azure AI services. ```bash cp .env.example .env # EditeazΔƒ .env cu cheile API Θ™i endpoint-urile tale ``` -------------------------------- ### Running .NET Agent Framework Example Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/05-agentic-rag/code_samples/05-dotnet-agent-framework.md Provides instructions on how to make the .NET agent framework script executable and run it using either the direct executable or the `dotnet run` command. ```bash # Make the script executable (Linux/macOS) chmod +x 05-dotnet-agent-framework.cs # Run the .NET Single File App ./05-dotnet-agent-framework.cs ``` ```bash dotnet run 05-dotnet-agent-framework.cs ``` -------------------------------- ### Platform-Specific Chrome Paths Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Provides example paths for Chrome installations on macOS, Windows, and Linux, useful for configuring the `executable_path` and `user_data_dir` when connecting to a local browser. ```python # macOS executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' user_data_dir='~/Library/Application Support/Google/Chrome' # Windows executable_path='C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe' user_data_dir='%LOCALAPPDATA%\\Google\\Chrome\\User Data' # Linux executable_path='/usr/bin/google-chrome' user_data_dir='~/.config/google-chrome' ``` -------------------------------- ### Basic Usage Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Demonstrates the fundamental setup and usage of the Browser Actor library, including starting the browser, creating new pages, and performing basic element interactions with LLM assistance. ```APIDOC ## Basic Usage This example shows how to initialize the Browser Actor, navigate to a page, interact with elements using LLM for element identification, and run agent tasks. ### Method ```python async def main(): from browser_use import Browser, Agent from browser_use.llm.openai import ChatOpenAI llm = ChatOpenAI(api_key="your-api-key") browser = Browser() await browser.start() # 1. Actor: Precise navigation and element interactions page = await browser.new_page("https://github.com/login") email_input = await page.must_get_element_by_prompt("username field", llm=llm) await email_input.fill("your-username") # 2. Agent: AI-driven complex tasks agent = Agent(browser=browser, llm=llm) await agent.run("Complete login and navigate to my repositories") await browser.stop() ``` ``` -------------------------------- ### Perform Initial Login for Session Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Run the login script for the first-time setup. This process requires scanning a QR code in the browser to authenticate the session, which will be saved for future use. ```bash python login.py ``` -------------------------------- ### Create and Run an Agent with MCP-Style Tools Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/11-agentic-protocols/code_samples/11-mcp-agent-framework.ipynb Demonstrates how to create an AI agent using the `provider.create_agent` method, providing it with the previously defined tools (`search_accommodations`, `get_local_experiences`). It then shows how to run the agent with a user query to get personalized travel recommendations. ```python agent = await provider.create_agent( tools=[ search_accommodations, get_local_experiences ], name="AccommodationAgent", instructions='''You are an accommodation and travel experiences specialist powered by MCP-connected services. Help travelers find the perfect place to stay and things to do. When searching: 1. Use the search_accommodations tool to find listings 2. Use the get_local_experiences tool to suggest activities 3. Compare options and make personalized recommendations 4. Consider the traveler's budget, interests, and travel style''', ) response = await agent.run( "I'm visiting Tokyo for 5 nights in April with my partner. We love traditional Japanese culture and food. Find us a place to stay and suggest some experiences.", ) print(response) ``` -------------------------------- ### Start Chrome with Debug Port Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Launches a Chrome instance with the remote debugging protocol enabled on a specified port. Requires Chrome or Chromium to be installed and accessible in the system's PATH or specified locations. ```python async def start_chrome_with_debug_port(port: int = 9222): """ Start Chrome with remote debugging enabled. Returns the Chrome process. """ # Create temporary directory for Chrome user data user_data_dir = tempfile.mkdtemp(prefix='chrome_cdp_') # Chrome launch command chrome_paths = [ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', # macOS '/usr/bin/google-chrome', # Linux '/usr/bin/chromium-browser', # Linux Chromium 'chrome', # Windows/PATH 'chromium', # Generic ] chrome_exe = None for path in chrome_paths: if os.path.exists(path) or path in ['chrome', 'chromium']: try: # Test if executable works test_proc = await asyncio.create_subprocess_exec( path, '--version', stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) await test_proc.wait() chrome_exe = path break except Exception: continue if not chrome_exe: raise RuntimeError('❌ Chrome not found. Please install Chrome or Chromium.') # Chrome command arguments cmd = [ chrome_exe, f'--remote-debugging-port={port}', f'--user-data-dir={user_data_dir}', '--no-first-run', '--no-default-browser-check', '--disable-extensions', 'about:blank', # Start with blank page ] # Start Chrome process process = await asyncio.create_subprocess_exec(*cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # Wait for Chrome to start and CDP to be ready cdp_ready = False for _ in range(20): # 20 second timeout try: async with aiohttp.ClientSession() as session: async with session.get( f'http://localhost:{port}/json/version', timeout=aiohttp.ClientTimeout(total=1) ) as response: if response.status == 200: cdp_ready = True break except Exception: pass await asyncio.sleep(1) if not cdp_ready: process.terminate() raise RuntimeError('❌ Chrome failed to start with CDP') return process ``` -------------------------------- ### Make Script Executable and Run Sample Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/08-multi-agent/code_samples/08-dotnet-agent-framework.md Use these bash commands to make the C# sample file executable on Linux/macOS and then run it. ```bash # Make the file executable (Linux/macOS) chmod +x 08-dotnet-agent-framework.cs # Run the sample ./08-dotnet-agent-framework.cs ``` -------------------------------- ### Start Chrome with CDP and Connect Playwright Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ar/15-browser-use/15-browser-user.ipynb Initiates a Chrome instance with the Chrome DevTools Protocol enabled and connects Playwright to it for browser automation. This setup is crucial for agents that need to interact with a live browser session. ```python chrome_process = None playwright_browser = None try: # Step 1: Start Chrome with CDP display_action( "Chrome", "Starting Chrome with CDP (remote debugging)...") chrome_process = await start_chrome_with_cdp(port=9222) cdp_url = 'http://localhost:9222' # Step 2: Connect Playwright to CDP (optional - for custom Playwright actions) display_action( "Playwright", "Connecting Playwright to Chrome via CDP...") playwright = await async_playwright().start() playwright_browser = await playwright.chromium.connect_over_cdp(cdp_url) display_result(True, "Playwright connected successfully") # Step 3: Create Browser-Use agent with CDP connection display_action( "Browser-Use", "Creating Browser-Use agent with CDP connection...") agent = AirbnbSearchAgent(llm=llm, cdp_url=cdp_url) display_result(True, "Agent initialized with CDP integration") # Step 4: Search and extract prices result = await agent.search_stockholm() # Step 5: Display results display( HTML("
")) display(HTML("""

πŸ“Š Search Results

""")) # Display summary stats display(HTML(f"""

πŸ“ˆ Price Analysis

Location: {result.location}
Total Listings Found: {result.total_listings_found}
Average Price: {result.average_price:.2f} SEK/night
Price Range: {result.price_range}
""")) # Display the CHEAPEST listing with clickable link cheapest = result.cheapest_listing # Create View Listing button if URL exists view_button = "" if cheapest.url: view_button = f""" πŸ”— View Listing on Airbnb """ display(HTML(f"""

πŸ† CHEAPEST AIRBNB IN STOCKHOLM

{cheapest.title}

{cheapest.price_per_night:.2f} {cheapest.currency}/night

``` -------------------------------- ### Install Browser Use Package Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Install or upgrade the browser-use package to the latest version, ensuring screenshot functionality is included. ```bash pip install -U browser-use ``` -------------------------------- ### Build and Run Sequential Agent Workflow Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pcm/11-agentic-protocols/code_samples/11-a2a-agent-framework.ipynb Constructs a sequential workflow where agents process tasks in order, starting with currency exchange, then activity planning, and finally travel management. This example demonstrates running the workflow with a user request and streaming the output. ```python workflow = WorkflowBuilder(start_executor=currency_agent) \ .add_edge(currency_agent, activity_agent) \ .add_edge(activity_agent, travel_manager) \ .build() last_author = None events = workflow.run( "Plan a week-long trip to Tokyo. I love food, temples, and technology.", stream=True, ) async for event in events: if event.type == "output" and isinstance(event.data, AgentResponseUpdate): update = event.data author = update.author_name if author != last_author: if last_author is not None: print() print(f"\n{'='*50}") print(f"πŸ€– {author}:") print(f"{ '='*50}") last_author = author print(update.text, end="", flush=True) ``` -------------------------------- ### Install browser-use and Playwright with pip Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Install 'browser-use' and Playwright, including Chromium, using 'pip install' and 'playwright install'. ```bash pip install browser-use pip install playwright && playwright install chromium --with-deps ``` -------------------------------- ### Initialize Browser and Agent with OpenAI Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Sets up the Browser and an AI Agent using OpenAI's chat model. Requires an API key and ensures the browser is started before use. ```python from browser_use import Browser, Agent from browser_use.llm.openai import ChatOpenAI async def main(): llm = ChatOpenAI(api_key="your-api-key") browser = Browser() await browser.start() # 1. Actor: Precise navigation and element interactions page = await browser.new_page("https://github.com/login") email_input = await page.must_get_element_by_prompt("username field", llm=llm) await email_input.fill("your-username") # 2. Agent: AI-driven complex tasks agent = Agent(browser=browser, llm=llm) await agent.run("Complete login and navigate to my repositories") await browser.stop() ``` -------------------------------- ### Copy Example .env File (Linux/macOS) Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/00-course-setup/README.md Copy the example environment file to create your active .env file. This file will store your Azure AI project credentials. ```bash # zsh/bash cp .env.example .env ``` -------------------------------- ### Install Agent Framework Package Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/02-explore-agentic-frameworks/code_samples/02-python-agent-framework.ipynb Installs the necessary packages for the Microsoft Agent Framework and Azure AI Projects. Use '-U' to upgrade if already installed and '-q' for quiet installation. ```python # Install the Microsoft Agent Framework package ! pip install agent-framework azure-ai-projects -U -q ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/15-browser-user.ipynb Use this command to install the required Python packages for the project. Ensure you have pip and Python installed. ```bash pip install browser_use langchain-openai playwright ``` -------------------------------- ### Create and Run an Agent with Simulated MCP Tools Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh-CN/11-agentic-protocols/code_samples/11-mcp-agent-framework.ipynb Demonstrates how to create an agent using a provider, equipping it with the simulated `search_accommodations` and `get_local_experiences` tools. The agent is then run with a specific travel request to find accommodation and activities. ```python agent = await provider.create_agent( tools=[search_accommodations, get_local_experiences], name="AccommodationAgent", instructions="""You are an accommodation and travel experiences specialist powered by MCP-connected services. Help travelers find the perfect place to stay and things to do. When searching: 1. Use the search_accommodations tool to find listings 2. Use the get_local_experiences tool to suggest activities 3. Compare options and make personalized recommendations 4. Consider the traveler's budget, interests, and travel style""", ) response = await agent.run( "I'm visiting Tokyo for 5 nights in April with my partner. We love traditional Japanese culture and food. " "Find us a place to stay and suggest some experiences.", ) print(response) ``` -------------------------------- ### Workflow Execution Start Message Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/14-microsoft-agent-framework/code-samples/14-human-loop.ipynb This output indicates the start of a human-in-the-loop workflow, including the initial request and the start of the process. ```text πŸ”„ Starting human-in-the-loop workflow... ============================================================ πŸš€ Starting workflow with request: 'I want to book a hotel in Paris' ``` -------------------------------- ### Clone Repository and Navigate to App Directory Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Clone the browser-use repository and change the directory to the specific application folder for setup. ```bash git clone https://github.com/browser-use/browser-use.git cd browser-use/examples/apps/msg-use ``` ```bash git clone https://github.com/browser-use/browser-use.git cd browser-use/examples/apps/news-use ``` -------------------------------- ### Create Agent with Summarization Tool Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/12-context-engineering/code_samples/12-chat_summarization.ipynb Creates an AI agent named "SummarizingTravelAgent" that is configured to manage conversation context using the `summarize_preferences` tool. The agent's instructions guide it to summarize preferences, recall them when needed, and keep responses concise. This setup is useful for agents that need to maintain continuity and remember user details over extended interactions. ```python # Create an enhanced agent with the summarization tool summarizing_agent = await provider.create_agent( name="SummarizingTravelAgent", instructions="""You are a helpful travel planning assistant that actively manages conversation context. CONTEXT MANAGEMENT RULES: 1. After gathering several user preferences, call summarize_preferences() to record a compact summary 2. When the user asks you to recall details, reference your recorded summaries 3. Keep responses concise β€” avoid restating the entire history PLANNING PROCESS: 1. Gather user preferences (destination, budget, dates, interests) 2. Summarize preferences using the tool 3. Create recommendations based on the summary 4. Update the summary when preferences change""", tools=[summarize_preferences], ) print("πŸ€– Summarizing travel agent created with context tools") ``` -------------------------------- ### Run MCP Server and Client Demo Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/11-agentic-protocols/code_samples/mcp-agents/README.md Start the MCP server with event store for resumption, and then run the interactive client in another terminal. Ensure the client connects to the correct server URL. ```bash # Start the server with event store for resumption python -m server.server --port 8006 # In another terminal, run the interactive client python -m client.client --url http://127.0.0.1:8006/mcp ``` -------------------------------- ### Install browser-use and Playwright with uv Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Install the 'browser-use' library and Playwright with Chromium dependencies using 'uv pip install' and 'uvx'. ```bash uv pip install browser-use uvx playwright install chromium --with-deps ``` -------------------------------- ### Initialize BrowserProfile and Browser Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/15-browser-use/llms.txt Demonstrates initializing a BrowserProfile and then a Browser instance for backward compatibility. The BrowserProfile can accept various configuration parameters. ```python from browser_use import BrowserProfile profile = BrowserProfile(headless=False) browser = Browser(browser_profile=profile) ``` -------------------------------- ### Specify Folders for Sparse Checkout Source: https://github.com/microsoft/ai-agents-for-beginners/blob/main/00-course-setup/README.md After performing a sparse clone, navigate into the repository and use this command to specify which folders you want to download. This example selects '00-course-setup' and '01-intro-to-ai-agents'. ```bash cd ai-agents-for-beginners git sparse-checkout set 00-course-setup 01-intro-to-ai-agents ```