Lilli98 commited on
Commit
269c319
·
verified ·
1 Parent(s): 8db87cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -179
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # app.py
2
- # @title Beer Game Final Version (v4.24)
3
 
4
  # -----------------------------------------------------------------------------
5
  # 1. Import Libraries
@@ -15,16 +15,14 @@ import random
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)
25
  # -----------------------------------------------------------------------------
26
  st.set_page_config(page_title="Beer Game: Human-AI Collaboration", layout="wide")
27
 
 
28
  # -----------------------------------------------------------------------------
29
  # 2. Game Parameters & API Configuration
30
  # -----------------------------------------------------------------------------
@@ -32,10 +30,10 @@ st.set_page_config(page_title="Beer Game: Human-AI Collaboration", layout="wide"
32
  WEEKS = 24
33
  INITIAL_INVENTORY = 12
34
  INITIAL_BACKLOG = 0
35
- ORDER_PASSING_DELAY = 1 # 订单传递延迟
36
- SHIPPING_DELAY = 2 # 通用运输延迟 (R->W, W->D)
37
- FACTORY_LEAD_TIME = 1 # 工厂生产延迟
38
- FACTORY_SHIPPING_DELAY = 1 # 工厂到分销商的运输延迟
39
  HOLDING_COST = 0.5
40
  BACKLOG_COST = 1.0
41
 
@@ -43,8 +41,7 @@ BACKLOG_COST = 1.0
43
  OPENAI_MODEL = "gpt-4o-mini"
44
  LOCAL_LOG_DIR = Path("logs")
45
  LOCAL_LOG_DIR.mkdir(exist_ok=True)
46
- IMAGE_PATH = "beer_game_diagram.png"
47
- LEADERBOARD_FILE = "leaderboard.json"
48
 
49
  # --- API & Secrets Configuration ---
50
  try:
@@ -58,6 +55,7 @@ except Exception as e:
58
  else:
59
  st.session_state.initialization_error = None
60
 
 
61
  # -----------------------------------------------------------------------------
62
  # 3. Core Game Logic Functions
63
  # -----------------------------------------------------------------------------
@@ -65,32 +63,21 @@ else:
65
  def get_customer_demand(week: int) -> int:
66
  return 4 if week <= 4 else 8
67
 
68
- # =============== MODIFIED Initialization (Corrected Queues) ===============
69
- def init_game_state(llm_personality: str, info_sharing: str, participant_id: str):
70
  roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
71
- human_role = "Distributor"
72
-
 
73
  st.session_state.game_state = {
74
  'game_running': True, 'participant_id': participant_id, 'week': 1,
75
  'human_role': human_role, 'llm_personality': llm_personality,
76
  'info_sharing': info_sharing, 'logs': [], 'echelons': {},
77
-
78
- # 管道现在必须模拟总延迟
79
- # Factory: 1 (订单) + 1 (生产) = 2 周延迟
80
- # 我们需要一个队列来处理订单 (1周),一个队列处理生产 (1周)
81
- 'factory_order_pipeline': deque([0] * ORDER_PASSING_DELAY, maxlen=ORDER_PASSING_DELAY),
82
  'factory_production_pipeline': deque([0] * FACTORY_LEAD_TIME, maxlen=FACTORY_LEAD_TIME),
83
-
84
- # Distributor -> Factory: 1(订单) + 1(生产) + 1(运输) = 3 周
85
- # Wholesaler -> Distributor: 1(订单) + 2(运输) = 3 周
86
- # Retailer -> Wholesaler: 1(订单) + 2(运输) = 3 周
87
- 'distributor_order_pipeline': deque([0] * ORDER_PASSING_DELAY, maxlen=ORDER_PASSING_DELAY),
88
- 'wholesaler_order_pipeline': deque([0] * ORDER_PASSING_DELAY, maxlen=ORDER_PASSING_DELAY),
89
- 'retailer_order_pipeline': deque([0] * ORDER_PASSING_DELAY, maxlen=ORDER_PASSING_DELAY),
90
-
91
  'decision_step': 'initial_order',
92
  'human_initial_order': None,
93
- 'current_ai_suggestion': None,
 
94
  }
95
 
96
  for i, name in enumerate(roles):
@@ -98,8 +85,8 @@ def init_game_state(llm_personality: str, info_sharing: str, participant_id: str
98
  downstream = roles[i - 1] if i - 1 >= 0 else None
99
 
100
  if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY
101
- elif name == "Factory": shipping_weeks = 0 # 工厂不收货
102
- else: shipping_weeks = SHIPPING_DELAY # R和W是2周
103
 
104
  st.session_state.game_state['echelons'][name] = {
105
  'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
@@ -107,7 +94,7 @@ def init_game_state(llm_personality: str, info_sharing: str, participant_id: str
107
  'incoming_order': 0, 'order_placed': 0, 'shipment_sent': 0,
108
  'weekly_cost': 0, 'total_cost': 0, 'upstream_name': upstream, 'downstream_name': downstream,
109
  }
110
- st.info(f"New game started for **{participant_id}**! AI Mode: **{llm_personality} / {info_sharing}**. You are the **{human_role}**.")
111
  # ==============================================================================
112
 
113
  def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
@@ -128,75 +115,50 @@ def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
128
  match = re.search(r'\d+', raw_text)
129
  if match: return int(match.group(0)), raw_text
130
  st.warning(f"LLM for {echelon_name} did not return a valid number. Defaulting to 4. Raw Response: '{raw_text}'")
131
- return 4, raw_text
132
  except Exception as e:
133
  st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
134
  return 4, f"API_ERROR: {e}"
135
 
136
- # =============== MODIFIED FUNCTION (Prompt uses new pipeline view) ===============
137
  def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
 
138
  e_state = echelon_state_decision_point
139
  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"
140
-
141
- # 查找正确的订单队列
142
- order_pipeline_to_show = deque()
143
- if e_state['name'] == 'Distributor':
144
- order_pipeline_to_show = st.session_state.game_state['distributor_order_pipeline']
145
- elif e_state['name'] == 'Wholesaler':
146
- order_pipeline_to_show = st.session_state.game_state['wholesaler_order_pipeline']
147
- elif e_state['name'] == 'Retailer':
148
- order_pipeline_to_show = st.session_state.game_state['retailer_order_pipeline']
149
-
150
  if e_state['name'] == 'Factory':
151
  task_word = "production quantity"
152
- base_info += f"- Your Production Pipeline (In Production): {list(st.session_state.game_state['factory_production_pipeline'])}\n"
153
- base_info += f"- Orders waiting for production (Just Arrived): {list(st.session_state.game_state['factory_order_pipeline'])}"
154
  else:
155
  task_word = "order quantity"
156
- base_info += f"- Shipments In Transit To You (On the way): {list(e_state['incoming_shipments'])}\n"
157
- base_info += f"- Orders You Placed (In transit to supplier): {list(order_pipeline_to_show)}"
158
-
159
- # --- Perfect Rational ---
160
  if llm_personality == 'perfect_rational' and info_sharing == 'full':
161
  stable_demand = 8
162
- if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME + ORDER_PASSING_DELAY
163
  elif e_state['name'] == 'Distributor': total_lead_time = ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY
164
  else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY
165
  safety_stock = 4
166
  target_inventory_level = (stable_demand * total_lead_time) + safety_stock
167
-
168
  if e_state['name'] == 'Factory':
169
- # IP = Inv - Backlog + In Production + Orders Waiting
170
- inventory_position = (e_state['inventory'] - e_state['backlog']
171
- + sum(st.session_state.game_state['factory_production_pipeline'])
172
- + sum(st.session_state.game_state['factory_order_pipeline']))
173
- inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InProd={sum(st.session_state.game_state['factory_production_pipeline'])} + Waiting={sum(st.session_state.game_state['factory_order_pipeline'])})"
174
  else:
175
- # IP = Inv - Backlog + In Transit Shipments + Orders In Transit to Supplier
176
- inventory_position = (e_state['inventory'] - e_state['backlog']
177
- + sum(e_state['incoming_shipments'])
178
- + sum(order_pipeline_to_show))
179
- inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + InTransitOrder={sum(order_pipeline_to_show)})"
180
-
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; anchor_demand = e_state['incoming_order']
186
  inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
187
-
188
  if e_state['name'] == 'Factory':
189
- supply_line = sum(st.session_state.game_state['factory_production_pipeline']) + sum(st.session_state.game_state['factory_order_pipeline'])
190
- supply_line_desc = "In Production / Waiting"
191
  else:
192
- supply_line = sum(e_state['incoming_shipments']) + sum(order_pipeline_to_show)
193
- supply_line_desc = "Supply Line (In Transit Shipments + Orders)"
194
-
195
  calculated_order = anchor_demand + inventory_correction - supply_line
196
  rational_local_order = max(0, int(calculated_order))
197
  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."
198
-
199
- # --- Human-like ---
200
  elif llm_personality == 'human_like' and info_sharing == 'full':
201
  full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
202
  for name, other_e_state in all_echelons_state_decision_point.items():
@@ -220,9 +182,8 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
220
  Your gut instinct is to panic and {task_word.split(' ')[0]} enough to ensure you are never caught with a backlog again, considering your current inventory.
221
  **React emotionally.** What is your knee-jerk {task_word}? Respond with a single integer.
222
  """
223
- # ==============================================================================
224
 
225
- # =============== CORRECTED step_game FUNCTION (Fixed Lead Time Logic v4.21) ===============
226
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
227
  state = st.session_state.game_state
228
  week, echelons, human_role = state['week'], state['echelons'], state['human_role']
@@ -237,42 +198,35 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
237
 
238
  # --- Game Simulation Steps ---
239
 
240
- # Step 1: Shipments Arrive (from incoming_shipments queue)
241
- inventory_after_arrival = {}
 
 
 
 
 
 
 
 
242
  for name in ["Retailer", "Wholesaler", "Distributor"]:
243
  arrived_shipment = 0
244
  if echelons[name]['incoming_shipments']:
245
- arrived_shipment = echelons[name]['incoming_shipments'].popleft()
246
  arrived_this_week[name] = arrived_shipment
247
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
248
 
249
- # Step 2: Orders Arrive (from order_pipeline queue)
250
- total_backlog_before_shipping = {}
251
  for name in echelon_order:
252
  incoming_order_for_this_week = 0
253
  if name == "Retailer":
254
  incoming_order_for_this_week = get_customer_demand(week)
255
  else:
256
- # Check the correct order pipeline based on the downstream partner
257
  downstream_name = echelons[name]['downstream_name']
258
- if downstream_name == 'Distributor':
259
- if state['distributor_order_pipeline']: incoming_order_for_this_week = state['distributor_order_pipeline'].popleft()
260
- elif downstream_name == 'Wholesaler':
261
- if state['wholesaler_order_pipeline']: incoming_order_for_this_week = state['wholesaler_order_pipeline'].popleft()
262
- elif downstream_name == 'Retailer':
263
- if state['retailer_order_pipeline']: incoming_order_for_this_week = state['retailer_order_pipeline'].popleft()
264
-
265
- echelons[name]['incoming_order'] = incoming_order_for_this_week
266
- # Factory's 'incoming_order' is now set (from distributor_order_pipeline)
267
-
268
- # Calculate intermediate state for Factory (production completion)
269
- if name == "Factory":
270
- produced_units = 0
271
- if state['factory_production_pipeline']:
272
- produced_units = state['factory_production_pipeline'].popleft()
273
- arrived_this_week["Factory"] = produced_units
274
- inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
275
 
 
276
  total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
277
 
278
  # --- Create State Snapshot for AI/Human Decision Point ---
@@ -280,13 +234,14 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
280
  for name in echelon_order:
281
  decision_point_states[name] = {
282
  'name': name,
283
- 'inventory': inventory_after_arrival[name],
284
- 'backlog': total_backlog_before_shipping[name],
285
- 'incoming_order': echelons[name]['incoming_order'],
286
  'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
287
  }
288
 
289
  # --- Step 4: Agent Decisions (Place Orders / Schedule Production) ---
 
290
  for name in echelon_order:
291
  e = echelons[name]
292
  prompt_state = decision_point_states[name]
@@ -299,15 +254,10 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
299
 
300
  llm_raw_responses[name] = raw_resp
301
  e['order_placed'] = max(0, order_amount)
 
302
 
303
- # Put the order into the correct pipeline to simulate ORDER_PASSING_DELAY
304
- if name == 'Distributor': state['distributor_order_pipeline'].append(e['order_placed'])
305
- elif name == 'Wholesaler': state['wholesaler_order_pipeline'].append(e['order_placed'])
306
- elif name == 'Retailer': state['retailer_order_pipeline'].append(e['order_placed'])
307
- # Factory's 'order_placed' is its production decision
308
-
309
-
310
- # --- Step 3 (Logic): Fulfill orders (Ship Beer) ---
311
  units_shipped = {name: 0 for name in echelon_order}
312
  for name in echelon_order:
313
  e = echelons[name]
@@ -315,44 +265,32 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
315
  available_inv = inventory_after_arrival[name]
316
 
317
  e['shipment_sent'] = min(available_inv, demand_to_meet)
318
- units_shipped[name] = e['shipment_sent']
319
 
320
  # Update the main state dict's inventory and backlog to reflect END OF WEEK state
321
  e['inventory'] = available_inv - e['shipment_sent']
322
  e['backlog'] = demand_to_meet - e['shipment_sent']
323
 
324
  # --- Step 5: Advance Pipelines (New Logic) ---
325
-
326
- # Factory: takes its incoming order (from distributor_order_pipeline)
327
- # and schedules it for production (adds to factory_production_pipeline)
328
- # This simulates FACTORY_LEAD_TIME
329
- # *** BUG FIX: Factory's order_placed IS its production decision ***
330
- # *** Factory's incoming_order is what drives its decision ***
331
-
332
- # Factory's decision ('order_placed') from Step 4 enters the production pipeline
333
  state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
334
-
335
- # What the Factory *shipped* in Step 3 (units_shipped["Factory"])
336
- # now enters the Distributor's shipping queue
337
  if units_shipped["Factory"] > 0:
338
  echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
339
-
340
- # What the Distributor *shipped* in Step 3...
341
  if units_shipped['Distributor'] > 0:
342
  echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
343
-
344
- # What the Wholesaler *shipped* in Step 3...
345
  if units_shipped['Wholesaler'] > 0:
346
  echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
347
 
348
-
349
  # --- Calculate Costs & Log (End of Week) ---
350
  log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
351
- # Clean up fields
352
- del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs']
353
- for key in ['distributor_order_pipeline', 'wholesaler_order_pipeline', 'retailer_order_pipeline', 'factory_order_pipeline']:
354
- if key in log_entry: del log_entry[key]
355
-
356
 
357
  for name in echelon_order:
358
  e = echelons[name]
@@ -375,13 +313,11 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
375
  state['logs'].append(log_entry)
376
 
377
  # --- Advance Week ---
378
- state['week'] += 1; state['decision_step'] = 'initial_order'
379
- # 'last_week_orders' is no longer needed with this pipeline logic
380
- # We rely on the order pipelines
381
  if state['week'] > WEEKS: state['game_running'] = False
382
  # ==============================================================================
383
 
384
-
385
  def plot_results(df: pd.DataFrame, title: str, human_role: str):
386
  # This function remains correct.
387
  fig, axes = plt.subplots(4, 1, figsize=(12, 22))
@@ -412,8 +348,10 @@ def plot_results(df: pd.DataFrame, title: str, human_role: str):
412
  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')
413
  plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
414
 
415
- # =============== Leaderboard Functions (Unchanged) ===============
416
- @st.cache_data(ttl=60)
 
 
417
  def load_leaderboard_data():
418
  if not hf_api or not HF_REPO_ID: return {}
419
  try:
@@ -494,8 +432,10 @@ def show_leaderboard_ui():
494
  except Exception as e:
495
  st.error(f"Error displaying leaderboard: {e}")
496
  st.dataframe(leaderboard_data)
 
497
 
498
  def save_logs_and_upload(state: dict):
 
499
  if not state.get('logs'):
500
  st.warning("No log data to save.")
501
  return
@@ -548,12 +488,12 @@ else:
548
  # --- Game Setup & Instructions ---
549
  if 'game_state' not in st.session_state or not st.session_state.game_state.get('game_running', False):
550
 
551
- # Introduction is removed as requested
552
-
553
  st.markdown("---")
554
  st.header("⚙️ Game Configuration")
555
 
 
556
  participant_id = st.text_input("Enter Your Name or Team ID:", key="participant_id_input", placeholder="e.g., Team A")
 
557
 
558
  c1, c2 = st.columns(2)
559
  with c1:
@@ -561,14 +501,17 @@ else:
561
  with c2:
562
  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.")
563
 
 
564
  if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
565
  if not participant_id:
566
  st.error("Please enter a Name or Team ID to start!")
567
  else:
 
568
  existing_data = load_leaderboard_data()
569
  if participant_id in existing_data:
570
- # Check for a re-click confirmation
571
  if st.session_state.get('last_id_warning') == participant_id:
 
572
  st.session_state.pop('last_id_warning', None)
573
  init_game_state(llm_personality, info_sharing, participant_id)
574
  st.rerun()
@@ -576,26 +519,29 @@ else:
576
  st.session_state['last_id_warning'] = participant_id
577
  st.warning(f"ID '{participant_id}' already exists! Your score will be overwritten. Click 'Start Game' again to confirm.")
578
  else:
 
579
  if 'last_id_warning' in st.session_state:
580
  del st.session_state['last_id_warning']
581
  init_game_state(llm_personality, info_sharing, participant_id)
582
  st.rerun()
 
583
 
 
584
  show_leaderboard_ui()
 
585
 
586
  # --- Main Game Interface ---
587
  elif 'game_state' in st.session_state and st.session_state.game_state.get('game_running'):
588
  state = st.session_state.game_state
589
  week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
590
- echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
591
 
592
 
593
  st.header(f"Week {week} / {WEEKS}")
594
  st.subheader(f"Your Role: **{human_role}** ({state['participant_id']}) | AI Mode: **{state['llm_personality'].replace('_', ' ')}** | Information: **{state['info_sharing']}**")
595
  st.markdown("---")
596
- st.subheader("Supply Chain Status (Start of Week State)")
597
 
598
- # =============== MODIFIED UI LOGIC (v4.21) ===============
599
  if info_sharing == 'full':
600
  cols = st.columns(4)
601
  for i, name in enumerate(echelon_order):
@@ -611,20 +557,16 @@ else:
611
  st.metric("Inventory (Opening)", e['inventory'])
612
  st.metric("Backlog (Opening)", e['backlog'])
613
 
614
- # --- Calculate and Display This Week's Events ---
615
- # Incoming Order (arriving in Step 2)
 
616
  current_incoming_order = 0
617
  if name == "Retailer":
618
  current_incoming_order = get_customer_demand(week)
619
  else:
620
- # PEEK at the order pipeline
621
  downstream_name = e['downstream_name']
622
- if downstream_name == 'Distributor': pipeline_peek = state['distributor_order_pipeline']
623
- elif downstream_name == 'Wholesaler': pipeline_peek = state['wholesaler_order_pipeline']
624
- elif downstream_name == 'Retailer': pipeline_peek = state['retailer_order_pipeline']
625
- else: pipeline_peek = deque()
626
- current_incoming_order = list(pipeline_peek)[0] if pipeline_peek else 0
627
-
628
  st.write(f"Incoming Order (This Week): **{current_incoming_order}**")
629
 
630
  if name == "Factory":
@@ -639,25 +581,19 @@ else:
639
  arriving_next = 0
640
  if len(e['incoming_shipments']) > 1:
641
  arriving_next = list(e['incoming_shipments'])[1]
642
- # Handle 2-week delay display for R/W
643
- elif name in ('Wholesaler', 'Retailer') and e['incoming_shipments'].maxlen == 2:
644
- if len(e['incoming_shipments']) == 1: # Only one item in queue
645
- arriving_next = list(e['incoming_shipments'])[0] # This must be the item for next week
646
- arriving_this_week = 0 # This week's arrival must have been 0
647
- # Re-calculate arriving_this_week for R/W based on maxlen
648
- arriving_this_week = list(e['incoming_shipments'])[0] if len(e['incoming_shipments']) == e['incoming_shipments'].maxlen else 0
649
- arriving_next = list(e['incoming_shipments'])[1] if len(e['incoming_shipments']) == e['incoming_shipments'].maxlen else (list(e['incoming_shipments'])[0] if len(e['incoming_shipments']) == 1 else 0)
650
-
651
- # Overwrite for clarity
652
- st.write(f"Arriving This Week: **{arriving_this_week}**")
653
- st.write(f"Arriving Next Week: **{arriving_next}**")
654
- else: # Distributor case (maxlen 1)
655
- arriving_next = 0 # Peek at index 1 is correct, it doesn't exist for maxlen=1
656
- st.write(f"Arriving Next Week: **{arriving_next}**")
657
 
658
  else: # Local Info Mode
659
  st.info("In Local Information mode, you can only see your own status dashboard.")
660
- e = echelons[human_role] # Distributor
661
  st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True)
662
 
663
  col1, col2, col3 = st.columns(3)
@@ -666,10 +602,10 @@ else:
666
  st.metric("Backlog (Opening)", e['backlog'])
667
 
668
  with col2:
669
- # Calculate Incoming Order for this week
670
  current_incoming_order = 0
671
- pipeline_peek = state['wholesaler_order_pipeline']
672
- current_incoming_order = list(pipeline_peek)[0] if pipeline_peek else 0
 
673
  st.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
674
 
675
  with col3:
@@ -678,18 +614,18 @@ else:
678
  st.write(f"**Shipment Arriving (This Week):**\n# {arriving_this_week}")
679
 
680
  # Arriving NEXT week (Peek at the next item in the 1-week delay queue)
681
- arriving_next = 0 # maxlen is 1, so index [1] doesn't exist
 
 
682
  st.write(f"**Shipment Arriving (Next Week):**\n# {arriving_next}")
683
 
684
- # =======================================================
685
-
686
  st.markdown("---")
687
  st.header("Your Decision (Step 4)")
688
 
689
  # Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
690
  all_decision_point_states = {}
691
  for name in echelon_order:
692
- e_curr = echelons[name]
693
  arrived = 0
694
  if name == "Factory":
695
  if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
@@ -700,11 +636,7 @@ else:
700
  if name == "Retailer": inc_order_this_week = get_customer_demand(week)
701
  else:
702
  ds_name = e_curr['downstream_name']
703
- pipeline_peek = deque()
704
- if ds_name == 'Distributor': pipeline_peek = state['distributor_order_pipeline']
705
- elif ds_name == 'Wholesaler': pipeline_peek = state['wholesaler_order_pipeline']
706
- elif ds_name == 'Retailer': pipeline_peek = state['retailer_order_pipeline']
707
- inc_order_this_week = list(pipeline_peek)[0] if pipeline_peek else 0
708
 
709
  inv_after_arrival = e_curr['inventory'] + arrived
710
  backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
@@ -725,16 +657,20 @@ else:
725
  state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
726
  state['decision_step'] = 'final_order'
727
 
 
728
  prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, state['llm_personality'], state['info_sharing'], all_decision_point_states)
729
  ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
730
  state['current_ai_suggestion'] = ai_suggestion # Store it
 
731
 
732
  st.rerun()
733
 
734
  elif state['decision_step'] == 'final_order':
735
  st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
736
 
 
737
  ai_suggestion = state.get('current_ai_suggestion', 4) # Read stored value
 
738
 
739
  with st.form(key="final_order_form"):
740
  st.markdown(f"#### **Step 4b:** The AI suggests ordering **{ai_suggestion}** units.")
@@ -809,7 +745,9 @@ else:
809
  except Exception as e:
810
  st.error(f"Error generating final report: {e}")
811
 
 
812
  show_leaderboard_ui()
 
813
 
814
  if st.button("✨ Start a New Game"):
815
  del st.session_state.game_state
 
1
  # app.py
2
+ # @title Beer Game Final Version (v4.21 - Corrected 3-Week Lead Time Logic & UI)
3
 
4
  # -----------------------------------------------------------------------------
5
  # 1. Import Libraries
 
15
  import uuid
16
  from pathlib import Path
17
  from datetime import datetime
18
+ from huggingface_hub import HfApi
 
 
 
19
 
20
  # -----------------------------------------------------------------------------
21
  # 0. Page Configuration (Must be the first Streamlit command)
22
  # -----------------------------------------------------------------------------
23
  st.set_page_config(page_title="Beer Game: Human-AI Collaboration", layout="wide")
24
 
25
+
26
  # -----------------------------------------------------------------------------
27
  # 2. Game Parameters & API Configuration
28
  # -----------------------------------------------------------------------------
 
30
  WEEKS = 24
31
  INITIAL_INVENTORY = 12
32
  INITIAL_BACKLOG = 0
33
+ ORDER_PASSING_DELAY = 1 # Handled by last_week_orders
34
+ SHIPPING_DELAY = 2 # General shipping delay (R->W, W->D)
35
+ FACTORY_LEAD_TIME = 1
36
+ FACTORY_SHIPPING_DELAY = 1 # Specific delay from Factory to Distributor
37
  HOLDING_COST = 0.5
38
  BACKLOG_COST = 1.0
39
 
 
41
  OPENAI_MODEL = "gpt-4o-mini"
42
  LOCAL_LOG_DIR = Path("logs")
43
  LOCAL_LOG_DIR.mkdir(exist_ok=True)
44
+ IMAGE_PATH = "beer_game_diagram.png" # Path to your uploaded image
 
45
 
46
  # --- API & Secrets Configuration ---
47
  try:
 
55
  else:
56
  st.session_state.initialization_error = None
57
 
58
+
59
  # -----------------------------------------------------------------------------
60
  # 3. Core Game Logic Functions
61
  # -----------------------------------------------------------------------------
 
63
  def get_customer_demand(week: int) -> int:
64
  return 4 if week <= 4 else 8
65
 
66
+ # =============== CORRECTED Initialization (v4.17 logic) ===============
67
+ def init_game_state(llm_personality: str, info_sharing: str):
68
  roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
69
+ human_role = "Distributor" # Role is fixed
70
+ participant_id = str(uuid.uuid4())[:8]
71
+
72
  st.session_state.game_state = {
73
  'game_running': True, 'participant_id': participant_id, 'week': 1,
74
  'human_role': human_role, 'llm_personality': llm_personality,
75
  'info_sharing': info_sharing, 'logs': [], 'echelons': {},
 
 
 
 
 
76
  'factory_production_pipeline': deque([0] * FACTORY_LEAD_TIME, maxlen=FACTORY_LEAD_TIME),
 
 
 
 
 
 
 
 
77
  'decision_step': 'initial_order',
78
  'human_initial_order': None,
79
+ # Initialize last week's orders to 0
80
+ 'last_week_orders': {name: 0 for name in roles}
81
  }
82
 
83
  for i, name in enumerate(roles):
 
85
  downstream = roles[i - 1] if i - 1 >= 0 else None
86
 
87
  if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY
88
+ elif name == "Factory": shipping_weeks = 0
89
+ else: shipping_weeks = SHIPPING_DELAY
90
 
91
  st.session_state.game_state['echelons'][name] = {
92
  'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
 
94
  'incoming_order': 0, 'order_placed': 0, 'shipment_sent': 0,
95
  'weekly_cost': 0, 'total_cost': 0, 'upstream_name': upstream, 'downstream_name': downstream,
96
  }
97
+ st.info(f"New game started! AI Mode: **{llm_personality} / {info_sharing}**. You are playing as the: **{human_role}**.")
98
  # ==============================================================================
99
 
100
  def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
 
115
  match = re.search(r'\d+', raw_text)
116
  if match: return int(match.group(0)), raw_text
117
  st.warning(f"LLM for {echelon_name} did not return a valid number. Defaulting to 4. Raw Response: '{raw_text}'")
118
+ return 4, raw_text # Default to 4
119
  except Exception as e:
120
  st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
121
  return 4, f"API_ERROR: {e}"
122
 
 
123
  def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
124
+ # This function's logic remains correct (from v4.17).
125
  e_state = echelon_state_decision_point
126
  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"
 
 
 
 
 
 
 
 
 
 
127
  if e_state['name'] == 'Factory':
128
  task_word = "production quantity"
129
+ base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
 
130
  else:
131
  task_word = "order quantity"
132
+ base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
 
 
 
133
  if llm_personality == 'perfect_rational' and info_sharing == 'full':
134
  stable_demand = 8
135
+ if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME
136
  elif e_state['name'] == 'Distributor': total_lead_time = ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY
137
  else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY
138
  safety_stock = 4
139
  target_inventory_level = (stable_demand * total_lead_time) + safety_stock
 
140
  if e_state['name'] == 'Factory':
141
+ inventory_position = (e_state['inventory'] - e_state['backlog'] + sum(st.session_state.game_state['factory_production_pipeline']))
142
+ inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InProd={sum(st.session_state.game_state['factory_production_pipeline'])})"
 
 
 
143
  else:
144
+ order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
145
+ inventory_position = (e_state['inventory'] - e_state['backlog'] + sum(e_state['incoming_shipments']) + order_in_transit_to_supplier)
146
+ inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
 
 
 
147
  optimal_order = max(0, int(target_inventory_level - inventory_position))
148
  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."
 
149
  elif llm_personality == 'perfect_rational' and info_sharing == 'local':
150
  safety_stock = 4; anchor_demand = e_state['incoming_order']
151
  inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
 
152
  if e_state['name'] == 'Factory':
153
+ supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
154
+ supply_line_desc = "In Production"
155
  else:
156
+ order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
157
+ supply_line = sum(e_state['incoming_shipments']) + order_in_transit_to_supplier
158
+ supply_line_desc = "Supply Line (In Transit Shipments + Order To Supplier)"
159
  calculated_order = anchor_demand + inventory_correction - supply_line
160
  rational_local_order = max(0, int(calculated_order))
161
  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."
 
 
162
  elif llm_personality == 'human_like' and info_sharing == 'full':
163
  full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
164
  for name, other_e_state in all_echelons_state_decision_point.items():
 
182
  Your gut instinct is to panic and {task_word.split(' ')[0]} enough to ensure you are never caught with a backlog again, considering your current inventory.
183
  **React emotionally.** What is your knee-jerk {task_word}? Respond with a single integer.
184
  """
 
185
 
186
+ # =============== CORRECTED step_game FUNCTION (Fixed Lead Time Logic) ===============
187
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
188
  state = st.session_state.game_state
189
  week, echelons, human_role = state['week'], state['echelons'], state['human_role']
 
198
 
199
  # --- Game Simulation Steps ---
200
 
201
+ # Step 1a: Factory Production completes
202
+ factory_state = echelons["Factory"]
203
+ produced_units = 0
204
+ if state['factory_production_pipeline']:
205
+ produced_units = state['factory_production_pipeline'].popleft() # Pop completed production
206
+ arrived_this_week["Factory"] = produced_units
207
+ inventory_after_arrival = {} # Store intermediate inventory state
208
+ inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
209
+
210
+ # Step 1b: Shipments arrive at downstream echelons
211
  for name in ["Retailer", "Wholesaler", "Distributor"]:
212
  arrived_shipment = 0
213
  if echelons[name]['incoming_shipments']:
214
+ arrived_shipment = echelons[name]['incoming_shipments'].popleft() # Pop arrived shipment
215
  arrived_this_week[name] = arrived_shipment
216
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
217
 
218
+ # Step 2: Orders Arrive from Downstream
219
+ total_backlog_before_shipping = {} # Store intermediate backlog state
220
  for name in echelon_order:
221
  incoming_order_for_this_week = 0
222
  if name == "Retailer":
223
  incoming_order_for_this_week = get_customer_demand(week)
224
  else:
 
225
  downstream_name = echelons[name]['downstream_name']
226
+ if downstream_name:
227
+ incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
+ echelons[name]['incoming_order'] = incoming_order_for_this_week # Store for logging/UI this week
230
  total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
231
 
232
  # --- Create State Snapshot for AI/Human Decision Point ---
 
234
  for name in echelon_order:
235
  decision_point_states[name] = {
236
  'name': name,
237
+ 'inventory': inventory_after_arrival[name], # Inventory available
238
+ 'backlog': total_backlog_before_shipping[name], # Total demand to meet
239
+ 'incoming_order': echelons[name]['incoming_order'], # Order received this week
240
  'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
241
  }
242
 
243
  # --- Step 4: Agent Decisions (Place Orders / Schedule Production) ---
244
+ current_week_orders = {} # Store THIS week's decisions
245
  for name in echelon_order:
246
  e = echelons[name]
247
  prompt_state = decision_point_states[name]
 
254
 
255
  llm_raw_responses[name] = raw_resp
256
  e['order_placed'] = max(0, order_amount)
257
+ current_week_orders[name] = e['order_placed'] # Store for NEXT week's Step 2
258
 
259
+ # --- Step 3 (Logic Moved): Fulfill orders (Ship Beer) ---
260
+ # This MUST happen BEFORE Step 5 (Pipelines Advance)
 
 
 
 
 
 
261
  units_shipped = {name: 0 for name in echelon_order}
262
  for name in echelon_order:
263
  e = echelons[name]
 
265
  available_inv = inventory_after_arrival[name]
266
 
267
  e['shipment_sent'] = min(available_inv, demand_to_meet)
268
+ units_shipped[name] = e['shipment_sent'] # Store temporarily
269
 
270
  # Update the main state dict's inventory and backlog to reflect END OF WEEK state
271
  e['inventory'] = available_inv - e['shipment_sent']
272
  e['backlog'] = demand_to_meet - e['shipment_sent']
273
 
274
  # --- Step 5: Advance Pipelines (New Logic) ---
275
+ # Factory's decision ('order_placed') from this week enters the production pipeline
276
+ # This simulates the FACTORY_LEAD_TIME
 
 
 
 
 
 
277
  state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
278
+
279
+ # Items shipped in Step 3 now enter their respective shipping pipelines
280
+ # Factory -> Distributor (uses FACTORY_SHIPPING_DELAY)
281
  if units_shipped["Factory"] > 0:
282
  echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
283
+ # Distributor -> Wholesaler (uses SHIPPING_DELAY)
 
284
  if units_shipped['Distributor'] > 0:
285
  echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
286
+ # Wholesaler -> Retailer (uses SHIPPING_DELAY)
 
287
  if units_shipped['Wholesaler'] > 0:
288
  echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
289
 
 
290
  # --- Calculate Costs & Log (End of Week) ---
291
  log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
292
+ del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
293
+ if 'current_ai_suggestion' in log_entry: del log_entry['current_ai_suggestion']
 
 
 
294
 
295
  for name in echelon_order:
296
  e = echelons[name]
 
313
  state['logs'].append(log_entry)
314
 
315
  # --- Advance Week ---
316
+ state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
317
+ state['current_ai_suggestion'] = None # Clean up
 
318
  if state['week'] > WEEKS: state['game_running'] = False
319
  # ==============================================================================
320
 
 
321
  def plot_results(df: pd.DataFrame, title: str, human_role: str):
322
  # This function remains correct.
323
  fig, axes = plt.subplots(4, 1, figsize=(12, 22))
 
348
  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')
349
  plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
350
 
351
+
352
+ # =============== NEW: Leaderboard Functions ===============
353
+
354
+ @st.cache_data(ttl=60) # 缓存1分钟
355
  def load_leaderboard_data():
356
  if not hf_api or not HF_REPO_ID: return {}
357
  try:
 
432
  except Exception as e:
433
  st.error(f"Error displaying leaderboard: {e}")
434
  st.dataframe(leaderboard_data)
435
+ # ==============================================================================
436
 
437
  def save_logs_and_upload(state: dict):
438
+ # This function is now responsible for CSV *and* leaderboard updates.
439
  if not state.get('logs'):
440
  st.warning("No log data to save.")
441
  return
 
488
  # --- Game Setup & Instructions ---
489
  if 'game_state' not in st.session_state or not st.session_state.game_state.get('game_running', False):
490
 
 
 
491
  st.markdown("---")
492
  st.header("⚙️ Game Configuration")
493
 
494
+ # =============== NEW: Participant ID Input ===============
495
  participant_id = st.text_input("Enter Your Name or Team ID:", key="participant_id_input", placeholder="e.g., Team A")
496
+ # =======================================================
497
 
498
  c1, c2 = st.columns(2)
499
  with c1:
 
501
  with c2:
502
  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.")
503
 
504
+ # =============== MODIFIED: Start Game Button ===============
505
  if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
506
  if not participant_id:
507
  st.error("Please enter a Name or Team ID to start!")
508
  else:
509
+ # 检查ID是否已存在
510
  existing_data = load_leaderboard_data()
511
  if participant_id in existing_data:
512
+ # 如果ID已存在,添加一个session_state标志,要求再次点击
513
  if st.session_state.get('last_id_warning') == participant_id:
514
+ # 这是第二次点击,确认覆盖
515
  st.session_state.pop('last_id_warning', None)
516
  init_game_state(llm_personality, info_sharing, participant_id)
517
  st.rerun()
 
519
  st.session_state['last_id_warning'] = participant_id
520
  st.warning(f"ID '{participant_id}' already exists! Your score will be overwritten. Click 'Start Game' again to confirm.")
521
  else:
522
+ # 新ID,直接开始
523
  if 'last_id_warning' in st.session_state:
524
  del st.session_state['last_id_warning']
525
  init_game_state(llm_personality, info_sharing, participant_id)
526
  st.rerun()
527
+ # ===========================================================
528
 
529
+ # =============== NEW: Show Leaderboard on Start Page ===============
530
  show_leaderboard_ui()
531
+ # =================================================================
532
 
533
  # --- Main Game Interface ---
534
  elif 'game_state' in st.session_state and st.session_state.game_state.get('game_running'):
535
  state = st.session_state.game_state
536
  week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
537
+ echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Define here for UI
538
 
539
 
540
  st.header(f"Week {week} / {WEEKS}")
541
  st.subheader(f"Your Role: **{human_role}** ({state['participant_id']}) | AI Mode: **{state['llm_personality'].replace('_', ' ')}** | Information: **{state['info_sharing']}**")
542
  st.markdown("---")
543
+ st.subheader("Supply Chain Status (Start of Week State)") # Clarified Timing
544
 
 
545
  if info_sharing == 'full':
546
  cols = st.columns(4)
547
  for i, name in enumerate(echelon_order):
 
557
  st.metric("Inventory (Opening)", e['inventory'])
558
  st.metric("Backlog (Opening)", e['backlog'])
559
 
560
+ # 移除成本显示
561
+
562
+ # --- UI FIX: Display "Arrived This Week" ---
563
  current_incoming_order = 0
564
  if name == "Retailer":
565
  current_incoming_order = get_customer_demand(week)
566
  else:
 
567
  downstream_name = e['downstream_name']
568
+ if downstream_name:
569
+ current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
 
 
 
 
570
  st.write(f"Incoming Order (This Week): **{current_incoming_order}**")
571
 
572
  if name == "Factory":
 
581
  arriving_next = 0
582
  if len(e['incoming_shipments']) > 1:
583
  arriving_next = list(e['incoming_shipments'])[1]
584
+ # 修正 2-week delay (R/W) 的显示
585
+ elif name in ('Wholesaler', 'Retailer') and len(e['incoming_shipments']) > 0 and e['incoming_shipments'].maxlen == 2:
586
+ # 如果队列长度为1但最大长度为2,说明下一个是0
587
+ if len(e['incoming_shipments']) == 1:
588
+ arriving_next = 0
589
+ else: # 这种情况不应该发生,但作为保险
590
+ arriving_next = list(e['incoming_shipments'])[0]
591
+
592
+ st.write(f"Arriving Next Week: **{arriving_next}**")
 
 
 
 
 
 
593
 
594
  else: # Local Info Mode
595
  st.info("In Local Information mode, you can only see your own status dashboard.")
596
+ e = echelons[human_role]
597
  st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True)
