TypeScript SDK Integration Tutorial

@acedatacloud/sdk is the official Ace Data Cloud TypeScript / JavaScript SDK. It encapsulates all services on api.acedata.cloud into typed methods such as client.openai.chat.completions.create(...), client.images.generate(...), and client.search.google(...), with built-in SSE streaming, retry backoff, and typed exceptions.

It can be used in Node.js, Deno, Bun, and modern browsers (with a bundler).

Source code and package addresses:

Installation

npm install @acedatacloud/sdk
# Or pnpm add / yarn add / bun add

If X402 on-chain payment is needed (the no-API-Token path), install one more:

npm install @acedatacloud/x402-client ethers

Version check output from a clean npm project:

$ npm ls @acedatacloud/sdk
└── @acedatacloud/sdk@2026.504.2

$ node -e "console.log(require('@acedatacloud/sdk').AceDataCloud?.name)"
AceDataCloud

Result explanation:

  • The package version is 2026.504.2 (CalVer, the 2nd revision of the 504th ISO week of 2026).
  • AceDataCloud is the main class used to construct the client, accessible from the default export.

Prepare the API Token

Refer to SDK Overview - Apply for an API Token to obtain a token, then export it in the shell:

export ACEDATACLOUD_API_TOKEN={token}

If apiToken is not passed when constructing the client, the SDK automatically reads the ACEDATACLOUD_API_TOKEN environment variable. If ACEDATACLOUD_API_KEY has already been stored in your environment (the project repository convention), you can pass it explicitly: new AceDataCloud({ apiToken: process.env.ACEDATACLOUD_API_KEY }).

Example 1: chat.completions (non-streaming)

import { AceDataCloud } from '@acedatacloud/sdk';

const client = new AceDataCloud();

const t0 = Date.now();
const res = await client.openai.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [
    { role: 'user', content: 'Reply with exactly: ADC_TS_SDK_OK' }
  ],
  max_tokens: 20,
  temperature: 0
});
console.log('elapsed_ms', Date.now() - t0);
console.log('id', res.id);
console.log('model', res.model);
console.log('content', res.choices[0].message.content);
console.log('usage', JSON.stringify(res.usage));

Program output:

elapsed_ms 2543
id chatcmpl-DldCcLvkTFaioST8e6SjOl0wJScQA
model gpt-4o-mini
content ADC_TS_SDK_OK
usage {"prompt_tokens":16,"completion_tokens":6,"total_tokens":22}

Result explanation:

  • id chatcmpl-DldCcLvkTFaioST8e6SjOl0wJScQA is an OpenAI-compatible response ID. You can search for the corresponding record in the console usage history.
  • content ADC_TS_SDK_OK is the fixed identifier actually returned by the model, proving that the response was not tampered with by the SDK.
  • One chat completion consumes approximately 22 tokens, billed at the gpt-4o-mini unit price.
  • The SDK declares the response as Record<string, unknown>. At runtime, it is a JSON object, and dot access such as .id / .choices[0].message.content works in .mjs, Node REPL, and Bun; in strict TypeScript projects, (res as any).id may be needed, or noImplicitAny can be disabled in tsconfig.

Example 2: chat.completions (SSE streaming)

After enabling stream: true, create returns an asynchronous iterator, and each frame is a ChatCompletionChunk.

import { AceDataCloud } from '@acedatacloud/sdk';

const client = new AceDataCloud();

const t0 = Date.now();
let firstChunkMs: number | null = null;
let chunks = 0;
const collected: string[] = [];

const stream = await client.openai.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [
    { role: 'user', content: 'Count from 1 to 5, separated by single spaces, no extra text.' }
  ],
  max_tokens: 20,
  stream: true
});

for await (const chunk of stream) {
  if (firstChunkMs === null) firstChunkMs = Date.now() - t0;
  chunks++;
  const delta = chunk.choices[0]?.delta?.content;
  if (delta) collected.push(delta);
}

console.log('total_elapsed_ms', Date.now() - t0);
console.log('first_chunk_ms', firstChunkMs);
console.log('chunks', chunks);
console.log('collected', collected.join('').trim());

