开发者文档

AI Gateway 客户端 SDK

企业级AI统一接入平台提供官方客户端 SDK,帮助业务系统快速接入全栈AI能力

支持的编程语言

语言 包名 最低版本 安装方式
Node.js @aigateway/sdk Node 18+ npm / yarn / pnpm
Java com.aigateway:aigateway-sdk Java 11+ Maven / Gradle

快速开始

Node.js SDK

安装

bash
npm install @aigateway/sdk
# 或
yarn add @aigateway/sdk
# 或
pnpm add @aigateway/sdk

初始化

typescript
import { AIClient } from '@aigateway/sdk';

const client = new AIClient({
  apiKey: 'ak-your-api-key',                        // 必填: API Key
  baseURL: 'https://api.aigateway.company.com',     // 可选: 网关地址
  timeout: 30000,                                   // 可选: 超时时间(ms)
  maxRetries: 3,                                    // 可选: 最大重试次数
});

从环境变量初始化

bash
export AIGATEWAY_API_KEY="ak-your-api-key"
export AIGATEWAY_BASE_URL="https://api.aigateway.company.com"
typescript
const client = AIClient.fromEnv();

LLM 对话

typescript
const response = await client.llm.chat({
  model: 'gpt-4o',
  messages: [
    { role: 'system', content: '你是一个有帮助的助手' },
    { role: 'user', content: '请介绍一下Go语言' }
  ],
  temperature: 0.7,
  maxTokens: 2048
});

console.log(response.data.choices[0].message.content);
console.log('Token用量:', response.data.usage.totalTokens);

流式对话

typescript
const stream = await client.llm.chatStream({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: '你好' }]
});

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

OCR 发票识别

typescript
import * as fs from 'fs';

const result = await client.ocr.invoice({
  image: fs.readFileSync('./invoice.jpg'),
  options: { enhance: true, language: 'zh' }
});

console.log(result.data.results.invoice_code);
console.log(result.data.confidence);

Java SDK

Maven 依赖

xml
<dependency>
    <groupId>com.aigateway</groupId>
    <artifactId>aigateway-sdk</artifactId>
    <version>1.0.0</version>
</dependency>

Gradle 依赖

groovy
implementation 'com.aigateway:aigateway-sdk:1.0.0'

初始化

java
import com.aigateway.sdk.AIClient;

AIClient client = AIClient.builder()
    .apiKey("ak-your-api-key")
    .baseURL("https://api.aigateway.company.com")
    .timeout(30000)
    .maxRetries(3)
    .build();

从环境变量初始化

bash
export AIGATEWAY_API_KEY="ak-your-api-key"
export AIGATEWAY_BASE_URL="https://api.aigateway.company.com"
java
AIClient client = AIClient.fromEnv();

LLM 对话

java
import com.aigateway.sdk.model.*;

ChatCompletionRequest request = ChatCompletionRequest.builder()
    .model("gpt-4o")
    .addMessage(Message.system("你是一个有帮助的助手"))
    .addMessage(Message.user("请介绍一下Go语言"))
    .temperature(0.7)
    .maxTokens(2048)
    .build();

StandardResponse<ChatCompletionResponse> response = client.llm().chat(request);
System.out.println(response.getData().getChoices().get(0).getMessage().getContent());
System.out.println("Token用量: " + response.getData().getUsage().getTotalTokens());

流式对话

java
client.llm().chatStream(request, new StreamCallback() {
    @Override
    public void onChunk(ChatCompletionChunk chunk) {
        String content = chunk.getChoices().get(0).getDelta().getContent();
        if (content != null) System.out.print(content);
    }

    @Override
    public void onComplete() {
        System.out.println("\n流结束");
    }
});

OCR 发票识别

java
import java.io.File;

File image = new File("./invoice.jpg");
StandardResponse<OCRInvoiceResult> result = client.ocr().invoice(
    image,
    OCRInvoiceOptions.builder()
        .enhance(true)
        .language("zh")
        .build()
);

System.out.println("发票代码: " + result.getData().getResults().getInvoiceCode());
System.out.println("置信度: " + result.getData().getConfidence());

功能特性

支持的能力

能力 Node.js Java 说明
LLM 同步对话标准对话补全
LLM 流式对话SSE 流式输出
OCR 发票识别增值税发票识别
OCR 仓库单据出入库单据识别
OCR 通用识别通用文字识别
模型列表查询获取可用模型
用量统计查询多维度用量分析
语音识别语音转文字
语音合成文字转语音
图像生成AI 生成图像
Embedding文本向量化

内置功能

  • 自动重试 — 对 429/500/502/503/504 错误自动指数退避重试
  • 连接池 — 复用 HTTP 连接,提升性能
  • 超时控制 — 可配置请求超时时间
  • 类型安全 — 完整的 TypeScript / Java 类型定义
  • 流式支持 — 原生支持 LLM 流式响应
  • 环境变量 — 支持从环境变量读取配置
  • 拦截器 — 支持自定义请求/响应拦截器

错误处理

Node.js

typescript
import { AIException, AuthenticationException, QuotaExceededException } from '@aigateway/sdk';

try {
  const response = await client.llm.chat({...});
} catch (error) {
  if (error instanceof AuthenticationException) {
    console.error('API Key 无效:', error.message);
  } else if (error instanceof QuotaExceededException) {
    console.error('配额不足:', error.message);
  } else if (error instanceof AIException) {
    console.error('AI 平台错误:', error.code, error.message);
  } else {
    console.error('未知错误:', error);
  }
}

Java

java
try {
    StandardResponse<ChatCompletionResponse> response = client.llm().chat(request);
} catch (AIException e) {
    switch (e.getCode()) {
        case 40101:
            System.err.println("API Key 无效: " + e.getMessage());
            break;
        case 40201:
        case 42901:
            System.err.println("配额不足: " + e.getMessage());
            break;
        default:
            System.err.println("AI 平台错误: [" + e.getCode() + "] " + e.getMessage());
    }
}

配置项

配置项 类型 必填 默认值 说明
apiKey string - 平台分配的 API Key
baseURL string https://api.aigateway.company.com 网关地址
timeout number 30000 请求超时时间(毫秒)
maxRetries number 3 最大重试次数
retryDelay number 1000 重试基础延迟(毫秒)
retryMultiplier number 2.0 指数退避乘数
maxRetryDelay number 30000 最大重试延迟(毫秒)

获取 API Key

请联系平台管理员获取 API Key。每个 API Key 关联特定的部门和项目,具有独立的配额限制。

更多资源

版本: v1.0.0  |  更新日期: 2026-05-26

客服二维码
扫码添加客服微信,获取专属解决方案
客服二维码
扫码添加客服微信,获取专属解决方案