> ## Documentation Index
> Fetch the complete documentation index at: https://docs.anchorbrowser.io/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Anchor Browser is cloud browser infrastructure for AI agents and automation: browser sessions you control over CDP or REST, natural-language web tasks, versioned automation tasks, managed authentication into third-party web apps (identities with MFA), persistent volumes and profiles, recordings, live view, batch sessions, webhooks, and network options including residential proxies, extra stealth, and captcha solving for sites that block standard browsers. The for-agents page (https://docs.anchorbrowser.io/for-agents) covers authentication and the first API calls. API keys are created at https://app.anchorbrowser.io/api-keys. Append .md to any page URL for its Markdown version. The SDKs read the API key from ANCHORBROWSER_API_KEY, and REST calls send it in the anchor-api-key header. End every session you create with DELETE /v1/sessions/{id}, because a session is billed until it ends. Location targeting, captcha solving and managed authentication need the Starter plan, and extra stealth needs the Growth plan; on the Free plan, create a session with an empty body. Plans and limits are at https://docs.anchorbrowser.io/pricing. The hosted MCP server is https://api.anchorbrowser.io/v1/mcp.

# Fireworks AI

> Run browser agents on Fireworks-hosted open models in an Anchor cloud browser, with Python and TypeScript examples.

[Fireworks AI](https://fireworks.ai/?utm_source=anchor) runs open models like GLM, Kimi, DeepSeek and MiniMax on fast serverless inference. Its API is OpenAI compatible, so any OpenAI SDK can talk to it by changing the base URL.

This guide connects the two. Anchor gives your agent a real cloud browser, and a Fireworks model decides what to do in it through tool calls. By the end you'll have an agent that opens GitHub Trending in an Anchor session and returns the top five repositories.

## Prerequisites

* Python 3.10 or higher, or Node.js 22 or higher
* An Anchor API key from the [Anchor dashboard](https://app.anchorbrowser.io/api-keys)
* A Fireworks API key from [app.fireworks.ai](https://app.fireworks.ai/settings/users/api-keys?utm_source=anchor)

In Fireworks, open **Settings**, then **API Keys**, and click **Create API Key**.

![The API Keys page in Fireworks settings, with the Create API Key button outlined.](https://mintcdn.com/anchor-b3ec2715/z6j4C99gvTLi2iPC/images/fireworks/fireworks-api-keys.png?fit=max\&auto=format\&n=z6j4C99gvTLi2iPC\&q=85\&s=2686c7bb304615e54712e22302773e87)

## Setup

1. **Set your API keys:**

```bash theme={null}
export ANCHORBROWSER_API_KEY="your-anchor-key"
export FIREWORKS_API_KEY="your-fireworks-key"
```

2. **Install dependencies:**

```bash Python theme={null}
pip install anchorbrowser openai playwright httpx
```

```bash Node.js theme={null}
npm install anchorbrowser openai playwright-core
npm install -D tsx
npm pkg set type=module
```

You don't need to run `playwright install`. The browser runs in Anchor, and Playwright only connects to it over CDP.

## Quick example: a Fireworks agent in an Anchor browser

The script below:

1. Creates an Anchor session with a 5 minute limit.
2. Connects Playwright to it over CDP.
3. Gives a Fireworks model two tools, `goto` and `get_text`, and lets it call them until it has an answer, for up to 8 steps.
4. Ends the session, even if something fails along the way.

It uses `accounts/fireworks/models/glm-5p3-flash` by default. Set `FIREWORKS_MODEL` to try another model with function calling, such as `accounts/fireworks/models/kimi-k3p1-pro`, `accounts/fireworks/models/deepseek-v4p1-flash-1017` or `accounts/fireworks/models/minimax-m3`.

```python fireworks_agent.py theme={null}
import json
import os

from anchorbrowser import Anchorbrowser
from openai import OpenAI
from playwright.sync_api import sync_playwright

MODEL = os.getenv("FIREWORKS_MODEL", "accounts/fireworks/models/glm-5p3-flash")
TASK = "Open GitHub Trending and give me the top 5 trending repositories."

fireworks = OpenAI(
    api_key=os.environ["FIREWORKS_API_KEY"],
    base_url=os.getenv("FIREWORKS_BASE_URL", "https://api.fireworks.ai/inference/v1"),
)
anchor = Anchorbrowser(api_key=os.environ["ANCHORBROWSER_API_KEY"])

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "goto",
            "description": "Open a URL in the browser and return the page title.",
            "parameters": {
                "type": "object",
                "properties": {"url": {"type": "string"}},
                "required": ["url"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_text",
            "description": "Return the text of every element matching a CSS selector on the current page (max 30).",
            "parameters": {
                "type": "object",
                "properties": {"selector": {"type": "string"}},
                "required": ["selector"],
            },
        },
    },
]


def run_tool(page, name, args):
    if name == "goto":
        page.goto(args["url"], wait_until="domcontentloaded")
        return {"title": page.title(), "url": page.url}
    if name == "get_text":
        texts = page.locator(args["selector"]).all_inner_texts()
        return {"count": len(texts), "texts": texts[:30]}
    return {"error": f"unknown tool {name}"}


session = anchor.sessions.create_session(
    session={
        "timeout": {"max_duration": 5, "idle_timeout": 1},
    }
)
print("Anchor session:", session.data.id)

try:
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp(session.data.cdp_url)
        context = browser.contexts[0]
        page = context.pages[0] if context.pages else context.new_page()

        messages = [
            {
                "role": "system",
                "content": (
                    "You control a real web browser through tools. Use goto to open pages "
                    "and get_text with CSS selectors to read them. On github.com/trending, "
                    "repository names match the selector 'article.Box-row h2 a'. When you have the "
                    "answer, reply with a JSON list of strings and nothing else."
                ),
            },
            {"role": "user", "content": TASK},
        ]

        for step in range(8):
            response = fireworks.chat.completions.create(
                model=MODEL, messages=messages, tools=TOOLS, temperature=0
            )
            message = response.choices[0].message
            messages.append(message.model_dump(exclude_none=True))

            if not message.tool_calls:
                print("\nAnswer from", MODEL)
                print(message.content)
                break

            for call in message.tool_calls:
                args = json.loads(call.function.arguments or "{}")
                result = run_tool(page, call.function.name, args)
                print(f"step {step + 1}: {call.function.name}({args})")
                messages.append(
                    {
                        "role": "tool",
                        "tool_call_id": call.id,
                        "content": json.dumps(result),
                    }
                )
        else:
            print("\nNo answer after 8 steps.")

        browser.close()
finally:
    anchor.sessions.delete_session(session.data.id)
    print("Session ended.")
```

```typescript fireworks-agent.ts theme={null}
import { client, Sessions } from 'anchorbrowser';
import OpenAI from 'openai';
import { chromium, type Page } from 'playwright-core';

const MODEL = process.env.FIREWORKS_MODEL ?? 'accounts/fireworks/models/glm-5p3-flash';
const TASK = 'Open GitHub Trending and give me the top 5 trending repositories.';

client.setConfig({ auth: () => process.env.ANCHORBROWSER_API_KEY });

const fireworks = new OpenAI({
  apiKey: process.env.FIREWORKS_API_KEY,
  baseURL: process.env.FIREWORKS_BASE_URL ?? 'https://api.fireworks.ai/inference/v1',
});

const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
  {
    type: 'function',
    function: {
      name: 'goto',
      description: 'Open a URL in the browser and return the page title.',
      parameters: {
        type: 'object',
        properties: { url: { type: 'string' } },
        required: ['url'],
      },
    },
  },
  {
    type: 'function',
    function: {
      name: 'get_text',
      description: 'Return the text of every element matching a CSS selector on the current page (max 30).',
      parameters: {
        type: 'object',
        properties: { selector: { type: 'string' } },
        required: ['selector'],
      },
    },
  },
];

async function runTool(page: Page, name: string, args: Record<string, string>) {
  if (name === 'goto') {
    await page.goto(args.url, { waitUntil: 'domcontentloaded' });
    return { title: await page.title(), url: page.url() };
  }
  if (name === 'get_text') {
    const texts = await page.locator(args.selector).allInnerTexts();
    return { count: texts.length, texts: texts.slice(0, 30) };
  }
  return { error: `unknown tool ${name}` };
}

const session = await Sessions.createSession({
  body: {
    session: {
      timeout: { max_duration: 5, idle_timeout: 1 },
    },
  },
});
const sessionId = session.data!.id!;
console.log('Anchor session:', sessionId);

try {
  const browser = await chromium.connectOverCDP(session.data!.cdp_url!);
  const context = browser.contexts()[0];
  const page = context.pages()[0] ?? (await context.newPage());

  const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
    {
      role: 'system',
      content:
        "You control a real web browser through tools. Use goto to open pages and get_text " +
        "with CSS selectors to read them. On github.com/trending, repository names match the " +
        "selector 'article.Box-row h2 a'. When you have the answer, reply with a JSON list of " +
        'strings and nothing else.',
    },
    { role: 'user', content: TASK },
  ];

  let answered = false;
  for (let step = 1; step <= 8; step++) {
    const response = await fireworks.chat.completions.create({
      model: MODEL,
      messages,
      tools,
      temperature: 0,
    });
    const message = response.choices[0].message;
    messages.push(message);

    if (!message.tool_calls?.length) {
      console.log(`\nAnswer from ${MODEL}`);
      console.log(message.content);
      answered = true;
      break;
    }

    for (const call of message.tool_calls) {
      if (call.type !== 'function') continue;
      const args = JSON.parse(call.function.arguments || '{}');
      const result = await runTool(page, call.function.name, args);
      console.log(`step ${step}: ${call.function.name}(${JSON.stringify(args)})`);
      messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
    }
  }
  if (!answered) console.log('\nNo answer after 8 steps.');

  await browser.close();
} finally {
  await Sessions.deleteSession({ path: { session_id: sessionId } });
  console.log('Session ended.');
}
```

Run it:

```bash Python theme={null}
python fireworks_agent.py
```

```bash Node.js theme={null}
npx tsx fireworks-agent.ts
```

The TypeScript file uses top-level `await`, which needs `"type": "module"` in your `package.json`. The install step sets it with `npm pkg set type=module`.

## Expected output

```text theme={null}
Anchor session: 0b7ef096-8fd2-4f4b-aa6a-1451865d2de2
step 1: goto({'url': 'https://github.com/trending'})
step 2: get_text({'selector': 'article.Box-row h2 a'})

Answer from accounts/fireworks/models/glm-5p3-flash
["elementalsouls / Claude-BugHunter", "obra / superpowers", "HKUDS / CLI-Anything", "jingyaogong / minimind", "cursor / plugins"]
Session ended.
```

The whole run takes about 10 seconds. You'll get a different session ID, and the repositories will change as Trending updates. This output is from the Python script. The TypeScript script prints the tool arguments as JSON, for example `goto({"url":"https://github.com/trending"})`.

This is the page the model was reading in the Anchor session:

![The GitHub Trending page open in an Anchor cloud browser session, with the repositories list that the Fireworks model read.](https://mintcdn.com/anchor-b3ec2715/z6j4C99gvTLi2iPC/images/fireworks/github-trending-session.jpg?fit=max\&auto=format\&n=z6j4C99gvTLi2iPC\&q=85\&s=3427046f5ed7417846e3b57e3cb22b23)

## Use Fireworks with Anchor's built-in agent (BYOK)

If you'd rather not write the agent loop yourself, Anchor's `perform-web-task` agent can run on your Fireworks key through [Bring Your Own Keys](https://docs.anchorbrowser.io/advanced/bring-your-own-key.md).

1. In the Anchor dashboard, open **Project Settings**, scroll to **BYOK** and click **Add Key**.
2. Pick **Custom / OpenAI-compatible**, name the key `fireworks`, paste your Fireworks API key and set the base URL to `https://api.fireworks.ai/inference/v1`.
3. Click **Verify & Save**. Anchor makes a live test call before it stores the key.

Then pass the key name and a Fireworks model on the request:

```python byok_web_task.py theme={null}
import os

import httpx

# The key name you gave your Fireworks key under Project Settings > BYOK.
KEY_SLUG = os.getenv("ANCHOR_FIREWORKS_KEY_SLUG", "fireworks")
MODEL = os.getenv("FIREWORKS_MODEL", "accounts/fireworks/models/glm-5p3-flash")

anchor = httpx.Client(
    base_url="https://api.anchorbrowser.io/v1",
    headers={"anchor-api-key": os.environ["ANCHORBROWSER_API_KEY"]},
    timeout=300,
)

response = anchor.post(
    "/tools/perform-web-task",
    json={
        "prompt": "Return the top 5 trending repositories as a JSON list of strings.",
        "url": "https://github.com/trending",
        "key_slug": KEY_SLUG,
        "provider": "custom",
        "model": MODEL,
    },
)
response.raise_for_status()
task = response.json()

try:
    print("Status:", task.get("status"), "in", task.get("steps"), "steps,", task.get("executionTimeMs"), "ms")
    print("Model:", (task.get("agents") or [{}])[0].get("model"))
    print("Result:", task.get("result"))
finally:
    # The task leaves its browser session running, so end it here.
    if task.get("sessionId"):
        anchor.delete(f"/sessions/{task['sessionId']}")
        print("Session ended.")
```

`provider` is optional. If you send it, it has to be `custom` to match the stored key, otherwise Anchor rejects the request. The current SDKs don't have a `key_slug` parameter yet, so this example calls the REST API directly.

The task leaves its browser session running when it finishes, so the example ends it using the `sessionId` from the response.

Expected output:

```text theme={null}
Status: success in 2 steps, 15900 ms
Model: accounts/fireworks/models/glm-5p3-flash
Result: ["elementalsouls/Claude-BugHunter", "obra/superpowers", "HKUDS/CLI-Anything", "jingyaogong/minimind", "cursor/plugins"]
Session ended.
```

LLM calls for this task go straight to Fireworks on your key. Anchor bills browser usage plus a flat [per-step fee for BYOK](https://docs.anchorbrowser.io/pricing.md#ai-pricing). We've run this with `glm-5p3-flash`, `deepseek-v4p1-flash-1017` and `minimax-m3`.

Token usage for each model shows up in Fireworks under **Analytics**, on the **Serverless** tab.

![The Serverless Usage chart in Fireworks Analytics for Nov 30, with a tooltip that lists tokens used by glm-5p3-flash, kimi-k3p1-pro, deepseek-v4p1-flash-1017 and minimax-m3.](https://mintcdn.com/anchor-b3ec2715/z6j4C99gvTLi2iPC/images/fireworks/fireworks-usage-by-model.png?fit=max\&auto=format\&n=z6j4C99gvTLi2iPC\&q=85\&s=f2c11bc8dfb1070cabf75b7d893f6c95)

## Next steps

* Add [proxies](https://docs.anchorbrowser.io/advanced/proxy.md) or [captcha solving](https://docs.anchorbrowser.io/advanced/captcha-solving.md) for sites that block automated browsers
* Sign your agent into web apps with [Managed Authentication](https://docs.anchorbrowser.io/essentials/managed-authentication.md)
* Watch or debug runs with [session recordings](https://docs.anchorbrowser.io/essentials/recording.md) and live view
* Browse the [Fireworks model library](https://app.fireworks.ai/models?utm_source=anchor) for other models with function calling


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.