Lilli98 commited on
Commit
887375d
·
verified ·
1 Parent(s): de81e80

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +227 -306
app.py CHANGED
@@ -1,6 +1,5 @@
1
  # app.py
2
  # @title Beer Game Final Version (v12 - v3 Base + Logic/UI Fix)
3
-
4
  # -----------------------------------------------------------------------------
5
  # 1. Import Libraries
6
  # -----------------------------------------------------------------------------
@@ -47,9 +46,17 @@ 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:
52
- client = openai.OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
 
53
  HF_TOKEN = st.secrets.get("HF_TOKEN")
54
  HF_REPO_ID = st.secrets.get("HF_REPO_ID")
55
  hf_api = HfApi() if HF_TOKEN else None
@@ -58,11 +65,9 @@ except Exception as e:
58
  client = None
59
  else:
60
  st.session_state.initialization_error = None
61
-
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
 
@@ -70,7 +75,7 @@ def get_customer_demand(week: int) -> int:
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,
@@ -83,7 +88,6 @@ def init_game_state(llm_personality: str, info_sharing: str, participant_id: str
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
@@ -98,9 +102,9 @@ def init_game_state(llm_personality: str, info_sharing: str, participant_id: str
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.
 
104
  if not client: return 8, "NO_API_KEY_DEFAULT"
105
  with st.spinner(f"Getting AI decision for {echelon_name}..."):
106
  try:
@@ -121,7 +125,6 @@ def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
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 (v4 - FIXES FOR OSCILLATION AND HUMAN-LIKE) ===============
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.
@@ -136,7 +139,6 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
136
  else:
137
  task_word = "order quantity"
138
  base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
139
-
140
  # --- PERFECT RATIONAL (NORMATIVE) PROMPTS ---
141
 
142
  if llm_personality == 'perfect_rational' and info_sharing == 'full':
@@ -161,7 +163,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
161
  supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
162
  inventory_position = (e_state['inventory'] - e_state['backlog'] + supply_line)
163
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InProd={supply_line})"
164
-
165
  elif e_state['name'] == 'Distributor':
166
  # Distributor pipeline: In Shipping (1 week) + In Production (1 week) + Order Delay (1 week)
167
  in_shipping = sum(e_state['incoming_shipments'])
@@ -169,17 +171,16 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
169
  supply_line = in_shipping + in_production + order_in_transit_to_supplier
170
  inventory_position = (e_state['inventory'] - e_state['backlog'] + supply_line)
171
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={in_shipping} + InProd={in_production} + OrderToSupplier={order_in_transit_to_supplier})"
172
-
173
  else: # Retailer and Wholesaler
174
  # R/W pipeline: In Shipping (2 weeks) + Order Delay (1 week)
175
  in_shipping = sum(e_state['incoming_shipments'])
176
  supply_line = in_shipping + order_in_transit_to_supplier
177
  inventory_position = (e_state['inventory'] - e_state['backlog'] + supply_line)
178
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={in_shipping} + OrderToSupplier={order_in_transit_to_supplier})"
179
-
180
  optimal_order = max(0, int(target_inventory_level - inventory_position))
181
  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."
182
-
183
  elif llm_personality == 'perfect_rational' and info_sharing == 'local':
184
  safety_stock = 4
185
  anchor_demand = e_state['incoming_order']
@@ -190,7 +191,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
190
  # Factory can see its full (local) pipeline
191
  supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
192
  supply_line_desc = "In Production"
193
-
194
  elif e_state['name'] == 'Distributor':
195
  # Distributor can *only* see its shipping queue (1 week)
196
  # It CANNOT see the factory pipeline or its own order delay
@@ -209,7 +210,6 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
209
  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 (that you can see). 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."
210
 
211
  # --- HUMAN-LIKE (DESCRIPTIVE) PROMPTS ---
212
-
213
  else:
214
  DESIRED_INVENTORY = 12 # Matches initial inventory
215
  net_inventory = e_state['inventory'] - e_state['backlog']
@@ -230,28 +230,24 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
230
  anchor_demand = e_state['incoming_order']
231
  panicky_order = max(0, int(anchor_demand + stock_correction))
232
  panicky_order_calc = f"{anchor_demand} (Your Incoming Order) + {stock_correction} (Your Stock Correction)"
233
-
234
  return f"""
235
  **You are a reactive supply chain manager for the {e_state['name']}.** You have a limited (local) view.
236
  You tend to make **reactive, 'gut-instinct' decisions** (like the classic Sterman 1989 model) that cause the Bullwhip Effect.
237
-
238
  {base_info}
239
-
240
  **Your Flawed 'Human' Heuristic:**
241
  Your gut tells you to fix your entire inventory problem *right now*, and you're afraid of your backlog.
242
  A 'rational' player would account for their {supply_line_desc} (which is {supply_line} units), but you're too busy panicking to trust that.
243
-
244
  **Your 'Panic' Calculation (Ignoring the Supply Line):**
245
  1. **Anchor on Demand:** You just got an order for **{anchor_demand}** units. You'll order *at least* that.
246
  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.
247
  3. **Ignore Supply Line:** You'll ignore the **{supply_line} units** already in your pipeline.
248
-
249
  **Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
250
  * Order = {panicky_order_calc} = **{panicky_order} units**.
251
-
252
  **Your Task:** Confirm this 'gut-instinct' {task_word}. Respond with a single integer.
253
  """
254
-
255
  elif info_sharing == 'full':
256
  # 1. HUMAN-LIKE / FULL (FIX v6): Anchors on an *average* of local panic and global reality
257
  local_anchor = e_state['incoming_order']
@@ -262,35 +258,30 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
262
 
263
  panicky_order = max(0, int(anchor_demand + stock_correction))
264
  panicky_order_calc = f"{anchor_demand} (Conflicted Anchor) + {stock_correction} (Your Stock Correction)"
265
-
266
  # Build the "Full Info" string just for context
267
  full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {current_stable_demand} units.\n"
268
  for name, other_e_state in all_echelons_state_decision_point.items():
269
  if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
270
-
271
  return f"""
272
  **You are a supply chain manager ({e_state['name']}) with full system visibility.**
273
  {base_info}
274
  {full_info_str}
275
-
276
  **A "Human-like" Flawed Decision:**
277
  You are judged by *your own* performance. You can see the stable End-Customer Demand is **{global_anchor}**, but you just received a panicky order for **{local_anchor}**.
278
  Your "gut-instinct" is to split the difference, anchoring on an average of the two.
279
  You still ignore your supply line, focusing only on your local stock.
280
-
281
  **Your 'Panic' Calculation (Ignoring Supply Line, Averaging Anchors):**
282
  1. **Anchor on Conflict:** (Your Incoming Order + End-Customer Demand) / 2
283
  * Anchor = ({local_anchor} + {global_anchor}) / 2 = **{anchor_demand}** units.
284
  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.
285
  3. **Ignore *Your* Supply Line:** You'll ignore the **{supply_line} units** in your own pipeline ({supply_line_desc}).
286
-
287
  **Final Panic Order:** (Conflicted Anchor) + (Your Stock Correction)
288
  * Order = {panicky_order_calc} = **{panicky_order} units**.
289
-
290
  **Your Task:** Confirm this 'gut-instinct', locally-focused {task_word}. Respond with a single integer.
291
  """
292
  # =========================================================
293
-
294
  # =============== STEP_GAME (v12) - Stable Logic + Correct Log Fix ===============
295
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
296
  # This is the correct logic from v4.17
@@ -299,51 +290,37 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
299
  llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
300
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
301
  llm_raw_responses = {}
302
-
303
  # Capture opening state for logging
304
  opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
305
  opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
306
-
307
  # --- LOG FIX (v12): Capture arrival data BEFORE mutation ---
308
  arrived_this_week = {name: 0 for name in echelon_order}
309
  # This dict will store the value shown on the UI for "next week"
310
  opening_arriving_next_week_UI_VALUE = {name: 0 for name in echelon_order}
311
-
312
  # Factory
