TOP AI SDK Integration Tutorial: Python, Node.js, Anthropic SDK, Vercel AI & LangChain
A hands-on systems engineering guide to wiring five production stacks—OpenAI Python SDK, OpenAI Node/TypeScript (Next.js App Router SSE + Zod), Official Anthropic SDK with cache_control and count_tokens, Vercel AI SDK, and LangChain plus n8n—into TOP AI's dual-protocol gateway without custom wrappers, backed by real streaming TTFT benchmarks and honest framework trade-offs.
Dimas Harjanto
•
Getting a single test completion back from a `curl` command is easy. Shipping an AI integration that survives real production traffic—async worker pools in Python, Next.js App Router streams that cancel cleanly when users close tabs, strict JSON extraction that never breaks downstream parsers, prompt caching that cuts input bills on long system instructions, and n8n automations that stop timing out halfway through a database lookup—is where teams burn weeks maintaining brittle custom HTTP wrappers.
If you do not have an account or a `tp-` key yet, start with the five-minute [TOP AI quickstart tutorial covering signup, API keys, and your first request](/en/blog/top-ai-quickstart-tutorial-signup-api-key-first-request). This **TOP AI SDK integration tutorial** picks up right after hello-world and walks through complete, copy-ready production implementations across all five dominant developer stacks: the OpenAI Python SDK, the OpenAI Node/TypeScript SDK (Next.js App Router SSE + Zod), the Official Anthropic SDK (Python and TypeScript with `cache_control` and `/v1/messages/count_tokens`), the Vercel AI SDK (`createOpenAI`, `streamText`, and `useChat`), and LangChain (`ChatOpenAI`) alongside the n8n AI Agent node.
> **Engineering TL;DR:** Export your `tp-` key as `TOPAI_API_KEY` on the server only. Point OpenAI-compatible SDKs to `https://topai.id/v1` (`Authorization: Bearer tp-...`) and official Anthropic SDKs to `https://topai.id` **without** `/v1` (`x-api-key: tp-...`). Every completion returns standard SDK payloads plus a `topai` telemetry block (`charged_gp`, `balance_after`, `upstream`, `failover`, `latency_ms`) so you get exact cost attribution with zero extra API round trips.
We will also examine real streaming Time-to-First-Token (TTFT) overhead numbers across all five client layers—from **395 ms** on raw `fetch()` up to **486 ms** inside LangChain's `ChatOpenAI`—so your stack choice rests on measured latency and debugging clarity rather than hype. Keep the official reference at [/en/docs](/en/docs) and live token rates at [/en/pricing](/en/pricing) open alongside this guide as you wire up each service.
---
## Why Dual-Protocol Beats Lowest-Common-Denominator Gateways
Many multi-model API gateways try to simplify their own backend by forcing every provider—including Anthropic's Claude family—through a single OpenAI `/chat/completions` translation layer. On paper that looks tidy. In production it strips away the exact features that make Claude cost-effective on large contexts: structured multi-block `system` arrays with `cache_control` breakpoints, explicit `stop_sequences`, native Anthropic `tools` semantics, and zero-cost preflight token validation through `/v1/messages/count_tokens`.
TOP AI avoids that trap by running two first-class native protocol surfaces in front of its routing, failover, and prepaid ledger engine—an architecture we unpack at the platform level in our [unified AI gateway field guide](/en/blog/unified-ai-gateway-field-guide-2026). OpenAI-dialect clients talk to `https://topai.id/v1`, while native Anthropic SDKs talk to `https://topai.id`. Both share the same `tp-` credentials, the same prepaid TOP Points wallet (`1 TP = Rp 1`), and the same automatic upstream failover.

Memorizing the boundary between these two contracts prevents the two most frequent integration mistakes we see in engineering tickets: trailing `/v1` duplication on Anthropic clients and misparsed error envelopes when a codebase mixes both SDKs.
| Contract Dimension | OpenAI-Compatible Surface | Anthropic-Native Surface | Production Notes & Current Status |
| :--- | :--- | :--- | :--- |
| **Base URL** | `https://topai.id/v1` | `https://topai.id` | Never append `/v1` on Anthropic SDKs (creates `/v1/v1/messages` -> `404`) |
| **Auth Header** | `Authorization: Bearer tp-...` | `x-api-key: tp-...` | Handled automatically by both official SDKs from the same `tp-` key |
| **Live Production Endpoints** | `/chat/completions`, `/models`, `/images/generations` | `/v1/messages`, `/v1/messages/count_tokens` | Backed by one prepaid balance and unified per-key governance |
| **Roadmap Endpoints** | `/embeddings`, `/audio/speech`, `/audio/transcriptions` | — | Currently marked *Coming Soon* in integration docs; keep a separate adapter if needed today |
| **Protocol-Specific Features** | `response_format`, `tools`, `tool_choice`, `stream_options` | `system` blocks, required `max_tokens`, `stop_sequences`, `tools`, `cache_control` | Use Anthropic native whenever prompt caching or preflight token counting matters |
| **Error Payload Shape** | `{ "error": { "message", "type", "code", "param" } }` | `{ "type": "error", "error": { "type", "message" } }` | Normalize both error shapes inside shared logging middleware |
| **Inline Billing Telemetry** | `topai` object on response | `topai` object on response | Zero extra calls: `charged_gp`, `balance_after`, `upstream`, `failover`, `latency_ms` |
One candid operational note before you migrate an entire monorepo in a single pull request: while the broader OpenAI specification includes `/embeddings`, `/audio/speech`, `/audio/transcriptions`, and `/responses`, TOP AI's current integration docs explicitly flag those four routes as **Coming Soon**. Everything centered on chat completions, reasoning, structured extraction, tool calling, streaming, preflight token counting, and image generation (`/v1/images/generations`) is live for production traffic today. If your RAG pipeline needs embeddings or Whisper transcription right now, isolate those calls behind a thin internal interface so you can flip their base URL in one line once those routes reach general availability.
### Zero-Extra-Call Cost Telemetry Inside Every Response
Most gateways make accurate per-tenant billing surprisingly annoying: you finish a completion, wait a second for their analytics pipeline to settle, and fire a second HTTP request just to ask what that generation cost. TOP AI returns settled billing and routing metadata inline inside every completion payload:
```json
{
"id": "chatcmpl-7a91e4b2",
"object": "chat.completion",
"model": "claude-sonnet-5-5",
"choices": [
{
"index": 0,
"message": { "role": "assistant", "content": "..." },
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 518,
"completion_tokens": 214,
"total_tokens": 732
},
"topai": {
"charged_gp": 54,
"balance_after": 49946,
"upstream": "anthropic",
"failover": false,
"latency_ms": 1126
}
}
```
Each of those five fields directly eliminates boilerplate in production services:
- **`charged_gp`**: Exact TOP Points atomically debited for the call. Write it directly to your customer usage ledger without currency conversion drift or stale local pricing tables.
- **`balance_after`**: Your remaining account wallet right after settlement. Trigger a low-balance webhook alert from your response middleware (for example when `balance_after < 500000`) instead of polling `/v1/balance` on a cron schedule.
- **`upstream`**: Identifies the upstream provider that actually served the call, essential when auditing routing behavior as covered in [understanding Smart Router per-request vs per-token modes](/en/blog/understanding-smart-router-per-request-vs-per-token).
- **`failover`**: Boolean flag telling you whether TOP AI transparently rerouted your request to a healthy backup upstream—the resilience layer detailed in our [zero-downtime multi-provider AI failover architecture](/en/blog/zero-downtime-multi-provider-ai-failover-architecture).
- **`latency_ms`**: End-to-end gateway processing time in milliseconds. Subtracting `latency_ms` from your client-measured wall clock immediately isolates whether a latency regression lives in your local network, your SDK layer, or the upstream model.
---
## Streaming TTFT Overhead Benchmark: What Each SDK Layer Costs You
Engineers routinely choose an AI client library based on README ergonomics and never measure what that abstraction adds to perceived responsiveness. In batch summarization jobs, an extra 80 milliseconds does not matter. In interactive chat, IDE inline completions, or voice pipelines, **Time to First Token (TTFT)** is the single number users actually feel.
To separate client-side overhead from model generation variance, we measured streaming TTFT against the same TOP AI endpoint using warm persistent connections (post-TLS handshake), identical short prompts, and the same runner environment across five client layers:

| Client Layer / Stack | Mean Streaming TTFT | Delta vs Raw `fetch()` | Where the Extra Milliseconds Go | Engineering Verdict |
| :--- | :---: | :---: | :--- | :--- |
| **Native `fetch()`** | **395 ms** | Baseline (0 ms) | Zero abstraction; manual SSE line buffering and retry logic | Best for edge proxies and ultra-lean workers |
| **OpenAI Node / TypeScript SDK** | **412 ms** | **+17 ms** | Request option normalization, async iterable framing, default retry wrapper | Sweet spot for Node/TS backends and strict JSON pipelines |
| **Anthropic Python SDK** | **418 ms** | **+23 ms** | Pydantic v2 validation, typed Anthropic SSE event dispatcher | Negligible tax for gaining `cache_control` and `count_tokens` |
| **Vercel AI SDK (`streamText`)** | **434 ms** | **+39 ms** | Provider adapter layer (`@ai-sdk/openai`), Data Stream wire translation, lifecycle hooks | Worth every millisecond if you pair it with React `useChat` |
| **LangChain (`ChatOpenAI`)** | **486 ms** | **+91 ms** | `Runnable` graph dispatch, callback manager lifecycle, message coercion twice per call | Noticeable tax—only pay it when you genuinely use LangChain's orchestration ecosystem |
Read those numbers pragmatically. Spending **17 ms** for the OpenAI Node/TypeScript SDK or **23 ms** for the Anthropic Python SDK is essentially free compared to human perception thresholds (~100 ms), and in return you avoid hand-rolling UTF-8 multibyte SSE boundary parsers and retry timers. Even Vercel AI SDK's **+39 ms** overhead earns its keep on full-stack Next.js apps by eliminating hundreds of lines of client stream state synchronization.
LangChain's **486 ms** (**+91 ms** above `fetch()`) is a different story. When you are calling a fast, low-cost extraction model like the ones we benchmarked in our [DeepSeek V4.1 Flash latency and JSON extraction audit](/en/blog/deepseek-v4-1-flash-latency-and-json-extraction-audit), burning nearly a tenth of a second purely inside Python callback and runnable plumbing can consume a quarter of your total latency budget before a single model token leaves the gateway.
---
## Stack 1: OpenAI Python SDK (Sync, AsyncIO, Streaming & Tool Calling)
Python remains the default runtime for data ingestion workers, FastAPI microservices, and evaluation harnesses. Because `https://topai.id/v1` implements the OpenAI contract cleanly, you install the official `openai` package with zero custom plugins:
```bash
pip install --upgrade openai httpx pydantic
export TOPAI_API_KEY="tp-replace-with-your-key"
```
Two details separate toy scripts from production Python integrations: **reusing a pooled `httpx` client** (re-instantiating `OpenAI()` inside every request handler forces a fresh TCP + TLS handshake that silently adds 60–120 ms per call) and **reading the `topai` telemetry block from `response.model_extra`**. Because `openai` v1+ parses payloads with Pydantic v2 (`extra="allow"`), TOP AI's inline billing object is preserved automatically without monkey-patching the SDK.
### Synchronous Client with Connection Pooling and Telemetry Extraction
```python
import os
import httpx
from openai import OpenAI, APIStatusError, APITimeoutError
# Share one httpx.Client across the process to keep TLS sockets warm
shared_http = httpx.Client(
timeout=httpx.Timeout(connect=10.0, read=120.0, write=30.0, pool=10.0),
limits=httpx.Limits(max_keepalive_connections=25, max_connections=60),
)
client = OpenAI(
base_url="https://topai.id/v1",
api_key=os.environ["TOPAI_API_KEY"],
http_client=shared_http,
max_retries=3,
)
def summarize_alert(raw_log: str) -> dict:
try:
resp = client.chat.completions.create(
model="claude-sonnet-5-5",
temperature=0.2,
max_tokens=512,
messages=[
{
"role": "system",
"content": "You are an on-call SRE. Output root cause, blast radius, and immediate mitigation in three tight bullets.",
},
{"role": "user", "content": raw_log},
],
)
except APITimeoutError as exc:
raise RuntimeError("Gateway read timeout exceeded; switch long prompts to streaming.") from exc
except APIStatusError as exc:
raise RuntimeError(f"TOP AI returned HTTP {exc.status_code}: {exc.message}") from exc
# Extract zero-extra-call billing telemetry directly from Pydantic model_extra
telemetry = (resp.model_extra or {}).get("topai", {})
return {
"summary": resp.choices[0].message.content or "",
"charged_gp": telemetry.get("charged_gp"),
"balance_after": telemetry.get("balance_after"),
"upstream": telemetry.get("upstream"),
"failover": telemetry.get("failover", False),
"latency_ms": telemetry.get("latency_ms"),
}
if __name__ == "__main__":
out = summarize_alert("2026-11-23T08:04Z WARN pg-bouncer saturation on shard-03 wait_queue=142")
print(out["summary"])
print(f"\n[Telemetry] cost={out['charged_gp']} TP | balance={out['balance_after']} TP | upstream={out['upstream']}")
```
### AsyncIO Streaming + Deterministic Tool Calling Loop
For FastAPI endpoints and high-concurrency async workers, switch to `AsyncOpenAI` backed by `httpx.AsyncClient`. The snippet below combines two real-world patterns: SSE streaming with `stream_options={"include_usage": True}` to capture final token counts, plus a clean two-turn tool execution loop with `temperature=0.0` for reliable JSON argument generation.
```python
import asyncio
import json
import os
import httpx
from openai import AsyncOpenAI
async_http = httpx.AsyncClient(
timeout=httpx.Timeout(connect=10.0, read=180.0, write=30.0, pool=10.0),
limits=httpx.Limits(max_keepalive_connections=50, max_connections=120),
)
aclient = AsyncOpenAI(
base_url="https://topai.id/v1",
api_key=os.environ["TOPAI_API_KEY"],
http_client=async_http,
max_retries=2,
)
# 1. Async SSE streaming with trailing usage telemetry
async def stream_answer(question: str) -> str:
chunks: list[str] = []
stream = await aclient.chat.completions.create(
model="deepseek-v4.1-flash",
messages=[{"role": "user", "content": question}],
max_tokens=512,
stream=True,
stream_options={"include_usage": True},
)
async for event in stream:
if event.choices and event.choices[0].delta.content:
token = event.choices[0].delta.content
chunks.append(token)
print(token, end="", flush=True)
elif event.usage:
meta = (event.model_extra or {}).get("topai", {})
print(
f"\n[Done] tokens={event.usage.total_tokens} "
f"charged_gp={meta.get('charged_gp')} failover={meta.get('failover')}"
)
return "".join(chunks)
# 2. End-to-end function/tool calling
TOOL_DEFS = [
{
"type": "function",
"function": {
"name": "lookup_shipment",
"description": "Retrieve live carrier status and ETA for a customer shipment ID.",
"parameters": {
"type": "object",
"properties": {
"shipment_id": {"type": "string", "description": "Shipment identifier, e.g. SHP-90412"}
},
"required": ["shipment_id"],
"additionalProperties": False,
},
},
}
]
def lookup_shipment(shipment_id: str) -> dict:
# Replace with internal order microservice or SQL query
return {"shipment_id": shipment_id, "status": "in_transit", "hub": "Jakarta Gateway", "eta_hours": 14}
async def run_tool_agent(user_prompt: str) -> str:
messages: list[dict] = [
{"role": "system", "content": "Call lookup_shipment whenever a user asks for shipment status."},
{"role": "user", "content": user_prompt},
]
first = await aclient.chat.completions.create(
model="gpt-6-1-sol",
messages=messages,
tools=TOOL_DEFS,
tool_choice="auto",
temperature=0.0,
)
assistant_msg = first.choices[0].message
messages.append(assistant_msg.model_dump(exclude_none=True))
if not assistant_msg.tool_calls:
return assistant_msg.content or ""
for call in assistant_msg.tool_calls:
if call.function.name == "lookup_shipment":
args = json.loads(call.function.arguments)
result = lookup_shipment(args["shipment_id"])
messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
}
)
second = await aclient.chat.completions.create(
model="gpt-6-1-sol",
messages=messages,
temperature=0.1,
)
return second.choices[0].message.content or ""
async def main() -> None:
await stream_answer("Explain HTTP keep-alive vs connection pooling in three sentences.")
print("\n--- Tool Call ---")
print(await run_tool_agent("Where is shipment SHP-90412 right now?"))
await async_http.aclose()
if __name__ == "__main__":
asyncio.run(main())
```
Always cap multi-turn tool loops with an explicit iteration counter (typically 4 to 6 turns max) and validate parsed tool arguments before executing database writes. Unbounded tool loops are the fastest way for a confused model to drain a prepaid key overnight.
---
## Stack 2: OpenAI Node/TypeScript SDK (Next.js App Router SSE & Zod Structured Output)
For TypeScript backends and Next.js App Router apps, one rule is non-negotiable: **your `tp-` key never touches browser code**. Even though gateway endpoints emit permissive CORS headers to speed up local curl/Postman tests, bundling an API key into client-side JavaScript allows any visitor to inspect network traffic and spend your wallet. Keep the OpenAI client strictly inside server modules, Route Handlers, or Server Actions.
```bash
npm install openai zod
```
### Typed Server Singleton With Inline `topai` Telemetry
```typescript
// lib/topai-client.ts
import OpenAI from "openai";
export interface TopAiTelemetry {
charged_gp: number;
balance_after: number;
upstream: string;
failover: boolean;
latency_ms: number;
}
export type TopAiChatCompletion = OpenAI.Chat.Completions.ChatCompletion & {
topai?: TopAiTelemetry;
};
if (!process.env.TOPAI_API_KEY) {
throw new Error("Missing server environment variable TOPAI_API_KEY.");
}
export const topai = new OpenAI({
baseURL: "https://topai.id/v1",
apiKey: process.env.TOPAI_API_KEY,
timeout: 180_000,
maxRetries: 2,
});
```
### Next.js App Router SSE Streaming Route Handler
A classic production leak in Next.js SSE routes is forgetting to forward `req.signal` into the OpenAI SDK call. If a user clicks Stop or navigates away mid-stream without `AbortSignal` propagation, your server keeps reading and paying for the remaining 1,500 tokens even though nobody is listening on the socket. Notice also the `X-Accel-Buffering: no` header, which prevents Nginx or self-hosted reverse proxies from buffering SSE frames until stream completion.
```typescript
// app/api/stream/route.ts
import { NextRequest } from "next/server";
import { topai } from "@/lib/topai-client";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
interface StreamBody {
model?: string;
messages: Array<{ role: "system" | "user" | "assistant"; content: string }>;
}
export async function POST(req: NextRequest) {
const payload = (await req.json()) as StreamBody;
const model = payload.model ?? "claude-sonnet-5-5";
if (!Array.isArray(payload.messages) || payload.messages.length === 0) {
return Response.json({ error: "messages must be a non-empty array" }, { status: 400 });
}
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
try {
const stream = await topai.chat.completions.create(
{
model,
messages: payload.messages,
stream: true,
stream_options: { include_usage: true },
},
{ signal: req.signal }
);
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content;
if (text) {
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: "delta", text })}\n\n`));
}
if (chunk.usage) {
const topaiMeta = (chunk as unknown as { topai?: Record }).topai;
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ type: "meta", usage: chunk.usage, topai: topaiMeta })}\n\n`)
);
}
}
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
} catch (err) {
if (req.signal.aborted) {
controller.close();
return;
}
const message = err instanceof Error ? err.message : "Unexpected streaming failure";
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: "error", message })}\n\n`));
controller.close();
}
},
});
return new Response(readable, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
});
}
```
### Strict Structured Output With Zod (`zodResponseFormat`)
Whenever LLM output feeds a database write, CRM update, or payment triage workflow, prompt-only JSON instructions eventually fail. Pair `zodResponseFormat` from `openai/helpers/zod` with a runtime `safeParse()` check so malformed payloads fail cleanly with HTTP `422` rather than corrupting downstream state:
```typescript
// app/api/triage/route.ts
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";
import { topai, type TopAiChatCompletion } from "@/lib/topai-client";
const SupportTriageSchema = z.object({
category: z.enum(["billing", "bug_report", "account_access", "feature_request"]),
severity: z.enum(["low", "medium", "high", "critical"]),
one_line_summary: z.string().min(10).max(180),
requires_oncall: z.boolean(),
affected_services: z.array(z.string()),
});
export async function POST(req: Request) {
const { customerMessage } = (await req.json()) as { customerMessage: string };
const completion = (await topai.chat.completions.create({
model: "deepseek-v4.1-flash",
temperature: 0,
messages: [
{
role: "system",
content: "Classify the support ticket strictly matching the provided JSON schema.",
},
{ role: "user", content: customerMessage },
],
response_format: zodResponseFormat(SupportTriageSchema, "support_triage"),
})) as TopAiChatCompletion;
const content = completion.choices[0]?.message?.content ?? "{}";
const result = SupportTriageSchema.safeParse(JSON.parse(content));
if (!result.success) {
return Response.json(
{ error: "Zod validation failed", details: result.error.flatten() },
{ status: 422 }
);
}
return Response.json({
triage: result.data,
billing: completion.topai ?? null,
});
}
```
Running `deepseek-v4-1-flash` through `zodResponseFormat` at `temperature: 0` keeps latency tight and per-ticket cost tiny while returning `completion.topai.charged_gp` right next to the validated payload.
---
## Stack 3: Official Anthropic SDK (Python & TypeScript With `cache_control` & `count_tokens`)
If your application sends short single-turn prompts to Claude, routing through the OpenAI-compatible path is completely fine. The moment your prompts include a 4,000-token coding standard, a 30-page policy PDF, or dozens of tool definitions repeated across a multi-turn agent session, switching that service to the **Official Anthropic SDK** directly against `https://topai.id` unlocks two capabilities that change your unit economics overnight:
1. **Ephemeral Prompt Caching (`cache_control`)**: Marking stable `system` or document blocks with `{"type": "ephemeral"}` slashes repeated input token costs across subsequent turns. We walk through the exact break-even math and TTL mechanics in [Anthropic prompt caching math explained](/en/blog/anthropic-prompt-caching-math-explained).
2. **Zero-Cost Preflight Token Counting (`/v1/messages/count_tokens`)**: Call `count_tokens` before committing to an expensive reasoning generation to measure the exact token count—including system blocks and tool schemas—for **0 TP**. See our deep dive on [preflight token counting with `/v1/messages/count_tokens`](/en/blog/preflight-token-counting-with-messages-count-tokens) for automatic history-trimming recipes.
Remember the single most important configuration rule in this section: **set `base_url` / `baseURL` to `https://topai.id` with NO `/v1` suffix**. Both official Anthropic SDKs append `/v1/messages` and `/v1/messages/count_tokens` internally and automatically inject `x-api-key: tp-...` from your `TOPAI_API_KEY`.
### Anthropic Python SDK (`count_tokens` + `cache_control` + `stop_sequences`)
```bash
pip install --upgrade anthropic
```
```python
import os
from anthropic import Anthropic
client = Anthropic(
base_url="https://topai.id", # NO /v1 suffix — SDK appends /v1/messages automatically
api_key=os.environ["TOPAI_API_KEY"],
timeout=180.0,
max_retries=2,
)
ARCHITECTURE_HANDBOOK = (
"Internal distributed systems & payments security baseline v4.2 ...\n" * 180
)
SYSTEM_BLOCKS = [
{
"type": "text",
"text": "You are a principal security reviewer. Ground every answer in the handbook below.",
},
{
"type": "text",
"text": ARCHITECTURE_HANDBOOK,
"cache_control": {"type": "ephemeral"},
},
]
def ask_with_preflight_guard(question: str, max_input_budget: int = 24_000) -> str:
messages = [{"role": "user", "content": question}]
# Step 1: Zero-cost preflight token check against /v1/messages/count_tokens
preflight = client.messages.count_tokens(
model="claude-sonnet-5-5",
system=SYSTEM_BLOCKS,
messages=messages,
)
print(f"[Preflight] Exact input_tokens={preflight.input_tokens}")
if preflight.input_tokens > max_input_budget:
raise ValueError(
f"Prompt exceeds budget ({preflight.input_tokens} > {max_input_budget}). Trim context before calling."
)
# Step 2: Execute with prompt caching and deterministic stop sequence
message = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
system=SYSTEM_BLOCKS,
stop_sequences=[""],
messages=messages,
)
usage = message.usage
print(
f"[Usage] input={usage.input_tokens} "
f"cache_write={getattr(usage, 'cache_creation_input_tokens', 0)} "
f"cache_read={getattr(usage, 'cache_read_input_tokens', 0)} "
f"output={usage.output_tokens}"
)
topai_meta = (message.model_extra or {}).get("topai", {})
if topai_meta:
print(
f"[TOP AI] charged_gp={topai_meta.get('charged_gp')} TP | "
f"balance_after={topai_meta.get('balance_after')} TP | "
f"latency_ms={topai_meta.get('latency_ms')}"
)
return "".join(block.text for block in message.content if block.type == "text")
if __name__ == "__main__":
print(ask_with_preflight_guard("What are our mandatory idempotency rules for payment webhook retries?"))
```
### Anthropic TypeScript SDK (Streaming + Preflight Guard + Caching)
```bash
npm install @anthropic-ai/sdk
```
```typescript
// lib/anthropic-topai.ts
import Anthropic from "@anthropic-ai/sdk";
export const anthropicClient = new Anthropic({
baseURL: "https://topai.id", // Omit /v1 — SDK appends /v1/messages automatically
apiKey: process.env.TOPAI_API_KEY,
timeout: 180_000,
maxRetries: 2,
});
export async function reviewPullRequestDiff(repoStandards: string, gitDiff: string) {
const system: Anthropic.TextBlockParam[] = [
{
type: "text",
text: "You are a senior backend code reviewer. Flag concurrency bugs, injection vectors, and resource leaks.",
},
{
type: "text",
text: repoStandards,
cache_control: { type: "ephemeral" },
},
];
// Preflight check prevents 90k-token lockfile diffs from burning credits
const tokenCheck = await anthropicClient.messages.countTokens({
model: "claude-sonnet-5-5",
system,
messages: [{ role: "user", content: gitDiff }],
});
if (tokenCheck.input_tokens > 36_000) {
throw new Error(`Diff too large (${tokenCheck.input_tokens} tokens). Chunk review by directory.`);
}
const stream = anthropicClient.messages.stream({
model: "claude-sonnet-5-5",
max_tokens: 1500,
system,
messages: [{ role: "user", content: gitDiff }],
});
for await (const delta of stream.textStream) {
process.stdout.write(delta);
}
return await stream.finalMessage();
}
```
Putting `countTokens()` directly in front of `messages.stream()` is one of the highest-leverage guardrails you can add to CI code-review bots or document Q&A services. It costs 0 TP and stops accidental lockfile or CSV dumps from triggering context-window errors or surprise charges.
---
## Stack 4: Vercel AI SDK (`createOpenAI`, `streamText` & `useChat`)
When you are building a customer-facing Next.js chat workspace, writing custom client-side `ReadableStream` decoders, retry controls, and optimistic message lists is tedious boilerplate. The **Vercel AI SDK** handles that entire full-stack streaming handshake while staying cleanly decoupled from OpenAI's own servers via `createOpenAI`.
```bash
npm install ai @ai-sdk/openai @ai-sdk/react zod
```
One detail worth pinning explicitly: call `topai.chat(modelId)` (with `compatibility: "compatible"` on `createOpenAI`) so the adapter consistently targets `/v1/chat/completions` rather than defaulting to OpenAI's `/v1/responses` route, which is still Coming Soon on TOP AI.
### Server Route Handler (`streamText` + Server-Side Tool + `onFinish`)
```typescript
// app/api/copilot/route.ts
import { createOpenAI } from "@ai-sdk/openai";
import { streamText, tool } from "ai";
import { z } from "zod";
export const maxDuration = 120;
const topai = createOpenAI({
baseURL: "https://topai.id/v1",
apiKey: process.env.TOPAI_API_KEY,
compatibility: "compatible",
});
const ALLOWED_MODELS = new Set([
"deepseek-v4.1-flash",
"claude-sonnet-5-5",
"gpt-6-1-sol",
]);
export async function POST(req: Request) {
const { messages, modelId } = (await req.json()) as {
messages: Array<{ role: "user" | "assistant" | "system"; content: string }>;
modelId?: string;
};
// Enforce server-side model allowlist so client tampering cannot invoke expensive models
const chosenModel = modelId && ALLOWED_MODELS.has(modelId) ? modelId : "claude-sonnet-5-5";
const result = streamText({
model: topai.chat(chosenModel),
system: "You are a concise developer tooling assistant. Provide runnable code and exact flags.",
messages,
maxTokens: 1200,
temperature: 0.2,
tools: {
estimateTokenCost: tool({
description: "Calculate estimated TOP Points cost from token counts and per-1M token rates.",
parameters: z.object({
inputTokens: z.number().int().positive(),
outputTokens: z.number().int().positive(),
inputRatePer1M: z.number().positive(),
outputRatePer1M: z.number().positive(),
}),
execute: async ({ inputTokens, outputTokens, inputRatePer1M, outputRatePer1M }) => {
const total =
(inputTokens / 1_000_000) * inputRatePer1M +
(outputTokens / 1_000_000) * outputRatePer1M;
return {
estimated_tp: Math.ceil(total),
currency_note: "1 TP equals Rp 1",
};
},
}),
},
maxSteps: 3,
onFinish: async ({ usage, finishReason }) => {
console.info(
JSON.stringify({
event: "copilot_stream_complete",
model: chosenModel,
finishReason,
promptTokens: usage.promptTokens,
completionTokens: usage.completionTokens,
})
);
},
});
return result.toDataStreamResponse();
}
```
### React Client Component Bound With `useChat`
```tsx
// components/CopilotPanel.tsx
"use client";
import { useState } from "react";
import { useChat } from "@ai-sdk/react";
export function CopilotPanel() {
const [modelId, setModelId] = useState("claude-sonnet-5-5");
const { messages, input, handleInputChange, handleSubmit, isLoading, stop, error } = useChat({
api: "/api/copilot",
body: { modelId },
});
return (
{messages.map((m) => (
{m.role}:{m.content}
))}
{error &&
Request failed: {error.message}
}
);
}
```
One nuance that catches Vercel AI SDK adopters off guard: `streamText` normalizes standard OpenAI fields (`usage`, `finishReason`, `toolCalls`), which means vendor-extension fields like TOP AI's inline `topai` telemetry block are stripped before `onFinish` fires. If you want exact `charged_gp` and `balance_after` logging inside Vercel AI SDK without extra API calls, pass a custom `fetch` wrapper into `createOpenAI({ baseURL, apiKey, fetch: telemetryFetch })` that tees the final SSE frame or non-streaming JSON body to your metrics sink before handing the response stream to the SDK.
---
## Stack 5: LangChain (`ChatOpenAI`) & n8n AI Agent Workflows
Many engineering and ops teams already run production pipelines built on LangChain or visual automations inside n8n. You do not need to rewrite those workflows to adopt TOP AI—both plug directly into `https://topai.id/v1`.
### LangChain Python (`ChatOpenAI`, LCEL Streaming & Pydantic Output)
```bash
pip install --upgrade langchain-openai langchain-core pydantic
```
```python
import asyncio
import os
from pydantic import BaseModel, Field
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="claude-sonnet-5-5",
base_url="https://topai.id/v1",
api_key=os.environ["TOPAI_API_KEY"],
temperature=0.2,
timeout=180,
max_retries=2,
)
# 1. LCEL async streaming chain
prompt = ChatPromptTemplate.from_messages([
("system", "You are a pragmatic infrastructure engineer. Answer with concrete commands."),
("human", "{question}"),
])
chain = prompt | llm
async def run_lcel_stream() -> None:
async for chunk in chain.astream({"question": "How do I verify TLS connection reuse with curl?"}):
if chunk.content:
print(chunk.content, end="", flush=True)
print()
# 2. Structured extraction with Pydantic
class ReleaseDigest(BaseModel):
version: str = Field(description="Semantic release version")
breaking_changes: list[str] = Field(description="List of breaking API or config changes")
migration_risk: str = Field(description="low, medium, or high")
def run_structured_extract() -> None:
fast_llm = ChatOpenAI(
model="deepseek-v4.1-flash",
base_url="https://topai.id/v1",
api_key=os.environ["TOPAI_API_KEY"],
temperature=0,
timeout=90,
)
extractor = fast_llm.with_structured_output(ReleaseDigest)
digest = extractor.invoke(
"v3.4.0 removes /legacy/auth, requires X-Request-ID on all webhook calls, "
"and fixes a worker socket leak under burst load."
)
print(digest.model_dump_json(indent=2))
if __name__ == "__main__":
asyncio.run(run_lcel_stream())
run_structured_extract()
```
### Wiring the n8n AI Agent Node to TOP AI
Skip third-party community nodes in n8n—they routinely break across minor n8n upgrades. Use n8n's built-in **OpenAI Chat Model** sub-node attached to the **AI Agent** node:
1. Open **Credentials** in n8n, create a new **OpenAi** (`OpenAI API`) credential, and paste a dedicated `tp-` key minted specifically for n8n (giving n8n its own key with a daily spend cap protects production traffic if a webhook trigger loops).
2. Expand **Base URL** inside the credential modal and set it to `https://topai.id/v1` (no trailing slash).
3. Drop an **AI Agent** node onto your workflow canvas and attach the **OpenAI Chat Model** sub-node linked to your TOP AI credential.
4. Set **Model** using an expression or manual entry to the exact raw model ID from TOP AI's catalog—for instance `deepseek-v4-1-flash`, `claude-sonnet-5-5`, or `gpt-6-1`—with **no vendor prefix** (never `anthropic/claude-sonnet-5-5` or `openai/gpt-6-1`).
5. Under **Options**, raise **Timeout** to `300000` (300 seconds) and set **Max Retries** to `2`. Multi-step n8n agents querying Postgres, Notion, or HTTP tools routinely blow past default 60-second timeouts.
The exact same OpenAI-compatible configuration pattern powers coding editors too—if your team also runs Cursor, Cline, Roo Code, or Claude Code CLI, follow our walkthrough to [connect Claude Code, Cursor, and Cline with one API key](/en/blog/connect-claude-code-cursor-cline-with-one-api-key).
### An Honest Critique: When LangChain Hurts More Than It Helps
Every senior engineer who has inherited a sprawling LangChain repository eventually hits the same realization: abstraction layers are not free. Look back at our streaming TTFT numbers—`ChatOpenAI` clocks in at **486 ms**, paying **+91 ms** over raw `fetch()` and roughly **+70 ms** over calling the official OpenAI or Anthropic SDK directly.
Latency is only half the story. The steeper cost shows up at 2 a.m. when a production tool call returns unexpected JSON and you have to step through thirty frames of `RunnableSequence`, `CallbackManager`, and message coercion adapters just to inspect the raw HTTP body that went over the wire. Add rapid package churn across `langchain-core` and partner packages, and simple services end up spending more engineering hours feeding the framework than shipping features.
Use a clear decision bar: **keep LangChain when you actively rely on at least two parts of its ecosystem**—for example, stateful LangGraph checkpointing across long-running human-in-the-loop workflows paired with battle-tested document loaders or vector retrievers. If your workload is a prompt pipeline, low-latency streaming UI, structured extraction job, or a straightforward 2–5 tool backend agent, call the OpenAI or Anthropic SDK directly against TOP AI. You will cut ~70 ms of TTFT, ship half the dependency tree, and debug raw payloads in seconds.
---
## SDK Feature Matrix & Stack Selection Decision Guide
Choosing the wrong client layer rarely breaks day-one demos; it bites three months later when you try to turn on prompt caching, need strict per-tenant cost attribution, or hunt down mysterious reverse-proxy timeouts.

