diff --git a/ops/scripts/prism_enrich_worker.py b/ops/scripts/prism_enrich_worker.py index f8ee0f5..b17aaaa 100644 --- a/ops/scripts/prism_enrich_worker.py +++ b/ops/scripts/prism_enrich_worker.py @@ -11,69 +11,99 @@ import llm_research as R import llm_fallback as L import rag -PROMPT = """Extract technical facts from this support/manual document. +SUPPORT_PROMPT = """Extract technical facts from this support/manual document. Return STRICT JSON only: {"device":"...", "facts":[{"key":"...","value":"...","unit":null,"quote":"..."}]} Only explicit facts. Never guess. If none: {"device":"","facts":[]}. Text: """ +MODEL_PROMPT = """Write a short technical positioning note for this AV product. +Do not invent specifications. Use only the given fields. 2-3 sentences, Russian. +Return plain text only. +Model: %s +Vendor: %s +Role: %s +Domain: %s +Known specs: %s +""" conn = psycopg2.connect(rag.DSN) cur = conn.cursor() +cur.execute("update prism.tasks set status='pending', started_at=null, worker=null where status='running'") +conn.commit() print("worker start", flush=True) while True: cur.execute(""" update prism.tasks t set status='running', worker='229-7b', started_at=now() where t.id = ( select id from prism.tasks where status='pending' order by id limit 1 for update skip locked - ) returning t.id, t.source_id, t.model_id + ) returning t.id, t.kind, t.source_id, t.model_id """) row = cur.fetchone() conn.commit() if not row: print("no pending tasks", flush=True) break - task_id, sid, mid = row + task_id, kind, sid, mid = row try: - cur.execute("select url,title from prism.sources where id=%s", (sid,)) - s = cur.fetchone() - if not s: - raise RuntimeError("source missing") - url, title = s - txt = R.fetch(url) - if len(txt) < 200: - raise RuntimeError("empty text %s" % len(txt)) - chunk = R.pick_excerpt(txt, 3500) - r = L.ask(PROMPT + chunk, max_tokens=700, temperature=0.0, - chain=[{"name": "qwen2.5:7b", "kind": "ollama", "timeout": 300}]) - m = re.search(r"\{.*\}", r["text"], re.S) - d = json.loads(m.group(0)) if m else {} - facts = d.get("facts") or [] - for f in facts: - key = re.sub(r"[^a-zA-Z0-9_.-]+", "_", str(f.get("key") or "fact")).strip("_").lower() - if not key: - continue - val = f.get("value") - vtext = None if val is None else str(val)[:2000] - cur.execute("""insert into prism.specs(model_id,key,value_text,unit,source_id,confidence) - values (%s,%s,%s,%s,%s,0.45) - on conflict (model_id,key,source_id) do nothing""", - (mid, key, vtext, f.get("unit"), sid)) - cur.execute("""insert into prism.evidence(model_id,source_id,field,value_text,unit,quote,confidence,verified) - values (%s,%s,%s,%s,%s,%s,0.45,false)""", - (mid, sid, key, vtext, f.get("unit"), f.get("quote"))) - cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,stats,started_at,finished_at) - values (%s,'enrich_support7b','ok','229',%s,%s,now(),now())""", - (mid, "qwen2.5:7b", json.dumps({"source_id": sid, "facts": len(facts)}))) + if kind == "model_note": + cur.execute("select vendor,name,role,domain from prism.models where id=%s", (mid,)) + m = cur.fetchone() + if not m: + raise RuntimeError("model missing") + vendor, name, role, domain = m + cur.execute("""select string_agg(key || '=' || coalesce(value_text,''), ', ' order by key) + from (select distinct key,value_text from prism.specs where model_id=%s limit 12) q""", (mid,)) + specs = (cur.fetchone() or [""])[0] or "" + prompt = MODEL_PROMPT % (name, vendor, role or "unknown", domain or "unknown", specs[:800]) + r = L.ask(prompt, max_tokens=250, temperature=0.2, + chain=[{"name": "qwen2.5:7b", "kind": "ollama", "timeout": 300}]) + text = r["text"].strip()[:2000] + cur.execute("""insert into prism.model_notes(model_id,kind,text,model) + values (%s,'positioning',%s,'qwen2.5:7b')""", (mid, text)) + cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,stats,started_at,finished_at) + values (%s,'model_note7b','ok','229',%s,%s,now(),now())""", + (mid, "qwen2.5:7b", json.dumps({"task_id": task_id, "chars": len(text)}))) + else: + cur.execute("select url,title from prism.sources where id=%s", (sid,)) + s = cur.fetchone() + if not s: + raise RuntimeError("source missing") + url, title = s + txt = R.fetch(url) + if len(txt) < 200: + raise RuntimeError("empty text %s" % len(txt)) + chunk = R.pick_excerpt(txt, 3500) + r = L.ask(SUPPORT_PROMPT + chunk, max_tokens=700, temperature=0.0, + chain=[{"name": "qwen2.5:7b", "kind": "ollama", "timeout": 300}]) + m = re.search(r"\{.*\}", r["text"], re.S) + d = json.loads(m.group(0)) if m else {} + facts = d.get("facts") or [] + for f in facts: + key = re.sub(r"[^a-zA-Z0-9_.-]+", "_", str(f.get("key") or "fact")).strip("_").lower() + if not key: + continue + val = f.get("value") + vtext = None if val is None else str(val)[:2000] + cur.execute("""insert into prism.specs(model_id,key,value_text,unit,source_id,confidence) + values (%s,%s,%s,%s,%s,0.45) + on conflict (model_id,key,source_id) do nothing""", + (mid, key, vtext, f.get("unit"), sid)) + cur.execute("""insert into prism.evidence(model_id,source_id,field,value_text,unit,quote,confidence,verified) + values (%s,%s,%s,%s,%s,%s,0.45,false)""", + (mid, sid, key, vtext, f.get("unit"), f.get("quote"))) + cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,stats,started_at,finished_at) + values (%s,'enrich_support7b','ok','229',%s,%s,now(),now())""", + (mid, "qwen2.5:7b", json.dumps({"source_id": sid, "facts": len(facts)}))) cur.execute("update prism.tasks set status='done', finished_at=now() where id=%s", (task_id,)) - print("done", task_id, "facts", len(facts), flush=True) + print("done", task_id, kind, flush=True) except Exception as e: cur.execute("update prism.tasks set status='error', error=%s, finished_at=now() where id=%s", (str(e)[:300], task_id)) cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,error,started_at,finished_at) - values (%s,'enrich_support7b','error','229',%s,%s,now(),now())""", + values (%s,'worker7b','error','229',%s,%s,now(),now())""", (mid, "qwen2.5:7b", str(e)[:300])) - print("error", task_id, str(e)[:150], flush=True) + print("error", task_id, kind, str(e)[:150], flush=True) conn.commit() time.sleep(1) conn.close()