598
 
599
  col1, col2, col3 = st.columns(3)
 
602
  st.metric("Backlog (Opening)", e['backlog'])
603
 
604
  with col2:
 
605
  current_incoming_order = 0
606
+ downstream_name = e['downstream_name'] # Wholesaler
607
+ if downstream_name:
608
+ current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
609
  st.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
610
 
611
  with col3:
 
614
  st.write(f"**Shipment Arriving (This Week):**\n# {arriving_this_week}")
615
 
616
  # Arriving NEXT week (Peek at the next item in the 1-week delay queue)
617
+ arriving_next = 0
618
+ if len(e['incoming_shipments']) > 1: # 仅当队列中有多于1个元素时,才显示 [1]
619
+ arriving_next = list(e['incoming_shipments'])[1]
620
  st.write(f"**Shipment Arriving (Next Week):**\n# {arriving_next}")
621
 
 
 
622
  st.markdown("---")
623
  st.header("Your Decision (Step 4)")
624
 
625
  # Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
626
  all_decision_point_states = {}
627
  for name in echelon_order:
628
+ e_curr = echelons[name] # This is END OF LAST WEEK state
629
  arrived = 0
630
  if name == "Factory":
631
  if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
 
636
  if name == "Retailer": inc_order_this_week = get_customer_demand(week)
