Lilli98 commited on
Commit
2c66a81
·
verified ·
1 Parent(s): f4afd60

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -146
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # app.py
2
- # @title Beer Game Final Version (v4.16 - Corrected 3-Week Lead Time Logic)
3
 
4
  # -----------------------------------------------------------------------------
5
  # 1. Import Libraries
@@ -30,7 +30,7 @@ st.set_page_config(page_title="Beer Game: Human-AI Collaboration", layout="wide"
30
  WEEKS = 24
31
  INITIAL_INVENTORY = 12
32
  INITIAL_BACKLOG = 0
33
- ORDER_PASSING_DELAY = 1
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
@@ -63,7 +63,7 @@ else:
63
  def get_customer_demand(week: int) -> int:
64
  return 4 if week <= 4 else 8
65
 
66
- # =============== MODIFIED FUNCTION (Corrected Initialization) ===============
67
  def init_game_state(llm_personality: str, info_sharing: str):
68
  roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
69
  human_role = "Distributor" # Role is fixed
@@ -73,14 +73,11 @@ def init_game_state(llm_personality: str, info_sharing: str):
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
- # Pipeline now needs to cover ORDER_PASSING_DELAY + FACTORY_LEAD_TIME
77
  'factory_production_pipeline': deque([0] * FACTORY_LEAD_TIME, maxlen=FACTORY_LEAD_TIME),
78
- 'distributor_order_pipeline': deque([0] * ORDER_PASSING_DELAY, maxlen=ORDER_PASSING_DELAY), # For D -> F order passing
79
- 'wholesaler_order_pipeline': deque([0] * ORDER_PASSING_DELAY, maxlen=ORDER_PASSING_DELAY), # For W -> D order passing
80
- 'retailer_order_pipeline': deque([0] * ORDER_PASSING_DELAY, maxlen=ORDER_PASSING_DELAY), # For R -> W order passing
81
  'decision_step': 'initial_order',
82
  'human_initial_order': None,
83
- # No need for last_week_orders anymore
 
84
  }
85
 
86
  for i, name in enumerate(roles):
@@ -121,63 +118,50 @@ def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
121
  raw_text = response.choices[0].message.content.strip()
122
  match = re.search(r'\d+', raw_text)
123
  if match: return int(match.group(0)), raw_text
124
- st.warning(f"LLM for {echelon_name} did not return a valid number. Defaulting to 8. Raw Response: '{raw_text}'")
125
- return 8, raw_text # Default if no number found
126
  except Exception as e:
127
- st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 8.")
128
- return 8, f"API_ERROR: {e}"
129
 
130
- # =============== MODIFIED FUNCTION (Prompt adjusted for new pipeline view) ===============
131
- def get_llm_prompt(echelon_state_after_arrivals: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_after_arrivals: dict) -> str:
132
  """Generates the prompt for the LLM based on the game scenario.
133
- Uses the state AFTER arrivals and new orders are processed, as this is the decision point."""
134
 
135
- e_state = echelon_state_after_arrivals # Use the passed-in state for prompts
136
 
137
  # Base Info reflects state before shipping
138
  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"
139
 
140
  if e_state['name'] == 'Factory':
141
  task_word = "production quantity"
142
- # Factory prompt needs its view of the production pipeline
143
  base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
144
  else:
145
  task_word = "order quantity"
146
- # Others need their incoming shipments and orders placed but not yet received by supplier
147
- base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}\n"
148
- # Show orders placed but not yet received by supplier (1 week delay)
149
- if e_state['name'] == 'Distributor':
150
- orders_in_transit = list(st.session_state.game_state['distributor_order_pipeline'])
151
- elif e_state['name'] == 'Wholesaler':
152
- orders_in_transit = list(st.session_state.game_state['wholesaler_order_pipeline'])
153
- elif e_state['name'] == 'Retailer':
154
- orders_in_transit = list(st.session_state.game_state['retailer_order_pipeline'])
155
- else: orders_in_transit = []
156
- base_info += f"- Orders You Placed (in transit to supplier): {orders_in_transit}"
157
-
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
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
- # Calculate Inventory Position based on state AFTER arrivals/orders AND pipelines
169
  if e_state['name'] == 'Factory':
170
  # IP = Inv - Backlog + In Production
171
  inventory_position = (e_state['inventory'] - e_state['backlog'] + sum(st.session_state.game_state['factory_production_pipeline']))
172
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InProd={sum(st.session_state.game_state['factory_production_pipeline'])})"
173
  else:
