Skip to main content

04 - Integrating OpenAI and Anthropic APIs in a Web App

How to call the OpenAI and Anthropic APIs from a web app: streaming, retries already in the SDK and a proxy that keeps the key on the server, with listings run.

What do you think about this article?

At a Glance

How to call the OpenAI and Anthropic APIs from a web app: streaming, retries already in the SDK and a proxy that keeps the key on the server, with listings run.

You want your web application to talk to a language model, and you face three concrete problems: where to keep the key without handing it to anyone who opens the browser's developer tools, how to show the answer while it is being generated instead of making the user wait, and what to do when the service answers 429. This article solves them with the two official TypeScript SDKs, OpenAI's and Anthropic's, and with a small server that sits between the browser and the provider. Naming these two providers is here a technical subject: they are the APIs the reader might integrate, not the ones that power this site.

The method is the same as in the rest of the series: no call to a real model. The SDKs accept a fetch option, and I supply a fake one that answers with a declared script, so the SDK code (serialisation, stream reading, repeated attempts) really runs and I need no keys, network or open ports. For context, two earlier articles: What is RAG and RAG with TypeScript and LangChain.js.

The model name does not belong in the code

The listings below use "test-model" because the list of models changes in weeks, not in years. The examples in many tutorials, and the earlier versions of this article, used identifiers that no longer appear among the current models of the official pages. The remedy is structural: the identifier lives in an environment variable or in a configuration file, and before going to production you compare it with the models page of Anthropic and with that of OpenAI (consulted on 2026-11-12). The same goes for prices: they vary by two orders of magnitude between the flagship model and the light one, and a table published in an article is out of date the next day.

Installation (run in a temporary folder, Node 24.11)
npm init -y
npm pkg set type=module
npm install openai @anthropic-ai/sdk express cors
npm install -D typescript @types/node @types/express @types/cors

The versions I worked with are openai 7.56.0, @anthropic-ai/sdk 1.8.0, express 5.3.0, cors 2.8.6 and TypeScript 7.0.2. If yours are different, the method names might not match: it is the first place to look when an example does not compile. The keys are read from the variables OPENAI_API_KEY and ANTHROPIC_API_KEY, which the constructors recognise on their own; they must never go in a committed file or in code that ends up in the browser.

Two request shapes, compared

The two APIs tell the same idea with different structures. To see the differences without trusting memory, the listing builds a client for each SDK with a fetch that records what is sent and answers with a scripted JSON. The output shows the address, the authentication header and the body of the request, plus the text and the tokens read from the response.

Listing 1: the request the two SDKs build (run with a fake fetch)
import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";

// Fake "fetch": records the request and answers with a scripted JSON. No network.
type Recording = { url: string; headers: Record<string, string>; body: unknown };
function fakeFetch(answer: unknown, log: Recording[]) {
  return async (url: string | URL | Request, init?: RequestInit): Promise<Response> => {
    const h = new Headers(init?.headers);
    log.push({
      url: String(url),
      headers: { auth: h.get("authorization") ?? "-", "x-api-key": h.get("x-api-key") ?? "-", version: h.get("anthropic-version") ?? "-" },
      body: JSON.parse(String(init?.body)),
    });
    return new Response(JSON.stringify(answer), { status: 200, headers: { "content-type": "application/json" } });
  };
}

const MODEL = "test-model";   // the real name comes from the configuration, not from the code

const logO: Recording[] = [];
const openai = new OpenAI({
  apiKey: "fake-key-openai",
  fetch: fakeFetch({
    id: "resp_1", object: "response", status: "completed", model: MODEL,
    output: [{ type: "message", id: "msg_1", status: "completed", role: "assistant",
      content: [{ type: "output_text", text: "The Observer pattern notifies the subscribers.", annotations: [] }] }],
    usage: { input_tokens: 21, output_tokens: 9, total_tokens: 30 },
  }, logO),
});
const r1 = await openai.responses.create({
  model: MODEL,
  instructions: "You are a technical assistant.",
  input: "Explain the Observer pattern.",
});

