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

# Quickstart - Humans

> Pull live LLM prices over REST or MCP, then wrap Vercel AI SDK calls with Narev middleware and send dollar usage to Polar or Stripe.

We'll go here in two steps: first pull live prices over REST or MCP, then wrap Vercel AI SDK calls with Narev middleware and send dollar usage to Polar.

## Part 1: Pull live prices

### REST API

<Tabs>
  <Tab title="List prices">
    Pull current rates for a provider.

    <CodeGroup>
      ```bash Request theme={null}
      curl -G 'https://api.narev.ai/v1/prices' \
        --data-urlencode 'provider_id=openai' \
        --data-urlencode 'model_id=gpt-4o'
      ```

      ```json Response theme={null}
      {
        "data": [
          {
            "model_id": "gpt-4o",
            "provider_id": "openai",
            "pricing": {
              "prompt": 0.0000025,
              "completion": 0.00001
            }
          }
        ],
        "meta": {
          "page": 1,
          "page_size": 100,
          "total": 1,
          "total_pages": 1
        }
      }
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Calculate cost">
    Send token counts. Get a dollar total for that call.

    <CodeGroup>
      ```bash Request theme={null}
      curl -X POST 'https://api.narev.ai/v1/traces/cost' \
        -H 'Content-Type: application/json' \
        -d '{
          "model_id": "gpt-4o",
          "provider_id": "openai",
          "usage": {
            "prompt_tokens": 1000,
            "completion_tokens": 500
          }
        }'
      ```

      ```json Response theme={null}
      {
        "model_id": "gpt-4o",
        "provider_id": "openai",
        "cost_breakdown": {
          "total": 0.0075
        }
      }
      ```
    </CodeGroup>
  </Tab>
</Tabs>

### MCP

Same catalog, over Model Context Protocol. No API key. Server URL: `https://mcp.narev.ai`

<CardGroup cols={2}>
  <Card title="Install in Cursor" icon="arrow-up-right" href="cursor://anysphere.cursor-deeplink/mcp/install?name=narev&config=eyJ1cmwiOiJodHRwczovL21jcC5uYXJldi5haS8ifQ==">
    Opens Cursor and prompts to add the Narev MCP server.
  </Card>

  <Card title="Install in VS Code" icon="arrow-up-right" href="vscode:mcp/install?%7B%22name%22%3A%22narev%22%2C%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fmcp.narev.ai%2F%22%7D">
    Opens VS Code and prompts to add the Narev MCP server.
  </Card>
</CardGroup>

Agents can call `list_providers`, `list_models`, `get_prices`, and `calculate_cost`, plus docs search tools.

## Part 2: Implement usage-based billing with Vercel AI SDK and Polar

We'll bootstrap a small app here in Next.js that charges users for LLM usage.

* We'll use Vercel AI SDK to call the model
* We'll use middleware to resolve the cost of the call and send the usage to Polar
* We'll use Next.js UI components to show the usage and let users buy credits

<Info>
  This guide uses Polar for a short setup path. The same middleware pattern works with Stripe, OpenMeter, Lago, and other supported destinations.
</Info>