174
- # IP = Inv - Backlog + In Transit Shipments + Orders Placed but not yet received by supplier
175
- if e_state['name'] == 'Distributor': orders_in_transit_sum = sum(st.session_state.game_state['distributor_order_pipeline'])
176
- elif e_state['name'] == 'Wholesaler': orders_in_transit_sum = sum(st.session_state.game_state['wholesaler_order_pipeline'])
177
- elif e_state['name'] == 'Retailer': orders_in_transit_sum = sum(st.session_state.game_state['retailer_order_pipeline'])
178
- else: orders_in_transit_sum = 0
179
- inventory_position = (e_state['inventory'] - e_state['backlog'] + sum(e_state['incoming_shipments']) + orders_in_transit_sum)
180
- inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + InTransitOrder={orders_in_transit_sum})"
181
 
182
  optimal_order = max(0, int(target_inventory_level - inventory_position))
183
 
@@ -191,23 +175,20 @@ def get_llm_prompt(echelon_state_after_arrivals: dict, week: int, llm_personalit
191
  supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
192
  supply_line_desc = "In Production"
193
  else:
194
- # Supply line includes shipments AND orders in transit
195
- if e_state['name'] == 'Distributor': orders_in_transit_sum = sum(st.session_state.game_state['distributor_order_pipeline'])
196
- elif e_state['name'] == 'Wholesaler': orders_in_transit_sum = sum(st.session_state.game_state['wholesaler_order_pipeline'])
197
- elif e_state['name'] == 'Retailer': orders_in_transit_sum = sum(st.session_state.game_state['retailer_order_pipeline'])
198
- else: orders_in_transit_sum = 0
199
- supply_line = sum(e_state['incoming_shipments']) + orders_in_transit_sum
200
- supply_line_desc = "Supply Line (In Transit Shipments + Orders)"
201
 
202
  calculated_order = anchor_demand + inventory_correction - supply_line
203
  rational_local_order = max(0, int(calculated_order))
204
 
205
- 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 (either shipping or orders in transit). 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."
206
 
207
  # --- Human-like ---
208
  elif llm_personality == 'human_like' and info_sharing == 'full':
209
  full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
210
- for name, other_e_state in all_echelons_state_after_arrivals.items():
211
  if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
212
 
213
  return f"""
@@ -232,7 +213,7 @@ def get_llm_prompt(echelon_state_after_arrivals: dict, week: int, llm_personalit
232
  """
233
  # ==============================================================================
234
 
235
- # =============== CORRECTED step_game FUNCTION (Handles 3-week LT) ===============
236
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
237
  state = st.session_state.game_state
238
  week, echelons, human_role = state['week'], state['echelons'], state['human_role']
@@ -240,7 +221,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
240
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Defined here
241
  llm_raw_responses = {}
242
 
243
- # Store state at the very beginning of the week for logging opening balances
244
  opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
245
  opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
246
  arrived_this_week = {name: 0 for name in echelon_order} # Track arrivals for logging
@@ -253,7 +234,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
253
  factory_state = echelons["Factory"]
254
  produced_units = 0
255
  if state['factory_production_pipeline']:
256
- produced_units = state['factory_production_pipeline'].popleft() # Pop from beginning (what was scheduled LEAST recently)
257
  arrived_this_week["Factory"] = produced_units
258
  inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
259
 
@@ -261,51 +242,46 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
261
  for name in ["Retailer", "Wholesaler", "Distributor"]:
262
  arrived_shipment = 0
263
  if echelons[name]['incoming_shipments']:
264
- arrived_shipment = echelons[name]['incoming_shipments'].popleft() # Pop from beginning
265
  arrived_this_week[name] = arrived_shipment
266
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
267
 
268
-
269
  # Step 2: Orders Arrive from Downstream & Update Temp Backlog
270
- # Orders arrive after ORDER_PASSING_DELAY
271
  total_backlog_before_shipping = {} # Store intermediate backlog state
272
  for name in echelon_order:
273
  incoming_order_for_this_week = 0
274
  if name == "Retailer":
275
  incoming_order_for_this_week = get_customer_demand(week)
276
  else:
277
- # Check the correct order pipeline based on the downstream partner
278
  downstream_name = echelons[name]['downstream_name']
279
- if downstream_name == 'Distributor':
280
- if state['distributor_order_pipeline']:
281
- incoming_order_for_this_week = state['distributor_order_pipeline'].popleft()
282
- elif downstream_name == 'Wholesaler':
283
- if state['wholesaler_order_pipeline']:
284
- incoming_order_for_this_week = state['wholesaler_order_pipeline'].popleft()
285
- elif downstream_name == 'Retailer':
286
- if state['retailer_order_pipeline']:
287
- incoming_order_for_this_week = state['retailer_order_pipeline'].popleft()
288
-
289
- echelons[name]['incoming_order'] = incoming_order_for_this_week # Store for logging/display
290
- total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
291
 
 
 
292
 
293
  # --- Create State Snapshot for AI/Human Decision Point ---
 
294
  decision_point_states = {}
295
  for name in echelon_order:
 
296
  decision_point_states[name] = {
297
  'name': name,
298
  'inventory': inventory_after_arrival[name], # Inventory available
299
  'backlog': total_backlog_before_shipping[name], # Total demand to meet
300
  'incoming_order': echelons[name]['incoming_order'], # Order received this week
 
301
  'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
302
  }
303
 
304
  # --- Step 4: Agent Decisions (Place Orders / Schedule Production) ---
 
305
  current_week_orders = {}
306
  for name in echelon_order:
307
- e = echelons[name]
308
- prompt_state = decision_point_states[name]
309
 
310
  if name == human_role:
311
  order_amount, raw_resp = human_final_order, "HUMAN_FINAL_INPUT"
@@ -314,63 +290,52 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
314
  order_amount, raw_resp = get_llm_order_decision(prompt, name)
315
 
316
  llm_raw_responses[name] = raw_resp
317
- e['order_placed'] = max(0, order_amount)
318
- current_week_orders[name] = e['order_placed']
319
 
320
- # Put the order into the correct pipeline to simulate ORDER_PASSING_DELAY
321
- if name == 'Distributor': state['distributor_order_pipeline'].append(e['order_placed'])
322
- elif name == 'Wholesaler': state['wholesaler_order_pipeline'].append(e['order_placed'])
323
- elif name == 'Retailer': state['retailer_order_pipeline'].append(e['order_placed'])
324
- # Factory's 'order_placed' is its production decision
325
-
326
-
327
- # Step 4b: Factory schedules production
328
- # Factory's decision ('order_placed') enters the production pipeline
329
  state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
330
 
331
 
332
  # --- Step 3: Fulfill orders (Ship Beer) ---
333
- # Occurs after decisions, uses inventory_after_arrival and total_backlog_before_shipping
334
- units_produced_and_shipped_by_factory = 0 # Track for adding to Distributor's shipment queue
335
  for name in echelon_order:
336
  e = echelons[name]
337
  demand_to_meet = total_backlog_before_shipping[name]
338
  available_inv = inventory_after_arrival[name]
339
 
340
  e['shipment_sent'] = min(available_inv, demand_to_meet)
 
 
341
  # Update the main state dict's inventory and backlog to reflect END OF WEEK state
342
  e['inventory'] = available_inv - e['shipment_sent']
343
  e['backlog'] = demand_to_meet - e['shipment_sent']
344
 
345
- # If Factory, what it 'sent' was actually produced and ready for shipping delay
346
- if name == "Factory":
347
- units_produced_and_shipped_by_factory = e['shipment_sent']
348
-
349
- # Step 3b: Place items shipped by Factory/Distributor/Wholesaler into appropriate shipment queues
350
  # Factory -> Distributor (uses FACTORY_SHIPPING_DELAY)
351
- if units_produced_and_shipped_by_factory > 0:
352
- echelons['Distributor']['incoming_shipments'].append(units_produced_and_shipped_by_factory)
353
  # Distributor -> Wholesaler (uses SHIPPING_DELAY)
354
- if echelons['Distributor']['shipment_sent'] > 0:
355
- echelons['Wholesaler']['incoming_shipments'].append(echelons['Distributor']['shipment_sent'])
356
  # Wholesaler -> Retailer (uses SHIPPING_DELAY)
357
- if echelons['Wholesaler']['shipment_sent'] > 0:
358
- echelons['Retailer']['incoming_shipments'].append(echelons['Wholesaler']['shipment_sent'])
359
 
360
 
361
  # --- Calculate Costs & Log (End of Week) ---
362
  log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
363
- del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs']
364
- # Delete the specific order pipelines as well
365
- for key in ['distributor_order_pipeline', 'wholesaler_order_pipeline', 'retailer_order_pipeline']:
366
- if key in log_entry: del log_entry[key]
367
-
368
 
369
  for name in echelon_order:
370
  e = echelons[name]
 
371
  e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST)