Program output:

total_elapsed_ms 2616
first_chunk_ms 2481
chunks 13
collected 1 2 3 4 5

Result explanation:

  • The first-frame latency of 2481 ms is the time for the model to generate the first token; all subsequent 12 frames arrived within 135 ms.
  • The 13 frames combined are "1 2 3 4 5", with each token in a separate frame + the final frame containing finish_reason.
  • Streaming does not save more tokens than non-streaming, but the first-character latency is significantly reduced, making it suitable for real-time UI.

Example 3: images.generate (NanoBanana)

client.images.generate({ provider: 'nano-banana', ... }) directly returns synchronously, and does not need the wait parameter—the NanoBanana API itself generates synchronously.

import { AceDataCloud } from '@acedatacloud/sdk';

const client = new AceDataCloud();

const t0 = Date.now();
const img = await client.images.generate({
  provider: 'nano-banana',
  prompt: 'A minimalist logo of a yellow banana on a white background, flat design'
});
console.log('elapsed_ms', Date.now() - t0);
console.log('task_id', img.task_id);
console.log('trace_id', img.trace_id);
console.log('image_url', img.data[0].image_url);

Program output:

elapsed_ms 16634
task_id 8e4b44a6-5ece-46a4-9013-9e0c8aca2217
trace_id 9529e241-54fe-40da-98a2-871e14989fb5
image_url https://platform.cdn.acedata.cloud/nanobanana/331be1d3-3330-4196-bd1c-aa75717c549c.png

Result explanation:

  • image_url is a stable address on the CDN, which can be directly used with <img src> or downloaded.
  • Most of the 16.6 seconds is model inference time; local SDK overhead is negligible.
  • trace_id is the request ID assigned by the platform. If there is a problem, providing this ID to customer service allows for the fastest diagnosis.
  • For asynchronous services (Midjourney, Sora, Veo, etc.), TaskHandle polling is required. See SDK Task Polling and Streaming Responses for details.

Example 4: Typed error handling

The SDK throws errors as specific subclasses according to HTTP status (AuthenticationError / BadRequestError / RateLimitError / InternalServerError / APIConnectionError, etc.), and instanceof can be used for precise branching.

import { AceDataCloud, AuthenticationError } from '@acedatacloud/sdk';

const bad = new AceDataCloud({ apiToken: 'definitely-not-a-real-token' });

try {
  await bad.openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [{ role: 'user', content: 'hi' }],
    max_tokens: 5
  });
} catch (err: any) {
  console.log('err_class', err.constructor.name);
  console.log('status', err.statusCode);
  console.log('code', err.code);
  console.log('instanceof AuthenticationError =', err instanceof AuthenticationError);
}

Program output:

A. err_class AuthenticationError
A. status 401
A. code invalid_token
A. instanceof AuthenticationError = true

Result explanation:

  • 401 is automatically mapped to AuthenticationError, and business code can use instanceof for precise branching.
  • code: invalid_token indicates that the API Key is invalid; please check the credentials.
  • Likewise, 429 → RateLimitError, 400 → BadRequestError, 5xx → InternalServerError.

Example 5: Multi-Model Routing

The same client can switch freely between multiple services, as long as the model name is consistent.

import { AceDataCloud } from '@acedatacloud/sdk';

const client = new AceDataCloud();

const MODELS = ['gpt-4o-mini', 'gemini-2.5-flash', 'deepseek-flash', 'grok-3-fast'];

for (const model of MODELS) {
  const t0 = Date.now();
  try {
    const r = await client.openai.chat.completions.create({
      model,
      messages: [{ role: 'user', content: 'Reply with exactly: ADC_OK' }],
      max_tokens: 5
    });
    console.log(model.padEnd(28), `${Date.now() - t0}ms`, `content="${r.choices[0].message.content}"`);
  } catch (err: any) {
    console.log(model.padEnd(28), `${Date.now() - t0}ms`, 'ERR', err.statusCode, err.code);
  }
}

