Spaces:
Sleeping
Sleeping
SmallConfidence deploy commited on
Commit ·
793dbf7
1
Parent(s): 79f6bba
Add rehearsal mode
Browse files116 unmodified lines11711811912012112211 unmodified lines1341351361371381396 unmodified lines1461471481491501517 unmodified lines1591601611621631641656 unmodified lines172173174175176177178179180181182183184185186187188189190191192193194195196197198116 unmodified linesreturn "\n\n".join(parts)def get_personality(personality_id: str) -> dict[str, Any] | None:return PERSONALITIES.get(personality_id)11 unmodified linesMAX_PROFILE_CHARS = 1200MAX_OPEN_STEPS = 3MAX_STEP_CHARS = 300class ChatRequest:6 unmodified lineshistory: 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")6 unmodified linesfor 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):continuerole = item.get("role")text = item.get("content")if role in ("user", "assistant") and isinstance(text, str):messages.append({"role": role, "content": text})messages = messages[:1] + messages[1:][-MAX_HISTORY:]if self.crisis:messages.append({"role": "system", "content": safety.CRISIS_INSTRUCTION})messages.append({"role": "user", "content": self.message})self.messages = messages116 unmodified lines11711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615711 unmodified lines1691701711721731741756 unmodified lines1821831841851861871881891901911921931941951961971981992002012022037 unmodified lines2112122132142152166 unmodified lines223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274116 unmodified linesreturn "\n\n".join(parts)# Rehearsal: the coach plays the other person in a scene the user wants to# practise, then steps out and debriefs.REHEARSAL_PROMPT = """You are helping a user practise a real conversation inside the Jazzii confidence app.Play the other person in this scene, as the user described it:"{scenario}"- Stay in character. Speak only as that person, in the first person, in 1–3 short sentences, like real speech.- Be realistic: hesitant, busy or pushy where that person would be, so the practice is useful. Never be cruel, abusive or sexual, and ease off if the user seems to be struggling.- When the scene starts, open with that person's first line.- Do not coach, give advice, comment on how the user is doing, or add a "Small step:" line. No narration, stage directions or quotation marks.- If the user steps out of the scene to ask for help, give one short encouraging line in brackets, then carry on in character."""REHEARSAL_START = "(The scene starts now. Say your first line.)"FEEDBACK_PROMPT = """The user just practised this conversation, with you playing the other person:"{scenario}"Transcript (User = the user, Them = your role):{transcript}Step out of the role and debrief as their coach. These rules replace "How to respond" above where they differ:- Start with what they did well, pointing to something they actually said.- Then give one thing to try differently next time. You may suggest one short line they could say instead.- End with one "Small step:" line about having this conversation for real or practising it again. Ask no question.Keep it to 2–3 short paragraphs plus the small step."""MODES = ("coach", "rehearse", "rehearse_feedback")def _transcript(history: list[dict[str, str]]) -> str:speaker = {"user": "User", "assistant": "Them"}lines = [f"{speaker[m['role']]}: {m['content']}" for m in history]return "\n".join(lines) or "(no lines yet)"def get_personality(personality_id: str) -> dict[str, Any] | None:return PERSONALITIES.get(personality_id)11 unmodified linesMAX_PROFILE_CHARS = 1200MAX_OPEN_STEPS = 3MAX_STEP_CHARS = 300MAX_SCENARIO_CHARS = 300class ChatRequest:6 unmodified lineshistory: Any,extras: dict[str, Any] | None = None,):extras = extras or {}mode = extras.get("mode")self.mode = mode if mode in MODES else "coach"scenario = extras.get("scenario")self.scenario = (" ".join(scenario.split())[:MAX_SCENARIO_CHARS]if isinstance(scenario, str)else "")if self.mode != "coach" and not self.scenario:raise HTTPException(status_code=400, detail="Describe the scene to rehearse.")# A rehearsal opens with the coach's first line in role, so the app# sends no message for it.if self.mode == "rehearse" and (not isinstance(message, str) or not message.strip()):message = REHEARSAL_STARTif 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")region = extras.get("region")self.region = region.strip()[:2] if isinstance(region, str) else Nonenotes_in = extras.get("profileNotes")6 unmodified linesfor s in (steps_in if isinstance(steps_in, list) else [])if isinstance(s, str) and s.strip()][:MAX_OPEN_STEPS]# In-role lines say nothing true about the user, so they never update memory.self.update_memory = extras.get("updateMemory") is True and self.mode != "rehearse"self.personality = personalityself.message = message.strip()self.crisis = safety.is_crisis(self.message) or (self.mode != "coach" and safety.is_crisis(self.scenario))turns: list[dict[str, str]] = []for item in history if isinstance(history, list) else []:if not isinstance(item, dict):continuerole = item.get("role")text = item.get("content")if role in ("user", "assistant") and isinstance(text, str):turns.append({"role": role, "content": text})turns = turns[-MAX_HISTORY:]in_role = self.mode == "rehearse" and not self.crisisif in_role:system = REHEARSAL_PROMPT.format(scenario=self.scenario)context = _user_context(self.profile_notes, [])else:query = self.messageif self.mode != "coach":query = f"{self.scenario} {self.message}"system = system_prompt(personality, CONTENT.search(personality["id"], query))# Open-step follow-ups belong to normal chats, not rehearsals.steps = self.open_steps if self.mode == "coach" else []context = _user_context(self.profile_notes, steps)if context:system = f"{system}\n\n{context}"if self.mode == "rehearse_feedback":system += "\n\n" + FEEDBACK_PROMPT.format(scenario=self.scenario, transcript=_transcript(turns))turns = []messages: list[dict[str, str]] = [{"role": "system", "content": system}, *turns]if self.crisis:if self.mode == "rehearse":messages.append({"role": "system","content": "You were playing a role in a practice scene. Step out of it now and speak as their coach.",})messages.append({"role": "system", "content": safety.CRISIS_INSTRUCTION})messages.append({"role": "user", "content": self.message})self.messages = messages
38 unmodified lines39404142434413 unmodified lines58596061626338 unmodified lines"""Returns the Firebase uid for a valid ID token, else raises AuthError."""if not token:raise AuthError("Sign in to chat.")try:key = (jwks or _default_jwks()).get_signing_key_from_jwt(token)claims = jwt.decode(13 unmodified linesreturn uiddef bearer_token(header: str | None) -> str:if not header:return ""38 unmodified lines394041424344454613 unmodified lines606162636465666768697071727374757677787980818283848586878889909192939438 unmodified lines"""Returns the Firebase uid for a valid ID token, else raises AuthError."""if not token:raise AuthError("Sign in to chat.")if os.environ.get("FIREBASE_AUTH_EMULATOR_HOST"):return _verify_emulator_token(token, project_id)try:key = (jwks or _default_jwks()).get_signing_key_from_jwt(token)claims = jwt.decode(13 unmodified linesreturn uiddef _verify_emulator_token(token: str, project_id: str) -> str:"""Local Firebase Auth emulator only (`./run.sh --local` in the app).The emulator signs nothing, so only the claims are checked. Never active onthe Space: it runs only when FIREBASE_AUTH_EMULATOR_HOST is set, as withfirebase-admin."""try:claims = jwt.decode(token,options={"verify_signature": False,"verify_exp": True,"verify_aud": True,"verify_iss": True,"require": ["exp", "iat", "sub"],},audience=project_id,issuer=f"https://securetoken.google.com/{project_id}",leeway=30,)except Exception as exc: # noqa: BLE001raise AuthError("Your sign-in has expired. Please sign in again.") from excuid = claims.get("sub")if not isinstance(uid, str) or not uid:raise AuthError("Your sign-in has expired. Please sign in again.")return uiddef bearer_token(header: str | None) -> str:if not header:return ""
app.py+87-11
guard.py+31