372
  e['total_cost'] += e['weekly_cost']
373
 
 
374
  log_entry[f'{name}.inventory'] = e['inventory']; log_entry[f'{name}.backlog'] = e['backlog']
375
  log_entry[f'{name}.incoming_order'] = e['incoming_order']; log_entry[f'{name}.order_placed'] = e['order_placed']
376
  log_entry[f'{name}.shipment_sent'] = e['shipment_sent']; log_entry[f'{name}.weekly_cost'] = e['weekly_cost']
@@ -378,11 +343,13 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
378
  log_entry[f'{name}.opening_inventory'] = opening_inventories[name]; log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
379
  log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name]
380
 
 
381
  if name != 'Factory':
382
  log_entry[f'{name}.arriving_next_week'] = list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0
383
  else:
384
  log_entry[f'{name}.production_completing_next_week'] = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
385
 
 
386
  log_entry[f'{human_role}.initial_order'] = human_initial_order
387
  log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
388
 
@@ -391,8 +358,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
391
  # --- Advance Week ---
392
  state['week'] += 1
393
  state['decision_step'] = 'initial_order'
394
- # 'last_week_orders' is no longer needed with pipeline approach
395
- # if 'last_week_orders' in state: del state['last_week_orders']
396
 
397
  if state['week'] > WEEKS: state['game_running'] = False
