Guías de SDK
Node.js
Usa el paquete oficial openai de npm con api14: configura baseURL y apiKey, chat, streaming, herramientas, salida estructurada, errores y reintentos.
Usa el paquete oficial de npm openai con api14. No cambia nada más: solo baseURL y apiKey apuntan a api14, y cualquier id de modelo sirve como model.
Instalación
npm install openai
Guarda tu clave en una variable de entorno:
export API14_API_KEY="sk-api14-..."
Configuración
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
});
Sin opciones, el SDK lee OPENAI_BASE_URL y OPENAI_API_KEY. Establecer esas dos variables cambia una aplicación existente a api14 sin modificar el código:
export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."
const client = new OpenAI(); // toma ambas variables
Chat
const result = await client.chat.completions.create({
model: "openai/gpt-5-mini",
messages: [{ role: "user", content: "Explain vector databases in two sentences." }],
});
console.log(result.choices[0].message.content);
Streaming
const stream = await client.chat.completions.create({
model: "anthropic/claude-sonnet-4.5",
messages: [{ role: "user", content: "Write a haiku about APIs." }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
Consulta Streaming para el formato de los eventos.
Llamadas a herramientas
Envía tools, ejecuta las llamadas que pida el modelo, añade los resultados y vuelve a llamar hasta que responda con texto:
const tools = [{
type: "function",
function: {
name: "get_weather",
description: "Current weather for a city",
parameters: {
type: "object",
properties: { city: { type: "string" } },
required: ["city"],
},
},
}];
const messages = [{ role: "user", content: "What's the weather in Istanbul?" }];
let res = await client.chat.completions.create({ model: "openai/gpt-5-mini", messages, tools });
while (res.choices[0].finish_reason === "tool_calls") {
const msg = res.choices[0].message;
messages.push(msg);
for (const call of msg.tool_calls) {
const args = JSON.parse(call.function.arguments);
const result = await getWeather(args.city); // tu función
messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
}
res = await client.chat.completions.create({ model: "openai/gpt-5-mini", messages, tools });
}
console.log(res.choices[0].message.content);
Consulta Llamadas a herramientas.
Salida estructurada
El helper parse convierte un esquema de Zod en un formato de respuesta json_schema y analiza la respuesta (npm install zod):
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";
const Person = z.object({ name: z.string(), born: z.number().int(), city: z.string() });
const res = await client.chat.completions.parse({
model: "openai/gpt-5-mini",
messages: [{ role: "user", content: "Extract: Ada Lovelace, born 1815 in London." }],
response_format: zodResponseFormat(Person, "person"),
});
console.log(res.choices[0].message.parsed); // { name: "Ada Lovelace", born: 1815, city: "London" }
Consulta Salidas estructuradas.
Entrada de imagen
Pasa content como un array de partes. Usa una URL pública o una URL de datos en base64:
import { readFileSync } from "node:fs";
const image = readFileSync("photo.png").toString("base64");
const res = await client.chat.completions.create({
model: "google/gemini-2.5-flash",
messages: [{
role: "user",
content: [
{ type: "text", text: "What is in this picture?" },
{ type: "image_url", image_url: { url: `data:image/png;base64,${image}` } },
],
}],
});
Consulta Visión y archivos para PDF, audio y vídeo.
Embeddings
const result = await client.embeddings.create({
model: "openai/text-embedding-3-small",
input: ["The quick brown fox", "Lorem ipsum"],
});
console.log(result.data.map((d) => d.embedding.length));
Endpoints sin método en el SDK
Los trabajos de vídeo y el rerank no forman parte de la superficie del SDK de OpenAI. Usa los helpers genéricos post / get del cliente, que reutilizan la URL base, la clave y los reintentos:
const ranked = await client.post("/rerank", {
body: {
model: "cohere/rerank-v3.5",
query: "What is the capital of France?",
documents: ["Paris is the capital of France.", "Berlin is in Germany."],
top_n: 1,
},
});
console.log(ranked.results);
Errores
Los errores llegan con el formato de OpenAI y se lanzan como OpenAI.APIError. Distingue por status y code:
try {
await client.chat.completions.create({ model: "openai/gpt-5-mini", messages: [{ role: "user", content: "Hi" }] });
} catch (err) {
if (err instanceof OpenAI.APIError) {
if (err.status === 402) console.error("Balance too low, add funds:", err.code); // insufficient_balance
else if (err.status === 429) console.error("Retry after", err.headers?.["retry-after"], "s:", err.code); // rate_limited
else throw err;
}
}
Consulta Errores para ver todos los códigos.
Tiempos de espera y reintentos
Por defecto, el SDK reintenta dos veces los errores de conexión y las respuestas 408, 409, 429 y 5xx, con retroceso exponencial que respeta Retry-After. El tiempo de espera por defecto es de 10 minutos por intento. Establece ambos en el cliente o sustitúyelos por petición:
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
timeout: 60_000, // ms por intento
maxRetries: 4,
});
await client.chat.completions.create(params, { timeout: 300_000, maxRetries: 0 });
Un reintento no puede resolver daily_limit_reached ni insufficient_balance. En trabajos largos por lotes, detente con esos códigos en lugar de reintentar. Consulta Límites de tasa.
Todas las capacidades
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
});
const result = await client.chat.completions.create({
"model": "openai/gpt-5-mini",
"messages": [
{
"role": "user",
"content": "Explain vector databases in two sentences."
}
]
});
console.log(result.choices[0].message.content);