Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
# app.py
|
| 2 |
-
# @title Beer Game Final Version (
|
| 3 |
-
|
| 4 |
# -----------------------------------------------------------------------------
|
| 5 |
# 1. Import Libraries
|
| 6 |
# -----------------------------------------------------------------------------
|
|
@@ -15,10 +14,7 @@ import random
|
|
| 15 |
import uuid
|
| 16 |
from pathlib import Path
|
| 17 |
from datetime import datetime
|
| 18 |
-
from huggingface_hub import HfApi
|
| 19 |
-
from huggingface_hub.utils import RepositoryNotFoundError, EntryNotFoundError
|
| 20 |
-
import json
|
| 21 |
-
import numpy as np
|
| 22 |
|
| 23 |
# -----------------------------------------------------------------------------
|
| 24 |
# 0. Page Configuration (Must be the first Streamlit command)
|
|
@@ -35,10 +31,7 @@ INITIAL_BACKLOG = 0
|
|
| 35 |
ORDER_PASSING_DELAY = 1 # Handled by last_week_orders
|
| 36 |
SHIPPING_DELAY = 2 # General shipping delay (R->W, W->D)
|
| 37 |
FACTORY_LEAD_TIME = 1
|
| 38 |
-
#
|
| 39 |
-
# This MUST be 2 for LT=3. (Order W2 -> F Rec W3 -> F Prod W3 -> F Fin W4 -> F Ship W4 -> D Rec W5)
|
| 40 |
-
FACTORY_SHIPPING_DELAY = 2 # Specific delay from Factory to Distributor
|
| 41 |
-
# -------------------------------------------------------------------
|
| 42 |
HOLDING_COST = 0.5
|
| 43 |
BACKLOG_COST = 1.0
|
| 44 |
|
|
@@ -46,8 +39,7 @@ BACKLOG_COST = 1.0
|
|
| 46 |
OPENAI_MODEL = "gpt-4o-mini"
|
| 47 |
LOCAL_LOG_DIR = Path("logs")
|
| 48 |
LOCAL_LOG_DIR.mkdir(exist_ok=True)
|
| 49 |
-
IMAGE_PATH = "beer_game_diagram.png"
|
| 50 |
-
LEADERBOARD_FILE = "leaderboard.json"
|
| 51 |
|
| 52 |
# --- API & Secrets Configuration ---
|
| 53 |
try:
|
|
@@ -64,45 +56,35 @@ else:
|
|
| 64 |
# -----------------------------------------------------------------------------
|
| 65 |
# 3. Core Game Logic Functions
|
| 66 |
# -----------------------------------------------------------------------------
|
| 67 |
-
|
| 68 |
def get_customer_demand(week: int) -> int:
|
| 69 |
return 4 if week <= 4 else 8
|
| 70 |
|
| 71 |
-
|
| 72 |
-
def init_game_state(llm_personality: str, info_sharing: str, participant_id: str):
|
| 73 |
roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 74 |
human_role = "Distributor" # Role is fixed
|
| 75 |
-
|
| 76 |
st.session_state.game_state = {
|
| 77 |
-
'game_running': True,
|
| 78 |
-
'participant_id': participant_id,
|
| 79 |
-
'week': 1,
|
| 80 |
'human_role': human_role, 'llm_personality': llm_personality,
|
| 81 |
'info_sharing': info_sharing, 'logs': [], 'echelons': {},
|
| 82 |
'factory_production_pipeline': deque([0] * FACTORY_LEAD_TIME, maxlen=FACTORY_LEAD_TIME),
|
| 83 |
'decision_step': 'initial_order',
|
| 84 |
'human_initial_order': None,
|
| 85 |
-
'
|
| 86 |
-
'last_week_orders': {name: 0 for name in roles} # v4.21 Logic: 初始化为0
|
| 87 |
}
|
| 88 |
-
|
| 89 |
for i, name in enumerate(roles):
|
| 90 |
upstream = roles[i + 1] if i + 1 < len(roles) else None
|
| 91 |
downstream = roles[i - 1] if i - 1 >= 0 else None
|
| 92 |
-
|
| 93 |
-
# USE THE CORRECT DELAY
|
| 94 |
-
if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY # This is 2
|
| 95 |
elif name == "Factory": shipping_weeks = 0
|
| 96 |
-
else: shipping_weeks = SHIPPING_DELAY
|
| 97 |
-
|
| 98 |
st.session_state.game_state['echelons'][name] = {
|
| 99 |
'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
|
| 100 |
'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
|
| 101 |
'incoming_order': 0, 'order_placed': 0, 'shipment_sent': 0,
|
| 102 |
'weekly_cost': 0, 'total_cost': 0, 'upstream_name': upstream, 'downstream_name': downstream,
|
| 103 |
}
|
| 104 |
-
st.info(f"New game started
|
| 105 |
-
# ==============================================================================
|
| 106 |
|
| 107 |
def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
| 108 |
# This function remains correct.
|
|
@@ -122,20 +104,15 @@ def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
|
| 122 |
match = re.search(r'\d+', raw_text)
|
| 123 |
if match: return int(match.group(0)), raw_text
|
| 124 |
st.warning(f"LLM for {echelon_name} did not return a valid number. Defaulting to 4. Raw Response: '{raw_text}'")
|
| 125 |
-
return 4, raw_text
|
| 126 |
except Exception as e:
|
| 127 |
st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
|
| 128 |
return 4, f"API_ERROR: {e}"
|
| 129 |
|
| 130 |
-
# =============== PROMPT FUNCTION (v3 - Sterman Heuristic + Demand Fix) ===============
|
| 131 |
def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
|
| 132 |
-
# This function's logic
|
| 133 |
e_state = echelon_state_decision_point
|
| 134 |
base_info = f"Your Current Status at the **{e_state['name']}** for **Week {week}** (Before Shipping):\n- On-hand inventory: {e_state['inventory']} units.\n- Backlog (total unfilled orders): {e_state['backlog']} units.\n- Incoming order this week (just received): {e_state['incoming_order']} units.\n"
|
| 135 |
-
|
| 136 |
-
# --- PROMPT FIX: Get correct demand (current, not future) ---
|
| 137 |
-
current_stable_demand = get_customer_demand(week) # Use current week's demand
|
| 138 |
-
|
| 139 |
if e_state['name'] == 'Factory':
|
| 140 |
task_word = "production quantity"
|
| 141 |
base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
|
|
@@ -143,15 +120,11 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 143 |
task_word = "order quantity"
|
| 144 |
base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
|
| 145 |
|
| 146 |
-
# --- PERFECT RATIONAL (NORMATIVE) PROMPTS ---
|
| 147 |
-
|
| 148 |
if llm_personality == 'perfect_rational' and info_sharing == 'full':
|
| 149 |
-
stable_demand =
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY # 1+2 = 3
|
| 154 |
-
# ----------------------------------------------------
|
| 155 |
safety_stock = 4
|
| 156 |
target_inventory_level = (stable_demand * total_lead_time) + safety_stock
|
| 157 |
if e_state['name'] == 'Factory':
|
|
@@ -163,7 +136,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 163 |
inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
|
| 164 |
optimal_order = max(0, int(target_inventory_level - inventory_position))
|
| 165 |
return f"**You are a perfectly rational supply chain AI with full system visibility.**\nYour only goal is to maintain stability and minimize costs based on mathematical optimization.\n**System Analysis:**\n* **Known Stable End-Customer Demand:** {stable_demand} units/week.\n* **Your Current Total Inventory Position:** {inventory_position} units. {inv_pos_components}\n* **Optimal Target Inventory Level:** {target_inventory_level} units (Target for {total_lead_time} weeks lead time).\n* **Mathematically Optimal {task_word.title()}:** The optimal decision is **{optimal_order} units**.\n**Your Task:** Confirm this optimal {task_word}. Respond with a single integer."
|
| 166 |
-
|
| 167 |
elif llm_personality == 'perfect_rational' and info_sharing == 'local':
|
| 168 |
safety_stock = 4; anchor_demand = e_state['incoming_order']
|
| 169 |
inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
|
|
@@ -178,142 +151,59 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 178 |
rational_local_order = max(0, int(calculated_order))
|
| 179 |
return f"**You are a perfectly rational supply chain AI with ONLY LOCAL information.**\nYou must use a logical heuristic to make a stable decision. A proven method is \"Anchoring and Adjustment\".\n\n{base_info}\n\n**Rational Calculation (Anchoring & Adjustment):**\n1. **Anchor on Demand:** Your best guess for future demand is your last incoming order: **{anchor_demand} units**.\n2. **Adjust for Inventory:** You want to hold a safety stock of {safety_stock} units. Your current stock (before shipping) is {e_state['inventory'] - e_state['backlog']}. You need to order an extra **{inventory_correction} units** to correct this.\n3. **Account for {supply_line_desc}:** You already have **{supply_line} units** being processed. These should be subtracted from your new decision.\n\n**Final Calculation:**\n* Decision = (Anchor Demand) + (Inventory Adjustment) - ({supply_line_desc})\n* Decision = {anchor_demand} + {inventory_correction} - {supply_line} = **{rational_local_order} units**.\n**Your Task:** Confirm this locally rational {task_word}. Respond with a single integer."
|
| 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 |
-
**You are a reactive supply chain manager for the {e_state['name']}.** You have a limited (local) view.
|
| 206 |
-
You tend to make **reactive, 'gut-instinct' decisions** (like the classic Sterman 1989 model) that cause the Bullwhip Effect.
|
| 207 |
-
|
| 208 |
-
{base_info}
|
| 209 |
-
|
| 210 |
-
**Your Flawed 'Human' Heuristic:**
|
| 211 |
-
Your gut tells you to fix your entire inventory problem *right now*, and you're afraid of your backlog.
|
| 212 |
-
A 'rational' player would account for their {supply_line_desc} (which is {supply_line} units), but you're too busy panicking to trust that.
|
| 213 |
-
|
| 214 |
-
**Your 'Panic' Calculation (Ignoring the Supply Line):**
|
| 215 |
-
1. **Anchor on Demand:** You just got an order for **{anchor_demand}** units. You'll order *at least* that.
|
| 216 |
-
2. **Correct for Stock:** Your desired 'safe' inventory is {DESIRED_INVENTORY}. Your current net inventory is {net_inventory}. You need to order **{stock_correction}** more units to feel safe again.
|
| 217 |
-
3. **Ignore Supply Line:** You'll ignore the **{supply_line} units** already in your pipeline.
|
| 218 |
-
|
| 219 |
-
**Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
|
| 220 |
-
* Order = {panicky_order_calc} = **{panicky_order} units**.
|
| 221 |
-
|
| 222 |
-
**Your Task:** Confirm this 'gut-instinct' {task_word}. Respond with a single integer.
|
| 223 |
-
"""
|
| 224 |
-
|
| 225 |
-
elif info_sharing == 'full':
|
| 226 |
-
# Build the "Full Info" string just for context
|
| 227 |
-
full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {current_stable_demand} units.\n"
|
| 228 |
-
for name, other_e_state in all_echelons_state_decision_point.items():
|
| 229 |
-
if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
|
| 230 |
-
|
| 231 |
-
return f"""
|
| 232 |
-
**You are a supply chain manager ({e_state['name']}) with full system visibility.**
|
| 233 |
-
{base_info}
|
| 234 |
-
{full_info_str}
|
| 235 |
-
|
| 236 |
-
**A "Human-like" Flawed Decision:**
|
| 237 |
-
Even though you have full information, you are judged by *your own* performance (your inventory, your backlog).
|
| 238 |
-
You tend to react to your *local* situation (like the classic Sterman 1989 model) instead of using the complex full-system data.
|
| 239 |
-
A 'rational' player would use the end-customer demand ({current_stable_demand}) and account for the *entire* system, but your gut-instinct is to panic about *your* numbers.
|
| 240 |
-
|
| 241 |
-
**Your 'Panic' Calculation (Ignoring Full Info and Your Supply Line):**
|
| 242 |
-
1. **Anchor on *Your* Demand:** You just got an order for **{anchor_demand}** units. You react to this, not the end-customer demand.
|
| 243 |
-
2. **Correct for *Your* Stock:** Your desired 'safe' inventory is {DESIRED_INVENTORY}. Your current net inventory is {net_inventory}. You need to order **{stock_correction}** more units.
|
| 244 |
-
3. **Ignore *Your* Supply Line:** You'll ignore the **{supply_line} units** in your own pipeline ({supply_line_desc}).
|
| 245 |
-
|
| 246 |
-
**Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
|
| 247 |
-
* Order = {panicky_order_calc} = **{panicky_order} units**.
|
| 248 |
-
|
| 249 |
-
**Your Task:** Confirm this 'gut-instinct', locally-focused {task_word}. Respond with a single integer.
|
| 250 |
-
"""
|
| 251 |
-
# =========================================================
|
| 252 |
|
| 253 |
-
# =============== STEP_GAME (v8) - Stable Logic + Correct Log Fix ===============
|
| 254 |
def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
|
| 255 |
-
# This
|
| 256 |
state = st.session_state.game_state
|
| 257 |
week, echelons, human_role = state['week'], state['echelons'], state['human_role']
|
| 258 |
llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
|
| 259 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 260 |
llm_raw_responses = {}
|
| 261 |
-
|
| 262 |
-
# Capture opening state for logging
|
| 263 |
opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
|
| 264 |
opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
|
| 265 |
|
| 266 |
-
|
| 267 |
-
arrived_this_week_LOG = {name: 0 for name in echelon_order}
|
| 268 |
-
arriving_next_week_LOG = {name: 0 for name in echelon_order}
|
| 269 |
-
factory_q = state['factory_production_pipeline']
|
| 270 |
-
|
| 271 |
-
# Factory UI Values
|
| 272 |
-
if factory_q:
|
| 273 |
-
arrived_this_week_LOG["Factory"] = factory_q[0] # Arrives this week
|
| 274 |
-
arriving_next_week_LOG["Factory"] = state['last_week_orders'].get("Distributor", 0) # Arrives next week
|
| 275 |
-
|
| 276 |
-
# R, W, D UI Values
|
| 277 |
-
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 278 |
-
shipment_q = echelons[name]['incoming_shipments']
|
| 279 |
-
if shipment_q:
|
| 280 |
-
arrived_this_week_LOG[name] = shipment_q[0] # Arrives this week (W+0)
|
| 281 |
-
|
| 282 |
-
# This logic MUST match the UI logic (v8)
|
| 283 |
-
if name == 'Distributor':
|
| 284 |
-
# "Next" for Distributor is the *second* item in its queue (or factory pipeline)
|
| 285 |
-
# --------------------- LT=3 FIX ---------------------
|
| 286 |
-
# With maxlen=2, the queue [0, 4] -> [0] is this week, [1] is next week
|
| 287 |
-
if len(shipment_q) > 1:
|
| 288 |
-
arriving_next_week_LOG[name] = shipment_q[1]
|
| 289 |
-
# ----------------------------------------------------
|
| 290 |
-
elif name in ("Retailer", "Wholesaler"):
|
| 291 |
-
# "Next" for R/W is the *second* item in their queue
|
| 292 |
-
if len(shipment_q) > 1:
|
| 293 |
-
arriving_next_week_LOG[name] = shipment_q[1]
|
| 294 |
-
# --- END LOG FIX (v8) ---
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
# === NOW, THE STABLE (v2) GAME LOGIC ===
|
| 298 |
-
# This block is separate from the logging block above.
|
| 299 |
-
# It uses its *own* variables to run the game.
|
| 300 |
-
arrived_this_week_GAME = {name: 0 for name in echelon_order} # Use a fresh dict for game logic
|
| 301 |
inventory_after_arrival = {}
|
|
|
|
| 302 |
factory_state = echelons["Factory"]
|
| 303 |
produced_units = 0
|
| 304 |
if state['factory_production_pipeline']:
|
| 305 |
-
produced_units = state['factory_production_pipeline'].popleft()
|
| 306 |
-
|
| 307 |
inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
|
| 308 |
-
|
| 309 |
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 310 |
arrived_shipment = 0
|
| 311 |
if echelons[name]['incoming_shipments']:
|
| 312 |
-
arrived_shipment = echelons[name]['incoming_shipments'].popleft()
|
| 313 |
-
|
| 314 |
inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
|
| 315 |
-
|
| 316 |
-
|
| 317 |
total_backlog_before_shipping = {}
|
| 318 |
for name in echelon_order:
|
| 319 |
incoming_order_for_this_week = 0
|
|
@@ -323,13 +213,15 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 323 |
if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
|
| 324 |
echelons[name]['incoming_order'] = incoming_order_for_this_week
|
| 325 |
total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
|
|
|
|
| 326 |
decision_point_states = {}
|
| 327 |
for name in echelon_order:
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
|
|
|
| 333 |
current_week_orders = {}
|
| 334 |
for name in echelon_order:
|
| 335 |
e = echelons[name]; prompt_state = decision_point_states[name]
|
|
@@ -338,43 +230,34 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 338 |
prompt = get_llm_prompt(prompt_state, week, llm_personality, info_sharing, decision_point_states)
|
| 339 |
order_amount, raw_resp = get_llm_order_decision(prompt, name)
|
| 340 |
llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
|
|
|
|
| 341 |
state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
|
|
|
|
| 342 |
units_shipped = {name: 0 for name in echelon_order}
|
| 343 |
for name in echelon_order:
|
| 344 |
e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
|
| 345 |
e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
|
| 346 |
e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
|
|
|
|
| 347 |
if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
|
| 348 |
if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
|
| 349 |
if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
|
| 350 |
-
|
| 351 |
-
# (Logging)
|
| 352 |
log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
|
| 353 |
del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
|
| 354 |
-
if 'current_ai_suggestion' in log_entry: del log_entry['current_ai_suggestion']
|
| 355 |
for name in echelon_order:
|
| 356 |
e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
|
| 357 |
for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
|
| 358 |
log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
log_entry[f'{name}.
|
| 362 |
-
log_entry[f'{name}.
|
| 363 |
-
log_entry[f'{name}.arrived_this_week'] = arrived_this_week_LOG[name] # Use captured
|
| 364 |
-
|
| 365 |
-
if name != 'Factory':
|
| 366 |
-
log_entry[f'{name}.arriving_next_week'] = arriving_next_week_LOG[name] # Use captured
|
| 367 |
-
else:
|
| 368 |
-
log_entry[f'{name}.production_completing_next_week'] = arriving_next_week_LOG[name] # Use captured
|
| 369 |
-
# --- END OF LOG FIX (v8) ---
|
| 370 |
-
|
| 371 |
log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
|
| 372 |
state['logs'].append(log_entry)
|
|
|
|
| 373 |
state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
|
| 374 |
-
state['current_ai_suggestion'] = None # Clean up
|
| 375 |
if state['week'] > WEEKS: state['game_running'] = False
|
| 376 |
-
# ==============================================================================
|
| 377 |
-
|
| 378 |
|
| 379 |
def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
| 380 |
# This function remains correct.
|
|
@@ -406,134 +289,27 @@ def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
|
| 406 |
axes[3].set_title(f'Analysis of Your ({human_role}) Decisions - Error Plotting Data'); axes[3].text(0.5, 0.5, f"Error: {plot_err}", ha='center', va='center'); axes[3].grid(True, linestyle='--'); axes[3].set_xlabel('Week')
|
| 407 |
plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
|
| 408 |
|
| 409 |
-
|
| 410 |
-
# =============== NEW: Leaderboard Functions ===============
|
| 411 |
-
@st.cache_data(ttl=60)
|
| 412 |
-
def load_leaderboard_data():
|
| 413 |
-
if not hf_api or not HF_REPO_ID: return {}
|
| 414 |
-
try:
|
| 415 |
-
local_path = hf_hub_download(repo_id=HF_REPO_ID, repo_type="dataset", filename=LEADERBOARD_FILE, token=HF_TOKEN, cache_dir=LOCAL_LOG_DIR / "hf_cache")
|
| 416 |
-
with open(local_path, 'r', encoding='utf-8') as f: return json.load(f)
|
| 417 |
-
except EntryNotFoundError:
|
| 418 |
-
st.sidebar.info("Leaderboard file not found. A new one will be created.")
|
| 419 |
-
return {}
|
| 420 |
-
except Exception as e:
|
| 421 |
-
st.sidebar.error(f"Could not load leaderboard: {e}")
|
| 422 |
-
return {}
|
| 423 |
-
|
| 424 |
-
def save_leaderboard_data(data):
|
| 425 |
-
if not hf_api or not HF_REPO_ID or not HF_TOKEN: return
|
| 426 |
-
try:
|
| 427 |
-
local_path = LOCAL_LOG_DIR / LEADERBOARD_FILE
|
| 428 |
-
with open(local_path, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2, ensure_ascii=False)
|
| 429 |
-
hf_api.upload_file(path_or_fileobj=str(local_path), path_in_repo=LEADERBOARD_FILE, repo_id=HF_REPO_ID, repo_type="dataset", token=HF_TOKEN, commit_message="Update leaderboard")
|
| 430 |
-
st.sidebar.success("Leaderboard updated!")
|
| 431 |
-
st.cache_data.clear()
|
| 432 |
-
except Exception as e:
|
| 433 |
-
st.sidebar.error(f"Failed to upload leaderboard: {e}")
|
| 434 |
-
|
| 435 |
-
def display_rankings(df, top_n=10):
|
| 436 |
-
if df.empty:
|
| 437 |
-
st.info("No completed games for this category yet. Be the first!")
|
| 438 |
-
return
|
| 439 |
-
df['total_cost'] = pd.to_numeric(df['total_cost'], errors='coerce')
|
| 440 |
-
df['order_std_dev'] = pd.to_numeric(df['order_std_dev'], errors='coerce')
|
| 441 |
-
df = df.dropna(subset=['total_cost', 'order_std_dev'])
|
| 442 |
-
if df.empty:
|
| 443 |
-
st.info("No valid completed games for this category yet.")
|
| 444 |
-
return
|
| 445 |
-
c1, c2, c3 = st.columns(3)
|
| 446 |
-
with c1:
|
| 447 |
-
st.subheader("🏆 Supply Chain Champions")
|
| 448 |
-
st.caption(f"Top {top_n} - Lowest Total Cost")
|
| 449 |
-
champs_df = df.sort_values('total_cost', ascending=True).head(top_n).copy()
|
| 450 |
-
champs_df['total_cost'] = champs_df['total_cost'].map('${:,.2f}'.format)
|
| 451 |
-
champs_df.rename(columns={'id': 'Participant', 'total_cost': 'Total Cost'}, inplace=True)
|
| 452 |
-
st.dataframe(champs_df[['Participant', 'Total Cost']], use_container_width=True, hide_index=True)
|
| 453 |
-
with c2:
|
| 454 |
-
st.subheader("👑 Bullwhip Kings")
|
| 455 |
-
st.caption(f"Top {top_n} - Highest Total Cost")
|
| 456 |
-
kings_df = df.sort_values('total_cost', ascending=False).head(top_n).copy()
|
| 457 |
-
kings_df['total_cost'] = kings_df['total_cost'].map('${:,.2f}'.format)
|
| 458 |
-
kings_df.rename(columns={'id': 'Participant', 'total_cost': 'Total Cost'}, inplace=True)
|
| 459 |
-
st.dataframe(kings_df[['Participant', 'Total Cost']], use_container_width=True, hide_index=True)
|
| 460 |
-
with c3:
|
| 461 |
-
st.subheader("🧘 Mr. Smooth")
|
| 462 |
-
st.caption(f"Top {top_n} - Lowest Order Variation (Std. Dev.)")
|
| 463 |
-
smooth_df = df.sort_values('order_std_dev', ascending=True).head(top_n).copy()
|
| 464 |
-
smooth_df['order_std_dev'] = smooth_df['order_std_dev'].map('{:,.2f}'.format)
|
| 465 |
-
smooth_df.rename(columns={'id': 'Participant', 'order_std_dev': 'Order Std. Dev.'}, inplace=True)
|
| 466 |
-
st.dataframe(smooth_df[['Participant', 'Order Std. Dev.']], use_container_width=True, hide_index=True)
|
| 467 |
-
|
| 468 |
-
def show_leaderboard_ui():
|
| 469 |
-
st.markdown("---")
|
| 470 |
-
st.header("📊 The Bullwhip Leaderboard")
|
| 471 |
-
st.caption("Leaderboard updates after you finish a game. Cached for 60 seconds.")
|
| 472 |
-
leaderboard_data = load_leaderboard_data()
|
| 473 |
-
if not leaderboard_data:
|
| 474 |
-
st.info("No leaderboard data yet. Be the first to finish a game!")
|
| 475 |
-
else:
|
| 476 |
-
try:
|
| 477 |
-
df = pd.DataFrame(leaderboard_data.values())
|
| 478 |
-
if 'id' not in df.columns and not df.empty: df['id'] = list(leaderboard_data.keys())
|
| 479 |
-
if 'total_cost' not in df.columns or 'order_std_dev' not in df.columns or 'setting' not in df.columns:
|
| 480 |
-
st.error("Leaderboard data is corrupted or incomplete.")
|
| 481 |
-
return
|
| 482 |
-
groups = sorted(df.setting.unique())
|
| 483 |
-
tabs = st.tabs(["**Overall**"] + groups)
|
| 484 |
-
with tabs[0]: display_rankings(df)
|
| 485 |
-
for i, group_name in enumerate(groups):
|
| 486 |
-
with tabs[i+1]:
|
| 487 |
-
df_group = df[df.setting == group_name].copy()
|
| 488 |
-
display_rankings(df_group)
|
| 489 |
-
except Exception as e:
|
| 490 |
-
st.error(f"Error displaying leaderboard: {e}")
|
| 491 |
-
st.dataframe(leaderboard_data)
|
| 492 |
-
|
| 493 |
def save_logs_and_upload(state: dict):
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
return
|
| 497 |
participant_id = state['participant_id']
|
| 498 |
-
logs_df = None
|
| 499 |
try:
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
logs_df.to_csv(fname, index=False)
|
| 505 |
st.success(f"Log successfully saved locally: `{fname}`")
|
| 506 |
with open(fname, "rb") as f: st.download_button("📥 Download Log CSV", data=f, file_name=fname.name, mime="text/csv")
|
| 507 |
if HF_TOKEN and HF_REPO_ID and hf_api:
|
| 508 |
-
with st.spinner("Uploading log
|
| 509 |
try:
|
| 510 |
url = hf_api.upload_file( path_or_fileobj=str(fname), path_in_repo=f"logs/{fname.name}", repo_id=HF_REPO_ID, repo_type="dataset", token=HF_TOKEN)
|
| 511 |
-
st.success(f"✅ Log
|
| 512 |
except Exception as e_upload: st.error(f"Upload to Hugging Face failed: {e_upload}")
|
| 513 |
-
except Exception as e_save:
|
| 514 |
-
st.error(f"Error processing or saving log CSV: {e_save}")
|
| 515 |
-
return
|
| 516 |
-
if logs_df is None: return
|
| 517 |
-
st.subheader("Updating Leaderboard...")
|
| 518 |
-
try:
|
| 519 |
-
human_role = state['human_role']
|
| 520 |
-
total_cost = logs_df[f'{human_role}.total_cost'].iloc[-1]
|
| 521 |
-
order_std_dev = logs_df[f'{human_role}.order_placed'].std()
|
| 522 |
-
setting_name = f"{state['llm_personality']} / {state['info_sharing']}"
|
| 523 |
-
new_entry = {
|
| 524 |
-
'id': participant_id, 'setting': setting_name,
|
| 525 |
-
'total_cost': float(total_cost),
|
| 526 |
-
'order_std_dev': float(order_std_dev) if pd.notna(order_std_dev) else 0.0
|
| 527 |
-
}
|
| 528 |
-
leaderboard_data = load_leaderboard_data()
|
| 529 |
-
leaderboard_data[participant_id] = new_entry
|
| 530 |
-
save_leaderboard_data(leaderboard_data)
|
| 531 |
-
except Exception as e_board:
|
| 532 |
-
st.error(f"Error calculating or saving leaderboard score: {e_board}")
|
| 533 |
-
# ==============================================================================
|
| 534 |
|
| 535 |
# -----------------------------------------------------------------------------
|
| 536 |
-
# 4. Streamlit UI (
|
| 537 |
# -----------------------------------------------------------------------------
|
| 538 |
st.title("🍺 The Beer Game: A Human-AI Collaboration Challenge")
|
| 539 |
|
|
@@ -543,75 +319,56 @@ else:
|
|
| 543 |
# --- Game Setup & Instructions ---
|
| 544 |
if 'game_state' not in st.session_state or not st.session_state.game_state.get('game_running', False):
|
| 545 |
|
| 546 |
-
|
| 547 |
-
st.header("⚙️ Game Configuration")
|
| 548 |
-
|
| 549 |
-
# =============== NEW: Participant ID Input ===============
|
| 550 |
-
participant_id = st.text_input("Enter Your Name or Team ID:", key="participant_id_input", placeholder="e.g., Team A")
|
| 551 |
-
# =======================================================
|
| 552 |
|
|
|
|
| 553 |
c1, c2 = st.columns(2)
|
| 554 |
with c1:
|
| 555 |
-
|
| 556 |
with c2:
|
| 557 |
info_sharing = st.selectbox("Information Sharing Level", ('local', 'full'), format_func=lambda x: x.title(), help="**Local:** You and the AI agents can only see your own inventory and incoming orders. **Full:** Everyone can see the entire supply chain's status and the true end-customer demand.")
|
| 558 |
-
|
| 559 |
-
# =============== MODIFIED: Start Game Button ===============
|
| 560 |
-
if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
|
| 561 |
-
if not participant_id:
|
| 562 |
-
st.error("Please enter a Name or Team ID to start!")
|
| 563 |
-
else:
|
| 564 |
-
existing_data = load_leaderboard_data()
|
| 565 |
-
if participant_id in existing_data:
|
| 566 |
-
# 如果ID已存在,添加一个session_state标志,要求再次点击
|
| 567 |
-
if st.session_state.get('last_id_warning') == participant_id:
|
| 568 |
-
# 这是第二次点击,确认覆盖
|
| 569 |
-
st.session_state.pop('last_id_warning', None)
|
| 570 |
-
init_game_state(llm_personality, info_sharing, participant_id)
|
| 571 |
-
st.rerun()
|
| 572 |
-
else:
|
| 573 |
-
st.session_state['last_id_warning'] = participant_id
|
| 574 |
-
st.warning(f"ID '{participant_id}' already exists! Your score will be overwritten. Click 'Start Game' again to confirm.")
|
| 575 |
-
else:
|
| 576 |
-
# 新ID,直接开始
|
| 577 |
-
if 'last_id_warning' in st.session_state:
|
| 578 |
-
del st.session_state['last_id_warning']
|
| 579 |
-
init_game_state(llm_personality, info_sharing, participant_id)
|
| 580 |
-
st.rerun()
|
| 581 |
-
# ===========================================================
|
| 582 |
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
|
| 587 |
# --- Main Game Interface ---
|
| 588 |
elif 'game_state' in st.session_state and st.session_state.game_state.get('game_running'):
|
| 589 |
state = st.session_state.game_state
|
| 590 |
week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
|
| 591 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Define here for UI
|
| 592 |
-
|
| 593 |
-
|
| 594 |
st.header(f"Week {week} / {WEEKS}")
|
| 595 |
-
st.subheader(f"Your Role: **{human_role}**
|
| 596 |
st.markdown("---")
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
if info_sharing == 'full':
|
| 601 |
cols = st.columns(4)
|
| 602 |
-
for i, name in enumerate(echelon_order):
|
| 603 |
with cols[i]:
|
| 604 |
-
e = echelons[name]
|
| 605 |
icon = "👤" if name == human_role else "🤖"
|
| 606 |
-
|
|
|
|
| 607 |
if name == human_role:
|
|
|
|
| 608 |
st.markdown(f"##### **<span style='border: 1px solid #FF4B4B; padding: 2px 5px; border-radius: 3px;'>{icon} {name} (You)</span>**", unsafe_allow_html=True)
|
| 609 |
else:
|
| 610 |
st.markdown(f"##### {icon} {name}")
|
|
|
|
| 611 |
|
|
|
|
| 612 |
st.metric("Inventory (Opening)", e['inventory'])
|
| 613 |
st.metric("Backlog (Opening)", e['backlog'])
|
| 614 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 615 |
current_incoming_order = 0
|
| 616 |
if name == "Retailer":
|
| 617 |
current_incoming_order = get_customer_demand(week)
|
|
@@ -619,57 +376,40 @@ else:
|
|
| 619 |
downstream_name = e['downstream_name']
|
| 620 |
if downstream_name:
|
| 621 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 622 |
-
|
| 623 |
-
|
|
|
|
|
|
|
| 624 |
if name == "Factory":
|
| 625 |
-
prod_completing_next = state['
|
| 626 |
st.write(f"Completing Next Week: **{prod_completing_next}**")
|
| 627 |
else:
|
| 628 |
-
arriving_next = 0
|
| 629 |
-
|
| 630 |
-
# This logic matches the v8 Log Fix
|
| 631 |
-
if name == 'Distributor':
|
| 632 |
-
# --------------------- LT=3 FIX ---------------------
|
| 633 |
-
q = e['incoming_shipments']
|
| 634 |
-
if len(q) > 1: arriving_next = list(q)[1]
|
| 635 |
-
# ----------------------------------------------------
|
| 636 |
-
elif name in ('Wholesaler', 'Retailer'):
|
| 637 |
-
# "Next" for R/W is the *second* item in their queue
|
| 638 |
-
q = e['incoming_shipments']
|
| 639 |
-
if len(q) > 1: arriving_next = list(q)[1]
|
| 640 |
-
|
| 641 |
st.write(f"Arriving Next Week: **{arriving_next}**")
|
| 642 |
-
|
| 643 |
else: # Local Info Mode
|
| 644 |
st.info("In Local Information mode, you can only see your own status dashboard.")
|
| 645 |
-
e = echelons[human_role]
|
| 646 |
-
st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True)
|
| 647 |
-
|
| 648 |
-
col1, col2, col3 = st.columns(3)
|
| 649 |
-
with col1:
|
| 650 |
-
st.metric("Inventory (Opening)", e['inventory'])
|
| 651 |
-
st.metric("Backlog (Opening)", e['backlog'])
|
| 652 |
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
# =======================================================
|
| 672 |
-
|
| 673 |
st.markdown("---")
|
| 674 |
st.header("Your Decision (Step 4)")
|
| 675 |
|
|
@@ -678,63 +418,66 @@ else:
|
|
| 678 |
for name in echelon_order:
|
| 679 |
e_curr = echelons[name] # This is END OF LAST WEEK state
|
| 680 |
arrived = 0
|
|
|
|
| 681 |
if name == "Factory":
|
| 682 |
-
|
| 683 |
else:
|
| 684 |
-
|
| 685 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 686 |
inc_order_this_week = 0
|
| 687 |
if name == "Retailer": inc_order_this_week = get_customer_demand(week)
|
| 688 |
else:
|
| 689 |
ds_name = e_curr['downstream_name']
|
| 690 |
if ds_name: inc_order_this_week = state['last_week_orders'].get(ds_name, 0)
|
| 691 |
-
|
| 692 |
-
inv_after_arrival = e_curr['inventory'] + arrived
|
| 693 |
backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
|
| 694 |
|
| 695 |
-
# This is the state used for the prompt, it's calculated BEFORE the pop
|
| 696 |
all_decision_point_states[name] = {
|
| 697 |
'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
|
| 698 |
-
'incoming_order': inc_order_this_week,
|
| 699 |
'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
|
| 700 |
}
|
|
|
|
| 701 |
human_echelon_state_for_prompt = all_decision_point_states[human_role]
|
| 702 |
|
| 703 |
-
|
| 704 |
if state['decision_step'] == 'initial_order':
|
| 705 |
with st.form(key="initial_order_form"):
|
| 706 |
st.markdown("#### **Step 4a:** Based on the dashboard, submit your **initial** order to the Factory.")
|
| 707 |
-
|
|
|
|
|
|
|
| 708 |
if st.form_submit_button("Submit Initial Order & See AI Suggestion", type="primary"):
|
|
|
|
| 709 |
state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
|
| 710 |
state['decision_step'] = 'final_order'
|
| 711 |
-
|
| 712 |
-
# --- NEW: Calculate and store suggestion ONCE ---
|
| 713 |
-
prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, state['llm_personality'], state['info_sharing'], all_decision_point_states)
|
| 714 |
-
ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
|
| 715 |
-
state['current_ai_suggestion'] = ai_suggestion # Store it
|
| 716 |
-
# ------------------------------------------------
|
| 717 |
-
|
| 718 |
st.rerun()
|
| 719 |
|
| 720 |
elif state['decision_step'] == 'final_order':
|
| 721 |
st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
|
| 722 |
|
| 723 |
-
#
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
with st.form(key="final_order_form"):
|
| 728 |
st.markdown(f"#### **Step 4b:** The AI suggests ordering **{ai_suggestion}** units.")
|
| 729 |
st.markdown("Considering the AI's advice, submit your **final** order to end the week. (This order will arrive in 3 weeks).")
|
| 730 |
-
|
|
|
|
|
|
|
| 731 |
|
| 732 |
if st.form_submit_button("Submit Final Order & Advance to Next Week"):
|
| 733 |
-
|
|
|
|
| 734 |
final_order_value = int(final_order_value) if final_order_value is not None else 0
|
| 735 |
-
|
| 736 |
step_game(final_order_value, state['human_initial_order'], ai_suggestion)
|
| 737 |
|
|
|
|
| 738 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
| 739 |
st.rerun()
|
| 740 |
|
|
@@ -745,25 +488,22 @@ else:
|
|
| 745 |
else:
|
| 746 |
try:
|
| 747 |
history_df = pd.json_normalize(state['logs'])
|
| 748 |
-
# FIX: Removed 'Arrived This Week' from log UI
|
| 749 |
human_cols = {
|
| 750 |
'week': 'Week', f'{human_role}.opening_inventory': 'Opening Inv.',
|
| 751 |
-
f'{human_role}.opening_backlog': 'Opening Backlog',
|
| 752 |
f'{human_role}.incoming_order': 'Incoming Order', f'{human_role}.initial_order': 'Your Initial Order',
|
| 753 |
f'{human_role}.ai_suggestion': 'AI Suggestion', f'{human_role}.order_placed': 'Your Final Order',
|
| 754 |
f'{human_role}.arriving_next_week': 'Arriving Next Week', f'{human_role}.weekly_cost': 'Weekly Cost',
|
| 755 |
}
|
| 756 |
-
# FIX: Removed 'Arrived This Week' from log UI
|
| 757 |
ordered_display_cols_keys = [
|
| 758 |
'week', f'{human_role}.opening_inventory', f'{human_role}.opening_backlog',
|
| 759 |
-
f'{human_role}.incoming_order',
|
| 760 |
f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed',
|
| 761 |
f'{human_role}.arriving_next_week', f'{human_role}.weekly_cost'
|
| 762 |
-
|
| 763 |
final_cols_to_display = [col for col in ordered_display_cols_keys if col in history_df.columns]
|
| 764 |
-
|
| 765 |
if not final_cols_to_display:
|
| 766 |
-
|
| 767 |
else:
|
| 768 |
display_df = history_df[final_cols_to_display].rename(columns=human_cols)
|
| 769 |
if 'Weekly Cost' in display_df.columns:
|
|
@@ -774,12 +514,10 @@ else:
|
|
| 774 |
|
| 775 |
try: st.sidebar.image(IMAGE_PATH, caption="Supply Chain Reference")
|
| 776 |
except FileNotFoundError: st.sidebar.warning("Image file not found.")
|
| 777 |
-
|
| 778 |
st.sidebar.header("Game Info")
|
| 779 |
st.sidebar.markdown(f"**Game ID**: `{state['participant_id']}`\n\n**Current Week**: {week}")
|
| 780 |
if st.sidebar.button("🔄 Reset Game"):
|
| 781 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
| 782 |
-
if 'current_ai_suggestion' in st.session_state.game_state: del st.session_state.game_state['current_ai_suggestion']
|
| 783 |
del st.session_state.game_state
|
| 784 |
st.rerun()
|
| 785 |
|
|
@@ -795,12 +533,10 @@ else:
|
|
| 795 |
state['human_role']
|
| 796 |
)
|
| 797 |
st.pyplot(fig)
|
| 798 |
-
save_logs_and_upload(state)
|
| 799 |
except Exception as e:
|
| 800 |
st.error(f"Error generating final report: {e}")
|
| 801 |
|
| 802 |
-
show_leaderboard_ui()
|
| 803 |
-
|
| 804 |
if st.button("✨ Start a New Game"):
|
| 805 |
del st.session_state.game_state
|
| 806 |
st.rerun()
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# @title Beer Game Final Version (v4.21 - Removed Introduction)
|
|
|
|
| 3 |
# -----------------------------------------------------------------------------
|
| 4 |
# 1. Import Libraries
|
| 5 |
# -----------------------------------------------------------------------------
|
|
|
|
| 14 |
import uuid
|
| 15 |
from pathlib import Path
|
| 16 |
from datetime import datetime
|
| 17 |
+
from huggingface_hub import HfApi
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# -----------------------------------------------------------------------------
|
| 20 |
# 0. Page Configuration (Must be the first Streamlit command)
|
|
|
|
| 31 |
ORDER_PASSING_DELAY = 1 # Handled by last_week_orders
|
| 32 |
SHIPPING_DELAY = 2 # General shipping delay (R->W, W->D)
|
| 33 |
FACTORY_LEAD_TIME = 1
|
| 34 |
+
FACTORY_SHIPPING_DELAY = 1 # Specific delay from Factory to Distributor
|
|
|
|
|
|
|
|
|
|
| 35 |
HOLDING_COST = 0.5
|
| 36 |
BACKLOG_COST = 1.0
|
| 37 |
|
|
|
|
| 39 |
OPENAI_MODEL = "gpt-4o-mini"
|
| 40 |
LOCAL_LOG_DIR = Path("logs")
|
| 41 |
LOCAL_LOG_DIR.mkdir(exist_ok=True)
|
| 42 |
+
IMAGE_PATH = "beer_game_diagram.png" # Path to your uploaded image
|
|
|
|
| 43 |
|
| 44 |
# --- API & Secrets Configuration ---
|
| 45 |
try:
|
|
|
|
| 56 |
# -----------------------------------------------------------------------------
|
| 57 |
# 3. Core Game Logic Functions
|
| 58 |
# -----------------------------------------------------------------------------
|
|
|
|
| 59 |
def get_customer_demand(week: int) -> int:
|
| 60 |
return 4 if week <= 4 else 8
|
| 61 |
|
| 62 |
+
def init_game_state(llm_personality: str, info_sharing: str):
|
|
|
|
| 63 |
roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 64 |
human_role = "Distributor" # Role is fixed
|
| 65 |
+
participant_id = str(uuid.uuid4())[:8]
|
| 66 |
st.session_state.game_state = {
|
| 67 |
+
'game_running': True, 'participant_id': participant_id, 'week': 1,
|
|
|
|
|
|
|
| 68 |
'human_role': human_role, 'llm_personality': llm_personality,
|
| 69 |
'info_sharing': info_sharing, 'logs': [], 'echelons': {},
|
| 70 |
'factory_production_pipeline': deque([0] * FACTORY_LEAD_TIME, maxlen=FACTORY_LEAD_TIME),
|
| 71 |
'decision_step': 'initial_order',
|
| 72 |
'human_initial_order': None,
|
| 73 |
+
'last_week_orders': {name: 0 for name in roles}
|
|
|
|
| 74 |
}
|
|
|
|
| 75 |
for i, name in enumerate(roles):
|
| 76 |
upstream = roles[i + 1] if i + 1 < len(roles) else None
|
| 77 |
downstream = roles[i - 1] if i - 1 >= 0 else None
|
| 78 |
+
if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY
|
|
|
|
|
|
|
| 79 |
elif name == "Factory": shipping_weeks = 0
|
| 80 |
+
else: shipping_weeks = SHIPPING_DELAY
|
|
|
|
| 81 |
st.session_state.game_state['echelons'][name] = {
|
| 82 |
'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
|
| 83 |
'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
|
| 84 |
'incoming_order': 0, 'order_placed': 0, 'shipment_sent': 0,
|
| 85 |
'weekly_cost': 0, 'total_cost': 0, 'upstream_name': upstream, 'downstream_name': downstream,
|
| 86 |
}
|
| 87 |
+
st.info(f"New game started! AI Mode: **{llm_personality} / {info_sharing}**. You are playing as the: **{human_role}**.")
|
|
|
|
| 88 |
|
| 89 |
def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
| 90 |
# This function remains correct.
|
|
|
|
| 104 |
match = re.search(r'\d+', raw_text)
|
| 105 |
if match: return int(match.group(0)), raw_text
|
| 106 |
st.warning(f"LLM for {echelon_name} did not return a valid number. Defaulting to 4. Raw Response: '{raw_text}'")
|
| 107 |
+
return 4, raw_text # Default to 4
|
| 108 |
except Exception as e:
|
| 109 |
st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
|
| 110 |
return 4, f"API_ERROR: {e}"
|
| 111 |
|
|
|
|
| 112 |
def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
|
| 113 |
+
# This function's logic remains correct (from v4.17).
|
| 114 |
e_state = echelon_state_decision_point
|
| 115 |
base_info = f"Your Current Status at the **{e_state['name']}** for **Week {week}** (Before Shipping):\n- On-hand inventory: {e_state['inventory']} units.\n- Backlog (total unfilled orders): {e_state['backlog']} units.\n- Incoming order this week (just received): {e_state['incoming_order']} units.\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
if e_state['name'] == 'Factory':
|
| 117 |
task_word = "production quantity"
|
| 118 |
base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
|
|
|
|
| 120 |
task_word = "order quantity"
|
| 121 |
base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
|
| 122 |
|
|
|
|
|
|
|
| 123 |
if llm_personality == 'perfect_rational' and info_sharing == 'full':
|
| 124 |
+
stable_demand = 8
|
| 125 |
+
if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME
|
| 126 |
+
elif e_state['name'] == 'Distributor': total_lead_time = ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY
|
| 127 |
+
else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY
|
|
|
|
|
|
|
| 128 |
safety_stock = 4
|
| 129 |
target_inventory_level = (stable_demand * total_lead_time) + safety_stock
|
| 130 |
if e_state['name'] == 'Factory':
|
|
|
|
| 136 |
inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
|
| 137 |
optimal_order = max(0, int(target_inventory_level - inventory_position))
|
| 138 |
return f"**You are a perfectly rational supply chain AI with full system visibility.**\nYour only goal is to maintain stability and minimize costs based on mathematical optimization.\n**System Analysis:**\n* **Known Stable End-Customer Demand:** {stable_demand} units/week.\n* **Your Current Total Inventory Position:** {inventory_position} units. {inv_pos_components}\n* **Optimal Target Inventory Level:** {target_inventory_level} units (Target for {total_lead_time} weeks lead time).\n* **Mathematically Optimal {task_word.title()}:** The optimal decision is **{optimal_order} units**.\n**Your Task:** Confirm this optimal {task_word}. Respond with a single integer."
|
| 139 |
+
|
| 140 |
elif llm_personality == 'perfect_rational' and info_sharing == 'local':
|
| 141 |
safety_stock = 4; anchor_demand = e_state['incoming_order']
|
| 142 |
inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
|
|
|
|
| 151 |
rational_local_order = max(0, int(calculated_order))
|
| 152 |
return f"**You are a perfectly rational supply chain AI with ONLY LOCAL information.**\nYou must use a logical heuristic to make a stable decision. A proven method is \"Anchoring and Adjustment\".\n\n{base_info}\n\n**Rational Calculation (Anchoring & Adjustment):**\n1. **Anchor on Demand:** Your best guess for future demand is your last incoming order: **{anchor_demand} units**.\n2. **Adjust for Inventory:** You want to hold a safety stock of {safety_stock} units. Your current stock (before shipping) is {e_state['inventory'] - e_state['backlog']}. You need to order an extra **{inventory_correction} units** to correct this.\n3. **Account for {supply_line_desc}:** You already have **{supply_line} units** being processed. These should be subtracted from your new decision.\n\n**Final Calculation:**\n* Decision = (Anchor Demand) + (Inventory Adjustment) - ({supply_line_desc})\n* Decision = {anchor_demand} + {inventory_correction} - {supply_line} = **{rational_local_order} units**.\n**Your Task:** Confirm this locally rational {task_word}. Respond with a single integer."
|
| 153 |
|
| 154 |
+
elif llm_personality == 'human_like' and info_sharing == 'full':
|
| 155 |
+
full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
|
| 156 |
+
for name, other_e_state in all_echelons_state_decision_point.items():
|
| 157 |
+
if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
|
| 158 |
+
return f"""
|
| 159 |
+
**You are a supply chain manager ({e_state['name']}) with full system visibility.**
|
| 160 |
+
You can see everyone's current inventory and backlog before shipping, and the real customer demand.
|
| 161 |
+
{base_info}
|
| 162 |
+
{full_info_str}
|
| 163 |
+
**Your Task:** Your primary responsibility is to meet the demand from your direct customer (your `Incoming order this week`: **{e_state['incoming_order']}** units), which contributes to your total current backlog of {e_state['backlog']}.
|
| 164 |
+
While you can see the stable end-customer demand ({get_customer_demand(week)} units), your priority is to fulfill the order you just received and manage your inventory/backlog.
|
| 165 |
+
You are still human and might get anxious about your own stock levels.
|
| 166 |
+
What {task_word} should you decide on this week? Respond with a single integer.
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
elif llm_personality == 'human_like' and info_sharing == 'local':
|
| 170 |
+
return f"""
|
| 171 |
+
**You are a reactive supply chain manager for the {e_state['name']}.** You have a limited view and tend to over-correct based on fear.
|
| 172 |
+
Your top priority is to NOT have a backlog.
|
| 173 |
+
{base_info}
|
| 174 |
+
**Your Task:** You just received an incoming order for **{e_state['incoming_order']}** units, adding to your total backlog.
|
| 175 |
+
Your gut instinct is to panic and {task_word.split(' ')[0]} enough to ensure you are never caught with a backlog again, considering your current inventory.
|
| 176 |
+
**React emotionally.** What is your knee-jerk {task_word}? Respond with a single integer.
|
| 177 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
|
|
|
| 179 |
def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
|
| 180 |
+
# This function's logic remains correct (from v4.17).
|
| 181 |
state = st.session_state.game_state
|
| 182 |
week, echelons, human_role = state['week'], state['echelons'], state['human_role']
|
| 183 |
llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
|
| 184 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 185 |
llm_raw_responses = {}
|
| 186 |
+
|
|
|
|
| 187 |
opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
|
| 188 |
opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
|
| 189 |
|
| 190 |
+
arrived_this_week = {name: 0 for name in echelon_order}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
inventory_after_arrival = {}
|
| 192 |
+
|
| 193 |
factory_state = echelons["Factory"]
|
| 194 |
produced_units = 0
|
| 195 |
if state['factory_production_pipeline']:
|
| 196 |
+
produced_units = state['factory_production_pipeline'].popleft()
|
| 197 |
+
arrived_this_week["Factory"] = produced_units
|
| 198 |
inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
|
| 199 |
+
|
| 200 |
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 201 |
arrived_shipment = 0
|
| 202 |
if echelons[name]['incoming_shipments']:
|
| 203 |
+
arrived_shipment = echelons[name]['incoming_shipments'].popleft()
|
| 204 |
+
arrived_this_week[name] = arrived_shipment
|
| 205 |
inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
|
| 206 |
+
|
|
|
|
| 207 |
total_backlog_before_shipping = {}
|
| 208 |
for name in echelon_order:
|
| 209 |
incoming_order_for_this_week = 0
|
|
|
|
| 213 |
if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
|
| 214 |
echelons[name]['incoming_order'] = incoming_order_for_this_week
|
| 215 |
total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
|
| 216 |
+
|
| 217 |
decision_point_states = {}
|
| 218 |
for name in echelon_order:
|
| 219 |
+
decision_point_states[name] = {
|
| 220 |
+
'name': name, 'inventory': inventory_after_arrival[name],
|
| 221 |
+
'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
|
| 222 |
+
'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
current_week_orders = {}
|
| 226 |
for name in echelon_order:
|
| 227 |
e = echelons[name]; prompt_state = decision_point_states[name]
|
|
|
|
| 230 |
prompt = get_llm_prompt(prompt_state, week, llm_personality, info_sharing, decision_point_states)
|
| 231 |
order_amount, raw_resp = get_llm_order_decision(prompt, name)
|
| 232 |
llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
|
| 233 |
+
|
| 234 |
state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
|
| 235 |
+
|
| 236 |
units_shipped = {name: 0 for name in echelon_order}
|
| 237 |
for name in echelon_order:
|
| 238 |
e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
|
| 239 |
e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
|
| 240 |
e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
|
| 241 |
+
|
| 242 |
if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
|
| 243 |
if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
|
| 244 |
if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
|
| 245 |
+
|
|
|
|
| 246 |
log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
|
| 247 |
del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
|
|
|
|
| 248 |
for name in echelon_order:
|
| 249 |
e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
|
| 250 |
for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
|
| 251 |
log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
|
| 252 |
+
log_entry[f'{name}.opening_inventory'] = opening_inventories[name]; log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
|
| 253 |
+
log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name]
|
| 254 |
+
if name != 'Factory': log_entry[f'{name}.arriving_next_week'] = list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0
|
| 255 |
+
else: log_entry[f'{name}.production_completing_next_week'] = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
|
| 257 |
state['logs'].append(log_entry)
|
| 258 |
+
|
| 259 |
state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
|
|
|
|
| 260 |
if state['week'] > WEEKS: state['game_running'] = False
|
|
|
|
|
|
|
| 261 |
|
| 262 |
def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
| 263 |
# This function remains correct.
|
|
|
|
| 289 |
axes[3].set_title(f'Analysis of Your ({human_role}) Decisions - Error Plotting Data'); axes[3].text(0.5, 0.5, f"Error: {plot_err}", ha='center', va='center'); axes[3].grid(True, linestyle='--'); axes[3].set_xlabel('Week')
|
| 290 |
plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
|
| 291 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
def save_logs_and_upload(state: dict):
|
| 293 |
+
# This function remains correct.
|
| 294 |
+
if not state.get('logs'): return
|
|
|
|
| 295 |
participant_id = state['participant_id']
|
|
|
|
| 296 |
try:
|
| 297 |
+
df = pd.json_normalize(state['logs'])
|
| 298 |
+
fname = LOCAL_LOG_DIR / f"log_{participant_id}_{int(time.time())}.csv"
|
| 299 |
+
for col in df.select_dtypes(include=['object']).columns: df[col] = df[col].astype(str)
|
| 300 |
+
df.to_csv(fname, index=False)
|
|
|
|
| 301 |
st.success(f"Log successfully saved locally: `{fname}`")
|
| 302 |
with open(fname, "rb") as f: st.download_button("📥 Download Log CSV", data=f, file_name=fname.name, mime="text/csv")
|
| 303 |
if HF_TOKEN and HF_REPO_ID and hf_api:
|
| 304 |
+
with st.spinner("Uploading log to Hugging Face Hub..."):
|
| 305 |
try:
|
| 306 |
url = hf_api.upload_file( path_or_fileobj=str(fname), path_in_repo=f"logs/{fname.name}", repo_id=HF_REPO_ID, repo_type="dataset", token=HF_TOKEN)
|
| 307 |
+
st.success(f"✅ Log successfully uploaded to Hugging Face! [View File]({url})")
|
| 308 |
except Exception as e_upload: st.error(f"Upload to Hugging Face failed: {e_upload}")
|
| 309 |
+
except Exception as e_save: st.error(f"Error processing or saving log data: {e_save}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
# -----------------------------------------------------------------------------
|
| 312 |
+
# 4. Streamlit UI (Adjusted Dashboard Labels & Logic)
|
| 313 |
# -----------------------------------------------------------------------------
|
| 314 |
st.title("🍺 The Beer Game: A Human-AI Collaboration Challenge")
|
| 315 |
|
|
|
|
| 319 |
# --- Game Setup & Instructions ---
|
| 320 |
if 'game_state' not in st.session_state or not st.session_state.game_state.get('game_running', False):
|
| 321 |
|
| 322 |
+
# --- Introduction Section Removed as Requested ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
|
| 324 |
+
st.header("⚙️ Game Configuration")
|
| 325 |
c1, c2 = st.columns(2)
|
| 326 |
with c1:
|
| 327 |
+
llm_personality = st.selectbox("AI Agent 'Personality'", ('human_like', 'perfect_rational'), format_func=lambda x: x.replace('_', ' ').title(), help="**Human-like:** Tends to react emotionally, potentially over-ordering. **Perfect Rational:** Uses a mathematical heuristic to make stable, logical decisions.")
|
| 328 |
with c2:
|
| 329 |
info_sharing = st.selectbox("Information Sharing Level", ('local', 'full'), format_func=lambda x: x.title(), help="**Local:** You and the AI agents can only see your own inventory and incoming orders. **Full:** Everyone can see the entire supply chain's status and the true end-customer demand.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
|
| 331 |
+
if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
|
| 332 |
+
init_game_state(llm_personality, info_sharing)
|
| 333 |
+
st.rerun()
|
| 334 |
|
| 335 |
# --- Main Game Interface ---
|
| 336 |
elif 'game_state' in st.session_state and st.session_state.game_state.get('game_running'):
|
| 337 |
state = st.session_state.game_state
|
| 338 |
week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
|
| 339 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Define here for UI
|
| 340 |
+
|
|
|
|
| 341 |
st.header(f"Week {week} / {WEEKS}")
|
| 342 |
+
st.subheader(f"Your Role: **{human_role}** | AI Mode: **{state['llm_personality'].replace('_', ' ')}** | Information: **{state['info_sharing']}**")
|
| 343 |
st.markdown("---")
|
| 344 |
+
|
| 345 |
+
st.subheader("Supply Chain Status (Start of Week State)") # Clarified Timing
|
| 346 |
+
|
| 347 |
if info_sharing == 'full':
|
| 348 |
cols = st.columns(4)
|
| 349 |
+
for i, name in enumerate(echelon_order): # Use the defined echelon_order
|
| 350 |
with cols[i]:
|
| 351 |
+
e = echelons[name] # Get the echelon state
|
| 352 |
icon = "👤" if name == human_role else "🤖"
|
| 353 |
+
|
| 354 |
+
# =============== UI CHANGE: Highlight Player ===============
|
| 355 |
if name == human_role:
|
| 356 |
+
# Use markdown with HTML/CSS for highlighting
|
| 357 |
st.markdown(f"##### **<span style='border: 1px solid #FF4B4B; padding: 2px 5px; border-radius: 3px;'>{icon} {name} (You)</span>**", unsafe_allow_html=True)
|
| 358 |
else:
|
| 359 |
st.markdown(f"##### {icon} {name}")
|
| 360 |
+
# ========================================================
|
| 361 |
|
| 362 |
+
# Display the END OF LAST WEEK state (which is OPENING state for this week)
|
| 363 |
st.metric("Inventory (Opening)", e['inventory'])
|
| 364 |
st.metric("Backlog (Opening)", e['backlog'])
|
| 365 |
|
| 366 |
+
# =============== UI CHANGE: Removed Costs ===============
|
| 367 |
+
# Costs are no longer displayed on the main dashboard
|
| 368 |
+
# =======================================================
|
| 369 |
+
|
| 370 |
+
# Display info about THIS week's events / NEXT week's arrivals
|
| 371 |
+
# Calculate the INCOMING order for THIS week
|
| 372 |
current_incoming_order = 0
|
| 373 |
if name == "Retailer":
|
| 374 |
current_incoming_order = get_customer_demand(week)
|
|
|
|
| 376 |
downstream_name = e['downstream_name']
|
| 377 |
if downstream_name:
|
| 378 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 379 |
+
|
| 380 |
+
st.write(f"Incoming Order (This Week): **{current_incoming_order}**") # Display calculated order
|
| 381 |
+
|
| 382 |
+
# Display prediction for NEXT week's arrivals
|
| 383 |
if name == "Factory":
|
| 384 |
+
prod_completing_next = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
|
| 385 |
st.write(f"Completing Next Week: **{prod_completing_next}**")
|
| 386 |
else:
|
| 387 |
+
arriving_next = list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
st.write(f"Arriving Next Week: **{arriving_next}**")
|
|
|
|
| 389 |
else: # Local Info Mode
|
| 390 |
st.info("In Local Information mode, you can only see your own status dashboard.")
|
| 391 |
+
e = echelons[human_role]
|
| 392 |
+
st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True) # Highlight self
|
| 393 |
+
col1, col2, col3, col4 = st.columns(4)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
|
| 395 |
+
# Display OPENING state
|
| 396 |
+
col1.metric("Inventory (Opening)", e['inventory'])
|
| 397 |
+
col2.metric("Backlog (Opening)", e['backlog'])
|
| 398 |
+
|
| 399 |
+
# Display info about THIS week's events / NEXT week's arrivals
|
| 400 |
+
# Calculate the INCOMING order for THIS week
|
| 401 |
+
current_incoming_order = 0
|
| 402 |
+
downstream_name = e['downstream_name'] # Wholesaler
|
| 403 |
+
if downstream_name:
|
| 404 |
+
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 405 |
+
|
| 406 |
+
col3.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}") # Display calculated order
|
| 407 |
+
col4.write(f"**Shipment Arriving (Next Week):**\n# {list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0}")
|
| 408 |
+
|
| 409 |
+
# =============== UI CHANGE: Removed Costs ===============
|
| 410 |
+
# Costs are no longer displayed on the main dashboard
|
| 411 |
+
# =======================================================
|
| 412 |
+
|
|
|
|
|
|
|
| 413 |
st.markdown("---")
|
| 414 |
st.header("Your Decision (Step 4)")
|
| 415 |
|
|
|
|
| 418 |
for name in echelon_order:
|
| 419 |
e_curr = echelons[name] # This is END OF LAST WEEK state
|
| 420 |
arrived = 0
|
| 421 |
+
# Peek at what *will* arrive this week (Step 1) based on current queues
|
| 422 |
if name == "Factory":
|
| 423 |
+
if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
|
| 424 |
else:
|
| 425 |
+
if e_curr['incoming_shipments']: arrived = list(e_curr['incoming_shipments'])[0]
|
| 426 |
|
| 427 |
+
# Calculate the state AFTER arrivals and incoming orders for the prompt
|
| 428 |
+
inv_after_arrival = e_curr['inventory'] + arrived
|
| 429 |
+
|
| 430 |
+
# Determine incoming order for *this* week again for prompt state
|
| 431 |
inc_order_this_week = 0
|
| 432 |
if name == "Retailer": inc_order_this_week = get_customer_demand(week)
|
| 433 |
else:
|
| 434 |
ds_name = e_curr['downstream_name']
|
| 435 |
if ds_name: inc_order_this_week = state['last_week_orders'].get(ds_name, 0)
|
| 436 |
+
|
|
|
|
| 437 |
backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
|
| 438 |
|
|
|
|
| 439 |
all_decision_point_states[name] = {
|
| 440 |
'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
|
| 441 |
+
'incoming_order': inc_order_this_week, # Use the correctly calculated incoming order
|
| 442 |
'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
|
| 443 |
}
|
| 444 |
+
|
| 445 |
human_echelon_state_for_prompt = all_decision_point_states[human_role]
|
| 446 |
|
|
|
|
| 447 |
if state['decision_step'] == 'initial_order':
|
| 448 |
with st.form(key="initial_order_form"):
|
| 449 |
st.markdown("#### **Step 4a:** Based on the dashboard, submit your **initial** order to the Factory.")
|
| 450 |
+
# =============== UI CHANGE: Removed Default Value ===============
|
| 451 |
+
initial_order = st.number_input("Your Initial Order Quantity:", min_value=0, step=1) # No 'value' argument
|
| 452 |
+
# ===============================================================
|
| 453 |
if st.form_submit_button("Submit Initial Order & See AI Suggestion", type="primary"):
|
| 454 |
+
# Handle case where user leaves it blank (input returns None)
|
| 455 |
state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
|
| 456 |
state['decision_step'] = 'final_order'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
st.rerun()
|
| 458 |
|
| 459 |
elif state['decision_step'] == 'final_order':
|
| 460 |
st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
|
| 461 |
|
| 462 |
+
# Use the correctly timed state for the prompt
|
| 463 |
+
prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, state['llm_personality'], state['info_sharing'], all_decision_point_states)
|
| 464 |
+
ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
|
| 465 |
+
|
| 466 |
with st.form(key="final_order_form"):
|
| 467 |
st.markdown(f"#### **Step 4b:** The AI suggests ordering **{ai_suggestion}** units.")
|
| 468 |
st.markdown("Considering the AI's advice, submit your **final** order to end the week. (This order will arrive in 3 weeks).")
|
| 469 |
+
# =============== UI CHANGE: Removed Default Value ===============
|
| 470 |
+
st.number_input("Your Final Order Quantity:", min_value=0, step=1, key='final_order_input') # No 'value' argument
|
| 471 |
+
# ===============================================================
|
| 472 |
|
| 473 |
if st.form_submit_button("Submit Final Order & Advance to Next Week"):
|
| 474 |
+
# Handle case where user leaves it blank
|
| 475 |
+
final_order_value = st.session_state.get('final_order_input', 0) # Use .get with default
|
| 476 |
final_order_value = int(final_order_value) if final_order_value is not None else 0
|
| 477 |
+
|
| 478 |
step_game(final_order_value, state['human_initial_order'], ai_suggestion)
|
| 479 |
|
| 480 |
+
# Clean up session state for the input key
|
| 481 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
| 482 |
st.rerun()
|
| 483 |
|
|
|
|
| 488 |
else:
|
| 489 |
try:
|
| 490 |
history_df = pd.json_normalize(state['logs'])
|
|
|
|
| 491 |
human_cols = {
|
| 492 |
'week': 'Week', f'{human_role}.opening_inventory': 'Opening Inv.',
|
| 493 |
+
f'{human_role}.opening_backlog': 'Opening Backlog', f'{human_role}.arrived_this_week': 'Arrived This Week',
|
| 494 |
f'{human_role}.incoming_order': 'Incoming Order', f'{human_role}.initial_order': 'Your Initial Order',
|
| 495 |
f'{human_role}.ai_suggestion': 'AI Suggestion', f'{human_role}.order_placed': 'Your Final Order',
|
| 496 |
f'{human_role}.arriving_next_week': 'Arriving Next Week', f'{human_role}.weekly_cost': 'Weekly Cost',
|
| 497 |
}
|
|
|
|
| 498 |
ordered_display_cols_keys = [
|
| 499 |
'week', f'{human_role}.opening_inventory', f'{human_role}.opening_backlog',
|
| 500 |
+
f'{human_role}.arrived_this_week', f'{human_role}.incoming_order',
|
| 501 |
f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed',
|
| 502 |
f'{human_role}.arriving_next_week', f'{human_role}.weekly_cost'
|
| 503 |
+
]
|
| 504 |
final_cols_to_display = [col for col in ordered_display_cols_keys if col in history_df.columns]
|
|
|
|
| 505 |
if not final_cols_to_display:
|
| 506 |
+
st.write("No data columns available to display.")
|
| 507 |
else:
|
| 508 |
display_df = history_df[final_cols_to_display].rename(columns=human_cols)
|
| 509 |
if 'Weekly Cost' in display_df.columns:
|
|
|
|
| 514 |
|
| 515 |
try: st.sidebar.image(IMAGE_PATH, caption="Supply Chain Reference")
|
| 516 |
except FileNotFoundError: st.sidebar.warning("Image file not found.")
|
|
|
|
| 517 |
st.sidebar.header("Game Info")
|
| 518 |
st.sidebar.markdown(f"**Game ID**: `{state['participant_id']}`\n\n**Current Week**: {week}")
|
| 519 |
if st.sidebar.button("🔄 Reset Game"):
|
| 520 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
|
|
|
| 521 |
del st.session_state.game_state
|
| 522 |
st.rerun()
|
| 523 |
|
|
|
|
| 533 |
state['human_role']
|
| 534 |
)
|
| 535 |
st.pyplot(fig)
|
| 536 |
+
save_logs_and_upload(state)
|
| 537 |
except Exception as e:
|
| 538 |
st.error(f"Error generating final report: {e}")
|
| 539 |
|
|
|
|
|
|
|
| 540 |
if st.button("✨ Start a New Game"):
|
| 541 |
del st.session_state.game_state
|
| 542 |
st.rerun()
|