313
  factory_q = state['factory_production_pipeline']
314
  if factory_q:
315
  arrived_this_week["Factory"] = factory_q[0] # Read before pop
316
  # "Next Week" for Factory is the order it just received (Distributor's last week order)
317
  opening_arriving_next_week_UI_VALUE["Factory"] = state['last_week_orders'].get("Distributor", 0)
318
-
319
  # R, W, D
320
  for name in ["Retailer", "Wholesaler", "Distributor"]:
321
  shipment_q = echelons[name]['incoming_shipments']
322
  if shipment_q:
323
  arrived_this_week[name] = shipment_q[0] # Read before pop
324
-
325
  # --- THIS IS THE REAL FIX V12 ---
326
  if name == 'Distributor':
327
  # "Next" for Distributor (maxlen=1) is the item that will arrive W+1
328
- # At the start of W4, shipping_q = [4] (from W2). This item arrives W5.
329
- # So, "Arriving Next Week" (W5) IS shipment_q[0].
330
  if shipment_q:
331
  opening_arriving_next_week_UI_VALUE[name] = shipment_q[0]
332
  elif name in ("Retailer", "Wholesaler"):
333
  # "Next" for R/W (maxlen=2) is the item that will arrive W+1
334
- # At start of W4, shipping_q = [0, 4]. [0] arrives W5, [1] arrives W6.
335
- # "Arriving Next Week" (W5) IS shipment_q[0].
336
- # (Wait, no, [0] arrives W4, [1] arrives W5)
337
- # (Let's re-trace R/W)
338
- # W2: D ships 4. R/W q.append(4) -> [0, 4]
339
- # W3: R/W popleft() -> 0 arrives. q = [4].
340
- # W3: D ships 8. R/W q.append(8) -> [4, 8]
341
- # W4: R/W popleft() -> 4 arrives. q = [8].
342
- # At start of W4, "Arriving Next Week" (W5) is q[0] = 8.
343
  if shipment_q:
344
  opening_arriving_next_week_UI_VALUE[name] = shipment_q[0]
345
  # --- END OF LOG FIX (v12) ---
346
-
347
  # Now, the *actual* state mutation (popping)
348
  inventory_after_arrival = {}
349
  factory_state = echelons["Factory"]
@@ -351,7 +328,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
351
  if state['factory_production_pipeline']:
352
  produced_units = state['factory_production_pipeline'].popleft()
353
  inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
354
-
355
  # --- LOGIC FIX (v12) ---
356
  for name in ["Retailer", "Wholesaler", "Distributor"]:
357
  # Use the value we captured *before* popping
@@ -360,7 +337,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
360
  echelons[name]['incoming_shipments'].popleft() # Now we pop
361
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
362
  # --- END LOGIC FIX (v12) ---
363
-
364
  # (Rest of game logic)
365
  total_backlog_before_shipping = {}
366
  for name in echelon_order:
@@ -371,6 +348,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
371
  if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
372
  echelons[name]['incoming_order'] = incoming_order_for_this_week
373
  total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
 
374
  decision_point_states = {}
375
  for name in echelon_order:
376
  decision_point_states[name] = {
@@ -386,16 +364,19 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
386
  prompt = get_llm_prompt(prompt_state, week, llm_personality, info_sharing, decision_point_states)
387
  order_amount, raw_resp = get_llm_order_decision(prompt, name)
388
  llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
 
389
  state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
 
390
  units_shipped = {name: 0 for name in echelon_order}
391
  for name in echelon_order:
392
  e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
393
  e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
394
  e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
 
395
  if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
396
  if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
397
  if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
398
-
399
  # (Logging)
400
  log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
401
  del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
@@ -404,26 +385,24 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
404
  e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
405
  for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
406
  log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
407
-
408
  # --- LOG FIX (v12): Use captured values ---
409
  log_entry[f'{name}.opening_inventory'] = opening_inventories[name]
410
  log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
411
  log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name] # Use captured value
412
-
413
  if name != 'Factory':
414
  log_entry[f'{name}.arriving_next_week'] = opening_arriving_next_week_UI_VALUE[name]
415
  else:
416
  log_entry[f'{name}.production_completing_next_week'] = opening_arriving_next_week_UI_VALUE[name]
417
  # --- END OF LOG FIX (v12) ---
418
-
419
- log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
420
  state['logs'].append(log_entry)
421
  state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
422
  state['current_ai_suggestion'] = None # Clean up
423
  if state['week'] > WEEKS: state['game_running'] = False
424
  # ==============================================================================
425
-
426
-
427
  def plot_results(df: pd.DataFrame, title: str, human_role: str):
428
  # This function remains correct.
429
  fig, axes = plt.subplots(4, 1, figsize=(12, 22))
@@ -453,8 +432,6 @@ def plot_results(df: pd.DataFrame, title: str, human_role: str):
453
  except (KeyError, ValueError) as plot_err:
454
  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')
455
  plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
456
-
457
-
458
  # =============== NEW: Leaderboard Functions (MODIFIED) ===============
459
  @st.cache_data(ttl=60)
460
  def load_leaderboard_data():
@@ -468,7 +445,6 @@ def load_leaderboard_data():
468
  except Exception as e:
469
  st.sidebar.error(f"Could not load leaderboard: {e}")
470
  return {}
471
-
472
  def save_leaderboard_data(data):
473
  if not hf_api or not HF_REPO_ID or not HF_TOKEN: return
474
  try:
@@ -479,20 +455,17 @@ def save_leaderboard_data(data):
479
  st.cache_data.clear()
480
  except Exception as e:
481
  st.sidebar.error(f"Failed to upload leaderboard: {e}")
482
-
483
  # ---------- MODIFIED FUNCTION (v2) ----------
484
  def display_rankings(df, top_n=10):
485
  if df.empty:
486
  st.info("No completed games for this category yet. Be the first!")
487
  return
488
-
489
  # 为新旧数据列进行数值转换
490
  df['distributor_cost'] = pd.to_numeric(df.get('total_cost'), errors='coerce') # 'total_cost' 是旧的 distributor_cost
491
  df['total_chain_cost'] = pd.to_numeric(df.get('total_chain_cost'), errors='coerce')
492
  df['order_std_dev'] = pd.to_numeric(df.get('order_std_dev'), errors='coerce')
493
-
494
  c1, c2, c3 = st.columns(3)
495
-
496
  # 排行榜 1: 总供应链成本 (新)
497
  with c1:
498
  st.subheader("🏆 Supply Chain Champions")
@@ -505,33 +478,30 @@ def display_rankings(df, top_n=10):
505
  champs_df['total_chain_cost'] = champs_df['total_chain_cost'].map('${:,.2f}'.format)
506
  champs_df.rename(columns={'id': 'Participant', 'total_chain_cost': 'Total Chain Cost'}, inplace=True)
507
  st.dataframe(champs_df[['Participant', 'Total Chain Cost']], use_container_width=True, hide_index=True)
508
-
509
  # 排行榜 2: 你的 (Distributor) 成本 (修改)
510
  with c2:
511
  st.subheader("👤 Distributor Champions")
512
  st.caption(f"Top {top_n} - Lowest **Your** (Distributor) Cost")
513
  dist_df = df.dropna(subset=['distributor_cost']).sort_values('distributor_cost', ascending=True).head(top_n).copy()
514
-
515
  if dist_df.empty:
516
  st.info("No data for this category yet.")
517
  else:
518
  dist_df['distributor_cost'] = dist_df['distributor_cost'].map('${:,.2f}'.format)
519
  dist_df.rename(columns={'id': 'Participant', 'distributor_cost': 'Your Cost'}, inplace=True)
520
  st.dataframe(dist_df[['Participant', 'Your Cost']], use_container_width=True, hide_index=True)
521
-
522
  # 排行榜 3: 订单平滑度 (不变)
523
  with c3:
524
  st.subheader("🧘 Mr. Smooth")
525
  st.caption(f"Top {top_n} - Lowest Order Variation (Std. Dev.)")
