Node.js TypeScript Guide to Claude and GPT Calls
Call Claude and GPT from One TypeScript Service
Supporting both Claude and GPT does not require maintaining two unrelated application architectures. In Node.js, the practical approach is to standardize your application around a provider-compatible client boundary, keep model selection configurable, and normalize the small differences that matter: message formats, streaming events, tool calls, and token accounting.
59API is useful for this setup because it provides pay-as-you-go access to Claude Opus, Sonnet, Haiku, Fable, and GPT models through https://api.59api.com. It is compatible with Claude Code, Codex, and OpenAI SDK clients, so a team can route requests through one low-cost relay while continuing to use official-quality native models rather than switching to downgraded substitutes.
Set Up Secrets and Typed Configuration
Install the SDK required by the interface you plan to use. For GPT-compatible calls, use the OpenAI Node SDK. For Claude-native requests, use the Anthropic TypeScript SDK. Store the 59API key in an environment variable such as AI_API_KEY and never expose it in browser code, committed .env files, logs, or error messages.
Create one typed configuration module that reads the key, base URL, timeout, and default model at process startup. Fail immediately when the key is absent. This is better than discovering a missing credential after a user request has already reached a queue or serverless invocation. Keep the 59API base URL as a configuration value, set to https://api.59api.com, rather than scattering it across route handlers.
For an OpenAI SDK client, configure apiKey from AI_API_KEY and baseURL from your relay setting. For an Anthropic client, configure apiKey and baseURL in the equivalent client options. Confirm the exact model identifiers available in your 59API account before hard-coding them. Model names change more often than application logic should.
Use a Model Registry Instead of String Literals
Advanced TypeScript projects should not let every feature choose arbitrary model strings. Define a model registry with entries for a fast low-cost model, a balanced general model, and a high-reasoning model. Each entry should include provider interface, model ID, maximum output token policy, retry policy, and intended workload.
- Fast path: classification, extraction, autocomplete, short support replies, and metadata generation.
- Balanced path: document summaries, coding assistance, structured business analysis, and multi-turn chat.
- Reasoning path: difficult debugging, architecture reviews, complex transformations, and high-value agent steps.
This makes cost control explicit. Route inexpensive work to a smaller model and reserve premium models for tasks where accuracy or reasoning depth affects the outcome. 59API's low pay-as-you-go pricing makes mixed-model routing especially practical because you can optimize each request instead of committing all traffic to one expensive tier.
Design for Structured Output and Tool Calls
Do not ask a model for “valid JSON” and immediately pass the response to JSON.parse in production. Define a schema for the result, validate it after every response, and retry with a concise correction prompt only when validation fails. For example, an invoice extractor should validate required fields, number formats, dates, and allowed currency values before writing to a database.
Keep tool definitions provider-neutral inside your application. Describe each tool with a name, input schema, authorization rule, and execution function. Then adapt that internal definition to the OpenAI-compatible or Claude-native request format at the edge. When a model returns a tool request, validate arguments, enforce user permissions again, execute the tool with a timeout, and send the result back as a tool response. Never let a model-selected tool bypass server-side authorization.
Stream Safely and Preserve Observability
Streaming reduces perceived latency, but it complicates error handling. Forward text deltas to the client as Server-Sent Events or a readable stream, while accumulating the final response server-side for auditing and persistence. Send a distinct completion event only after the upstream stream closes successfully. If the connection drops, mark the message incomplete instead of storing it as a finished answer.
Log request IDs, selected model, latency, input tokens, output tokens, retry count, and feature name. Do not log raw prompts by default when they may contain customer data. These fields let you compare Claude and GPT behavior, detect expensive routes, and identify prompts that cause repeated failures.
Make Retries Deliberate
Retry only transient failures such as rate limits, network timeouts, and temporary upstream errors. Use exponential backoff with jitter and cap attempts at two or three. Do not retry validation errors, authentication failures, or malformed tool arguments. For non-idempotent workflows, attach an idempotency key before retrying so a duplicated request cannot create a second order, ticket, or database record.
Start with one small production endpoint, record quality and cost by model, then expand the registry as real traffic identifies where premium reasoning is justified. Developers who want a compatible, inexpensive route to both Claude and GPT can sign up for 59API and point their existing SDK configuration at its API base URL.
¿Listo para empezar?
Conecta Claude y GPT en minutos a los precios más bajos, sin recortes. Regístrate para obtener tu clave API.
Registro gratis