pdf / models /groq_model.py
haresh15's picture
Upload 32 files
eef90c7 verified
Raw History Blame Contribute Delete
4.21 kB
import os
import json
import re
from dotenv import load_dotenv
from groq import Groq
from typing import List, Dict
import httpx # Needed for SSL bypass
class GroqModel:
def __init__(self):
load_dotenv()
api_key = os.getenv("GROQ_API_KEY")
if not api_key:
raise ValueError("❌ GROQ_API_KEY missing in .env")
# ⭐ FIX SSL: disable certificate verification (Your network uses self-signed cert)
self.client = Groq(
api_key=api_key,
http_client=httpx.Client(verify=False)
)
self.model_name = "llama-3.3-70b-versatile"
# -------------------------------------------------------
# Generate RAG Answer
# -------------------------------------------------------
def generate_answer(self, question: str, context: str) -> str:
prompt = f"""
Use ONLY the following context to answer the question:
Context:
{context}
Question: {question}
Give a clean, short answer. Do NOT add new information.
"""
response = self.client.chat.completions.create(
model=self.model_name,
messages=[
{"role": "system", "content": "You are a helpful RAG assistant."},
{"role": "user", "content": prompt},
]
)
return response.choices[0].message.content.strip()
# -------------------------------------------------------
# Rank chunks by relevance using Groq LLaMA
# -------------------------------------------------------
def score_chunks(self, question: str, chunks: List[Dict], top_k: int = 5) -> List[Dict]:
prompt_parts = [
f"Question: {question}\n\n"
"Rate each passage from 0–100 ONLY for relevance.\n"
"Return JSON ONLY in this format:\n"
"[{\"index\": 0, \"score\": 85}, {\"index\": 1, \"score\": 23}]\n\n"
"Passages:\n"
]
for i, c in enumerate(chunks):
text = c.get("content", "").replace("\n", " ")
prompt_parts.append(f"[{i}] {text[:700]}\n")
prompt = "\n".join(prompt_parts)
# Call Groq LLaMA model
response = self.client.chat.completions.create(
model=self.model_name,
messages=[
{"role": "system", "content": "Return ONLY strict JSON. No explanation."},
{"role": "user", "content": prompt}
]
)
raw = response.choices[0].message.content.strip()
# Parse JSON strictly
try:
cleaned = re.sub(r"```json|```", "", raw).strip()
parsed = json.loads(cleaned)
except Exception:
parsed = [{"index": i, "score": 0} for i in range(len(chunks))]
# Attach scores
for item in parsed:
idx = item.get("index", 0)
score = float(item.get("score", 0))
if idx < len(chunks):
chunks[idx]["_llm_score"] = score
ranked = sorted(chunks, key=lambda x: x.get("_llm_score", 0), reverse=True)
return ranked[:top_k]
# -------------------------------------------------------
# 🎀 Voice β†’ Text (Groq Whisper STT)
# -------------------------------------------------------
def transcribe_audio(self, audio_bytes):
"""
Convert microphone audio β†’ text using Groq Whisper.
audio_bytes: raw WAV bytes from st.audio_input()
"""
if not audio_bytes:
return "❌ No audio detected."
try:
response = self.client.audio.transcriptions.create(
model="whisper-large-v3",
file=("voice_input.wav", audio_bytes, "audio/wav")
)
# Whisper returns either .text or .transcription
text = getattr(response, "text", None) or getattr(response, "transcription", None)
if not text:
return "⚠️ Audio detected but transcription is empty."
return text.strip()
except Exception as e:
return f"❌ Transcription failed: {str(e)}"