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

# Stagehand

> Capture Stagehand act, extract, and observe calls through a traced model callback

## Choose a setup method

| Method | Use it when |
| - | - |
| **Agnost AI skill** | You want your coding agent to inspect the app, make the change, and verify it. |
| **Agnost AI SDK** | You want explicit control over the interaction boundaries and fields. |
| **OpenTelemetry** | The framework already emits useful spans or you operate an OTel pipeline. |

Start with one method for a call path. Combining SDK tracking with framework
OpenTelemetry on the same call can create duplicate interactions.

## Recommended: Agnost AI skill

> [!NOTE]
>
> **Recommended.** Choose this path when you want your coding agent to inspect the
> project, select a supported transport, make the smallest instrumentation change,
> send a test event, and verify that it reached Agnost AI.

Install the skill once in your coding-agent environment:

```bash theme={null}
npx skills add AgnostAI/skills --skill agnost-ai
```

Run the framework-specific prompt below from the application root. Review the
resulting diff before deploying it.

```text theme={null}
Use the agnost-ai skill to add Agnost AI analytics to this Stagehand application.
Org ID: your-org-id
Instrument the real stagehand.act(), extract(), or observe() path and verify one fresh interaction.
```

## Manual setup: Agnost AI SDK

```bash theme={null}
npm install agnostai
```

```typescript theme={null}
import * as agnost from 'agnostai';
import { z } from 'zod/v4';

agnost.init('your-org-id');
const instruction = 'extract the page heading';
const interaction = agnost.begin({
  userId: 'u-42',
  agentName: 'stagehand-extract',
  input: instruction,
  conversationId: 'conv-abc123',
});
if (!interaction) throw new Error('Agnost is not initialized. Call agnost.init() first.');
try {
  const { data } = await stagehand.extract(instruction, z.object({ heading: z.string() }));
  interaction.end(JSON.stringify(data));
} catch (error) {
  interaction.end(String(error), false);
  throw error;
}
```

Wrap each `act`, `extract`, or `observe` call that you want to see as one interaction.
Call `await agnost.shutdown()` once when the application exits, not after each request.

## Manual setup: OpenTelemetry

