Workhub / server /llm.py
ag235772's picture
files Replacement
e298636
Raw History Blame Contribute Delete
6.16 kB
"""Groq API proxy helpers (free tier, OpenAI-compatible). Text is processed in memory and never logged or stored.
Model choice (all free on Groq, no card needed):
primary : openai/gpt-oss-120b - best quality/JSON-following of the free models, 1K req/day
fallback : llama-3.3-70b-versatile - used automatically on rate-limit / model errors (separate limit pool)
Override with GROQ_MODEL / GROQ_FALLBACK_MODEL.
"""
import json, os, re, time, urllib.request, urllib.error
API_URL = os.environ.get("GROQ_BASE_URL", "https://api.groq.com/openai/v1") + "/chat/completions"
MODEL = os.environ.get("GROQ_MODEL", "openai/gpt-oss-120b")
FALLBACK = os.environ.get("GROQ_FALLBACK_MODEL", "llama-3.3-70b-versatile")
TIMEOUT = int(os.environ.get("GROQ_TIMEOUT", "45"))
def available():
return bool(os.environ.get("GROQ_API_KEY"))
def _call(model, system, user, max_tokens):
body = {"model": model, "temperature": 0.2, "max_completion_tokens": max_tokens,
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
if model.startswith("openai/gpt-oss"):
body["reasoning_effort"] = "low" # keep reasoning tokens small: faster + saves free-tier token quota
body["max_completion_tokens"] = max_tokens + 800 # reasoning tokens count toward the cap
req = urllib.request.Request(API_URL, data=json.dumps(body).encode(), method="POST", headers={
"Authorization": "Bearer " + os.environ["GROQ_API_KEY"], "Content-Type": "application/json",
"User-Agent": "workhub/1.0"})
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
data = json.loads(r.read())
return (data["choices"][0]["message"].get("content") or "").strip()
def complete(system, user, max_tokens=1500):
models = [MODEL] + ([FALLBACK] if FALLBACK and FALLBACK != MODEL else [])
last = None
for i, m in enumerate(models):
try:
out = _call(m, system, user, max_tokens)
if out:
return out
last = RuntimeError("empty response")
except urllib.error.HTTPError as e:
last = e
if e.code == 429 and i == len(models) - 1:
time.sleep(min(float(e.headers.get("retry-after", "2") or 2), 5))
if e.code in (401, 403): # bad key: fallback won't help
raise
except (urllib.error.URLError, TimeoutError, KeyError, ValueError) as e:
last = e
raise last or RuntimeError("AI call failed")
def _json(out):
m = re.search(r"[\[{].*[\]}]", out, re.S)
return json.loads(m.group(0)) if m else None
def _chunks(items, limit):
"""Split items into groups whose JSON stays under the free-tier tokens-per-minute cap (nothing is dropped)."""
group, size = [], 2
for it in items:
n = len(json.dumps(it)) + 1
if group and size + n > limit:
yield group
group, size = [], 2
group.append(it)
size += n
if group:
yield group
def nl_to_spec(question, today):
system = ("You convert questions about a work log of support Tickets and POCs into a JSON query. Reply with ONLY "
'a JSON object with keys: start (YYYY-MM-DD|null), end (YYYY-MM-DD|null), work_type ("Ticket"|"POC"|null), '
'product ("WAF"|"WAS"|null), keyword (string|null), intent (list|count|avg_day|avg_week|avg_month|'
"group_week|group_month). Weeks run Monday-Sunday.")
return _json(complete(system, f"Today is {today} .\nQuestion: {question}", 300))
MAIL_SYSTEM = ("You help a security support/POC engineer at a web application security company write emails. Use the "
"supplied templates as the primary source for structure, tone and wording. Never invent facts (names, IDs, "
"dates, findings, commitments). Keep {{placeholders}} for unknown values. Output only the email "
"(a 'Subject:' line, blank line, body).")
def _tpl(c):
return "\n\n".join(f"[Template {i + 1}: {t.get('title', '')}]\n{t.get('body', '')}" for i, t in enumerate(c))
def mail(mode, text, cands):
if mode == "fix":
return complete(MAIL_SYSTEM + " The user supplies a rough draft: fix grammar, clarity, tone and structure, keep "
"every fact exactly, match the reference templates' style, add no new commitments.",
f"Rough draft:\n{text}\n\nReference templates:\n{_tpl(cands) or '(none)'}", 1200)
return complete(MAIL_SYSTEM, f"Request:\n{text}\n\nTemplates:\n{_tpl(cands)}", 1200)
def import_map(rows, today):
system = ("You analyse a spreadsheet exported from a support engineer's personal work log (tickets and POCs for products "
"WAF and WAS). Given the first rows (each cell shown as [col index]: value), reply with ONLY JSON: "
'{"header_row": <0-based index or null>, "mapping": {"date": col|null, "work_type": col|null, "product": '
'col|null, "title": col|null, "item_id": col|null, "ticket_id": col|null, "poc_id": col|null, '
'"description": col|null}, "structured": true|false, "notes": "short"}. Use null when a field is absent.')
return _json(complete(system, f"Today is {today}.\n" + json.dumps(rows)[:12000], 600))
def import_extract(items, today):
system = ("Extract work-log records from messy spreadsheet rows. Each input item has an index i and raw text. Reply "
"with ONLY a JSON array, one object per item: {\"i\": n, \"date\": \"YYYY-MM-DD\"|null, \"work_type\": "
"\"Ticket\"|\"POC\"|null, \"product\": \"WAF\"|\"WAS\"|null, \"title\": str|null, \"item_id\": str|null, "
"\"description\": str|null, \"questions\": [short questions for anything missing or ambiguous]}. "
"NEVER guess a missing value: use null and add a question. Dates are day-first (India) unless obviously not.")
out = []
for g in _chunks(items, 9000):
res = _json(complete(system, f"Today is {today}.\n" + json.dumps(g), 3000))
if isinstance(res, list):
out.extend(res)
return out