AI Pass Web SDK — OAuth2 + PKCE with AI APIs
Docs > SDK > Reference

1. Setup

Add the SDK to your page and initialize it once on load. The clientId is required. The SDK automatically handles the OAuth redirect on the same page — no extra callback code needed.

<!-- Include the SDK -->
<script src="https://aipass.one/aipass-sdk.js"></script>

<script>
  // REQUIRED: provide your OAuth2 clientId
  AiPass.initialize({
    clientId: 'your_client_id',
    // redirectUri defaults to this page (same‑page flow)
    // Optional overrides
    // baseUrl: 'https://aipass.one',
    // scopes: ['api:access', 'profile:read']
  });
</script>
Use HTTPS in production. HTTP is allowed only on localhost for development.

2. Authentication

Start OAuth2 + PKCE in a popup, then call SDK methods with the stored token.

// Trigger login from a user action (e.g., button click)
async function login() {
  try {
    await AiPass.login();
    console.log('Signed in');
  } catch (e) {
    console.error('Login failed:', e);
  }
}

// Check status
if (AiPass.isAuthenticated()) {
  console.log('Ready to call APIs');
}

// Get token if needed (for custom calls)
const token = AiPass.getAccessToken();

// Logout helper
async function logout() { await AiPass.logout(); }

// Refresh helper
async function refreshToken() { await AiPass.refreshAccessToken(); }

3. Models

// List models
const { data } = await AiPass.getModels();
console.log('Available:', data.length);

// Get details for a specific model
const model = await AiPass.getModel('gpt-4o-mini');
console.log(model);

4. Chat Completions

// Simple prompt
const reply = await AiPass.generateCompletion({
  prompt: 'Explain async programming',
  model: 'gemini/gemini-2.5-flash-lite',
  temperature: 0.7,
  maxTokens: 500
});
console.log(reply.choices[0].message.content);

// Messages format
const chat = await AiPass.generateCompletion({
  messages: [
    { role: 'system', content: 'You are helpful.' },
    { role: 'user', content: 'What are closures?' }
  ]
});
Streaming is currently disabled on the backend — use non‑streaming calls.

5. Images

5.1 Generate

const result = await AiPass.generateImage({
  prompt: 'A futuristic city at sunset',
  model: 'gpt-image-1',
  n: 2,
  size: '1024x1024',
  quality: 'high',
  responseFormat: 'url'
});
result.data.forEach(img => console.log(img.url));

5.2 Edit

const edited = await AiPass.editImage({
  image: fileInput.files[0],
  prompt: 'Add a red hat',
  model: 'gpt-image-1',
  n: 1,
  size: '1024x1024',
  responseFormat: 'url'
});

5.3 Variations

const vars = await AiPass.generateImageVariations({
  image: fileInput.files[0],
  model: 'gpt-image-1',
  n: 3,
  size: '1024x1024',
  responseFormat: 'url'
});

6. Audio

6.1 Text → Speech

const audioBlob = await AiPass.generateSpeech({
  text: 'Hello world',
  model: 'tts-1',
  voice: 'nova',
  responseFormat: 'mp3',
  speed: 1.0
});
new Audio(URL.createObjectURL(audioBlob)).play();

6.2 Speech → Text

const out = await AiPass.transcribeAudio({
  audioFile: fileInput.files[0],
  model: 'whisper-1',
  language: 'en'
});
console.log(out.text);

7. Balance & Usage

const summary = await AiPass.getUserBalance();
console.log('Remaining $', summary.data.remainingBudget);
console.log('Used $', summary.data.totalCost);
console.log('Limit $', summary.data.maxBudget);

8. Embeddings

// Generate embeddings for text
const result = await AiPass.generateEmbeddings({
  input: 'Hello world',
  model: 'text-embedding-ada-002'
});
console.log(result.data[0].embedding);

// Multiple texts at once
const batch = await AiPass.generateEmbeddings({
  input: ['First text', 'Second text', 'Third text']
});

9. Utilities

// Open dashboard
AiPass.openDashboard();

// Clear stored tokens (localStorage)
AiPass.clearTokens();

10. UI Components

AI Pass provides ready-to-use UI components for authentication and balance display.

10.1 AI Pass Logo Button

A beautiful, animated button that handles authentication and displays user balance.

Features

  • Two States: Disconnected (dark with "CONNECT" text) and Connected (white with ripple animation)
  • Balance Display: Shows remaining balance inside the button when connected
  • Toggle Behavior: Click to login when disconnected, click to logout when connected
  • Ripple Animation: Elegant wave animation radiating from the AI box when connected
  • Signature Design: Three rounded corners, one square corner (top-right)
  • Size Variants: Default, small, and large sizes available

