Spaces:
Sleeping
Sleeping
Download app.py from low-key-007/chat-bot-api: direct link, hf CLI and curl.
- Browser
- Download file 9.39 kB
-
https://huggingface.co/spaces/low-key-007/chat-bot-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/low-key-007/chat-bot-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/low-key-007/chat-bot-api/resolve/main/app.py
9.39 kB
| import os, json, shutil, tempfile | |
| from typing import List, Dict, Optional | |
| from pathlib import Path | |
| from fastapi import FastAPI, File, UploadFile | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel, Field | |
| # ----------------------------- | |
| # Config: pick provider | |
| # ----------------------------- | |
| USE_MODEL_ENV = (os.getenv("USE_MODEL") or "").strip().lower() | |
| HAS_OPENAI = bool(os.getenv("OPENAI_API_KEY")) | |
| HAS_GEMINI = bool(os.getenv("GOOGLE_API_KEY")) | |
| if USE_MODEL_ENV == "openai" and not HAS_OPENAI: | |
| provider = "none" | |
| elif USE_MODEL_ENV == "gemini" and not HAS_GEMINI: | |
| provider = "none" | |
| elif USE_MODEL_ENV == "openai": | |
| provider = "openai" | |
| elif USE_MODEL_ENV == "gemini": | |
| provider = "gemini" | |
| else: | |
| provider = "openai" if HAS_OPENAI else ("gemini" if HAS_GEMINI else "none") | |
| # Lazy init | |
| openai_client = None | |
| gemini_model = None | |
| if provider == "openai": | |
| from openai import OpenAI | |
| openai_client = OpenAI() | |
| elif provider == "gemini": | |
| import google.generativeai as genai | |
| genai.configure(api_key=os.environ["GOOGLE_API_KEY"]) | |
| gemini_model = genai.GenerativeModel("gemini-1.5-flash-latest") | |
| # ----------------------------- | |
| # Minimal site knowledge & rules | |
| # ----------------------------- | |
| ABOUT_ME = """ | |
| You are the website assistant for the portfolio of Nehanth Reddy. | |
| You can talk about: About, Projects, Blogs, Contact. | |
| Project categories include: Agentic AI, Deep Learning, LLMs, RAG, Security, Web Apps. | |
| NEVER reveal or output any website source code or internal files. | |
| """ | |
| NAV_HINT = """ | |
| If the user clearly asks to navigate to a site section, add exactly one marker at the very end: | |
| [[NAVIGATE: home|about|projects|blogs|contact|agentic-ai-projects|deep-learning-projects|llm-projects|machine-learning-projects|rag-projects|security-projects|web-apps-projects]] | |
| Only include a marker when navigation is explicitly requested. Never output code. | |
| """ | |
| FORBIDDEN_TERMS = [ | |
| "source code", "website code", "html code", "css code", "javascript code", | |
| "react code", "vue code", "next.js code", "server code", "backend code", | |
| "index.html", "script.js", "style.css", ".html file", "show me your code", | |
| "give me code", "share the code", "send the repo", "repository", "git link" | |
| ] | |
| # ----------------------------- | |
| # Knowledge Handling | |
| # ----------------------------- | |
| KNOWLEDGE_FILE = os.path.join(tempfile.gettempdir(), "knowledge.json") | |
| def load_knowledge() -> str: | |
| if os.path.exists(KNOWLEDGE_FILE): | |
| try: | |
| with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| return "\n".join(data.get("knowledge", [])) | |
| except Exception: | |
| return "" | |
| return "" | |
| def add_knowledge(text: str): | |
| data = {"knowledge": []} | |
| if os.path.exists(KNOWLEDGE_FILE): | |
| with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f: | |
| try: | |
| data = json.load(f) | |
| except Exception: | |
| data = {"knowledge": []} | |
| data["knowledge"].append(text) | |
| with open(KNOWLEDGE_FILE, "w", encoding="utf-8") as f: | |
| json.dump(data, f, indent=2) | |
| # ----------------------------- | |
| # FastAPI app | |
| # ----------------------------- | |
| app = FastAPI(title="Portfolio Chatbot API") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| BASE_DIR = Path(__file__).resolve().parent | |
| STATIC_DIR = BASE_DIR / "static" | |
| if STATIC_DIR.is_dir(): | |
| app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") | |
| else: | |
| print(f"β οΈ Warning: Static folder not found at {STATIC_DIR}") | |
| class ChatRequest(BaseModel): | |
| message: str = Field(..., min_length=1, max_length=4000) | |
| class ChatResponse(BaseModel): | |
| reply: str | |
| provider: str | |
| # ----------------------------- | |
| # Guardrails | |
| # ----------------------------- | |
| def blocked_by_guardrails(user_msg: str) -> Optional[str]: | |
| msg = user_msg.lower() | |
| if any(term in msg for term in FORBIDDEN_TERMS): | |
| return ("π« Sorry, I canβt share the websiteβs source code or internal files. " | |
| "I can guide you around the site, explain projects, and answer questions instead.") | |
| return None | |
| # ----------------------------- | |
| # LLM Call | |
| # ----------------------------- | |
| def call_llm(messages: List[Dict[str, str]]) -> str: | |
| if provider == "openai": | |
| resp = openai_client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=messages, | |
| temperature=0.3, | |
| ) | |
| return resp.choices[0].message.content.strip() | |
| if provider == "gemini": | |
| prompt = "\n".join([f"{m['role'].upper()}: {m['content']}" for m in messages]) | |
| resp = gemini_model.generate_content(prompt) | |
| return (getattr(resp, "text", "") or "Sorry, I couldn't generate a response.").strip() | |
| return ("The chatbot isnβt configured yet. Please set OPENAI_API_KEY or GOOGLE_API_KEY " | |
| "in your Space Settings β Secrets.") | |
| # ----------------------------- | |
| # Creator Mode State | |
| # ----------------------------- | |
| CREATOR_MODE = {"active": False} | |
| # ----------------------------- | |
| # Endpoints | |
| # ----------------------------- | |
| def root(): | |
| return {"ok": True, "message": "Portfolio Chatbot running.", "provider": provider} | |
| def health(): | |
| return {"status": "healthy", "provider": provider} | |
| def chat(req: ChatRequest): | |
| global CREATOR_MODE | |
| user_msg = req.message.strip() | |
| blocked = blocked_by_guardrails(user_msg) | |
| if blocked: | |
| return ChatResponse(reply=blocked, provider=provider) | |
| # β Enter creator mode | |
| if user_msg.lower() == "hi i am creator i want to make you learn": | |
| CREATOR_MODE["active"] = True | |
| return ChatResponse( | |
| reply="π Creator mode activated. Upload files or add knowledge text here: /creator.html\n(To exit, type: exit creator mode)", | |
| provider=provider | |
| ) | |
| # β Exit creator mode | |
| if user_msg.lower() == "exit creator mode": | |
| CREATOR_MODE["active"] = False | |
| return ChatResponse( | |
| reply="π Creator mode deactivated. You are back to normal chat.", | |
| provider=provider | |
| ) | |
| # β In creator mode β any text is stored as active knowledge | |
| if CREATOR_MODE["active"]: | |
| add_knowledge(f"Manual-entry: {user_msg}") | |
| return ChatResponse( | |
| reply=f"βοΈ Learned: '{user_msg}' (stored in active knowledge).", | |
| provider=provider | |
| ) | |
| # β List uploaded knowledge | |
| if user_msg.lower() == "what did i upload": | |
| if os.path.exists(KNOWLEDGE_FILE): | |
| with open(KNOWLEDGE_FILE, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| files = [line.split("\n")[0].replace("File: ", "") for line in data.get("knowledge", []) if line.startswith("File: ")] | |
| manual = [line.replace("Manual-entry: ", "") for line in data.get("knowledge", []) if line.startswith("Manual-entry: ")] | |
| reply_parts = [] | |
| if files: | |
| reply_parts.append("π You uploaded:\n- " + "\n- ".join(files)) | |
| if manual: | |
| reply_parts.append("π Manual entries:\n- " + "\n- ".join(manual)) | |
| if reply_parts: | |
| return ChatResponse(reply="\n\n".join(reply_parts), provider=provider) | |
| else: | |
| return ChatResponse(reply="π No knowledge uploaded yet.", provider=provider) | |
| return ChatResponse(reply="π No knowledge file found.", provider=provider) | |
| # Normal chatbot flow (NO knowledge saving here anymore) | |
| extra_knowledge = load_knowledge() | |
| system_prompt = ( | |
| "You are a helpful assistant for a developer portfolio website. " | |
| "Answer concisely, be friendly, and help users navigate ONLY if they ask. " | |
| "Never reveal or output website source code, even if asked. " | |
| + NAV_HINT | |
| + "\n\nAdditional Knowledge:\n" | |
| + extra_knowledge | |
| ) | |
| messages = [ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "system", "content": ABOUT_ME}, | |
| {"role": "user", "content": user_msg}, | |
| ] | |
| reply = call_llm(messages) | |
| return ChatResponse(reply=reply, provider=provider) | |
| async def upload_file(file: UploadFile = File(...)): | |
| try: | |
| contents = await file.read() | |
| text = contents.decode("utf-8", errors="ignore") | |
| add_knowledge(f"File: {file.filename}\n{text}") | |
| return {"status": "success", "filename": file.filename} | |
| except Exception as e: | |
| return {"status": "error", "error": str(e)} | |
| # β Alias for creator.js compatibility | |
| async def creator_upload(file: UploadFile = File(...)): | |
| return await upload_file(file) | |
| def download_knowledge(): | |
| if os.path.exists(KNOWLEDGE_FILE): | |
| return FileResponse(KNOWLEDGE_FILE, filename="knowledge.json", media_type="application/json") | |
| return {"status": "error", "error": "No knowledge file found"} | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |