# Vercel AI SDK

Install Brizz alongside the Vercel AI SDK and tag sessions.

Quickstart for the Vercel AI SDK integration shown during onboarding. For the full TypeScript SDK reference, see the [TypeScript SDK guide](/docs/sdks/typescript.md).

## Setup

Pick the tab for the `ai` version your app uses (`npm ls ai`). Either way you pass the modules
you import to Brizz, then call the AI SDK as usual.

:::tabs
:::tab[ai@7 (recommended)]
Install the SDK and `@ai-sdk/otel`. On v7 the AI SDK reports its calls through that package,
so without it your calls produce no spans.

```bash
npm install @brizz/sdk @ai-sdk/otel
```

Pass `ai` and `@ai-sdk/otel` to `instrumentModules`. Brizz registers its collector before
`Brizz.initialize()` returns, so your first call is traced, in scripts, serverless functions
and bundled ESM too. Telemetry is on by default, so calls need no extra flag.

```typescript
import { Brizz, withSessionId } from '@brizz/sdk';
import * as ai from 'ai';
import * as aiOtel from '@ai-sdk/otel';
import { openai } from '@ai-sdk/openai';

Brizz.initialize({
  apiKey: 'your-brizzai-api-key',
  appName: 'my-app',
  instrumentModules: { ai, aiOtel },
});

async function chat(userMessage: string) {
  return await ai.generateText({
    model: openai('gpt-4o-mini'),
    prompt: userMessage,
  });
}

const sessionedChat = withSessionId('conversation-123', chat);
await sessionedChat('Hello!');
```
:::tab[ai@6 and earlier]
Install the SDK. `@ai-sdk/otel` isn't needed.

```bash
npm install @brizz/sdk
```

Pass `ai` to `instrumentModules`. Telemetry is off by default on these versions, so every
`generateText`, `streamText`, `generateObject`, `streamObject` and `embed` call must set
`experimental_telemetry: { isEnabled: true }`; a call without it produces no spans.

```typescript
import { Brizz, withSessionId } from '@brizz/sdk';
import * as ai from 'ai';
import { openai } from '@ai-sdk/openai';

Brizz.initialize({
  apiKey: 'your-brizzai-api-key',
  appName: 'my-app',
  instrumentModules: { ai },
});

async function chat(userMessage: string) {
  return await ai.generateText({
    model: openai('gpt-4o-mini'),
    prompt: userMessage,
    experimental_telemetry: { isEnabled: true }, // required on ai@6 and earlier
  });
}

const sessionedChat = withSessionId('conversation-123', chat);
await sessionedChat('Hello!');
```
:::

:::info Without instrumentModules
`Brizz.initialize({ apiKey, appName })` alone also works: Brizz loads the installed `ai` and
`@ai-sdk/otel` in the background. A call that starts before that finishes is not traced, so
pass the modules when your app makes AI SDK calls right after start-up.
:::

### Already registering your own `@ai-sdk/otel` collector?

If your app calls `ai.registerTelemetry(new OpenTelemetry())` itself and those spans already
reach Brizz, turn Brizz's collector off so each call is traced once:

```typescript
import { Brizz } from '@brizz/sdk';
import * as ai from 'ai';
import * as aiOtel from '@ai-sdk/otel';

Brizz.initialize({
  apiKey: 'your-brizzai-api-key',
  appName: 'my-app',
  instrumentModules: { ai },
  disableAiSdkCollector: true,
});
ai.registerTelemetry(new aiOtel.OpenTelemetry()); // after Brizz.initialize()
```

## Human-in-the-loop tool approvals

Vercel AI SDK 6 and 7 support tools that pause for human approval before executing. Add `needsApproval: true` to a `tool()` definition, then resume the run with a `tool-approval-response`. Brizz captures the approval request and the user's verdict, and renders them in the conversation view as an interrupt item next to the user response — once as **approved**, again as **denied** if the user rejected.

```typescript
import { generateText, stepCountIs, tool } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
import { startSession } from '@brizz/sdk';

const askUserQuestions = tool({
  description: 'Confirm a change with the user before applying it.',
  inputSchema: z.object({ question: z.string() }),
  needsApproval: true,
  // Runs only after the user approves; the "work" is the question itself.
  execute: async () => ({}),
});

await startSession('approval-demo', async () => {
  const turn1 = await generateText({
    model: openai('gpt-4o-mini'),
    tools: { ask_user_questions: askUserQuestions },
    prompt: 'Apply the mapping change. Use ask_user_questions to confirm first.',
    stopWhen: stepCountIs(1),
    experimental_telemetry: { isEnabled: true },
  });

  // Find the approval request the model produced.
  const approvalReq = turn1.content.find((p: any) => p.type === 'tool-approval-request');

  // In a real app, the user's verdict comes from your UI. Feed it back in:
  const turn2 = await generateText({
    model: openai('gpt-4o-mini'),
    tools: { ask_user_questions: askUserQuestions },
    messages: [
      { role: 'user', content: 'Apply the mapping change.' },
      ...turn1.response.messages,
      {
        role: 'tool',
        content: [{
          type: 'tool-approval-response',
          approvalId: (approvalReq as any).approvalId,
          approved: true,
        }],
      },
    ],
    stopWhen: stepCountIs(2),
    experimental_telemetry: { isEnabled: true },
  });
});
```

