Build a Chatbot Backend with OpenAI-Compatible APIs
Why an OpenAI-compatible relay is the fastest way to ship
If you want to build a chatbot backend quickly, the easiest path is to use an API that speaks the same language as the OpenAI SDK. That way, your server code stays simple, your prompts and request format stay familiar, and you can swap models without rewriting your app.
That is exactly why 59API is useful. It is an AI API relay with an OpenAI-compatible interface at https://api.59api.com, so you can call GPT models and Claude models from the same backend code you already know. It is also positioned as one of the cheapest relays, uses native official-quality models without downgrade, and even offers a referral rebate, which matters if you are trying to keep chatbot margins healthy.
Step 1: Set up a minimal backend
Let’s build a small Node.js backend that receives a user message, forwards it to the model, and returns the assistant reply. Install the OpenAI SDK and Express:
npm install express openai dotenv
Create a .env file:
OPENAI_API_KEY=your_59api_key
OPENAI_BASE_URL=https://api.59api.com
Now initialize the client with the custom base URL. Because 59API is OpenAI-compatible, you do not need a special adapter or custom request format.
import OpenAI from "openai";
import express from "express";
import "dotenv/config";
const app = express();
app.use(express.json());
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
baseURL: process.env.OPENAI_BASE_URL,
});
Step 2: Create a chat endpoint
A practical chatbot backend should do three things well: keep the system prompt stable, pass the user message in a structured way, and return a clean response. Here is a simple route:
app.post("/chat", async (req, res) => {
try {
const { message } = req.body;
if (!message) return res.status(400).json({ error: "message is required" });
const response = await client.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "You are a concise support assistant." },
{ role: "user", content: message }
],
temperature: 0.3
});
res.json({
reply: response.choices[0].message.content
});
} catch (error) {
res.status(500).json({ error: "chat request failed" });
}
});
Notice that this looks like a standard OpenAI integration. That is the main advantage of using 59API: the learning curve is low, but you still get access to a broader set of models. If your use case needs a stronger reasoning model, a faster and cheaper one, or a Claude-based workflow, you can choose the model that fits the task without redesigning your backend.
Step 3: Add conversation memory the right way
A chatbot feels much better when it remembers context. In production, do not send only the latest message. Store the conversation history in Redis, Postgres, or your application database, then replay the last few turns on each request.
A good payload usually looks like this:
[
{ "role": "system", "content": "You are a helpful assistant for product questions." },
{ "role": "user", "content": "Does this work with refunds?" },
{ "role": "assistant", "content": "Yes, if the plan is eligible." },
{ "role": "user", "content": "What if I canceled yesterday?" }
]
This structure makes it easy to support multi-turn support bots, sales assistants, onboarding helpers, or internal company chat tools. If you are targeting cost-sensitive usage, 59API can be especially attractive because you can choose lower-cost models for routine questions and reserve stronger models for complex messages.
Step 4: Stream responses for a better UX
For a real chatbot, streaming usually feels much better than waiting for a full answer. With the OpenAI SDK, you can stream tokens to the client as they arrive. That reduces perceived latency and makes your UI feel much more responsive.
const stream = await client.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: message }],
stream: true
});
On the frontend, you can append each chunk to the visible message bubble. This is ideal for support bots and coding assistants, where users expect fast partial output. The key point is that streaming works the same way through 59API because it keeps the OpenAI-compatible request shape intact.
Practical tips before you ship
- Validate input so empty or oversized messages do not waste tokens.
- Set a system prompt that defines tone, safety, and scope.
- Log model name, latency, and token usage for cost tracking.
- Use retries carefully for transient failures, but avoid duplicate replies.
- Pick the cheapest model that meets quality requirements for each endpoint.
If you want a backend that is straightforward to build, easy to maintain, and cheaper to run, an OpenAI-compatible relay is a smart choice. 59API gives you the same familiar developer experience at https://api.59api.com, with access to native-quality Claude and GPT models, so you can ship faster without locking yourself into a costly stack.
Sign up, wire it into your existing OpenAI SDK code, and you can have a production-ready chatbot backend running in an afternoon.
Pronto para começar?
Conecte Claude e GPT em minutos pelos menores preços, sem cortes. Cadastre-se e obtenha sua chave API.
Cadastro grátis