398
  # ==============================================================================
@@ -438,24 +404,30 @@ def plot_results(df: pd.DataFrame, title: str, human_role: str):
438
  # Safely access human decision columns
439
  human_cols = [f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed']
440
  human_df_cols = ['week'] + [col for col in human_cols if col in df.columns]
441
- human_df = df[human_df_cols].copy()
442
- human_df.rename(columns={
443
- f'{human_role}.initial_order': 'Your Initial Order',
444
- f'{human_role}.ai_suggestion': 'AI Suggestion',
445
- f'{human_role}.order_placed': 'Your Final Order'
446
- }, inplace=True)
447
-
448
- if len(human_df.columns) > 1: # Check if there's data to plot
449
- human_df.plot(x='week', ax=axes[3], marker='o', linestyle='-')
450
- axes[3].set_title(f'Analysis of Your ({human_role}) Decisions')
451
- axes[3].set_ylabel('Order Quantity')
452
- axes[3].grid(True, linestyle='--')
453
- axes[3].set_xlabel('Week')
454
- else:
455
- axes[3].set_title(f'Analysis of Your ({human_role}) Decisions - No Data')
 
 
 
 
 
456
  axes[3].grid(True, linestyle='--')
457
  axes[3].set_xlabel('Week')
458
 
 
459
  plt.tight_layout(rect=[0, 0, 1, 0.96])
460
  return fig
461
 
@@ -463,33 +435,38 @@ def save_logs_and_upload(state: dict):
463
  # This function remains correct.
464
  if not state.get('logs'): return
465
  participant_id = state['participant_id']
466
- df = pd.json_normalize(state['logs'])
467
- fname = LOCAL_LOG_DIR / f"log_{participant_id}_{int(time.time())}.csv"
468
-
469
- for col in df.columns:
470
- if df[col].dtype == 'object': df[col] = df[col].astype(str)
471
-
472
- df.to_csv(fname, index=False)
473
- st.success(f"Log successfully saved locally: `{fname}`")
474
- with open(fname, "rb") as f:
475
- st.download_button("📥 Download Log CSV", data=f, file_name=fname.name, mime="text/csv")
476
-
477
- if HF_TOKEN and HF_REPO_ID and hf_api:
478
- with st.spinner("Uploading log to Hugging Face Hub..."):
479
- try:
480
- url = hf_api.upload_file(
481
- path_or_fileobj=str(fname),
482
- path_in_repo=f"logs/{fname.name}",
483
- repo_id=HF_REPO_ID,
484
- repo_type="dataset",
485
- token=HF_TOKEN
486
- )
487
- st.success(f"✅ Log successfully uploaded to Hugging Face! [View File]({url})")
488
- except Exception as e:
489
- st.error(f"Upload to Hugging Face failed: {e}")
 
 
 
 
 
490
 
491
  # -----------------------------------------------------------------------------
492
- # 4. Streamlit UI (Minor adjustments for clarity)
493
  # -----------------------------------------------------------------------------
494
  st.title("🍺 The Beer Game: A Human-AI Collaboration Challenge")
495
 
@@ -576,8 +553,8 @@ else:
576
  The dashboard shows your status **at the start of the week, BEFORE Steps 1, 2, and 3 happen**:
577
  * `Inventory (Opening)`: Your stock **at the beginning of the week**.
578
  * `Backlog (Opening)`: Unfilled orders **carried over from the end of last week**.
579
- * `Incoming Order (This Week)`: The specific order quantity that **will arrive** from the Wholesaler *during* this week (Step 2).
580
- * `Arriving Next Week`: The quantity scheduled to arrive at the start of the **next week**.
581
  * `Your Total Cumulative Cost`: Sum of all weekly costs up to the **end of last week**.
582
  * `Cost Last Week`: The specific cost incurred just **last week**.
583
 
@@ -630,7 +607,7 @@ else:
630
  last_week_cost = state['logs'][-1][f"{human_role}.weekly_cost"] if week > 1 and state['logs'] else 0
631
  st.metric("Cost Last Week", f"${last_week_cost:,.2f}")
632
 
633
- # Display info about THIS week's events
634
  st.write(f"Incoming Order (This Week): **{e['incoming_order']}**") # Order arriving in Step 2
635
  if name == "Factory":
636
  # Production completing NEXT week
@@ -663,9 +640,9 @@ else:
663
  # Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
664
  all_decision_point_states = {}
665
  for name in echelon_order:
666
- e_curr = echelons[name]
667
  arrived = 0
668
- # Peek at what *will* arrive this week (Step 1)
669
  if name == "Factory":
670
  # Peek at production pipeline
671
  if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
@@ -673,11 +650,16 @@ else:
673
  # Peek at incoming shipments
674
  if e_curr['incoming_shipments']: arrived = list(e_curr['incoming_shipments'])[0]
675
 
 
 
 
 
676
  all_decision_point_states[name] = {
677
  'name': name,
678
- 'inventory': e_curr['inventory'] + arrived, # Opening Inv + Arriving This Week
679
- 'backlog': e_curr['backlog'] + e_curr['incoming_order'], # Opening Backlog + Incoming Order This Week
680
- 'incoming_order': e_curr['incoming_order'],
 
681
  'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
682
  }
683
  human_echelon_state_for_prompt = all_decision_point_states[human_role]
@@ -740,6 +722,7 @@ else:
740
  else:
741
  display_df = history_df[final_cols_to_display].rename(columns=human_cols)
742
  if 'Weekly Cost' in display_df.columns:
 
743
  display_df['Weekly Cost'] = display_df['Weekly Cost'].apply(lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "")
744
  st.dataframe(display_df.sort_values(by="Week", ascending=False), hide_index=True, use_container_width=True)
745
  except Exception as e:
 
1
  # app.py
2
+ # @title Beer Game Final Version (v4.17 - Simplified Order Logic & State Clarity - COMPLETE CODE)
3
 
4
  # -----------------------------------------------------------------------------
5
  # 1. Import Libraries
 
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
 
63
  def get_customer_demand(week: int) -> int:
64
  return 4 if week <= 4 else 8
65
 
66
+ # =============== CORRECTED Initialization ===============
67
  def init_game_state(llm_personality: str, info_sharing: str):
68
  roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
69
  human_role = "Distributor" # Role is fixed
 
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, representing the state before week 1
80
+ 'last_week_orders': {name: 0 for name in roles}
81
  }