526
  smooth_df = df.dropna(subset=['order_std_dev']).sort_values('order_std_dev', ascending=True).head(top_n).copy()
527
-
528
  if smooth_df.empty:
529
  st.info("No data for this category yet.")
530
  else:
531
  smooth_df['order_std_dev'] = smooth_df['order_std_dev'].map('{:,.2f}'.format)
532
  smooth_df.rename(columns={'id': 'Participant', 'order_std_dev': 'Order Std. Dev.'}, inplace=True)
533
  st.dataframe(smooth_df[['Participant', 'Order Std. Dev.']], use_container_width=True, hide_index=True)
534
-
535
  def show_leaderboard_ui():
536
  st.markdown("---")
537
  st.header("📊 The Bullwhip Leaderboard")
@@ -543,12 +513,12 @@ def show_leaderboard_ui():
543
  try:
544
  df = pd.DataFrame(leaderboard_data.values())
545
  if 'id' not in df.columns and not df.empty: df['id'] = list(leaderboard_data.keys())
546
-
547
  # 检查旧列是否存在即可
548
  if 'total_cost' not in df.columns or 'order_std_dev' not in df.columns or 'setting' not in df.columns:
549
  st.error("Leaderboard data is corrupted or incomplete.")
550
  return
551
-
552
  groups = sorted(df.setting.unique())
553
  tabs = st.tabs(["**Overall**"] + groups)
554
  with tabs[0]: display_rankings(df)
@@ -559,7 +529,6 @@ def show_leaderboard_ui():
559
  except Exception as e:
560
  st.error(f"Error displaying leaderboard: {e}")
561
  st.dataframe(leaderboard_data)
562
-
563
  # ---------- MODIFIED FUNCTION (v2) ----------
564
  def save_logs_and_upload(state: dict):
565
  if not state.get('logs'):
@@ -588,21 +557,21 @@ def save_logs_and_upload(state: dict):
588
  st.subheader("Updating Leaderboard...")
589
  try:
590
  human_role = state['human_role']
591
-
592
  # 1. 计算你的 (Distributor) 成本
593
  distributor_cost = logs_df[f'{human_role}.total_cost'].iloc[-1]
594
-
595
  # 2. 计算总供应链成本
596
  r_cost = logs_df['Retailer.total_cost'].iloc[-1]
597
  w_cost = logs_df['Wholesaler.total_cost'].iloc[-1]
598
  f_cost = logs_df['Factory.total_cost'].iloc[-1]
599
  total_chain_cost = r_cost + w_cost + distributor_cost + f_cost
600
-
601
  # 3. 计算订单标准差
602
  order_std_dev = logs_df[f'{human_role}.order_placed'].std()
603
-
604
  setting_name = f"{state['llm_personality']} / {state['info_sharing']}"
605
-
606
  # 4. 创建新的条目
607
  new_entry = {
608
  'id': participant_id,
@@ -611,20 +580,18 @@ def save_logs_and_upload(state: dict):
611
  'total_chain_cost': float(total_chain_cost), # 新增: 总成本
612
  'order_std_dev': float(order_std_dev) if pd.notna(order_std_dev) else 0.0
613
  }
614
-
615
  leaderboard_data = load_leaderboard_data()
616
  leaderboard_data[participant_id] = new_entry
617
  save_leaderboard_data(leaderboard_data)
618
-
619
  except Exception as e_board:
620
  st.error(f"Error calculating or saving leaderboard score: {e_board}")
621
  # ==============================================================================
622
-
623
  # -----------------------------------------------------------------------------
624
  # 4. Streamlit UI (Applying v4.22 + v4.23 fixes)
625
  # -----------------------------------------------------------------------------
626
  st.title("🍺 The Beer Game: A Human-AI Collaboration Challenge")
627
-
628
  if st.session_state.get('initialization_error'):
629
  st.error(st.session_state.initialization_error)
630
  else:
@@ -634,16 +601,27 @@ else:
634
  st.markdown("---")
635
  st.header("⚙️ Game Configuration")
636
 
637
- # =============== NEW: Participant ID Input ===============
638
  participant_id = st.text_input("Enter Your Name or Team ID:", key="participant_id_input", placeholder="e.g., Team A")
639
  # =======================================================
640
 
641
- c1, c2 = st.columns(2)
642
- with c1:
643
- 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.")
644
- with c2:
645
- 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.")
646
-
 
 
 
 
 
 
 
 
 
 
 
647
  # =============== MODIFIED: Start Game Button ===============
648
  if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
649
  if not participant_id:
@@ -655,7 +633,7 @@ else:
655
  if st.session_state.get('last_id_warning') == participant_id:
656
  # 这是第二次点击,确认覆盖
657
  st.session_state.pop('last_id_warning', None)
658
- init_game_state(llm_personality, info_sharing, participant_id)
659
  st.rerun()
660
  else:
661
  st.session_state['last_id_warning'] = participant_id
@@ -664,242 +642,187 @@ else:
664
  # 新ID,直接开始
665
  if 'last_id_warning' in st.session_state:
666
  del st.session_state['last_id_warning']
667
- init_game_state(llm_personality, info_sharing, participant_id)
668
  st.rerun()
669
  # ===========================================================
670
 
671
  # =============== NEW: Show Leaderboard on Start Page ===============
672
  show_leaderboard_ui()
673
  # =================================================================
674
-
675
  # --- Main Game Interface ---
676
  elif 'game_state' in st.session_state and st.session_state.game_state.get('game_running'):
677
  state = st.session_state.game_state
678
  week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
679
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Define here for UI
680
-
681
-
682
- st.header(f"Week {week} / {WEEKS}")
683
- st.subheader(f"Your Role: **{human_role}** ({state['participant_id']}) | AI Mode: **{state['llm_personality'].replace('_', ' ')}** | Information: **{state['info_sharing']}**")
684
- st.markdown("---")
685
- st.subheader("Supply Chain Status (Start of Week State)")
686
-
687
- # =============== MODIFIED UI LOGIC (v12) ===============
688
- if info_sharing == 'full':
689
- cols = st.columns(4)
690
- for i, name in enumerate(echelon_order):
691
- with cols[i]:
692
- e = echelons[name]
693
- icon = "👤" if name == human_role else "🤖"
694
-
695
- if name == human_role:
696
- st.markdown(f"##### **<span style='border: 1px solid #FF4B4B; padding: 2px 5px; border-radius: 3px;'>{icon} {name} (You)</span>**", unsafe_allow_html=True)
697
- else:
698
- st.markdown(f"##### {icon} {name}")
699
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
700
  st.metric("Inventory (Opening)", e['inventory'])
701
  st.metric("Backlog (Opening)", e['backlog'])
702
-
 
703
  current_incoming_order = 0
704
- if name == "Retailer":
705
- current_incoming_order = get_customer_demand(week)
706
- else:
707
- downstream_name = e['downstream_name']
708
- if downstream_name:
709
- current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
710
- st.write(f"Incoming Order (This Week): **{current_incoming_order}**")
711
-
712
- if name == "Factory":
713
- prod_completing_next = state['last_week_orders'].get("Distributor", 0)
714
- st.write(f"Completing Next Week: **{prod_completing_next}**")
715
- else:
716
- arriving_next = 0
717
-
718
- # --- UI FIX V12 ---
719
- q = e['incoming_shipments']
720
- if name == 'Distributor':
721
- # "Next" for Distributor (maxlen=1) is q[0]
722
- if q: arriving_next = list(q)[0]
723
- elif name in ('Wholesaler', 'Retailer'):
724
- # "Next" for R/W (maxlen=2) is q[0]
725
- # No, it's q[1].
726
- # W3: q=[4,8]. ArrivedThisWeek=4. ArrivingNextWeek=8
727
- # We pop 4. q=[8].
728
- # W4: q=[8]. ArrivedThisWeek=8.
729
- if len(q) > 1:
730
- arriving_next = list(q)[1] # Read W+2
731
 
