File size: 8,581 Bytes
313a4d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
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

@demo.app.get("/health")
async def health_check():
    return {"status": "ok", "service": "Stay4S-Agent-Interface", "backend": VLLM_BASE_URL}

@demo.app.get("/v1/models")
async def list_models():
    return {
        "object": "list",
        "data": [
            {
                "id": "qwen2.5-7b-instruct",
                "object": "model",
                "owned_by": "stay4s"
            }
        ]
    }

@demo.app.post("/chat")
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)