Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
# app.py
|
| 2 |
-
# @title Beer Game Final Version (
|
|
|
|
| 3 |
# -----------------------------------------------------------------------------
|
| 4 |
# 1. Import Libraries
|
| 5 |
# -----------------------------------------------------------------------------
|
|
@@ -14,7 +15,10 @@ import random
|
|
| 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,7 +35,8 @@ INITIAL_BACKLOG = 0
|
|
| 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 |
-
|
|
|
|
| 35 |
HOLDING_COST = 0.5
|
| 36 |
BACKLOG_COST = 1.0
|
| 37 |
|
|
@@ -39,7 +44,8 @@ BACKLOG_COST = 1.0
|
|
| 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"
|
|
|
|
| 43 |
|
| 44 |
# --- API & Secrets Configuration ---
|
| 45 |
try:
|
|
@@ -56,35 +62,42 @@ else:
|
|
| 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 |
-
|
|
|
|
| 63 |
roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 64 |
human_role = "Distributor" # Role is fixed
|
| 65 |
-
|
| 66 |
st.session_state.game_state = {
|
| 67 |
-
'game_running': True,
|
|
|
|
|
|
|
| 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 |
-
'
|
|
|
|
| 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
|
|
|
|
| 88 |
|
| 89 |
def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
| 90 |
# This function remains correct.
|
|
@@ -104,15 +117,20 @@ def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
|
| 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
|
| 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
|
| 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,11 +138,15 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 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 =
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
| 128 |
safety_stock = 4
|
| 129 |
target_inventory_level = (stable_demand * total_lead_time) + safety_stock
|
| 130 |
if e_state['name'] == 'Factory':
|
|
@@ -136,7 +158,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 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,59 +173,148 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 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 |
-
|
| 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 |
def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
|
| 180 |
-
# This
|
| 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 |
-
|
|
|
|
| 202 |
if echelons[name]['incoming_shipments']:
|
| 203 |
-
|
| 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,15 +324,13 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 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 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
current_week_orders = {}
|
| 226 |
for name in echelon_order:
|
| 227 |
e = echelons[name]; prompt_state = decision_point_states[name]
|
|
@@ -230,34 +339,43 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 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 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,27 +407,134 @@ def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
|
| 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 |
-
|
| 294 |
-
|
|
|
|
| 295 |
participant_id = state['participant_id']
|
|
|
|
| 296 |
try:
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
|
|
|
| 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
|
| 308 |
except Exception as e_upload: st.error(f"Upload to Hugging Face failed: {e_upload}")
|
| 309 |
-
except Exception as e_save:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
# -----------------------------------------------------------------------------
|
| 312 |
-
# 4. Streamlit UI (
|
| 313 |
# -----------------------------------------------------------------------------
|
| 314 |
st.title("🍺 The Beer Game: A Human-AI Collaboration Challenge")
|
| 315 |
|
|
@@ -319,56 +544,75 @@ else:
|
|
| 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 |
-
|
| 323 |
-
|
| 324 |
st.header("⚙️ Game Configuration")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
c1, c2 = st.columns(2)
|
| 326 |
with c1:
|
| 327 |
-
|
| 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 |
-
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 346 |
-
|
| 347 |
if info_sharing == 'full':
|
| 348 |
cols = st.columns(4)
|
| 349 |
-
for i, name in enumerate(echelon_order):
|
| 350 |
with cols[i]:
|
| 351 |
-
e = echelons[name]
|
| 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,40 +620,87 @@ else:
|
|
| 376 |
downstream_name = e['downstream_name']
|
| 377 |
if downstream_name:
|
| 378 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
# Display prediction for NEXT week's arrivals
|
| 383 |
if name == "Factory":
|
| 384 |
-
prod_completing_next =
|
| 385 |
st.write(f"Completing Next Week: **{prod_completing_next}**")
|
| 386 |
else:
|
| 387 |
-
arriving_next =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
| 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,66 +709,63 @@ else:
|
|
| 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 |
-
|
| 424 |
else:
|
| 425 |
-
|
| 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,
|
| 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 |
-
|
| 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 |
-
#
|
| 463 |
-
|
| 464 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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,22 +776,25 @@ else:
|
|
| 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',
|
| 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}.
|
| 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 |
-
|
| 507 |
else:
|
| 508 |
display_df = history_df[final_cols_to_display].rename(columns=human_cols)
|
| 509 |
if 'Weekly Cost' in display_df.columns:
|
|
@@ -514,10 +805,12 @@ else:
|
|
| 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,10 +826,12 @@ else:
|
|
| 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()
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# @title Beer Game Final Version (v12 - v3 Base + Logic/UI Fix)
|
| 3 |
+
|
| 4 |
# -----------------------------------------------------------------------------
|
| 5 |
# 1. Import Libraries
|
| 6 |
# -----------------------------------------------------------------------------
|
|
|
|
| 15 |
import uuid
|
| 16 |
from pathlib import Path
|
| 17 |
from datetime import datetime
|
| 18 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 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 |
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 |
+
# This is CORRECT for LT=3 (1 pass + 1 produce + 1 ship = 3 week total LT)
|
| 39 |
+
FACTORY_SHIPPING_DELAY = 1
|
| 40 |
HOLDING_COST = 0.5
|
| 41 |
BACKLOG_COST = 1.0
|
| 42 |
|
|
|
|
| 44 |
OPENAI_MODEL = "gpt-4o-mini"
|
| 45 |
LOCAL_LOG_DIR = Path("logs")
|
| 46 |
LOCAL_LOG_DIR.mkdir(exist_ok=True)
|
| 47 |
+
IMAGE_PATH = "beer_game_diagram.png"
|
| 48 |
+
LEADERBOARD_FILE = "leaderboard.json"
|
| 49 |
|
| 50 |
# --- API & Secrets Configuration ---
|
| 51 |
try:
|
|
|
|
| 62 |
# -----------------------------------------------------------------------------
|
| 63 |
# 3. Core Game Logic Functions
|
| 64 |
# -----------------------------------------------------------------------------
|
| 65 |
+
|
| 66 |
def get_customer_demand(week: int) -> int:
|
| 67 |
return 4 if week <= 4 else 8
|
| 68 |
|
| 69 |
+
# =============== MODIFIED Initialization (v4.21 logic + v4.23 bugfix) ===============
|
| 70 |
+
def init_game_state(llm_personality: str, info_sharing: str, participant_id: str):
|
| 71 |
roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 72 |
human_role = "Distributor" # Role is fixed
|
| 73 |
+
|
| 74 |
st.session_state.game_state = {
|
| 75 |
+
'game_running': True,
|
| 76 |
+
'participant_id': participant_id,
|
| 77 |
+
'week': 1,
|
| 78 |
'human_role': human_role, 'llm_personality': llm_personality,
|
| 79 |
'info_sharing': info_sharing, 'logs': [], 'echelons': {},
|
| 80 |
'factory_production_pipeline': deque([0] * FACTORY_LEAD_TIME, maxlen=FACTORY_LEAD_TIME),
|
| 81 |
'decision_step': 'initial_order',
|
| 82 |
'human_initial_order': None,
|
| 83 |
+
'current_ai_suggestion': None, # v4.23 Bugfix: 用于存储AI建议
|
| 84 |
+
'last_week_orders': {name: 0 for name in roles} # v4.21 Logic: 初始化为0
|
| 85 |
}
|
| 86 |
+
|
| 87 |
for i, name in enumerate(roles):
|
| 88 |
upstream = roles[i + 1] if i + 1 < len(roles) else None
|
| 89 |
downstream = roles[i - 1] if i - 1 >= 0 else None
|
| 90 |
+
if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY # This is 1
|
| 91 |
elif name == "Factory": shipping_weeks = 0
|
| 92 |
+
else: shipping_weeks = SHIPPING_DELAY # This is 2
|
| 93 |
st.session_state.game_state['echelons'][name] = {
|
| 94 |
'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
|
| 95 |
'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
|
| 96 |
'incoming_order': 0, 'order_placed': 0, 'shipment_sent': 0,
|
| 97 |
'weekly_cost': 0, 'total_cost': 0, 'upstream_name': upstream, 'downstream_name': downstream,
|
| 98 |
}
|
| 99 |
+
st.info(f"New game started for **{participant_id}**! AI Mode: **{llm_personality} / {info_sharing}**. You are the **{human_role}**.")
|
| 100 |
+
# ==============================================================================
|
| 101 |
|
| 102 |
def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
| 103 |
# This function remains correct.
|
|
|
|
| 117 |
match = re.search(r'\d+', raw_text)
|
| 118 |
if match: return int(match.group(0)), raw_text
|
| 119 |
st.warning(f"LLM for {echelon_name} did not return a valid number. Defaulting to 4. Raw Response: '{raw_text}'")
|
| 120 |
+
return 4, raw_text
|
| 121 |
except Exception as e:
|
| 122 |
st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
|
| 123 |
return 4, f"API_ERROR: {e}"
|
| 124 |
|
| 125 |
+
# =============== PROMPT FUNCTION (v3 - Sterman Heuristic + Demand Fix) ===============
|
| 126 |
def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
|
| 127 |
+
# This function's logic is updated for "human_like" to follow a flawed Sterman heuristic.
|
| 128 |
e_state = echelon_state_decision_point
|
| 129 |
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"
|
| 130 |
+
|
| 131 |
+
# --- PROMPT FIX: Get correct demand (current, not future) ---
|
| 132 |
+
current_stable_demand = get_customer_demand(week) # Use current week's demand
|
| 133 |
+
|
| 134 |
if e_state['name'] == 'Factory':
|
| 135 |
task_word = "production quantity"
|
| 136 |
base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
|
|
|
|
| 138 |
task_word = "order quantity"
|
| 139 |
base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
|
| 140 |
|
| 141 |
+
# --- PERFECT RATIONAL (NORMATIVE) PROMPTS ---
|
| 142 |
+
|
| 143 |
if llm_personality == 'perfect_rational' and info_sharing == 'full':
|
| 144 |
+
stable_demand = current_stable_demand # Use the correct demand
|
| 145 |
+
# --------------------- LT=3 (1+1+1) ---------------------
|
| 146 |
+
if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME # 1
|
| 147 |
+
elif e_state['name'] == 'Distributor': total_lead_time = ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY # 1+1+1 = 3
|
| 148 |
+
else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY # 1+2 = 3
|
| 149 |
+
# ----------------------------------------------------
|
| 150 |
safety_stock = 4
|
| 151 |
target_inventory_level = (stable_demand * total_lead_time) + safety_stock
|
| 152 |
if e_state['name'] == 'Factory':
|
|
|
|
| 158 |
inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
|
| 159 |
optimal_order = max(0, int(target_inventory_level - inventory_position))
|
| 160 |
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."
|
| 161 |
+
|
| 162 |
elif llm_personality == 'perfect_rational' and info_sharing == 'local':
|
| 163 |
safety_stock = 4; anchor_demand = e_state['incoming_order']
|
| 164 |
inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
|
|
|
|
| 173 |
rational_local_order = max(0, int(calculated_order))
|
| 174 |
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."
|
| 175 |
|
| 176 |
+
# --- HUMAN-LIKE (DESCRIPTIVE) PROMPTS ---
|
| 177 |
+
|
| 178 |
+
else: # Catches both 'human_like' / 'local' and 'human_like' / 'full'
|
| 179 |
+
|
| 180 |
+
# This is the flawed Sterman heuristic
|
| 181 |
+
DESIRED_INVENTORY = 12 # Matches initial inventory
|
| 182 |
+
anchor_demand = e_state['incoming_order']
|
| 183 |
+
net_inventory = e_state['inventory'] - e_state['backlog']
|
| 184 |
+
stock_correction = DESIRED_INVENTORY - net_inventory
|
| 185 |
+
panicky_order = max(0, int(anchor_demand + stock_correction))
|
| 186 |
+
panicky_order_calc = f"{anchor_demand} (Your Incoming Order) + {stock_correction} (Your Stock Correction)"
|
| 187 |
+
|
| 188 |
+
# Get supply line info *just to show* the AI it's being ignored
|
| 189 |
+
if e_state['name'] == 'Factory':
|
| 190 |
+
supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
|
| 191 |
+
supply_line_desc = "In Production"
|
| 192 |
+
else:
|
| 193 |
+
order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
|
| 194 |
+
supply_line = sum(e_state['incoming_shipments']) + order_in_transit_to_supplier
|
| 195 |
+
supply_line_desc = "Supply Line"
|
| 196 |
+
|
| 197 |
+
if info_sharing == 'local':
|
| 198 |
+
return f"""
|
| 199 |
+
**You are a reactive supply chain manager for the {e_state['name']}.** You have a limited (local) view.
|
| 200 |
+
You tend to make **reactive, 'gut-instinct' decisions** (like the classic Sterman 1989 model) that cause the Bullwhip Effect.
|
| 201 |
+
|
| 202 |
+
{base_info}
|
| 203 |
+
|
| 204 |
+
**Your Flawed 'Human' Heuristic:**
|
| 205 |
+
Your gut tells you to fix your entire inventory problem *right now*, and you're afraid of your backlog.
|
| 206 |
+
A 'rational' player would account for their {supply_line_desc} (which is {supply_line} units), but you're too busy panicking to trust that.
|
| 207 |
+
|
| 208 |
+
**Your 'Panic' Calculation (Ignoring the Supply Line):**
|
| 209 |
+
1. **Anchor on Demand:** You just got an order for **{anchor_demand}** units. You'll order *at least* that.
|
| 210 |
+
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.
|
| 211 |
+
3. **Ignore Supply Line:** You'll ignore the **{supply_line} units** already in your pipeline.
|
| 212 |
+
|
| 213 |
+
**Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
|
| 214 |
+
* Order = {panicky_order_calc} = **{panicky_order} units**.
|
| 215 |
+
|
| 216 |
+
**Your Task:** Confirm this 'gut-instinct' {task_word}. Respond with a single integer.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
elif info_sharing == 'full':
|
| 220 |
+
# Build the "Full Info" string just for context
|
| 221 |
+
full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {current_stable_demand} units.\n"
|
| 222 |
+
for name, other_e_state in all_echelons_state_decision_point.items():
|
| 223 |
+
if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
|
| 224 |
+
|
| 225 |
+
return f"""
|
| 226 |
+
**You are a supply chain manager ({e_state['name']}) with full system visibility.**
|
| 227 |
+
{base_info}
|
| 228 |
+
{full_info_str}
|
| 229 |
+
|
| 230 |
+
**A "Human-like" Flawed Decision:**
|
| 231 |
+
Even though you have full information, you are judged by *your own* performance (your inventory, your backlog).
|
| 232 |
+
You tend to react to your *local* situation (like the classic Sterman 1989 model) instead of using the complex full-system data.
|
| 233 |
+
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.
|
| 234 |
+
|
| 235 |
+
**Your 'Panic' Calculation (Ignoring Full Info and Your Supply Line):**
|
| 236 |
+
1. **Anchor on *Your* Demand:** You just got an order for **{anchor_demand}** units. You react to this, not the end-customer demand.
|
| 237 |
+
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.
|
| 238 |
+
3. **Ignore *Your* Supply Line:** You'll ignore the **{supply_line} units** in your own pipeline ({supply_line_desc}).
|
| 239 |
+
|
| 240 |
+
**Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
|
| 241 |
+
* Order = {panicky_order_calc} = **{panicky_order} units**.
|
| 242 |
+
|
| 243 |
+
**Your Task:** Confirm this 'gut-instinct', locally-focused {task_word}. Respond with a single integer.
|
| 244 |
+
"""
|
| 245 |
+
# =========================================================
|
| 246 |
|
| 247 |
+
# =============== STEP_GAME (v12) - Stable Logic + Correct Log Fix ===============
|
| 248 |
def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
|
| 249 |
+
# This is the correct logic from v4.17
|
| 250 |
state = st.session_state.game_state
|
| 251 |
week, echelons, human_role = state['week'], state['echelons'], state['human_role']
|
| 252 |
llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
|
| 253 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 254 |
llm_raw_responses = {}
|
| 255 |
+
|
| 256 |
+
# Capture opening state for logging
|
| 257 |
opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
|
| 258 |
opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
|
| 259 |
|
| 260 |
+
# --- LOG FIX (v12): Capture arrival data BEFORE mutation ---
|
| 261 |
arrived_this_week = {name: 0 for name in echelon_order}
|
| 262 |
+
# This dict will store the value shown on the UI for "next week"
|
| 263 |
+
opening_arriving_next_week_UI_VALUE = {name: 0 for name in echelon_order}
|
| 264 |
+
|
| 265 |
+
# Factory
|
| 266 |
+
factory_q = state['factory_production_pipeline']
|
| 267 |
+
if factory_q:
|
| 268 |
+
arrived_this_week["Factory"] = factory_q[0] # Read before pop
|
| 269 |
+
# "Next Week" for Factory is the order it just received (Distributor's last week order)
|
| 270 |
+
opening_arriving_next_week_UI_VALUE["Factory"] = state['last_week_orders'].get("Distributor", 0)
|
| 271 |
+
|
| 272 |
+
# R, W, D
|
| 273 |
+
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 274 |
+
shipment_q = echelons[name]['incoming_shipments']
|
| 275 |
+
if shipment_q:
|
| 276 |
+
arrived_this_week[name] = shipment_q[0] # Read before pop
|
| 277 |
+
|
| 278 |
+
# --- THIS IS THE REAL FIX V12 ---
|
| 279 |
+
if name == 'Distributor':
|
| 280 |
+
# "Next" for Distributor (maxlen=1) is the item that will arrive W+1
|
| 281 |
+
# At the start of W4, shipping_q = [4] (from W2). This item arrives W5.
|
| 282 |
+
# So, "Arriving Next Week" (W5) IS shipment_q[0].
|
| 283 |
+
if shipment_q:
|
| 284 |
+
opening_arriving_next_week_UI_VALUE[name] = shipment_q[0]
|
| 285 |
+
elif name in ("Retailer", "Wholesaler"):
|
| 286 |
+
# "Next" for R/W (maxlen=2) is the item that will arrive W+1
|
| 287 |
+
# At start of W4, shipping_q = [0, 4]. [0] arrives W5, [1] arrives W6.
|
| 288 |
+
# "Arriving Next Week" (W5) IS shipment_q[0].
|
| 289 |
+
# (Wait, no, [0] arrives W4, [1] arrives W5)
|
| 290 |
+
# (Let's re-trace R/W)
|
| 291 |
+
# W2: D ships 4. R/W q.append(4) -> [0, 4]
|
| 292 |
+
# W3: R/W popleft() -> 0 arrives. q = [4].
|
| 293 |
+
# W3: D ships 8. R/W q.append(8) -> [4, 8]
|
| 294 |
+
# W4: R/W popleft() -> 4 arrives. q = [8].
|
| 295 |
+
# At start of W4, "Arriving Next Week" (W5) is q[0] = 8.
|
| 296 |
+
if shipment_q:
|
| 297 |
+
opening_arriving_next_week_UI_VALUE[name] = shipment_q[0]
|
| 298 |
+
# --- END OF LOG FIX (v12) ---
|
| 299 |
+
|
| 300 |
+
# Now, the *actual* state mutation (popping)
|
| 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 |
inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
|
| 307 |
+
|
| 308 |
+
# --- LOGIC FIX (v12) ---
|
| 309 |
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 310 |
+
# Use the value we captured *before* popping
|
| 311 |
+
arrived_shipment = arrived_this_week[name]
|
| 312 |
if echelons[name]['incoming_shipments']:
|
| 313 |
+
echelons[name]['incoming_shipments'].popleft() # Now we pop
|
|
|
|
| 314 |
inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
|
| 315 |
+
# --- END LOGIC FIX (v12) ---
|
| 316 |
+
|
| 317 |
+
# (Rest of game logic)
|
| 318 |
total_backlog_before_shipping = {}
|
| 319 |
for name in echelon_order:
|
| 320 |
incoming_order_for_this_week = 0
|
|
|
|
| 324 |
if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
|
| 325 |
echelons[name]['incoming_order'] = incoming_order_for_this_week
|
| 326 |
total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
|
|
|
|
| 327 |
decision_point_states = {}
|
| 328 |
for name in echelon_order:
|
| 329 |
+
decision_point_states[name] = {
|
| 330 |
+
'name': name, 'inventory': inventory_after_arrival[name],
|
| 331 |
+
'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
|
| 332 |
+
'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
|
| 333 |
+
}
|
|
|
|
| 334 |
current_week_orders = {}
|
| 335 |
for name in echelon_order:
|
| 336 |
e = echelons[name]; prompt_state = decision_point_states[name]
|
|
|
|
| 339 |
prompt = get_llm_prompt(prompt_state, week, llm_personality, info_sharing, decision_point_states)
|
| 340 |
order_amount, raw_resp = get_llm_order_decision(prompt, name)
|
| 341 |
llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
|
|
|
|
| 342 |
state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
|
|
|
|
| 343 |
units_shipped = {name: 0 for name in echelon_order}
|
| 344 |
for name in echelon_order:
|
| 345 |
e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
|
| 346 |
e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
|
| 347 |
e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
|
|
|
|
| 348 |
if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
|
| 349 |
if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
|
| 350 |
if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
|
| 351 |
+
|
| 352 |
+
# (Logging)
|
| 353 |
log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
|
| 354 |
del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
|
| 355 |
+
if 'current_ai_suggestion' in log_entry: del log_entry['current_ai_suggestion']
|
| 356 |
for name in echelon_order:
|
| 357 |
e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
|
| 358 |
for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
|
| 359 |
log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
|
| 360 |
+
|
| 361 |
+
# --- LOG FIX (v12): Use captured values ---
|
| 362 |
+
log_entry[f'{name}.opening_inventory'] = opening_inventories[name]
|
| 363 |
+
log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
|
| 364 |
+
log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name] # Use captured value
|
| 365 |
+
|
| 366 |
+
if name != 'Factory':
|
| 367 |
+
log_entry[f'{name}.arriving_next_week'] = opening_arriving_next_week_UI_VALUE[name]
|
| 368 |
+
else:
|
| 369 |
+
log_entry[f'{name}.production_completing_next_week'] = opening_arriving_next_week_UI_VALUE[name]
|
| 370 |
+
# --- END OF LOG FIX (v12) ---
|
| 371 |
+
|
| 372 |
log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
|
| 373 |
state['logs'].append(log_entry)
|
|
|
|
| 374 |
state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
|
| 375 |
+
state['current_ai_suggestion'] = None # Clean up
|
| 376 |
if state['week'] > WEEKS: state['game_running'] = False
|
| 377 |
+
# ==============================================================================
|
| 378 |
+
|
| 379 |
|
| 380 |
def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
| 381 |
# This function remains correct.
|
|
|
|
| 407 |
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')
|
| 408 |
plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
|
| 409 |
|
| 410 |
+
|
| 411 |
+
# =============== NEW: Leaderboard Functions ===============
|
| 412 |
+
@st.cache_data(ttl=60)
|
| 413 |
+
def load_leaderboard_data():
|
| 414 |
+
if not hf_api or not HF_REPO_ID: return {}
|
| 415 |
+
try:
|
| 416 |
+
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")
|
| 417 |
+
with open(local_path, 'r', encoding='utf-8') as f: return json.load(f)
|
| 418 |
+
except EntryNotFoundError:
|
| 419 |
+
st.sidebar.info("Leaderboard file not found. A new one will be created.")
|
| 420 |
+
return {}
|
| 421 |
+
except Exception as e:
|
| 422 |
+
st.sidebar.error(f"Could not load leaderboard: {e}")
|
| 423 |
+
return {}
|
| 424 |
+
|
| 425 |
+
def save_leaderboard_data(data):
|
| 426 |
+
if not hf_api or not HF_REPO_ID or not HF_TOKEN: return
|
| 427 |
+
try:
|
| 428 |
+
local_path = LOCAL_LOG_DIR / LEADERBOARD_FILE
|
| 429 |
+
with open(local_path, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2, ensure_ascii=False)
|
| 430 |
+
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")
|
| 431 |
+
st.sidebar.success("Leaderboard updated!")
|
| 432 |
+
st.cache_data.clear()
|
| 433 |
+
except Exception as e:
|
| 434 |
+
st.sidebar.error(f"Failed to upload leaderboard: {e}")
|
| 435 |
+
|
| 436 |
+
def display_rankings(df, top_n=10):
|
| 437 |
+
if df.empty:
|
| 438 |
+
st.info("No completed games for this category yet. Be the first!")
|
| 439 |
+
return
|
| 440 |
+
df['total_cost'] = pd.to_numeric(df['total_cost'], errors='coerce')
|
| 441 |
+
df['order_std_dev'] = pd.to_numeric(df['order_std_dev'], errors='coerce')
|
| 442 |
+
df = df.dropna(subset=['total_cost', 'order_std_dev'])
|
| 443 |
+
if df.empty:
|
| 444 |
+
st.info("No valid completed games for this category yet.")
|
| 445 |
+
return
|
| 446 |
+
c1, c2, c3 = st.columns(3)
|
| 447 |
+
with c1:
|
| 448 |
+
st.subheader("🏆 Supply Chain Champions")
|
| 449 |
+
st.caption(f"Top {top_n} - Lowest Total Cost")
|
| 450 |
+
champs_df = df.sort_values('total_cost', ascending=True).head(top_n).copy()
|
| 451 |
+
champs_df['total_cost'] = champs_df['total_cost'].map('${:,.2f}'.format)
|
| 452 |
+
champs_df.rename(columns={'id': 'Participant', 'total_cost': 'Total Cost'}, inplace=True)
|
| 453 |
+
st.dataframe(champs_df[['Participant', 'Total Cost']], use_container_width=True, hide_index=True)
|
| 454 |
+
with c2:
|
| 455 |
+
st.subheader("👑 Bullwhip Kings")
|
| 456 |
+
st.caption(f"Top {top_n} - Highest Total Cost")
|
| 457 |
+
kings_df = df.sort_values('total_cost', ascending=False).head(top_n).copy()
|
| 458 |
+
kings_df['total_cost'] = kings_df['total_cost'].map('${:,.2f}'.format)
|
| 459 |
+
kings_df.rename(columns={'id': 'Participant', 'total_cost': 'Total Cost'}, inplace=True)
|
| 460 |
+
st.dataframe(kings_df[['Participant', 'Total Cost']], use_container_width=True, hide_index=True)
|
| 461 |
+
with c3:
|
| 462 |
+
st.subheader("🧘 Mr. Smooth")
|
| 463 |
+
st.caption(f"Top {top_n} - Lowest Order Variation (Std. Dev.)")
|
| 464 |
+
smooth_df = df.sort_values('order_std_dev', ascending=True).head(top_n).copy()
|
| 465 |
+
smooth_df['order_std_dev'] = smooth_df['order_std_dev'].map('{:,.2f}'.format)
|
| 466 |
+
smooth_df.rename(columns={'id': 'Participant', 'order_std_dev': 'Order Std. Dev.'}, inplace=True)
|
| 467 |
+
st.dataframe(smooth_df[['Participant', 'Order Std. Dev.']], use_container_width=True, hide_index=True)
|
| 468 |
+
|
| 469 |
+
def show_leaderboard_ui():
|
| 470 |
+
st.markdown("---")
|
| 471 |
+
st.header("📊 The Bullwhip Leaderboard")
|
| 472 |
+
st.caption("Leaderboard updates after you finish a game. Cached for 60 seconds.")
|
| 473 |
+
leaderboard_data = load_leaderboard_data()
|
| 474 |
+
if not leaderboard_data:
|
| 475 |
+
st.info("No leaderboard data yet. Be the first to finish a game!")
|
| 476 |
+
else:
|
| 477 |
+
try:
|
| 478 |
+
df = pd.DataFrame(leaderboard_data.values())
|
| 479 |
+
if 'id' not in df.columns and not df.empty: df['id'] = list(leaderboard_data.keys())
|
| 480 |
+
if 'total_cost' not in df.columns or 'order_std_dev' not in df.columns or 'setting' not in df.columns:
|
| 481 |
+
st.error("Leaderboard data is corrupted or incomplete.")
|
| 482 |
+
return
|
| 483 |
+
groups = sorted(df.setting.unique())
|
| 484 |
+
tabs = st.tabs(["**Overall**"] + groups)
|
| 485 |
+
with tabs[0]: display_rankings(df)
|
| 486 |
+
for i, group_name in enumerate(groups):
|
| 487 |
+
with tabs[i+1]:
|
| 488 |
+
df_group = df[df.setting == group_name].copy()
|
| 489 |
+
display_rankings(df_group)
|
| 490 |
+
except Exception as e:
|
| 491 |
+
st.error(f"Error displaying leaderboard: {e}")
|
| 492 |
+
st.dataframe(leaderboard_data)
|
| 493 |
+
|
| 494 |
def save_logs_and_upload(state: dict):
|
| 495 |
+
if not state.get('logs'):
|
| 496 |
+
st.warning("No log data to save.")
|
| 497 |
+
return
|
| 498 |
participant_id = state['participant_id']
|
| 499 |
+
logs_df = None
|
| 500 |
try:
|
| 501 |
+
logs_df = pd.json_normalize(state['logs'])
|
| 502 |
+
safe_participant_id = re.sub(r'[^a-zA-Z0-9_-]', '_', participant_id)
|
| 503 |
+
fname = LOCAL_LOG_DIR / f"log_{safe_participant_id}_{int(time.time())}.csv"
|
| 504 |
+
for col in logs_df.select_dtypes(include=['object']).columns: logs_df[col] = logs_df[col].astype(str)
|
| 505 |
+
logs_df.to_csv(fname, index=False)
|
| 506 |
st.success(f"Log successfully saved locally: `{fname}`")
|
| 507 |
with open(fname, "rb") as f: st.download_button("📥 Download Log CSV", data=f, file_name=fname.name, mime="text/csv")
|
| 508 |
if HF_TOKEN and HF_REPO_ID and hf_api:
|
| 509 |
+
with st.spinner("Uploading log CSV to Hugging Face Hub..."):
|
| 510 |
try:
|
| 511 |
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)
|
| 512 |
+
st.success(f"✅ Log CSV successfully uploaded! [View File]({url})")
|
| 513 |
except Exception as e_upload: st.error(f"Upload to Hugging Face failed: {e_upload}")
|
| 514 |
+
except Exception as e_save:
|
| 515 |
+
st.error(f"Error processing or saving log CSV: {e_save}")
|
| 516 |
+
return
|
| 517 |
+
if logs_df is None: return
|
| 518 |
+
st.subheader("Updating Leaderboard...")
|
| 519 |
+
try:
|
| 520 |
+
human_role = state['human_role']
|
| 521 |
+
total_cost = logs_df[f'{human_role}.total_cost'].iloc[-1]
|
| 522 |
+
order_std_dev = logs_df[f'{human_role}.order_placed'].std()
|
| 523 |
+
setting_name = f"{state['llm_personality']} / {state['info_sharing']}"
|
| 524 |
+
new_entry = {
|
| 525 |
+
'id': participant_id, 'setting': setting_name,
|
| 526 |
+
'total_cost': float(total_cost),
|
| 527 |
+
'order_std_dev': float(order_std_dev) if pd.notna(order_std_dev) else 0.0
|
| 528 |
+
}
|
| 529 |
+
leaderboard_data = load_leaderboard_data()
|
| 530 |
+
leaderboard_data[participant_id] = new_entry
|
| 531 |
+
save_leaderboard_data(leaderboard_data)
|
| 532 |
+
except Exception as e_board:
|
| 533 |
+
st.error(f"Error calculating or saving leaderboard score: {e_board}")
|
| 534 |
+
# ==============================================================================
|
| 535 |
|
| 536 |
# -----------------------------------------------------------------------------
|
| 537 |
+
# 4. Streamlit UI (Applying v4.22 + v4.23 fixes)
|
| 538 |
# -----------------------------------------------------------------------------
|
| 539 |
st.title("🍺 The Beer Game: A Human-AI Collaboration Challenge")
|
| 540 |
|
|
|
|
| 544 |
# --- Game Setup & Instructions ---
|
| 545 |
if 'game_state' not in st.session_state or not st.session_state.game_state.get('game_running', False):
|
| 546 |
|
| 547 |
+
st.markdown("---")
|
|
|
|
| 548 |
st.header("⚙️ Game Configuration")
|
| 549 |
+
|
| 550 |
+
# =============== NEW: Participant ID Input ===============
|
| 551 |
+
participant_id = st.text_input("Enter Your Name or Team ID:", key="participant_id_input", placeholder="e.g., Team A")
|
| 552 |
+
# =======================================================
|
| 553 |
+
|
| 554 |
c1, c2 = st.columns(2)
|
| 555 |
with c1:
|
| 556 |
+
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.")
|
| 557 |
with c2:
|
| 558 |
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.")
|
| 559 |
+
|
| 560 |
+
# =============== MODIFIED: Start Game Button ===============
|
| 561 |
if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
|
| 562 |
+
if not participant_id:
|
| 563 |
+
st.error("Please enter a Name or Team ID to start!")
|
| 564 |
+
else:
|
| 565 |
+
existing_data = load_leaderboard_data()
|
| 566 |
+
if participant_id in existing_data:
|
| 567 |
+
# 如果ID已存在,添加一个session_state标志,要求再次点击
|
| 568 |
+
if st.session_state.get('last_id_warning') == participant_id:
|
| 569 |
+
# 这是第二次点击,确认覆盖
|
| 570 |
+
st.session_state.pop('last_id_warning', None)
|
| 571 |
+
init_game_state(llm_personality, info_sharing, participant_id)
|
| 572 |
+
st.rerun()
|
| 573 |
+
else:
|
| 574 |
+
st.session_state['last_id_warning'] = participant_id
|
| 575 |
+
st.warning(f"ID '{participant_id}' already exists! Your score will be overwritten. Click 'Start Game' again to confirm.")
|
| 576 |
+
else:
|
| 577 |
+
# 新ID,直接开始
|
| 578 |
+
if 'last_id_warning' in st.session_state:
|
| 579 |
+
del st.session_state['last_id_warning']
|
| 580 |
+
init_game_state(llm_personality, info_sharing, participant_id)
|
| 581 |
+
st.rerun()
|
| 582 |
+
# ===========================================================
|
| 583 |
+
|
| 584 |
+
# =============== NEW: Show Leaderboard on Start Page ===============
|
| 585 |
+
show_leaderboard_ui()
|
| 586 |
+
# =================================================================
|
| 587 |
|
| 588 |
# --- Main Game Interface ---
|
| 589 |
elif 'game_state' in st.session_state and st.session_state.game_state.get('game_running'):
|
| 590 |
state = st.session_state.game_state
|
| 591 |
week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
|
| 592 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Define here for UI
|
| 593 |
+
|
| 594 |
+
|
| 595 |
st.header(f"Week {week} / {WEEKS}")
|
| 596 |
+
st.subheader(f"Your Role: **{human_role}** ({state['participant_id']}) | AI Mode: **{state['llm_personality'].replace('_', ' ')}** | Information: **{state['info_sharing']}**")
|
| 597 |
st.markdown("---")
|
| 598 |
+
st.subheader("Supply Chain Status (Start of Week State)")
|
| 599 |
+
|
| 600 |
+
# =============== MODIFIED UI LOGIC (v12) ===============
|
| 601 |
if info_sharing == 'full':
|
| 602 |
cols = st.columns(4)
|
| 603 |
+
for i, name in enumerate(echelon_order):
|
| 604 |
with cols[i]:
|
| 605 |
+
e = echelons[name]
|
| 606 |
icon = "👤" if name == human_role else "🤖"
|
| 607 |
+
|
|
|
|
| 608 |
if name == human_role:
|
|
|
|
| 609 |
st.markdown(f"##### **<span style='border: 1px solid #FF4B4B; padding: 2px 5px; border-radius: 3px;'>{icon} {name} (You)</span>**", unsafe_allow_html=True)
|
| 610 |
else:
|
| 611 |
st.markdown(f"##### {icon} {name}")
|
|
|
|
| 612 |
|
|
|
|
| 613 |
st.metric("Inventory (Opening)", e['inventory'])
|
| 614 |
st.metric("Backlog (Opening)", e['backlog'])
|
| 615 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 616 |
current_incoming_order = 0
|
| 617 |
if name == "Retailer":
|
| 618 |
current_incoming_order = get_customer_demand(week)
|
|
|
|
| 620 |
downstream_name = e['downstream_name']
|
| 621 |
if downstream_name:
|
| 622 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 623 |
+
st.write(f"Incoming Order (This Week): **{current_incoming_order}**")
|
| 624 |
+
|
|
|
|
|
|
|
| 625 |
if name == "Factory":
|
| 626 |
+
prod_completing_next = state['last_week_orders'].get("Distributor", 0)
|
| 627 |
st.write(f"Completing Next Week: **{prod_completing_next}**")
|
| 628 |
else:
|
| 629 |
+
arriving_next = 0
|
| 630 |
+
|
| 631 |
+
# --- UI FIX V12 ---
|
| 632 |
+
q = e['incoming_shipments']
|
| 633 |
+
if name == 'Distributor':
|
| 634 |
+
# "Next" for Distributor (maxlen=1) is q[0]
|
| 635 |
+
if q: arriving_next = list(q)[0]
|
| 636 |
+
elif name in ('Wholesaler', 'Retailer'):
|
| 637 |
+
# "Next" for R/W (maxlen=2) is q[0]
|
| 638 |
+
# No, it's q[1].
|
| 639 |
+
# W3: q=[4,8]. ArrivedThisWeek=4. ArrivingNextWeek=8
|
| 640 |
+
# We pop 4. q=[8].
|
| 641 |
+
# W4: q=[8]. ArrivedThisWeek=8.
|
| 642 |
+
if len(q) > 1:
|
| 643 |
+
arriving_next = list(q)[1] # Read W+2
|
| 644 |
+
|
| 645 |
+
# Let's retry R/W logic
|
| 646 |
+
# W3: q=[4,8]. ArrivedThisWeek=4 (from [0]). ANW=8 (from [1])
|
| 647 |
+
# W4: D ships 16. q.popleft() (4). q.append(16). q=[8,16]
|
| 648 |
+
# W4 start: ArrivedThisWeek=8 (from [0]). ANW=16 (from [1])
|
| 649 |
+
if len(q) > 1:
|
| 650 |
+
arriving_next = list(q)[1]
|
| 651 |
+
|
| 652 |
+
# Let's retry Distributor logic (maxlen=1)
|
| 653 |
+
# W3: F ships 4. q.append(4). q=[4]
|
| 654 |
+
# W4: ArrivedThisWeek=4 (from [0]). ANW=??
|
| 655 |
+
# W4: F ships 8. q.popleft() (4). q.append(8). q=[8]
|
| 656 |
+
# W5: ArrivedThisWeek=8 (from [0]).
|
| 657 |
+
# "Arriving Next Week" for Distributor (W+1) is ALWAYS list(q)[0]
|
| 658 |
+
if q: arriving_next = list(q)[0]
|
| 659 |
+
|
| 660 |
+
# --- RETHINK UI V12 ---
|
| 661 |
+
# For R/W (maxlen=2), q[0] is W+1, q[1] is W+2
|
| 662 |
+
# For D (maxlen=1), q[0] is W+1
|
| 663 |
+
|
| 664 |
+
if name in ('Wholesaler', 'Retailer'):
|
| 665 |
+
q = e['incoming_shipments']
|
| 666 |
+
if q: arriving_next = list(q)[0] # Read W+1
|
| 667 |
+
elif name == 'Distributor':
|
| 668 |
+
q = e['incoming_shipments']
|
| 669 |
+
if q: arriving_next = list(q)[0] # Read W+1
|
| 670 |
+
# --- END RETHINK V12 ---
|
| 671 |
+
|
| 672 |
st.write(f"Arriving Next Week: **{arriving_next}**")
|
| 673 |
+
|
| 674 |
else: # Local Info Mode
|
| 675 |
st.info("In Local Information mode, you can only see your own status dashboard.")
|
| 676 |
+
e = echelons[human_role] # Distributor
|
| 677 |
+
st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 678 |
|
| 679 |
+
col1, col2, col3 = st.columns(3)
|
| 680 |
+
with col1:
|
| 681 |
+
st.metric("Inventory (Opening)", e['inventory'])
|
| 682 |
+
st.metric("Backlog (Opening)", e['backlog'])
|
| 683 |
+
|
| 684 |
+
with col2:
|
| 685 |
+
current_incoming_order = 0
|
| 686 |
+
downstream_name = e['downstream_name'] # Wholesaler
|
| 687 |
+
if downstream_name:
|
| 688 |
+
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 689 |
+
st.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
|
| 690 |
+
|
| 691 |
+
with col3:
|
| 692 |
+
# --------------------- LOCAL UI FIX V12 ---------------------
|
| 693 |
+
# "Arriving Next Week" for Distributor in LOCAL mode.
|
| 694 |
+
# Read W+1 item from its own shipping queue
|
| 695 |
+
arriving_next = 0
|
| 696 |
+
q = e['incoming_shipments']
|
| 697 |
+
if q:
|
| 698 |
+
arriving_next = list(q)[0]
|
| 699 |
+
st.write(f"**Shipment Arriving (Next Week):**\n# {arriving_next}")
|
| 700 |
+
# -----------------------------------------------------------
|
| 701 |
+
|
| 702 |
+
# =======================================================
|
| 703 |
+
|
| 704 |
st.markdown("---")
|
| 705 |
st.header("Your Decision (Step 4)")
|
| 706 |
|
|
|
|
| 709 |
for name in echelon_order:
|
| 710 |
e_curr = echelons[name] # This is END OF LAST WEEK state
|
| 711 |
arrived = 0
|
|
|
|
| 712 |
if name == "Factory":
|
| 713 |
+
if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
|
| 714 |
else:
|
| 715 |
+
if e_curr['incoming_shipments']: arrived = list(e_curr['incoming_shipments'])[0]
|
|
|
|
|
|
|
|
|
|
| 716 |
|
|
|
|
| 717 |
inc_order_this_week = 0
|
| 718 |
if name == "Retailer": inc_order_this_week = get_customer_demand(week)
|
| 719 |
else:
|
| 720 |
ds_name = e_curr['downstream_name']
|
| 721 |
if ds_name: inc_order_this_week = state['last_week_orders'].get(ds_name, 0)
|
| 722 |
+
|
| 723 |
+
inv_after_arrival = e_curr['inventory'] + arrived
|
| 724 |
backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
|
| 725 |
|
| 726 |
+
# This is the state used for the prompt, it's calculated BEFORE the pop
|
| 727 |
all_decision_point_states[name] = {
|
| 728 |
'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
|
| 729 |
+
'incoming_order': inc_order_this_week,
|
| 730 |
'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
|
| 731 |
}
|
|
|
|
| 732 |
human_echelon_state_for_prompt = all_decision_point_states[human_role]
|
| 733 |
|
| 734 |
+
|
| 735 |
if state['decision_step'] == 'initial_order':
|
| 736 |
with st.form(key="initial_order_form"):
|
| 737 |
st.markdown("#### **Step 4a:** Based on the dashboard, submit your **initial** order to the Factory.")
|
| 738 |
+
initial_order = st.number_input("Your Initial Order Quantity:", min_value=0, step=1, value=None) # Start blank
|
|
|
|
|
|
|
| 739 |
if st.form_submit_button("Submit Initial Order & See AI Suggestion", type="primary"):
|
|
|
|
| 740 |
state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
|
| 741 |
state['decision_step'] = 'final_order'
|
| 742 |
+
|
| 743 |
+
# --- NEW: Calculate and store suggestion ONCE ---
|
| 744 |
+
prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, state['llm_personality'], state['info_sharing'], all_decision_point_states)
|
| 745 |
+
ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
|
| 746 |
+
state['current_ai_suggestion'] = ai_suggestion # Store it
|
| 747 |
+
# ------------------------------------------------
|
| 748 |
+
|
| 749 |
st.rerun()
|
| 750 |
|
| 751 |
elif state['decision_step'] == 'final_order':
|
| 752 |
st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
|
| 753 |
|
| 754 |
+
# --- NEW: Read stored suggestion ---
|
| 755 |
+
ai_suggestion = state.get('current_ai_suggestion', 4) # Read stored value
|
| 756 |
+
# -----------------------------------
|
| 757 |
+
|
| 758 |
with st.form(key="final_order_form"):
|
| 759 |
st.markdown(f"#### **Step 4b:** The AI suggests ordering **{ai_suggestion}** units.")
|
| 760 |
st.markdown("Considering the AI's advice, submit your **final** order to end the week. (This order will arrive in 3 weeks).")
|
| 761 |
+
st.number_input("Your Final Order Quantity:", min_value=0, step=1, key='final_order_input', value=None) # Start blank
|
|
|
|
|
|
|
| 762 |
|
| 763 |
if st.form_submit_button("Submit Final Order & Advance to Next Week"):
|
| 764 |
+
final_order_value = st.session_state.get('final_order_input', 0)
|
|
|
|
| 765 |
final_order_value = int(final_order_value) if final_order_value is not None else 0
|
| 766 |
+
|
| 767 |
step_game(final_order_value, state['human_initial_order'], ai_suggestion)
|
| 768 |
|
|
|
|
| 769 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
| 770 |
st.rerun()
|
| 771 |
|
|
|
|
| 776 |
else:
|
| 777 |
try:
|
| 778 |
history_df = pd.json_normalize(state['logs'])
|
| 779 |
+
# FIX: Removed 'Arrived This Week' from log UI
|
| 780 |
human_cols = {
|
| 781 |
'week': 'Week', f'{human_role}.opening_inventory': 'Opening Inv.',
|
| 782 |
+
f'{human_role}.opening_backlog': 'Opening Backlog',
|
| 783 |
f'{human_role}.incoming_order': 'Incoming Order', f'{human_role}.initial_order': 'Your Initial Order',
|
| 784 |
f'{human_role}.ai_suggestion': 'AI Suggestion', f'{human_role}.order_placed': 'Your Final Order',
|
| 785 |
f'{human_role}.arriving_next_week': 'Arriving Next Week', f'{human_role}.weekly_cost': 'Weekly Cost',
|
| 786 |
}
|
| 787 |
+
# FIX: Removed 'Arrived This Week' from log UI
|
| 788 |
ordered_display_cols_keys = [
|
| 789 |
'week', f'{human_role}.opening_inventory', f'{human_role}.opening_backlog',
|
| 790 |
+
f'{human_role}.incoming_order',
|
| 791 |
f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed',
|
| 792 |
f'{human_role}.arriving_next_week', f'{human_role}.weekly_cost'
|
| 793 |
+
]
|
| 794 |
final_cols_to_display = [col for col in ordered_display_cols_keys if col in history_df.columns]
|
| 795 |
+
|
| 796 |
if not final_cols_to_display:
|
| 797 |
+
st.write("No data columns available to display.")
|
| 798 |
else:
|
| 799 |
display_df = history_df[final_cols_to_display].rename(columns=human_cols)
|
| 800 |
if 'Weekly Cost' in display_df.columns:
|
|
|
|
| 805 |
|
| 806 |
try: st.sidebar.image(IMAGE_PATH, caption="Supply Chain Reference")
|
| 807 |
except FileNotFoundError: st.sidebar.warning("Image file not found.")
|
| 808 |
+
|
| 809 |
st.sidebar.header("Game Info")
|
| 810 |
st.sidebar.markdown(f"**Game ID**: `{state['participant_id']}`\n\n**Current Week**: {week}")
|
| 811 |
if st.sidebar.button("🔄 Reset Game"):
|
| 812 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
| 813 |
+
if 'current_ai_suggestion' in st.session_state.game_state: del st.session_state.game_state['current_ai_suggestion']
|
| 814 |
del st.session_state.game_state
|
| 815 |
st.rerun()
|
| 816 |
|
|
|
|
| 826 |
state['human_role']
|
| 827 |
)
|
| 828 |
st.pyplot(fig)
|
| 829 |
+
save_logs_and_upload(state) # This now also updates the leaderboard
|
| 830 |
except Exception as e:
|
| 831 |
st.error(f"Error generating final report: {e}")
|
| 832 |
|
| 833 |
+
show_leaderboard_ui()
|
| 834 |
+
|
| 835 |
if st.button("✨ Start a New Game"):
|
| 836 |
del st.session_state.game_state
|
| 837 |
st.rerun()
|