feat(chat): import standalone OpenAI chat demo

This commit is contained in:
2026-11-02 09:19:04 +00:00
parent 94a23b74a7
commit 048d4eab2f
8 changed files with 638 additions and 1 deletions

5
.dockerignore Normal file
View File

@@ -0,0 +1,5 @@
*
!Dockerfile
!server.js
!public/
!public/**

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
.env
.env.*
!.env.example
node_modules/
*.log

15
Dockerfile Normal file
View File

@@ -0,0 +1,15 @@
FROM node:22-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --chown=node:node server.js ./server.js
COPY --chown=node:node public ./public
USER node
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:8080/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server.js"]

View File

@@ -1,2 +1,36 @@
# openai-chat-demo # OpenAI Chat Demo
A small web chat service that sends questions to the OpenAI Responses API. The browser talks only to this app; `API_KEY` stays in the server container and is never sent to the browser.
## Configuration
The container uses exactly two application environment variables:
| Variable | Purpose | Example |
| --- | --- | --- |
| `MODEL` | OpenAI model name to call | `gpt-4.1-mini` |
| `API_KEY` | OpenAI API key; configure this as a secret | Set it in the runtime secret manager |
The app listens on port `8080`.
## Run with Docker
Set the real key in your shell or secret manager, then run:
```sh
docker run --rm -p 8080:8080 \
-e MODEL=gpt-4.1-mini \
-e API_KEY \
lucnguyen666/aisp-openai-chat-demo:1.0.0
```
Open <http://localhost:8080>. For a platform deployment, map `MODEL` as a regular environment variable and `API_KEY` as a secret environment variable.
## Build locally
```sh
docker build -t aisp-openai-chat-demo:local .
docker run --rm -p 8080:8080 -e MODEL=gpt-4.1-mini -e API_KEY aisp-openai-chat-demo:local
```
The chat history is held in browser memory for the current page session. The server calls `POST https://api.openai.com/v1/responses` with `store: false`. It does not log prompts or API keys.

86
public/app.js Normal file
View File

@@ -0,0 +1,86 @@
"use strict";
const form = document.querySelector("#chat-form");
const input = document.querySelector("#question");
const sendButton = document.querySelector("#send-button");
const messagesElement = document.querySelector("#messages");
const messages = [];
function appendMessage(role, content, { pending = false } = {}) {
const article = document.createElement("article");
article.className = `message ${role === "user" ? "user-message" : "assistant-message"}`;
const avatar = document.createElement("div");
avatar.className = "avatar";
avatar.setAttribute("aria-hidden", "true");
avatar.textContent = role === "user" ? "Bạn" : "AI";
const bubble = document.createElement("div");
bubble.className = "bubble";
if (pending) {
bubble.classList.add("pending-bubble");
bubble.setAttribute("aria-label", "Model đang trả lời");
bubble.innerHTML = '<span></span><span></span><span></span>';
} else {
const paragraph = document.createElement("p");
paragraph.textContent = content;
bubble.append(paragraph);
}
article.append(avatar, bubble);
messagesElement.append(article);
messagesElement.scrollTop = messagesElement.scrollHeight;
return article;
}
function resizeInput() {
input.style.height = "auto";
input.style.height = `${Math.min(input.scrollHeight, 180)}px`;
}
input.addEventListener("input", resizeInput);
input.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
form.requestSubmit();
}
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const question = input.value.trim();
if (!question || sendButton.disabled) return;
messages.push({ role: "user", content: question });
appendMessage("user", question);
input.value = "";
resizeInput();
sendButton.disabled = true;
sendButton.querySelector("span").textContent = "Đang gửi";
const pending = appendMessage("assistant", "", { pending: true });
try {
const response = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages }),
});
const result = await response.json();
pending.remove();
if (!response.ok) throw new Error(result.error || "Không thể nhận câu trả lời.");
messages.push({ role: "assistant", content: result.text });
appendMessage("assistant", result.text);
} catch (error) {
pending.remove();
appendMessage("assistant", error.message || "Đã xảy ra lỗi. Hãy thử lại.");
// The next request should not include an unanswered user turn twice.
messages.pop();
input.value = question;
resizeInput();
} finally {
sendButton.disabled = false;
sendButton.querySelector("span").textContent = "Gửi";
input.focus();
}
});

55
public/index.html Normal file
View File

@@ -0,0 +1,55 @@
<!doctype html>
<html lang="vi">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#f7f8fc" />
<title>OpenAI Chat Demo</title>
<link rel="stylesheet" href="/styles.css" />
<script src="/app.js" defer></script>
</head>
<body>
<main class="page-shell">
<section class="chat-card" aria-label="Trò chuyện với model">
<header class="topbar">
<div class="brand-mark" aria-hidden="true">AI</div>
<div>
<p class="eyebrow">SERVICE DEMO</p>
<h1>OpenAI Chat</h1>
</div>
<span class="status"><span class="status-dot"></span> Sẵn sàng</span>
</header>
<div id="messages" class="messages" aria-live="polite" aria-relevant="additions text">
<article class="message assistant-message">
<div class="avatar" aria-hidden="true">AI</div>
<div class="bubble">
<p>Xin chào! Bạn muốn hỏi điều gì?</p>
</div>
</article>
</div>
<form id="chat-form" class="composer">
<label class="visually-hidden" for="question">Câu hỏi</label>
<textarea
id="question"
name="question"
rows="1"
maxlength="8000"
placeholder="Nhập câu hỏi…"
autocomplete="off"
required
></textarea>
<button id="send-button" type="submit" aria-label="Gửi câu hỏi">
<span>Gửi</span>
<svg viewBox="0 0 20 20" aria-hidden="true">
<path d="M3.2 10h12.6M10.5 4.7l5.3 5.3-5.3 5.3" />
</svg>
</button>
<p class="composer-hint">Enter để gửi · Shift + Enter để xuống dòng</p>
</form>
</section>
<p class="page-note">Bản demo gọi model qua backend; API key không được gửi xuống trình duyệt.</p>
</main>
</body>
</html>

209
public/styles.css Normal file
View File

@@ -0,0 +1,209 @@
:root {
color-scheme: light;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: #172033;
background: #f7f8fc;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
--muted: #737e91;
--line: #e6e9f0;
--accent: #5a5be7;
}
* { box-sizing: border-box; }
body {
min-width: 320px;
min-height: 100vh;
margin: 0;
background:
radial-gradient(ellipse at 15% 5%, rgba(109, 110, 240, .08), transparent 36rem),
#f7f8fc;
}
button, textarea { font: inherit; }
.page-shell {
display: flex;
min-height: 100vh;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 36px 20px 20px;
}
.chat-card {
display: flex;
width: min(100%, 820px);
height: min(760px, calc(100vh - 100px));
min-height: 480px;
flex-direction: column;
overflow: hidden;
border: 1px solid rgba(226, 230, 239, .9);
border-radius: 22px;
background: #fff;
box-shadow: 0 24px 70px rgba(40, 48, 80, .10), 0 3px 12px rgba(40, 48, 80, .04);
}
.topbar {
display: flex;
min-height: 82px;
align-items: center;
gap: 13px;
padding: 17px 23px;
border-bottom: 1px solid var(--line);
}
.brand-mark, .avatar {
display: grid;
flex: 0 0 auto;
place-items: center;
font-size: 12px;
font-weight: 750;
}
.brand-mark {
width: 42px;
height: 42px;
border-radius: 14px;
background: #eeefff;
color: var(--accent);
letter-spacing: -.04em;
}
.eyebrow {
margin: 0 0 2px;
color: #8a91a3;
font-size: 10px;
font-weight: 750;
letter-spacing: .12em;
}
h1 { margin: 0; font-size: 16px; font-weight: 700; letter-spacing: -.02em; }
.status {
display: inline-flex;
align-items: center;
gap: 7px;
margin-left: auto;
color: #687488;
font-size: 12px;
}
.status-dot { width: 7px; height: 7px; border-radius: 50%; background: #30b879; }
.messages {
display: flex;
flex: 1;
flex-direction: column;
gap: 22px;
overflow-y: auto;
padding: 30px clamp(18px, 5vw, 44px);
scroll-behavior: smooth;
}
.message { display: flex; max-width: 88%; align-items: flex-end; gap: 10px; }
.user-message { align-self: flex-end; flex-direction: row-reverse; }
.avatar {
width: 30px;
height: 30px;
border: 1px solid #e7e9f1;
border-radius: 11px;
background: #fff;
color: #7a8192;
font-size: 10px;
}
.assistant-message .avatar { background: #f1f1ff; border-color: #e8e8ff; color: var(--accent); }
.user-message .avatar { background: #e9efff; border-color: #e0e8ff; color: #4e68b7; }
.bubble {
max-width: 100%;
border: 1px solid #eceef4;
border-radius: 16px 16px 16px 5px;
background: #fafbfe;
color: #30394b;
line-height: 1.65;
overflow-wrap: anywhere;
padding: 11px 15px;
white-space: pre-wrap;
}
.bubble p { margin: 0; }
.user-message .bubble { border-color: #e0e3ff; border-radius: 16px 16px 5px 16px; background: #f0f1ff; }
.composer {
display: grid;
grid-template-columns: 1fr auto;
align-items: end;
gap: 10px;
margin: 0 22px 20px;
padding: 12px 12px 8px 16px;
border: 1px solid #e3e6ef;
border-radius: 17px;
background: #fff;
box-shadow: 0 5px 18px rgba(37, 45, 74, .045);
}
.composer:focus-within { border-color: #c9caff; box-shadow: 0 0 0 3px rgba(90, 91, 231, .08); }
textarea {
width: 100%;
max-height: 180px;
min-height: 35px;
resize: none;
border: 0;
outline: 0;
padding: 7px 0;
color: #222b3b;
line-height: 1.5;
}
textarea::placeholder { color: #a0a6b4; }
.composer button {
display: inline-flex;
height: 38px;
align-items: center;
gap: 8px;
border: 0;
border-radius: 12px;
background: var(--accent);
color: white;
cursor: pointer;
font-size: 12px;
font-weight: 650;
padding: 0 12px;
transition: background .16s ease, transform .16s ease;
}
.composer button:hover:not(:disabled) { background: #494ad1; transform: translateY(-1px); }
.composer button:disabled { cursor: wait; opacity: .68; }
.composer button svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 1.7; }
.composer-hint { grid-column: 1 / -1; margin: -3px 0 0; color: #a0a6b4; font-size: 10px; }
.page-note { margin: 13px 0 0; color: #9299a8; font-size: 11px; text-align: center; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; clip-path: inset(50%); }
.pending-bubble { display: flex; min-width: 64px; align-items: center; gap: 4px; }
.pending-bubble span { width: 6px; height: 6px; border-radius: 50%; background: #9da1ec; animation: pulse 1.1s infinite ease-in-out; }
.pending-bubble span:nth-child(2) { animation-delay: .15s; }
.pending-bubble span:nth-child(3) { animation-delay: .3s; }
@keyframes pulse { 0%, 60%, 100% { opacity: .38; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-3px); } }
@media (max-width: 600px) {
.page-shell { justify-content: stretch; padding: 0; }
.chat-card { width: 100%; height: 100dvh; min-height: 420px; border: 0; border-radius: 0; }
.topbar { min-height: 72px; padding-inline: 17px; }
.messages { padding: 22px 16px; }
.message { max-width: 94%; }
.composer { margin: 0 12px 12px; }
.page-note { display: none; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; transition-duration: .01ms !important; }
}

228
server.js Normal file
View File

@@ -0,0 +1,228 @@
"use strict";
const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
const PORT = 8080;
const PUBLIC_DIR = path.join(__dirname, "public");
const MAX_BODY_BYTES = 64 * 1024;
const MAX_MESSAGES = 20;
const MAX_MESSAGE_LENGTH = 8000;
const REQUEST_TIMEOUT_MS = 60_000;
const securityHeaders = {
"Content-Security-Policy":
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer",
};
function sendJson(res, statusCode, value) {
res.writeHead(statusCode, {
...securityHeaders,
"Cache-Control": "no-store",
"Content-Type": "application/json; charset=utf-8",
});
res.end(JSON.stringify(value));
}
function readJson(req) {
return new Promise((resolve, reject) => {
let body = "";
let tooLarge = false;
req.setEncoding("utf8");
req.on("data", (chunk) => {
if (tooLarge) return;
body += chunk;
if (Buffer.byteLength(body, "utf8") > MAX_BODY_BYTES) {
tooLarge = true;
}
});
req.on("end", () => {
if (tooLarge) {
reject(Object.assign(new Error("Request body too large"), { statusCode: 413 }));
return;
}
try {
resolve(JSON.parse(body));
} catch {
reject(Object.assign(new Error("Invalid JSON"), { statusCode: 400 }));
}
});
req.on("error", () => {
reject(Object.assign(new Error("Unable to read request"), { statusCode: 400 }));
});
});
}
function validateMessages(value) {
if (!value || !Array.isArray(value.messages)) {
return "Cần gửi danh sách messages.";
}
if (value.messages.length === 0 || value.messages.length > MAX_MESSAGES) {
return `Cuộc trò chuyện cần có từ 1 đến ${MAX_MESSAGES} tin nhắn.`;
}
for (const message of value.messages) {
if (
!message ||
!["user", "assistant"].includes(message.role) ||
typeof message.content !== "string" ||
message.content.trim().length === 0 ||
message.content.length > MAX_MESSAGE_LENGTH
) {
return "Tin nhắn không hợp lệ hoặc vượt quá giới hạn độ dài.";
}
}
if (value.messages.at(-1).role !== "user") {
return "Tin nhắn cuối cùng phải là câu hỏi của bạn.";
}
return null;
}
function extractText(response) {
if (typeof response.output_text === "string" && response.output_text.trim()) {
return response.output_text.trim();
}
const parts = [];
for (const item of response.output || []) {
if (item.type !== "message" || !Array.isArray(item.content)) continue;
for (const content of item.content) {
if (content.type === "output_text" && typeof content.text === "string") {
parts.push(content.text);
}
}
}
return parts.join("\n").trim();
}
async function handleChat(req, res) {
const model = process.env.MODEL?.trim();
const apiKey = process.env.API_KEY?.trim();
if (!model || !apiKey) {
sendJson(res, 503, {
error: "Chưa cấu hình MODEL hoặc API_KEY cho container.",
});
return;
}
let payload;
try {
payload = await readJson(req);
} catch (error) {
sendJson(res, error.statusCode || 400, { error: error.message });
return;
}
const validationError = validateMessages(payload);
if (validationError) {
sendJson(res, 400, { error: validationError });
return;
}
let upstream;
try {
upstream = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
input: payload.messages.map(({ role, content }) => ({ role, content })),
store: false,
}),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
} catch (error) {
if (error.name === "AbortError" || error.name === "TimeoutError") {
sendJson(res, 504, { error: "OpenAI phản hồi quá thời gian chờ. Hãy thử lại." });
} else {
sendJson(res, 502, { error: "Không thể kết nối tới OpenAI." });
}
return;
}
if (!upstream.ok) {
if (upstream.status === 401 || upstream.status === 403) {
sendJson(res, 502, { error: "OpenAI từ chối yêu cầu. Hãy kiểm tra API_KEY và quyền truy cập model." });
} else if (upstream.status === 429) {
sendJson(res, 502, { error: "OpenAI đang giới hạn yêu cầu hoặc hết quota. Hãy kiểm tra billing và thử lại." });
} else {
sendJson(res, 502, { error: `OpenAI không xử lý được yêu cầu (HTTP ${upstream.status}).` });
}
return;
}
let result;
try {
result = await upstream.json();
} catch {
sendJson(res, 502, { error: "OpenAI trả về dữ liệu không hợp lệ." });
return;
}
const text = extractText(result);
if (!text) {
sendJson(res, 502, { error: "Model không trả về nội dung văn bản." });
return;
}
sendJson(res, 200, { text });
}
function serveStatic(res, fileName, contentType) {
const filePath = path.join(PUBLIC_DIR, fileName);
fs.readFile(filePath, (error, contents) => {
if (error) {
sendJson(res, 500, { error: "Không thể tải giao diện." });
return;
}
res.writeHead(200, {
...securityHeaders,
"Cache-Control": "no-cache",
"Content-Type": contentType,
});
res.end(contents);
});
}
const server = http.createServer((req, res) => {
const requestUrl = new URL(req.url, "http://localhost");
if (req.method === "GET" && requestUrl.pathname === "/health") {
sendJson(res, 200, { status: "ok" });
return;
}
if (req.method === "GET" && requestUrl.pathname === "/") {
serveStatic(res, "index.html", "text/html; charset=utf-8");
return;
}
if (req.method === "GET" && requestUrl.pathname === "/app.js") {
serveStatic(res, "app.js", "text/javascript; charset=utf-8");
return;
}
if (req.method === "GET" && requestUrl.pathname === "/styles.css") {
serveStatic(res, "styles.css", "text/css; charset=utf-8");
return;
}
if (req.method === "POST" && requestUrl.pathname === "/api/chat") {
void handleChat(req, res);
return;
}
sendJson(res, 404, { error: "Không tìm thấy đường dẫn." });
});
server.listen(PORT, "0.0.0.0", () => {
process.stdout.write(`OpenAI chat demo listening on port ${PORT}\n`);
});
for (const signal of ["SIGINT", "SIGTERM"]) {
process.on(signal, () => server.close(() => process.exit(0)));
}