732
- # Let's retry R/W logic
733
- # W3: q=[4,8]. ArrivedThisWeek=4 (from [0]). ANW=8 (from [1])
734
- # W4: D ships 16. q.popleft() (4). q.append(16). q=[8,16]
735
- # W4 start: ArrivedThisWeek=8 (from [0]). ANW=16 (from [1])
736
- if len(q) > 1:
737
- arriving_next = list(q)[1]
 
738
 
739
- # Let's retry Distributor logic (maxlen=1)
740
- # W3: F ships 4. q.append(4). q=[4]
741
- # W4: ArrivedThisWeek=4 (from [0]). ANW=??
742
- # W4: F ships 8. q.popleft() (4). q.append(8). q=[8]
743
- # W5: ArrivedThisWeek=8 (from [0]).
744
- # "Arriving Next Week" for Distributor (W+1) is ALWAYS list(q)[0]
745
- if q: arriving_next = list(q)[0]
746
-
747
- # --- RETHINK UI V12 ---
748
- # For R/W (maxlen=2), q[0] is W+1, q[1] is W+2
749
- # For D (maxlen=1), q[0] is W+1
750
-
751
- if name in ('Wholesaler', 'Retailer'):
752
- q = e['incoming_shipments']
753
- if q: arriving_next = list(q)[0] # Read W+1
754
- elif name == 'Distributor':
755
- q = e['incoming_shipments']
756
- if q: arriving_next = list(q)[0] # Read W+1
757
- # --- END RETHINK V12 ---
758
-
759
- st.write(f"Arriving Next Week: **{arriving_next}**")
760
-
761
- else: # Local Info Mode
762
- st.info("In Local Information mode, you can only see your own status dashboard.")
763
- e = echelons[human_role] # Distributor
764
- st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True)
765
-
766
- col1, col2, col3 = st.columns(3)
767
- with col1:
768
- st.metric("Inventory (Opening)", e['inventory'])
769
- st.metric("Backlog (Opening)", e['backlog'])
770
-
771
- with col2:
772
- current_incoming_order = 0
773
- downstream_name = e['downstream_name'] # Wholesaler
774
- if downstream_name:
775
- current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
776
- st.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
777
-
778
- with col3:
779
- # --------------------- LOCAL UI FIX V12 ---------------------
780
- # "Arriving Next Week" for Distributor in LOCAL mode.
781
- # Read W+1 item from its own shipping queue
782
- arriving_next = 0
783
- q = e['incoming_shipments']
784
- if q:
785
- arriving_next = list(q)[0]
786
- st.write(f"**Shipment Arriving (Next Week):**\n# {arriving_next}")
787
- # -----------------------------------------------------------
788
-
789
- # =======================================================
790
-
791
- st.markdown("---")
792
- st.header("Your Decision (Step 4)")
793
-
794
- # Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
795
- all_decision_point_states = {}
796
- for name in echelon_order:
797
- e_curr = echelons[name] # This is END OF LAST WEEK state
798
- arrived = 0
799
- if name == "Factory":
800
- if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
801
- else:
802
- if e_curr['incoming_shipments']: arrived = list(e_curr['incoming_shipments'])[0]
803
 
804
- inc_order_this_week = 0
805
- if name == "Retailer": inc_order_this_week = get_customer_demand(week)
806
- else:
807
- ds_name = e_curr['downstream_name']
808
- if ds_name: inc_order_this_week = state['last_week_orders'].get(ds_name, 0)
809
-
810
- inv_after_arrival = e_curr['inventory'] + arrived
811
- backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
812
 
813
- # This is the state used for the prompt, it's calculated BEFORE the pop
814
- all_decision_point_states[name] = {
815
- 'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
816
- 'incoming_order': inc_order_this_week,
817
- 'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
818
- }
819
- human_echelon_state_for_prompt = all_decision_point_states[human_role]
820
-
821
-
822
- if state['decision_step'] == 'initial_order':
823
- with st.form(key="initial_order_form"):
824
- st.markdown("#### **Step 4a:** Based on the dashboard, submit your **initial** order to the Factory.")
825
- initial_order = st.number_input("Your Initial Order Quantity:", min_value=0, step=1, value=None) # Start blank
826
- if st.form_submit_button("Submit Initial Order & See AI Suggestion", type="primary"):
827
- state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
828
- state['decision_step'] = 'final_order'
829
-
830
- # --- NEW: Calculate and store suggestion ONCE ---
831
- prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, state['llm_personality'], state['info_sharing'], all_decision_point_states)
832
- ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
833
- state['current_ai_suggestion'] = ai_suggestion # Store it
834
- # ------------------------------------------------
835
-
836
- st.rerun()
837
-
838
- elif state['decision_step'] == 'final_order':
839
- st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
 
 
 
 
 
 
 
 
 
 
 
 
840
 
841
- # --- NEW: Read stored suggestion ---
842
- ai_suggestion = state.get('current_ai_suggestion', 4) # Read stored value
843
- # -----------------------------------
844
-
845
- with st.form(key="final_order_form"):
846
- st.markdown(f"#### **Step 4b:** The AI suggests ordering **{ai_suggestion}** units.")
847
- st.markdown("Considering the AI's advice, submit your **final** order to end the week. (This order will arrive in 3 weeks).")
848
- st.number_input("Your Final Order Quantity:", min_value=0, step=1, key='final_order_input', value=None) # Start blank
849
-
850
- if st.form_submit_button("Submit Final Order & Advance to Next Week"):
851
- final_order_value = st.session_state.get('final_order_input', 0)
852
- final_order_value = int(final_order_value) if final_order_value is not None else 0
853
-
854
- step_game(final_order_value, state['human_initial_order'], ai_suggestion)
855
-
856
- if 'final_order_input' in st.session_state: del st.session_state.final_order_input
857
- st.rerun()
858
-
859
- st.markdown("---")
860
- with st.expander("📖 Your Weekly Decision Log", expanded=False):
861
- if not state.get('logs'):
862
- st.write("Your weekly history will be displayed here after you complete the first week.")
863
- else:
864
- try:
865
- history_df = pd.json_normalize(state['logs'])
866
- # FIX: Removed 'Arrived This Week' from log UI
867
- human_cols = {
868
- 'week': 'Week', f'{human_role}.opening_inventory': 'Opening Inv.',
869
- f'{human_role}.opening_backlog': 'Opening Backlog',
870
- f'{human_role}.incoming_order': 'Incoming Order', f'{human_role}.initial_order': 'Your Initial Order',
871
- f'{human_role}.ai_suggestion': 'AI Suggestion', f'{human_role}.order_placed': 'Your Final Order',
872
- f'{human_role}.arriving_next_week': 'Arriving Next Week', f'{human_role}.weekly_cost': 'Weekly Cost',
873
- }
874
- # FIX: Removed 'Arrived This Week' from log UI
875
- ordered_display_cols_keys = [
876
- 'week', f'{human_role}.opening_inventory', f'{human_role}.opening_backlog',
877
- f'{human_role}.incoming_order',
878
- f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed',
879
- f'{human_role}.arriving_next_week', f'{human_role}.weekly_cost'
880
- ]
881
- final_cols_to_display = [col for col in ordered_display_cols_keys if col in history_df.columns]
882
-
883
- if not final_cols_to_display:
884
- st.write("No data columns available to display.")
885
- else:
886
- display_df = history_df[final_cols_to_display].rename(columns=human_cols)
887
- if 'Weekly Cost' in display_df.columns:
888
- display_df['Weekly Cost'] = display_df['Weekly Cost'].apply(lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "")
889
- st.dataframe(display_df.sort_values(by="Week", ascending=False), hide_index=True, use_container_width=True)
890
- except Exception as e:
891
- st.error(f"Error displaying weekly log: {e}")
892
-
893
- try: st.sidebar.image(IMAGE_PATH, caption="Supply Chain Reference")
894
- except FileNotFoundError: st.sidebar.warning("Image file not found.")
895
-
896
- st.sidebar.header("Game Info")
897
- st.sidebar.markdown(f"**Game ID**: `{state['participant_id']}`\n\n**Current Week**: {week}")
898
- if st.sidebar.button("🔄 Reset Game"):
899
- if 'final_order_input' in st.session_state: del st.session_state.final_order_input
900
- if 'current_ai_suggestion' in st.session_state.game_state: del st.session_state.game_state['current_ai_suggestion']
901
- del st.session_state.game_state
902
- st.rerun()
903
 
