Spaces:
Running
Running
Download src/App.js from DeepThoughtAI/pl_ai_frontend: direct link, hf CLI and curl.
- Browser
- Download file 21 kB
-
https://huggingface.co/spaces/DeepThoughtAI/pl_ai_frontend/resolve/main/src/App.js
- Command line
-
hf download hf://spaces/DeepThoughtAI/pl_ai_frontend/src/App.js
-
curl -L -o App.js https://huggingface.co/spaces/DeepThoughtAI/pl_ai_frontend/resolve/main/src/App.js
21 kB
| // src/App.js | |
| import React, { useState } from "react"; | |
| import { sendChat, login, streamChat, uploadPrologFile, getKBMetadata, queryProlog, getMe, registerUser } from "./api"; | |
| import "./App.css"; | |
| import ReactMarkdown from "react-markdown"; | |
| import remarkMath from "remark-math"; | |
| import rehypeKatex from "rehype-katex"; | |
| import "katex/dist/katex.min.css"; | |
| import remarkGfm from "remark-gfm"; | |
| function normalizeLatex(text) { | |
| if (!text) return ""; | |
| let normalized = text; | |
| normalized = normalized.replace(/\\\[(.+?)\\\]/gs, (_, inner) => `$$${inner}$$`); | |
| normalized = normalized.replace(/\\\((.+?)\\\)/gs, (_, inner) => `$${inner}$`); | |
| return normalized; | |
| } | |
| function App() { | |
| // --------------------------- | |
| // Authentication State | |
| // --------------------------- | |
| const [token, setToken] = useState(null); | |
| const [authError, setAuthError] = useState(null); | |
| const [me, setMe] = useState(null); | |
| const [loginForm, setLoginForm] = useState({ | |
| username: "", | |
| password: "", | |
| }); | |
| // --------------------------- | |
| // Chat State | |
| // --------------------------- | |
| const [messages, setMessages] = useState([ | |
| { role: "assistant", text: "Hello! Ask me anything." }, | |
| ]); | |
| const [input, setInput] = useState(""); | |
| const [strictMode, setStrictMode] = useState(true); | |
| const [loading, setLoading] = useState(false); | |
| const [error, setError] = useState(null); | |
| // --------------------------- | |
| // KB Upload State | |
| // --------------------------- | |
| const [uploadStatus, setUploadStatus] = useState(null); | |
| const [kbMetadata, setKbMetadata] = useState(null); | |
| const [showUpload, setShowUpload] = useState(false); | |
| const [showQueryPanel, setShowQueryPanel] = useState(false); | |
| const [showRegisterPanel, setShowRegisterPanel] = useState(false); | |
| // --------------------------- | |
| // Admin Register State | |
| // --------------------------- | |
| const [registerForm, setRegisterForm] = useState({ | |
| username: "", | |
| password: "", | |
| overwrite: false, | |
| }); | |
| const [registerStatus, setRegisterStatus] = useState(null); | |
| // --------------------------- | |
| // Direct Query State | |
| // --------------------------- | |
| const [directQuery, setDirectQuery] = useState(""); | |
| const [queryResults, setQueryResults] = useState(null); | |
| // β AUTO-SCROLL WHENEVER MESSAGES CHANGE β | |
| React.useEffect(() => { | |
| const container = document.querySelector(".messages"); | |
| if (container) { | |
| container.scrollTop = container.scrollHeight; | |
| } | |
| }, [messages]); | |
| // ============================================================ | |
| // LOAD CURRENT USER INFO (after login / token change) | |
| // ============================================================ | |
| React.useEffect(() => { | |
| let cancelled = false; | |
| async function loadMe() { | |
| if (!token) { | |
| setMe(null); | |
| return; | |
| } | |
| try { | |
| const res = await getMe(token); | |
| if (!cancelled) setMe(res); | |
| } catch { | |
| // If token becomes invalid, leave UI working; API calls will fail. | |
| if (!cancelled) setMe(null); | |
| } | |
| } | |
| loadMe(); | |
| return () => { | |
| cancelled = true; | |
| }; | |
| }, [token]); | |
| // ============================================================ | |
| // LOGIN HANDLER | |
| // ============================================================ | |
| async function handleLogin(e) { | |
| e.preventDefault(); | |
| setAuthError(null); | |
| try { | |
| const res = await login(loginForm.username, loginForm.password); | |
| setToken(res.token); // Save JWT | |
| setAuthError(null); | |
| } catch (err) { | |
| setAuthError(err.message || "Login failed"); | |
| } | |
| } | |
| // ============================================================ | |
| // REGISTER USER HANDLER (ADMIN) | |
| // ============================================================ | |
| async function handleRegisterUser(e) { | |
| e.preventDefault(); | |
| setRegisterStatus(null); | |
| const username = (registerForm.username || "").trim(); | |
| const password = (registerForm.password || "").trim(); | |
| if (!username || !password) { | |
| setRegisterStatus("Error: Missing username or password"); | |
| return; | |
| } | |
| try { | |
| const result = await registerUser(username, password, token, registerForm.overwrite); | |
| setRegisterStatus(`Created user: ${result.username}`); | |
| setRegisterForm({ username: "", password: "", overwrite: false }); | |
| } catch (err) { | |
| setRegisterStatus(`Error: ${err.message}`); | |
| } | |
| } | |
| // ============================================================ | |
| // FILE UPLOAD HANDLER | |
| // ============================================================ | |
| async function handleFileUpload(e) { | |
| const file = e.target.files[0]; | |
| if (!file) return; | |
| setUploadStatus("Uploading..."); | |
| try { | |
| const text = await file.text(); | |
| const result = await uploadPrologFile(text, token); | |
| setUploadStatus(result.message || "Upload successful!"); | |
| // Refresh metadata | |
| const metadata = await getKBMetadata(token); | |
| setKbMetadata(metadata.metadata); | |
| } catch (err) { | |
| setUploadStatus(`Error: ${err.message}`); | |
| } | |
| } | |
| // ============================================================ | |
| // LOAD KB METADATA | |
| // ============================================================ | |
| async function handleLoadMetadata() { | |
| try { | |
| const result = await getKBMetadata(token); | |
| setKbMetadata(result.metadata); | |
| } catch (err) { | |
| setKbMetadata(`Error: ${err.message}`); | |
| } | |
| } | |
| // ============================================================ | |
| // DIRECT PROLOG QUERY | |
| // ============================================================ | |
| async function handleDirectQuery(e) { | |
| e.preventDefault(); | |
| if (!directQuery.trim()) return; | |
| try { | |
| const result = await queryProlog(directQuery, token); | |
| setQueryResults(result.solutions); | |
| } catch (err) { | |
| setQueryResults([{ error: err.message }]); | |
| } | |
| } | |
| // ============================================================ | |
| // SEND CHAT MESSAGE | |
| // ============================================================ | |
| async function handleSend(e) { | |
| if (e) e.preventDefault(); | |
| if (!input.trim() || loading || !token) return; | |
| const userMsg = { role: "user", text: input.trim() }; | |
| const newMessages = [...messages, userMsg]; | |
| // Create empty assistant bubble for streaming | |
| const assistantMsg = { role: "assistant", text: "", debug: null }; | |
| newMessages.push(assistantMsg); | |
| setMessages(newMessages); | |
| setInput(""); | |
| setError(null); | |
| setLoading(true); | |
| try { | |
| const historyForBackend = newMessages.map((m) => ({ | |
| role: m.role, | |
| content: m.text, | |
| })); | |
| // STREAM HERE β¬β¬β¬ | |
| await streamChat( | |
| userMsg.text, | |
| strictMode, | |
| historyForBackend, | |
| token, | |
| (chunk) => { | |
| assistantMsg.text += chunk; // append chunk | |
| setMessages([...newMessages]); // re-render UI | |
| } | |
| ); | |
| // After streaming completes, fetch debug info via non-streaming endpoint | |
| try { | |
| const debugResult = await sendChat(userMsg.text, strictMode, historyForBackend, token); | |
| if (debugResult.prolog_query_info) { | |
| assistantMsg.debug = debugResult.prolog_query_info; | |
| setMessages([...newMessages]); | |
| } else { | |
| // Still re-render if we replaced the text above. | |
| setMessages([...newMessages]); | |
| } | |
| } catch (debugErr) { | |
| // Ignore debug fetch errors | |
| } | |
| } catch (err) { | |
| assistantMsg.text += `\n[Error: ${err.message}]`; | |
| setMessages([...newMessages]); | |
| } finally { | |
| setLoading(false); | |
| } | |
| } | |
| // ============================================================ | |
| // LOGIN SCREEN (shown if no token) | |
| // ============================================================ | |
| if (!token) { | |
| return ( | |
| <div className="app-root"> | |
| <header className="header"> | |
| <h1 className="header-title">Prolog AI</h1> | |
| </header> | |
| <main className="main login"> | |
| <form className="login-form" onSubmit={handleLogin}> | |
| <h2>Sign In</h2> | |
| <input | |
| type="text" | |
| placeholder="Username" | |
| value={loginForm.username} | |
| onChange={(e) => | |
| setLoginForm({ ...loginForm, username: e.target.value }) | |
| } | |
| /> | |
| <input | |
| type="password" | |
| placeholder="Password" | |
| value={loginForm.password} | |
| onChange={(e) => | |
| setLoginForm({ ...loginForm, password: e.target.value }) | |
| } | |
| /> | |
| <button type="submit">Log In</button> | |
| {authError && <div className="error">{authError}</div>} | |
| </form> | |
| </main> | |
| </div> | |
| ); | |
| } | |
| // ============================================================ | |
| // CHAT UI (visible only when logged in) | |
| // ============================================================ | |
| return ( | |
| <div className="app-root"> | |
| <header className="header"> | |
| <h1 className="header-title">Prolog AI</h1> | |
| <div className="header-actions"> | |
| <label className="strict-toggle" style={{ | |
| padding: "0.5rem 1rem", | |
| background: strictMode ? "rgba(220, 38, 38, 0.2)" : "rgba(34, 197, 94, 0.2)", | |
| border: `1px solid ${strictMode ? "rgba(220, 38, 38, 0.5)" : "rgba(34, 197, 94, 0.5)"}`, | |
| borderRadius: "6px", | |
| cursor: "pointer" | |
| }}> | |
| <input | |
| type="checkbox" | |
| checked={strictMode} | |
| onChange={(e) => setStrictMode(e.target.checked)} | |
| />{" "} | |
| {strictMode ? "π Strict KB Mode" : "π Flexible Mode"} | |
| </label> | |
| <button | |
| className="btn-secondary" | |
| onClick={() => setShowUpload(!showUpload)} | |
| > | |
| π€ Upload KB | |
| </button> | |
| <button | |
| className="btn-secondary" | |
| onClick={() => setShowQueryPanel(!showQueryPanel)} | |
| > | |
| π Query KB | |
| </button> | |
| {me && me.is_admin && ( | |
| <button | |
| className="btn-secondary" | |
| onClick={() => { | |
| setShowRegisterPanel((v) => !v); | |
| setShowQueryPanel(false); | |
| }} | |
| > | |
| π€ Register User | |
| </button> | |
| )} | |
| <button | |
| className="logout-btn" | |
| onClick={() => { | |
| setToken(null); | |
| setMe(null); | |
| setShowUpload(false); | |
| setShowQueryPanel(false); | |
| setShowRegisterPanel(false); | |
| setRegisterStatus(null); | |
| }} | |
| > | |
| Logout | |
| </button> | |
| </div> | |
| </header> | |
| <div className="app-container"> | |
| {/* Left Sidebar - Upload Panel */} | |
| {showUpload && ( | |
| <aside className="sidebar left-sidebar"> | |
| <h3>π€ Upload Knowledge Base</h3> | |
| <p style={{ fontSize: "0.9em", color: "#666" }}> | |
| Upload a .pl Prolog file to load into the knowledge base | |
| </p> | |
| <input | |
| type="file" | |
| accept=".pl" | |
| onChange={handleFileUpload} | |
| style={{ marginTop: "10px", marginBottom: "10px" }} | |
| /> | |
| {uploadStatus && ( | |
| <div className="status-message">{uploadStatus}</div> | |
| )} | |
| <button | |
| onClick={handleLoadMetadata} | |
| style={{ marginTop: "10px", width: "100%" }} | |
| > | |
| π Refresh Metadata | |
| </button> | |
| {kbMetadata && ( | |
| <div className="metadata-panel" style={{ marginTop: "15px" }}> | |
| <h4>π KB Metadata</h4> | |
| <pre style={{ fontSize: "0.85em", overflowX: "auto" }}> | |
| {kbMetadata} | |
| </pre> | |
| </div> | |
| )} | |
| </aside> | |
| )} | |
| {/* Main Chat Area */} | |
| <main className="main"> | |
| <div className="messages"> | |
| {messages.map((msg, idx) => ( | |
| <Message key={idx} message={msg} /> | |
| ))} | |
| </div> | |
| {error && <div className="error">{error}</div>} | |
| <form className="input-row" onSubmit={handleSend}> | |
| <textarea | |
| placeholder="Ask a question about your knowledge base..." | |
| value={input} | |
| onChange={(e) => setInput(e.target.value)} | |
| onKeyDown={(e) => { | |
| if (e.key === "Enter" && !e.shiftKey) { | |
| e.preventDefault(); | |
| handleSend(); | |
| } | |
| }} | |
| disabled={loading} | |
| rows="2" | |
| /> | |
| <button type="submit" disabled={loading || !input.trim()}> | |
| {loading ? "β³" : "Send"} | |
| </button> | |
| </form> | |
| </main> | |
| {/* Right Sidebar - Direct Query Panel */} | |
| {showQueryPanel && ( | |
| <aside className="sidebar right-sidebar"> | |
| <h3>π Direct Prolog Query</h3> | |
| <p style={{ fontSize: "0.9em", color: "#666" }}> | |
| Execute raw Prolog queries directly | |
| </p> | |
| <form onSubmit={handleDirectQuery}> | |
| <textarea | |
| placeholder="Enter Prolog query (e.g., capability(X))" | |
| value={directQuery} | |
| onChange={(e) => setDirectQuery(e.target.value)} | |
| rows="3" | |
| style={{ width: "100%", marginTop: "10px" }} | |
| /> | |
| <button type="submit" style={{ marginTop: "10px", width: "100%" }}> | |
| Execute Query | |
| </button> | |
| </form> | |
| {queryResults && ( | |
| <div className="query-results" style={{ marginTop: "15px" }}> | |
| <h4>Results</h4> | |
| <pre style={{ fontSize: "0.85em", overflowX: "auto" }}> | |
| {JSON.stringify(queryResults, null, 2)} | |
| </pre> | |
| </div> | |
| )} | |
| </aside> | |
| )} | |
| {/* Right Sidebar - Admin Register Panel */} | |
| {showRegisterPanel && me && me.is_admin && ( | |
| <aside className="sidebar right-sidebar"> | |
| <h3>π€ Register User</h3> | |
| <p style={{ fontSize: "0.9em", color: "#666" }}> | |
| Create a new user account (admin only) | |
| </p> | |
| <form onSubmit={handleRegisterUser}> | |
| <input | |
| type="text" | |
| placeholder="Username" | |
| value={registerForm.username} | |
| onChange={(e) => setRegisterForm({ ...registerForm, username: e.target.value })} | |
| style={{ width: "100%", marginTop: "10px" }} | |
| /> | |
| <input | |
| type="password" | |
| placeholder="Password" | |
| value={registerForm.password} | |
| onChange={(e) => setRegisterForm({ ...registerForm, password: e.target.value })} | |
| style={{ width: "100%", marginTop: "10px" }} | |
| /> | |
| <label style={{ display: "flex", alignItems: "center", gap: "8px", marginTop: "10px" }}> | |
| <input | |
| type="checkbox" | |
| checked={registerForm.overwrite} | |
| onChange={(e) => setRegisterForm({ ...registerForm, overwrite: e.target.checked })} | |
| /> | |
| Overwrite if user exists | |
| </label> | |
| <button type="submit" style={{ marginTop: "10px", width: "100%" }}> | |
| Create User | |
| </button> | |
| </form> | |
| {registerStatus && ( | |
| <div className="status-message" style={{ marginTop: "10px" }}> | |
| {registerStatus} | |
| </div> | |
| )} | |
| </aside> | |
| )} | |
| </div> | |
| </div> | |
| ); | |
| } | |
| // ============================================================ | |
| // MESSAGE COMPONENT | |
| // ============================================================ | |
| function Message({ message }) { | |
| const isUser = message.role === "user"; | |
| const [showDebug, setShowDebug] = useState(false); | |
| const normalizedText = React.useMemo( | |
| () => normalizeLatex(message.text || ""), | |
| [message.text] | |
| ); | |
| return ( | |
| <div className={`message ${isUser ? "user" : "assistant"}`}> | |
| <div className="bubble"> | |
| <ReactMarkdown | |
| className="markdown-body" | |
| remarkPlugins={[remarkMath, remarkGfm]} | |
| rehypePlugins={[[rehypeKatex, { strict: "ignore", throwOnError: false, trust: true }]]} | |
| skipHtml={false} | |
| breaks={true} | |
| > | |
| {normalizedText} | |
| </ReactMarkdown> | |
| </div> | |
| {!isUser && message.debug && ( | |
| <> | |
| <button | |
| className="debug-toggle" | |
| onClick={() => setShowDebug((v) => !v)} | |
| style={{ | |
| marginTop: "8px", | |
| fontSize: "0.85em", | |
| padding: "4px 10px", | |
| background: "#f0f0f0", | |
| border: "1px solid #ccc", | |
| borderRadius: "4px", | |
| cursor: "pointer" | |
| }} | |
| > | |
| {showDebug ? "π½ Hide Prolog Queries" : "πΌ Show Prolog Queries"} | |
| </button> | |
| {showDebug && ( | |
| <div className="debug-panel" style={{ | |
| marginTop: "10px", | |
| padding: "12px", | |
| background: "#f8f8f8", | |
| border: "1px solid #ddd", | |
| borderRadius: "6px", | |
| fontSize: "0.9em", | |
| color: "#1a1a1a" | |
| }}> | |
| <h4 style={{ marginTop: 0, marginBottom: "10px", color: "#1a1a1a" }}>π Prolog Query Analysis</h4> | |
| {message.debug.llm_analysis && ( | |
| <div style={{ marginBottom: "15px" }}> | |
| <strong style={{ color: "#1a1a1a" }}>Generated Queries:</strong> | |
| <pre style={{ | |
| background: "#fff", | |
| padding: "8px", | |
| borderRadius: "4px", | |
| fontSize: "0.9em", | |
| overflowX: "auto", | |
| color: "#1a1a1a" | |
| }}> | |
| {message.debug.llm_analysis} | |
| </pre> | |
| </div> | |
| )} | |
| {message.debug.predicates_queried && message.debug.predicates_queried.length > 0 && ( | |
| <div style={{ marginBottom: "15px" }}> | |
| <strong style={{ color: "#1a1a1a" }}>Predicates Queried:</strong>{" "} | |
| <span style={{ color: "#0066cc", fontWeight: "500" }}> | |
| {message.debug.predicates_queried.join(", ")} | |
| </span> | |
| </div> | |
| )} | |
| {message.debug.queries_executed && message.debug.queries_executed.length > 0 && ( | |
| <div style={{ marginBottom: "15px" }}> | |
| <strong style={{ color: "#1a1a1a" }}>Executed Queries ({message.debug.queries_executed.length}):</strong> | |
| <ul style={{ marginTop: "5px", paddingLeft: "20px", color: "#1a1a1a" }}> | |
| {message.debug.queries_executed.map((q, idx) => ( | |
| <li key={idx} style={{ marginBottom: "5px" }}> | |
| <code style={{ | |
| background: "#e8f4f8", | |
| padding: "2px 6px", | |
| borderRadius: "3px", | |
| fontSize: "0.9em", | |
| color: "#1a1a1a" | |
| }}> | |
| {q.query} | |
| </code>{" "} | |
| <span style={{ color: "#333" }}> | |
| β {q.results_count} result{q.results_count !== 1 ? "s" : ""} | |
| </span> | |
| </li> | |
| ))} | |
| </ul> | |
| </div> | |
| )} | |
| <div> | |
| <strong style={{ color: "#1a1a1a" }}>Total Results:</strong>{" "} | |
| <span style={{ color: "#00aa00", fontWeight: "bold" }}> | |
| {message.debug.total_results || 0} | |
| </span> | |
| </div> | |
| </div> | |
| )} | |
| </> | |
| )} | |
| </div> | |
| ); | |
| } | |
| export default App; | |