From 76ad52d3a9ea571cc14c37b310768373a91d62b8 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Mon, 3 Mar 2025 15:55:48 +0100 Subject: [PATCH] refactor: Addressing PR comments Refs: OPS-12 Consolidated AI gen module Changed API endpoint --- senju/ai_gen.py | 75 ------------------------------------- senju/haiku.py | 70 ++++++++++++++++++++++++++++++++++ senju/main.py | 5 +-- senju/templates/prompt.html | 2 +- 4 files changed, 73 insertions(+), 79 deletions(-) delete mode 100644 senju/ai_gen.py diff --git a/senju/ai_gen.py b/senju/ai_gen.py deleted file mode 100644 index 9dec9ae..0000000 --- a/senju/ai_gen.py +++ /dev/null @@ -1,75 +0,0 @@ -from __future__ import annotations - -import json - -import requests - -from senju.haiku import Haiku - -AI_BASE_URL: str = "http://ollama:11434/api" -AI_GEN_ENDPOINT: str = "/generate" - -AI_GEN_SYS_PROMPT = """ -You are a haiku generation AI. Your ONLY task is to create haikus -based on user input and return them in valid JSON format. - -HAIKU DEFINITION: -- Traditional Japanese poetry with three lines -- 5 syllables in the first line -- 7 syllables in the second line -- 5 syllables in the third line -- Must incorporate the subject(s) from user input - -OUTPUT RULES: -1. ONLY respond with a valid JSON object in this exact format: -{ - "line1": "First line of haiku", - "line2": "Second line of haiku", - "line3": "Third line of haiku" -} - -2. Do NOT include: - - Any explanations - - Any markdown formatting (like ```json or ```) - - Any additional text before or after the JSON - - Any line breaks within the JSON structure - -3. Before submitting, verify: - - The JSON uses double quotes (not single quotes) - - All property names are lowercase and exactly as shown above - - There are no trailing commas - - The JSON is properly formatted - -IMPORTANT: The output will be consumed by a web application that requires -EXACT FORMAT compliance. Any deviation will cause the application to break. - -USER INPUT FOR HAIKU CREATION: -""" - - -def request_haiku(seed: str) -> Haiku: - """This function prompts the ai to generate - the hauku based on the user input""" - - ai_gen_request = { - "model": "llama3.2:1b", - "prompt": f"{AI_GEN_SYS_PROMPT}{seed}", - "stream": False - } - - while True: - try: - r = requests.post(url=AI_BASE_URL+AI_GEN_ENDPOINT, - json=ai_gen_request) - ai_response = json.loads(r.json()["response"]) - haiku = Haiku( - [ - ai_response["line1"], - ai_response["line2"], - ai_response["line3"] - ]) - break - except json.JSONDecodeError: - continue - - return haiku diff --git a/senju/haiku.py b/senju/haiku.py index 1a626e4..4450308 100644 --- a/senju/haiku.py +++ b/senju/haiku.py @@ -3,6 +3,48 @@ from __future__ import annotations import json from dataclasses import dataclass +import requests + +AI_BASE_URL: str = "http://ollama:11434/api" +AI_GEN_ENDPOINT: str = "/generate" + +AI_GEN_SYS_PROMPT = """ +You are a haiku generation AI. Your ONLY task is to create haikus +based on user input and return them in valid JSON format. + +HAIKU DEFINITION: +- Traditional Japanese poetry with three lines +- 5 syllables in the first line +- 7 syllables in the second line +- 5 syllables in the third line +- Must incorporate the subject(s) from user input + +OUTPUT RULES: +1. ONLY respond with a valid JSON object in this exact format: +{ +"line1": "First line of haiku", +"line2": "Second line of haiku", +"line3": "Third line of haiku" +} + +2. Do NOT include: +- Any explanations +- Any markdown formatting (like ```json or ```) +- Any additional text before or after the JSON +- Any line breaks within the JSON structure + +3. Before submitting, verify: +- The JSON uses double quotes (not single quotes) +- All property names are lowercase and exactly as shown above +- There are no trailing commas +- The JSON is properly formatted + +IMPORTANT: The output will be consumed by a web application that requires +EXACT FORMAT compliance. Any deviation will cause the application to break. + +USER INPUT FOR HAIKU CREATION: +""" + @dataclass class Haiku: @@ -10,3 +52,31 @@ class Haiku: def get_json(self): return json.dumps(self.lines) + + @staticmethod + def request_haiku(seed: str) -> Haiku: + """This function prompts the ai to generate + the hauku based on the user input""" + + ai_gen_request = { + "model": "llama3.2:1b", + "prompt": f"{AI_GEN_SYS_PROMPT}{seed}", + "stream": False + } + + while True: + try: + r = requests.post(url=AI_BASE_URL+AI_GEN_ENDPOINT, + json=ai_gen_request) + ai_response = json.loads(r.json()["response"]) + haiku = Haiku( + [ + ai_response["line1"], + ai_response["line2"], + ai_response["line3"] + ]) + break + except json.JSONDecodeError: + continue + + return haiku diff --git a/senju/main.py b/senju/main.py index 75f6043..c9aa498 100644 --- a/senju/main.py +++ b/senju/main.py @@ -4,7 +4,6 @@ from pathlib import Path from flask import Flask, redirect, render_template, request, url_for -from senju.ai_gen import request_haiku from senju.haiku import Haiku from senju.store_manager import StoreManager @@ -51,13 +50,13 @@ def prompt_view(): ) -@app.route("/generate_haiku", methods=['POST']) +@app.route("/api/v1/haiku", methods=['POST']) def generate_haiku(): prompt = "a" if request.method == 'POST': json_data = request.get_json() prompt = json_data["prompt"] - haiku = request_haiku(prompt) + haiku = Haiku.request_haiku(prompt) id = store.save_haiku(haiku) return str(id) else: diff --git a/senju/templates/prompt.html b/senju/templates/prompt.html index 730d47e..1f08089 100644 --- a/senju/templates/prompt.html +++ b/senju/templates/prompt.html @@ -50,7 +50,7 @@ document.getElementById("submit-btn").addEventListener("click", function() { console.log(userInput ); - fetch('/generate_haiku', { + fetch('/api/v1/haiku', { method: 'POST', headers: { 'Content-Type': 'application/json'