904
  # --- Game Over Interface ---
905
  if 'game_state' in st.session_state and not st.session_state.game_state.get('game_running', False) and st.session_state.game_state['week'] > WEEKS:
@@ -916,9 +839,7 @@ else:
916
  save_logs_and_upload(state) # This now also updates the leaderboard
917
  except Exception as e:
918
  st.error(f"Error generating final report: {e}")
919
-
920
  show_leaderboard_ui()
921
-
922
  if st.button("✨ Start a New Game"):
923
  del st.session_state.game_state
924
  st.rerun()
 
1
  # app.py
2
  # @title Beer Game Final Version (v12 - v3 Base + Logic/UI Fix)
 
3
  # -----------------------------------------------------------------------------
4
  # 1. Import Libraries
5
  # -----------------------------------------------------------------------------
 
46
  IMAGE_PATH = "beer_game_diagram.png"
47
  LEADERBOARD_FILE = "leaderboard.json"
48
 
49
+ # --- 实验条件配置:新增常量 ---
50
+ EXPERIMENT_SETTINGS = [
51
+ ('human_like', 'local'),
52
+ ('human_like', 'full'),
53
+ ('perfect_rational', 'local'),
54
+ ('perfect_rational', 'full'),
55
+ ]
56
  # --- API & Secrets Configuration ---
57
  try:
58
+ # 注意:在多Space部署中,每个Space的secrets中只放一个API KEY
59
+ client = openai.OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
60
  HF_TOKEN = st.secrets.get("HF_TOKEN")
61
  HF_REPO_ID = st.secrets.get("HF_REPO_ID")
62
  hf_api = HfApi() if HF_TOKEN else None
 
65
  client = None
66
  else:
67
  st.session_state.initialization_error = None
 
68
  # -----------------------------------------------------------------------------
69
  # 3. Core Game Logic Functions
70
  # -----------------------------------------------------------------------------
 
71
  def get_customer_demand(week: int) -> int:
72
  return 4 if week <= 4 else 8
73
 
 
75
  def init_game_state(llm_personality: str, info_sharing: str, participant_id: str):
76
  roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
77
  human_role = "Distributor" # Role is fixed
78
+
79
  st.session_state.game_state = {
80
  'game_running': True,
81
  'participant_id': participant_id,
 
88
  'current_ai_suggestion': None, # v4.23 Bugfix: 用于存储AI建议
89
  'last_week_orders': {name: 0 for name in roles} # v4.21 Logic: 初始化为0
90
  }
 
91
  for i, name in enumerate(roles):
92
  upstream = roles[i + 1] if i + 1 < len(roles) else None
93
  downstream = roles[i - 1] if i - 1 >= 0 else None
 
102
  }
103
  st.info(f"New game started for **{participant_id}**! AI Mode: **{llm_personality} / {info_sharing}**. You are the **{human_role}**.")
104
  # ==============================================================================
 
105
  def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
106
  # This function remains correct.
107
+ # 注意:client 现在是全局的,所有用户的API请求都通过它进行。
108
  if not client: return 8, "NO_API_KEY_DEFAULT"
109
  with st.spinner(f"Getting AI decision for {echelon_name}..."):
110
  try:
 
125
  except Exception as e:
126
  st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
127
  return 4, f"API_ERROR: {e}"
 
128
  # =============== PROMPT FUNCTION (v4 - FIXES FOR OSCILLATION AND HUMAN-LIKE) ===============
129
  def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
130
  # This function's logic is updated for "human_like" to follow a flawed Sterman heuristic.
 
139
  else:
140
  task_word = "order quantity"
141
  base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
 
142
  # --- PERFECT RATIONAL (NORMATIVE) PROMPTS ---
143
 
144
  if llm_personality == 'perfect_rational' and info_sharing == 'full':
 
163
  supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
164
  inventory_position = (e_state['inventory'] - e_state['backlog'] + supply_line)
165
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InProd={supply_line})"
166
+
167
  elif e_state['name'] == 'Distributor':
168
  # Distributor pipeline: In Shipping (1 week) + In Production (1 week) + Order Delay (1 week)
169
  in_shipping = sum(e_state['incoming_shipments'])
 
171
  supply_line = in_shipping + in_production + order_in_transit_to_supplier
172
  inventory_position = (e_state['inventory'] - e_state['backlog'] + supply_line)
173
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={in_shipping} + InProd={in_production} + OrderToSupplier={order_in_transit_to_supplier})"
174
+
175
  else: # Retailer and Wholesaler
176
  # R/W pipeline: In Shipping (2 weeks) + Order Delay (1 week)
177
  in_shipping = sum(e_state['incoming_shipments'])
178
  supply_line = in_shipping + order_in_transit_to_supplier
179
  inventory_position = (e_state['inventory'] - e_state['backlog'] + supply_line)
180
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={in_shipping} + OrderToSupplier={order_in_transit_to_supplier})"
 
181
  optimal_order = max(0, int(target_inventory_level - inventory_position))
182
  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."
183
+
184
  elif llm_personality == 'perfect_rational' and info_sharing == 'local':
185
  safety_stock = 4
186
  anchor_demand = e_state['incoming_order']
 
191
  # Factory can see its full (local) pipeline
192
  supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
193
  supply_line_desc = "In Production"
194
+
195
  elif e_state['name'] == 'Distributor':
196
  # Distributor can *only* see its shipping queue (1 week)
197
  # It CANNOT see the factory pipeline or its own order delay
 
210
  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 (that you can see). 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."
211
 
212
  # --- HUMAN-LIKE (DESCRIPTIVE) PROMPTS ---
 
213
  else:
214
  DESIRED_INVENTORY = 12 # Matches initial inventory
215
  net_inventory = e_state['inventory'] - e_state['backlog']
 
230
  anchor_demand = e_state['incoming_order']
231
  panicky_order = max(0, int(anchor_demand + stock_correction))
232
  panicky_order_calc = f"{anchor_demand} (Your Incoming Order) + {stock_correction} (Your Stock Correction)"
 
233
  return f"""
234
  **You are a reactive supply chain manager for the {e_state['name']}.** You have a limited (local) view.
235
  You tend to make **reactive, 'gut-instinct' decisions** (like the classic Sterman 1989 model) that cause the Bullwhip Effect.
236
+
237
  {base_info}
 
238
  **Your Flawed 'Human' Heuristic:**
239
  Your gut tells you to fix your entire inventory problem *right now*, and you're afraid of your backlog.
240
  A 'rational' player would account for their {supply_line_desc} (which is {supply_line} units), but you're too busy panicking to trust that.
 
241
  **Your 'Panic' Calculation (Ignoring the Supply Line):**
242
  1. **Anchor on Demand:** You just got an order for **{anchor_demand}** units. You'll order *at least* that.
243
  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.
244
  3. **Ignore Supply Line:** You'll ignore the **{supply_line} units** already in your pipeline.
 
245
  **Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
246
  * Order = {panicky_order_calc} = **{panicky_order} units**.
247
+
248
  **Your Task:** Confirm this 'gut-instinct' {task_word}. Respond with a single integer.
249
  """
250
+
251
  elif info_sharing == 'full':
252
  # 1. HUMAN-LIKE / FULL (FIX v6): Anchors on an *average* of local panic and global reality
253
  local_anchor = e_state['incoming_order']
 
258
 
259
  panicky_order = max(0, int(anchor_demand + stock_correction))
260
  panicky_order_calc = f"{anchor_demand} (Conflicted Anchor) + {stock_correction} (Your Stock Correction)"
 
261
  # Build the "Full Info" string just for context