### Feature Parity Matrix Across All Five Stacks
| Capability | OpenAI Python SDK | OpenAI Node/TS SDK | Anthropic SDK (Py/TS) | Vercel AI SDK | LangChain + n8n |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **TOP AI Base URL** | `https://topai.id/v1` | `https://topai.id/v1` | `https://topai.id` | `https://topai.id/v1` | `https://topai.id/v1` |
| **Native SSE Streaming** | Yes (sync & `AsyncOpenAI`) | Yes (`for await` + `AbortSignal`) | Yes (`.stream()` & `textStream`) | Yes (`streamText` + `useChat`) | Yes (`astream` / node stream) |
| **Tool / Function Calling** | Full JSON Schema | Full JSON Schema + Zod | Native Anthropic `tools` | Full (`tool()` + `maxSteps`) | Full (Agent & sub-tools) |
| **Strict Structured Output** | Pydantic `.parse()` | `zodResponseFormat` | Tool schema / prefill | `generateObject` + Zod | `with_structured_output` |
| **Prompt Caching (`cache_control`)** | Not native | Not native | **Full Native Support** | Requires Anthropic adapter | Limited on OpenAI route |
| **Zero-Cost `/v1/messages/count_tokens`** | Manual `httpx` call | Manual `fetch` call | **Native `.count_tokens()`** | Not native | Not native |
| **Inline `topai` Telemetry Access** | Direct via `model_extra` | Direct via typed extension | Direct via `model_extra` | Needs custom `fetch` wrapper | Buried in raw response metadata |
| **Mean Streaming TTFT Overhead** | ~+20 ms | **+17 ms** | **+23 ms** | +39 ms | **+91 ms** |
### Stack Selection Matrix: Pick Based on Workload Shape
| Workload & Team Profile | Recommended Stack | Why It Wins | Skip It When... |
| :--- | :--- | :--- | :--- |
| **Python FastAPI services, async workers, batch ETL & evals** | **OpenAI Python SDK (`AsyncOpenAI`)** | Rock-solid `httpx` pooling, swap models across vendors via one string, direct `model_extra["topai"]` telemetry | Prompts exceed 4k static tokens and need Anthropic `cache_control` |
| **Node/TS APIs, strict JSON pipelines, custom streaming proxies** | **OpenAI Node/TS SDK + Zod** | Lowest SDK TTFT overhead (+17 ms), full control over `AbortSignal` and `X-Accel-Buffering` | Frontend engineers want prebuilt React chat state hooks |
| **Claude-heavy coding tools, long-doc Q&A, policy/SOP review** | **Official Anthropic SDK (Py/TS)** | Major input savings via `cache_control` plus 0-TP context protection via `/v1/messages/count_tokens` | You switch frequently between non-Claude vendors in the same call path |
| **Full-stack Next.js SaaS with live chat & tool-driven UI** | **Vercel AI SDK (`createOpenAI` + `useChat`)** | Fastest frontend delivery, built-in stop/regenerate UX, clean Zod tool execution | You are building headless backend workers or need zero-overhead SSE proxies |
| **Internal ops automations (Slack, CRM, DB) & stateful graphs** | **n8n AI Agent** (or **LangChain / LangGraph**) | Connects dozens of SaaS triggers visually or handles durable graph state out of the box | Sub-500 ms TTFT is mandatory or simple prompt flows do not justify framework indirection |
Most mature engineering teams do not force a single stack across every repo. A clean hybrid setup uses the **Official Anthropic SDK** for long-context Claude services (capturing prompt caching and preflight token checks), **OpenAI Node/TS SDK or Vercel AI SDK** inside customer-facing Next.js web apps (keeping model switching effortless between `claude-sonnet-5-5`, `gpt-6-1`, and `deepseek-v4-1-flash`), and a dedicated daily-capped key inside **n8n** for back-office automations.
---
## Error Contracts, Backoff Discipline & Production Rollout Checklist
Most production incidents after an SDK migration trace back to three boring causes: retrying non-retryable `4xx` errors in a tight loop, mismatched timeouts between client SDKs and reverse proxies, or reusing one unconstrained API key across staging, production, and automation runners.
TOP AI preserves native error envelopes per protocol: OpenAI-compatible routes emit `{ "error": { "message", "type", "code", "param" } }`, while Anthropic routes emit `{ "type": "error", "error": { "type", "message" } }`. Your error handler should strictly separate transient faults (`429`, `502`, `503`) from permanent failures (`400`, `401`, `402`, `403`, `404`):
| HTTP Status | Typical Error Type | Root Cause in Production | Correct Client Behavior |
| :---: | :--- | :--- | :--- |
| **`400`** | `invalid_request_error` | Malformed message array, missing `max_tokens` on Anthropic route, or unknown model ID | Fail fast (no retry); log sanitized payload and validate model ID against `GET /v1/models` |
| **`401`** | `authentication_error` | Revoked or mistyped `tp-` key, stray newline in secret env var, or missing auth header | Fail fast; page ops on credential drift and inspect secret manager injection |
| **`402`** | `insufficient_quota` | Account TOP Points balance cannot cover the estimated request reservation | Fail fast; trigger graceful degradation and fire top-up alert |
| **`403`** | `permission_error` | Requested model blocked by key allowlist or per-key daily spend cap reached | Fail fast; review key scope and cap settings in `/dashboard/kunci` |
| **`404`** | `not_found_error` | Wrong base URL—most commonly passing `/v1` into the Anthropic SDK (`/v1/v1/messages`) | Fix base URL configuration; verify route is not a *Coming Soon* endpoint |
| **`429`** | `rate_limit_error` | Burst traffic hit key RPM limit or transient upstream throttling | **Retry with exponential backoff + random jitter**, honoring `Retry-After` header first |
| **`502` / `503`** | `upstream_error` | Brief upstream turbulence prior to or during automatic failover | **Retry up to 3–4 attempts** (`500ms * 2^n + jitter`); log `topai.failover` on recovery |
### Production Exponential Backoff With Jitter (TypeScript)
Whenever you use raw `fetch()` or inject a custom `fetch` wrapper into the Vercel AI SDK, always add random jitter to backoff intervals. Deterministic backoff without jitter causes every rate-limited worker to wake up on the exact same millisecond and stampede the gateway again:
```typescript
// lib/topai-backoff.ts
export async function fetchWithJitterBackoff(
url: string,
init: RequestInit,
maxAttempts = 4
): Promise {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const res = await fetch(url, init);
if (res.ok) return res;
const isRetryable = res.status === 429 || res.status === 502 || res.status === 503;
if (!isRetryable || attempt === maxAttempts - 1) {
return res;
}
const retryAfterSec = Number(res.headers.get("retry-after") ?? 0);
const delayMs = retryAfterSec > 0 ? retryAfterSec * 1000 : 2 ** attempt * 500;
const jitterMs = Math.floor(Math.random() * 250);
await new Promise((resolve) => setTimeout(resolve, delayMs + jitterMs));
}
throw new Error("Exhausted TOP AI retry attempts.");
}
```
### Five-Point Pre-Cutover Hardening Checklist
Before shifting 100% of production traffic onto your newly wired SDKs, run through these five operational controls:
1. **Isolate `tp-` keys per service and environment:** Mint separate keys for staging, Python workers, Next.js production, and n8n workflows so a runaway automation loop never starves customer-facing traffic. Follow the full governance blueprint in our guide to [enterprise AI API key governance: caps, allowlists, and audit logs](/en/blog/enterprise-ai-api-key-governance-caps-allowlists-audit-logs).
2. **Pin model allowlists and daily spend caps:** If a ticket-triage service should only ever call `deepseek-v4-1-flash`, lock its `tp-` key to that single model ID in `/dashboard/kunci`. Any misconfigured deployment attempting to invoke a frontier model gets stopped immediately with `403` before burning budget.
3. **Align timeouts end to end:** Match your reverse proxy read timeout (Nginx/Cloudflare/ALB), serverless function `maxDuration`, and SDK client timeout (180–300 seconds for reasoning and multi-tool flows). Unaligned timeouts create phantom `504` failures where your frontend aborts while the upstream generation still runs to completion.
4. **Ship behind a percentage canary flag:** Shift 10% of non-critical traffic onto TOP AI first and compare `topai.latency_ms`, Zod/Pydantic schema pass rates, and `topai.charged_gp` against your legacy provider baseline before ramping to 100%.
5. **Emit `topai` telemetry into structured logs:** Shipping `charged_gp`, `balance_after`, `upstream`, `failover`, and `latency_ms` into Datadog, Grafana, or your analytics warehouse gives engineering and finance a single real-time source of truth for every model call across Python, TypeScript, Vercel AI, LangChain, and n8n.
With all five stacks wired cleanly against TOP AI's dual-protocol gateway, your application code stays vendor-portable, your streaming TTFT stays lean, and your team can adopt newer models or switch upstream routing without touching a single business-logic wrapper.
Why does the official Anthropic SDK return a 404 when configured with https://topai.id/v1?+
Both the Python and TypeScript Anthropic SDKs automatically append /v1/messages and /v1/messages/count_tokens to whatever base URL you provide. Supplying https://topai.id/v1 causes the client to hit https://topai.id/v1/v1/messages and fail with 404 Not Found. Drop the /v1 suffix and set the base URL to https://topai.id.
Do I need to manually set Authorization or x-api-key headers when switching between SDKs?+
No. Pass the exact same tp- prefixed TOPAI_API_KEY into api_key or apiKey. OpenAI-compatible clients automatically send Authorization: Bearer tp-..., while official Anthropic clients automatically send x-api-key: tp-.... TOP AI validates both authentication headers natively.
How do I capture exact per-request billing telemetry without extra balance API calls?+
Every TOP AI completion response includes a topai telemetry object containing charged_gp, balance_after, upstream, failover, and latency_ms. In native fetch or typed TypeScript clients you read it directly off the parsed JSON payload; in Pydantic-backed Python SDKs (OpenAI and Anthropic) it is preserved under response.model_extra['topai'].
How much streaming TTFT latency does each SDK layer add over raw fetch?+
TOP ECOSYSTEM · 3 TOOLS WORTH CLICKING
Build Faster, Post on Autopilot & Lock Down Security
In controlled streaming TTFT measurements against TOP AI, raw fetch() averages 395 ms, the OpenAI Node/TypeScript SDK averages 412 ms (+17 ms), the Anthropic Python SDK averages 418 ms (+23 ms), Vercel AI SDK streamText averages 434 ms (+39 ms), and LangChain ChatOpenAI averages 486 ms (+91 ms).
Are /v1/embeddings, /v1/audio/speech, and /v1/audio/transcriptions live on TOP AI today?+
The production-ready endpoints available today are /v1/chat/completions, /v1/models, and /v1/images/generations on the OpenAI path, plus /v1/messages and /v1/messages/count_tokens on the Anthropic path. According to TOP AI's integration documentation, /v1/embeddings, /v1/audio/speech, /v1/audio/transcriptions, and /v1/responses are currently marked Coming Soon, so services requiring vector embeddings or audio transcription today should isolate those calls behind a separate adapter until general availability.
Why do n8n AI Agent workflows time out during multi-step tool execution?+
Default HTTP client timeouts inside workflow runners and wrapper libraries often sit at 30 to 60 seconds, which is too short for chained tool calls or long-context reasoning models. Set the client timeout on your n8n OpenAI Chat Model node (and any upstream reverse proxy) to at least 300,000 ms (300 seconds) and enable streaming whenever supported.
When should an engineering team skip LangChain and call the OpenAI or Anthropic SDK directly?+
Skip LangChain when your feature consists of one to three deterministic prompt calls, low-latency streaming chat, or strict JSON extraction via Zod or Pydantic. In those cases, LangChain adds roughly 91 ms of TTFT overhead, deepens stack traces during payload debugging, and introduces framework upgrade churn without paying its rent.