Spaces:
Runtime error
Runtime error
Download app.py from low-key-007/chat-bot-api-2: direct link, hf CLI and curl.
- Browser
- Download file 6.95 kB
-
https://huggingface.co/spaces/low-key-007/chat-bot-api-2/resolve/main/app.py
- Command line
-
hf download hf://spaces/low-key-007/chat-bot-api-2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/low-key-007/chat-bot-api-2/resolve/main/app.py
6.95 kB
| import os, json, shutil | |
| from typing import List, Dict, Optional | |
| 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") | |
| # ----------------------------- | |
| # 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 = "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=["*"], # TODO: restrict later | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Serve static files (creator page) | |
| app.mount("/static", StaticFiles(directory="static"), name="static") | |
| 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.") | |
| # ----------------------------- | |
| # Endpoints | |
| # ----------------------------- | |
| def root(): | |
| return {"ok": True, "message": "Portfolio Chatbot running.", "provider": provider} | |
| def health(): | |
| return {"status": "healthy", "provider": provider} | |
| def chat(req: ChatRequest): | |
| blocked = blocked_by_guardrails(req.message) | |
| if blocked: | |
| return ChatResponse(reply=blocked, provider=provider) | |
| # Creator activation | |
| if req.message.strip().lower() == "hi i am creator i want to make you learn": | |
| return ChatResponse( | |
| reply="🔑 Creator mode activated. Upload files here: /creator", | |
| provider=provider | |
| ) | |
| 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": req.message}, | |
| ] | |
| 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)} | |
| def get_creator_page(): | |
| return FileResponse("static/creator.html") | |
| # ----------------------------- | |
| # Run (local only) | |
| # ----------------------------- | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |