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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
import datetime
|
| 6 |
+
import urllib.request
|
| 7 |
+
import urllib.error
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from fastapi import Request, Response, HTTPException
|
| 10 |
+
from fastapi.responses import JSONResponse
|
| 11 |
+
|
| 12 |
+
# Import BM25 Indexer
|
| 13 |
+
from rag_indexer import BM25Index, tokenize
|
| 14 |
+
|
| 15 |
+
# Configuration from Secrets / Environment
|
| 16 |
+
VLLM_BASE_URL = os.environ.get("VLLM_BASE_URL", "https://p0rg87xyorc99i-8000.proxy.runpod.net/v1").rstrip('/')
|
| 17 |
+
VLLM_API_KEY = os.environ.get("VLLM_API_KEY", "sk-stay4s-mitchell-pod-2026")
|
| 18 |
+
CHAT_API_KEY = os.environ.get("CHAT_API_KEY", "sk-stay4s-mitchell-2026")
|
| 19 |
+
|
| 20 |
+
# Load RAG Index
|
| 21 |
+
JSONL_PATH = "infovault_chunks.jsonl"
|
| 22 |
+
print(f"Loading InfoVault chunks from {JSONL_PATH}...")
|
| 23 |
+
chunks = []
|
| 24 |
+
if os.path.exists(JSONL_PATH):
|
| 25 |
+
with open(JSONL_PATH, "r", encoding="utf-8") as f:
|
| 26 |
+
for line in f:
|
| 27 |
+
if line.strip():
|
| 28 |
+
chunks.append(json.loads(line))
|
| 29 |
+
|
| 30 |
+
index = BM25Index()
|
| 31 |
+
index.build_index(chunks)
|
| 32 |
+
print(f"Indexed {len(chunks)} InfoVault records!")
|
| 33 |
+
|
| 34 |
+
def log_step(tool_name: str, input_data: any, output_data: any, latency_sec: float):
|
| 35 |
+
log_entry = {
|
| 36 |
+
"tijd": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
| 37 |
+
"tool": tool_name,
|
| 38 |
+
"input": input_data,
|
| 39 |
+
"output": output_data,
|
| 40 |
+
"latency_sec": round(latency_sec, 4)
|
| 41 |
+
}
|
| 42 |
+
with open("agent_execution.jsonl", "a", encoding="utf-8") as f:
|
| 43 |
+
f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")
|
| 44 |
+
|
| 45 |
+
def call_vllm_llm(prompt: str, max_tokens: int = 256) -> str:
|
| 46 |
+
url = f"{VLLM_BASE_URL}/completions"
|
| 47 |
+
payload = {
|
| 48 |
+
"model": "qwen2.5-7b-instruct",
|
| 49 |
+
"prompt": prompt,
|
| 50 |
+
"max_tokens": max_tokens,
|
| 51 |
+
"temperature": 0.1,
|
| 52 |
+
"stop": ["\n\n\n", "Vraag:", "Context:"]
|
| 53 |
+
}
|
| 54 |
+
headers = {
|
| 55 |
+
"Content-Type": "application/json",
|
| 56 |
+
"Authorization": f"Bearer {VLLM_API_KEY}",
|
| 57 |
+
"User-Agent": "Mozilla/5.0"
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
t0 = time.time()
|
| 61 |
+
req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
|
| 62 |
+
try:
|
| 63 |
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 64 |
+
raw_res = resp.read().decode("utf-8")
|
| 65 |
+
latency = time.time() - t0
|
| 66 |
+
response_json = json.loads(raw_res)
|
| 67 |
+
log_step("llm_call", payload, response_json, latency)
|
| 68 |
+
choices = response_json.get("choices", [])
|
| 69 |
+
if choices:
|
| 70 |
+
return choices[0].get("text", "").strip()
|
| 71 |
+
return "Geen antwoord van LLM."
|
| 72 |
+
except urllib.error.HTTPError as e:
|
| 73 |
+
err_body = e.read().decode("utf-8")
|
| 74 |
+
log_step("llm_call_error", payload, f"HTTP {e.code}: {err_body}", time.time() - t0)
|
| 75 |
+
# Fallback to chat completions if completions fail
|
| 76 |
+
return call_vllm_chat(prompt, max_tokens)
|
| 77 |
+
except Exception as e:
|
| 78 |
+
log_step("llm_call_error", payload, str(e), time.time() - t0)
|
| 79 |
+
raise RuntimeError(f"Fout bij verbinden met vLLM endpoint: {str(e)}")
|
| 80 |
+
|
| 81 |
+
def call_vllm_chat(prompt: str, max_tokens: int = 256) -> str:
|
| 82 |
+
url = f"{VLLM_BASE_URL}/chat/completions"
|
| 83 |
+
payload = {
|
| 84 |
+
"model": "qwen2.5-7b-instruct",
|
| 85 |
+
"messages": [
|
| 86 |
+
{"role": "system", "content": "Je bent de Stay4S-agent. Beantwoord de vraag nauwkeurig op basis van de context en vermeld altijd de bron."},
|
| 87 |
+
{"role": "user", "content": prompt}
|
| 88 |
+
],
|
| 89 |
+
"max_tokens": max_tokens,
|
| 90 |
+
"temperature": 0.1
|
| 91 |
+
}
|
| 92 |
+
headers = {
|
| 93 |
+
"Content-Type": "application/json",
|
| 94 |
+
"Authorization": f"Bearer {VLLM_API_KEY}",
|
| 95 |
+
"User-Agent": "Mozilla/5.0"
|
| 96 |
+
}
|
| 97 |
+
t0 = time.time()
|
| 98 |
+
req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
|
| 99 |
+
try:
|
| 100 |
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 101 |
+
raw_res = resp.read().decode("utf-8")
|
| 102 |
+
response_json = json.loads(raw_res)
|
| 103 |
+
log_step("llm_chat_call", payload, response_json, time.time() - t0)
|
| 104 |
+
return response_json["choices"][0]["message"]["content"].strip()
|
| 105 |
+
except Exception as e:
|
| 106 |
+
log_step("llm_chat_error", payload, str(e), time.time() - t0)
|
| 107 |
+
return f"FOUT bij LLM call: {str(e)}"
|
| 108 |
+
|
| 109 |
+
def answer_question(query: str):
|
| 110 |
+
if not query or not query.strip():
|
| 111 |
+
return "Voer a.u.b. een vraag in.", "Geen bron"
|
| 112 |
+
|
| 113 |
+
t0 = time.time()
|
| 114 |
+
hits = index.search(query, top_n=3)
|
| 115 |
+
log_step("rag_zoek", {"query": query}, hits, time.time() - t0)
|
| 116 |
+
|
| 117 |
+
if not hits:
|
| 118 |
+
return "Geen relevante informatie gevonden in InfoVault.", "Geen bron"
|
| 119 |
+
|
| 120 |
+
top_hit = hits[0]
|
| 121 |
+
bron_titel = top_hit.get("titel", "Onbekend")
|
| 122 |
+
bron_id = top_hit.get("id", "Onbekend")
|
| 123 |
+
bronverwijzing = f"[Titel: '{bron_titel}' | Record-ID: {bron_id}]"
|
| 124 |
+
|
| 125 |
+
# Context construction
|
| 126 |
+
context_parts = []
|
| 127 |
+
for h in hits:
|
| 128 |
+
h_titel = h.get("titel", "")
|
| 129 |
+
h_id = h.get("id", "")
|
| 130 |
+
h_samenvatting = h.get("samenvatting", "")
|
| 131 |
+
h_inhoud = h.get("ruwe_inhoud", "")
|
| 132 |
+
context_parts.append(f"Bron ({h_titel} | Record-ID: {h_id}):\n{h_samenvatting}\n{h_inhoud[:1000]}")
|
| 133 |
+
|
| 134 |
+
full_context = "\n\n".join(context_parts)
|
| 135 |
+
if len(full_context) > 2500:
|
| 136 |
+
full_context = full_context[:2500]
|
| 137 |
+
|
| 138 |
+
prompt = (
|
| 139 |
+
"Je bent de Stay4S-agent. Beantwoord de vraag van de gebruiker beknopt en feitelijk. "
|
| 140 |
+
f"Vermeld aan het einde van je antwoord expliciet de bronverwijzing: {bronverwijzing}.\n\n"
|
| 141 |
+
f"Context uit InfoVault:\n{full_context}\n\n"
|
| 142 |
+
f"Vraag: {query}\n"
|
| 143 |
+
"Antwoord:"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
antwoord = call_vllm_llm(prompt)
|
| 147 |
+
|
| 148 |
+
# Ensure source attribution is in response
|
| 149 |
+
if bron_id not in antwoord and bron_titel not in antwoord:
|
| 150 |
+
antwoord = f"{antwoord}\n\nBron: {bronverwijzing}"
|
| 151 |
+
|
| 152 |
+
return antwoord, bronverwijzing
|
| 153 |
+
|
| 154 |
+
# Gradio Web UI
|
| 155 |
+
with gr.Blocks(title="Stay4S AI Agent", theme=gr.themes.Soft()) as demo:
|
| 156 |
+
gr.Markdown("# 🤖 Stay4S AI Agent Interface")
|
| 157 |
+
gr.Markdown("Welkom Mitchell! Stel hier je vragen over Stay4S, InfoVault, contracten, hardware en veilingen.")
|
| 158 |
+
|
| 159 |
+
with gr.Row():
|
| 160 |
+
with gr.Column():
|
| 161 |
+
vraag_input = gr.Textbox(
|
| 162 |
+
label="Jouw Vraag",
|
| 163 |
+
placeholder="Bijv.: Wat is de prijs van STRATO OpenClaw VPS M?",
|
| 164 |
+
lines=3
|
| 165 |
+
)
|
| 166 |
+
submit_btn = gr.Button("Verstuur Vraag", variant="primary")
|
| 167 |
+
|
| 168 |
+
with gr.Column():
|
| 169 |
+
antwoord_output = gr.Textbox(label="Antwoord van Stay4S Agent", lines=6)
|
| 170 |
+
bron_output = gr.Textbox(label="Bronverwijzing (InfoVault)", lines=2)
|
| 171 |
+
|
| 172 |
+
submit_btn.click(
|
| 173 |
+
fn=answer_question,
|
| 174 |
+
inputs=[vraag_input],
|
| 175 |
+
outputs=[antwoord_output, bron_output]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
gr.Examples(
|
| 179 |
+
examples=[
|
| 180 |
+
["Wat is de prijs van STRATO OpenClaw VPS M?"],
|
| 181 |
+
["Wat is de capaciteit en het vermogen van de Awilco ES-2002?"],
|
| 182 |
+
["Wat is het serienummer en het huidige bod op de Mac mini M1?"],
|
| 183 |
+
["Wat is het stay4s.com contractnummer bij Strato?"]
|
| 184 |
+
],
|
| 185 |
+
inputs=vraag_input
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# FastAPI Integration for custom POST /chat, /health, /v1/models
|
| 189 |
+
app = demo.app if hasattr(demo, "app") else None
|
| 190 |
+
|
| 191 |
+
@demo.app.get("/health")
|
| 192 |
+
async def health_check():
|
| 193 |
+
return {"status": "ok", "service": "Stay4S-Agent-Interface", "backend": VLLM_BASE_URL}
|
| 194 |
+
|
| 195 |
+
@demo.app.get("/v1/models")
|
| 196 |
+
async def list_models():
|
| 197 |
+
return {
|
| 198 |
+
"object": "list",
|
| 199 |
+
"data": [
|
| 200 |
+
{
|
| 201 |
+
"id": "qwen2.5-7b-instruct",
|
| 202 |
+
"object": "model",
|
| 203 |
+
"owned_by": "stay4s"
|
| 204 |
+
}
|
| 205 |
+
]
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
@demo.app.post("/chat")
|
| 209 |
+
async def chat_api(request: Request):
|
| 210 |
+
auth_header = request.headers.get("Authorization", "")
|
| 211 |
+
expected_token = f"Bearer {CHAT_API_KEY}"
|
| 212 |
+
|
| 213 |
+
if not auth_header or auth_header != expected_token:
|
| 214 |
+
return JSONResponse(
|
| 215 |
+
status_code=401,
|
| 216 |
+
content={"status": "error", "message": "Unauthorized: Ongeldige API-key in Authorization header"}
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
try:
|
| 220 |
+
body = await request.json()
|
| 221 |
+
except Exception:
|
| 222 |
+
body = {}
|
| 223 |
+
|
| 224 |
+
query = body.get("query") or body.get("opdracht") or body.get("question")
|
| 225 |
+
if not query:
|
| 226 |
+
return JSONResponse(status_code=400, content={"status": "error", "message": "Geen 'query' opgegeven in JSON payload."})
|
| 227 |
+
|
| 228 |
+
antwoord, bron = answer_question(query)
|
| 229 |
+
return {
|
| 230 |
+
"status": "success",
|
| 231 |
+
"query": query,
|
| 232 |
+
"antwoord": antwoord,
|
| 233 |
+
"bron": bron,
|
| 234 |
+
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat()
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
if __name__ == "__main__":
|
| 238 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|