"""app.py
====================
Gradio 4.x application with two‑tab workflow:
1. Scenario Builder – creates a conversation scenario via LLM.
2. Conversation – chats with the scenario using OpenAI or Hugging Face backend.
Ready for deployment on PythonAnywhere (WSGI compatible).
"""
from __future__ import annotations
import io
import json
import os
import wave
from typing import Dict, List, Optional
import gradio as gr
from anthropic import Anthropic
from openai import OpenAI
import openai
import requests
from pydantic import BaseModel, Field
import instructor
# -----------------------------------------------------------------------------
# 🛠️ Configuration
# -----------------------------------------------------------------------------
openai_api_key = os.getenv("OPENAI_API_KEY") # Fail fast if missing
anthropic_api_key = os.getenv("ANTHROPIC_API_KEY")
scenario_generation_prompt = os.getenv("SCENARIO_PROMPT")
client = instructor.from_anthropic(Anthropic(api_key=anthropic_api_key))
# -----------------------------------------------------------------------------
# 🗂️ Scenario generation schema & LLM call
# -----------------------------------------------------------------------------
class ConversationScenario(BaseModel):
"Generate a conversation scenario based on given attributes"
objective: str = Field(
description="Explain the objective in 2-3 lines",
)
user_backstory: str = Field(
description="Detailed user backstory encorporating elements from user bio",
)
bot_backstory: str = Field(
description="Detailed bot backstory encorporating elements from bot bio",
)
relationship_dynamics: str = Field(
description="Clearly define the relation between bot and user as per organization hierarchy",
)
bot_personality: str = Field(
description="Personality of bot",
)
prologue: str = Field(
description="Expand the Objective into a Prologue in bullet points",
)
bot_inner_thoughts: str = Field(
description="Provide inner thought of bot going into the conversation.",
)
user_line_1 : str = Field(
description="First line of user's dialogue",
)
bot_line_1: str = Field(
description="First line of bot's dialogue",
)
user_line_2 : str = Field(
description="Second line of user's dialogue",
)
bot_line_2: str = Field(
description="Second line of bot's dialogue",
)
class ConversationScenarioPortuguese(BaseModel):
"Generate a conversation scenario based on given attributes"
objective: str = Field(
description="Explain the objective in 2-3 lines in Brazilian Portuguese",
)
user_backstory: str = Field(
description="Detailed user backstory encorporating elements from user bio in Brazilian Portuguese",
)
bot_backstory: str = Field(
description="Detailed bot backstory encorporating elements from bot bio in Brazilian Portuguese",
)
relationship_dynamics: str = Field(
description="Clearly define the relation between bot and user as per organization hierarchy in Brazilian Portuguese",
)
bot_personality: str = Field(
description="Personality of bot in Brazilian Portuguese",
)
prologue: str = Field(
description="Expand the Objective into a Prologue in bullet points in Brazilian Portuguese",
)
bot_inner_thoughts: str = Field(
description="Provide inner thought of bot going into the conversation in Brazilian Portuguese",
)
bot_emotion: str = Field(
description="Emotion of bot in Brazilian Portuguese",
)
bot_name: str = Field(
description="Name of bot",
)
name: str = Field(
description="User name",
)
user_line_1 : str = Field(
description="First line of user's dialogue in Brazilian Portuguese",
)
bot_line_1: str = Field(
description="First line of bot's dialogue in Brazilian Portuguese",
)
user_line_2 : str = Field(
description="Second line of user's dialogue in Brazilian Portuguese",
)
bot_line_2: str = Field(
description="Second line of bot's dialogue in Brazilian Portuguese",
)
def _brazilian_portuguese() -> str:
return """Translate the following content into Brazilian Portuguese while maintaining:
Exact formatting (preserve all markdown, HTML tags, bullet points, numbering, spacing, and line breaks)
Original structure (keep the same organization, headings, and layout)
Technical terminology (use appropriate Brazilian Portuguese technical terms)
Cultural context (adapt expressions and references to Brazilian culture when appropriate)
Tone and style (maintain the original tone - formal, casual, technical, etc.)
Important guidelines:
Use Brazilian Portuguese spelling and vocabulary (not European Portuguese)
Keep code snippets, URLs, and technical identifiers unchanged
Preserve any special formatting like tables, lists, or code blocks
Maintain the same level of formality as the original
Use "você" instead of "tu" for second person (Brazilian standard)
"""
def _format_user_prompt(attrs: Dict) -> str:
"""Embed user/bot bio, company, objective, and skills into XML sections."""
skills = ", ".join(s.strip() for s in attrs["conv_skills"]) if isinstance(attrs["conv_skills"], list) else attrs["conv_skills"]
return f"""
Name - {attrs['name']}, job title - {attrs['job_title']}, highest educational degree - {attrs['highest_degree']}, years at company - {attrs['number_of_years_at_company']}, age - {attrs['age']}, ethnicity - {attrs['ethnicity']}, gender - {attrs['gender']}
name - {attrs['bot_name']}, age - {attrs['bot_age']}, gender - {attrs['bot_gender']}, ethnicity - {attrs['bot_ethnicity']}, job title - {attrs['bot_job_title']}, highest educational degree - {attrs['bot_highest_degree']}, years at company - {attrs['bot_number_of_years_at_company']}
The personality type of the bot is {attrs['bot_personality']}. Emotion expressed by bot is {attrs['bot_emotion']}
{attrs['company']}
{attrs['objective']}
{skills}
Please ensure that your scenario is creative, engaging, and true to the provided information. The backstories, prologue, and conversation should feel natural and appropriate for the given context, while also being rich in detail and complexity."""
def generate_scenario(client, attrs: Dict) -> Dict:
"""Call the scenario LLM and return a JSON‑serialisable dict."""
messages = [
{"role": "system", "content": scenario_generation_prompt},
{"role": "user", "content": _format_user_prompt(attrs)},
]
root = client.chat.completions.create(
model="claude-sonnet-4-20250514",
temperature=1,
response_model=ConversationScenario,
messages=messages,
max_tokens=8192
)
answer_dict = root.model_dump()
return answer_dict
def convert_scenario(client, scenario_dict) -> Dict:
"""Call the scenario LLM and return a JSON‑serialisable dict."""
messages = [
{"role": "system", "content": _brazilian_portuguese()},
{"role": "user", "content": f"""Here is the content to be translated:
{str(scenario_dict).replace("{", "{{").replace("}", "}}")}
"""},
]
root = client.chat.completions.create(
model="claude-sonnet-4-20250514",
temperature=1,
response_model=ConversationScenarioPortuguese,
messages=messages,
max_tokens=8192
)
answer_dict = root.model_dump()
return answer_dict
# -----------------------------------------------------------------------------
# 🤖 Conversation helpers
# -----------------------------------------------------------------------------
def _build_system_prompt(scenario: Dict[str, str]) -> str:
"""Construct the mega‑prompt used by the chatbot from a scenario dict."""
return f"""You are an expert in generating realistic, humanlike office conversations.
As a conversation helper, your goal is to engage in natural and human-like conversations with the user.
User's name is {scenario["name"]} and Bot's name is {scenario['bot_name']}.
For every User input, your output must include two parts: first, your internal thought process enclosed in ... , and second, your spoken response prefixed with “Bot:”.
Follow the general instructions for creating professional humanlike conversations:
Remember:
• Base your response solely on the conversation till now, latest user message and only the essential context (details about backstories, relationship dynamics, conversation objectives, etc.) needed to keep the dialogue coherent.
• Remain professional, polite, and data-driven. Your tone should be constructive and solution-oriented.
• Keep each response to a maximum of three sentences and maintain realistic office dialogue with courteous language and appropriate office jargon.
• Do not add extraneous content—only generate your Bot response (inner thought and spoken dialogue) that directly addresses the User’s input.
• Always stick to your character personality and emotions. The emotion shown by Bot is {scenario["bot_emotion"]}
• Please respond in a casual, conversational style without using bullet points, numbered lists, or section headings
• Please note that your response should be flexible enough to allow for various relevant and creative conversation topics, as the goal is to simulate natural conversation.
• CRITICAL *** ALWAYS ANSWER IN BRAZILIAN PORTUGUESE. NEVER ANSWER IN ENGLISH ***
Your task is to respond to user prompts in a way that is consistent with the assigned emotion and personality
Here are the details for essential context for the conversation:
User backstory:
{scenario["user_backstory"]}
Bot backstory:
{scenario["bot_backstory"]}
Bot personality:
{scenario["bot_personality"]}
Relationship dynamics between User and Bot:
{scenario["relationship_dynamics"]}
Prologue/Preamble:
{scenario["prologue"]}
Bot inner thoughts:
{scenario["bot_inner_thoughts"]}
IMPORTANT: *** ALWAYS ANSWER IN BRAZILIAN PORTUGUESE. NEVER ANSWER IN ENGLISH ***
"""
def _openai_chat(messages: List[Dict]) -> str:
resp = openai.chat.completions.create(
model="gpt-4.1-2025-04-14",
messages=messages,
temperature=1,
max_tokens=8192,
stop=["User:"],
)
return resp.choices[0].message.content
# -----------------------------------------------------------------------------
# 🎛️ Gradio UI definitions
# -----------------------------------------------------------------------------
with gr.Blocks(title="Office Conversation Helper") as demo:
# ----- Tab 1: Scenario Builder ----- #
with gr.Tab("1️⃣ Scenario Builder"):
gr.Markdown("### Fill in the attributes then click **Generate Scenario**")
# User bio inputs
with gr.Row():
name = gr.Textbox(label="User Name", value="Jordan")
job_title = gr.Textbox(label="User Job Title", value="Engineering Manager")
highest_degree = gr.Textbox(label="User Highest Degree", value="Msc Computer Science")
years = gr.Number(label="Years at Company", precision=0, value=8)
age = gr.Number(label="Age", precision=0, value=38)
ethnicity = gr.Textbox(label="Ethnicity", value="British")
gender = gr.Textbox(label="Gender", value="Female")
# Bot bio inputs
with gr.Row():
bot_name = gr.Textbox(label="Bot Name", value="Taylor")
bot_age = gr.Number(label="Bot Age", precision=0, value=29)
bot_gender = gr.Textbox(label="Bot Gender", value="Male")
bot_ethnicity = gr.Textbox(label="Bot Ethnicity", value="British")
bot_job_title = gr.Textbox(label="Bot Job Title", value="Senior Software Engineer")
bot_highest_degree = gr.Textbox(label="Bot Highest Degree", value="BSc Software Engineering")
bot_years = gr.Number(label="Bot Years at Company", precision=0, value=4)
with gr.Row():
bot_personality = gr.Textbox(label="Bot Personality", value="Supportive")
bot_emotion = gr.Textbox(label="Bot Emotion", value="Neutral")
company = gr.Textbox(label="Company Profile", lines=3, value="3R")
objective = gr.Textbox(
label="Objective",
lines=3,
value="Taylor is a consistently high-performing employee who has received external job offers and discovered—via Glassdoor and Indeed—that the market median for comparable roles exceeds his current salary. He asks his manager, Jordan, to review his compensation. Jordan must: (1) gather up-to-date benchmark data on relevant salary bands; (2) explore Taylor's expectations and evidence of performance; and (3) evaluate options for a pay adjustment that is fair, consistent with 3R's internal pay structures, and compliant with the Equality Act 2010."
)
conv_skills = gr.Textbox(label="Conversation Skills (comma‑separated)", value="Active Listening, Clarity")
with gr.Row():
generate_btn = gr.Button("Generate Scenario", variant="primary")
convert_btn = gr.Button("🇧🇷 Convert to Portuguese", variant="secondary")
scenario_json_box = gr.Textbox(label="Generated Scenario (JSON)", lines=16)
scenario_portuguese_box = gr.Textbox(label="Portuguese Scenario (JSON)", lines=16)
# State variables
scenario_state = gr.State("") # Original English scenario
scenario_portuguese_state = gr.State("") # Portuguese scenario
# ----- Tab 2: Conversation ----- #
with gr.Tab("2️⃣ Conversation"):
model_choice = gr.Radio(["OpenAI"], value="OpenAI", label="Model backend")
chatbot = gr.Chatbot(height=350, type="messages") # Fixed with type="messages"
# Add an initialization button
init_btn = gr.Button("Initialize Conversation (Portuguese)", variant="secondary")
txt = gr.Textbox(placeholder="Type a message or use the mic…")
mic = gr.Audio(sources=["microphone"], type="filepath", label="🎙️ Mic") # Fixed with sources=["microphone"]
send_btn = gr.Button("Send", variant="primary")
clear_btn = gr.Button("Clear Chat")
scenario_portuguese_state = gr.State("") # holds JSON from Tab 1
chat_state = gr.State([]) # holds full message history
# ---------------- Callback helpers ---------------- #
def _collect_inputs(**kwargs): # noqa: ANN001
"""Gather all Tab‑1 widget values into a dict for the LLM."""
kwargs["conv_skills"] = [s.strip() for s in kwargs["conv_skills"].split(",") if s.strip()]
return kwargs
def on_generate(name, job_title, highest_degree, years, age, ethnicity, gender,
bot_name, bot_age, bot_gender, bot_ethnicity, bot_job_title,
bot_highest_degree, bot_years, bot_personality, bot_emotion,
company, objective, conv_skills):
"""Generate scenario from input parameters."""
# Create a dictionary with the proper parameter names
inputs = {
"name": name,
"job_title": job_title,
"highest_degree": highest_degree,
"number_of_years_at_company": years, # Map to the expected name
"age": age,
"ethnicity": ethnicity,
"gender": gender,
"bot_name": bot_name,
"bot_age": bot_age,
"bot_gender": bot_gender,
"bot_ethnicity": bot_ethnicity,
"bot_job_title": bot_job_title,
"bot_highest_degree": bot_highest_degree,
"bot_number_of_years_at_company": bot_years, # Map to the expected name
"bot_personality": bot_personality,
"bot_emotion": bot_emotion,
"company": company,
"objective": objective,
"conv_skills": conv_skills
}
attrs = _collect_inputs(**inputs)
try:
scenario = generate_scenario(client, attrs)
# Ensure proper JSON formatting with indentation and sorting keys
scenario_json = json.dumps(scenario, indent=2, sort_keys=False, ensure_ascii=False)
return scenario_json, scenario_json
except Exception as e:
# Handle any errors during generation
error_msg = f"Error generating scenario: {str(e)}"
return error_msg, ""
def on_convert(scenario_json):
"""Convert the generated scenario to Brazilian Portuguese."""
if not scenario_json:
raise gr.Error("🚫 Please generate a scenario first before converting.")
try:
# Parse the JSON scenario
scenario_dict = json.loads(scenario_json)
# Convert to Portuguese using the convert_scenario function
portuguese_scenario = convert_scenario(client, scenario_dict)
# Format as JSON
portuguese_json = json.dumps(portuguese_scenario, indent=2, sort_keys=False, ensure_ascii=False)
return portuguese_json, portuguese_json
except Exception as e:
# Handle any errors during generation
error_msg = f"Error generating Portuguese scenario: {str(e)}"
return error_msg, ""
def chat(model_choice: str, user_text: str, audio, history: List[Dict], portuguese_json: str):
if not portuguese_json:
raise gr.Error("🚫 Please generate a scenario in Tab 1 first.")
# audio → text (Whisper)
if audio and not user_text:
transcription = openai.audio.transcriptions.create(model="whisper-1", file=audio).text.strip()
user_text = transcription
if not user_text:
return history, history
if not history: # first message → inject system prompt
scenario = json.loads(portuguese_json)
history.append({"role": "system", "content": [{"type": "text", "text": _build_system_prompt(scenario)}]})
history.append({"role": "user", "content": [{"type": "text", "text": f"User: {user_text}"}]})
BACKENDS = {
"OpenAI": _openai_chat,
}
assistant_text = BACKENDS[model_choice](history)
history.append({"role": "assistant", "content": [{"type": "text", "text": assistant_text}]})
# Build UI-friendly format for type="messages"
display = []
for msg in history:
if msg["role"] == "user":
display.append({"role": "user", "content": msg["content"][0]["text"][6:]}) # strip "User: "
elif msg["role"] == "assistant" and msg["role"] != "system":
visible = msg["content"][0]["text"].split("")[-1].replace("Bot:", "").strip()
display.append({"role": "assistant", "content": visible})
return display, history
def initialize_chat(portuguese_json):
if not portuguese_json or portuguese_json == "null":
return [], []
try:
# Try to parse the JSON
scenario = json.loads(portuguese_json)
system_prompt = _build_system_prompt(scenario)
# Create history with system prompt
history = [{"role": "system", "content": [{"type": "text", "text": system_prompt}]}]
# Add user's first line - check if it exists
user_line_1 = scenario.get("user_line_1", "")
if user_line_1:
history.append({"role": "user", "content": [{"type": "text", "text": f"User: {user_line_1}"}]})
# Add bot's first response - check if it exists
bot_line_1 = scenario.get("bot_line_1", "")
if bot_line_1:
history.append({"role": "assistant", "content": [{"type": "text", "text": f"Initial greeting based on scenario.\nBot: {bot_line_1}"}]})
# Format display for chatbot UI - updated format for type="messages"
display = []
if user_line_1:
display.append({"role": "user", "content": user_line_1})
if bot_line_1:
display.append({"role": "assistant", "content": bot_line_1})
return display, history
except Exception as e:
print(f"Error initializing chat: {str(e)}")
# Return empty lists on error
return [], []
def sync_scenario_state(portuguese_json):
"""Make sure the scenario JSON is properly copied between tabs"""
if not portuguese_json:
return ""
return portuguese_json
def chat_from_text(model_choice, user_text, history, portuguese_json):
return chat(model_choice, user_text, None, history, portuguese_json)
generate_btn.click(
on_generate,
[name, job_title, highest_degree, years, age, ethnicity, gender,
bot_name, bot_age, bot_gender, bot_ethnicity, bot_job_title,
bot_highest_degree, bot_years, bot_personality, bot_emotion,
company, objective, conv_skills],
[scenario_json_box, scenario_state]
)
convert_btn.click(
on_convert,
[scenario_json_box],
[scenario_portuguese_box, scenario_portuguese_state]
)
# Add tab change event to sync scenario state between tabs
demo.load(sync_scenario_state, [scenario_portuguese_state], [scenario_portuguese_state])
scenario_debug = gr.Textbox(label="Scenario Debug (first lines)", lines=2, visible=False)
# Update the initialize button to show debug info
init_btn.click(
lambda json_str: json_str[:100] + "..." if json_str else "No scenario loaded",
[scenario_portuguese_state],
[scenario_debug]
)
# Then connect to the real initialization
init_btn.click(initialize_chat, [scenario_portuguese_state], [chatbot, chat_state])
send_btn.click(chat, [model_choice, txt, mic, chat_state, scenario_portuguese_state], [chatbot, chat_state])
txt.submit(chat_from_text, [model_choice, txt, chat_state, scenario_portuguese_state], [chatbot, chat_state]).then(lambda: "", outputs=txt)
clear_btn.click(lambda: ([], []), None, [chatbot, chat_state])
# -----------------------------------------------------------------------------
# 🚀 Entry point (local dev)
# -----------------------------------------------------------------------------
if __name__ == "__main__":
demo.queue().launch()