---
title: "How to add agent analytics to your app with v0"
description: "Instrument a v0 report assistant with the Node AI SDK, metadata-only telemetry, isolated task IDs, and verified event grouping."
canonical: "https://amplitude.com/build/v0-agent-analytics"
---

# How to add agent analytics to your app with v0

Instrument a v0 report assistant with the Node AI SDK, metadata-only telemetry, isolated task IDs, and verified event grouping.

Source: https://amplitude.com/build/v0-agent-analytics

---

# How to add agent analytics to your app with v0

Use v0 to instrument a Node.js report assistant with the Amplitude AI SDK. Record one synthetic task with metadata-only telemetry, flush it before exit, and check the processed session in Amplitude.

- v0
- Node.js
- AI SDK 0.24.2
- 30 min

Chris Tam · Last updated 11 November 2026

v0 can build the server code behind a report assistant and run checks in its Terminal. Amplitude [agent analytics](https://amplitude.com/agent-analytics) shows the assistant's requests, responses and usage together as a task.

In this tutorial, you'll give v0 an implementation prompt, inspect the provider wrapper, run a synthetic report-summary job, and verify the resulting session. The instrumentation belongs to your app's assistant; it does not collect v0's coding conversation.

A Node.js report-summary job with a synthetic user, a unique task ID, automatic provider instrumentation, metadata-only telemetry and a flush after the job closes. The model provider still receives the question and report needed to answer it.

## Prerequisites

- A v0 chat you can edit with a Node.js workspace and Terminal access. Check the selected model and remaining allowance before generating changes.
- A development Amplitude project with agent analytics access, its client ingestion API key from Settings > Projects > your project > General, and its US or EU data center.
- Node.js 22.12 or later, Corepack and pnpm 10.33.2. The reference pins @amplitude/ai 0.24.2, @amplitude/analytics-node 1.5.81 and openai 6.49.0.
- Your own OpenAI API key and a chat-completions model available to that account. A live model call can incur provider charges. The local tests use controlled replies and require neither key.

[Sign up for Amplitude](https://app.amplitude.com/signup) and [compare plans](https://amplitude.com/pricing) for your project's allowances. Use synthetic data and a separate development project.

## 1. Identify the task and its runtime

Start with the Node process that calls the model. This reference is a standalone job with terminal output. In an existing v0 web app, keep its framework and authenticated backend; use a separate example directory to run the reference without replacing the app's package manifest.

v0 planning prompt

```text
Planning only. Inspect this v0 project's actual runtime, model client, assistant request boundary, authentication, consent and existing analytics. Identify one task's genuine start and finish. Plan an isolated Node reference job and tests without replacing the existing app. Keep provider credentials server-only. Show the files and checks, then stop before implementation.
```

The [AI SDK instrumentation guide](https://amplitude.com/docs/amplitude-ai/agent-analytics/instrument-ai-sdk) supplies the integration. [v0's workspace guide](https://v0.app/docs/sandbox) describes its Node environment and Terminal. This example needs no Preview page or web port.

For a Next.js app, keep the AI SDK in a server-side module and use the Node runtime. The [AI SDK framework notes](https://amplitude.com/docs/sdks/agent-analytics/sdk#framework-notes) describe `serverExternalPackages` and request-scoped sessions. The job below is not a replacement for your app's authenticated web route.

**MCP.** A connected Amplitude agent can help inspect project context through the [MCP server](https://amplitude.com/docs/amplitude-ai/amplitude-mcp). That optional account connection is separate from the application's ingestion key.

## 2. Give Agent the implementation prompt

Use v0's planning instruction first, review the proposed changes, then ask it to implement. The request below keeps the telemetry on the app's model call and makes privacy and lifecycle decisions explicit.

v0 implementation prompt

```text
Planning only: inspect and read the sources, then show the proposed files and tests. Do not modify files yet; stop and wait for my approval to implement.

Instrument this v0 app's Node report-summary assistant using @amplitude/ai. Read https://amplitude.com/docs/amplitude-ai/agent-analytics/instrument-ai-sdk and https://amplitude.com/docs/sdks/agent-analytics/sdk, plus the official provider guide at https://github.com/amplitude/Amplitude-AI-Node/blob/main/amplitude-ai.md. Report the sources. Read the complete reference at https://github.com/amplitude/ampli-examples/tree/ffac5f46bc32da3e3da20474708d974c70cd0eaa/node/replit-agent-analytics and its sibling source files. Use the complete files in this tutorial as the isolated reference; preserve the existing framework and backend when merging.

Use the existing analytics/model client where present. For this standalone reference, initialize @amplitude/analytics-node once with the project ingestion key and correct serverZone, then pass that instance to AmplitudeAI. Use AIConfig with contentMode metadata_only, redactPii true and debug false. Wrap the OpenAI client through @amplitude/ai. The wrapper automatically tracks the input and response: do not also call trackUserMessage or manually emit AI Response for that call. Capture real usage from the provider; do not invent tokens, cost, tools or success.

Create a named v0-report-assistant agent. Generate one unique task ID per report-summary job; keep the same confirmed user ID throughout it. Use session.run for this single scoped job, and await ai.flush after it closes, including failure. This CLI reference ends a task after one answer; do not use its per-run UUID policy for every request in an ongoing conversation. In a real conversation, retain its task ID across turns and close it only at the actual end.

Read all configuration from the environment. Keep OPENAI_API_KEY in ignored local backend environment configuration for this reference. Never put it in VITE_, NEXT_PUBLIC_, project instructions, committed files, logs or browser bundles. Before using a connected hosted environment, review who can read its values, including the coding agent. Guard missing keys, model, user and invalid region before initializing or making requests. Use synthetic demo identity only in the isolated example; derive production identity from confirmed authentication. Respect consent before sending telemetry. Keep message text out of Amplitude telemetry and logs. The model provider still needs the prompt. Preserve existing routes, authentication, consent and enabled products.

Run local tests with a controlled provider transport and an in-memory analytics sink; no keys, paid inference or event uploads. Check one user message and response per call, metadata privacy, isolated concurrent tasks, task closure, awaited flush, failure, and the blank configuration guard. Report local results separately from native v0 and processed Amplitude checks. If sources conflict, record both statements and pause that claim until resolved by current SDK evidence or its owner.

Use an isolated example directory if this is an existing Next.js project. Keep the Node-only SDK out of client components and edge execution. For an existing Next.js Node route, preserve authentication and use the SDK's documented serverExternalPackages configuration. Do not change the app scaffold or expose a public inference endpoint. Use the supplied controlled tests first; do not make a live provider call, upload keys, deploy, publish, connect accounts or purchase credits. Save the reviewed files in a version and inspect its diff.
```

## 3. Review the generated changes

Inspect the backend before configuring a provider key. The wrapper must surround the actual model client, the user must come from confirmed application identity, and the session must cover the real task lifetime.

v0 review prompt

```text
Show every changed file, server-only import and existing integration preserved. Trace identity, task lifetime, model request, metadata_only configuration, error handling and awaited flush. Confirm there is no duplicate manual User Message or AI Response around the wrapped call. Run local checks with controlled replies and no credentials. Inspect the saved version diff and distinguish these results from native v0 execution, live ingestion and processed grouping.
```

Use the Code tab and saved diff to inspect the result. [v0's editor guide](https://v0.app/docs/code-editing) explains how Save persists pending edits; a running workspace alone does not establish a saved version.

For an existing model client with custom transport, the wrapper's `client` option can retain that client. Confirm its supported options rather than assuming every provider constructor setting is forwarded.

## 4. Add the complete reference files

These seven files make a complete standalone Node job. Keep them in a separate directory when extending an existing v0 app. The [Node SDK reference](https://amplitude.com/docs/sdks/analytics/node/node-js-sdk) supplies the regional analytics client; the [AI SDK reference](https://amplitude.com/docs/sdks/agent-analytics/sdk) supplies the wrapper and task scope.

The example pins its SDK versions for repeatable checks. The controlled test uses the installed real wrapper and its in-memory analytics client, so no real keys or provider calls are needed.

package.json

```json
{
  "name": "amplitude-v0-agent-analytics",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
  "engines": {
    "node": ">=22.12.0",
    "pnpm": ">=10.21.0"
  },
  "scripts": {
    "start": "node --env-file-if-exists=.env.local run.js",
    "check": "node --check run.js && node --check report-agent.js",
    "test": "node --test report-agent.test.js"
  },
  "dependencies": {
    "@amplitude/ai": "0.24.2",
    "@amplitude/analytics-node": "1.5.81",
    "openai": "6.49.0"
  }
```

pnpm-workspace.yaml

```yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
```

.gitignore

```text
node_modules/
.env.local
.env
```

.env.example

```sh
AMPLITUDE_AI_API_KEY=
AMPLITUDE_SERVER_ZONE=US
OPENAI_API_KEY=
OPENAI_MODEL=
DEMO_USER_ID=build-v0-agent-demo
```

report-agent.js

```javascript
export function createReportAgent({ ai, openai }) {
  const agent = ai.agent("v0-report-assistant", { description: "Explains a synthetic usage report" });
  return async function explainReport({ taskId, userId, question, model }) {
    if (!taskId || !userId || !question || !model) throw new Error("Task configuration is missing");
    try {
      return await agent.session({ userId, sessionId: taskId }).run(async () => {
        // The provider wrapper records the user message and AI response. Do not also track them manually.
        const result = await openai.chat.completions.create({
          model,
          messages: [
            { role: "system", content: "Explain this synthetic seven-day report: 12 exports and 8 active accounts. Be brief. Do not claim to access real customer records." },
            { role: "user", content: question },
          ],
        });
        const text = result.choices?.[0]?.message?.content;
        if (typeof text !== "string" || !text.trim()) throw new Error("The assistant returned no text");
        return text;
      });
    } finally {
      const pending = ai.flush();
      await (pending?.promise ?? pending);
    }
  };
}
```

run.js

```javascript
import { randomUUID } from "node:crypto";
import * as amplitude from "@amplitude/analytics-node";
import { AmplitudeAI, AIConfig, OpenAI } from "@amplitude/ai";
import { createReportAgent } from "./report-agent.js";

const apiKey = process.env.AMPLITUDE_AI_API_KEY?.trim();
const providerKey = process.env.OPENAI_API_KEY?.trim();
const model = process.env.OPENAI_MODEL?.trim();
const userId = process.env.DEMO_USER_ID?.trim();
const zone = (process.env.AMPLITUDE_SERVER_ZONE || "US").trim();
if (!apiKey || !providerKey || !model || !userId || !["US", "EU"].includes(zone)) {
  console.error("Add the demo configuration and select US or EU. No model request was made.");
  process.exitCode = 1;
} else {
  amplitude.init(apiKey, { serverZone: zone });
  const ai = new AmplitudeAI({ amplitude, config: new AIConfig({ contentMode: "metadata_only", redactPii: true, debug: false }) });
  const openai = new OpenAI({ apiKey: providerKey, amplitude: ai });
  const explainReport = createReportAgent({ ai, openai });
  const taskId = randomUUID();
  try {
    const answer = await explainReport({ taskId, userId, model, question: "Summarize the report and suggest one question to investigate." });
    console.log(answer);
    console.log(`Finished synthetic task ${taskId}. Check the processed session separately.`);
  } catch {
    console.error("The assistant failed. Check provider access and configuration; no reply was confirmed.");
    process.exitCode = 1;
  }
```

report-agent.test.js

```javascript
import test from "node:test";
import assert from "node:assert/strict";
import { AIConfig, OpenAI } from "@amplitude/ai";
import { MockAmplitudeAI } from "@amplitude/ai/testing";
import OpenAIClient from "openai";
import { createReportAgent } from "./report-agent.js";

function setup({ failure=false, empty=false }={}) {
  const ai=new MockAmplitudeAI(new AIConfig({contentMode:"metadata_only",debug:false}));
  const requests=[];
  const client=new OpenAIClient({apiKey:"synthetic-not-a-real-key",maxRetries:0,fetch:async(url,options)=>{
    requests.push(JSON.parse(options.body));
    if(failure) return new Response(JSON.stringify({error:{message:"synthetic-provider-error",type:"server_error"}}),{status:500,headers:{"content-type":"application/json"}});
    return new Response(JSON.stringify({id:"chatcmpl-local-test",object:"chat.completion",created:1,model:"gpt-4o-mini",choices:[{index:0,message:{role:"assistant",content:empty?"":"synthetic reply private@example.com"},finish_reason:"stop"}],usage:{prompt_tokens:11,completion_tokens:7,total_tokens:18}}),{headers:{"content-type":"application/json"}});
  }});
  const openai=new OpenAI({client,amplitude:ai});
  return {ai,openai,requests,run:createReportAgent({ai,openai})};
}
const args={taskId:"synthetic-report-task-1",userId:"build-v0-agent-demo",question:"synthetic private question private@example.com",model:"gpt-4o-mini"};
test("wrapped provider emits one user message and one response, then closes the task",async()=>{
  const {ai,requests,run}=setup();const reply=await run(args);
  assert.match(reply,/synthetic reply/);assert.equal(requests.length,1);
  assert.equal(ai.getEvents("[Agent] User Message").length,1);
  assert.equal(ai.getEvents("[Agent] AI Response").length,1);
  assert.equal(ai.getEvents("[Agent] Session End").length,1);
  assert.equal(ai.getEvents("[Agent] Tool Call").length,0);
  assert.ok(ai.events.every(e=>e.user_id===args.userId&&e.event_properties["[Agent] Session ID"]===args.taskId));
  const p=ai.getEvents("[Agent] AI Response")[0].event_properties;
  assert.equal(p["[Agent] Input Tokens"],11);assert.equal(p["[Agent] Output Tokens"],7);assert.equal(p["[Agent] Provider"],"openai");
  assert.ok(!JSON.stringify(ai.events).includes("private@example.com"));
  for(const event of ai.events) assert.ok(!("$llm_message" in event.event_properties));
});
test("positive control: a manual user message plus the wrapper duplicates the input",async()=>{
  const {ai,openai}=setup();
  await ai.agent("duplication-positive-control").session({userId:args.userId,sessionId:"synthetic-duplicate-task"}).run(async s=>{
    s.trackUserMessage(args.question);
    await openai.chat.completions.create({model:args.model,messages:[{role:"user",content:args.question}]});
  });
  assert.equal(ai.getEvents("[Agent] User Message").length,2);
});
test("concurrent users and tasks keep identity separate",async()=>{
  const {ai,run}=setup();await Promise.all([run(args),run({...args,taskId:"synthetic-other-task",userId:"synthetic-other-user"})]);
  assert.equal(ai.getEvents("[Agent] User Message").length,2);
  for(const e of ai.events) assert.equal(e.user_id,e.event_properties["[Agent] Session ID"]===args.taskId?args.userId:"synthetic-other-user");
  assert.equal(new Set(ai.events.map(e=>e.event_properties["[Agent] Agent ID"])).size,1);
});
test("flush is awaited before returning and also after failure",async()=>{
  const ok=setup();let flushCompleted=false;ok.ai.flush=async()=>{await Promise.resolve();flushCompleted=true};
  await ok.run(args);assert.equal(flushCompleted,true);
  const bad=setup({failure:true});let flushed=false;bad.ai.flush=async()=>{flushed=true};
  await assert.rejects(bad.run(args));assert.equal(flushed,true);assert.equal(bad.ai.getEvents("[Agent] Session End").length,1);
});
test("empty reply is not reported as successful application output",async()=>{
  const {run}=setup({empty:true});await assert.rejects(run(args),/no text/);
});
test("configuration guard prevents provider requests",async()=>{
  const {run,requests}=setup();await assert.rejects(run({...args,userId:""}),/configuration/);assert.equal(requests.length,0);
});
```

Install with the pinned package manager. Keep the generated lockfile or use the matching dependency lock in the public example, then use frozen installs on subsequent checkouts.

Terminal

```sh
corepack pnpm install
corepack pnpm check
corepack pnpm test
```

These tests use a controlled provider transport and an in-memory analytics sink. They do not establish live ingestion or processed task grouping.

## 5. Configure the backend and run one task

Keep the live configuration in an ignored local `.env.local` for this standalone check. Copy `.env.example` and fill in your intended development-project ingestion key, provider key, model, region and synthetic user. Do not paste keys into the v0 conversation or reusable instructions. Before using a connected hosted project's environment, review its access scope, including agent access.

The backend reads `AMPLITUDE_AI_API_KEY`, `OPENAI_API_KEY`, `OPENAI_MODEL`, `AMPLITUDE_SERVER_ZONE` and `DEMO_USER_ID`. Use `US` or `EU` for the region and `build-v0-agent-demo` for the isolated test user. Keep the provider key out of every `VITE_` or `NEXT_PUBLIC_` variable.

Local terminal

```sh
corepack pnpm start
```

With missing configuration, the process stops before a model request. With valid credentials, this command requests one synthetic report summary and prints the answer plus a unique task ID. A live provider request can incur charges; the controlled tests are the key-free check. This job produces terminal output, not a Preview UI. For the request/response shape, see the [OpenAI Chat Completions reference](https://developers.openai.com/api/reference/typescript/resources/chat/subresources/completions/methods/create).

**Why.**` session.run()` closes this one-job scope. Awaiting flush afterward lets buffered telemetry finish before the short-lived process exits, including on failure. An application answer still needs a separate service-side data check.

## Verify it worked

1. Run pnpm check and pnpm test with no real keys. Confirm the controlled wrapper produces one User Message, one AI Response and a Session End for the task, with message content omitted and actual fixture usage preserved.
2. Run pnpm start with blank configuration. Confirm it makes no model request. Then configure only the intended development keys and run one synthetic task, checking provider usage and charges separately.
3. In Amplitude, find build-v0-agent-demo and the printed task ID. Inspect \[Agent] User Message, \[Agent] AI Response and \[Agent] Session End. Check the same user, agent and session identifiers and provider/model/usage metadata. Unknown usage or cost should remain absent rather than fabricated.
4. Confirm prompt and response text are absent from Amplitude event properties under metadata\_only. The answer printed in Terminal is application output; do not copy private answers into telemetry or debug logs.
5. After processing, inspect the agent session. Confirm this job forms one session, closes once and contains its expected exchange. Repeat with another task ID to check separation. Event upload or local tests alone do not prove that processed grouping succeeded.

## Troubleshooting

**The configuration guard stops the job.** Check each required environment value and use US or EU exactly. Restart the process after editing backend configuration. A blank model name intentionally prevents inference.

**The model request fails.** Confirm provider access, key and model availability. The example reports a generic failure without printing credentials or the private prompt. Check the provider dashboard before retrying a billable request.

**Each input appears twice.** Keep the provider wrapper's automatic instrumentation and remove an extra manual User Message for that same input. Manual instrumentation belongs to a call that is not already captured.

**The answer appears but the session is missing.** Confirm the Amplitude project, region, identity, task ID, ingestion result and processing time. Keep the flush after close. For a long-running app, also handle shutdown according to the SDK lifecycle guidance.

**Every turn becomes a separate session.** This example deliberately runs one completed report job. A multi-turn conversation must reuse its session ID across requests and close only when the conversation actually ends.

**Quality signals are absent.** Metadata-only capture omits message content; content-dependent analysis needs an approved content-capture policy. Keep the privacy choice explicit rather than enabling content collection solely to populate a chart.

## FAQ

### Does this track v0 Agent's coding conversation?

This instruments the report assistant inside your application. v0 Agent creates the code; your app's model requests are what the SDK observes.

### Can I put the model key in a public environment variable?

Keep it in backend environment configuration. VITE\_ and NEXT\_PUBLIC\_ values are exposed in the browser bundle. The Node reference needs no public model credential.

### Does metadata-only prevent the provider from seeing my question?

Metadata-only controls Amplitude telemetry. The model provider still receives the prompt and synthetic report so it can produce an answer.

### Do the local tests prove that Amplitude processed the session?

They verify the SDK wrapper, event contract and lifecycle with controlled replies. Run the development-project verification steps to establish ingestion and processed grouping.

## Full code reference

Step 4 contains the complete standalone job, configuration and tests. Keep the lockfile with them. The [public report-agent reference](https://github.com/amplitude/ampli-examples/tree/ffac5f46bc32da3e3da20474708d974c70cd0eaa/node/replit-agent-analytics) provides the same SDK behavior and dependency lock. This article names its agent and synthetic user for the v0 demo.

### Save the project instructions

Add these conventions to [v0 Instructions](https://v0.app/docs/instructions) and apply them to the conversation. Keep existing project guidance and exclude credentials.

v0 reusable instructions

```text
Instrument the application's backend model call, keeping the Node SDK and model key out of browser and edge bundles. Preserve authentication, consent, existing analytics and model transport. Reuse the confirmed user identity and genuine task ID for its full lifetime. The provider wrapper records the message and response; do not emit duplicate manual events for that same call. Keep metadata_only explicit, unknown metrics absent and tools limited to real calls. Close scoped jobs and await flush on success and failure. Use controlled replies for local tests. Record local checks, native execution, ingestion and processed grouping separately. Do not broaden data access or run billable inference without the intended configuration and scope.
```

## What this unlocks

[Agent analytics](https://amplitude.com/agent-analytics) connects model usage and task completion to the same identity used in [product analytics](https://amplitude.com/amplitude-analytics). A report export can then be compared with the assistant task that preceded it, using the application's confirmed identity.

## Next steps

[Foundationv0 analyticsConnect the app's product events and confirmed identity.](https://amplitude.com/build/v0-product-analytics)[ReferenceAgent session lifecycleCheck closure and processing for your task model.](https://amplitude.com/docs/amplitude-ai/agent-analytics/sessions)[WorkflowVerify agent instrumentationInspect the processed session before relying on its charts.](https://amplitude.com/docs/amplitude-ai/agent-analytics/verify)

Reference docs

[AI SDK instrumentation →](https://amplitude.com/docs/amplitude-ai/agent-analytics/instrument-ai-sdk)[AI SDK reference →](https://amplitude.com/docs/sdks/agent-analytics/sdk)[Agent event taxonomy →](https://amplitude.com/docs/amplitude-ai/agent-analytics/taxonomy)[Agent privacy modes →](https://amplitude.com/docs/amplitude-ai/agent-analytics/privacy-modes)[v0 workspace →](https://v0.app/docs/sandbox)[OpenAI Chat Completions →](https://developers.openai.com/api/reference/typescript/resources/chat/subresources/completions/methods/create)

Amplitude is the leading [all-in-one analytics platform](https://amplitude.com/) for building better products. Product and engineering teams use Amplitude to connect [product analytics](https://amplitude.com/amplitude-analytics) and [web analytics](https://amplitude.com/web-analytics) with [session replay](https://amplitude.com/session-replay), [heatmaps](https://amplitude.com/heatmaps), [experimentation](https://amplitude.com/amplitude-experiment), [feature flags](https://amplitude.com/feature-management), and [guides and surveys](https://amplitude.com/guides-and-surveys) in one unified workflow, with [AI agents](https://amplitude.com/ai-agents) working across all of it. Learn how Amplitude is building [self-improving products](https://amplitude.com/self-improving-products) with [Wave](https://amplitude.com/wave), helping teams turn product data into PRs.

For agents

[View raw .md](/build/v0-agent-analytics.md)[llms.txt](/llms.txt)

## Build the report, then check the result

Connect a development project and verify the report action before you roll out the integration.

[Create a free account](https://app.amplitude.com/signup)[Browse all Build tutorials](https://amplitude.com/build)