262
  full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {current_stable_demand} units.\n"
263
  for name, other_e_state in all_echelons_state_decision_point.items():
264
  if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
 
265
  return f"""
266
  **You are a supply chain manager ({e_state['name']}) with full system visibility.**
267
  {base_info}
268
  {full_info_str}
269
+
270
  **A "Human-like" Flawed Decision:**
271
  You are judged by *your own* performance. You can see the stable End-Customer Demand is **{global_anchor}**, but you just received a panicky order for **{local_anchor}**.
272
  Your "gut-instinct" is to split the difference, anchoring on an average of the two.
273
  You still ignore your supply line, focusing only on your local stock.
 
274
  **Your 'Panic' Calculation (Ignoring Supply Line, Averaging Anchors):**
275
  1. **Anchor on Conflict:** (Your Incoming Order + End-Customer Demand) / 2
276
  * Anchor = ({local_anchor} + {global_anchor}) / 2 = **{anchor_demand}** units.
277
  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.
278
  3. **Ignore *Your* Supply Line:** You'll ignore the **{supply_line} units** in your own pipeline ({supply_line_desc}).
 
279
  **Final Panic Order:** (Conflicted Anchor) + (Your Stock Correction)
280
  * Order = {panicky_order_calc} = **{panicky_order} units**.
281
+
282
  **Your Task:** Confirm this 'gut-instinct', locally-focused {task_word}. Respond with a single integer.
283
  """
284
  # =========================================================
 
285
  # =============== STEP_GAME (v12) - Stable Logic + Correct Log Fix ===============
286
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
287
  # This is the correct logic from v4.17
 
290
  llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
291
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
292
  llm_raw_responses = {}
293
+
294
  # Capture opening state for logging
295
  opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
296
  opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
 
297
  # --- LOG FIX (v12): Capture arrival data BEFORE mutation ---
298
  arrived_this_week = {name: 0 for name in echelon_order}
299
  # This dict will store the value shown on the UI for "next week"
300
  opening_arriving_next_week_UI_VALUE = {name: 0 for name in echelon_order}
301
+
302
  # Factory
303
  factory_q = state['factory_production_pipeline']
304
  if factory_q:
305
  arrived_this_week["Factory"] = factory_q[0] # Read before pop
306
  # "Next Week" for Factory is the order it just received (Distributor's last week order)
307
  opening_arriving_next_week_UI_VALUE["Factory"] = state['last_week_orders'].get("Distributor", 0)
 
308
  # R, W, D
309
  for name in ["Retailer", "Wholesaler", "Distributor"]:
310
  shipment_q = echelons[name]['incoming_shipments']
311
  if shipment_q:
312
  arrived_this_week[name] = shipment_q[0] # Read before pop
313
+
314
  # --- THIS IS THE REAL FIX V12 ---
315
  if name == 'Distributor':
316
  # "Next" for Distributor (maxlen=1) is the item that will arrive W+1
 
 
317
  if shipment_q:
318
  opening_arriving_next_week_UI_VALUE[name] = shipment_q[0]
319
  elif name in ("Retailer", "Wholesaler"):
320
  # "Next" for R/W (maxlen=2) is the item that will arrive W+1
 
 
 
 
 
 
 
 
 
321
  if shipment_q:
322
  opening_arriving_next_week_UI_VALUE[name] = shipment_q[0]
323
  # --- END OF LOG FIX (v12) ---
 
324
  # Now, the *actual* state mutation (popping)
325
  inventory_after_arrival = {}
326
  factory_state = echelons["Factory"]
 
328
  if state['factory_production_pipeline']:
329
  produced_units = state['factory_production_pipeline'].popleft()
330
  inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
331
+
332
  # --- LOGIC FIX (v12) ---
333
  for name in ["Retailer", "Wholesaler", "Distributor"]:
334
  # Use the value we captured *before* popping
 
337
  echelons[name]['incoming_shipments'].popleft() # Now we pop
338
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
339
  # --- END LOGIC FIX (v12) ---
340
+
341
  # (Rest of game logic)
342
  total_backlog_before_shipping = {}
343
  for name in echelon_order:
 
348
  if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
349
  echelons[name]['incoming_order'] = incoming_order_for_this_week
350
  total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
351
+
352
  decision_point_states = {}
353
  for name in echelon_order:
354
  decision_point_states[name] = {
 
364
  prompt = get_llm_prompt(prompt_state, week, llm_personality, info_sharing, decision_point_states)
365
  order_amount, raw_resp = get_llm_order_decision(prompt, name)
366
  llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
367
+
368
  state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
369
+
370
  units_shipped = {name: 0 for name in echelon_order}
371
  for name in echelon_order:
372
  e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
373
  e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
374
  e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
375
+
376
  if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
377
  if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
378
  if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
379
+
380
  # (Logging)
381
  log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
382
  del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
 
385
  e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
386
  for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
387
  log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
388
+
389
  # --- LOG FIX (v12): Use captured values ---
390
  log_entry[f'{name}.opening_inventory'] = opening_inventories[name]
391
  log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
392
  log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name] # Use captured value
393
+
394
  if name != 'Factory':
395
  log_entry[f'{name}.arriving_next_week'] = opening_arriving_next_week_UI_VALUE[name]
396
  else:
397
  log_entry[f'{name}.production_completing_next_week'] = opening_arriving_next_week_UI_VALUE[name]
398
  # --- END OF LOG FIX (v12) ---
399
+
400
+ log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
401
  state['logs'].append(log_entry)
402
  state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
403
  state['current_ai_suggestion'] = None # Clean up
404
  if state['week'] > WEEKS: state['game_running'] = False
405
  # ==============================================================================
 
 
406
  def plot_results(df: pd.DataFrame, title: str, human_role: str):
407
  # This function remains correct.
408
  fig, axes = plt.subplots(4, 1, figsize=(12, 22))
 
432
  except (KeyError, ValueError) as plot_err:
433
  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')
434
  plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
 
 
435
  # =============== NEW: Leaderboard Functions (MODIFIED) ===============
436
  @st.cache_data(ttl=60)
437
  def load_leaderboard_data():
 
445
  except Exception as e:
446
  st.sidebar.error(f"Could not load leaderboard: {e}")
447
  return {}
 
448
  def save_leaderboard_data(data):
449
  if not hf_api or not HF_REPO_ID or not HF_TOKEN: return
450
  try:
 
455
  st.cache_data.clear()
456
  except Exception as e:
457
  st.sidebar.error(f"Failed to upload leaderboard: {e}")
 
458
  # ---------- MODIFIED FUNCTION (v2) ----------
459
  def display_rankings(df, top_n=10):
460
  if df.empty:
461
  st.info("No completed games for this category yet. Be the first!")
462
  return
463
+
464
  # 为新旧数据列进行数值转换
465
  df['distributor_cost'] = pd.to_numeric(df.get('total_cost'), errors='coerce') # 'total_cost' 是旧的 distributor_cost
466
  df['total_chain_cost'] = pd.to_numeric(df.get('total_chain_cost'), errors='coerce')
467
  df['order_std_dev'] = pd.to_numeric(df.get('order_std_dev'), errors='coerce')
 
468
  c1, c2, c3 = st.columns(3)
 
469
  # 排行榜 1: 总供应链成本 (新)
470
  with c1:
471
  st.subheader("🏆 Supply Chain Champions")
 
478
  champs_df['total_chain_cost'] = champs_df['total_chain_cost'].map('${:,.2f}'.format)
479
  champs_df.rename(columns={'id': 'Participant', 'total_chain_cost': 'Total Chain Cost'}, inplace=True)
480
  st.dataframe(champs_df[['Participant', 'Total Chain Cost']], use_container_width=True, hide_index=True)
 
481
  # 排行榜 2: 你的 (Distributor) 成本 (修改)
482
  with c2:
483
  st.subheader("👤 Distributor Champions")
484
  st.caption(f"Top {top_n} - Lowest **Your** (Distributor) Cost")