82
 
83
  for i, name in enumerate(roles):
 
118
  raw_text = response.choices[0].message.content.strip()
119
  match = re.search(r'\d+', raw_text)
120
  if match: return int(match.group(0)), raw_text
121
+ st.warning(f"LLM for {echelon_name} did not return a valid number. Defaulting to 4. Raw Response: '{raw_text}'")
122
+ return 4, raw_text # Default to 4 if no number found
123
  except Exception as e:
124
+ st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
125
+ return 4, f"API_ERROR: {e}"
126
 
127
+ # =============== MODIFIED FUNCTION (Prompt uses simplified state) ===============
128
+ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
129
  """Generates the prompt for the LLM based on the game scenario.
130
+ Uses the state AFTER arrivals and new orders are processed (decision point)."""
131
 
132
+ e_state = echelon_state_decision_point
133
 
134
  # Base Info reflects state before shipping
135
  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"
136
 
137
  if e_state['name'] == 'Factory':
138
  task_word = "production quantity"
 
139
  base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
140
  else:
141
  task_word = "order quantity"
142
+ base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}" # This queue length matches shipping delay
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  # --- Perfect Rational ---
145
  if llm_personality == 'perfect_rational' and info_sharing == 'full':
146
  stable_demand = 8
147
+ # Lead time calculation remains the same for target inventory
148
  if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME
149
  elif e_state['name'] == 'Distributor': total_lead_time = ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY
150
  else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY
151
  safety_stock = 4
152
  target_inventory_level = (stable_demand * total_lead_time) + safety_stock
153
 
154
+ # Calculate Inventory Position based on decision point state + relevant pipelines
155
  if e_state['name'] == 'Factory':
156
  # IP = Inv - Backlog + In Production
157
  inventory_position = (e_state['inventory'] - e_state['backlog'] + sum(st.session_state.game_state['factory_production_pipeline']))
158
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InProd={sum(st.session_state.game_state['factory_production_pipeline'])})"
159
  else:
160
+ # IP = Inv - Backlog + In Transit Shipments + Order Placed Last Week (in transit to supplier)
161
+ order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
162
+
163
+ inventory_position = (e_state['inventory'] - e_state['backlog'] + sum(e_state['incoming_shipments']) + order_in_transit_to_supplier)
164
+ inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
 
 
165
 
166
  optimal_order = max(0, int(target_inventory_level - inventory_position))
167
 
 
175
  supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
176
  supply_line_desc = "In Production"
177
  else:
178
+ # Supply line includes shipments AND the order placed last week
179
+ order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
180
+ supply_line = sum(e_state['incoming_shipments']) + order_in_transit_to_supplier
181
+ supply_line_desc = "Supply Line (In Transit Shipments + Order To Supplier)"
 
 
 
182
 
183
  calculated_order = anchor_demand + inventory_correction - supply_line
184
  rational_local_order = max(0, int(calculated_order))
185
 
186
+ 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."
187
 
188
  # --- Human-like ---
189
  elif llm_personality == 'human_like' and info_sharing == 'full':
190
  full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
191
+ for name, other_e_state in all_echelons_state_decision_point.items():
192
  if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
193
 
194
  return f"""
 
213
  """
214
  # ==============================================================================
215
 
216
+ # =============== CORRECTED step_game FUNCTION (Simplified Order Logic) ===============
217
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
218
  state = st.session_state.game_state
219
  week, echelons, human_role = state['week'], state['echelons'], state['human_role']
 
221
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Defined here
222
  llm_raw_responses = {}
223
 
224
+ # Store state at the very beginning of the week (End of last week)
225
  opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
226
  opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
227
  arrived_this_week = {name: 0 for name in echelon_order} # Track arrivals for logging
 
234
  factory_state = echelons["Factory"]
235
  produced_units = 0
236
  if state['factory_production_pipeline']:
237
+ produced_units = state['factory_production_pipeline'].popleft() # Pop completed production
238
  arrived_this_week["Factory"] = produced_units
239
  inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
240
 
 
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() # Pop arrived shipment
246
  arrived_this_week[name] = arrived_shipment
247
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
248
 
 
249
  # Step 2: Orders Arrive from Downstream & Update Temp Backlog
250
+ # Orders arrive based on LAST WEEK's placed order (Delay = 1)
251
  total_backlog_before_shipping = {} # Store intermediate backlog state
252
  for name in echelon_order:
253
  incoming_order_for_this_week = 0
254
  if name == "Retailer":
255
  incoming_order_for_this_week = get_customer_demand(week)
256
  else:
 
257
  downstream_name = echelons[name]['downstream_name']
258
+ if downstream_name:
259
+ # Use the order placed by the downstream partner LAST week
260
+ incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
 
 
 
 
 
 
 
 
 
261
 
262
+ echelons[name]['incoming_order'] = incoming_order_for_this_week # Store for logging/UI this week
263
+ total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
264
 
265
  # --- Create State Snapshot for AI/Human Decision Point ---
266
+ # This reflects the state AFTER arrivals and new orders, BEFORE shipping
267
  decision_point_states = {}
268
  for name in echelon_order:
269
+ # Need a copy, including DEQUEUES for prompt generation
270
  decision_point_states[name] = {
271
  'name': name,
272
  'inventory': inventory_after_arrival[name], # Inventory available
273
  'backlog': total_backlog_before_shipping[name], # Total demand to meet
274
  'incoming_order': echelons[name]['incoming_order'], # Order received this week
275
+ # Pass the current state of queues for prompt generation
276
  'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
277
  }
278
 
279
  # --- Step 4: Agent Decisions (Place Orders / Schedule Production) ---
280
+ # Agents make decisions based on the decision_point_states
281
  current_week_orders = {}
282
  for name in echelon_order:
283
+ e = echelons[name] # Get the main state dict to store results
284
+ prompt_state = decision_point_states[name] # Use the snapshot for the prompt
285
 
286
  if name == human_role:
287
  order_amount, raw_resp = human_final_order, "HUMAN_FINAL_INPUT"
 
290
  order_amount, raw_resp = get_llm_order_decision(prompt, name)
291
 
292
  llm_raw_responses[name] = raw_resp
293
+ e['order_placed'] = max(0, order_amount) # Store the decision in the main state dict
294
+ current_week_orders[name] = e['order_placed'] # Store for NEXT week's Step 2
295
 
296
+ # Factory schedules production based on its 'order_placed' decision
 
 
 
 
 
 
 
 
297
  state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
298
 
299
 
300
  # --- Step 3: Fulfill orders (Ship Beer) ---
