|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +""" |
| 4 | +This script interacts with the Ollama API to generate text based on a given prompt. |
| 5 | +The output will be printed to the console and saved to a Markdown file named `generated_output.md`. |
| 6 | +Version: 1.1 |
| 7 | +Python 3.13+ |
| 8 | +Date created: April 30th, 2026 |
| 9 | +Date modified: - |
| 10 | +""" |
| 11 | + |
| 12 | +import json |
| 13 | +import sys |
| 14 | + |
| 15 | +import requests # type: ignore |
| 16 | +from requests.exceptions import RequestException # type: ignore |
| 17 | + |
| 18 | +# Endpoint of Ollama API |
| 19 | +URL = "http://localhost:11434/api/generate" |
| 20 | + |
| 21 | +data = { |
| 22 | + "model": "qwen2.5-coder", |
| 23 | + "prompt": "Write a Python class called `Cameras` with the field `manufacturer`.", |
| 24 | + "max_tokens": 1000, |
| 25 | + "temperature": 0.6, |
| 26 | + "top_p": 0.9, |
| 27 | + "n": 1, |
| 28 | + "stream": False, |
| 29 | +} |
| 30 | + |
| 31 | + |
| 32 | +def fetch_generated_text() -> str: |
| 33 | + """ |
| 34 | + Fetch generated text from the Ollama API. |
| 35 | + """ |
| 36 | + |
| 37 | + generated_text = "" |
| 38 | + |
| 39 | + try: |
| 40 | + # Make a POST request to the Ollama API |
| 41 | + response: requests.Response = requests.post(URL, json=data, stream=True) |
| 42 | + except RequestException as e: |
| 43 | + print(f"Error message:\n{e}") |
| 44 | + sys.exit("No connection to Ollama API. Exit program!") |
| 45 | + |
| 46 | + for line in response.iter_lines(): |
| 47 | + if line: |
| 48 | + decoded_line = line.decode("utf-8") |
| 49 | + result = json.loads(decoded_line) |
| 50 | + # Get the generated text from the response |
| 51 | + generated_text = result.get("response", "") |
| 52 | + |
| 53 | + return generated_text |
| 54 | + |
| 55 | + |
| 56 | +def main() -> None: |
| 57 | + """Main function to execute the script.""" |
| 58 | + |
| 59 | + answer: str = fetch_generated_text() |
| 60 | + |
| 61 | + print(answer, end="", flush=True) |
| 62 | + |
| 63 | + # Save the generated text to a Markdown file |
| 64 | + with open("generated_output.md", "a", encoding="utf-8") as md_file: |
| 65 | + md_file.write(answer) |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + main() |
0 commit comments