Spaces:
Sleeping
Sleeping
Download app.py from miesdevries/stay4s-agent: direct link, hf CLI and curl.
- Browser
- Download file 8.58 kB
-
https://huggingface.co/spaces/miesdevries/stay4s-agent/resolve/main/app.py
- Command line
-
hf download hf://spaces/miesdevries/stay4s-agent/app.py
-
curl -L -o app.py https://huggingface.co/spaces/miesdevries/stay4s-agent/resolve/main/app.py
8.58 kB
| import os | |
| import sys | |
| import json | |
| import time | |
| import datetime | |
| import urllib.request | |
| import urllib.error | |
| import gradio as gr | |
| from fastapi import Request, Response, HTTPException | |
| from fastapi.responses import JSONResponse | |
| # Import BM25 Indexer | |
| from rag_indexer import BM25Index, tokenize | |
| # Configuration from Secrets / Environment | |
| VLLM_BASE_URL = os.environ.get("VLLM_BASE_URL", "https://p0rg87xyorc99i-8000.proxy.runpod.net/v1").rstrip('/') | |
| VLLM_API_KEY = os.environ.get("VLLM_API_KEY", "sk-stay4s-mitchell-pod-2026") | |
| CHAT_API_KEY = os.environ.get("CHAT_API_KEY", "sk-stay4s-mitchell-2026") | |
| # Load RAG Index | |
| JSONL_PATH = "infovault_chunks.jsonl" | |
| print(f"Loading InfoVault chunks from {JSONL_PATH}...") | |
| chunks = [] | |
| if os.path.exists(JSONL_PATH): | |
| with open(JSONL_PATH, "r", encoding="utf-8") as f: | |
| for line in f: | |
| if line.strip(): | |
| chunks.append(json.loads(line)) | |
| index = BM25Index() | |
| index.build_index(chunks) | |
| print(f"Indexed {len(chunks)} InfoVault records!") | |
| def log_step(tool_name: str, input_data: any, output_data: any, latency_sec: float): | |
| log_entry = { | |
| "tijd": datetime.datetime.now(datetime.timezone.utc).isoformat(), | |
| "tool": tool_name, | |
| "input": input_data, | |
| "output": output_data, | |
| "latency_sec": round(latency_sec, 4) | |
| } | |
| with open("agent_execution.jsonl", "a", encoding="utf-8") as f: | |
| f.write(json.dumps(log_entry, ensure_ascii=False) + "\n") | |
| def call_vllm_llm(prompt: str, max_tokens: int = 256) -> str: | |
| url = f"{VLLM_BASE_URL}/completions" | |
| payload = { | |
| "model": "qwen2.5-7b-instruct", | |
| "prompt": prompt, | |
| "max_tokens": max_tokens, | |
| "temperature": 0.1, | |
| "stop": ["\n\n\n", "Vraag:", "Context:"] | |
| } | |
| headers = { | |
| "Content-Type": "application/json", | |
| "Authorization": f"Bearer {VLLM_API_KEY}", | |
| "User-Agent": "Mozilla/5.0" | |
| } | |
| t0 = time.time() | |
| req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST") | |
| try: | |
| with urllib.request.urlopen(req, timeout=30) as resp: | |
| raw_res = resp.read().decode("utf-8") | |
| latency = time.time() - t0 | |
| response_json = json.loads(raw_res) | |
| log_step("llm_call", payload, response_json, latency) | |
| choices = response_json.get("choices", []) | |
| if choices: | |
| return choices[0].get("text", "").strip() | |
| return "Geen antwoord van LLM." | |
| except urllib.error.HTTPError as e: | |
| err_body = e.read().decode("utf-8") | |
| log_step("llm_call_error", payload, f"HTTP {e.code}: {err_body}", time.time() - t0) | |
| # Fallback to chat completions if completions fail | |
| return call_vllm_chat(prompt, max_tokens) | |
| except Exception as e: | |
| log_step("llm_call_error", payload, str(e), time.time() - t0) | |
| raise RuntimeError(f"Fout bij verbinden met vLLM endpoint: {str(e)}") | |
| def call_vllm_chat(prompt: str, max_tokens: int = 256) -> str: | |
| url = f"{VLLM_BASE_URL}/chat/completions" | |
| payload = { | |
| "model": "qwen2.5-7b-instruct", | |
| "messages": [ | |
| {"role": "system", "content": "Je bent de Stay4S-agent. Beantwoord de vraag nauwkeurig op basis van de context en vermeld altijd de bron."}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| "max_tokens": max_tokens, | |
| "temperature": 0.1 | |
| } | |
| headers = { | |
| "Content-Type": "application/json", | |
| "Authorization": f"Bearer {VLLM_API_KEY}", | |
| "User-Agent": "Mozilla/5.0" | |
| } | |
| t0 = time.time() | |
| req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST") | |
| try: | |
| with urllib.request.urlopen(req, timeout=30) as resp: | |
| raw_res = resp.read().decode("utf-8") | |
| response_json = json.loads(raw_res) | |
| log_step("llm_chat_call", payload, response_json, time.time() - t0) | |
| return response_json["choices"][0]["message"]["content"].strip() | |
| except Exception as e: | |
| log_step("llm_chat_error", payload, str(e), time.time() - t0) | |
| return f"FOUT bij LLM call: {str(e)}" | |
| def answer_question(query: str): | |
| if not query or not query.strip(): | |
| return "Voer a.u.b. een vraag in.", "Geen bron" | |
| t0 = time.time() | |
| hits = index.search(query, top_n=3) | |
| log_step("rag_zoek", {"query": query}, hits, time.time() - t0) | |
| if not hits: | |
| return "Geen relevante informatie gevonden in InfoVault.", "Geen bron" | |
| top_hit = hits[0] | |
| bron_titel = top_hit.get("titel", "Onbekend") | |
| bron_id = top_hit.get("id", "Onbekend") | |
| bronverwijzing = f"[Titel: '{bron_titel}' | Record-ID: {bron_id}]" | |
| # Context construction | |
| context_parts = [] | |
| for h in hits: | |
| h_titel = h.get("titel", "") | |
| h_id = h.get("id", "") | |
| h_samenvatting = h.get("samenvatting", "") | |
| h_inhoud = h.get("ruwe_inhoud", "") | |
| context_parts.append(f"Bron ({h_titel} | Record-ID: {h_id}):\n{h_samenvatting}\n{h_inhoud[:1000]}") | |
| full_context = "\n\n".join(context_parts) | |
| if len(full_context) > 2500: | |
| full_context = full_context[:2500] | |
| prompt = ( | |
| "Je bent de Stay4S-agent. Beantwoord de vraag van de gebruiker beknopt en feitelijk. " | |
| f"Vermeld aan het einde van je antwoord expliciet de bronverwijzing: {bronverwijzing}.\n\n" | |
| f"Context uit InfoVault:\n{full_context}\n\n" | |
| f"Vraag: {query}\n" | |
| "Antwoord:" | |
| ) | |
| antwoord = call_vllm_llm(prompt) | |
| # Ensure source attribution is in response | |
| if bron_id not in antwoord and bron_titel not in antwoord: | |
| antwoord = f"{antwoord}\n\nBron: {bronverwijzing}" | |
| return antwoord, bronverwijzing | |
| # Gradio Web UI | |
| with gr.Blocks(title="Stay4S AI Agent", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 🤖 Stay4S AI Agent Interface") | |
| gr.Markdown("Welkom Mitchell! Stel hier je vragen over Stay4S, InfoVault, contracten, hardware en veilingen.") | |
| with gr.Row(): | |
| with gr.Column(): | |
| vraag_input = gr.Textbox( | |
| label="Jouw Vraag", | |
| placeholder="Bijv.: Wat is de prijs van STRATO OpenClaw VPS M?", | |
| lines=3 | |
| ) | |
| submit_btn = gr.Button("Verstuur Vraag", variant="primary") | |
| with gr.Column(): | |
| antwoord_output = gr.Textbox(label="Antwoord van Stay4S Agent", lines=6) | |
| bron_output = gr.Textbox(label="Bronverwijzing (InfoVault)", lines=2) | |
| submit_btn.click( | |
| fn=answer_question, | |
| inputs=[vraag_input], | |
| outputs=[antwoord_output, bron_output] | |
| ) | |
| gr.Examples( | |
| examples=[ | |
| ["Wat is de prijs van STRATO OpenClaw VPS M?"], | |
| ["Wat is de capaciteit en het vermogen van de Awilco ES-2002?"], | |
| ["Wat is het serienummer en het huidige bod op de Mac mini M1?"], | |
| ["Wat is het stay4s.com contractnummer bij Strato?"] | |
| ], | |
| inputs=vraag_input | |
| ) | |
| # FastAPI Integration for custom POST /chat, /health, /v1/models | |
| app = demo.app if hasattr(demo, "app") else None | |
| async def health_check(): | |
| return {"status": "ok", "service": "Stay4S-Agent-Interface", "backend": VLLM_BASE_URL} | |
| async def list_models(): | |
| return { | |
| "object": "list", | |
| "data": [ | |
| { | |
| "id": "qwen2.5-7b-instruct", | |
| "object": "model", | |
| "owned_by": "stay4s" | |
| } | |
| ] | |
| } | |
| async def chat_api(request: Request): | |
| auth_header = request.headers.get("Authorization", "") | |
| expected_token = f"Bearer {CHAT_API_KEY}" | |
| if not auth_header or auth_header != expected_token: | |
| return JSONResponse( | |
| status_code=401, | |
| content={"status": "error", "message": "Unauthorized: Ongeldige API-key in Authorization header"} | |
| ) | |
| try: | |
| body = await request.json() | |
| except Exception: | |
| body = {} | |
| query = body.get("query") or body.get("opdracht") or body.get("question") | |
| if not query: | |
| return JSONResponse(status_code=400, content={"status": "error", "message": "Geen 'query' opgegeven in JSON payload."}) | |
| antwoord, bron = answer_question(query) | |
| return { | |
| "status": "success", | |
| "query": query, | |
| "antwoord": antwoord, | |
| "bron": bron, | |
| "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat() | |
| } | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |