import requests
import json

url = "http://192.168.1.52:11434/api/generate"



data = {
    "model": "llama3",
    "prompt": "Hello World!! "
}

try:
    # Try to connect to Ollama API
    response = requests.post(url, json=data, stream=True, timeout=10)
    response.raise_for_status()  # Raise error if status code != 200

    print("Connected to Ollama server. Streaming response...\n")

    for line in response.iter_lines():
        if line:
            try:
                # Parse JSON safely
                chunk = json.loads(line)
                print(chunk.get("response", ""), end="")
            except json.JSONDecodeError:
                print("\n⚠ Received malformed JSON chunk, skipping...")

except requests.exceptions.ConnectionError:
    print(" Cannot connect to Ollama server. Is it running on {url}")
    print(" Try running: `ollama serve` in another terminal.")

except requests.exceptions.Timeout:
    print(" Request timed out. The server may be busy or not responding.")

except requests.exceptions.HTTPError as e:
    print(f"HTTP error occurred: {e}")

except Exception as e:
    print(f"Unexpected error: {e}")
