chat 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import json
  5. import signal
  6. import hashlib
  7. import requests
  8. from pathlib import Path
  9. # Configuration
  10. PROXY_HOST = "chat.reesec.net"
  11. PROXY_PORT = 443
  12. MODEL = "mistral:7b"
  13. #MODEL = "deepseek-r1:8b"
  14. #MODEL = "gemma3:4b"
  15. def signal_handler(sig, frame):
  16. print() # Newline for clean exit
  17. sys.exit(0)
  18. signal.signal(signal.SIGINT, signal_handler)
  19. def chat(host, port, api_key, model, question):
  20. """Send a question to Ollama proxy and stream the response."""
  21. url = f"https://{host}:{port}/api/generate"
  22. payload = {
  23. "model": model,
  24. "prompt": question,
  25. "stream": True
  26. }
  27. headers = {
  28. "X-API-Key": api_key
  29. }
  30. try:
  31. response = requests.post(url, json=payload, stream=True, headers=headers)
  32. response.raise_for_status()
  33. # Stream and print the response
  34. for line in response.iter_lines():
  35. if line:
  36. data = json.loads(line)
  37. if "response" in data:
  38. print(data["response"], end="", flush=True)
  39. print() # Newline at the end
  40. except requests.exceptions.HTTPError as e:
  41. if e.response.status_code == 401:
  42. print("Error: Invalid API key", file=sys.stderr)
  43. else:
  44. print(f"Error: {e}", file=sys.stderr)
  45. sys.exit(1)
  46. except requests.exceptions.ConnectionError as e:
  47. print(f"Error: Could not connect to proxy at {host}:{port}\n{e}", file=sys.stderr)
  48. sys.exit(1)
  49. except requests.exceptions.RequestException as e:
  50. print(f"Error: {e}", file=sys.stderr)
  51. sys.exit(1)
  52. if __name__ == "__main__":
  53. home_path = Path.home()
  54. with open(f'{home_path}/.ssh/chat.key', 'r') as f:
  55. API_KEY = str(f.read().strip())
  56. # Get question from command line arguments
  57. if len(sys.argv) < 2:
  58. print("Usage: python chat.py <question>", file=sys.stderr)
  59. print("Example: python chat.py 'What is Python?'", file=sys.stderr)
  60. sys.exit(1)
  61. question = " ".join(sys.argv[1:])
  62. chat(PROXY_HOST, PROXY_PORT, API_KEY, MODEL, question)