Installation

Simply include the AI Pass SDK and optional UI stylesheet:

<!-- Include AI Pass UI Stylesheet (optional) -->
<link rel="stylesheet" href="https://aipass.one/aipass-ui.css">

<!-- Include AI Pass SDK (UI components built-in!) -->
<script src="https://aipass.one/aipass-sdk.js"></script>
Note: UI components are built into the SDK! Just include the CSS for styling. Everything works automatically with zero configuration!

Quick Example - Zero Configuration!

Complete working example - no JavaScript code needed:

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
  <!-- 1. Include AI Pass UI Stylesheet -->
  <link rel="stylesheet" href="https://aipass.one/aipass-ui.css">
</head>
<body>
  <!-- 2. Add the button with data-aipass-button attribute -->
  <div data-aipass-button></div>

  <!-- 3. Include SDK (UI built-in!) -->
  <script src="https://aipass.one/aipass-sdk.js"></script>

  <!-- 4. Initialize SDK with your client ID -->
  <script>
    AiPass.initialize({ clientId: 'your_client_id' });
  </script>
</body>
</html>

That's it! The button will automatically:

  • Handle login/logout on click
  • Switch between connected/disconnected states
  • Fetch and display balance
  • Show ripple animation when connected
  • Be keyboard accessible (Tab, Enter, Space)

Custom Events

The button emits custom events for app integration:

// Listen for login event
document.addEventListener('aipass:login', (e) => {
  console.log('User logged in!');
  // Enable your app features
});

// Listen for logout event
document.addEventListener('aipass:logout', (e) => {
  console.log('User logged out!');
  // Disable your app features
});

// Listen for balance updates
document.addEventListener('aipass:balance', (e) => {
  console.log('Balance:', e.detail.formatted);
  console.log('Raw amount:', e.detail.balance);
});

// Listen for errors
document.addEventListener('aipass:error', (e) => {
  console.error('Error:', e.detail.error);
  console.log('Action:', e.detail.action); // 'login' or 'logout'
});

Public API

Manual control when needed:

// Refresh balance manually
AiPassUI.refreshBalance();

// Or for a specific button
const button = document.querySelector('[data-aipass-button]');
AiPassUI.refreshBalance(button);

// Re-initialize all buttons (for dynamic content)
AiPassUI.reinit();

// Check if button is connected
const isConnected = AiPassUI.isConnected(button);

Advanced Usage

Multiple buttons or custom attributes:

<!-- Multiple buttons work independently -->
<div data-aipass-button></div>
<div data-aipass-button class="large"></div>

<!-- Listen to specific button events -->
<div id="my-button" data-aipass-button></div>

<script>
  document.getElementById('my-button').addEventListener('aipass:login', () => {
    console.log('My specific button was clicked!');
  });
</script>

Size Variants

The logo button supports three sizes:

<!-- Default size -->
<div class="logo-container dark">...</div>

<!-- Small size -->
<div class="logo-container small dark">...</div>

<!-- Large size -->
<div class="logo-container large dark">...</div>
Tip: The balance automatically updates after API calls. You can call fetchBalance() manually to refresh it at any time.

Live Interactive Demo

See the AI Pass button in action! Code on the left, live demo on the right:

Complete Example Code

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet"
    href="https://aipass.one/aipass-ui.css">
</head>
<body>
  <!-- Zero-config button -->
  <div data-aipass-button></div>

  <button id="ask" disabled>
    Ask AI
  </button>
  <div id="out"></div>

  <script
    src="https://aipass.one/aipass-sdk.js">
  </script>
  <script>
    AiPass.initialize({
      clientId: 'your_client_id'
    });

    // Enable on login
    document.addEventListener(
      'aipass:login', () => {
      document.getElementById('ask')
        .disabled = false;
    });

    // Disable on logout
    document.addEventListener(
      'aipass:logout', () => {
      document.getElementById('ask')
        .disabled = true;
      document.getElementById('out')
        .textContent = '';
    });

    // Check if authenticated
    if (AiPass.isAuthenticated()) {
      document.getElementById('ask')
        .disabled = false;
    }

    // Ask AI handler
    document.getElementById('ask')
      .onclick = async () => {
      const res = await
        AiPass.generateCompletion({
        prompt: 'Short joke!',
        model: 'gemini/gemini-2.5-flash-lite'
      });
      document.getElementById('out')
        .textContent =
        res.choices[0].message.content;
    };
  </script>
</body>
</html>

Live Working Demo

How to use:
1. Click the AI Pass button above to authenticate
2. Once logged in, click "Ask AI"
3. Watch the real API response appear!
4. Click AI Pass button again to logout

More Examples: