> ## 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.

# OpenAI SDK Integration

> Use the official OpenAI SDK with the TEE-protected gateway

## Overview

The platform is fully compatible with the [official OpenAI SDK](https://github.com/openai/openai-python). Just change the base URL and you get access to a broad range of models with TEE privacy protection.

<Info>
  The easiest way to get started - works with your existing OpenAI code!
</Info>

## Installation

<CodeGroup>
  ```bash Python theme={null}
  pip install openai
  ```

  ```bash TypeScript/JavaScript theme={null}
  npm install openai
  ```
</CodeGroup>

## Python Quick Start

### Basic Setup

```python theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

response = client.chat.completions.create(
    model="openai/gpt-5",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain how TEE protects my data"}
    ]
)

print(response.choices[0].message.content)
```

### Streaming Responses

```python theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

stream = client.chat.completions.create(
    model="openai/gpt-5",
    messages=[{"role": "user", "content": "Write a story about AI"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
```

### Function Calling

```python theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather in a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City name, e.g. San Francisco"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"]
                    }
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="openai/gpt-5",
    messages=[{"role": "user", "content": "What's the weather in Paris?"}],
    tools=tools
)

# Check if model wants to call a function
if response.choices[0].message.tool_calls:
    tool_call = response.choices[0].message.tool_calls[0]
    print(f"Function: {tool_call.function.name}")
    print(f"Arguments: {tool_call.function.arguments}")
```

### Embeddings

```python theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

response = client.embeddings.create(
    model="openai/text-embedding-3-small",
    input="The platform protects your AI requests with hardware TEE"
)

embedding = response.data[0].embedding
print(f"Embedding dimensions: {len(embedding)}")  # 1536
```

### Vision (Image Analysis)

```python theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

response = client.chat.completions.create(
    model="openai/gpt-5",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What's in this image?"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://example.com/image.jpg"
                    }
                }
            ]
        }
    ]
)

print(response.choices[0].message.content)
```

## TypeScript/JavaScript Quick Start

### Basic Setup

```typescript theme={null}
import OpenAI from 'openai';

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

async function main() {
  const response = await client.chat.completions.create({
    model: 'openai/gpt-5',
    messages: [
      { role: 'system', content: 'You are a helpful assistant.' },
      { role: 'user', content: 'Explain how TEE protects my data' }
    ]
  });

  console.log(response.choices[0].message.content);
}

main();
```

### Streaming in TypeScript

```typescript theme={null}
import OpenAI from 'openai';

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

async function main() {
  const stream = await client.chat.completions.create({
    model: 'openai/gpt-5',
    messages: [{ role: 'user', content: 'Write a story about AI' }],
    stream: true
  });

  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || '');
  }
}

main();
```

### Function Calling in TypeScript

```typescript theme={null}
import OpenAI from 'openai';

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

async function main() {
  const tools: OpenAI.Chat.ChatCompletionTool[] = [
    {
      type: 'function',
      function: {
        name: 'get_weather',
        description: 'Get current weather in a location',
        parameters: {
          type: 'object',
          properties: {
            location: {
              type: 'string',
              description: 'City name'
            },
            unit: {
              type: 'string',
              enum: ['celsius', 'fahrenheit']
            }
          },
          required: ['location']
        }
      }
    }
  ];

  const response = await client.chat.completions.create({
    model: 'openai/gpt-5',
    messages: [{ role: 'user', content: "What's the weather in Paris?" }],
    tools
  });

  const toolCall = response.choices[0].message.tool_calls?.[0];
  if (toolCall) {
    console.log('Function:', toolCall.function.name);
    console.log('Arguments:', toolCall.function.arguments);
  }
}

main();
```

## Using Multiple Models

The platform gives you access to a broad range of models through the same SDK:

```python theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

# GPU TEE model for sensitive reasoning
tee_response = client.chat.completions.create(
    model="z-ai/glm-5.1",
    messages=[{"role": "user", "content": "Process this confidential..."}]
)

# Confidential (is_tee) model for systems engineering
near_response = client.chat.completions.create(
    model="z-ai/glm-5",
    messages=[{"role": "user", "content": "Analyze this architecture..."}]
)

# OpenAI GPT-5 for general tasks
gpt_response = client.chat.completions.create(
    model="openai/gpt-5",
    messages=[{"role": "user", "content": "Summarize this article..."}]
)

# Anthropic Claude for analysis
claude_response = client.chat.completions.create(
    model="anthropic/claude-sonnet-4.5",
    messages=[{"role": "user", "content": "Analyze this data..."}]
)
```

## Environment Variables

Never hardcode API keys. Use environment variables:

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

```python Python theme={null}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("API_KEY"),
    base_url="https://api.redpill.ai/v1"
)
```

```typescript TypeScript theme={null}
// Uses process.env.API_KEY automatically
const client = new OpenAI({
  baseURL: 'https://api.redpill.ai/v1'
});
```

## Error Handling

```python theme={null}
from openai import OpenAI, APIError, RateLimitError

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

try:
    response = client.chat.completions.create(
        model="openai/gpt-5",
        messages=[{"role": "user", "content": "Hello!"}]
    )
    print(response.choices[0].message.content)

except RateLimitError:
    print("Rate limit exceeded. Please wait and retry.")

except APIError as e:
    print(f"API error: {e}")

except Exception as e:
    print(f"Unexpected error: {e}")
```

## Async Support

### Python Async

```python theme={null}
import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

async def main():
    response = await client.chat.completions.create(
        model="openai/gpt-5",
        messages=[{"role": "user", "content": "Hello!"}]
    )
    print(response.choices[0].message.content)

asyncio.run(main())
```

### TypeScript Async (built-in)

```typescript theme={null}
// All OpenAI SDK methods are async by default in TypeScript
const response = await client.chat.completions.create({
  model: 'openai/gpt-5',
  messages: [{ role: 'user', content: 'Hello!' }]
});
```

## Migration from OpenAI

<Steps>
  <Step title="Update Base URL">
    Add `base_url="https://api.redpill.ai/v1"` to your client initialization
  </Step>

  <Step title="Update API Key">
    Replace your OpenAI API key with your platform API key
  </Step>

  <Step title="Add Provider Prefix">
    Change `model="gpt-4"` to `model="openai/gpt-5"`
  </Step>

  <Step title="Test">
    Run your application - everything else stays the same!
  </Step>
</Steps>

<Card title="Detailed Migration Guide" icon="arrows-turn-right" href="/guides/migration-from-openai">
  Full migration guide with examples →
</Card>

## Supported Features

| Feature          | Python | TypeScript | Notes               |
| ---------------- | ------ | ---------- | ------------------- |
| Chat Completions | ✅      | ✅          | All models          |
| Streaming        | ✅      | ✅          | Real-time responses |
| Function Calling | ✅      | ✅          | Tool use support    |
| Embeddings       | ✅      | ✅          | Vector generation   |
| Vision           | ✅      | ✅          | Image analysis      |
| Async/Await      | ✅      | ✅          | Non-blocking calls  |

## Popular Models

| Model                         | Best For                                   | Context     |
| ----------------------------- | ------------------------------------------ | ----------- |
| `z-ai/glm-5.1`                | Confidential reasoning (GPU TEE)           | 128K tokens |
| `z-ai/glm-5`                  | Confidential systems engineering (GPU TEE) | 128K tokens |
| `qwen/qwen3.5-27b`            | Confidential general purpose (GPU TEE)     | 128K tokens |
| `openai/gpt-5`                | General purpose                            | 128K tokens |
| `anthropic/claude-sonnet-4.5` | Reasoning, analysis                        | 200K tokens |
| `deepseek/deepseek-chat-v3.1` | Coding tasks                               | 64K tokens  |
| `google/gemini-2.5-pro`       | Multimodal tasks                           | 2M tokens   |

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

## Example Projects

<CardGroup cols={2}>
  <Card title="CLI Chatbot" icon="terminal">
    Build a command-line AI assistant
  </Card>

  <Card title="Document Q&A" icon="file-lines">
    Create a RAG system with embeddings
  </Card>

  <Card title="Code Assistant" icon="code">
    Build an AI pair programmer
  </Card>

  <Card title="Data Analyzer" icon="chart-bar">
    Analyze datasets with AI
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Function Calling Guide" icon="function" href="/guides/function-calling">
    Learn advanced function calling
  </Card>

  <Card title="Streaming Guide" icon="stream" href="/guides/streaming">
    Implement streaming responses
  </Card>

  <Card title="Vision Guide" icon="image" href="/guides/vision">
    Work with images and vision models
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/guides/error-handling">
    Handle errors gracefully
  </Card>
</CardGroup>
