跳轉到主要內容

Documentation Index

Fetch the complete documentation index at: https://docs.aihubmix.com/llms.txt

Use this file to discover all available pages before exploring further.

1. 核心整合模式

1.1 統一驗證與路由

// Core logic: Replace API Key, Base URL, add APP-Code
const config = {
  apiKey: 'your-aihubmix-api-key',  // Replace with aihubmix API Key
  baseURL: 'https://aihubmix.com',   // Replace with aihubmix gateway
  headers: {
    'APP-Code': 'App Code'  // App Code can be obtained from https://aihubmix.com/appstore
  }
};

// Model routing rules
function routeModel(modelName: string) {
  if (modelName.startsWith('claude')) {
    // Claude models: Use Anthropic SDK
    return 'anthropic';
  } else if (modelName.startsWith('gemini') && !modelName.endsWith('-nothink') && !modelName.endsWith('-search')) {
    // Gemini models: Use Google SDK, endpoint https://aihubmix.com/gemini
    return 'gemini';
  } else {
    // Other models: Use OpenAI compatible interface
    return 'openai';
  }
}

1.2 特殊處理要點

  • 空 Tools 修正:當 tools=[]tool_choice 存在時,自動移除 tool_choice
  • 檔案副檔名:依據 mediaType 自動設定正確的檔案副檔名
  • 快取控制:支援透過 <cache> 標籤進行快取控制

2. 統一整合實作

2.1 核心 Client 封裝

class AihubmixModelClient {
  private config: {
    apiKey: string;
    baseURL: string;
    appCode: string;
  };

  constructor(apiKey: string) {
    this.config = {
      apiKey,
      baseURL: 'https://aihubmix.com',
      appCode: 'App Code can be obtained from https://aihubmix.com/appstore'
    };
  }

  async chatCompletion(model: string, messages: any[], options: any = {}) {
    // Automatically route to corresponding SDK based on model name
    if (model.startsWith('claude')) {
      return this.claudeCompletion(model, messages, options);
    } else if (model.startsWith('gemini')) {
      return this.geminiCompletion(model, messages, options);
    } else {
      return this.openaiCompletion(model, messages, options);
    }
  }

  private async claudeCompletion(model: string, messages: any[], options: any) {
    const { Anthropic } = await import('@anthropic-ai/sdk');
    const client = new Anthropic({
      apiKey: this.config.apiKey,
      baseURL: this.config.baseURL,
      defaultHeaders: { 'APP-Code': this.config.appCode }
    });
    return client.messages.create({ model, messages, ...options });
  }

  private async geminiCompletion(model: string, messages: any[], options: any) {
    const { GoogleGenerativeAI } = await import('@google/generative-ai');
    const genAI = new GoogleGenerativeAI(this.config.apiKey, {
      baseURL: `${this.config.baseURL}/gemini/v1beta`,
      defaultHeaders: { 'APP-Code': this.config.appCode }
    });
    const genModel = genAI.getGenerativeModel({ model });
    return genModel.generateContent(messages);
  }

  private async openaiCompletion(model: string, messages: any[], options: any) {
    const OpenAI = await import('openai');
    const client = new OpenAI.default({
      apiKey: this.config.apiKey,
      baseURL: `${this.config.baseURL}/v1`,
      defaultHeaders: { 'APP-Code': this.config.appCode }
    });
    return client.chat.completions.create({ model, messages, ...options });
  }
}

// Usage example
const client = new AihubmixModelClient('your-aihubmix-api-key');
await client.chatCompletion('gpt-4o-mini', messages);
await client.chatCompletion('claude-3-5-sonnet-20241022', messages);
await client.chatCompletion('gemini-2.5-flash', messages);

2.2 特殊處理與工具函式

// Empty tools fix
function fixToolChoice(requestBody: any): any {
  if (requestBody.tools?.length === 0 && requestBody.tool_choice) {
    delete requestBody.tool_choice;
  }
  return requestBody;
}

