Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
# app.py
|
| 2 |
-
# @title Beer Game Final Version (v4.
|
| 3 |
-
|
| 4 |
# -----------------------------------------------------------------------------
|
| 5 |
# 1. Import Libraries
|
| 6 |
# -----------------------------------------------------------------------------
|
|
@@ -22,7 +21,6 @@ from huggingface_hub import HfApi
|
|
| 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 |
# -----------------------------------------------------------------------------
|
|
@@ -55,11 +53,9 @@ except Exception as e:
|
|
| 55 |
else:
|
| 56 |
st.session_state.initialization_error = None
|
| 57 |
|
| 58 |
-
|
| 59 |
# -----------------------------------------------------------------------------
|
| 60 |
# 3. Core Game Logic Functions
|
| 61 |
# -----------------------------------------------------------------------------
|
| 62 |
-
|
| 63 |
def get_customer_demand(week: int) -> int:
|
| 64 |
return 4 if week <= 4 else 8
|
| 65 |
|
|
@@ -67,7 +63,6 @@ def init_game_state(llm_personality: str, info_sharing: str):
|
|
| 67 |
roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 68 |
human_role = "Distributor" # Role is fixed
|
| 69 |
participant_id = str(uuid.uuid4())[:8]
|
| 70 |
-
|
| 71 |
st.session_state.game_state = {
|
| 72 |
'game_running': True, 'participant_id': participant_id, 'week': 1,
|
| 73 |
'human_role': human_role, 'llm_personality': llm_personality,
|
|
@@ -77,15 +72,12 @@ def init_game_state(llm_personality: str, info_sharing: str):
|
|
| 77 |
'human_initial_order': None,
|
| 78 |
'last_week_orders': {name: 0 for name in roles}
|
| 79 |
}
|
| 80 |
-
|
| 81 |
for i, name in enumerate(roles):
|
| 82 |
upstream = roles[i + 1] if i + 1 < len(roles) else None
|
| 83 |
downstream = roles[i - 1] if i - 1 >= 0 else None
|
| 84 |
-
|
| 85 |
if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY
|
| 86 |
elif name == "Factory": shipping_weeks = 0
|
| 87 |
else: shipping_weeks = SHIPPING_DELAY
|
| 88 |
-
|
| 89 |
st.session_state.game_state['echelons'][name] = {
|
| 90 |
'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
|
| 91 |
'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
|
|
@@ -127,6 +119,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 127 |
else:
|
| 128 |
task_word = "order quantity"
|
| 129 |
base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
|
|
|
|
| 130 |
if llm_personality == 'perfect_rational' and info_sharing == 'full':
|
| 131 |
stable_demand = 8
|
| 132 |
if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME
|
|
@@ -143,6 +136,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 143 |
inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
|
| 144 |
optimal_order = max(0, int(target_inventory_level - inventory_position))
|
| 145 |
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."
|
|
|
|
| 146 |
elif llm_personality == 'perfect_rational' and info_sharing == 'local':
|
| 147 |
safety_stock = 4; anchor_demand = e_state['incoming_order']
|
| 148 |
inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
|
|
@@ -156,6 +150,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 156 |
calculated_order = anchor_demand + inventory_correction - supply_line
|
| 157 |
rational_local_order = max(0, int(calculated_order))
|
| 158 |
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."
|
|
|
|
| 159 |
elif llm_personality == 'human_like' and info_sharing == 'full':
|
| 160 |
full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
|
| 161 |
for name, other_e_state in all_echelons_state_decision_point.items():
|
|
@@ -170,6 +165,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 170 |
You are still human and might get anxious about your own stock levels.
|
| 171 |
What {task_word} should you decide on this week? Respond with a single integer.
|
| 172 |
"""
|
|
|
|
| 173 |
elif llm_personality == 'human_like' and info_sharing == 'local':
|
| 174 |
return f"""
|
| 175 |
**You are a reactive supply chain manager for the {e_state['name']}.** You have a limited view and tend to over-correct based on fear.
|
|
@@ -187,22 +183,27 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 187 |
llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
|
| 188 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 189 |
llm_raw_responses = {}
|
|
|
|
| 190 |
opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
|
| 191 |
opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
|
|
|
|
| 192 |
arrived_this_week = {name: 0 for name in echelon_order}
|
| 193 |
inventory_after_arrival = {}
|
|
|
|
| 194 |
factory_state = echelons["Factory"]
|
| 195 |
produced_units = 0
|
| 196 |
if state['factory_production_pipeline']:
|
| 197 |
produced_units = state['factory_production_pipeline'].popleft()
|
| 198 |
arrived_this_week["Factory"] = produced_units
|
| 199 |
inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
|
|
|
|
| 200 |
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 201 |
arrived_shipment = 0
|
| 202 |
if echelons[name]['incoming_shipments']:
|
| 203 |
arrived_shipment = echelons[name]['incoming_shipments'].popleft()
|
| 204 |
arrived_this_week[name] = arrived_shipment
|
| 205 |
inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
|
|
|
|
| 206 |
total_backlog_before_shipping = {}
|
| 207 |
for name in echelon_order:
|
| 208 |
incoming_order_for_this_week = 0
|
|
@@ -212,6 +213,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 212 |
if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
|
| 213 |
echelons[name]['incoming_order'] = incoming_order_for_this_week
|
| 214 |
total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
|
|
|
|
| 215 |
decision_point_states = {}
|
| 216 |
for name in echelon_order:
|
| 217 |
decision_point_states[name] = {
|
|
@@ -219,6 +221,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 219 |
'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
|
| 220 |
'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
|
| 221 |
}
|
|
|
|
| 222 |
current_week_orders = {}
|
| 223 |
for name in echelon_order:
|
| 224 |
e = echelons[name]; prompt_state = decision_point_states[name]
|
|
@@ -227,15 +230,19 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 227 |
prompt = get_llm_prompt(prompt_state, week, llm_personality, info_sharing, decision_point_states)
|
| 228 |
order_amount, raw_resp = get_llm_order_decision(prompt, name)
|
| 229 |
llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
|
|
|
|
| 230 |
state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
|
|
|
|
| 231 |
units_shipped = {name: 0 for name in echelon_order}
|
| 232 |
for name in echelon_order:
|
| 233 |
e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
|
| 234 |
e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
|
| 235 |
e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
|
|
|
|
| 236 |
if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
|
| 237 |
if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
|
| 238 |
if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
|
|
|
|
| 239 |
log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
|
| 240 |
del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
|
| 241 |
for name in echelon_order:
|
|
@@ -248,6 +255,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 248 |
else: log_entry[f'{name}.production_completing_next_week'] = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
|
| 249 |
log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
|
| 250 |
state['logs'].append(log_entry)
|
|
|
|
| 251 |
state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
|
| 252 |
if state['week'] > WEEKS: state['game_running'] = False
|
| 253 |
|
|
@@ -310,66 +318,16 @@ if st.session_state.get('initialization_error'):
|
|
| 310 |
else:
|
| 311 |
# --- Game Setup & Instructions ---
|
| 312 |
if 'game_state' not in st.session_state or not st.session_state.game_state.get('game_running', False):
|
| 313 |
-
|
| 314 |
-
# --- Introduction Section
|
| 315 |
-
|
| 316 |
-
st.header("📖 Welcome to the Beer Game!")
|
| 317 |
-
st.markdown("This is a simulation of a supply chain. You will play against 3 AI agents. **You do not need any prior knowledge to play.** Please read these instructions carefully.")
|
| 318 |
-
st.subheader("1. Your Goal: Minimize Costs")
|
| 319 |
-
st.success("**Your single, most important goal is to: Minimize the total cost for your position in the supply chain.**")
|
| 320 |
-
st.markdown("You get costs from two things every week:")
|
| 321 |
-
st.markdown(f"- **Holding Inventory:** **${HOLDING_COST:,.2f} per unit per week.** (Cost applies to inventory left *after* shipping)\n- **Backlog (Unfilled Orders):** **${BACKLOG_COST:,.2f} per unit per week.** (Cost applies to orders you couldn't fill *after* shipping)")
|
| 322 |
-
with st.expander("Click to see a cost calculation example"):
|
| 323 |
-
st.markdown(f"Imagine at the **end** of Week 5, *after* you shipped beer to the Wholesaler, your final state is:\n- Inventory: 10 units\n- Backlog: 0 units\nYour cost for Week 5 would be calculated *at this point*:\n- `(10 units of Inventory * ${HOLDING_COST:,.2f})` = $5.00\n- `(0 units of Backlog * ${BACKLOG_COST:,.2f})` = $0.00\n- **Total Weekly Cost:** = **$5.00**\nThis cost is added to your cumulative total.")
|
| 324 |
-
st.subheader("2. Your Role: The Distributor")
|
| 325 |
-
st.markdown("You will always play as the **Distributor**. The other 3 roles are played by AI.\n- **Retailer (AI):** Sells to the final customer.\n- **Wholesaler (AI):** Sells to the Retailer.\n- **Distributor (You):** You sell to the Wholesaler.\n- **Factory (AI):** You order from the Factory.")
|
| 326 |
-
try: st.image(IMAGE_PATH, caption="You are the Distributor. You get orders from the Wholesaler and place orders to the Factory.")
|
| 327 |
-
except FileNotFoundError: st.warning("Image file not found.")
|
| 328 |
-
st.subheader("3. The Core Challenge: Delays!")
|
| 329 |
-
st.warning(f"It takes **{ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY} weeks** for an order you place to arrive in your inventory.")
|
| 330 |
-
with st.expander("Click to see a detailed example of the 3-week delay"):
|
| 331 |
-
st.markdown(f"* **Week 10 (You):** You place an order for **50**.\n* **Week 11 (System):** Your order arrives at the Factory (**{ORDER_PASSING_DELAY}w Order Delay**). Factory AI decides to produce 50.\n* **Week 12 (System):** Factory finishes producing 50 (**{FACTORY_LEAD_TIME}w Production Delay**) & ships it.\n* **Week 13 (System):** The 50 units arrive at your warehouse (**{FACTORY_SHIPPING_DELAY}w Shipping Delay**).\n**Conclusion:** Think 3 weeks ahead! Your order in Week 10 arrives at the start of Week 13.")
|
| 332 |
-
st.subheader("4. Understanding Inventory & Backlog")
|
| 333 |
-
st.markdown("Managing your inventory and backlog is key to minimizing costs. Here's how they work:\n* **Effective \"Orders to Fill\":** Each week, the total demand you need to satisfy is your `Incoming Order` for the week PLUS any `Backlog` carried over from the previous week.\n* **If you DON'T have enough inventory:**\n * You ship **all** the inventory you have (after receiving any arrivals for the week).\n * The remaining unfilled \"Orders to Fill\" becomes your **new Backlog** for next week.\n * **Backlog is cumulative!** If you start Week 10 with a backlog of 5, get an order for 8 (total needed = 13), receive 10 units, and ship those 10 units, your new backlog for Week 11 is `13 - 10 = 3`.\n* **If you DO have enough inventory:**\n * You ship all the \"Orders to Fill\".\n * Your Backlog becomes 0.\n * The remaining inventory is carried over to next week (and incurs holding costs).")
|
| 334 |
-
st.subheader("5. The Bullwhisp Effect (What to Avoid)")
|
| 335 |
-
st.markdown("The \"Bullwhip Effect\" happens when small changes in customer demand cause **amplified**, chaotic swings in orders further up the supply chain (like you and the Factory). This often leads to cycles of **panic ordering** (ordering too much when out of stock) followed by **massive inventory pile-ups** (when late orders arrive). This cycle is very expensive. Try to order smoothly.")
|
| 336 |
-
|
| 337 |
-
# =============== UPDATED: How Each Week Works & Dashboard Explanation ===============
|
| 338 |
-
st.subheader("6. How Each Week Works & Understanding Your Dashboard")
|
| 339 |
-
st.markdown(f"""
|
| 340 |
-
Your main job is simple: place one order each week based on the dashboard presented to you.
|
| 341 |
-
|
| 342 |
-
**A) At the start of every week, BEFORE your turn:**
|
| 343 |
-
* **(Step 1) Shipments Arrive:** Beer you ordered {ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY} weeks ago arrives.
|
| 344 |
-
* **(Step 2) New Orders Arrive:** You receive a new order from the Wholesaler (this is their order placed *last* week, due to the {ORDER_PASSING_DELAY} week delay).
|
| 345 |
-
* **(Step 3) You Ship Beer (Automatically):** The system ships beer *immediately* based on your inventory *after* Step 1 and the total demand *after* Step 2.
|
| 346 |
-
|
| 347 |
-
**B) Your Dashboard (What You See for Your Turn):**
|
| 348 |
-
The dashboard shows your status **at the start of the week, BEFORE Steps 1, 2, and 3 happen**:
|
| 349 |
-
* `Inventory (Opening)`: Your stock **at the beginning of the week**.
|
| 350 |
-
* `Backlog (Opening)`: Unfilled orders **carried over from the end of last week**.
|
| 351 |
-
* `Incoming Order (This Week)`: The specific order quantity arriving from the Wholesaler *during* this week (Step 2). **This is the primary demand signal you need to react to.**
|
| 352 |
-
* `Arriving Next Week`: The quantity scheduled to arrive from the Factory at the start of the **next week**.
|
| 353 |
-
* `Your Total Cumulative Cost`: Sum of all weekly costs up to the **end of last week** (Removed from dashboard).
|
| 354 |
-
* `Cost Last Week`: The specific cost incurred just **last week** (Removed from dashboard).
|
| 355 |
-
|
| 356 |
-
**C) Your Decision (Step 4 - Two Parts):**
|
| 357 |
-
Now, looking at the dashboard (showing the start-of-week state) and considering the incoming order and future arrivals, you decide how much to order:
|
| 358 |
-
* **(Step 4a - Initial Order):** Submit your first estimate. Input box starts blank.
|
| 359 |
-
* **(Step 4b - Final Order):** See the AI's suggestion, then submit your final decision. Input box starts blank (or with AI suggestion if preferred - currently blank). This order will arrive in 3 weeks.
|
| 360 |
-
|
| 361 |
-
Submitting your final order ends the week. The system then calculates your `Weekly Cost` based on your inventory/backlog *after* Step 3 shipping, logs everything, and advances to the next week.
|
| 362 |
-
""")
|
| 363 |
-
# ==============================================================================
|
| 364 |
-
|
| 365 |
-
st.markdown("---")
|
| 366 |
st.header("⚙️ Game Configuration")
|
| 367 |
c1, c2 = st.columns(2)
|
| 368 |
with c1:
|
| 369 |
llm_personality = st.selectbox("AI Agent 'Personality'", ('human_like', 'perfect_rational'), format_func=lambda x: x.replace('_', ' ').title(), help="**Human-like:** Tends to react emotionally, potentially over-ordering. **Perfect Rational:** Uses a mathematical heuristic to make stable, logical decisions.")
|
| 370 |
with c2:
|
| 371 |
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.")
|
| 372 |
-
|
| 373 |
if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
|
| 374 |
init_game_state(llm_personality, info_sharing)
|
| 375 |
st.rerun()
|
|
@@ -379,20 +337,20 @@ else:
|
|
| 379 |
state = st.session_state.game_state
|
| 380 |
week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
|
| 381 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Define here for UI
|
| 382 |
-
|
| 383 |
-
|
| 384 |
st.header(f"Week {week} / {WEEKS}")
|
| 385 |
st.subheader(f"Your Role: **{human_role}** | AI Mode: **{state['llm_personality'].replace('_', ' ')}** | Information: **{state['info_sharing']}**")
|
| 386 |
st.markdown("---")
|
|
|
|
| 387 |
st.subheader("Supply Chain Status (Start of Week State)") # Clarified Timing
|
| 388 |
-
|
| 389 |
if info_sharing == 'full':
|
| 390 |
cols = st.columns(4)
|
| 391 |
for i, name in enumerate(echelon_order): # Use the defined echelon_order
|
| 392 |
with cols[i]:
|
| 393 |
e = echelons[name] # Get the echelon state
|
| 394 |
icon = "👤" if name == human_role else "🤖"
|
| 395 |
-
|
| 396 |
# =============== UI CHANGE: Highlight Player ===============
|
| 397 |
if name == human_role:
|
| 398 |
# Use markdown with HTML/CSS for highlighting
|
|
@@ -400,15 +358,15 @@ else:
|
|
| 400 |
else:
|
| 401 |
st.markdown(f"##### {icon} {name}")
|
| 402 |
# ========================================================
|
| 403 |
-
|
| 404 |
# Display the END OF LAST WEEK state (which is OPENING state for this week)
|
| 405 |
st.metric("Inventory (Opening)", e['inventory'])
|
| 406 |
st.metric("Backlog (Opening)", e['backlog'])
|
| 407 |
-
|
| 408 |
# =============== UI CHANGE: Removed Costs ===============
|
| 409 |
# Costs are no longer displayed on the main dashboard
|
| 410 |
# =======================================================
|
| 411 |
-
|
| 412 |
# Display info about THIS week's events / NEXT week's arrivals
|
| 413 |
# Calculate the INCOMING order for THIS week
|
| 414 |
current_incoming_order = 0
|
|
@@ -418,8 +376,9 @@ else:
|
|
| 418 |
downstream_name = e['downstream_name']
|
| 419 |
if downstream_name:
|
| 420 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
|
|
|
| 421 |
st.write(f"Incoming Order (This Week): **{current_incoming_order}**") # Display calculated order
|
| 422 |
-
|
| 423 |
# Display prediction for NEXT week's arrivals
|
| 424 |
if name == "Factory":
|
| 425 |
prod_completing_next = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
|
|
@@ -431,26 +390,26 @@ else:
|
|
| 431 |
st.info("In Local Information mode, you can only see your own status dashboard.")
|
| 432 |
e = echelons[human_role]
|
| 433 |
st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True) # Highlight self
|
| 434 |
-
|
| 435 |
col1, col2, col3, col4 = st.columns(4)
|
|
|
|
| 436 |
# Display OPENING state
|
| 437 |
col1.metric("Inventory (Opening)", e['inventory'])
|
| 438 |
col2.metric("Backlog (Opening)", e['backlog'])
|
| 439 |
-
|
| 440 |
# Display info about THIS week's events / NEXT week's arrivals
|
| 441 |
# Calculate the INCOMING order for THIS week
|
| 442 |
current_incoming_order = 0
|
| 443 |
downstream_name = e['downstream_name'] # Wholesaler
|
| 444 |
if downstream_name:
|
| 445 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
|
|
|
| 446 |
col3.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}") # Display calculated order
|
| 447 |
col4.write(f"**Shipment Arriving (Next Week):**\n# {list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0}")
|
| 448 |
-
|
| 449 |
# =============== UI CHANGE: Removed Costs ===============
|
| 450 |
# Costs are no longer displayed on the main dashboard
|
| 451 |
# =======================================================
|
| 452 |
|
| 453 |
-
|
| 454 |
st.markdown("---")
|
| 455 |
st.header("Your Decision (Step 4)")
|
| 456 |
|
|
@@ -464,26 +423,27 @@ else:
|
|
| 464 |
if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
|
| 465 |
else:
|
| 466 |
if e_curr['incoming_shipments']: arrived = list(e_curr['incoming_shipments'])[0]
|
| 467 |
-
|
| 468 |
# Calculate the state AFTER arrivals and incoming orders for the prompt
|
| 469 |
inv_after_arrival = e_curr['inventory'] + arrived
|
|
|
|
| 470 |
# Determine incoming order for *this* week again for prompt state
|
| 471 |
inc_order_this_week = 0
|
| 472 |
if name == "Retailer": inc_order_this_week = get_customer_demand(week)
|
| 473 |
else:
|
| 474 |
ds_name = e_curr['downstream_name']
|
| 475 |
if ds_name: inc_order_this_week = state['last_week_orders'].get(ds_name, 0)
|
| 476 |
-
|
| 477 |
backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
|
| 478 |
-
|
| 479 |
all_decision_point_states[name] = {
|
| 480 |
'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
|
| 481 |
'incoming_order': inc_order_this_week, # Use the correctly calculated incoming order
|
| 482 |
'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
|
| 483 |
}
|
|
|
|
| 484 |
human_echelon_state_for_prompt = all_decision_point_states[human_role]
|
| 485 |
|
| 486 |
-
|
| 487 |
if state['decision_step'] == 'initial_order':
|
| 488 |
with st.form(key="initial_order_form"):
|
| 489 |
st.markdown("#### **Step 4a:** Based on the dashboard, submit your **initial** order to the Factory.")
|
|
@@ -498,26 +458,25 @@ else:
|
|
| 498 |
|
| 499 |
elif state['decision_step'] == 'final_order':
|
| 500 |
st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
|
|
|
|
| 501 |
# Use the correctly timed state for the prompt
|
| 502 |
prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, state['llm_personality'], state['info_sharing'], all_decision_point_states)
|
| 503 |
ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
|
| 504 |
-
|
| 505 |
-
# We don't pre-fill the final_order_input anymore
|
| 506 |
-
# if 'final_order_input' not in st.session_state:
|
| 507 |
-
# st.session_state.final_order_input = ai_suggestion
|
| 508 |
-
|
| 509 |
with st.form(key="final_order_form"):
|
| 510 |
st.markdown(f"#### **Step 4b:** The AI suggests ordering **{ai_suggestion}** units.")
|
| 511 |
st.markdown("Considering the AI's advice, submit your **final** order to end the week. (This order will arrive in 3 weeks).")
|
| 512 |
# =============== UI CHANGE: Removed Default Value ===============
|
| 513 |
st.number_input("Your Final Order Quantity:", min_value=0, step=1, key='final_order_input') # No 'value' argument
|
| 514 |
# ===============================================================
|
|
|
|
| 515 |
if st.form_submit_button("Submit Final Order & Advance to Next Week"):
|
| 516 |
# Handle case where user leaves it blank
|
| 517 |
final_order_value = st.session_state.get('final_order_input', 0) # Use .get with default
|
| 518 |
final_order_value = int(final_order_value) if final_order_value is not None else 0
|
| 519 |
-
|
| 520 |
step_game(final_order_value, state['human_initial_order'], ai_suggestion)
|
|
|
|
| 521 |
# Clean up session state for the input key
|
| 522 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
| 523 |
st.rerun()
|
|
@@ -543,7 +502,6 @@ else:
|
|
| 543 |
f'{human_role}.arriving_next_week', f'{human_role}.weekly_cost'
|
| 544 |
]
|
| 545 |
final_cols_to_display = [col for col in ordered_display_cols_keys if col in history_df.columns]
|
| 546 |
-
|
| 547 |
if not final_cols_to_display:
|
| 548 |
st.write("No data columns available to display.")
|
| 549 |
else:
|
|
@@ -556,7 +514,6 @@ else:
|
|
| 556 |
|
| 557 |
try: st.sidebar.image(IMAGE_PATH, caption="Supply Chain Reference")
|
| 558 |
except FileNotFoundError: st.sidebar.warning("Image file not found.")
|
| 559 |
-
|
| 560 |
st.sidebar.header("Game Info")
|
| 561 |
st.sidebar.markdown(f"**Game ID**: `{state['participant_id']}`\n\n**Current Week**: {week}")
|
| 562 |
if st.sidebar.button("🔄 Reset Game"):
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# @title Beer Game Final Version (v4.21 - Removed Introduction)
|
|
|
|
| 3 |
# -----------------------------------------------------------------------------
|
| 4 |
# 1. Import Libraries
|
| 5 |
# -----------------------------------------------------------------------------
|
|
|
|
| 21 |
# -----------------------------------------------------------------------------
|
| 22 |
st.set_page_config(page_title="Beer Game: Human-AI Collaboration", layout="wide")
|
| 23 |
|
|
|
|
| 24 |
# -----------------------------------------------------------------------------
|
| 25 |
# 2. Game Parameters & API Configuration
|
| 26 |
# -----------------------------------------------------------------------------
|
|
|
|
| 53 |
else:
|
| 54 |
st.session_state.initialization_error = None
|
| 55 |
|
|
|
|
| 56 |
# -----------------------------------------------------------------------------
|
| 57 |
# 3. Core Game Logic Functions
|
| 58 |
# -----------------------------------------------------------------------------
|
|
|
|
| 59 |
def get_customer_demand(week: int) -> int:
|
| 60 |
return 4 if week <= 4 else 8
|
| 61 |
|
|
|
|
| 63 |
roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 64 |
human_role = "Distributor" # Role is fixed
|
| 65 |
participant_id = str(uuid.uuid4())[:8]
|
|
|
|
| 66 |
st.session_state.game_state = {
|
| 67 |
'game_running': True, 'participant_id': participant_id, 'week': 1,
|
| 68 |
'human_role': human_role, 'llm_personality': llm_personality,
|
|
|
|
| 72 |
'human_initial_order': None,
|
| 73 |
'last_week_orders': {name: 0 for name in roles}
|
| 74 |
}
|
|
|
|
| 75 |
for i, name in enumerate(roles):
|
| 76 |
upstream = roles[i + 1] if i + 1 < len(roles) else None
|
| 77 |
downstream = roles[i - 1] if i - 1 >= 0 else None
|
|
|
|
| 78 |
if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY
|
| 79 |
elif name == "Factory": shipping_weeks = 0
|
| 80 |
else: shipping_weeks = SHIPPING_DELAY
|
|
|
|
| 81 |
st.session_state.game_state['echelons'][name] = {
|
| 82 |
'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
|
| 83 |
'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
|
|
|
|
| 119 |
else:
|
| 120 |
task_word = "order quantity"
|
| 121 |
base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
|
| 122 |
+
|
| 123 |
if llm_personality == 'perfect_rational' and info_sharing == 'full':
|
| 124 |
stable_demand = 8
|
| 125 |
if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME
|
|
|
|
| 136 |
inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
|
| 137 |
optimal_order = max(0, int(target_inventory_level - inventory_position))
|
| 138 |
return f"**You are a perfectly rational supply chain AI with full system visibility.**\nYour only goal is to maintain stability and minimize costs based on mathematical optimization.\n**System Analysis:**\n* **Known Stable End-Customer Demand:** {stable_demand} units/week.\n* **Your Current Total Inventory Position:** {inventory_position} units. {inv_pos_components}\n* **Optimal Target Inventory Level:** {target_inventory_level} units (Target for {total_lead_time} weeks lead time).\n* **Mathematically Optimal {task_word.title()}:** The optimal decision is **{optimal_order} units**.\n**Your Task:** Confirm this optimal {task_word}. Respond with a single integer."
|
| 139 |
+
|
| 140 |
elif llm_personality == 'perfect_rational' and info_sharing == 'local':
|
| 141 |
safety_stock = 4; anchor_demand = e_state['incoming_order']
|
| 142 |
inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
|
|
|
|
| 150 |
calculated_order = anchor_demand + inventory_correction - supply_line
|
| 151 |
rational_local_order = max(0, int(calculated_order))
|
| 152 |
return f"**You are a perfectly rational supply chain AI with ONLY LOCAL information.**\nYou must use a logical heuristic to make a stable decision. A proven method is \"Anchoring and Adjustment\".\n\n{base_info}\n\n**Rational Calculation (Anchoring & Adjustment):**\n1. **Anchor on Demand:** Your best guess for future demand is your last incoming order: **{anchor_demand} units**.\n2. **Adjust for Inventory:** You want to hold a safety stock of {safety_stock} units. Your current stock (before shipping) is {e_state['inventory'] - e_state['backlog']}. You need to order an extra **{inventory_correction} units** to correct this.\n3. **Account for {supply_line_desc}:** You already have **{supply_line} units** being processed. These should be subtracted from your new decision.\n\n**Final Calculation:**\n* Decision = (Anchor Demand) + (Inventory Adjustment) - ({supply_line_desc})\n* Decision = {anchor_demand} + {inventory_correction} - {supply_line} = **{rational_local_order} units**.\n**Your Task:** Confirm this locally rational {task_word}. Respond with a single integer."
|
| 153 |
+
|
| 154 |
elif llm_personality == 'human_like' and info_sharing == 'full':
|
| 155 |
full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
|
| 156 |
for name, other_e_state in all_echelons_state_decision_point.items():
|
|
|
|
| 165 |
You are still human and might get anxious about your own stock levels.
|
| 166 |
What {task_word} should you decide on this week? Respond with a single integer.
|
| 167 |
"""
|
| 168 |
+
|
| 169 |
elif llm_personality == 'human_like' and info_sharing == 'local':
|
| 170 |
return f"""
|
| 171 |
**You are a reactive supply chain manager for the {e_state['name']}.** You have a limited view and tend to over-correct based on fear.
|
|
|
|
| 183 |
llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
|
| 184 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 185 |
llm_raw_responses = {}
|
| 186 |
+
|
| 187 |
opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
|
| 188 |
opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
|
| 189 |
+
|
| 190 |
arrived_this_week = {name: 0 for name in echelon_order}
|
| 191 |
inventory_after_arrival = {}
|
| 192 |
+
|
| 193 |
factory_state = echelons["Factory"]
|
| 194 |
produced_units = 0
|
| 195 |
if state['factory_production_pipeline']:
|
| 196 |
produced_units = state['factory_production_pipeline'].popleft()
|
| 197 |
arrived_this_week["Factory"] = produced_units
|
| 198 |
inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
|
| 199 |
+
|
| 200 |
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 201 |
arrived_shipment = 0
|
| 202 |
if echelons[name]['incoming_shipments']:
|
| 203 |
arrived_shipment = echelons[name]['incoming_shipments'].popleft()
|
| 204 |
arrived_this_week[name] = arrived_shipment
|
| 205 |
inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
|
| 206 |
+
|
| 207 |
total_backlog_before_shipping = {}
|
| 208 |
for name in echelon_order:
|
| 209 |
incoming_order_for_this_week = 0
|
|
|
|
| 213 |
if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
|
| 214 |
echelons[name]['incoming_order'] = incoming_order_for_this_week
|
| 215 |
total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
|
| 216 |
+
|
| 217 |
decision_point_states = {}
|
| 218 |
for name in echelon_order:
|
| 219 |
decision_point_states[name] = {
|
|
|
|
| 221 |
'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
|
| 222 |
'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
|
| 223 |
}
|
| 224 |
+
|
| 225 |
current_week_orders = {}
|
| 226 |
for name in echelon_order:
|
| 227 |
e = echelons[name]; prompt_state = decision_point_states[name]
|
|
|
|
| 230 |
prompt = get_llm_prompt(prompt_state, week, llm_personality, info_sharing, decision_point_states)
|
| 231 |
order_amount, raw_resp = get_llm_order_decision(prompt, name)
|
| 232 |
llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
|
| 233 |
+
|
| 234 |
state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
|
| 235 |
+
|
| 236 |
units_shipped = {name: 0 for name in echelon_order}
|
| 237 |
for name in echelon_order:
|
| 238 |
e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
|
| 239 |
e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
|
| 240 |
e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
|
| 241 |
+
|
| 242 |
if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
|
| 243 |
if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
|
| 244 |
if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
|
| 245 |
+
|
| 246 |
log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
|
| 247 |
del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
|
| 248 |
for name in echelon_order:
|
|
|
|
| 255 |
else: log_entry[f'{name}.production_completing_next_week'] = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
|
| 256 |
log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
|
| 257 |
state['logs'].append(log_entry)
|
| 258 |
+
|
| 259 |
state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
|
| 260 |
if state['week'] > WEEKS: state['game_running'] = False
|
| 261 |
|
|
|
|
| 318 |
else:
|
| 319 |
# --- Game Setup & Instructions ---
|
| 320 |
if 'game_state' not in st.session_state or not st.session_state.game_state.get('game_running', False):
|
| 321 |
+
|
| 322 |
+
# --- Introduction Section Removed as Requested ---
|
| 323 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
st.header("⚙️ Game Configuration")
|
| 325 |
c1, c2 = st.columns(2)
|
| 326 |
with c1:
|
| 327 |
llm_personality = st.selectbox("AI Agent 'Personality'", ('human_like', 'perfect_rational'), format_func=lambda x: x.replace('_', ' ').title(), help="**Human-like:** Tends to react emotionally, potentially over-ordering. **Perfect Rational:** Uses a mathematical heuristic to make stable, logical decisions.")
|
| 328 |
with c2:
|
| 329 |
info_sharing = st.selectbox("Information Sharing Level", ('local', 'full'), format_func=lambda x: x.title(), help="**Local:** You and the AI agents can only see your own inventory and incoming orders. **Full:** Everyone can see the entire supply chain's status and the true end-customer demand.")
|
| 330 |
+
|
| 331 |
if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
|
| 332 |
init_game_state(llm_personality, info_sharing)
|
| 333 |
st.rerun()
|
|
|
|
| 337 |
state = st.session_state.game_state
|
| 338 |
week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
|
| 339 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"] # Define here for UI
|
| 340 |
+
|
|
|
|
| 341 |
st.header(f"Week {week} / {WEEKS}")
|
| 342 |
st.subheader(f"Your Role: **{human_role}** | AI Mode: **{state['llm_personality'].replace('_', ' ')}** | Information: **{state['info_sharing']}**")
|
| 343 |
st.markdown("---")
|
| 344 |
+
|
| 345 |
st.subheader("Supply Chain Status (Start of Week State)") # Clarified Timing
|
| 346 |
+
|
| 347 |
if info_sharing == 'full':
|
| 348 |
cols = st.columns(4)
|
| 349 |
for i, name in enumerate(echelon_order): # Use the defined echelon_order
|
| 350 |
with cols[i]:
|
| 351 |
e = echelons[name] # Get the echelon state
|
| 352 |
icon = "👤" if name == human_role else "🤖"
|
| 353 |
+
|
| 354 |
# =============== UI CHANGE: Highlight Player ===============
|
| 355 |
if name == human_role:
|
| 356 |
# Use markdown with HTML/CSS for highlighting
|
|
|
|
| 358 |
else:
|
| 359 |
st.markdown(f"##### {icon} {name}")
|
| 360 |
# ========================================================
|
| 361 |
+
|
| 362 |
# Display the END OF LAST WEEK state (which is OPENING state for this week)
|
| 363 |
st.metric("Inventory (Opening)", e['inventory'])
|
| 364 |
st.metric("Backlog (Opening)", e['backlog'])
|
| 365 |
+
|
| 366 |
# =============== UI CHANGE: Removed Costs ===============
|
| 367 |
# Costs are no longer displayed on the main dashboard
|
| 368 |
# =======================================================
|
| 369 |
+
|
| 370 |
# Display info about THIS week's events / NEXT week's arrivals
|
| 371 |
# Calculate the INCOMING order for THIS week
|
| 372 |
current_incoming_order = 0
|
|
|
|
| 376 |
downstream_name = e['downstream_name']
|
| 377 |
if downstream_name:
|
| 378 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 379 |
+
|
| 380 |
st.write(f"Incoming Order (This Week): **{current_incoming_order}**") # Display calculated order
|
| 381 |
+
|
| 382 |
# Display prediction for NEXT week's arrivals
|
| 383 |
if name == "Factory":
|
| 384 |
prod_completing_next = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
|
|
|
|
| 390 |
st.info("In Local Information mode, you can only see your own status dashboard.")
|
| 391 |
e = echelons[human_role]
|
| 392 |
st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True) # Highlight self
|
|
|
|
| 393 |
col1, col2, col3, col4 = st.columns(4)
|
| 394 |
+
|
| 395 |
# Display OPENING state
|
| 396 |
col1.metric("Inventory (Opening)", e['inventory'])
|
| 397 |
col2.metric("Backlog (Opening)", e['backlog'])
|
| 398 |
+
|
| 399 |
# Display info about THIS week's events / NEXT week's arrivals
|
| 400 |
# Calculate the INCOMING order for THIS week
|
| 401 |
current_incoming_order = 0
|
| 402 |
downstream_name = e['downstream_name'] # Wholesaler
|
| 403 |
if downstream_name:
|
| 404 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 405 |
+
|
| 406 |
col3.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}") # Display calculated order
|
| 407 |
col4.write(f"**Shipment Arriving (Next Week):**\n# {list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0}")
|
| 408 |
+
|
| 409 |
# =============== UI CHANGE: Removed Costs ===============
|
| 410 |
# Costs are no longer displayed on the main dashboard
|
| 411 |
# =======================================================
|
| 412 |
|
|
|
|
| 413 |
st.markdown("---")
|
| 414 |
st.header("Your Decision (Step 4)")
|
| 415 |
|
|
|
|
| 423 |
if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
|
| 424 |
else:
|
| 425 |
if e_curr['incoming_shipments']: arrived = list(e_curr['incoming_shipments'])[0]
|
| 426 |
+
|
| 427 |
# Calculate the state AFTER arrivals and incoming orders for the prompt
|
| 428 |
inv_after_arrival = e_curr['inventory'] + arrived
|
| 429 |
+
|
| 430 |
# Determine incoming order for *this* week again for prompt state
|
| 431 |
inc_order_this_week = 0
|
| 432 |
if name == "Retailer": inc_order_this_week = get_customer_demand(week)
|
| 433 |
else:
|
| 434 |
ds_name = e_curr['downstream_name']
|
| 435 |
if ds_name: inc_order_this_week = state['last_week_orders'].get(ds_name, 0)
|
| 436 |
+
|
| 437 |
backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
|
| 438 |
+
|
| 439 |
all_decision_point_states[name] = {
|
| 440 |
'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
|
| 441 |
'incoming_order': inc_order_this_week, # Use the correctly calculated incoming order
|
| 442 |
'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
|
| 443 |
}
|
| 444 |
+
|
| 445 |
human_echelon_state_for_prompt = all_decision_point_states[human_role]
|
| 446 |
|
|
|
|
| 447 |
if state['decision_step'] == 'initial_order':
|
| 448 |
with st.form(key="initial_order_form"):
|
| 449 |
st.markdown("#### **Step 4a:** Based on the dashboard, submit your **initial** order to the Factory.")
|
|
|
|
| 458 |
|
| 459 |
elif state['decision_step'] == 'final_order':
|
| 460 |
st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
|
| 461 |
+
|
| 462 |
# Use the correctly timed state for the prompt
|
| 463 |
prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, state['llm_personality'], state['info_sharing'], all_decision_point_states)
|
| 464 |
ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
|
| 465 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
with st.form(key="final_order_form"):
|
| 467 |
st.markdown(f"#### **Step 4b:** The AI suggests ordering **{ai_suggestion}** units.")
|
| 468 |
st.markdown("Considering the AI's advice, submit your **final** order to end the week. (This order will arrive in 3 weeks).")
|
| 469 |
# =============== UI CHANGE: Removed Default Value ===============
|
| 470 |
st.number_input("Your Final Order Quantity:", min_value=0, step=1, key='final_order_input') # No 'value' argument
|
| 471 |
# ===============================================================
|
| 472 |
+
|
| 473 |
if st.form_submit_button("Submit Final Order & Advance to Next Week"):
|
| 474 |
# Handle case where user leaves it blank
|
| 475 |
final_order_value = st.session_state.get('final_order_input', 0) # Use .get with default
|
| 476 |
final_order_value = int(final_order_value) if final_order_value is not None else 0
|
| 477 |
+
|
| 478 |
step_game(final_order_value, state['human_initial_order'], ai_suggestion)
|
| 479 |
+
|
| 480 |
# Clean up session state for the input key
|
| 481 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
| 482 |
st.rerun()
|
|
|
|
| 502 |
f'{human_role}.arriving_next_week', f'{human_role}.weekly_cost'
|
| 503 |
]
|
| 504 |
final_cols_to_display = [col for col in ordered_display_cols_keys if col in history_df.columns]
|
|
|
|
| 505 |
if not final_cols_to_display:
|
| 506 |
st.write("No data columns available to display.")
|
| 507 |
else:
|
|
|
|
| 514 |
|
| 515 |
try: st.sidebar.image(IMAGE_PATH, caption="Supply Chain Reference")
|
| 516 |
except FileNotFoundError: st.sidebar.warning("Image file not found.")
|
|
|
|
| 517 |
st.sidebar.header("Game Info")
|
| 518 |
st.sidebar.markdown(f"**Game ID**: `{state['participant_id']}`\n\n**Current Week**: {week}")
|
| 519 |
if st.sidebar.button("🔄 Reset Game"):
|