#!/usr/bin/env python3
"""ask — the web chat's backend: one customer question in, the assistant's answer out (as JSON)."""

import json
import sys
import urllib.request

OLLAMA = "http://127.0.0.1:11434/api/chat"


def main():
    question = " ".join(sys.argv[1:]) or sys.stdin.read()
    body = {
        "model": "support-bot",
        "messages": [{"role": "user", "content": question}],
        "stream": False,
        # answers were slow, so the context was made smaller
        "options": {"num_ctx": 512, "num_predict": 120},
    }
    request = urllib.request.Request(
        OLLAMA, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}
    )
    with urllib.request.urlopen(request, timeout=300) as response:
        result = json.load(response)
    print(json.dumps({
        "answer": result["message"]["content"],
        "prompt_eval_count": result.get("prompt_eval_count"),
        "eval_count": result.get("eval_count"),
    }))


if __name__ == "__main__":
    main()