const logA: Recording[] = [];
const anthropic = new Anthropic({
  apiKey: "fake-key-anthropic",
  fetch: fakeFetch({
    id: "msg_1", type: "message", role: "assistant", model: MODEL, stop_reason: "end_turn", stop_sequence: null,
    content: [{ type: "text", text: "The Observer pattern notifies the subscribers." }],
    usage: { input_tokens: 19, output_tokens: 9 },
  }, logA),
});
const r2 = await anthropic.messages.create({
  model: MODEL,
  max_tokens: 256,
  system: "You are a technical assistant.",
  messages: [{ role: "user", content: "Explain the Observer pattern." }],
});

console.log("OPENAI   ", JSON.stringify(logO[0]));
console.log("ANTHROPIC", JSON.stringify(logA[0]));
console.log("OpenAI text   :", r1.output_text, "| tokens:", r1.usage?.input_tokens, "+", r1.usage?.output_tokens);
const block = r2.content[0];
console.log("Anthropic text:", block.type === "text" ? block.text : "(not text)", "| tokens:", r2.usage.input_tokens, "+", r2.usage.output_tokens);

// Output:
// OPENAI    {"url":"https://api.openai.com/v1/responses","headers":{"auth":"Bearer fake-key-openai","x-api-key":"-","version":"-"},"body":{"model":"test-model","instructions":"You are a technical assistant.","input":"Explain the Observer pattern."}}
// ANTHROPIC {"url":"https://api.anthropic.com/v1/messages","headers":{"auth":"Bearer fake-key-anthropic","x-api-key":"-","version":"2026-10-21"},"body":{"model":"test-model","max_tokens":256,"system":"You are a technical assistant.","messages":[{"role":"user","content":"Explain the Observer pattern."}]}}
// OpenAI text   : The Observer pattern notifies the subscribers. | tokens: 21 + 9
// Anthropic text: The Observer pattern notifies the subscribers. | tokens: 19 + 9

Three differences can be read directly in the output. OpenAI uses here the Responses API (/v1/responses), with the system instructions in the instructions field and the message in the input field; its documentation recommends this API, in particular for streaming, and still documents Chat Completions for existing code. Anthropic uses the Messages API (/v1/messages), with the system prompt in the system parameter, a list of messages that contains only user and assistant, and max_tokens mandatory: without it, the type does not compile. Finally the response: OpenAI offers the quick accessor output_text, Anthropic returns an array of blocks among which you look for the one of type text.

Authentication is a version trap. With this SDK Anthropic sends the key as Authorization: Bearer and adds the anthropic-version header by itself (2026-10-21 in the output); the API documentation lists x-api-key as a "legacy" alternative that is still supported. If you write the HTTP calls by hand instead of using the SDK, these headers are yours. The token values (21 + 9, 19 + 9) are those of my script, not a measurement of a model.

Streaming: two event formats

With streaming the response arrives as a sequence of Server-Sent Events instead of a single JSON. The total time does not change, but the user sees the first words immediately, and that is the difference between an interface that looks frozen and one that looks alive. The two SDKs expose the stream as an async iterator, but the events they produce are different, and the listing consumes both from a scripted stream that follows the sequences described in the respective documentation pages.

Listing 2: reading the text from the events of the two SDKs (run with a fake stream)
import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";

