Usiamo i cookie. Cookie e memoria del browser ti mantengono connesso e ricordano le tue preferenze. Con il tuo consenso misuriamo anche come viene usato il sito. Puoi in qualsiasi momento. Consulta la nostra cookie policy.

Node.js

Guide agli SDK

Node.js

Usa il pacchetto npm ufficiale openai con api14 in Node.js: configurazione, chat, streaming, strumenti, output strutturato, embeddings, errori e retry.

Usa il pacchetto npm ufficiale openai con api14. Non cambia nient'altro: solo baseURL e apiKey puntano ad api14, e ogni id di modello funziona come model.

Installazione

npm install openai

Salva la tua chiave in una variabile d'ambiente:

export API14_API_KEY="sk-api14-..."

Configurazione

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api14.com/api/v1",
  apiKey: process.env.API14_API_KEY,
});

Senza opzioni, l'SDK legge OPENAI_BASE_URL e OPENAI_API_KEY. Impostando queste due variabili un'app esistente passa ad api14 senza modifiche al codice:

export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."
const client = new OpenAI(); // legge entrambe le variabili

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 ?? "");
}

Vedi Streaming per il formato degli eventi.

Tool calling

Invia tools, esegui le chiamate richieste dal modello, aggiungi i risultati e chiama di nuovo finché risponde con del testo:

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); // la tua funzione
    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);

Vedi Tool calling.

Output strutturato

L'helper parse trasforma uno schema Zod in un formato di risposta json_schema e analizza la risposta (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" }

Vedi Output strutturati.

Input di immagini

Passa content come array di parti. Usa un URL pubblico o un data URL in 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}` } },
    ],
  }],
});

Vedi Visione e file per PDF, audio e video.

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

Endpoint senza metodo nell'SDK

I job video e il rerank non fanno parte dell'interfaccia dell'SDK OpenAI. Usa gli helper generici post / get del client: riutilizzano base URL, chiave e retry:

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

Errori

Gli errori arrivano nel formato OpenAI e vengono lanciati come OpenAI.APIError. Distingui i casi con status e 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;
  }
}

Vedi Errori per ogni codice.

Timeout e retry

Per impostazione predefinita l'SDK ripete due volte gli errori di connessione e le risposte 408, 409, 429 e 5xx, con backoff esponenziale che rispetta Retry-After. Il timeout predefinito è di 10 minuti per tentativo. Impostali entrambi sul client, oppure sovrascrivili per singola richiesta:

const client = new OpenAI({
  baseURL: "https://api14.com/api/v1",
  apiKey: process.env.API14_API_KEY,
  timeout: 60_000, // ms per tentativo
  maxRetries: 4,
});

await client.chat.completions.create(params, { timeout: 300_000, maxRetries: 0 });

Un retry non può risolvere daily_limit_reached o insufficient_balance. Per i job batch lunghi, fermati su questi codici invece di riprovare. Vedi Limiti di frequenza.

Tutte le funzionalità

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