> ## Documentation Index
> Fetch the complete documentation index at: https://docs.acedata.cloud/llms.txt
> Use this file to discover all available pages before exploring further.

# Ace Data Cloud SDK 개요

> Platform API guide - Ace Data Cloud

Ace Data Cloud는 TypeScript / Python / Go 세 가지 언어의 공식 클라이언트 SDK를 제공하여 `api.acedata.cloud`에서의 채팅 완성, 이미지, 비디오, 음악, 검색, x402 등의 기능을 강타입 메서드로 캡슐화하여 HTTP, SSE, 작업 폴링, 오류 처리 및 재시도 백오프 작업을 수동으로 작성할 필요를 없앱니다.

이 장은 실제 접속 순서에 따라 구성됩니다: 먼저 콘솔에서 API 토큰을 얻고, 다음으로 언어를 선택하여 해당 장을 보고, 마지막으로 작업 폴링, 스트리밍 응답 및 X402 체인 상 결제의 고급 사용법을 살펴봅니다.

## 저장소 및 패키지

* SDK 소스 코드 (monorepo): [https://github.com/AceDataCloud/SDK](https://github.com/AceDataCloud/SDK)
* TypeScript: [`@acedatacloud/sdk`](https://www.npmjs.com/package/@acedatacloud/sdk)
* Python: [`acedatacloud`](https://pypi.org/project/acedatacloud/)
* Go: [`github.com/AceDataCloud/SDK/go`](https://pkg.go.dev/github.com/AceDataCloud/SDK/go)
* X402 클라이언트 (TypeScript): [`@acedatacloud/x402-client`](https://www.npmjs.com/package/@acedatacloud/x402-client)
* X402 클라이언트 (Python): [`acedatacloud-x402`](https://pypi.org/project/acedatacloud-x402/)

## 세 언어 능력 매트릭스

| 능력 | TypeScript | Python | Go |
| - | - | - | - |
| `chat.completions.create`（비스트리밍） | ✅ | ✅ | ✅ |
| `chat.completions.create`（SSE 스트리밍） | ✅ | ✅ | ✅ |
| `images.generate`（Midjourney / Flux / NanoBanana / Seedream） | ✅ | ✅ | 🚧 (알파) |
| `videos.generate`（Sora / Veo / Luma / Kling / Hailuo / Wan） | ✅ | ✅ | 🚧 (알파) |
| `audios.generate`（Suno / Producer / Fish） | ✅ | ✅ | 🚧 (알파) |
| `search.google`（Serp） | ✅ | ✅ | 🚧 (알파) |
| TaskHandle 비동기 폴링 | ✅（밀리초） | ✅（초） | 🚧 |
| 비동기 클라이언트 | ✅ (Promise) | ✅ (`AsyncAceDataCloud`) | ✅ (`context.Context`) |
| 자동 재시도 + 지수 백오프 | ✅ | ✅ | ✅ |
| 타입화된 예외（`AuthenticationError` / `RateLimitError` …） | ✅ | ✅ | ✅ |
| X402 `paymentHandler` 훅（토큰 없이 체인 결제） | ✅ | ✅ | ❌（계획 중） |

> Go SDK의 멀티미디어 리소스와 작업 폴링은 현재 알파 단계에 있습니다（가짜 버전 `v0.0.0-20260505072132-4a3d921f9bb4`），안정적인 기능은 `chat.completions`입니다. 멀티미디어 시나리오는 TypeScript 또는 Python을 우선 선택하십시오.

## SDK / MCP / 원시 HTTP / X402 사용 시기

| 장면 | 추천 방법 |
| - | - |
| 백엔드 서비스, CLI, 자동화 스크립트, 에이전트 프레임워크 | **SDK**（이 장） |
| Claude Desktop / Cursor / Cline 등의 MCP 클라이언트 호출 | MCP 서버 |
| 일회성 curl 검증, 디버깅, 임베디드 HTTP만 지원하는 환경 | 원시 HTTP（각 서비스의 빠른 시작） |
| API 토큰을 생성하고 싶지 않거나 호출 체인에서 USDC로 결제 | [X402 통합 가이드](https://platform.acedata.cloud/documents/x402-integration) |

SDK와 X402는 상호 배타적이지 않습니다: SDK는 동시에 "토큰 경로"와 "`paymentHandler` 경로"를 지원합니다, 자세한 내용은 [SDK + X402 결제 훅](https://platform.acedata.cloud/documents/sdk-x402-payment)을 참조하십시오.

## API 토큰 신청

SDK를 사용하려면 먼저 [Ace Data Cloud 콘솔 - 애플리케이션 목록](https://platform.acedata.cloud/console/applications)에서 API 토큰을 신청하십시오:

![](https://cdn.acedata.cloud/dvc3cg.jpg)

로그인 또는 등록하지 않은 경우 자동으로 로그인 페이지로 리디렉션되어 등록 및 로그인하라는 초대가 표시됩니다. 로그인 및 등록 후에는 자동으로 현재 페이지로 돌아갑니다.

첫 번째 신청 시 무료 한도가 제공되어 Ace Data Cloud에서 제공하는 다양한 AI 서비스를 무료로 체험할 수 있습니다.

방금 받은 토큰을 복사하여 아래에서 통일하여 `{token}`으로 표기합니다.

## 통일 환경 변수

세 가지 언어의 SDK는 모두 동일한 환경 변수 `ACEDATACLOUD_API_TOKEN`을 자동으로 읽습니다. 셸에서 `export`하여 SDK가 자동으로 가져오도록 하는 것이 좋습니다:

```bash theme={null}
export ACEDATACLOUD_API_TOKEN={token}
# 선택 사항: 기본 https://api.acedata.cloud
# export ACEDATACLOUD_BASE_URL=https://api.acedata.cloud
```

클라이언트를 구성할 때 명시적으로 전달할 수도 있으며, 세 가지 언어에 해당하는 매개변수 이름은 각각 다음과 같습니다:

* TypeScript: `new AceDataCloud({ apiToken: '{token}' })`
* Python: `AceDataCloud(api_token="{token}")`
* Go: `adc.NewClient(adc.WithAPIToken("{token}"))`

> 주의: AceDataCloud 프로젝트 저장소에서는 관례적으로 `ACEDATACLOUD_API_KEY`를 사용하지만（`.env` / CI에서），이 세 가지 SDK는 `ACEDATACLOUD_API_TOKEN`만 인식합니다. 환경에 `ACEDATACLOUD_API_KEY`만 있는 경우 구성 시 명시적으로 전달하십시오.

## 30초 만에 시작하는 세 가지 예

아래 세 개의 코드는 동일한 작업을 수행합니다: `gpt-4o-mini`를 호출하여 정확히 `ADC_*_OK`로 응답하도록 합니다. 각 코드에는 **실제 실행 결과**가 첨부되어 있으며, 자신의 토큰으로 재현할 수 있습니다.

### TypeScript

```ts theme={null}
import { AceDataCloud } from '@acedatacloud/sdk';

const client = new AceDataCloud({ apiToken: process.env.ACEDATACLOUD_API_KEY });

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));
```

> SDK는 현재 응답을 `Record<string, unknown>`으로 선언하고 있으며, 실행 시 일반 JSON 객체로, 필드에 직접 접근할 수 있습니다. 엄격한 TS 프로젝트에서 타입 오류가 발생하면 일시적으로 `as any`를 사용하거나 [SDK 작업 폴링 및 스트리밍 응답](https://platform.acedata.cloud/documents/sdk-tasks-and-streaming)을 참조하여 사용자 정의 타입 래퍼를 만들 수 있습니다.

프로그램 실행 결과:

```text theme={null}
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}
```

### Python

```python theme={null}
import os, time, json
from acedatacloud import AceDataCloud

client = AceDataCloud(api_token=os.environ["ACEDATACLOUD_API_KEY"])

t0 = time.time()
res = client.openai.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Reply with exactly: ADC_PY_SDK_OK"}],
    max_tokens=20,
    temperature=0,
)
print("elapsed_ms", int((time.time() - t0) * 1000))
print("id", res["id"])
print("model", res["model"])
print("content", res["choices"][0]["message"]["content"])
print("usage", json.dumps({k: v for k, v in res["usage"].items()
                            if k in ("prompt_tokens","completion_tokens","total_tokens")}))
```

> Python SDK 현재 반환되는 것은 `dict`이므로 `res["id"]`를 사용하고 `res.id`를 사용하지 않습니다. 이 점은 `openai-python`과 다르므로, 마이그레이션 시 주의해야 합니다.

프로그램 실행 결과:

```text theme={null}
elapsed_ms 2963
id chatcmpl-DldFdnIlhSUXINpupgsUmZL78MnBu
model gpt-4o-mini
content ADC_PY_SDK_OK
usage {"prompt_tokens": 17, "completion_tokens": 7, "total_tokens": 24}
```

### Go

```go theme={null}
package main

import (
    "context"
    "fmt"
    "os"
    "time"

    adc "github.com/AceDataCloud/SDK/go"
)

func main() {
    client, err := adc.NewClient(adc.WithAPIToken(os.Getenv("ACEDATACLOUD_API_KEY")))
    if err != nil {
        panic(err)
    }
    ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
    defer cancel()

    t0 := time.Now()
    res, err := client.OpenAI().Chat().Completions().Create(ctx, adc.ChatCompletionRequest{
        Model:     "gpt-4o-mini",
        Messages:  []map[string]any{{"role": "user", "content": "Reply with exactly: ADC_GO_SDK_OK"}},
        MaxTokens: 20,
    })
    if err != nil {
        panic(err)
    }
    fmt.Println("elapsed_ms", time.Since(t0).Milliseconds())
    fmt.Println("id", res["id"])
    fmt.Println("model", res["model"])
    choices := res["choices"].([]any)
    msg := choices[0].(map[string]any)["message"].(map[string]any)
    fmt.Println("content", msg["content"])
    usage := res["usage"].(map[string]any)
    fmt.Printf("usage prompt=%v completion=%v total=%v\n",
        usage["prompt_tokens"], usage["completion_tokens"], usage["total_tokens"])
}
```

> Go SDK의 응답은 모두 `map[string]any`로 통일되어 있으며, 강타입 구조체가 없으므로 직접 타입 단언을 해야 합니다. 모든 리소스 접근자는 메서드 체인으로: `client.OpenAI().Chat().Completions().Create(...)`입니다.

프로그램 실행 결과:

```text theme={null}
elapsed_ms 6436
id chatcmpl-89DHExvFvBc4ciIPfolZYUOy7ivxv
model gpt-4o-mini
content ADC_GO_SDK_OK
usage prompt=16 completion=5 total=21
```

세 가지 언어의 응답에서 `id`, `elapsed_ms`, `usage`의 출처는 일관되며: PlatformGateway 인증 → 대상 OpenAI 호환 API → 청구 기록 작성. `content` 필드는 모델의 실제 출력이며, 고정 식별자 `ADC_*_OK`를 사용하여 응답이 SDK에 의해 변조되지 않았음을 증명합니다.

## 추천 읽기 순서

1. [TypeScript SDK 접속 튜토리얼](https://platform.acedata.cloud/documents/sdk-typescript) —— `npm install` 후 첫 번째 단락에서 실행할 수 있는 코드.
2. [Python SDK 접속 튜토리얼](https://platform.acedata.cloud/documents/sdk-python) —— 동기, 비동기, 스트리밍 세 가지 사용법.
3. [Go SDK 접속 튜토리얼](https://platform.acedata.cloud/documents/sdk-go) —— Go 스타일의 `context.Context`와 채널 스트리밍.
4. [SDK 작업 폴링 및 스트리밍 응답](https://platform.acedata.cloud/documents/sdk-tasks-and-streaming) —— TaskHandle 단위 차이, SSE 구현 세부사항, 재시도 백오프.
5. [SDK + X402 결제 훅](https://platform.acedata.cloud/documents/sdk-x402-payment) —— 토큰 없이 호출에 따라 블록체인 정산.

## 잔여 한도 확인 방법

[Ace Data Cloud 콘솔 - 애플리케이션 목록](https://platform.acedata.cloud/console/applications)을 통해 현재 계정의 잔여 한도를 확인할 수 있습니다.

[Ace Data Cloud 콘솔 - 사용 이력](https://platform.acedata.cloud/console/usages)을 통해 모든 사용 이력과 요금 세부사항을 확인할 수 있습니다.

## 더 알아보기

* 📦 [SDK 모노레포 소스코드](https://github.com/AceDataCloud/SDK)
* 🔌 [X402 통합 가이드](https://platform.acedata.cloud/documents/x402-integration)
* 🛠 MCP 서버 튜토리얼
* 📊 [서비스 목록 및 가격](https://platform.acedata.cloud/services)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.