485
  dist_df = df.dropna(subset=['distributor_cost']).sort_values('distributor_cost', ascending=True).head(top_n).copy()
486
+
487
  if dist_df.empty:
488
  st.info("No data for this category yet.")
489
  else:
490
  dist_df['distributor_cost'] = dist_df['distributor_cost'].map('${:,.2f}'.format)
491
  dist_df.rename(columns={'id': 'Participant', 'distributor_cost': 'Your Cost'}, inplace=True)
492
  st.dataframe(dist_df[['Participant', 'Your Cost']], use_container_width=True, hide_index=True)
 
493
  # 排行榜 3: 订单平滑度 (不变)
494
  with c3:
495
  st.subheader("🧘 Mr. Smooth")
496
  st.caption(f"Top {top_n} - Lowest Order Variation (Std. Dev.)")
497
  smooth_df = df.dropna(subset=['order_std_dev']).sort_values('order_std_dev', ascending=True).head(top_n).copy()
498
+
499
  if smooth_df.empty:
500
  st.info("No data for this category yet.")
501
  else:
502
  smooth_df['order_std_dev'] = smooth_df['order_std_dev'].map('{:,.2f}'.format)
503
  smooth_df.rename(columns={'id': 'Participant', 'order_std_dev': 'Order Std. Dev.'}, inplace=True)
504
  st.dataframe(smooth_df[['Participant', 'Order Std. Dev.']], use_container_width=True, hide_index=True)
 
505
  def show_leaderboard_ui():
506
  st.markdown("---")
507
  st.header("📊 The Bullwhip Leaderboard")
 
513
  try:
514
  df = pd.DataFrame(leaderboard_data.values())
515
  if 'id' not in df.columns and not df.empty: df['id'] = list(leaderboard_data.keys())
516
+
517
  # 检查旧列是否存在即可
518
  if 'total_cost' not in df.columns or 'order_std_dev' not in df.columns or 'setting' not in df.columns:
519
  st.error("Leaderboard data is corrupted or incomplete.")
520
  return
521
+
522
  groups = sorted(df.setting.unique())
523
  tabs = st.tabs(["**Overall**"] + groups)
524
  with tabs[0]: display_rankings(df)
 
529
  except Exception as e:
530
  st.error(f"Error displaying leaderboard: {e}")
531
  st.dataframe(leaderboard_data)
 
532
  # ---------- MODIFIED FUNCTION (v2) ----------
533
  def save_logs_and_upload(state: dict):
534
  if not state.get('logs'):
 
557
  st.subheader("Updating Leaderboard...")
558
  try:
559
  human_role = state['human_role']
560
+
561
  # 1. 计算你的 (Distributor) 成本
562
  distributor_cost = logs_df[f'{human_role}.total_cost'].iloc[-1]
563
+
564
  # 2. 计算总供应链成本
565
  r_cost = logs_df['Retailer.total_cost'].iloc[-1]
566
  w_cost = logs_df['Wholesaler.total_cost'].iloc[-1]
567
  f_cost = logs_df['Factory.total_cost'].iloc[-1]
568
  total_chain_cost = r_cost + w_cost + distributor_cost + f_cost
569
+
570
  # 3. 计算订单标准差
571
  order_std_dev = logs_df[f'{human_role}.order_placed'].std()
572
+
573
  setting_name = f"{state['llm_personality']} / {state['info_sharing']}"
574
+
575
  # 4. 创建新的条目
576
  new_entry = {
577
  'id': participant_id,
 
580
  'total_chain_cost': float(total_chain_cost), # 新增: 总成本
581
  'order_std_dev': float(order_std_dev) if pd.notna(order_std_dev) else 0.0
582
  }
583
+
584
  leaderboard_data = load_leaderboard_data()
585
  leaderboard_data[participant_id] = new_entry
586
  save_leaderboard_data(leaderboard_data)
587
+
588
  except Exception as e_board:
589
  st.error(f"Error calculating or saving leaderboard score: {e_board}")
590
  # ==============================================================================
 
591
  # -----------------------------------------------------------------------------
592
  # 4. Streamlit UI (Applying v4.22 + v4.23 fixes)
593
  # -----------------------------------------------------------------------------
594
  st.title("🍺 The Beer Game: A Human-AI Collaboration Challenge")
 
595
  if st.session_state.get('initialization_error'):
596
  st.error(st.session_state.initialization_error)
597
  else:
 
601
  st.markdown("---")
602
  st.header("⚙️ Game Configuration")
603
 
604
+ # =============== 1. NEW: Participant ID Input ===============
605
  participant_id = st.text_input("Enter Your Name or Team ID:", key="participant_id_input", placeholder="e.g., Team A")
606
  # =======================================================
607
 
608
+ # =============== 1. MODIFIED: 自动分配逻辑 (移除手动选择) ===============
609
+ if participant_id:
610
+ # 使用哈希和模运算,将用户均匀分配到 4 个实验组
611
+ setting_index = hash(participant_id) % len(EXPERIMENT_SETTINGS)
612
+ llm_personality, info_sharing = EXPERIMENT_SETTINGS[setting_index]
613
+ else:
614
+ # 默认值,如果未输入ID
615
+ llm_personality, info_sharing = ('human_like', 'local')
616
+
617
+ st.info(f"You will be automatically assigned to the condition: **{llm_personality.replace('_', ' ').title()} / {info_sharing.title()}**.")
618
+ # =================================================================
619
+
620
+ # 移除原有的 c1, c2 和 selectbox
621
+ # c1, c2 = st.columns(2)
622
+ # with c1:
623
+ # with c2:
624
+
625
  # =============== MODIFIED: Start Game Button ===============
626
  if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
627
  if not participant_id:
 
633
  if st.session_state.get('last_id_warning') == participant_id:
634
  # 这是第二次点击,确认覆盖
635
  st.session_state.pop('last_id_warning', None)
636
+ init_game_state(llm_personality, info_sharing, participant_id) # 使用自动分配的值
637
  st.rerun()
638
  else:
639
  st.session_state['last_id_warning'] = participant_id
 
642
  # 新ID,直接开始
643
  if 'last_id_warning' in st.session_state:
644
  del st.session_state['last_id_warning']
645
+ init_game_state(llm_personality, info_sharing, participant_id) # 使用自动分配的值
646
  st.rerun()
647
  # ===========================================================
648
 
649
  # =============== NEW: Show Leaderboard on Start Page ===============
650
  show_leaderboard_ui()
651
  # =================================================================
 
652
  # --- Main Game Interface ---
653
  elif 'game_state' in st.session_state and st.session_state.game_state.get('game_running'):
654
  state = st.session_state.game_state
655
  week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
656
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Define here for UI
657
+
658
+ # =============== 2. IMAGE SIZE MODIFICATION (使用 st.columns) ===============
659
+ col_main, col_sidebar_image = st.columns([4, 1]) # 增大主内容区,同时保持侧边栏用于放置图表
660
+
661
+ with col_main:
662
+ st.header(f"Week {week} / {WEEKS}")
663
+ st.subheader(f"Your Role: **{human_role}** ({state['participant_id']}) | AI Mode: **{state['llm_personality'].replace('_', ' ')}** | Information: **{state['info_sharing']}**")
664
+ st.markdown("---")
665
+ st.subheader("Supply Chain Status (Start of Week State)")
666
+
667
+ # ... (UI LOGIC REMAINS HERE) ...
668
+
669
+ # --- MODIFIED UI LOGIC (v12) ---
670
+ if info_sharing == 'full':
671
+ cols = st.columns(4)
672
+ for i, name in enumerate(echelon_order):
673
+ with cols[i]:
674
+ e = echelons[name]
675
+ icon = "👤" if name == human_role else "🤖"
676
+ if name == human_role:
677
+ st.markdown(f"##### **<span style='border: 1px solid #FF4B4B; padding: 2px 5px; border-radius: 3px;'>{icon} {name} (You)</span>**", unsafe_allow_html=True)
678
+ else:
679
+ st.markdown(f"##### {icon} {name}")
680
+
681
+ st.metric("Inventory (Opening)", e['inventory'])
682
+ st.metric("Backlog (Opening)", e['backlog'])
683
+
684
+ current_incoming_order = 0
685
+ if name == "Retailer":
686
+ current_incoming_order = get_customer_demand(week)
687
+ else:
688
+ downstream_name = e['downstream_name']
689
+ if downstream_name:
690
+ current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
691
+ st.write(f"Incoming Order (This Week): **{current_incoming_order}**")
692
+
693
+ if name == "Factory":
694
+ prod_completing_next = state['last_week_orders'].get("Distributor", 0)
695
+ st.write(f"Completing Next Week: **{prod_completing_next}**")
696
+ else:
697
+ arriving_next = 0
698
+ q = e['incoming_shipments']
699
+ if q: arriving_next = list(q)[0] # Read W+1
700
+ st.write(f"Arriving Next Week: **{arriving_next}**")
701
+ else: # Local Info Mode
702
+ st.info("In Local Information mode, you can only see your own status dashboard.")
703
+ e = echelons[human_role] # Distributor
704
+ st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True)
705
+ col1, col2, col3 = st.columns(3)
706
+ with col1:
707
  st.metric("Inventory (Opening)", e['inventory'])