301
+ # Uses inventory_after_arrival and total_backlog_before_shipping
302
+ units_shipped = {name: 0 for name in echelon_order}
303
  for name in echelon_order:
304
  e = echelons[name]
305
  demand_to_meet = total_backlog_before_shipping[name]
306
  available_inv = inventory_after_arrival[name]
307
 
308
  e['shipment_sent'] = min(available_inv, demand_to_meet)
309
+ units_shipped[name] = e['shipment_sent'] # Store temporarily
310
+
311
  # Update the main state dict's inventory and backlog to reflect END OF WEEK state
312
  e['inventory'] = available_inv - e['shipment_sent']
313
  e['backlog'] = demand_to_meet - e['shipment_sent']
314
 
315
+ # Step 3b: Place shipped items into the *end* of the downstream partner's incoming shipment queue
 
 
 
 
316
  # Factory -> Distributor (uses FACTORY_SHIPPING_DELAY)
317
+ if units_shipped["Factory"] > 0:
318
+ echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
319
  # Distributor -> Wholesaler (uses SHIPPING_DELAY)
320
+ if units_shipped['Distributor'] > 0:
321
+ echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
322
  # Wholesaler -> Retailer (uses SHIPPING_DELAY)
323
+ if units_shipped['Wholesaler'] > 0:
324
+ echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
325
 
326
 
327
  # --- Calculate Costs & Log (End of Week) ---
328
  log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
329
+ # Clean up fields not suitable for direct logging
330
+ del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
 
 
 
331
 
332
  for name in echelon_order:
333
  e = echelons[name]
334
+ # Costs are based on the END OF WEEK state
335
  e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST)
336
  e['total_cost'] += e['weekly_cost']
337
 
338
+ # Log end-of-week internal state and decisions/events of the week
339
  log_entry[f'{name}.inventory'] = e['inventory']; log_entry[f'{name}.backlog'] = e['backlog']
340
  log_entry[f'{name}.incoming_order'] = e['incoming_order']; log_entry[f'{name}.order_placed'] = e['order_placed']
341
  log_entry[f'{name}.shipment_sent'] = e['shipment_sent']; log_entry[f'{name}.weekly_cost'] = e['weekly_cost']
 
343
  log_entry[f'{name}.opening_inventory'] = opening_inventories[name]; log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
344
  log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name]
345
 
346
+ # Log prediction for next week's arrival/completion (based on queues AFTER this week's processing)
347
  if name != 'Factory':
348
  log_entry[f'{name}.arriving_next_week'] = list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0
349
  else:
350
  log_entry[f'{name}.production_completing_next_week'] = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
351
 
352
+ # Log human-specific decisions
353
  log_entry[f'{human_role}.initial_order'] = human_initial_order
354
  log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
355
 
 
358
  # --- Advance Week ---
359
  state['week'] += 1
360
  state['decision_step'] = 'initial_order'
361
+ state['last_week_orders'] = current_week_orders # Store current decisions for next week's Step 2
 
362
 
363
  if state['week'] > WEEKS: state['game_running'] = False
364
  # ==============================================================================
 
404
  # Safely access human decision columns
