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

# Vercel AI SDK Integration

> Build AI-powered applications with Vercel AI SDK and the platform

## Overview

[Vercel AI SDK](https://sdk.vercel.ai/) is a TypeScript toolkit for building AI-powered applications with React, Next.js, Vue, and Svelte. The platform works seamlessly with Vercel AI SDK using the OpenAI provider.

<Info>
  Perfect for building streaming chat UIs, AI-powered forms, and interactive AI experiences.
</Info>

## Installation

```bash theme={null}
npm install ai openai
```

## Basic Setup

### Text Generation

```typescript theme={null}
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const redpill = createOpenAI({
  apiKey: process.env.API_KEY,
  baseURL: 'https://api.redpill.ai/v1'
});

async function main() {
  const { text } = await generateText({
    model: redpill('openai/gpt-5'),
    prompt: 'Explain how TEE protects data privacy'
  });

  console.log(text);
}

main();
```

### Streaming Text

```typescript theme={null}
import { streamText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const redpill = createOpenAI({
  apiKey: process.env.API_KEY,
  baseURL: 'https://api.redpill.ai/v1'
});

async function main() {
  const result = streamText({
    model: redpill('openai/gpt-5'),
    prompt: 'Write a story about privacy-first AI'
  });

  for await (const chunk of result.textStream) {
    process.stdout.write(chunk);
  }
}

main();
```

## Next.js Chat Application

### Route Handler (app/api/chat/route.ts)

```typescript theme={null}
import { streamText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

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

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

  const result = streamText({
    model: redpill('openai/gpt-5'),
    messages,
    temperature: 0.7,
    maxTokens: 1000
  });

  return result.toDataStreamResponse();
}
```

### Chat UI Component (app/page.tsx)

```typescript theme={null}
'use client';

import { useChat } from 'ai/react';

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
    api: '/api/chat'
  });

  return (
    <div className="flex flex-col h-screen max-w-2xl mx-auto p-4">
      {/* Messages */}
      <div className="flex-1 overflow-y-auto space-y-4 mb-4">
        {messages.map(message => (
          <div
            key={message.id}
            className={`p-4 rounded-lg ${
              message.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'
            }`}
          >
            <div className="font-bold mb-1">
              {message.role === 'user' ? 'You' : 'AI'}
            </div>
            <div>{message.content}</div>
          </div>
        ))}
        {isLoading && <div className="text-gray-500">AI is thinking...</div>}
      </div>

      {/* Input Form */}
      <form onSubmit={handleSubmit} className="flex gap-2">
        <input
          value={input}
          onChange={handleInputChange}
          placeholder="Type your message..."
          className="flex-1 p-2 border rounded"
          disabled={isLoading}
        />
        <button
          type="submit"
          disabled={isLoading}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-400"
        >
          Send
        </button>
      </form>
    </div>
  );
}
```

### Environment Variables (.env.local)

```bash theme={null}
API_KEY=YOUR_API_KEY
```

## Tool Calling (Function Calling)

```typescript theme={null}
import { generateText, tool } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import { z } from 'zod';

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

async function main() {
  const result = await generateText({
    model: redpill('openai/gpt-5'),
    prompt: 'What is the weather in Paris and San Francisco?',
    tools: {
      getWeather: tool({
        description: 'Get the current weather in a location',
        parameters: z.object({
          location: z.string().describe('The city name'),
          unit: z.enum(['celsius', 'fahrenheit']).optional()
        }),
        execute: async ({ location, unit = 'celsius' }) => {
          // API call to weather service
          return {
            location,
            temperature: 22,
            unit,
            condition: 'sunny'
          };
        }
      })
    },
    maxSteps: 5  // Allow multiple tool calls
  });

  console.log(result.text);
}

main();
```

## Streaming with Tool Calls

```typescript theme={null}
import { streamText, tool } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import { z } from 'zod';

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

async function main() {
  const result = streamText({
    model: redpill('openai/gpt-5'),
    prompt: 'Calculate the sum of 15 and 27, then multiply by 3',
    tools: {
      calculate: tool({
        description: 'Perform mathematical calculations',
        parameters: z.object({
          expression: z.string().describe('Math expression to evaluate')
        }),
        execute: async ({ expression }) => {
          return { result: eval(expression) };
        }
      })
    }
  });

  for await (const chunk of result.fullStream) {
    if (chunk.type === 'text-delta') {
      process.stdout.write(chunk.textDelta);
    } else if (chunk.type === 'tool-call') {
      console.log('\nTool call:', chunk.toolName, chunk.args);
    } else if (chunk.type === 'tool-result') {
      console.log('Tool result:', chunk.result);
    }
  }
}

main();
```

## Multi-Model Support

Switch between different AI providers seamlessly:

```typescript theme={null}
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

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

// Use GPU TEE for sensitive reasoning
const teeResult = await generateText({
  model: redpill('z-ai/glm-5.1'),
  prompt: 'Process this confidential information...'
});

// Use confidential (is_tee) model for systems engineering
const nearResult = await generateText({
  model: redpill('z-ai/glm-5'),
  prompt: 'Analyze this architecture...'
});

// Use GPT-5 for general tasks
const gptResult = await generateText({
  model: redpill('openai/gpt-5'),
  prompt: 'Summarize this article...'
});

// Use Claude for analysis
const claudeResult = await generateText({
  model: redpill('anthropic/claude-sonnet-4.5'),
  prompt: 'Analyze this data...'
});

// Use DeepSeek for coding
const deepseekResult = await generateText({
  model: redpill('deepseek/deepseek-chat-v3.1'),
  prompt: 'Write a React component...'
});

```

## React Server Components

```typescript theme={null}
// app/generate/page.tsx
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

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

export default async function Page() {
  const { text } = await generateText({
    model: redpill('openai/gpt-5'),
    prompt: 'Generate a creative tagline for a privacy-first AI platform'
  });

  return (
    <div className="p-8">
      <h1 className="text-2xl font-bold mb-4">Generated Tagline</h1>
      <p className="text-lg">{text}</p>
    </div>
  );
}
```

## Structured Output

Generate type-safe structured data:

```typescript theme={null}
import { generateObject } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import { z } from 'zod';

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

async function main() {
  const { object } = await generateObject({
    model: redpill('openai/gpt-5'),
    schema: z.object({
      name: z.string(),
      age: z.number(),
      occupation: z.string(),
      skills: z.array(z.string())
    }),
    prompt: 'Generate a profile for a software engineer named Alice'
  });

  console.log(object);
  // TypeScript knows the exact shape:
  // { name: string, age: number, occupation: string, skills: string[] }
}

main();
```

## Error Handling

```typescript theme={null}
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

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

async function main() {
  try {
    const result = await generateText({
      model: redpill('openai/gpt-5'),
      prompt: 'Hello!'
    });

    console.log(result.text);
  } catch (error) {
    if (error instanceof Error) {
      console.error('Error:', error.message);

      // Handle specific error types
      if (error.message.includes('rate limit')) {
        console.log('Rate limited, retrying...');
      } else if (error.message.includes('insufficient credits')) {
        console.log('Please add credits to your account');
      }
    }
  }
}

main();
```

## Supported Models

All available models work with Vercel AI SDK:

| Model                         | Use Case                                   |
| ----------------------------- | ------------------------------------------ |
| `z-ai/glm-5.1`                | Confidential reasoning (GPU TEE)           |
| `z-ai/glm-5`                  | Confidential systems engineering (GPU TEE) |
| `qwen/qwen3.5-27b`            | Confidential general purpose (GPU TEE)     |
| `openai/gpt-5`                | General purpose, chat                      |
| `anthropic/claude-sonnet-4.5` | Reasoning, analysis                        |
| `deepseek/deepseek-chat-v3.1` | Coding, technical tasks                    |
| `google/gemini-2.5-flash`     | Fast responses                             |

<Card title="View All Models" icon="list" href="/api-reference/models">
  Browse supported models →
</Card>

## Example Use Cases

<CardGroup cols={2}>
  <Card title="Chatbot" icon="comment">
    Build a streaming chat interface with Next.js
  </Card>

  <Card title="Content Generator" icon="pen">
    Generate blog posts, summaries, and creative content
  </Card>

  <Card title="AI Forms" icon="input-text">
    Create forms with AI-powered suggestions
  </Card>

  <Card title="Data Extraction" icon="table">
    Extract structured data from unstructured text
  </Card>
</CardGroup>

## Resources

* [Vercel AI SDK Documentation](https://sdk.vercel.ai/)
* [Next.js AI Chatbot Template](https://vercel.com/templates/next.js/nextjs-ai-chatbot)
* [RedPill Discord](https://discord.gg/P2ukR4Z5ps)
* [GitHub Examples](https://github.com/redpill-ai/examples)

## Next Steps

<CardGroup cols={2}>
  <Card title="OpenAI SDK" icon="code" href="/guides/integrations/openai-sdk">
    Use the official OpenAI SDK
  </Card>

  <Card title="LangChain" icon="link" href="/guides/integrations/langchain">
    Build with LangChain framework
  </Card>
</CardGroup>
