JavaScript 示例

以下是使用 JavaScript/Node.js 调用 AI2API 的示例代码。

使用 Fetch API

// 基础对话请求
const response = await fetch('https://api.ai2api.top/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'YOUR_API_KEY'
  },
  body: JSON.stringify({
    model: 'gpt-3.5-turbo',
    messages: [
      { role: 'user', content: '你好,请介绍一下你自己' }
    ]
  })
});

const data = await response.json();
console.log(data.choices[0].message.content);

流式响应

// 流式响应处理
const response = await fetch('https://api.ai2api.top/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'YOUR_API_KEY'
  },
  body: JSON.stringify({
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: '讲个故事' }],
    stream: true
  })
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value);
  const lines = chunk.split('\n');
  
  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = line.slice(6);
      if (data === '[DONE]') break;
      
      const parsed = JSON.parse(data);
      const content = parsed.choices[0]?.delta?.content || '';
      process.stdout.write(content);
    }
  }
}

使用 Axios

import axios from 'axios';

const client = axios.create({
  baseURL: 'https://api.ai2api.top',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'YOUR_API_KEY'
  }
});

async function chat(message) {
  const response = await client.post('/v1/chat/completions', {
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: message }]
  });
  
  return response.data.choices[0].message.content;
}

// 使用示例
chat('你好').then(console.log);

错误处理

async function safeChat(message) {
  try {
    const response = await fetch('https://api.ai2api.top/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': 'YOUR_API_KEY'
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content: message }]
      })
    });
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error?.message || '请求失败');
    }
    
    const data = await response.json();
    return data.choices[0].message.content;
  } catch (error) {
    console.error('API 调用失败:', error.message);
    throw error;
  }
}