708
  st.metric("Backlog (Opening)", e['backlog'])
709
+
710
+ with col2:
711
  current_incoming_order = 0
712
+ downstream_name = e['downstream_name'] # Wholesaler
713
+ if downstream_name:
714
+ current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
715
+ st.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
716
+
717
+ with col3:
718
+ arriving_next = 0
719
+ q = e['incoming_shipments']
720
+ if q:
721
+ arriving_next = list(q)[0]
722
+ st.write(f"**Shipment Arriving (Next Week):**\n# {arriving_next}")
723
+
724
+ # --- Decision Logic (Remainging the Same) ---
725
+ st.markdown("---")
726
+ st.header("Your Decision (Step 4)")
727
+
728
+ # Prepare state snapshot for the AI prompt (logic remains identical)
729
+ all_decision_point_states = {}
730
+ for name in echelon_order:
731
+ e_curr = echelons[name]
732
+ arrived = 0
733
+ if name == "Factory":
734
+ if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
735
+ else:
736
+ if e_curr['incoming_shipments']: arrived = list(e_curr['incoming_shipments'])[0]
 
 
737
 
738
+ inc_order_this_week = 0
739
+ if name == "Retailer": inc_order_this_week = get_customer_demand(week)
740
+ else:
741
+ ds_name = e_curr['downstream_name']
742
+ if ds_name: inc_order_this_week = state['last_week_orders'].get(ds_name, 0)
743
+ inv_after_arrival = e_curr['inventory'] + arrived
744
+ backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
745
 
746
+ all_decision_point_states[name] = {
747
+ 'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
748
+ 'incoming_order': inc_order_this_week,
749
+ 'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
750
+ }
751
+ human_echelon_state_for_prompt = all_decision_point_states[human_role]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752
 
753
+ if state['decision_step'] == 'initial_order':
754
+ with st.form(key="initial_order_form"):
755
+ st.markdown("#### **Step 4a:** Based on the dashboard, submit your **initial** order to the Factory.")
756
+ initial_order = st.number_input("Your Initial Order Quantity:", min_value=0, step=1, value=None) # Start blank
757
+ if st.form_submit_button("Submit Initial Order & See AI Suggestion", type="primary"):
758
+ state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
759
+ state['decision_step'] = 'final_order'
760
+ prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, state['llm_personality'], state['info_sharing'], all_decision_point_states)
761
+ ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
762
+ state['current_ai_suggestion'] = ai_suggestion # Store it
763
+ st.rerun()
764
+ elif state['decision_step'] == 'final_order':
765
+ st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
766
+ ai_suggestion = state.get('current_ai_suggestion', 4) # Read stored value
767
+ with st.form(key="final_order_form"):
768
+ st.markdown(f"#### **Step 4b:** The AI suggests ordering **{ai_suggestion}** units.")
769
+ st.markdown("Considering the AI's advice, submit your **final** order to end the week. (This order will arrive in 3 weeks).")
770
+ st.number_input("Your Final Order Quantity:", min_value=0, step=1, key='final_order_input', value=None) # Start blank
771
+
772
+ if st.form_submit_button("Submit Final Order & Advance to Next Week"):
773
+ final_order_value = st.session_state.get('final_order_input', 0)
774
+ final_order_value = int(final_order_value) if final_order_value is not None else 0
775
+
776
+ step_game(final_order_value, state['human_initial_order'], ai_suggestion)
777
+
778
+ if 'final_order_input' in st.session_state: del st.session_state.final_order_input
779
+ st.rerun()
780
 
781
+ st.markdown("---")
782
+ with st.expander("📖 Your Weekly Decision Log", expanded=False):
783
+ if not state.get('logs'):
784
+ st.write("Your weekly history will be displayed here after you complete the first week.")
785
+ else:
786
+ try:
787
+ history_df = pd.json_normalize(state['logs'])
788
+ human_cols = {
789
+ 'week': 'Week', f'{human_role}.opening_inventory': 'Opening Inv.',
790
+ f'{human_role}.opening_backlog': 'Opening Backlog',
791
+ f'{human_role}.incoming_order': 'Incoming Order', f'{human_role}.initial_order': 'Your Initial Order',
792
+ f'{human_role}.ai_suggestion': 'AI Suggestion', f'{human_role}.order_placed': 'Your Final Order',
793
+ f'{human_role}.arriving_next_week': 'Arriving Next Week', f'{human_role}.weekly_cost': 'Weekly Cost',
794
+ }
795
+ ordered_display_cols_keys = [
796
+ 'week', f'{human_role}.opening_inventory', f'{human_role}.opening_backlog',
797
+ f'{human_role}.incoming_order',
798
+ f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed',
799
+ f'{human_role}.arriving_next_week', f'{human_role}.weekly_cost'
800
+ ]
801
+ final_cols_to_display = [col for col in ordered_display_cols_keys if col in history_df.columns]
802
+ if not final_cols_to_display:
803
+ st.write("No data columns available to display.")
804
+ else:
805
+ display_df = history_df[final_cols_to_display].rename(columns=human_cols)
806
+ if 'Weekly Cost' in display_df.columns:
807
+ display_df['Weekly Cost'] = display_df['Weekly Cost'].apply(lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "")
808
+ st.dataframe(display_df.sort_values(by="Week", ascending=False), hide_index=True, use_container_width=True)
809
+ except Exception as e:
810
+ st.error(f"Error displaying weekly log: {e}")
811
+
812
+ # 将原来的侧边栏内容移入 col_sidebar_image
813
+ with col_sidebar_image:
814
+ st.header("Game Info")
815
+ st.markdown(f"**Game ID**: `{state['participant_id']}`\n\n**Current Week**: {week}")
816
+ # --- 放大图片 ---
817
+ try: st.image(IMAGE_PATH, caption="Supply Chain Reference", use_column_width=True)
818
+ except FileNotFoundError: st.warning("Image file not found.")
819
+ # --- 放大图片 ---
820
 
821
+ if st.button("🔄 Reset Game"):
822
+ if 'final_order_input' in st.session_state: del st.session_state.final_order_input
823
+ if 'current_ai_suggestion' in st.session_state.game_state: del st.session_state.game_state['current_ai_suggestion']
824
+ del st.session_state.game_state
825
+ st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826
 
827
  # --- Game Over Interface ---
828
  if 'game_state' in st.session_state and not st.session_state.game_state.get('game_running', False) and st.session_state.game_state['week'] > WEEKS:
 
839
  save_logs_and_upload(state) # This now also updates the leaderboard
840
  except Exception as e:
841
  st.error(f"Error generating final report: {e}")
 
842
  show_leaderboard_ui()
 
843
  if st.button("✨ Start a New Game"):
844
  del st.session_state.game_state
845
  st.rerun()