Spaces:
Sleeping
Sleeping
SmallConfidence deploy commited on
Commit ·
45aee2a
1
Parent(s): 73ecc58
Small steps, coach memory, regional crisis lines, evals
Browse filesFiles changed (4)
- README.md+8-3
- __pycache__/app.cpython-315.pycAdded
- app.py+119-14
- safety.py+32-7
15 unmodified lines16171819202122232425262728293015 unmodified lines## Endpoints (Flutter)- `GET /health` (open)- `POST /chat/stream` — `{ "personalityId", "message", "history?" }` → server-sent events:`{"delta": "..."}` chunks, then `{"done": true, "safety": bool}` or `{"error": "..."}`- `POST /chat` — same body, whole reply as `{ "reply", "safety", "personality" }`Both chat routes need `Authorization: Bearer <Firebase ID token>` for project`smallconfidence` (401 otherwise) and are rate limited per user (429).Replies draw on `content.json`, built from the app's content PDFs with`scripts/build_content.py`. Messages that mention self-harm or suicide getAustralian crisis lines added to the reply, even if the model call fails.Public URL: `https://scchess-confidence-api.hf.space`15 unmodified lines161718192021222324252627282930313233343515 unmodified lines## Endpoints (Flutter)- `GET /health` (open)- `POST /chat/stream` — `{ "personalityId", "message", "history?", "region?","profileNotes?", "openSteps?", "updateMemory?" }` → server-sent events:`{"delta": "..."}` chunks, then (with `updateMemory`) `{"memory": "..."}`,then `{"done": true, "safety": bool}` or `{"error": "..."}`- `POST /chat` — same body, whole reply as `{ "reply", "safety", "personality" }`Both chat routes need `Authorization: Bearer <Firebase ID token>` for project`smallconfidence` (401 otherwise) and are rate limited per user (429).Replies draw on `content.json`, built from the app's content PDFs with`scripts/build_content.py`. Messages that mention self-harm or suicide getcrisis lines for the user's `region` (AU default; NZ, US, CA, GB, IE; othersget findahelpline.com) added to the reply, even if the model call fails.`profileNotes` and `openSteps` come from the app's Firestore; replies may endwith a `Small step:` line the app offers to save.Public URL: `https://scchess-confidence-api.hf.space`
86 unmodified lines8788899091929394959697989910010 unmodified lines1111121131141151161171181191201211227 unmodified lines13013113213313413513613713813914014114214318 unmodified lines16216316416516616716816917024 unmodified lines19519619719819920020120220320420520621 unmodified lines2282292302312322332342352362372381 unmodified line24024124224324424524624724 unmodified lines2722732742752762771 unmodified line27928028128228328428528628728828973 unmodified lines3633643653663673689 unmodified lines37837938038138238386 unmodified linesTONE = """You are a confidence coach inside the Jazzii app.You are warm and supportive — not a therapist or doctor.Do not diagnose mental health conditions. If someone expresses crisis or self-harm, gently encourage professional help and crisis resources.Keep replies concise (2–4 short paragraphs max unless the user asks for more).How to respond:- Name what they seem to feel before you advise.- Stay with that feeling for a sentence. Do not rush them past it.- Then offer one small step or one question, not a list of advice.- Do not correct them, lecture them, or jump to reassurance before they feel heard.- Use the coach notes below as your subject knowledge. Ask a follow-up when it helps."""def get_personality(personality_id: str) -> dict[str, Any] | None:10 unmodified linesMAX_MESSAGE_CHARS = 2000MAX_HISTORY = 20class ChatRequest:"""A validated chat turn, ready to send to DeepSeek."""def __init__(self, personality_id: str, message: Any, history: Any):if not personality_id or not isinstance(message, str) or not message.strip():raise HTTPException(status_code=400, detail="personalityId and message are required"7 unmodified linesif not personality:raise HTTPException(status_code=404, detail="Personality not found")self.personality = personalityself.message = message.strip()self.crisis = safety.is_crisis(self.message)notes = CONTENT.search(personality["id"], self.message)messages: list[dict[str, str]] = [{"role": "system", "content": system_prompt(personality, notes)},]for item in history if isinstance(history, list) else []:if not isinstance(item, dict):continue18 unmodified linesdef finish(self, reply: str) -> str:if self.crisis:return safety.with_resources(reply or safety.FALLBACK_REPLY)return replydef _deepseek_payload(req: ChatRequest, stream: bool) -> dict[str, Any]:return {24 unmodified linesreturn fallbackasync def deepseek_chat(personality_id: str,message: str,history: list[dict[str, Any]] | None = None,) -> dict[str, Any]:req = ChatRequest(personality_id, message, history or [])api_key = _require_key()try:21 unmodified linesif not reply and not req.crisis:raise HTTPException(status_code=502, detail="Empty response from DeepSeek")return {"reply": req.finish(reply),"safety": req.crisis,"personality": req.personality_summary(),}def _sse(payload: dict[str, Any]) -> str:1 unmodified lineasync def deepseek_stream(req: ChatRequest, api_key: str) -> AsyncIterator[str]:"""Server-sent events: {"delta"}… then {"done", "safety"} or {"error"}."""got_text = Falsetry:async with httpx.AsyncClient(timeout=60.0, transport=HTTP_TRANSPORT) as client:async with client.stream(24 unmodified lines)if delta:got_text = Trueyield _sse({"delta": delta})except Exception as exc: # noqa: BLE001if not req.crisis:1 unmodified linereturnif req.crisis:tail = safety.CRISIS_RESOURCES if got_text else req.finish("")yield _sse({"delta": ("\n\n" if got_text else "") + tail})elif not got_text:yield _sse({"error": "Empty response from DeepSeek"})returnyield _sse({"done": True, "safety": req.crisis})73 unmodified linespersonality_id=body.get("personalityId", ""),message=body.get("message", ""),history=body.get("history") or [],)except HTTPException as exc:return JSONResponse({"error": exc.detail}, status_code=exc.status_code)9 unmodified linesbody.get("personalityId", ""),body.get("message", ""),body.get("history") or [],)api_key = _require_key()except HTTPException as exc:86 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211311411511611711811912010 unmodified lines1311321331341351361371381391401411421431441451461471481491501517 unmodified lines15916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818918 unmodified lines20820921021121221321421521621721821924 unmodified lines24424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629721 unmodified lines3193203213223233243253263273283293303313323333341 unmodified line33633733833934034134234334434524 unmodified lines3703713723733743753761 unmodified line37837938038138238338438538638738838939039139273 unmodified lines4664674684694704714729 unmodified lines48248348448548648748886 unmodified linesTONE = """You are a confidence coach inside the Jazzii app.You are warm and supportive — not a therapist or doctor.Do not diagnose mental health conditions. If someone expresses crisis or self-harm, gently encourage professional help and crisis resources.Keep replies short: 2–3 short paragraphs unless the user asks for more.How to respond:- Name what they seem to feel before you advise. Stay with that feeling for a sentence; do not rush them past it.- Then give one idea at most, in plain words. Do not explain the psychology behind it, list tips, or offer example scripts unless they ask.- End with exactly one of these, never both:- one question, or- one small step, on its own last line starting "Small step:" (one short sentence they could do in the next day or two). If you end with a small step, ask no question anywhere in the reply.- Do not correct them, lecture them, or jump to reassurance before they feel heard.- Use the coach notes below as your subject knowledge.- Never offer a small step during a crisis."""def _user_context(profile_notes: str, open_steps: list[str]) -> str:parts = []if profile_notes:parts.append("What you know about this user from earlier chats (use it naturally; ""do not recite it):\n" + profile_notes)if open_steps:steps = "\n".join(f"- {s}" for s in open_steps)parts.append("Small steps the user planned earlier and hasn't marked done:\n" + steps +"\nIf the conversation is just starting, ask once, briefly, how one of these ""went before moving on. Don't press if they change the subject.")return "\n\n".join(parts)def get_personality(personality_id: str) -> dict[str, Any] | None:10 unmodified linesMAX_MESSAGE_CHARS = 2000MAX_HISTORY = 20MAX_PROFILE_CHARS = 1200MAX_OPEN_STEPS = 3MAX_STEP_CHARS = 300class ChatRequest:"""A validated chat turn, ready to send to DeepSeek."""def __init__(self,personality_id: str,message: Any,history: Any,extras: dict[str, Any] | None = None,):if not personality_id or not isinstance(message, str) or not message.strip():raise HTTPException(status_code=400, detail="personalityId and message are required"7 unmodified linesif not personality:raise HTTPException(status_code=404, detail="Personality not found")extras = extras or {}region = extras.get("region")self.region = region.strip()[:2] if isinstance(region, str) else Nonenotes_in = extras.get("profileNotes")self.profile_notes = (notes_in.strip()[:MAX_PROFILE_CHARS] if isinstance(notes_in, str) else "")steps_in = extras.get("openSteps")self.open_steps = [s.strip()[:MAX_STEP_CHARS]for s in (steps_in if isinstance(steps_in, list) else [])if isinstance(s, str) and s.strip()][:MAX_OPEN_STEPS]self.update_memory = extras.get("updateMemory") is Trueself.personality = personalityself.message = message.strip()self.crisis = safety.is_crisis(self.message)notes = CONTENT.search(personality["id"], self.message)system = system_prompt(personality, notes)context = _user_context(self.profile_notes, self.open_steps)if context:system = f"{system}\n\n{context}"messages: list[dict[str, str]] = [{"role": "system", "content": system}]for item in history if isinstance(history, list) else []:if not isinstance(item, dict):continue18 unmodified linesdef finish(self, reply: str) -> str:if self.crisis:return safety.with_resources(reply or safety.FALLBACK_REPLY, self.region)return replydef resources(self) -> str:return safety.crisis_resources(self.region)def _deepseek_payload(req: ChatRequest, stream: bool) -> dict[str, Any]:return {24 unmodified linesreturn fallbackMEMORY_PROMPT = """You keep short private notes that help a confidence coach remember a user between chats.Update the notes from the latest exchange. Keep what still matters, add lasting facts(their name if they gave it, goals, situations they face, what helps or doesn't, progress),and drop anything outdated. Leave out passing details and anything about self-harm or crisis.Write at most 8 short lines starting with "- ", under 120 words in total.If nothing new is worth keeping, return the current notes unchanged.Return only the notes."""async def update_memory(req: ChatRequest, reply: str, api_key: str) -> str | None:"""Revised profile notes after this exchange, or None if the call fails."""exchange = (f"Current notes:\n{req.profile_notes or '(none yet)'}\n\n"f"Latest exchange:\nUser: {req.message}\nCoach: {reply}")try:async with httpx.AsyncClient(timeout=30.0, transport=HTTP_TRANSPORT) as client:response = await client.post(DEEPSEEK_URL,headers=_headers(api_key),json={"model": MODEL,"messages": [{"role": "system", "content": MEMORY_PROMPT},{"role": "user", "content": exchange},],"temperature": 0.2,"max_tokens": 300,},)data = response.json()except Exception: # noqa: BLE001return Noneif response.status_code >= 400:return Nonenotes = (((data.get("choices") or [{}])[0].get("message") or {}).get("content") or "").strip()return notes[:MAX_PROFILE_CHARS] or Noneasync def deepseek_chat(personality_id: str,message: str,history: list[dict[str, Any]] | None = None,extras: dict[str, Any] | None = None,) -> dict[str, Any]:req = ChatRequest(personality_id, message, history or [], extras)api_key = _require_key()try:21 unmodified linesif not reply and not req.crisis:raise HTTPException(status_code=502, detail="Empty response from DeepSeek")result = {"reply": req.finish(reply),"safety": req.crisis,"personality": req.personality_summary(),}if req.update_memory and not req.crisis:notes = await update_memory(req, reply, api_key)if notes is not None:result["memory"] = notesreturn resultdef _sse(payload: dict[str, Any]) -> str:1 unmodified lineasync def deepseek_stream(req: ChatRequest, api_key: str) -> AsyncIterator[str]:"""Server-sent events: {"delta"}… then optional {"memory"}, then{"done", "safety"} or {"error"}."""got_text = Falseparts: list[str] = []try:async with httpx.AsyncClient(timeout=60.0, transport=HTTP_TRANSPORT) as client:async with client.stream(24 unmodified lines)if delta:got_text = Trueparts.append(delta)yield _sse({"delta": delta})except Exception as exc: # noqa: BLE001if not req.crisis:1 unmodified linereturnif req.crisis:tail = req.resources() if got_text else req.finish("")yield _sse({"delta": ("\n\n" if got_text else "") + tail})elif not got_text:yield _sse({"error": "Empty response from DeepSeek"})returnelif req.update_memory:notes = await update_memory(req, "".join(parts), api_key)if notes is not None:yield _sse({"memory": notes})yield _sse({"done": True, "safety": req.crisis})73 unmodified linespersonality_id=body.get("personalityId", ""),message=body.get("message", ""),history=body.get("history") or [],extras=body,)except HTTPException as exc:return JSONResponse({"error": exc.detail}, status_code=exc.status_code)9 unmodified linesbody.get("personalityId", ""),body.get("message", ""),body.get("history") or [],extras=body,)api_key = _require_key()except HTTPException as exc:
19 unmodified lines20212223242526272829303132333412 unmodified lines474849505119 unmodified lines]_RE = re.compile("|".join(_PATTERNS), re.IGNORECASE)CRISIS_RESOURCES = ("If you're thinking about hurting yourself or you feel unsafe, please reach out ""to someone now:\n""• Emergency: 000\n""• Lifeline (24/7): 13 11 14\n""• Beyond Blue: 1300 22 4636\n""Outside Australia, call your local emergency number.")CRISIS_INSTRUCTION = ("Safety note: the user's latest message may mean they are at risk of harming ""themselves. Put confidence coaching aside. Respond briefly and warmly, take "12 unmodified linesreturn bool(_RE.search(text or ""))def with_resources(reply: str) -> str:return f"{reply.rstrip()}\n\n{CRISIS_RESOURCES}"19 unmodified lines2021222324252627282930313233343536373839404142434445464748495051525354555657585912 unmodified lines727374757619 unmodified lines]_RE = re.compile("|".join(_PATTERNS), re.IGNORECASE)_INTRO = ("If you're thinking about hurting yourself or you feel unsafe, please reach out ""to someone now:\n")# Keyed by ISO country code from the phone's region setting._LINES: dict[str, list[str]] = {"AU": ["Emergency: 000", "Lifeline (24/7): 13 11 14", "Beyond Blue: 1300 22 4636"],"NZ": ["Emergency: 111", "Need to talk? Call or text 1737 (free, 24/7)"],"US": ["Emergency: 911", "988 Suicide & Crisis Lifeline: call or text 988"],"CA": ["Emergency: 911", "Suicide Crisis Helpline: call or text 988"],"GB": ["Emergency: 999", "Samaritans (free, 24/7): 116 123"],"IE": ["Emergency: 112 or 999", "Samaritans (free, 24/7): 116 123"],}_DEFAULT_REGION = "AU"_OTHER = ("Call your local emergency number, or find a free helpline near you at ""findahelpline.com.")def crisis_resources(region: str | None = None) -> str:code = (region or "").strip().upper()if code == "UK":code = "GB"if code and code not in _LINES:return _INTRO + _OTHERlines = _LINES[code or _DEFAULT_REGION]return _INTRO + "\n".join(f"• {line}" for line in lines)# Australian default, kept for callers that don't know the region.CRISIS_RESOURCES = crisis_resources(_DEFAULT_REGION)CRISIS_INSTRUCTION = ("Safety note: the user's latest message may mean they are at risk of harming ""themselves. Put confidence coaching aside. Respond briefly and warmly, take "12 unmodified linesreturn bool(_RE.search(text or ""))def with_resources(reply: str, region: str | None = None) -> str:return f"{reply.rstrip()}\n\n{crisis_resources(region)}"
README.md+8-3
__pycache__/app.cpython-315.pycAdded
app.py+119-14
safety.py+32-7