Spaces:
Sleeping
Sleeping
SmallConfidence deploy commited on
Commit ·
793dbf7
1
Parent(s): 79f6bba
Add rehearsal mode
Browse files116 unmodified lines11711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615711 unmodified lines1691701711721731741756 unmodified lines1821831841851861871881891901911921931941951961971981992002012022037 unmodified lines2112122131622142152166 unmodified lines223224225226175227228229230179180231232233234182183184185186235236237238239240241193194242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274116 unmodified lines return "\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 = 300
class ChatRequest:6 unmodified lines history: 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_START
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 lines if 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 None notes_in = extras.get("profileNotes")6 unmodified lines for 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 self.update_memory = extras.get("updateMemory") is True and self.mode != "rehearse"
self.personality = personality self.message = message.strip() self.crisis = safety.is_crisis(self.message) notes = CONTENT.search(personality["id"], self.message) self.crisis = safety.is_crisis(self.message) or ( self.mode != "coach" and safety.is_crisis(self.scenario) )
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}] turns: list[dict[str, str]] = [] for item in history if isinstance(history, list) else []: if not isinstance(item, dict): continue role = 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:] turns.append({"role": role, "content": text}) turns = turns[-MAX_HISTORY:]
in_role = self.mode == "rehearse" and not self.crisis if in_role: system = REHEARSAL_PROMPT.format(scenario=self.scenario) context = _user_context(self.profile_notes, []) else: query = self.message if 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 = messages38 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 lines return uid
def _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 on the Space: it runs only when FIREBASE_AUTH_EMULATOR_HOST is set, as with firebase-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: BLE001 raise AuthError("Your sign-in has expired. Please sign in again.") from exc uid = claims.get("sub") if not isinstance(uid, str) or not uid: raise AuthError("Your sign-in has expired. Please sign in again.") return uid
def bearer_token(header: str | None) -> str: if not header: return ""app.py+87-11
guard.py+31