Stagehand v4 can export its own traces with the `telemetry.traces` option, but those spans
carry only `stagehand.*` operation and log attributes: no prompts, no model output, and no
user or session. Agnost AI does not ingest them. Instead, route Stagehand's model calls
through a [bring-your-own-LLM callback](https://docs.stagehand.dev/v4/configuration/models)
that calls the Vercel AI SDK with telemetry on. Every inference Stagehand makes for `act`,
`extract`, and `observe` then arrives as GenAI spans with the full prompt and answer.

### Install

```bash theme={null}
npm install @browserbasehq/stagehand ai @ai-sdk/anthropic @ai-sdk/otel \
  @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-proto
```

Use `@ai-sdk/openai` or another AI SDK provider in place of `@ai-sdk/anthropic` if you prefer.

### Setup

**1. Register the exporter once at startup**

```typescript theme={null}
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { registerTelemetry } from 'ai';
import { OpenTelemetry } from '@ai-sdk/otel';

const sdk = new NodeSDK({
  traceExporter: new OTLPTraceExporter({
    url: 'https://otel.agnost.ai/v1/traces',
    headers: { 'X-Agnost-Org-ID': process.env.AGNOST_ORG_ID! },
  }),
});
sdk.start();
registerTelemetry(new OpenTelemetry({ runtimeContext: true }));
```

**2. Write a traced generate callback**

```typescript theme={null}
import { generateText, jsonSchema, Output, type LanguageModel, type ModelMessage } from 'ai';

type Block = { type: string; text?: string; data?: string; mimeType?: string };
type StagehandParams = {
  messages: Array<{ role: 'user' | 'assistant'; content: Block | Block[] }>;
  systemPrompt?: string;
  temperature?: number;
  responseFormat?: { type: 'text' } | { type: 'json_schema'; name: string; schema: unknown };
};

function toMessage(m: StagehandParams['messages'][number]): ModelMessage {
  const blocks = Array.isArray(m.content) ? m.content : [m.content];
  if (m.role === 'assistant') {
    return { role: 'assistant', content: blocks.map((b) => b.text ?? '').join('') };
  }
  return {
    role: 'user',
    content: blocks.map((b) =>
      b.type === 'image'
        ? { type: 'image' as const, image: b.data!, mediaType: b.mimeType }
        : { type: 'text' as const, text: b.text ?? '' },
    ),
  };
}

export function tracedGenerate(opts: { model: LanguageModel; userId: string; sessionId: string }) {
  return async (params: StagehandParams) => {
    if (params.responseFormat?.type !== 'json_schema') {
      throw new TypeError('Stagehand only issues structured generations');
    }
    const { output, text, usage } = await generateText({
      model: opts.model,
      system: params.systemPrompt,
      temperature: params.temperature,
      messages: params.messages.map(toMessage),
      output: Output.object({ schema: jsonSchema<Record<string, any>>(params.responseFormat.schema as any) }),
      runtimeContext: { userId: opts.userId, sessionId: opts.sessionId },
      telemetry: {
        isEnabled: true,
        functionId: 'stagehand',
        includeRuntimeContext: { userId: true, sessionId: true },
      },
    });
    return {
      role: 'assistant' as const,
      content: { type: 'text' as const, text },
      outputFormat: 'json_schema' as const,
      structuredContent: output,
      usage: {
        inputTokens: usage.inputTokens ?? 0,
        outputTokens: usage.outputTokens ?? 0,
        totalTokens: usage.totalTokens ?? 0,
      },
    };
  };
}
```

**3. Create one Stagehand instance per user session**

```typescript theme={null}
import { localBrowser, Stagehand } from '@browserbasehq/stagehand';
import { anthropic } from '@ai-sdk/anthropic';
import { z } from 'zod/v4';

const browser = await localBrowser.launch();
const stagehand = await Stagehand.create({
  browser,
  model: {
    generate: tracedGenerate({
      model: anthropic('claude-haiku-4-5'),
      userId: 'u-42',
      sessionId: 'conv-abc123',
    }),
  },
});

const [page] = await browser.context.pages();
await page.goto('https://example.com');
const { data } = await stagehand.extract('extract the page heading', z.object({ heading: z.string() }));

await stagehand.close();
await browser.close();
```

The callback runs in your process, so it works the same with `browserbase.launch()` in
place of `localBrowser.launch()`. Model Gateway is bypassed: the callback calls your provider
with your own key.

### What appears in Agnost AI

* **Conversations** grouped by `sessionId`.
* **User-level analytics** grouped by `userId`.
* **Events** named `stagehand` (one per model call), with `agent_step` and `chat` children.
  The input is Stagehand's instruction plus the page snapshot; the output is the JSON the
  model returned. `extract` makes a second call that checks whether the extraction finished.

### Verify

Run one `extract` call, then open **Events** in Agnost AI. Confirm a `stagehand` event with
the instruction as input and the extracted JSON as output, and that the conversation shows
your `sessionId` and `userId`.

### Troubleshooting

* No events: confirm `registerTelemetry(...)` runs before `Stagehand.create()` and that the
  exporter has `X-Agnost-Org-ID`. Call `await sdk.shutdown()` before a short script exits.
* `model` with a `modelName` (for example `anthropic/claude-sonnet-5`) runs the model inside
  Stagehand's runtime, where your telemetry cannot reach it. Use the `generate` callback.
* Do not point `telemetry.traces` at Agnost AI. Those spans have no GenAI attributes and are
  dropped.
* Events split across conversations: create the callback with the right `sessionId` for
  each user session.

### References

* [Stagehand bring your own LLM](https://docs.stagehand.dev/v4/configuration/models)
* [Stagehand observability](https://docs.stagehand.dev/v4/configuration/observability)
* [Vercel AI SDK telemetry](https://ai-sdk.dev/docs/ai-sdk-core/telemetry)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review the complete Stagehand session.
* [Events](https://docs.agnost.ai/using-events.md): inspect each model call Stagehand made.
* [Patterns](https://docs.agnost.ai/using-patterns.md): organize production conversations by what users wanted.


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