<Steps>
  <Step title="Get your API keys">
    You need a Narev Cloud key for price resolution, plus credentials for your billing destination.

    1. Create a free [Narev Cloud](https://www.narev.ai/login) account.
    2. Open **Settings → API Keys** and create a `NAREV_API_KEY`.
    3. Create a [Polar sandbox](https://polar.sh/docs/integrate/sandbox#sandbox-environment) and [generate a `POLAR_ACCESS_TOKEN`](https://polar.sh/docs/integrate/oat).

    ```bash .env.local theme={null}
    NAREV_API_KEY=your_narev_api_key_here
    POLAR_ACCESS_TOKEN=your_polar_access_token_here
    POLAR_SERVER=sandbox
    ```
  </Step>

  <Step title="Install the packages">
    Install the provider middleware, Polar destination, Next.js UI components, and the Vercel AI SDK packages you call.

    <CodeGroup>
      ```bash npm theme={null}
      npm install @ai-billing/core @ai-billing/openai @ai-billing/polar @ai-billing/nextjs ai @ai-sdk/openai
      ```

      ```bash pnpm theme={null}
      pnpm add @ai-billing/core @ai-billing/openai @ai-billing/polar @ai-billing/nextjs ai @ai-sdk/openai
      ```

      ```bash yarn theme={null}
      yarn add @ai-billing/core @ai-billing/openai @ai-billing/polar @ai-billing/nextjs ai @ai-sdk/openai
      ```

      ```bash bun theme={null}
      bun add @ai-billing/core @ai-billing/openai @ai-billing/polar @ai-billing/nextjs ai @ai-sdk/openai
      ```
    </CodeGroup>
  </Step>

  <Step title="Configure your billing destination">
    Create `lib/destinations.ts`. Set `externalCustomerIdKey` to the Customer Tagging field Polar should treat as the customer id.

    <Tabs>
      <Tab title="Next.js" icon="triangle">
        ```typescript lib/destinations.ts theme={null}
        import { createPolarDestination } from '@ai-billing/polar';

        export function getBillingDestinations() {
          const accessToken = process.env.POLAR_ACCESS_TOKEN;

          if (!accessToken) return [];

          return [
            createPolarDestination({
              accessToken,
              server: process.env.POLAR_SERVER === 'production' ? 'production' : 'sandbox',
              eventName: 'llm_usage',
              externalCustomerIdKey: 'userId',
            }),
          ];
        }
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Wrap the model with billing middleware">
    Attach Narev middleware with `wrapLanguageModel`. Each generation resolves token cost from the live catalog and forwards usage to your destination.

    <Tabs>
      <Tab title="Next.js" icon="triangle">
        ```typescript lib/billing.ts theme={null}
        import { wrapLanguageModel } from 'ai';
        import { openai } from '@ai-sdk/openai';
        import { createOpenAIV3Middleware } from '@ai-billing/openai';
        import { getBillingDestinations } from './destinations';

        const billingMiddleware = createOpenAIV3Middleware({
          destinations: getBillingDestinations()
        });

        // Wrap your model so every generation is metered
        export const billedModel = wrapLanguageModel({
          model: openai('gpt-4o'),
          middleware: billingMiddleware
        });
        ```
      </Tab>
    </Tabs>

    <Tip>
      Keep model creation in one helper so every route uses the metered instance.
    </Tip>
  </Step>

  <Step title="Call the model from an API route">
    Pass the wrapped model into `streamText`. Put Customer Tagging metadata in `providerOptions` so Polar knows which customer to charge.

    <Tabs>
      <Tab title="Next.js" icon="triangle">
        ```typescript app/api/chat/route.ts theme={null}
        import { streamText } from 'ai';
        import { billedModel } from '@/lib/billing';

        export async function POST(req: Request) {
          const { messages } = await req.json();

          // Replace with the authenticated user id from your auth layer
          const userId = 'user_123';

          const result = streamText({
            model: billedModel,
            messages,
            providerOptions: {
              'ai-billing-tags': {
                userId: userId,
                feature: 'chat-interface'
              },
            },
          });

          return result.toDataStreamResponse();
        }
        ```
      </Tab>
    </Tabs>

    <Warning>
      Confirm `userId` maps to the customer record in Polar. Stay on sandbox until the mapping looks right.
    </Warning>
  </Step>

  <Step title="Add billing UI components">
    Use `@ai-billing/nextjs` to show usage and let users buy credits.

    <Tabs>
      <Tab title="Next.js" icon="triangle">
        ```tsx app/components/usage-dashboard.tsx theme={null}
        import { CreditUsagePolar, CreditTopUpPolar } from '@ai-billing/nextjs';

        export default function BillingDashboard({ userId }: { userId: string }) {
          return (
            <div className="flex flex-col gap-6 p-6 bg-white dark:bg-zinc-950 rounded-xl border border-zinc-200 dark:border-zinc-800">
              <h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100">
                Usage and billing
              </h2>

              <div className="p-4 bg-zinc-50 dark:bg-zinc-900 rounded-lg">
                <CreditUsagePolar userId={userId} />
              </div>

              <div className="p-4 bg-zinc-50 dark:bg-zinc-900 rounded-lg">
                <CreditTopUpPolar userId={userId} />
              </div>
            </div>
          );
        }
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Verify billing works">
    Run a chat request, then check Polar for an `llm_usage` event tied to your sandbox customer. The UI should show usage for that `userId`.

    <Frame caption="Usage component showing current consumption">
      <img src="https://mintcdn.com/narev/vk3N1vAMCBfZgm44/images/intro-billing-usage.png?fit=max&auto=format&n=vk3N1vAMCBfZgm44&q=85&s=79bf69c15ef6d90c646b7490898093c2" alt="Billing dashboard using Narev components showing real-time usage" width="1272" height="416" data-path="images/intro-billing-usage.png" />
    </Frame>

    <Frame caption="Top-up component for buying credits">
      <img src="https://mintcdn.com/narev/vk3N1vAMCBfZgm44/images/intro-billing-topup.png?fit=max&auto=format&n=vk3N1vAMCBfZgm44&q=85&s=86fedfaa3e921f741ccef23b090deb75" alt="Billing dashboard using Narev components showing credit top-up options" width="1406" height="1228" data-path="images/intro-billing-topup.png" />
    </Frame>

    <Check>
      Middleware resolves cost from Narev prices and Polar receives billable events for tagged customers.
    </Check>
  </Step>
</Steps>

## Next steps

<CardGroup cols={2}>
  <Card title="MCP quickstart" icon="robot" href="/docs/quickstart-agents">
    Connect Cursor, Claude, or VS Code to `https://mcp.narev.ai`.
  </Card>

  <Card title="API reference" icon="brackets-curly" href="/docs/platform/api-reference/overview">
    Full REST paths for providers, models, prices, and cost calculation.
  </Card>

  <Card title="Node.js billing integration" icon="node-js" href="/docs/platform/billing/integrations/frameworks/nodejs">
    Reusable middleware helpers and coverage checks for any Node server.
  </Card>

  <Card title="Narev SDK overview" icon="code" href="/docs/sdk/ai-billing/index">
    Provider middleware, price resolvers, and billing destinations.
  </Card>
</CardGroup>


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