From 048d4eab2f49949a94bcf454e01b2fcc25c5c133 Mon Sep 17 00:00:00 2001 From: lucnguyen1375 Date: Mon, 2 Nov 2026 09:19:04 +0000 Subject: [PATCH] feat(chat): import standalone OpenAI chat demo --- .dockerignore | 5 + .gitignore | 5 + Dockerfile | 15 +++ README.md | 36 +++++++- public/app.js | 86 +++++++++++++++++ public/index.html | 55 +++++++++++ public/styles.css | 209 ++++++++++++++++++++++++++++++++++++++++++ server.js | 228 ++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 638 insertions(+), 1 deletion(-) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 public/app.js create mode 100644 public/index.html create mode 100644 public/styles.css create mode 100644 server.js diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..6c9f82c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +* +!Dockerfile +!server.js +!public/ +!public/** diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1093530 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.env +.env.* +!.env.example +node_modules/ +*.log diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..531f67d --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/README.md b/README.md index f3d4495..92a782a 100644 --- a/README.md +++ b/README.md @@ -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 . 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. diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..528fd92 --- /dev/null +++ b/public/app.js @@ -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 = ''; + } 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(); + } +}); diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..35d08f4 --- /dev/null +++ b/public/index.html @@ -0,0 +1,55 @@ + + + + + + + OpenAI Chat Demo + + + + +
+
+
+ +
+

SERVICE DEMO

+

OpenAI Chat

+
+ Sẵn sàng +
+ +
+
+ +
+

Xin chào! Bạn muốn hỏi điều gì?

+
+
+
+ +
+ + + +

Enter để gửi · Shift + Enter để xuống dòng

+
+
+

Bản demo gọi model qua backend; API key không được gửi xuống trình duyệt.

+
+ + diff --git a/public/styles.css b/public/styles.css new file mode 100644 index 0000000..7f6b239 --- /dev/null +++ b/public/styles.css @@ -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; } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..e475cf3 --- /dev/null +++ b/server.js @@ -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))); +}