### Run the Magnitude Example Application Source: https://docs.magnitude.run/getting-started/introduction/getting-started/quickstart Navigate into the newly created project directory and execute `npm start` to run the basic example application provided by the template, showcasing Magnitude's core functionalities. ```shell cd my-project npm start ``` -------------------------------- ### Initialize Magnitude Project Configuration Source: https://docs.magnitude.run/getting-started/introduction/testing/test-setup Execute this command to initialize Magnitude within your project. It creates a `tests/magnitude` directory containing `magnitude.config.ts` for test configuration and an `example.mag.ts` file to get you started. ```shell npx magnitude init ``` -------------------------------- ### Install Magnitude Test Library Source: https://docs.magnitude.run/getting-started/introduction/testing/test-setup This command installs the `magnitude-test` package as a development dependency in your project. It's the first step to integrate Magnitude into your web application testing workflow. ```shell npm install --save-dev magnitude-test ``` -------------------------------- ### Create a New Magnitude Project Source: https://docs.magnitude.run/getting-started/introduction/getting-started/quickstart Use `npx` to run the `create-magnitude-app` script, which interactively sets up a new Magnitude project from a starter template, including LLM configuration. ```shell npx create-magnitude-app ``` -------------------------------- ### Example Magnitude Test Case in TypeScript Source: https://docs.magnitude.run/getting-started/introduction/testing/test-setup This TypeScript snippet demonstrates how to define a Magnitude test case. It utilizes `agent.act` for simulating user actions and `agent.check` for verifying application states, both expressed using natural language descriptions for clarity and readability. ```typescript import { test } from 'magnitude-test'; test('can log in and create company', async (agent) => { await agent.act('Log in to the app', { data: { username: 'test-user@magnitude.run', password: 'test' } }); await agent.check('Can see dashboard'); await agent.act('Create a new company', { data: 'Make up the first 2 values and use defaults for the rest' }); await agent.check('Company added successfully'); }); ``` -------------------------------- ### Run All Magnitude Tests Source: https://docs.magnitude.run/getting-started/introduction/testing/test-setup Use this command to execute all Magnitude test files identified by the `*.mag.ts` pattern. The Magnitude agent will report any issues found in your application. Optional `-w ` can be added for parallel test execution. ```shell npx magnitude ``` -------------------------------- ### GitHub Actions Workflow for Magnitude Tests Source: https://docs.magnitude.run/getting-started/introduction/testing/ci This GitHub Actions workflow demonstrates how to set up and run Magnitude tests in a CI environment. It includes steps for checking out code, setting up Node.js, installing dependencies, installing Playwright, starting a development server, waiting for it to be ready, and finally running Magnitude tests using `npx magnitude -p` within an Xvfb environment. ```YAML name: Run Magnitude Tests on: push: branches: [ main ] pull_request: branches: [ main ] jobs: test: runs-on: ubuntu-latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} steps: - uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: '22' cache: 'npm' - name: Install dependencies run: npm ci - name: Install playwright run: npx playwright install chromium - name: Start development server run: npm run dev & - name: Wait for server to start run: sleep 5 - name: Run tests with Xvfb uses: GabrielBB/xvfb-action@v1 with: run: npx magnitude -p ``` -------------------------------- ### BrowserAgent Launch with Proxy Configuration Source: https://docs.magnitude.run/getting-started/introduction/reference/browser-agent Example demonstrating how to configure `startBrowserAgent` to launch the browser with a specified proxy server using the `launchOptions` property within the `browser` configuration. ```javascript const agent = await startBrowserAgent({ browser: { launchOptions: { proxy: { server: 'http://my-proxy-server.com:8080' } } } }); ``` -------------------------------- ### Configure Moondream Grounding Provider Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers This TypeScript code snippet provides an example of configuring Moondream as a grounding provider within a Magnitude project. It shows how to specify a custom base URL for self-hosted instances and how to optionally include an API key, noting it's not required for self-hosted setups. ```TypeScript import { type MagnitudeConfig } from 'magnitude-test'; export default { url: "http://localhost:5173", grounding: { provider: 'moondream', options: { baseUrl: 'your-self-hosted-moondream-endpoint', apiKey: process.env.MOONDREAM_API_KEY // not necessary if self-hosted } } } satisfies MagnitudeConfig; ``` -------------------------------- ### Initialize Magnitude Browser Agent with Core Options Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/agent-options Demonstrates how to start a Magnitude browser agent, specifying the initial URL, enabling narration for agent thoughts and actions, configuring the LLM provider (Anthropic) with its model and API key, and setting a custom prompt for agent behavior. ```javascript await startBrowserAgent({ // Starting URL for agent url: "https://google.com", // Show thoughts and actions narrate: true, // LLM configuration llm: { provider: 'anthropic', options: { model: 'claude-sonnet-4-20250514', apiKey: process.env.ANTHROPIC_API_KEY } }, // Any system instructions specific to your agent or website prompt: 'Prefer mouse to keyboard when filling out form fields' }); ``` -------------------------------- ### Magnitude Test Case Example with `agent.act` and `agent.check` Source: https://docs.magnitude.run/getting-started/introduction/reference/test-case-agent Demonstrates a complete Magnitude test case using the `test` function from 'magnitude-test'. It illustrates how to perform browser actions with `agent.act` and verify conditions using `agent.check`, both driven by natural language descriptions. ```JavaScript import { test } from 'magnitude-test'; test('should create three todos', async (agent) => { await agent.act('create three todos'); await agent.check('three todos exist'); }); ``` -------------------------------- ### Configure Automatic Development Web Server Launch Source: https://docs.magnitude.run/getting-started/introduction/testing/test-configuration This configuration snippet shows how Magnitude can automatically launch a development server before tests run. It specifies the command to start the server, its URL, a timeout for startup, and an option to reuse an already running server. ```typescript import { type MagnitudeConfig } from 'magnitude-test'; export default { url: 'http://localhost:3000', webServer: { command: 'npm run start', url: 'http://localhost:3000', timeout: 120_000, reuseExistingServer: true } } satisfies MagnitudeConfig; ``` -------------------------------- ### BrowserAgent Context with Custom User Agent Source: https://docs.magnitude.run/getting-started/introduction/reference/browser-agent Example demonstrating how to set a custom user agent for the browser context when initializing `BrowserAgent` using the `contextOptions` property. ```javascript const agent = await startBrowserAgent({ browser: { contextOptions: { userAgent: 'MyCustomBrowser/1.0' } } }); ``` -------------------------------- ### Configure Test Case with Specific URL Source: https://docs.magnitude.run/getting-started/introduction/testing/building-test-cases Demonstrates how to override the default starting URL for a Magnitude test case by providing a 'url' option in the test configuration object. ```TypeScript test('can add and remove todos', { url: "https://mytodoapp.com" }, async (agent) => { await agent.act('Add a todo'); await agent.act('Remove the todo'); }); ``` -------------------------------- ### Configure Magnitude LLM Provider in TypeScript Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers Example `magnitude.config.ts` file demonstrating how to specify an LLM provider (e.g., Anthropic) and its options, including the model and API key. This configuration dictates which LLM Magnitude will use for its operations. ```typescript import { type MagnitudeConfig } from 'magnitude-test'; export default { url: "http://localhost:5173", llm: { provider: 'anthropic', // your provider of choice options: { // any required + optional configuration for that provider model: 'claude-3-7-sonnet-latest', apiKey: process.env.ANTHROPIC_API_KEY } } } satisfies MagnitudeConfig; ``` -------------------------------- ### Configure Magnitude with Google Vertex AI in TypeScript Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers Example `magnitude.config.ts` file showing how to configure Magnitude to use Google Vertex AI. This snippet demonstrates specifying the model and location, assuming prior authentication via the `gcloud` CLI. ```typescript import { type MagnitudeConfig } from "magnitude-test"; export default { url: "http://localhost:5173", llm: { provider: 'vertex-ai', options: { model: 'google/gemini-2.5-pro-preview-05-06', location: 'us-central1' } } } satisfies MagnitudeConfig; ``` -------------------------------- ### Example of Grouping Magnitude Test Cases Source: https://docs.magnitude.run/getting-started/introduction/reference/test-declaration This example demonstrates how to use `test.group` to organize multiple test cases under a shared configuration, such as a base URL. It shows nested `test` calls within the `groupFn` to define individual tests that inherit group-level options. ```typescript import { test } from 'magnitude-test'; test.group('User Authentication Flow', { url: '/login' }, () => { test('should display login form', async (agent) => { await agent.check("Login form is visible"); }); test('should allow login with valid credentials', async (agent) => { await agent.act("Log in with valid credentials"); await agent.check("User is redirected to dashboard"); }); }); ``` -------------------------------- ### Customize Playwright Browser Context Options Source: https://docs.magnitude.run/getting-started/introduction/testing/test-configuration This example demonstrates how to configure Playwright browser context options within `magnitude.config.ts`. It shows how to set a custom viewport size and enable video recording of test runs, specifying the output directory and video dimensions. ```typescript import { type MagnitudeConfig } from 'magnitude-test'; export default { url: "http://localhost:5173", browser: { contextOptions: { viewport: { width: 800, height: 600 }, recordVideo: { dir: './videos/', size: { width: 800, height: 600 } } } } } satisfies MagnitudeConfig; ``` -------------------------------- ### Perform Low-Level Playwright Operations with Magnitude Agent Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/playwright This example demonstrates how to access and utilize Playwright's `BrowserContext` and `Page` objects exposed by the Magnitude agent. It illustrates injecting authorization cookies, mocking API responses using `page.route`, and manually emulating keyboard presses, providing fine-grained control over browser interactions. ```javascript // Inject some authorization cookies directly with browser context await agent.context.addCookies([{ name: 'session_id', value: 'fake-session-token', domain: 'localhost', path: '/' }]); // Mock the settings API await agent.page.route('**/api/user/settings', async route => { await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockProfileData) }); }); // Manually emulate a keypress await agent.page.keyboard.press('ArrowRight'); ``` -------------------------------- ### BrowserAgent.stop() Method and Basic Usage Example Source: https://docs.magnitude.run/getting-started/introduction/reference/browser-agent Closes the browser and cleans up any resources used by the agent. This method is crucial for proper termination and resource management after completing browser automation tasks. ```APIDOC stop() Closes the browser and cleans up any resources used by the agent. ``` ```TypeScript import { startBrowserAgent } from 'magnitude-core'; const agent = await startBrowserAgent(); await agent.nav("https://google.com"); // ... perform actions await agent.stop(); ``` -------------------------------- ### Extracting a single number with Zod Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/data-extraction Demonstrates the basic usage of `agent.extract()` to retrieve a single numerical value from the current browser page. It combines a natural language instruction with a simple Zod number schema to guide the data extraction process. ```JavaScript import z from 'zod'; const numInProgress = await agent.extract( 'how many items are "In Progress"?', z.number() ); ``` -------------------------------- ### Connect Magnitude Agent to an Existing CDP-Enabled Browser Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/agent-options Shows how to connect the Magnitude agent to an already running browser instance that exposes a Chrome DevTools Protocol (CDP) endpoint. This allows the agent to control an external browser, useful for integrating with existing browser setups or debugging sessions. ```javascript const agent = await startBrowserAgent({ url: "https://google.com", browser: { cdp: "http://localhost:9222" } }); ``` -------------------------------- ### Extracting complex array of objects with Zod Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/data-extraction Illustrates how to use `agent.extract()` with a sophisticated Zod schema to extract an array of complex objects. This example defines a detailed schema for 'tasks' including strings, enums, and arrays, showcasing Magnitude's ability to capture rich, structured data. ```JavaScript const tasks = await agent.extract( 'list all tasks', z.array(z.object({ title: z.string(), status: z.enum(['todo', 'inprogress', 'done']), description: z.string(), priority: z.enum(['low', 'medium', 'high', 'urgent']), labels: z.array(z.string()), assignee: z.string() })) ); ``` -------------------------------- ### Basic Usage of BrowserAgent Source: https://docs.magnitude.run/getting-started/introduction/reference/browser-agent Demonstrates how to import the `startBrowserAgent` function, initialize a BrowserAgent instance, navigate to a URL, and stop the agent. ```javascript import { startBrowserAgent } from 'magnitude-core'; const agent = await startBrowserAgent(); await agent.nav("https://google.com"); // ... perform actions await agent.stop(); ``` -------------------------------- ### startBrowserAgent Function API Reference Source: https://docs.magnitude.run/getting-started/introduction/reference/browser-agent Detailed API documentation for the `startBrowserAgent` function, including its optional `options` parameter and all configurable sub-properties for browser behavior, LLM settings, and visual input dimensions. ```APIDOC startBrowserAgent(options?): BrowserAgent instance description: This function creates, initializes, and returns a BrowserAgent instance. options: object (optional) description: An optional configuration object that can be used to customize the agent’s behavior, including Playwright launch options and LLM settings. properties: browser: object description: An object to configure the browser instance. It can contain either Playwright `launchOptions` or `contextOptions`. properties: launchOptions: object description: Standard Playwright launch options. See the Playwright documentation for a full list of options. contextOptions: object description: Standard Playwright browser context options. See the Playwright documentation for a full list of options. url: string description: An initial URL to navigate to immediately after the browser starts. virtualScreenDimensions: { width: number, height: number } description: Sets the resolution of the screenshot that the LLM sees. This does not change the browser’s viewport size, but scales the screenshot to these dimensions. This is useful for ensuring a consistent input size for the vision model. llm: object description: Configure the LLM to be used by the agent. See the LLM Providers documentation for details. narrate: boolean description: If true, the agent will narrate its actions to the console, providing a running commentary of what it’s doing. ``` -------------------------------- ### Configure Magnitude Browser Agent with Qwen 2.5 VL 72B via OpenRouter Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/compatible-llms This code snippet demonstrates how to initialize a Magnitude browser agent using `startBrowserAgent` and configure it to use the Qwen 2.5 VL 72B model through OpenRouter's API. It sets the `baseUrl` to OpenRouter and specifies the model and API key from environment variables. ```javascript const agent = await startBrowserAgent({ url: "https://google.com", llm: { provider: 'openai-generic', options: { baseUrl: 'https://openrouter.ai/api/v1', model: 'qwen/qwen2.5-vl-72b-instruct', apiKey: process.env.OPENROUTER_API_KEY } } }); ``` -------------------------------- ### Execute All Magnitude Test Cases Source: https://docs.magnitude.run/getting-started/introduction/testing/running-tests This command initiates the execution of all Magnitude test cases defined in your project using the Magnitude CLI. ```shell npx magnitude ``` -------------------------------- ### Define a Basic Magnitude Test Case Source: https://docs.magnitude.run/getting-started/introduction/testing/building-test-cases Illustrates the fundamental structure of a Magnitude test case, showing how to define a test that navigates to a URL and performs actions using an agent. ```TypeScript test('can add and remove todos', async (agent) => { await agent.act('Add a todo'); await agent.act('Remove the todo'); }); ``` -------------------------------- ### Configure Browser Launch and Context Options for Magnitude Agent Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/agent-options Illustrates how to pass detailed browser configuration options to the Magnitude agent, including Playwright launch options like enabling CDP for debugging, and context options such as setting a specific viewport size, providing fine-grained control over the browser environment. ```javascript const agent = await startBrowserAgent({ url: "https://google.com", browser: { // Configured launched browser: launchOptions: { // chromium launch options, for example enabling CDP args: ["--remote-debugging-port=9222"] }, contextOptions: { // see https://playwright.dev/docs/api/class-browser#browser-new-context // for comprehensive list of options viewport: { width: 1280, height: 720 } } } }); ``` -------------------------------- ### Custom LLM Prompting for an Action Source: https://docs.magnitude.run/getting-started/introduction/testing/building-test-cases Explains how to provide custom instructions to the underlying LLM for a specific `agent.act()` call using the `prompt` option, influencing the agent's behavior during that step. ```TypeScript test('example', async (agent) => { await agent.act('create 3 todos', { prompt: 'all todos must be animal-related' }); }); ``` -------------------------------- ### Provide Key-Value Test Data for a Step Source: https://docs.magnitude.run/getting-started/introduction/testing/building-test-cases Demonstrates how to pass structured key-value pair data to a test step using the `data` option within `agent.act()`, useful for inputs like login credentials or form fields. ```TypeScript test('example', async (agent) => { await agent.act('Log in', { data: { email: "foo@bar.com", password: "foo" } }); await agent.check('Dashboard is visible'); }); ``` -------------------------------- ### Provide Custom Prompt Instructions to agent.act() Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/browser-interaction Illustrates using the `prompt` option within `agent.act()` to give custom system prompt instructions to the agent. This influences its behavior for a specific action, such as requiring output or actions in a certain style or language. ```JavaScript await agent.act('create a new task', { prompt: 'tasks should be written in spanish' }); ``` -------------------------------- ### Google AI Studio Client Interface Definition Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers API documentation for the `GoogleAIClient` interface, detailing its `provider` type and `options` for configuring Google AI models. It specifies parameters like `model`, optional `apiKey`, `temperature`, and `baseUrl`. ```APIDOC interface GoogleAIClient { provider: 'google-ai', options: { model: string, apiKey?: string // defaults to GOOGLE_API_KEY temperature?: number, baseUrl?: string // defaults to https://generativelanguage.googleapis.com/v1beta } } ``` -------------------------------- ### Google Vertex AI Client Interface Definition Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers API documentation for the `GoogleVertexClient` interface, outlining its `provider` type and `options` for configuring Google Vertex AI models. It includes parameters such as `model`, `location`, optional `baseUrl`, `projectId`, `credentials`, and `temperature`. ```APIDOC interface GoogleVertexClient { provider: 'vertex-ai', options: { model: string, location: string, baseUrl?: string, projectId?: string, credentials?: string | object, temperature?: number, } } ``` -------------------------------- ### Provide Freeform String Test Data for a Step Source: https://docs.magnitude.run/getting-started/introduction/testing/building-test-cases Shows how to pass completely freeform string data to a test step using the `data` option, allowing for more descriptive or unstructured input for the agent's interpretation. ```TypeScript test('example', async (agent) => { await agent.act('Add 3 todos', { data: 'Use "Take out trash" for the first todo and make up the other 2' }); }); ``` -------------------------------- ### Magnitude Test Case and Agent API Reference Source: https://docs.magnitude.run/getting-started/introduction/testing/building-test-cases Comprehensive reference for the `test` function and `agent` methods used in Magnitude test cases, detailing their parameters, types, and purpose. ```APIDOC test(description: string, options?: { url: string }, callback: (agent: Agent) => Promise): void description: A string describing the test case's purpose. options: Optional configuration object. url: string - The starting URL for the test case (overrides project default). callback: An asynchronous function receiving an 'agent' instance. Agent: act(description: string, options?: { data?: string | object, prompt?: string }): Promise description: A natural language description of the action to perform. options: Optional configuration for the action. data: string | object - Additional test data for the step (key-value object or freeform string). prompt: string - Custom instructions for the underlying LLM. check(description: string): Promise description: A natural language visual assertion to validate after the step. ``` -------------------------------- ### Define a Single Test Step with Description Source: https://docs.magnitude.run/getting-started/introduction/testing/building-test-cases Shows how to define an individual step within a Magnitude test case using `agent.act()`, providing a clear natural language description of the action to be performed. ```TypeScript test('example', async (agent) => { await agent.act('Log in'); // step description }); ``` -------------------------------- ### Perform High-Level Browser Actions with agent.act() Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/browser-interaction Demonstrates using `agent.act()` to instruct the agent to perform a high-level task like logging in. This allows for abstract commands rather than specific UI interactions, letting the agent determine the necessary steps. ```JavaScript await agent.act('log in to the app'); ``` -------------------------------- ### OpenAI Client Interface Definition Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers API documentation for the `OpenAIClient` interface, detailing its `provider` type and `options` for configuring OpenAI models. It specifies parameters such as `model`, optional `apiKey`, and `temperature`. ```APIDOC interface OpenAIClient { provider: 'openai', options: { model: string, apiKey?: string, temperature?: number } } ``` -------------------------------- ### TestCaseAgent `agent.check` Method API Reference Source: https://docs.magnitude.run/getting-started/introduction/reference/test-case-agent API documentation for the `agent.check` method of the `TestCaseAgent` class. This method allows verifying conditions on a web page using a natural language description, which is then evaluated by AI against the current DOM state. ```APIDOC TestCaseAgent.check(description: string): Promise description: A natural language statement describing the expected condition or state to verify. (required) ``` -------------------------------- ### Configure Magnitude Global LLM Settings in magnitude.config.ts Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/compatible-llms This configuration file snippet shows how to set up the default LLM provider for Magnitude globally using `magnitude.config.ts`. It configures the `openai-generic` provider to use Qwen 2.5 VL 72B via OpenRouter, including the base URL, model name, and API key from environment variables. ```typescript export default { url: "http://localhost:5173", llm: { provider: 'openai-generic', options: { baseUrl: 'https://openrouter.ai/api/v1', model: 'qwen/qwen2.5-vl-72b-instruct', apiKey: process.env.OPENROUTER_API_KEY } } } satisfies MagnitudeConfig; ``` -------------------------------- ### Migrating Playwright Todo Test to Magnitude Source: https://docs.magnitude.run/getting-started/introduction/testing/building-test-cases This snippet compares a Playwright test case for adding todo items with its equivalent implementation in Magnitude. It demonstrates how Magnitude abstracts direct UI interactions into higher-level `agent.act` and `agent.check` calls, simplifying test logic and improving readability compared to Playwright's direct DOM manipulation. ```Playwright (JavaScript) test('should allow me to add todo items', async ({ page }) => { const newTodo = page.getByPlaceholder('What needs to be done?'); await newTodo.fill(TODO_ITEMS[0]); await newTodo.press('Enter'); await expect(page.getByTestId('todo-title')).toHaveText([ TODO_ITEMS[0] ]); await newTodo.fill(TODO_ITEMS[1]); await newTodo.press('Enter'); await expect(page.getByTestId('todo-title')).toHaveText([ TODO_ITEMS[0], TODO_ITEMS[1] ]); }); ``` ```Magnitude (JavaScript) test('should allow me to add todo items', async (agent) => { await agent.act('Create todo', { data: TODO_ITEMS[0] }); await agent.check('First todo appears in list'); await agent.act('Create another todo', { data: TODO_ITEMS[1] }); await agent.check('List has two todos'); }); ``` -------------------------------- ### Anthropic Client Interface Definition Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers API documentation for the `AnthropicClient` interface, specifying its `provider` type and `options` for configuring Anthropic models. It includes parameters like `model`, optional `apiKey`, and `temperature`. ```APIDOC interface AnthropicClient { provider: 'anthropic', options: { model: string, apiKey?: string, temperature?: number } } ``` -------------------------------- ### Navigate Directly to a URL with agent.nav() Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/browser-interaction Shows how to use `agent.nav()` to force the agent to navigate to a specific URL. This is useful when direct control over navigation is desired, bypassing the agent's own navigation capabilities. ```JavaScript await agent.nav('https://google.com'); ``` -------------------------------- ### Set AWS Bedrock Authentication Environment Variables Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers These shell commands demonstrate how to set the necessary environment variables for authenticating with AWS Bedrock. It includes setting the AWS access key ID, secret access key, and the AWS region, which are crucial for programmatic access. ```Shell export AWS_ACCESS_KEY_ID="your_key" export AWS_SECRET_ACCESS_KEY="your_secret" export AWS_REGION="us-east-1" ``` -------------------------------- ### BrowserAgent.extract() Method for Structured Data Extraction Source: https://docs.magnitude.run/getting-started/introduction/reference/browser-agent Uses AI to pull structured data from a webpage based on natural language instructions and a Zod schema. Adding `.describe()` calls to schema fields can significantly improve the accuracy of the extraction by providing more context to the AI. ```APIDOC extract(instructions: string, schema: ZodSchema) instructions: string (required) Natural language instructions for the AI, describing what data to extract from the page. schema: ZodSchema (required) A Zod schema that defines the structure of the data to be extracted. The AI will do its best to populate the fields of the schema based on the page content and your instructions. Adding .describe() calls to your schema fields can significantly improve the accuracy of the extraction by providing more context to the AI. ``` ```TypeScript import { startBrowserAgent } from 'magnitude-core'; import { z } from 'zod'; const HackerNewsStory = z.object({ rank: z.number().describe('The story rank'), title: z.string().describe('The title of the story'), url: z.string().url().describe('The URL of the story') }); const HackerNewsSchema = z.array(HackerNewsStory); const agent = await startBrowserAgent(); await agent.nav("https://news.ycombinator.com"); const stories = await agent.extract( "Extract the top 5 stories from Hacker News", HackerNewsSchema ); console.log(stories); await agent.stop(); ``` -------------------------------- ### Define Azure OpenAI Client Configuration Interface Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers This TypeScript interface outlines the required parameters for configuring an Azure OpenAI LLM client. It specifies the Azure resource name, deployment ID, API version, and the API key necessary for authentication and access to the service. ```TypeScript interface AzureOpenAIClient { provider: 'azure-openai', options: { resourceName: string, deploymentId: string, apiVersion: string, apiKey: string } } ``` -------------------------------- ### Perform Low-Level Browser Actions with agent.act() Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/browser-interaction Illustrates using `agent.act()` for a specific, low-level browser action such as clicking a submit button. This shows the flexibility of `act()` for detailed interactions when more precision is needed. ```JavaScript await agent.act('click the submit button'); ``` -------------------------------- ### Define OpenAI-Compatible Client Configuration Interface Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers This TypeScript interface defines the structure for configuring generic OpenAI-compatible LLM clients. It includes properties for the provider type, model name, base URL, optional API key, temperature, and custom headers for API requests. ```TypeScript interface OpenAIGenericClient { provider: 'openai-generic' options: { model: string, baseUrl: string, apiKey?: string, temperature?: number, headers?: Record } } ``` -------------------------------- ### Chain Multiple agent.act() Calls Sequentially Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/browser-interaction Shows how to combine several `agent.act()` calls sequentially to achieve a complex workflow. Each call represents a distinct step, allowing for granular control over the interaction sequence. ```JavaScript await agent.act('go to tasks page'); await agent.act('assign all pending tasks to Bob'); await agent.act('move all pending tasks to "In Progress"'); ``` -------------------------------- ### BrowserAgent.nav() Method for URL Navigation Source: https://docs.magnitude.run/getting-started/introduction/reference/browser-agent Navigates the browser to a specified URL. This method is fundamental for directing the agent to the desired web page before performing actions or extractions. ```APIDOC nav(url: string) url: string (required) The URL to navigate to. ``` ```JavaScript await agent.nav('https://google.com'); ``` -------------------------------- ### Chain Multiple Actions within a Single agent.act() Call Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/browser-interaction Demonstrates an alternative way to chain actions by providing an array of instructions to a single `agent.act()` call. This can simplify code for sequential operations, grouping related steps for convenience. ```JavaScript await agent.act([ 'go to tasks page', 'assign all pending tasks to Bob', 'move all pending tasks to "In Progress"' ]); ``` -------------------------------- ### Chaining data extraction with agent actions Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/data-extraction Shows how extracted data can be integrated into standard control flow to trigger subsequent agent actions. This snippet filters extracted tasks based on priority and status, and if a condition is met, uses `agent.act()` to create a new task, demonstrating dynamic workflow automation. ```JavaScript const urgentTasks = tasks.filter( task => task.priority === 'urgent' && task.status === 'todo' ); if (urgentTasks.length > 10) { await agent.act('create a new task', data: { title: 'get some of these urgent tasks done!', description: urgentTasks.map(task => task.title).join(', ') }); } ``` -------------------------------- ### Default Magnitude Test Runner Configuration Source: https://docs.magnitude.run/getting-started/introduction/testing/test-configuration This snippet shows the basic `magnitude.config.ts` file structure, generated by `npx magnitude init`. It defines the default URL that all test cases will use unless overridden. ```typescript import { type MagnitudeConfig } from 'magnitude-test'; export default { url: "http://localhost:5173" } satisfies MagnitudeConfig; ``` -------------------------------- ### API Reference for `test` Function Source: https://docs.magnitude.run/getting-started/introduction/reference/test-declaration Detailed API specification for the `test` function, outlining its parameters: `title` (string), `options` (object, optional), and `testFn` (asynchronous function). It describes the purpose of each parameter, including the `agent` object passed to `testFn` for AI and Playwright interactions. ```APIDOC test(title, options?, testFn) title: string (required) A descriptive title for the test case. This title appears in test reports and logs. options: object (optional) Optional configuration specific to this test case. url: string Overrides the base URL defined in the global configuration or test group for this specific test case. testFn: (agent) => Promise (required) An asynchronous function containing the test logic. It receives an `agent` object with the properties described below. agent: object (required) The agent object providing methods for AI interaction (`agent.act()`, `agent.check()`) and access to Playwright’s `agent.page` and `agent.context`. See [AI Steps and Checks](./ai-steps-checks), [Low-Level AI Actions](./ai-low-level), and [Playwright Access](./playwright-access). ``` -------------------------------- ### BrowserAgent.act() Method for Natural Language Actions Source: https://docs.magnitude.run/getting-started/introduction/reference/browser-agent Executes one or more browser actions based on a natural language description. Magnitude interprets the description and determines the necessary interactions (clicks, types, scrolls, etc.). It supports injecting data into placeholders within the description. ```APIDOC act(description: string, options?: object) description: string (required) A natural language description of the action(s) to perform. Can include placeholders like {key} which will be substituted by values from options.data. options: object (optional) Optional parameters for the step. Properties: data: string | Record Provides data for the step. - string: A single string value. - Record: Key-value pairs where keys match placeholders in the description. prompt: string Provide additional instructions for the LLM. These are injected into the system prompt. ``` ```JavaScript // Simple step await agent.act("Click the main login button"); // Step with data await agent.act("Enter {username} into the user field", { data: { username: "test@example.com" } }); ``` -------------------------------- ### Define AWS Bedrock Client Configuration Interface Source: https://docs.magnitude.run/getting-started/introduction/reference/llm-providers This TypeScript interface specifies the configuration options for integrating with AWS Bedrock LLM services. It includes the provider type, the specific model to be used, and an optional temperature setting for inference configuration. ```TypeScript interface BedrockClient { provider: 'aws-bedrock', options: { model: string, // passed to inference_configuration temperature?: number } } ``` -------------------------------- ### Provide Arbitrary Data to agent.act() for Context Source: https://docs.magnitude.run/getting-started/introduction/core-concepts/browser-interaction Explains how to pass a `data` object to `agent.act()` to provide additional context or specific values for the agent's actions. This allows the agent to use structured information, like a task title and description, during its operation. ```JavaScript await agent.act('create a new task', { data: { title: 'important task', description: 'some description' } }); ``` -------------------------------- ### Run Magnitude Tests in Parallel Source: https://docs.magnitude.run/getting-started/introduction/testing/running-tests This command executes Magnitude tests concurrently across multiple worker processes. The `--workers` or `-w` flag specifies the desired number of parallel workers. ```shell npx magnitude -w 4 ``` -------------------------------- ### Add a Natural Language Check to a Test Step Source: https://docs.magnitude.run/getting-started/introduction/testing/building-test-cases Illustrates how to incorporate a natural language visual assertion (`agent.check()`) after a test step to validate the state or content of the web application. ```TypeScript test('example', async (agent) => { await agent.act('Log in'); await agent.check('Dashboard is visible'); }); ``` -------------------------------- ### BrowserAgent Access to Playwright Page and Context Source: https://docs.magnitude.run/getting-started/introduction/reference/browser-agent Provides direct access to the underlying Playwright `Page` and `BrowserContext` objects. This allows for advanced browser control and interactions beyond what the high-level `BrowserAgent` methods offer. ```APIDOC Properties: page: Playwright.Page Access the underlying Playwright Page object. context: Playwright.BrowserContext Access the underlying Playwright BrowserContext object. ``` ```JavaScript const page = agent.page; const context = agent.context; ``` -------------------------------- ### Define a Basic Magnitude Test Case Source: https://docs.magnitude.run/getting-started/introduction/reference/test-declaration This snippet demonstrates the fundamental structure for defining a test case using the `test` function imported from `magnitude-test`. It takes a descriptive title and an asynchronous function containing the test logic, which receives an `agent` object for interactions. ```typescript import { test } from 'magnitude-test'; test('Descriptive test title', async (agent) => { // Test logic using agent }); ``` -------------------------------- ### API Reference for `test.group` Method Source: https://docs.magnitude.run/getting-started/introduction/reference/test-declaration Detailed API specification for the `test.group` method, used to define a collection of test cases that can share common options. It specifies parameters for `id` (string), `options` (object, optional), and `groupFn` (synchronous function) that contains the nested `test()` declarations. ```APIDOC test.group(id, options?, groupFn) id: string (required) A descriptive identifier for the test group. options: object (optional) Optional configuration applied to all tests within this group. url: string Sets a base URL for all tests within the group. Can be overridden by individual test options. groupFn: () => void (required) A synchronous function that contains the `test()` declarations belonging to this group. ``` -------------------------------- ### Disable Telemetry in Magnitude Configuration Source: https://docs.magnitude.run/getting-started/introduction/testing/test-configuration This configuration snippet demonstrates how to disable telemetry collection in Magnitude. By setting the 'telemetry' property to 'false' within the MagnitudeConfig object, you prevent the sending of basic anonymized usage data during test runs. ```typescript import { type MagnitudeConfig } from 'magnitude-test'; export default { url: "http://localhost:5173", telemetry: false } satisfies MagnitudeConfig; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.