Excerpt from the program output:

gpt-4o-mini                  2189ms   content="ADC_OK"
gemini-2.5-flash             2569ms   content=""
grok-3-fast                  3598ms   content="ADC_OK"

Result explanation:

  • One codebase and one token cover four types of model services: OpenAI / Google / DeepSeek / xAI.
  • gemini-2.5-flash did not return ADC_OK this time, due to differences in the model's own output style—the SDK does not silently swallow anything and faithfully passes the model's original response through to the business layer.
  • Pricing is based on the per-token rate of each model.
import { AceDataCloud } from '@acedatacloud/sdk';

const client = new AceDataCloud();

const t0 = Date.now();
const r = await client.search.google({
  query: 'Ace Data Cloud',
  resource: 'web'
});
const items = (r as any).organic ?? [];
console.log('elapsed_ms', Date.now() - t0);
console.log('organic_count', items.length);
items.slice(0, 2).forEach((it: any, i: number) => {
  console.log(`#${i + 1}`, it.title, '->', it.link);
});

Program output:

elapsed_ms 2382
organic_count 10
#1 Ace Data Cloud -> https://platform.acedata.cloud/
#2 Ace Data Cloud - GitHub -> https://github.com/acedatacloud

Result explanation:

  • One request retrieves 10 organic results, with the field name organic (not organic_results).
  • Search goes through the Serp service and is charged per request.
  • The same client instance can both chat and search; one token is enough.

Configuration Options

const client = new AceDataCloud({
  // One of these is required: an explicit token or the ACEDATACLOUD_API_TOKEN environment variable
  apiToken: process.env.MY_TOKEN,

  // Platform API root URL, defaults to https://api.acedata.cloud
  baseURL: 'https://api.acedata.cloud',

  // Some services (such as dashboard metadata) use the platform domain
  platformBaseURL: 'https://platform.acedata.cloud',

  // Timeout for a single request, in milliseconds; defaults to 300_000 (5 minutes)
  timeout: 300_000,

  // Number of automatic retries, defaults to 2; retry conditions: 408 / 409 / 429 / 5xx / network errors
  maxRetries: 2,

  // Custom request headers
  defaultHeaders: { 'x-app': 'my-service/1.0' }
});

Browser Usage

@acedatacloud/sdk is an ESM + ISO (isomorphic) package that can be directly imported in modern browsers with a bundler. Note: do not hardcode the API Token in frontend code. For the frontend, it is recommended to:

  1. Use X402 paymentHandler — the user's wallet signs USDC per request, with no token required.
  2. Or use the SDK on your own server, and let the browser call only your own backend.

Advanced: Task Polling and Streaming Responses

  • Task-based services (Midjourney, Sora, Veo, Suno): use TaskHandle for polling; see SDK Task Polling and Streaming Responses for units, timeouts, and retry details.
  • Streaming chat: demonstrated in Example 2 on this page; streaming audio / video is also supported.

Advanced: X402 Payment Hook

If you do not want to apply for an API Token and want to pay on-chain per request, you can use paymentHandler:

import { AceDataCloud } from '@acedatacloud/sdk';
import { createX402PaymentHandler } from '@acedatacloud/x402-client';

const client = new AceDataCloud({
  paymentHandler: createX402PaymentHandler({
    network: 'base',
    evmProvider: (window as any).ethereum,  // EIP-1193 provider, or viem walletClient
    evmAddress: userAddress
  })
});

On the TypeScript side, createX402PaymentHandler accepts { network, evmProvider, evmAddress, preferScheme? } (EVM chains) or { network: 'solana', solanaWallet } (Solana). When a Node server does not have window.ethereum, use viem's createWalletClient (based on a private key) to wrap an EIP-1193-compatible provider and pass it in; see SDK + X402 Payment Hook for detailed instructions and actual on-chain results.

How to Check Remaining Credits

You can view the remaining credits of the current account through Ace Data Cloud Console - Application List.

You can view all usage history and billing details through Ace Data Cloud Console - Usage History.

Learn More