Node.js SDK

Node.js SDK 安装和使用指南

Node.js SDK

艾塔达克官方 Node.js SDK,支持 Node.js 18+。

安装

npm install @atdak/sdk
# 或
yarn add @atdak/sdk
# 或
pnpm add @atdak/sdk

初始化

import { AtdakClient } from '@atdak/sdk';

// 使用 API Key 初始化
const client = new AtdakClient({
  apiKey: 'YOUR_API_KEY'
});

// 或从环境变量读取(推荐)
// ATDAK_API_KEY=YOUR_API_KEY
const client = new AtdakClient();

Chat Completions

// 基础对话
const response = await client.chat.completions.create({
  model: 'atdak-gpt-4',
  messages: [
    { role: 'system', content: '你是一个专业的助手' },
    { role: 'user', content: '解释什么是机器学习' }
  ]
});
console.log(response.choices[0].message.content);

// 流式输出
const stream = await client.chat.completions.create({
  model: 'atdak-gpt-4',
  messages: [{ role: 'user', content: '写一个故事' }],
  stream: true
});

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

图像分析

const response = await client.chat.completions.create({
  model: 'atdak-gpt-4-vision',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: '描述这张图片' },
        {
          type: 'image_url',
          image_url: { url: 'https://example.com/image.jpg' }
        }
      ]
    }
  ]
});
console.log(response.choices[0].message.content);

语音识别

import fs from 'fs';

const transcription = await client.audio.transcriptions.create({
  model: 'atdak-whisper',
  file: fs.createReadStream('audio.mp3')
});
console.log(transcription.text);

语音合成

const response = await client.audio.speech.create({
  model: 'atdak-tts',
  voice: 'alloy',
  input: '你好,欢迎使用艾塔达克'
});

const buffer = Buffer.from(await response.arrayBuffer());
fs.writeFileSync('output.mp3', buffer);

文本向量化

const response = await client.embeddings.create({
  model: 'atdak-embedding',
  input: ['你好世界', '机器学习入门']
});

response.data.forEach(item => {
  console.log(item.embedding.slice(0, 5)); // 打印前5维
});

错误处理

import { AtdakError, RateLimitError, AuthenticationError } from '@atdak/sdk';

try {
  const response = await client.chat.completions.create({...});
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.log('API Key 无效');
  } else if (error instanceof RateLimitError) {
    console.log('超出速率限制,请稍后重试');
  } else if (error instanceof AtdakError) {
    console.log(`API 错误: ${error.message}`);
  }
}

TypeScript 支持

SDK 完全使用 TypeScript 编写,提供完整的类型定义:

import type { 
  ChatCompletion, 
  ChatCompletionMessage,
  ChatCompletionCreateParams 
} from '@atdak/sdk';

const params: ChatCompletionCreateParams = {
  model: 'atdak-gpt-4',
  messages: [{ role: 'user', content: '你好' }]
};

const response: ChatCompletion = await client.chat.completions.create(params);