codex-context/saturn/ollama_client.py

40 lines
1.2 KiB
Python
Raw Normal View History

2026-05-04 20:28:20 +02:00
import json
import os
import urllib.error
import urllib.request
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434").rstrip("/")
def ask(prompt: str) -> str:
payload = {
"model": "deepseek-coder",
"messages": [{"role": "user", "content": prompt}],
"stream": False,
}
req = urllib.request.Request(
f"{OLLAMA_URL}/api/chat",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
raw = resp.read().decode("utf-8")
body = json.loads(raw)
return body["message"]["content"]
except urllib.error.HTTPError as exc:
return f"ERROR: HTTP {exc.code} {exc.reason}"
except urllib.error.URLError as exc:
return f"ERROR: {exc.reason}"
except json.JSONDecodeError as exc:
return f"ERROR: Invalid JSON response: {exc}"
except (KeyError, TypeError) as exc:
return f"ERROR: Invalid response format: {exc}"
except Exception as exc:
return f"ERROR: {exc}"
if __name__ == "__main__":
print(ask("Write docker-compose for nginx"))