-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai_handler.py
More file actions
83 lines (68 loc) · 3.2 KB
/
Copy pathai_handler.py
File metadata and controls
83 lines (68 loc) · 3.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import json
import google.generativeai as genai
from typing import Dict, List, Optional
from config import GEMINI_API_KEY, GEMINI_MODEL
from ai_prompts import PromptTemplates
class AIHandler:
def __init__(self):
if not GEMINI_API_KEY:
raise ValueError("GEMINI_API_KEY not found in the .env file")
genai.configure(api_key=GEMINI_API_KEY)
self.model = genai.GenerativeModel(GEMINI_MODEL)
self.prompts = PromptTemplates()
def _call_api(self, prompt: str, response_format: Optional[Dict] = None) -> str:
try:
if response_format:
prompt = prompt + "\n\nIMPORTANT: Respond with valid JSON only, no markdown code blocks or additional text."
response = self.model.generate_content(prompt)
text = response.text
if response_format:
text = text.strip()
if text.startswith("```json"):
text = text[7:]
elif text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
return text
except Exception as e:
raise Exception(f"AI API call failed: {str(e)}")
def generate_summary(self, text: str, summary_length: str,
output_format: str, tone: str) -> str:
prompt = self.prompts.create_summary_prompt(
text, summary_length, output_format, tone
)
return self._call_api(prompt)
def generate_summary_for_chunks(self, chunks: List[str], summary_length: str,
output_format: str, tone: str) -> str:
if len(chunks) == 1:
return self.generate_summary(chunks[0], summary_length, output_format, tone)
chunk_summaries = []
for chunk in chunks:
summary = self.generate_summary(chunk, summary_length, output_format, tone)
chunk_summaries.append(summary)
merge_prompt = self.prompts.create_merge_summary_prompt(
chunk_summaries, output_format, tone
)
return self._call_api(merge_prompt)
def extract_key_terms(self, text: str) -> Dict:
prompt = self.prompts.create_key_terms_prompt(text)
response = self._call_api(prompt, response_format={"type": "json_object"})
try:
return json.loads(response)
except json.JSONDecodeError:
return {
"key_terms": [],
"exam_topics": []
}
def generate_quiz(self, text: str, difficulty: str = "medium") -> Dict:
prompt = self.prompts.create_quiz_prompt(text, difficulty)
response = self._call_api(prompt, response_format={"type": "json_object"})
try:
data = json.loads(response)
if not data.get("multiple_choice") and not data.get("short_answer"):
raise ValueError("Quiz response is empty")
return data
except (json.JSONDecodeError, ValueError) as e:
raise Exception(f"Quiz parsing failed: {str(e)}. Response: {response[:200]}")