405
  human_cols = [f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed']
406
  human_df_cols = ['week'] + [col for col in human_cols if col in df.columns]
407
+
408
+ # Add try-except for robust plotting if columns are missing
409
+ try:
410
+ human_df = df[human_df_cols].copy()
411
+ human_df.rename(columns={
412
+ f'{human_role}.initial_order': 'Your Initial Order',
413
+ f'{human_role}.ai_suggestion': 'AI Suggestion',
414
+ f'{human_role}.order_placed': 'Your Final Order'
415
+ }, inplace=True)
416
+
417
+ if len(human_df.columns) > 1: # Check if there's data to plot
418
+ human_df.plot(x='week', ax=axes[3], marker='o', linestyle='-')
419
+ axes[3].set_title(f'Analysis of Your ({human_role}) Decisions')
420
+ axes[3].set_ylabel('Order Quantity')
421
+ axes[3].grid(True, linestyle='--')
422
+ axes[3].set_xlabel('Week')
423
+ else: raise ValueError("No human decision data columns found.")
424
+ except (KeyError, ValueError) as plot_err:
425
+ axes[3].set_title(f'Analysis of Your ({human_role}) Decisions - Error Plotting Data')
426
+ axes[3].text(0.5, 0.5, f"Error: {plot_err}", ha='center', va='center')
427
  axes[3].grid(True, linestyle='--')
428
  axes[3].set_xlabel('Week')
429
 
430
+
431
  plt.tight_layout(rect=[0, 0, 1, 0.96])
432
  return fig
433
 
 
435
  # This function remains correct.
436
  if not state.get('logs'): return
437
  participant_id = state['participant_id']
438
+ try:
439
+ df = pd.json_normalize(state['logs'])
440
+ fname = LOCAL_LOG_DIR / f"log_{participant_id}_{int(time.time())}.csv"
441
+
442
+ # Convert potential object columns safely before saving
443
+ for col in df.select_dtypes(include=['object']).columns:
444
+ df[col] = df[col].astype(str)
445
+
446
+ df.to_csv(fname, index=False)
447
+ st.success(f"Log successfully saved locally: `{fname}`")
448
+ with open(fname, "rb") as f:
449
+ st.download_button("📥 Download Log CSV", data=f, file_name=fname.name, mime="text/csv")
450
+
451
+ if HF_TOKEN and HF_REPO_ID and hf_api:
452
+ with st.spinner("Uploading log to Hugging Face Hub..."):
453
+ try:
454
+ url = hf_api.upload_file(
455
+ path_or_fileobj=str(fname),
456
+ path_in_repo=f"logs/{fname.name}",
457
+ repo_id=HF_REPO_ID,
458
+ repo_type="dataset",
459
+ token=HF_TOKEN
460
+ )
461
+ st.success(f" Log successfully uploaded to Hugging Face! [View File]({url})")
462
+ except Exception as e_upload:
463
+ st.error(f"Upload to Hugging Face failed: {e_upload}")
464
+ except Exception as e_save:
465
+ st.error(f"Error processing or saving log data: {e_save}")
466
+
467
 
468
  # -----------------------------------------------------------------------------
469
+ # 4. Streamlit UI (Adjusted Dashboard Labels)
470
  # -----------------------------------------------------------------------------
471
  st.title("🍺 The Beer Game: A Human-AI Collaboration Challenge")
472
 
 
553
  The dashboard shows your status **at the start of the week, BEFORE Steps 1, 2, and 3 happen**:
554
  * `Inventory (Opening)`: Your stock **at the beginning of the week**.
555
  * `Backlog (Opening)`: Unfilled orders **carried over from the end of last week**.
556
+ * `Incoming Order (This Week)`: The specific order quantity that **will arrive** from the Wholesaler *during* this week (Step 2). Use this for your planning.
557
+ * `Arriving Next Week`: The quantity scheduled to arrive at the start of the **next week**. Use this for your planning.
558
  * `Your Total Cumulative Cost`: Sum of all weekly costs up to the **end of last week**.
559
  * `Cost Last Week`: The specific cost incurred just **last week**.
560
 
 
607
  last_week_cost = state['logs'][-1][f"{human_role}.weekly_cost"] if week > 1 and state['logs'] else 0
608
  st.metric("Cost Last Week", f"${last_week_cost:,.2f}")
609
 
610
+ # Display info about THIS week's events / NEXT week's arrivals
611
  st.write(f"Incoming Order (This Week): **{e['incoming_order']}**") # Order arriving in Step 2
612
  if name == "Factory":
613
  # Production completing NEXT week
 
640
  # Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
641
  all_decision_point_states = {}
642
  for name in echelon_order:
643
+ e_curr = echelons[name] # This is END OF LAST WEEK state
644
  arrived = 0
645
+ # Peek at what *will* arrive this week (Step 1) based on current queues
646
  if name == "Factory":
647
  # Peek at production pipeline
648
  if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
 
650
  # Peek at incoming shipments
651
  if e_curr['incoming_shipments']: arrived = list(e_curr['incoming_shipments'])[0]
652
 
653
+ # Calculate the state AFTER arrivals and incoming orders for the prompt
654
+ inv_after_arrival = e_curr['inventory'] + arrived
655
+ backlog_after_new_order = e_curr['backlog'] + e_curr['incoming_order']
656
+
657
  all_decision_point_states[name] = {
658
  'name': name,
659
+ 'inventory': inv_after_arrival, # State for decision making
660
+ 'backlog': backlog_after_new_order, # State for decision making
661
+ 'incoming_order': e_curr['incoming_order'], # Info for decision making
662
+ # Pass queue state as it is at start of week for prompt context
663
  'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
664
  }
665
  human_echelon_state_for_prompt = all_decision_point_states[human_role]
 
722
  else:
723
  display_df = history_df[final_cols_to_display].rename(columns=human_cols)
724
  if 'Weekly Cost' in display_df.columns:
725
+ # Safely apply formatting, handling potential non-numeric data
726
  display_df['Weekly Cost'] = display_df['Weekly Cost'].apply(lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "")
727
  st.dataframe(display_df.sort_values(by="Week", ascending=False), hide_index=True, use_container_width=True)
728
  except Exception as e: