JavaScript/TypeScript SDK

强大的JavaScript SDK,完美支持Node.js、浏览器和各种前端框架

Node.js 14+TypeScriptESM & CJSReact/Vue/Angular

安装

使用npm

终端
npm install openai

使用yarn

yarn add openai

使用pnpm

pnpm add openai

TypeScript支持:SDK自带TypeScript类型定义,无需额外安装@types包。

快速开始

Node.js环境

// CommonJS
const OpenAI = require('openai');

// ES Modules (推荐)
import OpenAI from 'openai';

// 初始化客户端
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY || 'your-api-key',
  baseURL: 'https://api.n1n.ai/v1'  // 使用n1n.ai端点
});

// 基础对话
async function chat() {
  const completion = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "Hello, how are you?" }
    ]
  });
  
  console.log(completion.choices[0].message.content);
}

chat();

TypeScript示例

import OpenAI from 'openai';
import { 
  ChatCompletionMessage,
  ChatCompletionMessageParam 
} from 'openai/resources/chat';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY!,
  baseURL: 'https://api.n1n.ai/v1'
});

interface ChatOptions {
  model?: string;
  temperature?: number;
  maxTokens?: number;
}

async function createChat(
  messages: ChatCompletionMessageParam[],
  options: ChatOptions = {}
): Promise<string> {
  const completion = await openai.chat.completions.create({
    model: options.model || "gpt-3.5-turbo",
    messages,
    temperature: options.temperature || 0.7,
    max_tokens: options.maxTokens
  });
  
  return completion.choices[0].message.content || '';
}

// 使用示例
const response = await createChat([
  { role: "user", content: "Explain TypeScript in one sentence" }
]);

浏览器环境

安全提醒:不要在前端直接暴露API密钥!建议通过后端代理API请求。

// 前端通过后端代理调用
async function callAPI(message) {
  const response = await fetch('/api/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ message })
  });
  
  const data = await response.json();
  return data.reply;
}

// 后端API路由 (Next.js示例)
// pages/api/chat.js 或 app/api/chat/route.js
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY
});

export async function POST(request) {
  const { message } = await request.json();
  
  const completion = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",
    messages: [{ role: "user", content: message }]
  });
  
  return Response.json({ 
    reply: completion.choices[0].message.content 
  });
}

高级功能

流式响应

// Node.js流式响应
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY
});

async function streamChat() {
  const stream = await openai.chat.completions.create({
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: 'Tell me a story' }],
    stream: true,
  });

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

// 浏览器中处理流式响应
async function streamInBrowser() {
  const response = await fetch('/api/stream', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ message: 'Tell me a story' })
  });

  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);
    // 更新UI
    updateUI(chunk);
  }
}

错误处理

import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  maxRetries: 3,  // 自动重试
});

async function safeChat(message) {
  try {
    const completion = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: message }]
    });
    
    return completion.choices[0].message.content;
  } catch (error) {
    if (error instanceof OpenAI.APIError) {
      console.error('API Error:', error.status, error.message);
      
      if (error.status === 401) {
        throw new Error('Invalid API key');
      } else if (error.status === 429) {
        throw new Error('Rate limit exceeded');
      } else if (error.status >= 500) {
        throw new Error('Server error, please retry');
      }
    }
    
    throw error;
  }
}

// 使用AbortController取消请求
const controller = new AbortController();

const promise = openai.chat.completions.create({
  model: 'gpt-3.5-turbo',
  messages: [{ role: 'user', content: 'Hello' }]
}, {
  signal: controller.signal
});

// 取消请求
setTimeout(() => controller.abort(), 1000);

函数调用

// 定义函数
const functions = [
  {
    name: 'get_weather',
    description: 'Get the current weather',
    parameters: {
      type: 'object',
      properties: {
        location: {
          type: 'string',
          description: 'The city and state'
        },
        unit: {
          type: 'string',
          enum: ['celsius', 'fahrenheit']
        }
      },
      required: ['location']
    }
  }
];

// 实现函数
async function getWeather(location, unit = 'celsius') {
  // 实际调用天气API
  return JSON.stringify({
    location,
    temperature: 22,
    unit,
    description: 'Sunny'
  });
}

// 使用函数调用
const response = await openai.chat.completions.create({
  model: 'gpt-3.5-turbo',
  messages: [
    { role: 'user', content: "What's the weather in New York?" }
  ],
  functions,
  function_call: 'auto'
});

const message = response.choices[0].message;

if (message.function_call) {
  const functionName = message.function_call.name;
  const functionArgs = JSON.parse(message.function_call.arguments);
  
  let functionResult;
  if (functionName === 'get_weather') {
    functionResult = await getWeather(
      functionArgs.location,
      functionArgs.unit
    );
  }
  
  // 将函数结果发送回模型
  const secondResponse = await openai.chat.completions.create({
    model: 'gpt-3.5-turbo',
    messages: [
      { role: 'user', content: "What's the weather in New York?" },
      message,
      {
        role: 'function',
        name: functionName,
        content: functionResult
      }
    ]
  });
  
  console.log(secondResponse.choices[0].message.content);
}

React集成示例

import { useState, useCallback } from 'react';

// 自定义Hook
function useChat() {
  const [messages, setMessages] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const sendMessage = useCallback(async (content) => {
    setIsLoading(true);
    setError(null);
    
    // 添加用户消息
    const userMessage = { role: 'user', content };
    setMessages(prev => [...prev, userMessage]);
    
    try {
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: [...messages, userMessage]
        })
      });
      
      if (!response.ok) throw new Error('API request failed');
      
      const data = await response.json();
      
      // 添加AI响应
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: data.reply
      }]);
    } catch (err) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  }, [messages]);

  const clearMessages = useCallback(() => {
    setMessages([]);
  }, []);

  return {
    messages,
    isLoading,
    error,
    sendMessage,
    clearMessages
  };
}

// React组件
function ChatComponent() {
  const { messages, isLoading, error, sendMessage } = useChat();
  const [input, setInput] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (input.trim()) {
      sendMessage(input);
      setInput('');
    }
  };

  return (
    <div className="chat-container">
      <div className="messages">
        {messages.map((msg, index) => (
          <div key={index} className={`message ${msg.role}`}>
            {msg.content}
          </div>
        ))}
        {isLoading && <div className="loading">AI正在思考...</div>}
        {error && <div className="error">{error}</div>}
      </div>
      
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="输入消息..."
          disabled={isLoading}
        />
        <button type="submit" disabled={isLoading}>
          发送
        </button>
      </form>
    </div>
  );
}

配置选项

选项类型说明
apiKeystringAPI密钥
baseURLstringAPI基础URL
timeoutnumber请求超时(毫秒)
maxRetriesnumber最大重试次数
httpAgentAgent自定义HTTP代理

最佳实践

环境变量管理

使用.env文件管理敏感信息:

OPENAI_API_KEY=sk-xxxx
OPENAI_BASE_URL=https://api.n1n.ai/v1

类型安全

使用TypeScript获得完整的类型推导和自动补全

性能优化

  • • 复用OpenAI实例
  • • 使用流式响应
  • • 实施请求缓存

错误处理

  • • 捕获所有异常
  • • 实现重试逻辑
  • • 用户友好的错误提示