A full runnable version lives at `apps/sdk/typescript/examples/vercel-ai-hitl.ts`.

## Subagents

When a tool's `execute` runs another agent, wrap that call in `startAgent` so the subagent's work shows as its own lane in the conversation instead of mixing into the main transcript.

```typescript
import { generateText, tool } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
import { startAgent } from '@brizz/sdk';

const research = tool({
  description: 'Research a topic in depth.',
  inputSchema: z.object({ topic: z.string() }),
  execute: async ({ topic }) =>
    startAgent('research', () =>
      generateText({
        model: openai('gpt-4o-mini'),
        prompt: `Research ${topic} and summarize the findings.`,
        experimental_telemetry: { isEnabled: true },
      }),
    ),
});
```

When the tool's `execute` *is* the subagent, `withAgent` says so once instead of wrapping the body:

```typescript
import { withAgent } from '@brizz/sdk';

const research = tool({
  description: 'Research a topic in depth.',
  inputSchema: z.object({ topic: z.string() }),
  execute: withAgent('research', async ({ topic }) => generateText({ ... })),
});
```

Two calls to the same tool are two separate lanes, and a subagent that starts one of its own nests. In a route or job handler that has no block worth wrapping, `setAgent(...)` marks everything after it. See [Subagents](/docs/instrument/subagents.md) for the full picture, including subagents that run somewhere else.

## Complete example

A single file you can copy, set `BRIZZ_API_KEY` + `OPENAI_API_KEY`, and run with `node chat.mjs`.

```typescript
// chat.ts — ai@7 with @ai-sdk/otel installed
import { Brizz, withSessionId, withProperties, emitEvent } from '@brizz/sdk';
import * as ai from 'ai';
import * as aiOtel from '@ai-sdk/otel';
import { openai } from '@ai-sdk/openai';

Brizz.initialize({
  apiKey: process.env.BRIZZ_API_KEY!,
  appName: 'my-app',
  environment: process.env.NODE_ENV ?? 'development',
  instrumentModules: { ai, aiOtel }, // on ai@6 and earlier: { ai }
});

// On ai@6 and earlier, also pass experimental_telemetry: { isEnabled: true }
// on every call, or it emits no spans.
async function chat(userMessage: string) {
  const result = await ai.generateText({
    model: openai('gpt-4o-mini'),
    prompt: userMessage,
  });
  // User feedback — map "feedback.positive" / "feedback.negative" to system
  // events in Org Settings -> Event so it powers filters and the Overview chart.
  emitEvent(
    'feedback.positive',
    { category: 'helpfulness' },
    { comment: 'Exactly what I needed!', context: 'support-agent' },
  );
  return result.text;
}

const sessioned = withProperties(
  { userId: 'user-42' },
  withSessionId('conversation-123', chat),
);

console.log(await sessioned('Hello!'));

// Streaming works the same way — on ai@6, flip experimental_telemetry on streamText too:
// const stream = ai.streamText({ model: openai('gpt-4o-mini'), prompt: '...',
//   experimental_telemetry: { isEnabled: true } });
```

**Gotchas**

- Calls not showing up? On `ai@7`, check that `@ai-sdk/otel` is installed and passed as `aiOtel` in `instrumentModules`. On `ai@6` and earlier, check that `generateText`, `streamText`, `generateObject`, `streamObject`, and `embed` each pass `experimental_telemetry: { isEnabled: true }`.
- First call after start-up missing? Pass `instrumentModules` (see [Setup](#setup)); without it Brizz registers in the background and an early call can start before that finishes.
- Calls traced twice? Your app registers its own `@ai-sdk/otel` collector; set `disableAiSdkCollector: true`.
- On `ai@6` and earlier, `experimental_telemetry.metadata` lands on the span as attributes — usable for dashboard filters and `beforeSendSpan`.

## See also

- [Node.js / TypeScript SDK](/docs/sdks/typescript.md) — full SDK reference.
- [Sessions](/docs/instrument/sessions.md) — session capture patterns.
- [Custom events](/docs/instrument/custom-events.md) — emit business events from `generateText` / `streamText` flows.
- [Subagents](/docs/instrument/subagents.md) — give a delegated agent its own lane in the conversation.
- [Troubleshooting](/docs/help/troubleshooting.md) — common issue: AI SDK calls not showing up.

---

[All Brizz documentation](https://docs.brizz.ai/llms.txt) · [Full documentation (single file)](https://docs.brizz.ai/llms-full.txt)