// Builds an SSE response in pieces: "pieces" are the blocks of bytes the network would deliver.
function sse(pieces: string[]): Response {
  const enc = new TextEncoder();
  const body = new ReadableStream({
    start(c) { for (const p of pieces) c.enqueue(enc.encode(p)); c.close(); },
  });
  return new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } });
}
const ev = (name: string, data: object) => `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;

// --- OpenAI, Responses API: the text events are called response.output_text.delta
const openai = new OpenAI({
  apiKey: "fake-key",
  fetch: async () => sse([
    ev("response.output_text.delta", { type: "response.output_text.delta", delta: "Hello", sequence_number: 1 }),
    ev("response.output_text.delta", { type: "response.output_text.delta", delta: ", world", sequence_number: 2 }),
    ev("response.completed", { type: "response.completed", sequence_number: 3, response: { id: "resp_1", status: "completed", usage: { input_tokens: 12, output_tokens: 4, total_tokens: 16 } } }),
  ]),
});
const streamO = await openai.responses.create({ model: "test-model", input: "Say hello.", stream: true });
let textO = "";
for await (const e of streamO) {
  if (e.type === "response.output_text.delta") textO += e.delta;
  if (e.type === "response.completed") console.log("OpenAI completed, tokens:", e.response.usage?.total_tokens);
}
console.log("OpenAI :", textO);

// --- Anthropic, Messages API: the text is in content_block_delta / text_delta
const anthropic = new Anthropic({
  apiKey: "fake-key",
  fetch: async () => sse([
    ev("message_start", { type: "message_start", message: { id: "msg_1", type: "message", role: "assistant", content: [], model: "test-model", stop_reason: null, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 1 } } }),
    ev("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }),
    ev("ping", { type: "ping" }),
    ev("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hello" } }),
    ev("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: ", world" } }),
    ev("content_block_stop", { type: "content_block_stop", index: 0 }),
    ev("message_delta", { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 4 } }),
    ev("message_stop", { type: "message_stop" }),
  ]),
});
let textA = "";
for await (const e of anthropic.messages.stream({ model: "test-model", max_tokens: 64, messages: [{ role: "user", content: "Say hello." }] })) {
  if (e.type === "content_block_delta" && e.delta.type === "text_delta") textA += e.delta.text;
}
console.log("Anthropic:", textA);

// Output:
// OpenAI completed, tokens: 16
// OpenAI : Hello, world
// Anthropic: Hello, world

In OpenAI the text is in the response.output_text.delta events (the delta field is the string) and the closing is the response.completed event, which also carries the token usage. In Anthropic the events arrive in a fixed order (message_start, then for each content block a content_block_start, several content_block_delta and a content_block_stop, finally message_delta and message_stop) and the text is in delta.text when delta.type is text_delta. That check on the type is not pedantry: the same family of events also carries other types of delta (for example thinking_delta for reasoning and input_json_delta for the parameters of a tool), and reading delta.text without looking at the type produces undefined in the text.

Errors and retries: the SDK already does them

A widespread practice is to write your own retry system with growing waits. Before doing it, read Anthropic's errors documentation: it says that the official SDK retries transient errors by itself (connection errors, 429s and 5xxs) with exponential backoff, twice by default, and respects the retry-after header when present. The listing verifies it on both SDKs with fake responses, counting how many times fetch is called.

Listing 3: how many attempts the SDKs make (run; identical output in two runs)
import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";

// Fake fetch that answers with a sequence of statuses and counts the calls.
function sequence(statuses: number[]) {
  const calls = { n: 0 };
  const f = async (): Promise<Response> => {
    const status = statuses[Math.min(calls.n++, statuses.length - 1)];
    const body = status === 200
      ? { id: "msg_1", type: "message", role: "assistant", model: "m", stop_reason: "end_turn", stop_sequence: null, content: [{ type: "text", text: "ok" }], usage: { input_tokens: 1, output_tokens: 1 } }
      : { type: "error", error: { type: status === 429 ? "rate_limit_error" : "invalid_request_error", message: `fake error ${status}` } };
    return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "retry-after": "0" } });
  };
  return { f, calls };
}
const request = { model: "m", max_tokens: 8, messages: [{ role: "user" as const, content: "hello" }] };

for (const [name, statuses, maxRetries] of [
  ["429 then 200, maxRetries 2 (default)", [429, 200], undefined],
  ["429 always, maxRetries 2", [429], undefined],
  ["429 always, maxRetries 0", [429], 0],
  ["400, maxRetries 2", [400], undefined],
] as const) {
  const { f, calls } = sequence([...statuses]);
  const client = new Anthropic({ apiKey: "fake-key", fetch: f, ...(maxRetries === undefined ? {} : { maxRetries }) });
  try {
    await client.messages.create(request);
    console.log(`${name}: succeeded, calls=${calls.n}`);
  } catch (e) {
    const err = e as { constructor: { name: string }; status?: number };
    console.log(`${name}: ${err.constructor.name} (status ${err.status}), calls=${calls.n}`);
  }
}

// Same test with the OpenAI SDK
const o = sequence([429, 429, 429]);
const openai = new OpenAI({ apiKey: "fake-key", fetch: o.f });
try { await openai.responses.create({ model: "m", input: "hello" }); }
catch (e) { console.log(`OpenAI 429 always: ${(e as object).constructor.name}, calls=${o.calls.n}`); }

// Output:
// 429 then 200, maxRetries 2 (default): succeeded, calls=2
// 429 always, maxRetries 2: RateLimitError (status 429), calls=3
// 429 always, maxRetries 0: RateLimitError (status 429), calls=1
// 400, maxRetries 2: BadRequestError (status 400), calls=1
// OpenAI 429 always: RateLimitError, calls=3

A 429 followed by a 200 resolves by itself with two calls. A 429 that does not go away produces three calls in total (the first plus two retries) and then a RateLimitError; with maxRetries: 0 the call is a single one. A 400 is not retried, and rightly so: the request is wrong and repeating it does not fix it. The practical consequence is that on top of the SDK you must not add a second layer of retries: you would multiply the calls (three times three makes nine) just when the service is asking you to slow down. What is left for you to decide is the behaviour after the last error: a clear message to the user and, if it makes sense for your case, a fallback provider.

In the Anthropic documentation transient errors have precise codes: 429 for the rate limit, 500 for the internal error, 529 for overload. There is a nuance not to be missed: the same stream can fail midway, after having already sent part of the text, and in that case there is no HTTP code to read, because the 200 status has already gone out. That is why the server in the next section turns an exception into an error event inside the stream.

The proxy: the key stays on the server

If the browser called the API directly, the key would be readable by anyone who looks at the network tab. The intermediate server receives the user's message, adds the key, calls the provider and forwards the text. It also has the job the provider does not have: deciding who can call and how much. The delicate part is the streaming format towards the browser, and the listing isolates the function that produces it, sendAsSse, together with two client-side readings to show a frequent defect.

Listing 4: SSE events from the server and two ways of reading them (run; identical output in two runs)
// Server side: turns a text stream into SSE events. "res" is any object with write/end.
export type Output = { write(s: string): unknown; end(): unknown };

export async function sendAsSse(texts: AsyncIterable<string>, res: Output): Promise<void> {
  try {
    for await (const t of texts) res.write(`data: ${JSON.stringify({ content: t })}\n\n`);
    res.write("data: [DONE]\n\n");
  } catch {
    // A generic message to the browser: the error detail stays in the server logs.
    res.write(`data: ${JSON.stringify({ error: "AI service temporarily unavailable" })}\n\n`);
  } finally {
    res.end();
  }
}

// Client side, naive version: treats every network block as made of whole lines.
export function readNaive(blocks: string[]): string {
  let text = "";
  for (const b of blocks) {
    for (const line of b.split("\n")) {
      if (!line.startsWith("data: ")) continue;
      try { const d = JSON.parse(line.slice(6)); if (d.content) text += d.content; } catch { /* split line: lost */ }
    }
  }
  return text;
}

// Client side, buffered version: an event is complete only when the empty line arrives.
export function readBuffered(blocks: string[]): string {
  let text = "", buffer = "";
  for (const b of blocks) {
    buffer += b;
    let end: number;
    while ((end = buffer.indexOf("\n\n")) >= 0) {
      const event = buffer.slice(0, end);
      buffer = buffer.slice(end + 2);
      for (const line of event.split("\n")) {
        if (!line.startsWith("data: ")) continue;
        const data = line.slice(6);
        if (data === "[DONE]") return text;
        const d = JSON.parse(data);
        if (d.content) text += d.content;
      }
    }
  }
  return text;
}

// --- Test: two words sent by the server, then the network delivers them cut in half.
async function* words() { yield "Hello"; yield ", world"; }
const written: string[] = [];
await sendAsSse(words(), { write: s => written.push(String(s)), end: () => {} });
const stream = written.join("");
const cut = stream.indexOf("world") + 2;       // cuts inside the second word
const blocks = [stream.slice(0, cut), stream.slice(cut)];

console.log("stream:", JSON.stringify(stream));
console.log("network blocks:", JSON.stringify(blocks));
console.log("naive   :", JSON.stringify(readNaive(blocks)));
console.log("buffered:", JSON.stringify(readBuffered(blocks)));

async function* failing() { yield "Hello"; throw new Error("key sk-secret rejected"); }
const errors: string[] = [];
await sendAsSse(failing(), { write: s => errors.push(String(s)), end: () => {} });
console.log("after a failure:", JSON.stringify(errors));

// Output:
// stream: "data: {\"content\":\"Hello\"}\n\ndata: {\"content\":\", world\"}\n\ndata: [DONE]\n\n"
// network blocks: ["data: {\"content\":\"Hello\"}\n\ndata: {\"content\":\", wo","rld\"}\n\ndata: [DONE]\n\n"]
// naive   : "Hello"
// buffered: "Hello, world"
// after a failure: ["data: {\"content\":\"Hello\"}\n\n","data: {\"error\":\"AI service temporarily unavailable\"}\n\n"]

The server writes an event every time it receives a fragment and closes with [DONE]. The defect is in the client: the network delivers blocks of bytes that do not coincide with the events. In the test the block is cut inside the word "world": the naive reading splits the text by lines, the data: ... line arrives halfway, the JSON.parse fails and the exception is swallowed: nothing is left of the second word, and the output shows only "Hello". The buffered version accumulates the bytes and treats as complete only what ends with the empty line: "Hello, world". The last line of the output shows the other decision taken in the server: after a failure the browser receives a generic message, and the text of the exception (here it contains a fake key) does not leave the server.

CORS and rate limiting

An open proxy is a gift: anyone who finds it can consume your credit. Two essential defences are the origin check (CORS) and a limit of requests per address. The listing queries the cors package the way Express would, in the three cases that matter, and tests a sliding-window limit.

Listing 5: CORS in three cases and a per-address limit (run; identical output in two runs)
import cors from "cors";

// 1. CORS: what the "cors" package answers in three cases, queried the way Express would.
function tryCors(origin: string | string[] | undefined, requester: string): string {
  const headers: Record<string, string> = {};
  const res = {
    setHeader: (k: string, v: string) => { headers[k.toLowerCase()] = v; },
    getHeader: (k: string) => headers[k.toLowerCase()],
    end: () => {},
    statusCode: 200,
  };
  const req = { method: "GET", headers: { origin: requester } };
  cors({ origin })(req as never, res as never, () => {});
  return headers["access-control-allow-origin"] ?? "(no header)";
}
const readVariable = (name: string): string | undefined => process.env[name];
const variable = readVariable("ALLOWED_ORIGINS_NOT_SET");   // variable not set
const allowed = ["https://my-site.example"];
console.log("variable not set       :", tryCors(variable?.split(","), "https://my-site.example"));
console.log("origin in the list     :", tryCors(allowed, "https://my-site.example"));
console.log("origin outside the list:", tryCors(allowed, "https://other.example"));

// 2. Per-address limit with a sliding window, without hidden global state.
export function createLimit(max: number, windowMs: number) {
  const requests = new Map<string, number[]>();
  return (ip: string, now: number): boolean => {
    const recent = (requests.get(ip) ?? []).filter(t => now - t < windowMs);
    if (recent.length >= max) { requests.set(ip, recent); return false; }
    requests.set(ip, [...recent, now]);
    return true;
  };
}
const allow = createLimit(3, 60_000);
const results = [0, 1000, 2000, 3000, 61_000].map(t => allow("203.0.113.7", t));
console.log("3 requests per 60 s, at 0/1/2/3/61 s:", results.join(" "));
console.log("other address, at 3 s :", allow("203.0.113.8", 3000));

// Output:
// variable not set       : (no header)
// origin in the list     : https://my-site.example
// origin outside the list: (no header)
// 3 requests per 60 s, at 0/1/2/3/61 s: true true true false true
// other address, at 3 s : true

With the origins variable absent, the cors package 2.8.6 adds no header: browsers then block calls from other origins, which is a safe behaviour but hard to diagnose, because no error shows up on the server side. With a list that contains the origin, the header reports that origin; with a list that does not contain it, it is missing again. The limit accepts three requests, rejects the fourth, and after 61 seconds starts again; another address has a count of its own. For an address other than the proxy's there is one more step: behind a reverse proxy such as nginx, Express sees the proxy's address unless you set trust proxy, as its guide explains. Without it, all users share the same count.

The in-memory limit is valid for a single process: if you start more instances, each has its own count and you need a shared state. It is fine to begin with, not to scale.

The complete server, compiled

The listing puts the pieces together with Express. It validates the provider and the length of the messages, decides the system prompt on the server instead of accepting it from the browser (otherwise whoever calls could replace it), and forwards the stream with the function of listing 4. It is a schema to adapt, not run: starting it would require a listening port and real keys. I passed it to the compiler, which checked all the types against the installed SDKs.

Listing 6: the proxy with Express (compiled with tsc, not run)
import express from "express";
import cors from "cors";
import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";
import { sendAsSse } from "../sse.ts";            // the functions of listing 4
import { createLimit } from "./05_proxy_limits.ts";    // the limit of listing 5

const MODELS = {                                     // the names come from the configuration
  openai: process.env.OPENAI_MODEL ?? "",
  anthropic: process.env.ANTHROPIC_MODEL ?? "",
};
const openai = new OpenAI();                          // reads OPENAI_API_KEY
const anthropic = new Anthropic();                    // reads ANTHROPIC_API_KEY

const app = express();
app.set("trust proxy", 1);                            // a single proxy (nginx) in front of the app
app.use(cors({ origin: (process.env.ALLOWED_ORIGINS ?? "").split(",").filter(Boolean) }));
app.use(express.json({ limit: "32kb" }));

const allow = createLimit(20, 60_000);
app.use("/api", (req, res, next) => {
  if (!allow(req.ip ?? "unknown", Date.now())) { res.status(429).json({ error: "Too many requests" }); return; }
  next();
});

type Msg = { role: "user" | "assistant"; content: string };

async function* fromOpenAI(messages: Msg[], system: string): AsyncGenerator<string> {
  const stream = await openai.responses.create({ model: MODELS.openai, instructions: system, input: messages, stream: true });
  for await (const e of stream) if (e.type === "response.output_text.delta") yield e.delta;
}
async function* fromAnthropic(messages: Msg[], system: string): AsyncGenerator<string> {
  const stream = anthropic.messages.stream({ model: MODELS.anthropic, max_tokens: 1024, system, messages });
  for await (const e of stream) if (e.type === "content_block_delta" && e.delta.type === "text_delta") yield e.delta.text;
}

app.post("/api/chat/stream", async (req, res) => {
  const { provider, messages } = req.body as { provider?: string; messages?: Msg[] };
  if ((provider !== "openai" && provider !== "anthropic") || !Array.isArray(messages) || messages.length === 0 || messages.length > 50) {
    res.status(400).json({ error: "Invalid request" });
    return;
  }
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  const system = "You are a technical assistant.";            // decided by the server, not by the browser
  await sendAsSse(provider === "openai" ? fromOpenAI(messages, system) : fromAnthropic(messages, system), res);
});

app.listen(3001);

Note three choices. trust proxy is 1 because it presupposes exactly one proxy in front of the app: a value that is too permissive lets whoever calls forge their own address, and it is the same warning as in the Express guide. The list of origins, if the variable is missing, becomes an empty array, that is no origin allowed. And express.json({ limit: "32kb" }) prevents a single request from sending a huge body into memory, because every token sent to the provider is paid for.

The client in the browser

On the browser side you need the buffered reading of listing 4, with one more detail: the bytes of an accented character can be split between two blocks. The TextDecoder must remember the bytes left halfway between one call and the next, and it does so only with the { stream: true } option. The listing produces an async generator, and tests both variants by cutting the "é" of "Perché" (Italian for "why") in half.

Listing 7: SSE reading with a buffer and a streaming decoder (run; compatible with Angular via RxJS)
import { from } from "rxjs";

// Reads an SSE response and produces the text fragments. Works in the browser and in Node.
export async function* readSse(response: Response): AsyncGenerator<string> {
  const reader = response.body!.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  while (true) {
    const { done, value } = await reader.read();
    if (done) return;
    buffer += decoder.decode(value, { stream: true });     // stream: true keeps the bytes of a split character
    let end: number;
    while ((end = buffer.indexOf("\n\n")) >= 0) {
      const event = buffer.slice(0, end);
      buffer = buffer.slice(end + 2);
      for (const line of event.split("\n")) {
        if (!line.startsWith("data: ")) continue;
        const data = line.slice(6);
        if (data === "[DONE]") return;
        const d = JSON.parse(data);
        if (d.error) throw new Error(d.error);
        if (d.content) yield d.content as string;
      }
    }
  }
}

// --- Test: "Perché" (Italian for "why") with the é (2 bytes in UTF-8) cut between two network blocks.
const bytes = new TextEncoder().encode('data: {"content":"Perché"}\n\ndata: [DONE]\n\n');
const cut = bytes.indexOf(0xc3) + 1;                      // inside the é
const fake = () => new Response(new ReadableStream({
  start(c) { c.enqueue(bytes.slice(0, cut)); c.enqueue(bytes.slice(cut)); c.close(); },
}));

let text = "";
for await (const t of readSse(fake())) text += t;
console.log("with stream:true :", text);

const naive = new TextDecoder();                              // same test without { stream: true }
console.log("without stream   :", JSON.stringify(naive.decode(bytes.slice(0, cut)) + naive.decode(bytes.slice(cut))).slice(0, 40));

// For Angular: an AsyncGenerator becomes an Observable with RxJS from().
const observed: string[] = [];
from(readSse(fake())).subscribe({ next: t => observed.push(t), complete: () => console.log("Observable:", observed.join("")) });

// Output:
// with stream:true : Perché
// without stream   : "data: {\"content\":\"Perch��\"}\n\ndata
// Observable: Perché

Without stream: true the "é" becomes two replacement characters (the two diamonds in the output), with the option the text arrives intact. The last line shows how to adapt the generator to an Angular service: RxJS's from() accepts an async iterator, so you return the Observable and the component keeps using subscribe. To cancel the request when the user closes the page, pass an AbortSignal to fetch.

Before publishing the proxy

  • The key is only on the server: no frontend file, no shared repository contains it
  • The input is validated: allowed providers, number and size of messages, system prompt decided by the server
  • A per-address limit exists and trust proxy describes your real infrastructure
  • The allowed origins are listed and you have verified what happens with an unexpected origin
  • Errors do not leave the server: a generic message to the browser, the details in the logs

The five items are ordered by the cost of the mistake: an exposed key is paid immediately and in money, a missing limit is paid at the first wave of requests, an error message that is too rich is paid when someone reads it. None replaces another, and the test that verifies them all is the same: call the proxy from outside, without cookies and without your origin, and check what it manages to do.

What happens to users' data

Think of a professional firm that uses a model to sort incoming mail: the body of an email contains clients' data. Sending it to an external API means entrusting that data to a provider, and the GDPR, in Article 28, paragraph 1, asks the controller to use only processors that provide sufficient guarantees. Before writing a line of code you therefore need an agreement with the provider, a check of where the data is processed and a reduction of what you send (subject and first lines, not the attachments). When a processing cannot leave your perimeter, the alternative route is a local model, the topic of Local LLMs with Ollama.

What you can do now

You can read the shape of OpenAI and Anthropic requests and bring them into a configuration that does not contain model names; you can consume the streaming of the two SDKs; you know that repeated attempts are already in the SDK and how to control them; you can write a proxy that keeps the key on the server, validates input, limits requests and does not leak errors; and you can read an SSE stream without losing pieces or accented letters. What stays outside a test without a network is the real behaviour of the model: quality, latency and costs are measured with your key and your data. The next step in the series is running a model locally; for a system that decides by itself which tools to call, see AI Agents.

Frequently asked questions

Do I have to choose between OpenAI and Anthropic?

No, but it is better to isolate the choice. In the proxy of listing 6 the provider is a parameter and each provider has a function that produces a text stream: adding a third means writing another function of the same type. The comparison on quality you make with your own questions, because it depends on the task.

Is it safe to put the API key in the frontend?

No. Any key present in the browser code is readable by whoever opens the developer tools, and an exposed key consumes your credit. The key stays on the server, and the browser talks only to your proxy, which decides who can call and how much.

Do I need to write a retry system?

As a rule no: both SDKs retry transient errors by themselves. Write one only if you need a different policy, and in that case disable the SDK's with maxRetries: 0 so as not to multiply the calls.

When the model has to learn something the prompt cannot carry, the choice is the one between fine-tuning and RAG; when it has to run in the release pipeline, the case is AI in CI/CD.

If the model has to answer from your own documents, you first need somewhere to search them: vector databases are the previous article in the series.

Sources

Listings 1, 2, 3, 4, 5 and 7 were run with Node 24.11 without a network: the SDKs receive a scripted fake fetch, and the outputs (tokens, texts, outcomes) are those of the script, not of a model. Listing 6 was only compiled with TypeScript 7.0.2 and not run. No model was called and no port was opened.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects