Spaces:
Sleeping
Sleeping
Create groq_client.py
Browse files- groq_client.py +36 -0
groq_client.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
from config import MODEL
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
from groq import Groq
|
| 8 |
+
except Exception:
|
| 9 |
+
Groq = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def init_groq_client():
|
| 13 |
+
api_key = os.getenv("GROQ_API_KEY")
|
| 14 |
+
if not api_key or Groq is None:
|
| 15 |
+
return None
|
| 16 |
+
return Groq(api_key=api_key)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def ask_groq_for_matches(system, user, model=MODEL):
|
| 20 |
+
client = init_groq_client()
|
| 21 |
+
if not client:
|
| 22 |
+
raise RuntimeError("Groq client not initialized.")
|
| 23 |
+
|
| 24 |
+
resp = client.chat.completions.create(
|
| 25 |
+
model=model,
|
| 26 |
+
messages=[
|
| 27 |
+
{"role": "system", "content": system},
|
| 28 |
+
{"role": "user", "content": user},
|
| 29 |
+
],
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
content = resp.choices[0].message.content or ""
|
| 33 |
+
match = re.search(r"(\[\s*\{[\s\S]*?\}\s*\])", content)
|
| 34 |
+
if not match:
|
| 35 |
+
raise RuntimeError("No JSON array found.")
|
| 36 |
+
return json.loads(match.group(1))
|