File size: 17,991 Bytes
2129942
 
 
 
 
 
c37e7d2
 
3fa45ef
2c30381
bb24fdd
3fa45ef
9d6bce3
0d8e8db
9d6bce3
aaa5822
c37e7d2
aaa5822
 
bd56ca5
 
 
 
389bf98
af6d7ef
 
 
 
 
e7c03d2
2129942
9c71d08
249b762
9c71d08
 
6b20b2f
 
 
2c30381
 
 
 
3fa45ef
 
b310153
0d8e8db
2129942
8483e68
9b5540f
 
 
 
 
 
8483e68
e7c03d2
 
 
 
276be42
 
 
 
9966912
2129942
 
224585b
 
 
 
 
 
 
2129942
c37e7d2
8483e68
c37e7d2
8483e68
af6d7ef
 
 
5fe3c5f
af6d7ef
9966912
8483e68
 
 
 
 
 
 
9b5540f
8483e68
9b5540f
8483e68
9b5540f
8483e68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c37e7d2
 
 
196658e
c37e7d2
 
 
 
 
 
 
 
 
 
 
8483e68
c37e7d2
8483e68
 
 
 
 
 
 
 
c37e7d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8483e68
 
c37e7d2
8483e68
 
 
 
 
 
 
c37e7d2
aaa5822
 
 
9b5540f
9966912
2129942
8483e68
 
 
 
c37e7d2
8483e68
 
 
 
 
 
 
 
aaa5822
 
 
9b5540f
8483e68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2129942
9966912
 
 
2129942
c37e7d2
9966912
 
 
c61132d
9b5540f
276be42
9b5540f
 
9d6bce3
8483e68
 
 
 
 
 
c37e7d2
8483e68
 
 
 
 
 
 
 
9b5540f
 
8483e68
 
 
 
 
 
 
 
 
c37e7d2
8483e68
 
 
 
 
 
 
 
9b5540f
 
8483e68
 
 
 
bf92151
 
22695c6
 
c37e7d2
22695c6
 
 
8483e68
 
 
 
 
 
 
 
 
 
 
 
 
bf92151
 
 
22695c6
 
c37e7d2
22695c6
 
 
8483e68
 
 
 
 
 
 
 
 
 
 
 
 
9966912
 
5fe3c5f
e7c03d2
9966912
 
 
 
 
 
 
 
 
 
 
 
389bf98
 
 
 
 
 
 
 
 
 
 
 
 
 
abe8a34
 
 
 
 
 
 
 
ea5a5fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89e110a
781ecb0
89e110a
781ecb0
89e110a
 
 
 
 
dc9acf2
781ecb0
 
c61132d
2129942
9966912
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import os
import sys

# Add src directory to Python path for Hugging Face Spaces compatibility
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))

import ast
import json
import logging
import warnings
from pathlib import Path

import gradio as gr
import spaces

from unpredictable_lord.chat.chat import chat_with_mcp_tools
from unpredictable_lord.chat.mcp_client import MCPClient
from unpredictable_lord.mcp_server.game_state import PERSONALITY_DESCRIPTIONS
from unpredictable_lord.mcp_server.mcp_server import (
    execute_turn,
    get_game_state,
    init_game,
    list_available_advice,
)
from unpredictable_lord.settings import (
    ENABLE_CHAT,
    ENABLE_GRADIO_DEPRECATION_WARNING,
    LOGGING_LEVEL,
)
from unpredictable_lord.utils import get_tool_prefix, update_guide_with_tool_prefix

# Configure logging level from environment variable
log_level = getattr(logging, LOGGING_LEVEL, logging.INFO)
logging.basicConfig(level=log_level, format="%(asctime)s %(levelname)s %(message)s")

# Suppress HTTP request logs from httpx
logging.getLogger("httpx").setLevel(logging.WARNING)

# Suppress Gradio DeprecationWarnings
if not ENABLE_GRADIO_DEPRECATION_WARNING:
    warnings.filterwarnings("ignore", category=DeprecationWarning, message=".*Gradio.*")

logger = logging.getLogger(__name__)

logger.info(f"Gradio version: {gr.__version__}")
logger.info(f"ZeroGPU: {spaces.config.Config.zero_gpu}")

# Constants
NO_GAME_MESSAGE = """_No active game._

**To start playing:**
1. Select a Lord Personality above
2. Click "โš”๏ธ Start New Game"
"""

# Load MCP guide from external file
MCP_GUIDE_PATH = Path(__file__).parent / "docs" / "mcp_guide.md"
MCP_GUIDE_TEMPLATE = MCP_GUIDE_PATH.read_text(encoding="utf-8")

# MCP tool prefix for HF Spaces
tool_prefix = get_tool_prefix()
logger.info(f"Using tool prefix: '{tool_prefix}'")


# Gradio UI
with gr.Blocks(title="Unpredictable Lord") as demo:
    gr.Markdown(
        "# Unpredictable Lord\n\n"
        "**Lord Advisor AI Simulation** ๐Ÿฐ๐ŸŽฎ<br>"
        "๐ŸŽฏ **Overview:** A turn-based advisor game where players propose policies and counsel a lord AI. ๐Ÿค<br>"
        "โš–๏ธ Decisions depend on lord personality, advisor trust, and current state โ€” affecting resources, population, and morale. ๐Ÿ“ˆ๐Ÿ“‰<br>"
        "๐Ÿ† Win by expanding territory, earning royal favor, or growing wealth; โš ๏ธ beware rebellion, exile, or bankruptcy. ๐Ÿ’€๐Ÿ‘‘๐Ÿ’ฐ"
    )

    # State to store current session_id and system_instructions for Chat tab
    chat_session_id = gr.State(value=None)
    chat_system_instructions = gr.State(value="")

    SELECTED_TAB = "chat" if ENABLE_CHAT else "mcp_server"

    with gr.Tabs(selected=SELECTED_TAB):
        # Chat Tab (hidden - not ready for release)
        with gr.TabItem("Chat", id="chat", visible=ENABLE_CHAT):
            with gr.Row():
                # Left column: Chat interface
                with gr.Column(scale=3):
                    chatbot = gr.Chatbot(label="Lord AI", height=500, type="messages")

                    with gr.Row():
                        msg = gr.Textbox(
                            label="Your Advice",
                            placeholder="Start a new game first...",
                            scale=4,
                            interactive=False,
                        )
                        submit_btn = gr.Button("Submit", scale=1, interactive=False)

                # Right column: Game status panel
                with gr.Column(scale=1):
                    gr.Markdown("### ๐ŸŽฎ Game Status")

                    # Game control buttons
                    with gr.Group():
                        chat_personality = gr.Dropdown(
                            choices=["cautious", "idealist", "populist"],
                            value="cautious",
                            label="Lord Personality",
                        )
                        start_game_btn = gr.Button(
                            "โš”๏ธ Start New Game", variant="primary"
                        )
                        reset_game_btn = gr.Button("๐Ÿ”„ Reset Game", variant="secondary")

                    # Status display
                    game_status_md = gr.Markdown(value=NO_GAME_MESSAGE)

                    # Parameter bars
                    with gr.Group():
                        territory_bar = gr.Slider(
                            label="๐Ÿฐ Territory",
                            minimum=0,
                            maximum=100,
                            value=50,
                            interactive=False,
                        )
                        population_bar = gr.Slider(
                            label="๐Ÿ‘ฅ Population",
                            minimum=0,
                            maximum=100,
                            value=50,
                            interactive=False,
                        )
                        treasury_bar = gr.Slider(
                            label="๐Ÿ’ฐ Treasury",
                            minimum=0,
                            maximum=100,
                            value=50,
                            interactive=False,
                        )
                        satisfaction_bar = gr.Slider(
                            label="๐Ÿ˜Š Satisfaction",
                            minimum=0,
                            maximum=100,
                            value=50,
                            interactive=False,
                        )
                        royal_trust_bar = gr.Slider(
                            label="๐Ÿ‘‘ Royal Trust",
                            minimum=0,
                            maximum=100,
                            value=50,
                            interactive=False,
                        )
                        advisor_trust_bar = gr.Slider(
                            label="๐Ÿค Advisor Trust",
                            minimum=0,
                            maximum=100,
                            value=50,
                            interactive=False,
                        )

            # Helper functions for Chat tab
            async def start_chat_game(personality: str):
                """Start a new game via MCP client and return updated UI state."""
                # Call init_game via MCP client
                mcp_client = MCPClient(tool_prefix=tool_prefix)
                result_json = await mcp_client.call_tool(
                    "init_game", {"personality": personality}
                )

                # Parse result - MCP may return JSON or Python dict repr
                try:
                    result = json.loads(result_json)
                except json.JSONDecodeError:
                    # Gradio MCP sometimes returns Python dict repr (single quotes)
                    result = ast.literal_eval(result_json)

                session_id = result.get("session_id", "")
                system_instructions = result.get("system_instructions", "")
                state = result.get("initial_state", {})
                personality_name = personality.capitalize()
                personality_desc = PERSONALITY_DESCRIPTIONS.get(personality, "")

                status_md = f"""**Turn:** {state.get("turn", 1)} | **Lord:** {personality_name}

_{personality_desc}_"""

                # Build initial chat message with game context (collapsible)
                initial_state_text = f"""**Session ID:** {session_id}
**Personality:** {personality_name}

**Initial State:**
- Territory: {state.get("territory", 50)}
- Population: {state.get("population", 50)}
- Treasury: {state.get("treasury", 50)}
- Satisfaction: {state.get("satisfaction", 50)}
- Royal Trust: {state.get("royal_trust", 50)}
- Advisor Trust: {state.get("advisor_trust", 50)}

{system_instructions}
"""
                initial_history = [
                    gr.ChatMessage(
                        role="user",
                        content=initial_state_text,
                        metadata={"title": "๐ŸŽฎ Game Initialized", "status": "done"},
                    )
                ]

                return (
                    session_id,
                    system_instructions,
                    status_md,
                    state.get("territory", 50),
                    state.get("population", 50),
                    state.get("treasury", 50),
                    state.get("satisfaction", 50),
                    state.get("royal_trust", 50),
                    state.get("advisor_trust", 50),
                    initial_history,
                    gr.update(
                        interactive=True, placeholder="My Lord, I have a proposal..."
                    ),
                    gr.update(interactive=True),
                )

            def reset_chat_game():
                """Reset game state to initial values."""
                return (
                    None,  # session_id
                    "",  # system_instructions
                    NO_GAME_MESSAGE,
                    50,
                    50,
                    50,
                    50,
                    50,
                    50,
                    [],  # Clear chat history
                    gr.update(
                        interactive=False, placeholder="Start a new game first..."
                    ),
                    gr.update(interactive=False),
                )

            def refresh_game_state(session_id: str | None):
                """Refresh the game state display."""
                if not session_id:
                    return (
                        NO_GAME_MESSAGE,
                        50,
                        50,
                        50,
                        50,
                        50,
                        50,
                    )

                result = get_game_state(session_id)
                if "error" in result:
                    return (
                        f"_Error: {result['error']}_",
                        50,
                        50,
                        50,
                        50,
                        50,
                        50,
                    )

                state = result.get("state", {})
                personality = state.get("lord_personality", "unknown").capitalize()
                turn = state.get("turn", 1)
                game_over = state.get("game_over", False)
                game_result = state.get("result")

                if game_over and game_result:
                    result_messages = {
                        "victory_territory": "๐ŸŽ‰ **VICTORY!** You achieved territorial dominance!",
                        "victory_trust": "๐ŸŽ‰ **VICTORY!** You became a trusted co-ruler!",
                        "victory_wealth": "๐ŸŽ‰ **VICTORY!** You achieved great wealth!",
                        "defeat_rebellion": "๐Ÿ’€ **DEFEAT!** A rebellion overthrew the lord...",
                        "defeat_exile": "๐Ÿ’€ **DEFEAT!** Exiled from the kingdom...",
                        "defeat_bankruptcy": "๐Ÿ’€ **DEFEAT!** The realm fell to bankruptcy...",
                    }
                    status_md = f"""**Turn:** {turn} | **Lord:** {personality}

{result_messages.get(game_result, f"Game Over: {game_result}")}"""
                else:
                    status_md = f"**Turn:** {turn} | **Lord:** {personality}"

                return (
                    status_md,
                    state.get("territory", 50),
                    state.get("population", 50),
                    state.get("treasury", 50),
                    state.get("satisfaction", 50),
                    state.get("royal_trust", 50),
                    state.get("advisor_trust", 50),
                )

            def user(user_message, history):
                # Append user message to history in messages format
                return "", history + [{"role": "user", "content": user_message}]

            async def bot(history, system_instructions):
                # The last message is the user's message
                user_message = history[-1]["content"]
                history_for_model = history[:-1]

                async for updated_history in chat_with_mcp_tools(
                    user_message, history_for_model, system_instructions, tool_prefix
                ):
                    yield updated_history

            # Event handlers
            start_game_btn.click(
                fn=start_chat_game,
                inputs=chat_personality,
                outputs=[
                    chat_session_id,
                    chat_system_instructions,
                    game_status_md,
                    territory_bar,
                    population_bar,
                    treasury_bar,
                    satisfaction_bar,
                    royal_trust_bar,
                    advisor_trust_bar,
                    chatbot,
                    msg,
                    submit_btn,
                ],
                show_api=False,
            )

            reset_game_btn.click(
                fn=reset_chat_game,
                inputs=[],
                outputs=[
                    chat_session_id,
                    chat_system_instructions,
                    game_status_md,
                    territory_bar,
                    population_bar,
                    treasury_bar,
                    satisfaction_bar,
                    royal_trust_bar,
                    advisor_trust_bar,
                    chatbot,
                    msg,
                    submit_btn,
                ],
                show_api=False,
            )

            msg.submit(
                user, [msg, chatbot], [msg, chatbot], queue=False, show_api=False
            ).then(
                bot,
                [chatbot, chat_system_instructions],
                chatbot,
                show_api=False,
            ).then(
                fn=refresh_game_state,
                inputs=chat_session_id,
                outputs=[
                    game_status_md,
                    territory_bar,
                    population_bar,
                    treasury_bar,
                    satisfaction_bar,
                    royal_trust_bar,
                    advisor_trust_bar,
                ],
                show_api=False,
            )

            submit_btn.click(
                user, [msg, chatbot], [msg, chatbot], queue=False, show_api=False
            ).then(
                bot,
                [chatbot, chat_system_instructions],
                chatbot,
                show_api=False,
            ).then(
                fn=refresh_game_state,
                inputs=chat_session_id,
                outputs=[
                    game_status_md,
                    territory_bar,
                    population_bar,
                    treasury_bar,
                    satisfaction_bar,
                    royal_trust_bar,
                    advisor_trust_bar,
                ],
                show_api=False,
            )

        # MCP Server Tab
        with gr.TabItem("MCP Server", id="mcp_server"):
            gr.Markdown(update_guide_with_tool_prefix(tool_prefix, MCP_GUIDE_TEMPLATE))

            gr.Markdown("### Test: Initialize Game")
            with gr.Row():
                personality_input = gr.Dropdown(
                    choices=["cautious", "idealist", "populist"],
                    value="cautious",
                    label="Lord Personality",
                )
                init_btn = gr.Button("Start New Game")

            init_output = gr.JSON(label="Game Session Info")

            gr.Markdown("### Test: Get Game State")
            with gr.Row():
                session_id_input = gr.Textbox(
                    label="Session ID",
                    placeholder="Enter session_id from init_game",
                )
                get_state_btn = gr.Button("Get State")

            state_output = gr.JSON(label="Current Game State")

            get_state_btn.click(
                fn=get_game_state, inputs=session_id_input, outputs=state_output
            )

            gr.Markdown("### Test: List Available Advice")
            list_advice_btn = gr.Button("List Advice Options")
            advice_output = gr.JSON(label="Available Advice Options")

            list_advice_btn.click(
                fn=list_available_advice, inputs=[], outputs=advice_output
            )

            gr.Markdown("### Test: Execute Turn")
            with gr.Row():
                exec_session_id = gr.Textbox(
                    label="Session ID",
                    placeholder="Enter session_id",
                )
                exec_advice = gr.Dropdown(
                    choices=[
                        "increase_tax",
                        "decrease_tax",
                        "expand_territory",
                        "improve_diplomacy",
                        "public_festival",
                        "build_infrastructure",
                        "do_nothing",
                    ],
                    value="do_nothing",
                    label="Advice",
                )
                exec_btn = gr.Button("Execute Turn")

            exec_output = gr.JSON(label="Turn Result")

            exec_btn.click(
                fn=execute_turn,
                inputs=[exec_session_id, exec_advice],
                outputs=exec_output,
            )

            # Link init_game output to session_id inputs for testing
            init_btn.click(
                fn=init_game,
                inputs=personality_input,
                outputs=init_output,
            ).then(
                fn=lambda res: [res.get("session_id")] * 2,
                inputs=init_output,
                outputs=[session_id_input, exec_session_id],
                show_api=False,
            )


if __name__ == "__main__":
    demo.launch(mcp_server=True)