637
  else:
638
  ds_name = e_curr['downstream_name']
639
+ if ds_name: inc_order_this_week = state['last_week_orders'].get(ds_name, 0)
 
 
 
 
640
 
641
  inv_after_arrival = e_curr['inventory'] + arrived
642
  backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
 
657
  state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
658
  state['decision_step'] = 'final_order'
659
 
660
+ # --- NEW: Calculate and store suggestion ONCE ---
661
  prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, state['llm_personality'], state['info_sharing'], all_decision_point_states)
662
  ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
663
  state['current_ai_suggestion'] = ai_suggestion # Store it
664
+ # ------------------------------------------------
665
 
666
  st.rerun()
667
 
668
  elif state['decision_step'] == 'final_order':
669
  st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
670
 
671
+ # --- NEW: Read stored suggestion ---
672
  ai_suggestion = state.get('current_ai_suggestion', 4) # Read stored value
673
+ # -----------------------------------
674
 
675
  with st.form(key="final_order_form"):
676
  st.markdown(f"#### **Step 4b:** The AI suggests ordering **{ai_suggestion}** units.")
 
745
  except Exception as e:
746
  st.error(f"Error generating final report: {e}")
747
 
748
+ # =============== NEW: Show Leaderboard on End Page ===============
749
  show_leaderboard_ui()
750
+ # ===============================================================
751
 
752
  if st.button("✨ Start a New Game"):
753
  del st.session_state.game_state