"""Run one local Ollama tool call with Python's standard library.

Requires Ollama running locally with qwen3:14b already installed.
The only network destination is the local Ollama server. Input is the sample 'abc'.
"""
import hashlib
import json
from urllib.request import Request, urlopen


def chat(messages, tools):
    payload = {
        "model": "qwen3:14b", "stream": False, "think": False,
        "messages": messages, "tools": tools,
        "options": {"temperature": 0, "num_predict": 160},
    }
    request = Request(
        "http://127.0.0.1:11434/api/chat",
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )
    with urlopen(request, timeout=120) as response:
        return json.load(response)["message"]


definition = {
    "type": "function",
    "function": {
        "name": "sha256_text",
        "description": "Calculate SHA-256 of a UTF-8 string.",
        "parameters": {
            "type": "object",
            "properties": {"text": {"type": "string"}},
            "required": ["text"],
        },
    },
}
messages = [{
    "role": "user",
    "content": "Compute the SHA-256 digest of abc using sha256_text. Reply with only the digest.",
}]
first = chat(messages, [definition])
calls = first.get("tool_calls", [])
assert len(calls) == 1, "Expected one tool request; inspect the actual model reply."
call = calls[0]["function"]
assert call["name"] == "sha256_text" and call["arguments"] == {"text": "abc"}
digest = hashlib.sha256(call["arguments"]["text"].encode("utf-8")).hexdigest()
assert digest == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
final = chat(messages + [first, {
    "role": "tool", "tool_name": "sha256_text", "content": digest,
}], [])
assert digest in final["content"], "The final answer did not reproduce the tool result."
print(json.dumps({"model_request": call, "python_result": digest,
                  "model_final_answer": final["content"]}, indent=2))
