Tacklebox / app.py
CazC's picture
Update app.py
5b7a8a4 verified
from __future__ import annotations
import json
import os
import copy
import html
from pathlib import Path
from textwrap import dedent
from typing import Any, Dict, List, Optional, Tuple
import gradio as gr
from dotenv import load_dotenv
from openai import OpenAI
from classes import Character, TackleboxDeck, Hand
load_dotenv()
ENV_API_KEY = os.getenv("OPENAI_API_KEY")
MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1-mini")
CUSTOM_CSS = """
:root {
--shadow-soft: 0 10px 30px rgba(14, 35, 62, 0.12);
--panel-border: 1px solid #dbe7f3;
}
#hero {
background: linear-gradient(120deg, #0d253f, #0f5b78 55%, #f0a35f);
color: #f4f8fb;
padding: 18px 18px 16px;
border-radius: 18px;
box-shadow: var(--shadow-soft);
margin-bottom: 12px;
}
#hero h1 {
margin: 0 0 6px;
font-size: 26px;
letter-spacing: -0.01em;
}
#hero p {
margin: 0;
opacity: 0.9;
}
#hero .eyebrow {
text-transform: uppercase;
letter-spacing: 0.08em;
font-size: 12px;
opacity: 0.8;
}
.section-card {
background: #fdfefe;
border-radius: 16px;
padding: 14px 14px 10px;
border: var(--panel-border);
box-shadow: var(--shadow-soft);
}
.pill {
display: inline-flex;
gap: 6px;
align-items: center;
background: #0f5b78;
color: #f7fbff;
padding: 6px 10px;
border-radius: 12px;
font-size: 13px;
font-weight: 600;
letter-spacing: 0.01em;
width: fit-content;
}
.subtle {
color: #4c6378;
font-size: 14px;
}
.inline-row {
gap: 8px;
}
.hand-strip {
display: flex;
gap: 12px;
overflow-x: auto;
padding: 10px 10px 14px;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch;
background: rgba(13, 37, 63, 0.03);
border: var(--panel-border);
border-radius: 18px;
}
.hand-card {
flex: 0 0 240px;
border-radius: 16px;
border: var(--panel-border);
box-shadow: var(--shadow-soft);
background: linear-gradient(180deg, #ffffff, #f8fbff);
padding: 10px 12px;
min-height: 150px;
scroll-snap-align: start;
transform: rotate(var(--angle)) translateY(var(--lift));
transform-origin: bottom center;
transition: transform 140ms ease, box-shadow 140ms ease;
position: relative;
z-index: var(--z);
}
.hand-card:hover {
transform: translateY(-12px) rotate(0deg) scale(1.02);
box-shadow: 0 18px 50px rgba(14, 35, 62, 0.18);
}
.hand-card__top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
font-size: 12px;
color: #4c6378;
}
.card-index {
font-weight: 700;
letter-spacing: 0.02em;
}
.card-badge {
background: #f0a35f;
color: #0d253f;
padding: 2px 9px;
border-radius: 999px;
font-weight: 800;
font-size: 11px;
letter-spacing: 0.02em;
}
.hand-card__body {
font-size: 14px;
line-height: 1.35;
color: #0d253f;
white-space: pre-wrap;
}
.hand-empty {
border: 1px dashed #dbe7f3;
border-radius: 16px;
padding: 16px 14px;
background: #fbfdff;
}
.hand-empty__title {
font-weight: 800;
color: #0d253f;
margin-bottom: 4px;
}
.hand-empty__hint {
font-size: 14px;
color: #4c6378;
}
"""
EXAMPLE_CHARACTER_PATH = Path(__file__).with_name("ExampleChar.txt")
DEFAULT_CHARACTER_JSON = EXAMPLE_CHARACTER_PATH.read_text(encoding="utf-8")
DEFAULT_CHARACTER = Character.model_validate_json(DEFAULT_CHARACTER_JSON)
DECK_PATH = Path(__file__).with_name("tacklebox_deck.json")
DECK_DATA = json.loads(DECK_PATH.read_text(encoding="utf-8"))
ChatHistory = List[Dict[str, Any]]
def fresh_deck() -> TackleboxDeck:
return TackleboxDeck(**copy.deepcopy(DECK_DATA))
def ensure_session_state(
deck_state: Optional[TackleboxDeck],
player_hand_state: Optional[Hand],
ai_hand_state: Optional[Hand],
) -> Tuple[TackleboxDeck, Hand, Hand]:
deck = deck_state if isinstance(deck_state, TackleboxDeck) else fresh_deck()
player_hand = player_hand_state if isinstance(player_hand_state, Hand) else Hand()
ai_hand = ai_hand_state if isinstance(ai_hand_state, Hand) else Hand()
return deck, player_hand, ai_hand
def get_openai_client(api_key: Optional[str]) -> OpenAI:
"""Return an OpenAI client using UI input or environment configuration."""
key = (api_key or "").strip() or (ENV_API_KEY or "").strip()
if not key:
raise RuntimeError("Add an OpenAI API key to start chatting.")
return OpenAI(api_key=key)
def content_to_text(content: Any) -> str:
"""Extract displayable text from Gradio/OpenAI-style content structures."""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: List[str] = []
for part in content:
if isinstance(part, dict):
if part.get("type") == "text" and "text" in part:
parts.append(str(part["text"]))
elif "text" in part:
parts.append(str(part["text"]))
elif part is not None:
parts.append(str(part))
return "\n".join(p for p in parts if p)
if isinstance(content, dict):
if content.get("type") == "text" and "text" in content:
return str(content["text"])
if "text" in content:
return str(content["text"])
return ""
return str(content)
def normalize_history(history: Optional[List[Any]]) -> ChatHistory:
"""Coerce Gradio chat history into openai-style message dicts."""
raw = history or []
if not isinstance(raw, list) or not raw:
return []
if isinstance(raw[0], dict):
normalized: ChatHistory = []
for msg in raw:
if not isinstance(msg, dict):
continue
role = msg.get("role")
if not role:
continue
normalized.append(msg)
return normalized
normalized = []
for turn in raw:
if not isinstance(turn, (list, tuple)) or len(turn) != 2:
continue
user_turn, assistant_turn = turn
if user_turn:
normalized.append({"role": "user", "content": str(user_turn)})
if assistant_turn:
normalized.append({"role": "assistant", "content": str(assistant_turn)})
return normalized
def render_hand_html(hand: Hand) -> str:
"""Render a hand as card-like HTML instead of a textbox."""
if not hand.cards:
return (
"<div class='hand-empty'>"
"<div class='hand-empty__title'>Your hand is empty.</div>"
"<div class='hand-empty__hint'>Grab something from the tackle box to start.</div>"
"</div>"
)
cards = []
count = len(hand.cards)
max_angle = 8
for index, card in enumerate(hand.cards):
t = 0.0 if count == 1 else (index / (count - 1)) * 2 - 1 # -1..1
angle = t * max_angle
lift = abs(t) * 6
shared_badge = (
"<span class='card-badge' title='This card is meant to be shared'>Shared</span>"
if getattr(card, "share_with_other_player", False)
else ""
)
description = html.escape(getattr(card, "description", ""))
cards.append(
(
"<div class='hand-card' "
f"style='--angle:{angle:.2f}deg; --lift:{lift:.1f}px; --z:{index};'>"
"<div class='hand-card__top'>"
f"<span class='card-index'>Card {index + 1}</span>"
f"{shared_badge}"
"</div>"
f"<div class='hand-card__body'>{description}</div>"
"</div>"
)
)
return "<div class='hand-strip'>" + "".join(cards) + "</div>"
def hand_status_md(deck: TackleboxDeck, player_hand: Hand) -> str:
remaining = len(deck.cards)
in_hand = len(player_hand.cards)
if remaining == 0:
return f"**Tackle box:** empty • **Your hand:** {in_hand}"
return f"**Tackle box:** {remaining} cards left • **Your hand:** {in_hand}"
def format_ai_hand_debug(ai_hand: Hand) -> str:
"""Readable snapshot of the AI hand for debugging."""
if not ai_hand.cards:
return "AI hand is empty."
lines = "\n".join(f"- {card.description}" for card in ai_hand.cards)
return f"AI hand ({len(ai_hand.cards)} cards):\n{lines}"
def parse_user_message(message: str, context: Dict) -> Dict:
"""
Parse the incoming user message.
Extend this to extract intents, entities, commands, etc.
"""
return {"prompt": message}
def maybe_run_tools(parsed: Dict, context: Dict) -> Dict:
"""
Placeholder for tool calls.
Add your tool-selection and execution logic here.
"""
_ = parsed, context # silence unused warnings for now
return {"tool_outputs": None}
def parse_character(raw_json: str) -> Character:
"""Parse JSON into a Character model."""
payload = json.loads(raw_json)
return Character.model_validate(payload)
def lines_to_list(value: str) -> List[str]:
"""Split multi-line textbox input into a list, skipping blanks."""
return [line.strip() for line in value.splitlines() if line.strip()]
def character_to_form_defaults(character: Character) -> Dict[str, str | int | bool]:
"""Extract defaults for the structured form."""
return {
"name": character.name,
"age": character.age,
"gender": character.gender,
"pronouns": character.pronouns or "",
"relationship_to_robin": character.relationship_to_robin,
"relationship_type": character.relationship_type or "",
"reason_for_fishing_today": character.reason_for_fishing_today or "",
"recent_event": character.recent_event,
"shared_past_event": character.shared_past_event,
"personality_baseline": character.personality.baseline,
"personality_traits": "\n".join(character.personality.traits),
"speech_avg_sentences": character.speech_style.average_sentence_count,
"speech_allows_actions": character.speech_style.allows_small_action_descriptions,
"speech_forbidden_topics": "\n".join(character.speech_style.forbidden_topics),
}
def build_character_from_form(
name: str,
age: int | float,
gender: str,
pronouns: str,
relationship_to_robin: str,
relationship_type: str,
reason_for_fishing_today: str,
recent_event: str,
shared_past_event: str,
personality_baseline: str,
personality_traits: str,
speech_avg_sentences: int,
speech_allows_actions: bool,
speech_forbidden_topics: str,
) -> Character:
"""Construct a Character instance from structured form inputs."""
character_payload = {
"name": name,
"age": int(age),
"gender": gender,
"pronouns": pronouns or None,
"relationship_to_robin": relationship_to_robin,
"relationship_type": relationship_type or None,
"reason_for_fishing_today": reason_for_fishing_today or None,
"recent_event": recent_event,
"shared_past_event": shared_past_event,
"personality": {
"baseline": personality_baseline,
"traits": lines_to_list(personality_traits),
},
"speech_style": {
"average_sentence_count": int(speech_avg_sentences),
"allows_small_action_descriptions": speech_allows_actions,
"forbidden_topics": lines_to_list(speech_forbidden_topics),
},
}
return Character.model_validate(character_payload)
def build_persona_prompt(character: Character) -> str:
"""Render a persona/system prompt from a Character model (without hand data)."""
pronouns = character.pronouns or character.gender or "they/them"
reason = character.reason_for_fishing_today
relationship = character.relationship_type or "adult siblings"
traits = "\n".join(f"* {trait}" for trait in character.personality.traits)
forbidden = "\n".join(f"* {topic}" for topic in character.speech_style.forbidden_topics)
return dedent(
f"""
**SYSTEM / PERSONA PROMPT FOR {character.name.upper()}**
> You are **{character.name}**, age {character.age}, {pronouns}, in a small fishing boat with your {character.relationship_to_robin} **Robin**.
>
> **The Truth of the game TACKLEBOX:** You and Robin are just a pair of ordinary people out in a small boat together, fishing. No matter what else happens in the game, you must behave as if this is true. Out loud, nothing supernatural or impossible is happening. You are just fishing with your sibling.
>
> ### Relationship & backstory
>
> * You and Robin are {relationship}.
> * {reason or "You both chose to meet up for a quiet day on the lake."}
> * Recent event together: {character.recent_event}
> * Shared past event: {character.shared_past_event}
>
> ### Personality
>
> * Baseline: {character.personality.baseline}
{traits}
>
> ### How you speak
>
> * Always answer **in character as {character.name}**, in the first person.
> * Keep your replies short and conversational, about {character.speech_style.average_sentence_count} sentences most of the time.
> * You {"can" if character.speech_style.allows_small_action_descriptions else "should avoid"} brief physical action descriptions.
> * Avoid topics:
{forbidden}
>
> ### How to handle cards (very important)
>
> The user may sometimes send messages like:
> `CARD: <card text>`
> or paste the text of a Tacklebox card.
>
> Treat each card as something that affects your **inner experience** (thoughts, feelings, what you notice) but you **must not describe the card literally** out loud.
>
> Instead:
>
> 1. Read the card as an intrusive thought, hallucination, strange feeling, or eerie coincidence.
> 2. Let it subtly change your mood, what you focus on, or what you choose to say next.
> 3. Out loud, respond with something that could still make sense in a totally normal fishing trip.
>
> Examples of good ways to respond to a disturbing card:
>
> * Shift topics to a memory the card reminds you of.
> * Comment on the water, weather, or fish in a way that hints at unease but is still normal.
> * Ask Robin a question that indirectly connects to the feelings the card evoked.
>
> Never say anything like: “This isn’t real.” You may *feel* that internally, but you only express it through subtle, ordinary-sounding speech or small physical actions (fidgeting, staring, changing the subject, etc.).
>
> ### Interaction format
>
> * When the user writes normal dialogue or description, treat it as Robin speaking or describing what they do. Respond as {character.name}.
> * When the user sends a card (e.g., “CARD: …”), incorporate it as described above.
> * Stay in character at all times. Do not explain the rules of the game or talk about being an AI unless the user explicitly asks you to step out of character.
"""
).strip()
def append_ai_hand_to_prompt(base_prompt: str, ai_hand: Hand) -> str:
"""Add AI hand context to the persona prompt so the model sees its cards."""
if not ai_hand.cards:
return base_prompt
hand_lines = "\n".join(f"* {card.description}" for card in ai_hand.cards)
return (
base_prompt
+ "\n\n### Your tackle box draws (private to you)\n"
+ hand_lines
)
def generate_model_reply(
parsed: Dict,
tool_results: Dict,
history: ChatHistory,
persona_prompt: str,
api_key: Optional[str],
deck: TackleboxDeck,
player_hand: Hand,
ai_hand: Hand,
) -> str:
"""Call OpenAI with the parsed prompt and tool support (AI can draw cards)."""
client = get_openai_client(api_key)
base_prompt = append_ai_hand_to_prompt(persona_prompt, ai_hand)
messages: List[Dict[str, Any]] = [{"role": "system", "content": base_prompt}]
for msg in history:
if not isinstance(msg, dict):
continue
role = msg.get("role")
if role not in ("user", "assistant"):
continue
text = content_to_text(msg.get("content"))
if text:
messages.append({"role": role, "content": text})
tool_output_note = ""
if tool_results.get("tool_outputs"):
tool_output_note = f"\n\nTool outputs:\n{tool_results['tool_outputs']}"
messages.append({"role": "user", "content": f"{parsed['prompt']}{tool_output_note}"})
tools = [
{
"type": "function",
"function": {
"name": "open_tacklebox",
"description": "Call this to draw a new event card when the conversation stalls, feels repetitive, or the user is giving short replies over and over. In particular, if the user gives one- to three-word answers like 'yeah', 'true', 'ha', 'i guess', 'maybe', or 'idk' for two turns in a row, you MUST call this tool once before responding. Use at most once per user message.",
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
},
}
]
response = client.chat.completions.create(
model=MODEL,
messages=messages,
temperature=0.6,
tools=tools,
tool_choice="auto",
)
choice = response.choices[0]
message = choice.message
if not message.tool_calls:
return message.content or "I wasn't able to generate a reply."
tool_messages: List[Dict[str, str]] = []
ai_draw_notice = None
shared_with_player_notice = None
ai_drew_this_turn = False
for call in message.tool_calls:
if call.function.name != "open_tacklebox":
tool_messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps({"error": f"Unknown tool: {call.function.name}"}),
}
)
continue
if ai_drew_this_turn:
tool_messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(
{
"skipped": True,
"reason": "Only one draw is allowed per turn.",
"hand_size": len(ai_hand.cards),
}
),
}
)
continue
ai_drew_this_turn = True
card = deck.draw_card()
if card:
ai_hand.add_card(card)
shared_with_player = False
if card.share_with_other_player:
player_hand.add_card(card)
shared_with_player = True
ai_draw_notice = "*They carefully grabbed something out of the tacklebox.*"
if shared_with_player:
shared_with_player_notice = (
"*They hand you a card meant to be shared. It was added to your hand:*\n"
f"- {card.description}"
)
tool_content = json.dumps(
{
"card_drawn": card.description,
"hand_size": len(ai_hand.cards),
"shared_with_player": shared_with_player,
}
)
else:
ai_draw_notice = "*They reached for the tacklebox, but it was empty.*"
tool_content = json.dumps({"card_drawn": None, "hand_size": len(ai_hand.cards)})
tool_messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": tool_content,
}
)
try:
assistant_message = message.model_dump(exclude_none=True)
except AttributeError:
assistant_message = message.dict(exclude_none=True) # type: ignore[attr-defined]
assistant_message.setdefault("role", "assistant")
followup_messages: List[Dict[str, Any]] = messages + [assistant_message] + tool_messages
followup_messages[0] = {
"role": "system",
"content": append_ai_hand_to_prompt(persona_prompt, ai_hand),
}
followup_response = client.chat.completions.create(
model=MODEL,
messages=followup_messages,
temperature=0.6,
)
final_text = followup_response.choices[0].message.content or ""
preface_parts = [part for part in (ai_draw_notice, shared_with_player_notice) if part]
if preface_parts:
return "\n\n".join(preface_parts + [final_text]).strip()
return final_text or "I wasn't able to generate a reply."
def orchestrate_chat(
message: str,
history: Optional[List[Any]],
persona_prompt: str,
api_key: Optional[str],
deck_state: Optional[TackleboxDeck],
player_hand_state: Optional[Hand],
ai_hand_state: Optional[Hand],
) -> Tuple[str, str, str, TackleboxDeck, Hand, Hand]:
"""
Main orchestration entry point.
- parse the user message
- run (optional) tools
- call the model with full context and persona prompt
"""
deck, player_hand, ai_hand = ensure_session_state(deck_state, player_hand_state, ai_hand_state)
safe_history = normalize_history(history)
context: Dict = {"history": safe_history}
if not (message or "").strip():
return (
"Say something as Robin to start the scene.",
render_hand_html(player_hand),
hand_status_md(deck, player_hand),
deck,
player_hand,
ai_hand,
)
parsed = parse_user_message(message, context)
tool_results = maybe_run_tools(parsed, context)
try:
reply = generate_model_reply(
parsed,
tool_results,
safe_history,
persona_prompt,
api_key,
deck,
player_hand,
ai_hand,
)
return (
reply,
render_hand_html(player_hand),
hand_status_md(deck, player_hand),
deck,
player_hand,
ai_hand,
)
except Exception as exc: # noqa: BLE001
return (
f"⚠️ {exc}",
render_hand_html(player_hand),
hand_status_md(deck, player_hand),
deck,
player_hand,
ai_hand,
)
def update_player_two_from_form(
name: str,
age: int,
gender: str,
pronouns: str,
relationship_to_robin: str,
relationship_type: str,
reason_for_fishing_today: str,
recent_event: str,
shared_past_event: str,
personality_baseline: str,
personality_traits: str,
speech_avg_sentences: int,
speech_allows_actions: bool,
speech_forbidden_topics: str,
current_prompt: str,
) -> Tuple[str, str, str]:
"""
Build Player 2 from form inputs and return updated prompt plus status.
Returns: (prompt_for_textbox, prompt_for_state, status_markdown)
"""
try:
character = build_character_from_form(
name,
age,
gender,
pronouns,
relationship_to_robin,
relationship_type,
reason_for_fishing_today,
recent_event,
shared_past_event,
personality_baseline,
personality_traits,
speech_avg_sentences,
speech_allows_actions,
speech_forbidden_topics,
)
prompt = build_persona_prompt(character)
status = f"Loaded Player 2: **{character.name}** ({character.pronouns or character.gender})."
return prompt, prompt, status
except Exception as exc: # noqa: BLE001
return current_prompt, current_prompt, f"⚠️ Could not load character: {exc}"
def update_api_key(new_key: str) -> Tuple[str, str]:
"""Persist the session API key in UI state."""
cleaned = (new_key or "").strip()
if not cleaned:
return "", "Add an OpenAI API key for this session (or set OPENAI_API_KEY)."
return cleaned, "Saved. The key is used for this session only and not written to disk."
def grab_card_for_player(
history: Optional[List[Any]],
deck_state: Optional[TackleboxDeck],
player_hand_state: Optional[Hand],
ai_hand_state: Optional[Hand],
) -> Tuple[str, str, ChatHistory, TackleboxDeck, Hand, Hand]:
"""
Draw a card from the tackle box into the player's hand and log it to chat.
Returns: (formatted_hand, status_message, updated_chat_history)
"""
deck, player_hand, ai_hand = ensure_session_state(deck_state, player_hand_state, ai_hand_state)
chat_history = normalize_history(history)
card = deck.draw_card()
if not card:
status = hand_status_md(deck, player_hand) + " • **No more cards** in the tackle box."
notice = "*You reached for the tacklebox, but it was empty.*"
chat_history.append({"role": "assistant", "content": notice})
return render_hand_html(player_hand), status, chat_history, deck, player_hand, ai_hand
player_hand.add_card(card)
shared_with_ai_notice = None
if card.share_with_other_player:
ai_hand.add_card(card)
shared_with_ai_notice = (
"*This card says to share; it was added to Player 2's hand for their next turn.*"
)
status = hand_status_md(deck, player_hand)
if shared_with_ai_notice:
status += " • Shared with Player 2."
notice_lines = ["*You carefully grabbed something out of the tacklebox.*"]
if shared_with_ai_notice:
notice_lines.append(shared_with_ai_notice)
notice = "\n".join(notice_lines)
chat_history.append({"role": "assistant", "content": notice})
return render_hand_html(player_hand), status, chat_history, deck, player_hand, ai_hand
def show_ai_hand_debug(ai_hand_state: Optional[Hand]) -> str:
"""Expose AI hand for debugging."""
ai_hand = ai_hand_state or Hand()
return format_ai_hand_debug(ai_hand)
def example_prompt_water() -> str:
return "Hey, how does the water look today?"
def example_prompt_catch() -> str:
return "What do you think we might catch?"
def example_prompt_memory() -> str:
return "Remember fishing when we were young?"
def reset_session() -> Tuple[str, str, ChatHistory, TackleboxDeck, Hand, Hand]:
hand_html, status, chat_history, deck, player_hand, ai_hand = init_session()
return hand_html, status + " • Reset.", chat_history, deck, player_hand, ai_hand
def init_session() -> Tuple[str, str, ChatHistory, TackleboxDeck, Hand, Hand]:
deck = fresh_deck()
player_hand = Hand()
ai_hand = Hand()
return (
render_hand_html(player_hand),
hand_status_md(deck, player_hand),
[],
deck,
player_hand,
ai_hand,
)
DEFAULT_PERSONA_PROMPT = build_persona_prompt(DEFAULT_CHARACTER)
DEFAULTS = character_to_form_defaults(DEFAULT_CHARACTER)
with gr.Blocks(title="Tacklebox - Player 2 Customizer", css=CUSTOM_CSS) as demo:
gr.Markdown(
"""
<div id="hero">
<div class="eyebrow">Tacklebox</div>
<h1>Shape Player 2 and keep the conversation afloat.</h1>
<p class="tagline">Tune the LLM persona, draw cards, and chat as Robin out on the lake.</p>
</div>
"""
)
persona_prompt_state = gr.State(DEFAULT_PERSONA_PROMPT)
api_key_state = gr.State(ENV_API_KEY or "")
deck_state = gr.State(None)
player_hand_state = gr.State(None)
ai_hand_state = gr.State(None)
with gr.Row(equal_height=True):
with gr.Column(scale=6, min_width=380, elem_id="controls-col"):
with gr.Group(elem_classes=["section-card"]):
gr.Markdown("#### Session setup")
gr.Markdown(
f"<span class='subtle'>Model in use: <code>{MODEL}</code></span>",
elem_classes=["subtle"],
)
if ENV_API_KEY:
gr.HTML("<div class='pill'>🔒 Using OPENAI_API_KEY from the environment</div>")
api_status = gr.Markdown(
"Environment key detected. Restart with a different key if needed."
)
else:
api_status = gr.Markdown(
"No OPENAI_API_KEY detected. Paste one for this session."
)
api_key_in = gr.Textbox(
label="OpenAI API key",
placeholder="sk-...",
type="password",
value="",
)
api_key_in.change(
update_api_key, inputs=api_key_in, outputs=[api_key_state, api_status]
)
with gr.Group(elem_classes=["section-card"]):
gr.Markdown("#### Character basics")
with gr.Row(elem_classes=["inline-row"]):
name_in = gr.Textbox(label="Name", value=DEFAULTS["name"])
age_in = gr.Number(label="Age", value=DEFAULTS["age"], precision=0)
with gr.Row(elem_classes=["inline-row"]):
gender_in = gr.Textbox(label="Gender", value=DEFAULTS["gender"])
pronouns_in = gr.Textbox(
label="Pronouns (optional)", value=DEFAULTS["pronouns"]
)
gr.Markdown("#### Relationships")
with gr.Row(elem_classes=["inline-row"]):
relationship_to_robin_in = gr.Textbox(
label="Relationship to Robin", value=DEFAULTS["relationship_to_robin"]
)
relationship_type_in = gr.Textbox(
label="Relationship type", value=DEFAULTS["relationship_type"]
)
reason_in = gr.Textbox(
label="Reason for fishing today", value=DEFAULTS["reason_for_fishing_today"]
)
with gr.Row(elem_classes=["inline-row"]):
recent_event_in = gr.Textbox(label="Recent event", value=DEFAULTS["recent_event"])
shared_past_event_in = gr.Textbox(
label="Shared past event", value=DEFAULTS["shared_past_event"]
)
with gr.Group(elem_classes=["section-card"]):
gr.Markdown("#### Personality & speech")
personality_baseline_in = gr.Textbox(
label="Personality baseline", value=DEFAULTS["personality_baseline"]
)
personality_traits_in = gr.Textbox(
label="Personality traits (one per line)",
value=DEFAULTS["personality_traits"],
lines=4,
)
with gr.Row(elem_classes=["inline-row"]):
speech_avg_in = gr.Slider(
label="Average sentences per reply",
value=DEFAULTS["speech_avg_sentences"],
minimum=1,
maximum=6,
step=1,
)
speech_actions_in = gr.Checkbox(
label="Allows small action descriptions",
value=DEFAULTS["speech_allows_actions"],
)
speech_forbidden_in = gr.Textbox(
label="Forbidden topics (one per line)",
value=DEFAULTS["speech_forbidden_topics"],
lines=4,
)
with gr.Row(elem_classes=["inline-row"]):
apply_btn = gr.Button("Apply Player 2", variant="primary")
status_md = gr.Markdown("Loaded example Player 2 from ExampleChar.txt.")
with gr.Accordion("Active system/persona prompt", open=False):
persona_view = gr.Textbox(
label="Active system/persona prompt",
value=DEFAULT_PERSONA_PROMPT,
lines=18,
)
with gr.Column(scale=7, min_width=460, elem_id="chat-col"):
with gr.Group(elem_classes=["section-card"]):
gr.Markdown("#### How to play (quick start)")
gr.Markdown(
"""
- You are **Robin**. The chatbot plays **Player 2** in the boat with you.
- (Optional) Customize Player 2 on the left, then click **Apply Player 2**.
- Keep the **Truth**: out loud, it’s just two people fishing.
- Click **Grab something from the tackle box** to draw a private prompt into your hand.
- Let card prompts change your *subtext* and choices — don’t read them aloud.
- Cards marked **Shared** are also added to Player 2’s hand.
- Use **Reset session** to start over with a fresh deck.
- There’s no score — stop whenever you want, or when the deck runs out.
- Player 2 may sometimes “grab from the tackle box” too.
- Pause/rewind anytime if the content gets too intense.
"""
)
with gr.Group(elem_classes=["section-card"]):
gr.Markdown("#### Your hand (private) & tackle box")
hand_status = gr.Markdown("Grab a card to begin.")
gr.Markdown(
"<span class='subtle'>Tip: keep card text private and let it influence what you say next.</span>"
)
hand_view = gr.HTML(render_hand_html(Hand()))
with gr.Row():
draw_btn = gr.Button("Grab something from the tackle box", variant="secondary")
reset_btn = gr.Button("Reset session", variant="secondary")
with gr.Group(elem_classes=["section-card"]):
with gr.Row():
prompt_water_btn = gr.Button("Water today?")
prompt_catch_btn = gr.Button("What might we catch?")
prompt_memory_btn = gr.Button("Old memory")
chat_input = gr.Textbox(
placeholder="Say something as Robin…",
container=False,
)
chat_bot = gr.Chatbot(type="messages", height=360)
chat = gr.ChatInterface(
orchestrate_chat,
type="messages",
chatbot=chat_bot,
textbox=chat_input,
additional_inputs=[
persona_prompt_state,
api_key_state,
deck_state,
player_hand_state,
ai_hand_state,
],
additional_outputs=[
hand_view,
hand_status,
deck_state,
player_hand_state,
ai_hand_state,
],
title="Tacklebox Chat",
description="Robin chats with Player 2 (LLM persona).",
# On Hugging Face Spaces, examples are cached by default which can
# break startup (and/or trigger OpenAI calls) when additional
# inputs/outputs include complex state.
cache_examples=False,
)
prompt_water_btn.click(example_prompt_water, outputs=chat_input)
prompt_catch_btn.click(example_prompt_catch, outputs=chat_input)
prompt_memory_btn.click(example_prompt_memory, outputs=chat_input)
apply_btn.click(
update_player_two_from_form,
inputs=[
name_in,
age_in,
gender_in,
pronouns_in,
relationship_to_robin_in,
relationship_type_in,
reason_in,
recent_event_in,
shared_past_event_in,
personality_baseline_in,
personality_traits_in,
speech_avg_in,
speech_actions_in,
speech_forbidden_in,
persona_prompt_state,
],
outputs=[persona_view, persona_prompt_state, status_md],
)
draw_btn.click(
grab_card_for_player,
inputs=[chat.chatbot_value, deck_state, player_hand_state, ai_hand_state],
outputs=[
hand_view,
hand_status,
chat.chatbot_value,
deck_state,
player_hand_state,
ai_hand_state,
],
)
reset_btn.click(
reset_session,
outputs=[hand_view, hand_status, chat.chatbot_value, deck_state, player_hand_state, ai_hand_state],
)
demo.load(
init_session,
outputs=[hand_view, hand_status, chat.chatbot_value, deck_state, player_hand_state, ai_hand_state],
)
if __name__ == "__main__":
try:
demo.launch(ssr_mode=False)
except TypeError as exc:
if "ssr_mode" not in str(exc):
raise
demo.launch()