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

> ## Agent Instructions
> The Venice API is OpenAI-compatible: use any OpenAI SDK with the base URL `https://api.venice.ai/api/v1` and a Venice API key, or pay per request from a USDC wallet through x402 with no account.
> Read model IDs from `GET /models` or `GET /models/traits` at runtime instead of hardcoding them from memory or from these pages. Models are added and retired often.
> Every model's price is in https://docs.venice.ai/pricing.md. Quote video and audio jobs with `POST /video/quote` or `POST /audio/quote` before you queue them.
> Search these docs from an MCP client at https://docs.venice.ai/mcp. The full agent guide is https://docs.venice.ai/agents.md.

# Vercel AI SDK

> Stream Venice chat completions in Next.js and React with the Vercel AI SDK.

The [Vercel AI SDK](https://ai-sdk.dev/) is the most popular way to build AI features in Next.js, React, Svelte, and Vue apps. Venice works out of the box as an OpenAI-compatible provider.

## Setup

The examples use AI SDK 7, which requires Node.js 22 or later and ESM (`import` rather than `require()`). Install it with the OpenAI provider, the React hooks, and Zod:

```bash theme={"system"}
npm install ai@7 @ai-sdk/openai@4 @ai-sdk/react@4 zod
```

## Provider Configuration

Create a Venice provider using the OpenAI-compatible adapter:

```typescript theme={"system"}
// lib/venice.ts
import { createOpenAI } from '@ai-sdk/openai';

const openai = createOpenAI({
  apiKey: process.env.VENICE_API_KEY!,
  baseURL: 'https://api.venice.ai/api/v1',
});

// Use .chat() to ensure compatibility with Venice's chat completions endpoint
export const venice = (modelId: string) => openai.chat(modelId);
```

> [!NOTE]
>
> Using `.chat()` ensures requests go to Venice's `/chat/completions` endpoint. In recent AI SDK versions, the default `openai('model')` syntax uses the Responses API instead, which Venice serves at `/responses` with some limitations. See the [Responses API guide](https://docs.venice.ai/guides/features/responses-api.md) before using it.

## Streaming Chat (Next.js App Router)

### API Route

```typescript theme={"system"}
// app/api/chat/route.ts
import {
  convertToModelMessages,
  createUIMessageStreamResponse,
  streamText,
  toUIMessageStream,
  type UIMessage,
} from 'ai';
import { venice } from '@/lib/venice';

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

  const result = streamText({
    model: venice('venice-uncensored-1-2'),
    instructions: 'You are a helpful, privacy-respecting AI assistant.',
    messages: await convertToModelMessages(messages),
  });

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  });
}
```

### React Component

```tsx theme={"system"}
// app/page.tsx
'use client';

import { useChat } from '@ai-sdk/react';
import { useState } from 'react';

export default function Chat() {
  const [input, setInput] = useState('');
  const { messages, sendMessage, status } = useChat();
  const isLoading = status === 'submitted' || status === 'streaming';

  return (
    <div className="max-w-2xl mx-auto p-4">
      <div className="space-y-4 mb-4">
        {messages.map((m) => (
          <div key={m.id} className={m.role === 'user' ? 'text-right' : 'text-left'}>
            <span className="font-bold">{m.role === 'user' ? 'You' : 'Venice'}:</span>
            {m.parts.map((part, i) =>
              part.type === 'text' ? (
                <p key={i} className="whitespace-pre-wrap">{part.text}</p>
              ) : null,
            )}
          </div>
        ))}
      </div>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (!input.trim()) return;
          sendMessage({ text: input });
          setInput('');
        }}
        className="flex gap-2"
      >
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask anything..."
          className="flex-1 border rounded px-3 py-2"
          disabled={isLoading}
        />
        <button type="submit" disabled={isLoading} className="bg-red-600 text-white px-4 py-2 rounded">
          Send
        </button>
      </form>
    </div>
  );
}
```

## Generating Text (Non-Streaming)

```typescript theme={"system"}
import { generateText } from 'ai';
import { venice } from '@/lib/venice';

const { text } = await generateText({
  model: venice('z-ai-glm-5-3-flash'),
  prompt: 'Explain zero-knowledge proofs in simple terms.',
});

console.log(text);
```

## Structured Output

```typescript theme={"system"}
import { generateText, Output } from 'ai';
import { venice } from '@/lib/venice';
import { z } from 'zod';

const { output } = await generateText({
  model: venice('venice-uncensored-1-2'),
  output: Output.object({
    schema: z.object({
      recipe: z.object({
        name: z.string(),
        ingredients: z.array(z.string()),
        steps: z.array(z.string()),
        prepTimeMinutes: z.number(),
      }),
    }),
  }),
  prompt: 'Generate a recipe for chocolate chip cookies.',
});

console.log(output.recipe.name);
console.log(`Prep time: ${output.recipe.prepTimeMinutes} minutes`);
```

## Tool Calling

```typescript theme={"system"}
import { isStepCount, streamText, tool } from 'ai';
import { venice } from '@/lib/venice';
import { z } from 'zod';

const result = streamText({
  model: venice('z-ai-glm-5-3-flash'),
  messages: [{ role: 'user', content: 'What is the weather in Tokyo?' }],
  tools: {
    getWeather: tool({
      description: 'Get current weather for a location',
      inputSchema: z.object({
        location: z.string().describe('City name'),
      }),
      execute: async ({ location }) => {
        // Your weather API call here
        return { temperature: 22, condition: 'Sunny', location };
      },
    }),
  },
  stopWhen: isStepCount(2),
});

for await (const part of result.stream) {
  if (part.type === 'text-delta') {
    process.stdout.write(part.text);
  } else if (part.type === 'tool-result') {
    console.log('Tool result:', part.output);
  }
}
```

`stopWhen: isStepCount(2)` lets the model answer in a second step after the tool runs. Without it, the stream ends after the tool result.

## Image Generation

Venice image generation can be called directly alongside the AI SDK:

```typescript theme={"system"}
// app/api/image/route.ts
export async function POST(req: Request) {
  const { prompt } = await req.json();

  const response = await fetch('https://api.venice.ai/api/v1/image/generate', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.VENICE_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'qwen-image',
      prompt,
      aspect_ratio: '1:1',
    }),
  });

  const data = await response.json();
  return Response.json({ image: data.images[0] });
}
```

## Multi-Model Chat (Model Selector)

Let users choose between Venice models:

```typescript theme={"system"}
// app/api/chat/route.ts
import {
  convertToModelMessages,
  createUIMessageStreamResponse,
  streamText,
  toUIMessageStream,
  type UIMessage,
} from 'ai';
import { venice } from '@/lib/venice';

const ALLOWED_MODELS = [
  'venice-uncensored-1-2',
  'z-ai-glm-5-3-flash',
  'qwen3-vl-235b-a22b',
  'nvidia-nemotron-3-nano-30b-a3b',
];

export async function POST(req: Request) {
  const { messages, model: modelId }: { messages: UIMessage[]; model: string } =
    await req.json();

  if (!ALLOWED_MODELS.includes(modelId)) {
    return new Response('Invalid model', { status: 400 });
  }

  const result = streamText({
    model: venice(modelId),
    messages: await convertToModelMessages(messages),
  });

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  });
}
```

```tsx theme={"system"}
// Client component with model selector
'use client';

import { useChat } from '@ai-sdk/react';
import { useState } from 'react';

const MODELS = [
  { id: 'venice-uncensored-1-2', name: 'Venice Uncensored', desc: 'Fast & uncensored' },
  { id: 'z-ai-glm-5-3-flash', name: 'GLM 5.3 Flash', desc: 'Fast private reasoning' },
  { id: 'qwen3-vl-235b-a22b', name: 'Qwen Vision', desc: 'Advanced vision + text' },
  { id: 'nvidia-nemotron-3-nano-30b-a3b', name: 'Nemotron 3 Nano 30B', desc: 'Fast & low cost' },
];

export default function Chat() {
  const [model, setModel] = useState('venice-uncensored-1-2');
  const [input, setInput] = useState('');
  const { messages, sendMessage } = useChat();

  return (
    <div>
      <select value={model} onChange={(e) => setModel(e.target.value)}>
        {MODELS.map((m) => (
          <option key={m.id} value={m.id}>{m.name} — {m.desc}</option>
        ))}
      </select>
      {messages.map((m) => (
        <p key={m.id}>
          {m.role}: {m.parts.map((part) => (part.type === 'text' ? part.text : '')).join('')}
        </p>
      ))}
      <form
        onSubmit={(e) => {
          e.preventDefault();
          sendMessage({ text: input }, { body: { model } });
          setInput('');
        }}
      >
        <input value={input} onChange={(e) => setInput(e.target.value)} />
      </form>
    </div>
  );
}
```

`sendMessage` sends the selected `model` in the request body with each message, so switching models applies to the next message.

## Web Search Integration

Turn on Venice web search with a [model feature suffix](https://docs.venice.ai/api-reference/endpoint/chat/model_feature_suffix.md) on the model ID. The suffix passes `venice_parameters` through the model ID, so you don't need to add fields to the request:

```typescript theme={"system"}
import { streamText } from 'ai';
import { venice } from '@/lib/venice';

const result = streamText({
  model: venice('venice-uncensored-1-2:enable_web_search=auto'),
  messages: [{ role: 'user', content: 'What happened in AI news today?' }],
});
```

## Embeddings

For embeddings, use `embeddingModel()` on the provider directly:

```typescript theme={"system"}
import { embed, embedMany } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const openai = createOpenAI({
  apiKey: process.env.VENICE_API_KEY!,
  baseURL: 'https://api.venice.ai/api/v1',
});

// Single embedding
const { embedding } = await embed({
  model: openai.embeddingModel('text-embedding-bge-m3'),
  value: 'Privacy-first AI infrastructure',
});

// Batch embeddings
const { embeddings } = await embedMany({
  model: openai.embeddingModel('text-embedding-bge-m3'),
  values: [
    'Venice AI provides private inference.',
    'Zero data retention guaranteed.',
    'OpenAI SDK compatible.',
  ],
});
```

## Environment Variables

```bash theme={"system"}
# .env.local
VENICE_API_KEY=your-venice-api-key
```

## Recommended Models

| Use Case | Model | Why |
| - | - | - |
| Chat apps | `venice-uncensored-1-2` | Fast, cheap, no filtering |
| Complex tasks | `z-ai-glm-5-3-flash` | Fast private reasoning |
| Vision apps | `qwen3-vl-235b-a22b` | Advanced image understanding |
| High-volume | `nvidia-nemotron-3-nano-30b-a3b` | Low cost at $0.075/1M input, $0.30/1M output |
| Tool calling | `z-ai-glm-5-3-flash` | Reliable function calling |

> [card] [Vercel AI SDK Docs](https://ai-sdk.dev/docs)
>
> Official Vercel AI SDK documentation

> [card] [Venice Models](https://docs.venice.ai/models/overview.md)
>
> Browse all Venice models


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