Spaces:
Sleeping

curium-intel / feedback_digest.py
Piers Lyon
Claude Opus 4.7 (1M context)
Closed-loop feedback: recipients reply, system digests, recap surfaces
3395614
Raw History Blame Contribute Delete
7.57 kB
"""
Feedback Digest (feedback_digest.py) β€” closes the loop visibly.
Reads feedback_signals from the last N days and produces:
1. A short LLM-written "What you told us / what we're doing" HTML
block that sits at the very top of the weekly digest.
2. (Optional) A structured per-recipient view so each colleague's
own feedback is acknowledged in their own digest.
Design notes
- This module ONLY summarises β€” it does NOT auto-tune scoring,
thresholds, or prompts. Auto-tuning over small N is unsafe; the
feedback recap creates the visibility a human needs to make those
decisions. Marking signals applied=true is done by hand or by a
future iteration.
- Cached per-week in `feedback_recap` (created on the fly here β€” small
enough that a separate migration would be overkill). Reads from
feedback_signals.
"""
from __future__ import annotations
import os
import json
import sqlite3
from datetime import datetime, timedelta, date
from pathlib import Path
from typing import Optional, Callable
from dotenv import load_dotenv
env_path = Path(__file__).parent / '.env'
load_dotenv(dotenv_path=env_path, override=True)
DATABASE = "leads.db"
def _week_start_iso(d: Optional[date] = None) -> str:
d = d or date.today()
return (d - timedelta(days=d.weekday())).isoformat()
def fetch_recent_feedback(days: int = 7,
recipient: Optional[str] = None) -> list[dict]:
"""Pull structured feedback signals from the last `days` days.
If `recipient` is given, narrow to that colleague's own feedback.
"""
cutoff = (datetime.utcnow() - timedelta(days=days)).isoformat()
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
if recipient:
rows = conn.execute("""
SELECT id, recipient, sentiment, target_type, target_token,
target_label, suggestion, received_at, applied_at
FROM feedback_signals
WHERE received_at >= ? AND recipient = ?
ORDER BY received_at DESC
""", (cutoff, recipient)).fetchall()
else:
rows = conn.execute("""
SELECT id, recipient, sentiment, target_type, target_token,
target_label, suggestion, received_at, applied_at
FROM feedback_signals
WHERE received_at >= ?
ORDER BY received_at DESC
""", (cutoff,)).fetchall()
conn.close()
return [dict(r) for r in rows]
# ---------------------------------------------------------------------------
# LLM summary
# ---------------------------------------------------------------------------
_SUMMARY_PROMPT = """You are writing the "What you told us last week" recap that sits at the top of the Curium Sales Intelligence weekly digest. Tone: terse, factual, addresses the team directly. Goal: show each contributor their feedback was heard, without flattering or hedging.
You receive a JSON array of structured feedback signals from the last week (sentiment, target_type, target_label, suggestion, recipient name).
Output a short HTML block following this exact pattern:
<h2 style="color:#1a237e;font-size:1.05em;margin:8px 0 8px 0;border-bottom:1px solid #cfd8dc;padding-bottom:4px;">What you told us last week</h2>
<ul style="margin:0 0 12px 18px;padding:0;">
<li style="margin:6px 0;"><strong>{Recipient or "Team"}:</strong> "{one-sentence paraphrase of suggestion}" β€” {what the system is doing about it in one short clause, e.g. "added food manufacturing to this week's theme search" / "noted β€” we'll watch for repeat freshness misses" / "no change yet β€” too small a sample"}.</li>
…
</ul>
Strict rules:
- Maximum 5 bullets. Cluster duplicates (3 people saying "more food manufacturing" β†’ ONE bullet).
- Each bullet attributes the feedback to a recipient name when one is set, else "Team".
- The "what we're doing" clause must be honest. Allowed options: "added to this week's focus", "noted β€” recurring pattern, will adjust", "noted β€” single instance, watching", "no change yet β€” needs more signal", "already applied". Don't invent capabilities the system doesn't have.
- UK English. No emoji. No hedging ("we'll try to", "hopefully") β€” just say what's happening.
- If feedback signals contradict each other (e.g. "more X" vs "less X"), say so explicitly: "Mixed signal on X β€” flagging for review."
If the input array is empty, return ONLY the literal string `__NO_FEEDBACK__`.
Do NOT include `<html>`/`<body>` tags. Do NOT include any preamble or explanation. Start directly with `<h2>`."""
def build_recap_html(days: int = 7,
recipient: Optional[str] = None,
progress_cb: Optional[Callable[[str], None]] = None
) -> str:
"""LLM-build the recap HTML block. Returns "" if there's nothing to
report (so the digest skips the section cleanly).
"""
signals = fetch_recent_feedback(days=days, recipient=recipient)
if not signals:
return ""
api_key = os.environ.get("ANTHROPIC_API_KEY")
if not api_key:
if progress_cb:
progress_cb("feedback recap: no ANTHROPIC_API_KEY β€” fallback rendering")
return _fallback_recap_html(signals)
from anthropic import Anthropic
client = Anthropic(api_key=api_key)
user_msg = (
f"Here are the {len(signals)} feedback signals from the last "
f"{days} days. Build the recap.\n\n"
f"{json.dumps(signals, indent=2, default=str)}"
)
try:
msg = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1500,
system=_SUMMARY_PROMPT,
messages=[{"role": "user", "content": user_msg}],
)
except Exception as e:
if progress_cb:
progress_cb(f"feedback recap: LLM call failed: {e} β€” using fallback")
return _fallback_recap_html(signals)
body = msg.content[0].text.strip()
if body == "__NO_FEEDBACK__":
return ""
if body.startswith("```"):
parts = body.split("```")
if len(parts) >= 2:
body = parts[1]
if body.startswith("html"):
body = body[4:]
body = body.strip()
return body
def _fallback_recap_html(signals: list[dict]) -> str:
"""No-LLM fallback: render every feedback signal as a literal bullet.
Used only when the LLM is unavailable so the loop still closes."""
parts = [
'<h2 style="color:#1a237e;font-size:1.05em;margin:8px 0 8px 0;'
'border-bottom:1px solid #cfd8dc;padding-bottom:4px;">'
'What you told us last week</h2>',
'<ul style="margin:0 0 12px 18px;padding:0;">',
]
for s in signals[:5]:
who = s.get("recipient") or "Team"
suggestion = (s.get("suggestion") or "").strip()
parts.append(
f'<li style="margin:6px 0;"><strong>{who}:</strong> '
f'"{suggestion}" β€” noted, no automatic change applied (LLM summariser unavailable).</li>'
)
parts.append('</ul>')
return "\n".join(parts)
if __name__ == "__main__":
import argparse
p = argparse.ArgumentParser()
p.add_argument("--days", type=int, default=7)
p.add_argument("--recipient", default=None)
args = p.parse_args()
def log(msg: str) -> None:
print(f"[feedback-digest] {msg}", flush=True)
html = build_recap_html(days=args.days, recipient=args.recipient, progress_cb=log)
if not html:
print("(no feedback in the window β€” recap would be omitted)")
else:
print(html)