// File extension mapping
function setFileExtension(mediaType: string): string {
  const mimeToExt: Record<string, string> = {
    'audio/mpeg': 'mp3', 'audio/wav': 'wav', 'audio/flac': 'flac'
  };
  return mimeToExt[mediaType] || 'bin';
}

// Cache control
function processCacheTags(content: string): { content: string; cacheControl?: any } {
  if (content.includes('<cache>')) {
    return { content: content.replace('<cache>', ''), cacheControl: { type: 'ephemeral' } };
  }
  return { content };
}

3. 部署與設定

3.1 環境變數

const config = {
  apiKey: process.env.AIHUBMIX_API_KEY || '',
  baseURL: process.env.AIHUBMIX_BASE_URL || 'https://aihubmix.com',
  appCode: process.env.AIHUBMIX_APP_CODE || 'App Code can be obtained from https://aihubmix.com/appstore'
};

3.2 錯誤處理

class AihubmixError extends Error {
  constructor(message: string, public code?: string, public status?: number) {
    super(message);
    this.name = 'AihubmixError';
  }
}

function handleAihubmixErrors(error: any): AihubmixError {
  const message = error.message || 'Unknown error';
  if (message.toLowerCase().includes('rate limit')) {
    return new AihubmixError('Rate limit exceeded', 'RATE_LIMIT', 429);
  } else if (message.toLowerCase().includes('unauthorized')) {
    return new AihubmixError('Authentication failed', 'AUTH_ERROR', 401);
  } else {
    return new AihubmixError(message, error.code, error.status);
  }
}

4. 參考實作與對齊檢查清單

4.1 cherry-studio Client 參考(TypeScript)

下列來自 cherry-studioAihubmixAPIClient.ts 的關鍵要點,可作為第三方前端/桌面應用程式在 TypeScript 端整合 aihubmix 的落地模式:
  • 統一加入折扣碼:在 Provider 層合併 extra_headers 並設定 APP-Code(專案中使用 MLTG2087)
  • 多 client 路由:
    • claude* → 使用 Anthropic client
    • 未以 -nothink/-search 結尾且不包含 embeddinggemini*/imagen* → 使用 Gemini client(apiHost: https://aihubmix.com/gemini)
    • OpenAI 系列(不包含 gpt-oss)→ 使用 OpenAI 相容 response client
    • 其他 → 預設使用 OpenAI client
  • BaseURL 取得:從目前路由所對應的具體 client 匯出,維持各供應商的端點差異

4.2 dify-plugin-aihubmix 參考(Python)

下列來自 dify-plugin-aihubmix 實作的關鍵要點,可作為第三方 Python 工具整合 aihubmix 的落地模式:
  • 統一加入折扣碼:在 Provider 層合併 extra_headers 並設定 APP-Code(專案中使用 Dify2025)
  • 多 client 路由:
    • claude* → 使用 Anthropic client
    • 未以 -nothink/-search 結尾且不包含 embeddinggemini*/imagen* → 使用 Gemini client(apiHost: https://aihubmix.com/gemini)
    • OpenAI 系列(不包含 gpt-oss)→ 使用 OpenAI 相容 response client
    • 其他 → 預設使用 OpenAI client
  • BaseURL 取得:從目前路由所對應的具體 client 匯出,維持各供應商的端點差異

4.3 對齊檢查清單

  • Provider 入口統一合併 extra_headers 並注入 APP-Code
  • Gemini client 使用 https://aihubmix.com/gemini 作為 apiHost
  • 路由規則與 claude*gemini*/imagen*、OpenAI 系列(不包含 gpt-oss)一致
  • 預設使用 OpenAI client,維持 OpenAI 相容介面行為
  • getBaseURL() 一律從目前路由的 client 匯出,避免硬編碼

5. 遷移檢查清單

  • 將 API Key 替換為 aihubmix API Key
  • 將 Base URL 替換為 https://aihubmix.com
  • 加入 APP-Code 標頭以享有折扣
  • 實作模型路由邏輯(claude/gemini/openai)
  • 處理 tools 為空時的 tool_choice 修正
  • 設定檔案上傳的 MIME 類型處理
  • 測試各種模型呼叫

最後更新:2026-06-01