For modern web developers, integrating artificial intelligence into existing software architectures does not require training models from scratch. Enterprise web applications leverage commercial and open-source foundation model APIs — such as OpenAI (GPT-4o), Google (Gemini 1.5 Pro), and Anthropic (Claude 3.5 Sonnet) — to build smart features: natural language search, intelligent customer copilots, automated invoice parsing, and content generation.
Figure 41.1: Production Full-Stack AI Architecture — Client Interface, Secure Backend Proxy, Vector Indexing, and Model API Endpoints.
Never call AI API endpoints directly from browser frontend code (React, Vue, vanilla JS). Malicious users can inspect network requests, extract your secret API key, and exhaust your billing quota within minutes. Always route requests through a secure backend server (Node.js, Python, or PHP) that stores keys in environment variables (.env) and enforces session authentication, rate limiting, and input validation.
| Provider & Model | Context Window | Key Strengths & Pricing Tier |
|---|---|---|
| OpenAI (GPT-4o / GPT-4o-mini) | 128,000 Tokens | Native multimodality (text, vision, audio), structured JSON mode, reliable tool calling, fast token throughput. |
| Google (Gemini 1.5 Pro / Flash) | 2,000,000 Tokens | Industry-leading massive context window (can ingest entire codebases, 1-hour videos, or 50 books in a single prompt!). |
| Anthropic (Claude 3.5 Sonnet) | 200,000 Tokens | Superior coding benchmark performance (HumanEval), complex software engineering, nuanced system instruction adherence. |
| Self-Hosted (Ollama / vLLM) | Custom (e.g. 128k) | Zero per-token API cost, 100% data privacy, fully compatible with OpenAI SDK specification! |
// server.js (Node.js)
const express = require('express');
const OpenAI = require('openai');
require('dotenv').config();
const app = express();
app.use(express.json());
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
app.post('/api/generate-summary', async (req, res) => {
try {
const { userText } = req.body;
if (!userText) return res.status(400).json({ error: "userText is required" });
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "You are an executive summarization engine. Return a 3-bullet summary." },
{ role: "user", content: userText }
],
temperature: 0.3,
max_tokens: 250
});
res.json({ summary: completion.choices[0].message.content });
} catch (error) {
console.error("AI API Error:", error.message);
res.status(500).json({ error: "Internal AI Gateway Error" });
}
});
app.listen(3000, () => console.log("AI Server listening on port 3000"));
# main.py (FastAPI)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import os
from openai import AsyncOpenAI
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
class PromptRequest(BaseModel):
query: str
@app.post("/api/ask")
async def ask_ai(request: PromptRequest):
try:
response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": request.query}],
temperature=0.7
)
return {"answer": response.choices[0].message.content}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
<?php
// api_handler.php
header('Content-Type: application/json');
$apiKey = getenv('OPENAI_API_KEY');
$inputData = json_decode(file_get_contents('php://input'), true);
$userMessage = $inputData['message'] ?? 'Hello AI';
$payload = [
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'system', 'content' => 'You are a helpful customer support agent.'],
['role' => 'user', 'content' => $userMessage]
],
'temperature' => 0.5
];
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Broaden your foundational and advanced AI knowledge across our curriculum:
Streaming AI responses to web browsers with low latency Server-Sent Events.
Parsing and validating structured AI JSON outputs in web backend APIs.
Running local lightweight AI models entirely in the client browser.
Replacing third-party paid APIs with private self-hosted vLLM servers.