Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# app.py
|
| 2 |
-
# @title Beer Game Final Version (v4.
|
| 3 |
# -----------------------------------------------------------------------------
|
| 4 |
# 1. Import Libraries
|
| 5 |
# -----------------------------------------------------------------------------
|
|
@@ -59,19 +59,44 @@ else:
|
|
| 59 |
def get_customer_demand(week: int) -> int:
|
| 60 |
return 4 if week <= 4 else 8
|
| 61 |
|
| 62 |
-
def init_game_state(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,
|
|
|
|
| 69 |
'info_sharing': info_sharing, 'logs': [], 'echelons': {},
|
| 70 |
'factory_production_pipeline': deque([0] * FACTORY_LEAD_TIME, maxlen=FACTORY_LEAD_TIME),
|
| 71 |
'decision_step': 'initial_order',
|
| 72 |
'human_initial_order': None,
|
| 73 |
'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
|
|
@@ -79,18 +104,21 @@ def init_game_state(llm_personality: str, info_sharing: str):
|
|
| 79 |
elif name == "Factory": shipping_weeks = 0
|
| 80 |
else: shipping_weeks = SHIPPING_DELAY
|
| 81 |
st.session_state.game_state['echelons'][name] = {
|
| 82 |
-
'name': name,
|
|
|
|
|
|
|
| 83 |
'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
|
| 84 |
'incoming_order': 0, 'order_placed': 0, 'shipment_sent': 0,
|
| 85 |
'weekly_cost': 0, 'total_cost': 0, 'upstream_name': upstream, 'downstream_name': downstream,
|
| 86 |
}
|
| 87 |
-
st.info(f"New game started! AI Mode: **{
|
| 88 |
|
| 89 |
def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
| 90 |
# This function remains correct.
|
| 91 |
if not client: return 8, "NO_API_KEY_DEFAULT"
|
| 92 |
with st.spinner(f"Getting AI decision for {echelon_name}..."):
|
| 93 |
try:
|
|
|
|
| 94 |
temp = 0.1 if 'rational' in prompt else 0.7
|
| 95 |
response = client.chat.completions.create(
|
| 96 |
model=OPENAI_MODEL,
|
|
@@ -110,7 +138,11 @@ def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
|
| 110 |
return 4, f"API_ERROR: {e}"
|
| 111 |
|
| 112 |
def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
e_state = echelon_state_decision_point
|
| 115 |
base_info = f"Your Current Status at the **{e_state['name']}** for **Week {week}** (Before Shipping):\n- On-hand inventory: {e_state['inventory']} units.\n- Backlog (total unfilled orders): {e_state['backlog']} units.\n- Incoming order this week (just received): {e_state['incoming_order']} units.\n"
|
| 116 |
if e_state['name'] == 'Factory':
|
|
@@ -136,7 +168,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 136 |
inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
|
| 137 |
optimal_order = max(0, int(target_inventory_level - inventory_position))
|
| 138 |
return f"**You are a perfectly rational supply chain AI with full system visibility.**\nYour only goal is to maintain stability and minimize costs based on mathematical optimization.\n**System Analysis:**\n* **Known Stable End-Customer Demand:** {stable_demand} units/week.\n* **Your Current Total Inventory Position:** {inventory_position} units. {inv_pos_components}\n* **Optimal Target Inventory Level:** {target_inventory_level} units (Target for {total_lead_time} weeks lead time).\n* **Mathematically Optimal {task_word.title()}:** The optimal decision is **{optimal_order} units**.\n**Your Task:** Confirm this optimal {task_word}. Respond with a single integer."
|
| 139 |
-
|
| 140 |
elif llm_personality == 'perfect_rational' and info_sharing == 'local':
|
| 141 |
safety_stock = 4; anchor_demand = e_state['incoming_order']
|
| 142 |
inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
|
|
@@ -150,7 +182,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 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,7 +197,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 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.
|
|
@@ -177,33 +209,33 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 177 |
"""
|
| 178 |
|
| 179 |
def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
|
| 180 |
-
# This function's logic remains correct
|
| 181 |
state = st.session_state.game_state
|
| 182 |
week, echelons, human_role = state['week'], state['echelons'], state['human_role']
|
| 183 |
-
|
|
|
|
| 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,7 +245,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 213 |
if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
|
| 214 |
echelons[name]['incoming_order'] = incoming_order_for_this_week
|
| 215 |
total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
|
| 216 |
-
|
| 217 |
decision_point_states = {}
|
| 218 |
for name in echelon_order:
|
| 219 |
decision_point_states[name] = {
|
|
@@ -221,42 +253,58 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 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]
|
| 228 |
-
|
|
|
|
|
|
|
| 229 |
else:
|
| 230 |
-
|
|
|
|
|
|
|
| 231 |
order_amount, raw_resp = get_llm_order_decision(prompt, name)
|
|
|
|
| 232 |
llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
|
| 233 |
-
|
| 234 |
state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
|
| 235 |
-
|
| 236 |
units_shipped = {name: 0 for name in echelon_order}
|
|
|
|
| 237 |
for name in echelon_order:
|
| 238 |
e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
|
| 239 |
e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
|
| 240 |
e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
|
| 241 |
-
|
| 242 |
if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
|
| 243 |
if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
|
| 244 |
if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
|
| 245 |
-
|
|
|
|
| 246 |
log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
|
|
|
|
| 247 |
del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
|
|
|
|
|
|
|
| 248 |
for name in echelon_order:
|
| 249 |
e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
|
| 250 |
-
for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']:
|
|
|
|
|
|
|
|
|
|
| 251 |
log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
|
| 252 |
log_entry[f'{name}.opening_inventory'] = opening_inventories[name]; log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
|
| 253 |
log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name]
|
| 254 |
-
if name != 'Factory':
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
| 256 |
log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
|
|
|
|
| 257 |
state['logs'].append(log_entry)
|
| 258 |
-
|
| 259 |
state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
|
|
|
|
| 260 |
if state['week'] > WEEKS: state['game_running'] = False
|
| 261 |
|
| 262 |
def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
|
@@ -264,6 +312,7 @@ def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
|
| 264 |
fig, axes = plt.subplots(4, 1, figsize=(12, 22))
|
| 265 |
fig.suptitle(title, fontsize=16)
|
| 266 |
echelons = ['Retailer', 'Wholesaler', 'Distributor', 'Factory']
|
|
|
|
| 267 |
plot_data = []
|
| 268 |
for _, row in df.iterrows():
|
| 269 |
for e in echelons:
|
|
@@ -271,13 +320,17 @@ def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
|
| 271 |
'inventory': row.get(f'{e}.inventory', 0), 'order_placed': row.get(f'{e}.order_placed', 0),
|
| 272 |
'total_cost': row.get(f'{e}.total_cost', 0)})
|
| 273 |
plot_df = pd.DataFrame(plot_data)
|
|
|
|
| 274 |
inventory_pivot = plot_df.pivot(index='week', columns='echelon', values='inventory').reindex(columns=echelons)
|
| 275 |
inventory_pivot.plot(ax=axes[0], kind='line', marker='o', markersize=4); axes[0].set_title('Inventory Levels (End of Week)'); axes[0].grid(True, linestyle='--'); axes[0].set_ylabel('Stock (Units)')
|
|
|
|
| 276 |
order_pivot = plot_df.pivot(index='week', columns='echelon', values='order_placed').reindex(columns=echelons)
|
| 277 |
order_pivot.plot(ax=axes[1], style='--'); axes[1].plot(range(1, WEEKS + 1), [get_customer_demand(w) for w in range(1, WEEKS + 1)], label='Customer Demand', color='black', lw=2.5); axes[1].set_title('Order Quantities / Production Decisions'); axes[1].grid(True, linestyle='--'); axes[1].legend(); axes[1].set_ylabel('Ordered/Produced (Units)')
|
|
|
|
| 278 |
total_costs = plot_df.loc[plot_df.groupby('echelon')['week'].idxmax()]
|
| 279 |
total_costs = total_costs.set_index('echelon')['total_cost'].reindex(echelons, fill_value=0)
|
| 280 |
total_costs.plot(kind='bar', ax=axes[2], rot=0); axes[2].set_title('Total Cumulative Cost'); axes[2].set_ylabel('Cost ($)')
|
|
|
|
| 281 |
human_cols = [f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed']
|
| 282 |
human_df_cols = ['week'] + [col for col in human_cols if col in df.columns]
|
| 283 |
try:
|
|
@@ -287,6 +340,7 @@ def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
|
| 287 |
else: raise ValueError("No human decision data columns found.")
|
| 288 |
except (KeyError, ValueError) as plot_err:
|
| 289 |
axes[3].set_title(f'Analysis of Your ({human_role}) Decisions - Error Plotting Data'); axes[3].text(0.5, 0.5, f"Error: {plot_err}", ha='center', va='center'); axes[3].grid(True, linestyle='--'); axes[3].set_xlabel('Week')
|
|
|
|
| 290 |
plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
|
| 291 |
|
| 292 |
def save_logs_and_upload(state: dict):
|
|
@@ -319,56 +373,64 @@ 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
with c2:
|
| 329 |
-
info_sharing = st.selectbox(
|
| 330 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
|
| 332 |
-
|
|
|
|
| 333 |
st.rerun()
|
| 334 |
|
| 335 |
# --- Main Game Interface ---
|
| 336 |
elif 'game_state' in st.session_state and st.session_state.game_state.get('game_running'):
|
| 337 |
state = st.session_state.game_state
|
| 338 |
week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
|
| 339 |
-
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 340 |
-
|
| 341 |
st.header(f"Week {week} / {WEEKS}")
|
| 342 |
-
|
|
|
|
| 343 |
st.markdown("---")
|
| 344 |
-
|
| 345 |
-
st.subheader("Supply Chain Status (Start of Week State)")
|
| 346 |
-
|
| 347 |
if info_sharing == 'full':
|
| 348 |
cols = st.columns(4)
|
| 349 |
-
for i, name in enumerate(echelon_order):
|
| 350 |
with cols[i]:
|
| 351 |
-
e = echelons[name]
|
| 352 |
icon = "👤" if name == human_role else "🤖"
|
| 353 |
-
|
| 354 |
-
# =============== UI CHANGE: Highlight Player ===============
|
| 355 |
if name == human_role:
|
| 356 |
-
# Use markdown with HTML/CSS for highlighting
|
| 357 |
st.markdown(f"##### **<span style='border: 1px solid #FF4B4B; padding: 2px 5px; border-radius: 3px;'>{icon} {name} (You)</span>**", unsafe_allow_html=True)
|
| 358 |
else:
|
| 359 |
st.markdown(f"##### {icon} {name}")
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
|
|
|
|
|
|
| 363 |
st.metric("Inventory (Opening)", e['inventory'])
|
| 364 |
st.metric("Backlog (Opening)", e['backlog'])
|
| 365 |
-
|
| 366 |
-
# =============== UI CHANGE: Removed Costs ===============
|
| 367 |
-
# Costs are no longer displayed on the main dashboard
|
| 368 |
-
# =======================================================
|
| 369 |
-
|
| 370 |
-
# Display info about THIS week's events / NEXT week's arrivals
|
| 371 |
-
# Calculate the INCOMING order for THIS week
|
| 372 |
current_incoming_order = 0
|
| 373 |
if name == "Retailer":
|
| 374 |
current_incoming_order = get_customer_demand(week)
|
|
@@ -376,111 +438,121 @@ else:
|
|
| 376 |
downstream_name = e['downstream_name']
|
| 377 |
if downstream_name:
|
| 378 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 379 |
-
|
| 380 |
-
st.write(f"Incoming Order (This Week): **{current_incoming_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
|
| 385 |
st.write(f"Completing Next Week: **{prod_completing_next}**")
|
| 386 |
else:
|
| 387 |
arriving_next = list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0
|
| 388 |
st.write(f"Arriving Next Week: **{arriving_next}**")
|
|
|
|
| 389 |
else: # Local Info Mode
|
| 390 |
st.info("In Local Information mode, you can only see your own status dashboard.")
|
| 391 |
e = echelons[human_role]
|
| 392 |
-
st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True)
|
| 393 |
col1, col2, col3, col4 = st.columns(4)
|
| 394 |
|
| 395 |
-
# Display OPENING state
|
| 396 |
col1.metric("Inventory (Opening)", e['inventory'])
|
| 397 |
col2.metric("Backlog (Opening)", e['backlog'])
|
| 398 |
-
|
| 399 |
-
# Display info about THIS week's events / NEXT week's arrivals
|
| 400 |
-
# Calculate the INCOMING order for THIS week
|
| 401 |
current_incoming_order = 0
|
| 402 |
downstream_name = e['downstream_name'] # Wholesaler
|
| 403 |
-
if downstream_name:
|
| 404 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 405 |
-
|
| 406 |
-
col3.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
|
| 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 |
-
|
| 416 |
# Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
|
| 417 |
all_decision_point_states = {}
|
| 418 |
for name in echelon_order:
|
| 419 |
-
e_curr = echelons[name]
|
| 420 |
arrived = 0
|
| 421 |
-
|
| 422 |
-
if name == "Factory":
|
| 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,
|
| 442 |
'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
|
| 443 |
}
|
| 444 |
-
|
| 445 |
human_echelon_state_for_prompt = all_decision_point_states[human_role]
|
| 446 |
-
|
| 447 |
if state['decision_step'] == 'initial_order':
|
| 448 |
with st.form(key="initial_order_form"):
|
| 449 |
st.markdown("#### **Step 4a:** Based on the dashboard, submit your **initial** order to the Factory.")
|
| 450 |
-
|
| 451 |
-
initial_order = st.number_input("Your Initial Order Quantity:", min_value=0, step=1) # No 'value' argument
|
| 452 |
-
# ===============================================================
|
| 453 |
if st.form_submit_button("Submit Initial Order & See AI Suggestion", type="primary"):
|
| 454 |
-
# Handle case where user leaves it blank (input returns None)
|
| 455 |
state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
|
| 456 |
state['decision_step'] = 'final_order'
|
| 457 |
st.rerun()
|
| 458 |
-
|
| 459 |
elif state['decision_step'] == 'final_order':
|
| 460 |
st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
|
|
|
|
|
|
| 465 |
|
|
|
|
|
|
|
|
|
|
| 466 |
with st.form(key="final_order_form"):
|
| 467 |
-
st.markdown(f"#### **Step 4b:**
|
| 468 |
st.markdown("Considering the AI's advice, submit your **final** order to end the week. (This order will arrive in 3 weeks).")
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
# ===============================================================
|
| 472 |
-
|
| 473 |
if st.form_submit_button("Submit Final Order & Advance to Next Week"):
|
| 474 |
-
|
| 475 |
-
final_order_value = st.session_state.get('final_order_input', 0) # Use .get with default
|
| 476 |
final_order_value = int(final_order_value) if final_order_value is not None else 0
|
| 477 |
-
|
| 478 |
step_game(final_order_value, state['human_initial_order'], ai_suggestion)
|
| 479 |
-
|
| 480 |
-
# Clean up session state for the input key
|
| 481 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
| 482 |
st.rerun()
|
| 483 |
-
|
| 484 |
st.markdown("---")
|
| 485 |
with st.expander("📖 Your Weekly Decision Log", expanded=False):
|
| 486 |
if not state.get('logs'):
|
|
@@ -499,10 +571,10 @@ else:
|
|
| 499 |
'week', f'{human_role}.opening_inventory', f'{human_role}.opening_backlog',
|
| 500 |
f'{human_role}.arrived_this_week', f'{human_role}.incoming_order',
|
| 501 |
f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed',
|
| 502 |
-
f'{human_role}.arriving_next_week', f'{human_role}.weekly_cost'
|
| 503 |
]
|
| 504 |
final_cols_to_display = [col for col in ordered_display_cols_keys if col in history_df.columns]
|
| 505 |
-
if not final_cols_to_display:
|
| 506 |
st.write("No data columns available to display.")
|
| 507 |
else:
|
| 508 |
display_df = history_df[final_cols_to_display].rename(columns=human_cols)
|
|
@@ -511,7 +583,7 @@ else:
|
|
| 511 |
st.dataframe(display_df.sort_values(by="Week", ascending=False), hide_index=True, use_container_width=True)
|
| 512 |
except Exception as e:
|
| 513 |
st.error(f"Error displaying weekly log: {e}")
|
| 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")
|
|
@@ -527,16 +599,17 @@ else:
|
|
| 527 |
state = st.session_state.game_state
|
| 528 |
try:
|
| 529 |
logs_df = pd.json_normalize(state['logs'])
|
|
|
|
| 530 |
fig = plot_results(
|
| 531 |
logs_df,
|
| 532 |
-
f"Beer Game (Human: {state['human_role']})\n(AI: {state['
|
| 533 |
state['human_role']
|
| 534 |
)
|
| 535 |
st.pyplot(fig)
|
| 536 |
save_logs_and_upload(state)
|
| 537 |
except Exception as e:
|
| 538 |
st.error(f"Error generating final report: {e}")
|
| 539 |
-
|
| 540 |
if st.button("✨ Start a New Game"):
|
| 541 |
del st.session_state.game_state
|
| 542 |
st.rerun()
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# @title Beer Game Final Version (v4.30 - Heterogeneous "Locus of Chaos" Design)
|
| 3 |
# -----------------------------------------------------------------------------
|
| 4 |
# 1. Import Libraries
|
| 5 |
# -----------------------------------------------------------------------------
|
|
|
|
| 59 |
def get_customer_demand(week: int) -> int:
|
| 60 |
return 4 if week <= 4 else 8
|
| 61 |
|
| 62 |
+
def init_game_state(locus_of_chaos: str, info_sharing: str):
|
| 63 |
+
"""
|
| 64 |
+
Initializes the game state based on the Locus of Chaos and Information Sharing conditions.
|
| 65 |
+
The human role is fixed as 'Distributor'.
|
| 66 |
+
"""
|
| 67 |
roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 68 |
+
human_role = "Distributor" # Role is fixed as per our discussion
|
| 69 |
participant_id = str(uuid.uuid4())[:8]
|
| 70 |
+
|
| 71 |
+
# --- NEW: Define heterogeneous personalities based on Locus of Chaos ---
|
| 72 |
+
if locus_of_chaos == 'Downstream Chaos':
|
| 73 |
+
personalities = {
|
| 74 |
+
"Retailer": "human_like",
|
| 75 |
+
"Wholesaler": "human_like",
|
| 76 |
+
"Distributor": "HUMAN_PLAYER", # Human role
|
| 77 |
+
"Factory": "perfect_rational"
|
| 78 |
+
}
|
| 79 |
+
else: # 'Upstream Chaos'
|
| 80 |
+
personalities = {
|
| 81 |
+
"Retailer": "perfect_rational",
|
| 82 |
+
"Wholesaler": "perfect_rational",
|
| 83 |
+
"Distributor": "HUMAN_PLAYER", # Human role
|
| 84 |
+
"Factory": "human_like"
|
| 85 |
+
}
|
| 86 |
+
# ---------------------------------------------------------------------
|
| 87 |
+
|
| 88 |
st.session_state.game_state = {
|
| 89 |
'game_running': True, 'participant_id': participant_id, 'week': 1,
|
| 90 |
+
'human_role': human_role,
|
| 91 |
+
'locus_of_chaos': locus_of_chaos, # <-- NEW: Store chaos condition
|
| 92 |
'info_sharing': info_sharing, 'logs': [], 'echelons': {},
|
| 93 |
'factory_production_pipeline': deque([0] * FACTORY_LEAD_TIME, maxlen=FACTORY_LEAD_TIME),
|
| 94 |
'decision_step': 'initial_order',
|
| 95 |
'human_initial_order': None,
|
| 96 |
'last_week_orders': {name: 0 for name in roles}
|
| 97 |
+
# 'llm_personality' is now REMOVED from the global state
|
| 98 |
}
|
| 99 |
+
|
| 100 |
for i, name in enumerate(roles):
|
| 101 |
upstream = roles[i + 1] if i + 1 < len(roles) else None
|
| 102 |
downstream = roles[i - 1] if i - 1 >= 0 else None
|
|
|
|
| 104 |
elif name == "Factory": shipping_weeks = 0
|
| 105 |
else: shipping_weeks = SHIPPING_DELAY
|
| 106 |
st.session_state.game_state['echelons'][name] = {
|
| 107 |
+
'name': name,
|
| 108 |
+
'personality': personalities[name], # <-- NEW: Store agent-specific personality
|
| 109 |
+
'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
|
| 110 |
'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
|
| 111 |
'incoming_order': 0, 'order_placed': 0, 'shipment_sent': 0,
|
| 112 |
'weekly_cost': 0, 'total_cost': 0, 'upstream_name': upstream, 'downstream_name': downstream,
|
| 113 |
}
|
| 114 |
+
st.info(f"New game started! AI Mode: **{locus_of_chaos} / {info_sharing}**. You are playing as the: **{human_role}**.")
|
| 115 |
|
| 116 |
def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
| 117 |
# This function remains correct.
|
| 118 |
if not client: return 8, "NO_API_KEY_DEFAULT"
|
| 119 |
with st.spinner(f"Getting AI decision for {echelon_name}..."):
|
| 120 |
try:
|
| 121 |
+
# Use lower temp for rational, higher for human-like
|
| 122 |
temp = 0.1 if 'rational' in prompt else 0.7
|
| 123 |
response = client.chat.completions.create(
|
| 124 |
model=OPENAI_MODEL,
|
|
|
|
| 138 |
return 4, f"API_ERROR: {e}"
|
| 139 |
|
| 140 |
def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
|
| 141 |
+
"""
|
| 142 |
+
Generates the prompt for a specific AI agent based on its *individual* personality.
|
| 143 |
+
NO CHANGE WAS NEEDED in this function's logic, as it correctly routes
|
| 144 |
+
based on the llm_personality string it receives.
|
| 145 |
+
"""
|
| 146 |
e_state = echelon_state_decision_point
|
| 147 |
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"
|
| 148 |
if e_state['name'] == 'Factory':
|
|
|
|
| 168 |
inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
|
| 169 |
optimal_order = max(0, int(target_inventory_level - inventory_position))
|
| 170 |
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."
|
| 171 |
+
|
| 172 |
elif llm_personality == 'perfect_rational' and info_sharing == 'local':
|
| 173 |
safety_stock = 4; anchor_demand = e_state['incoming_order']
|
| 174 |
inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
|
|
|
|
| 182 |
calculated_order = anchor_demand + inventory_correction - supply_line
|
| 183 |
rational_local_order = max(0, int(calculated_order))
|
| 184 |
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."
|
| 185 |
+
|
| 186 |
elif llm_personality == 'human_like' and info_sharing == 'full':
|
| 187 |
full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
|
| 188 |
for name, other_e_state in all_echelons_state_decision_point.items():
|
|
|
|
| 197 |
You are still human and might get anxious about your own stock levels.
|
| 198 |
What {task_word} should you decide on this week? Respond with a single integer.
|
| 199 |
"""
|
| 200 |
+
|
| 201 |
elif llm_personality == 'human_like' and info_sharing == 'local':
|
| 202 |
return f"""
|
| 203 |
**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.
|
|
|
|
| 209 |
"""
|
| 210 |
|
| 211 |
def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
|
| 212 |
+
# This function's core logic remains correct.
|
| 213 |
state = st.session_state.game_state
|
| 214 |
week, echelons, human_role = state['week'], state['echelons'], state['human_role']
|
| 215 |
+
# --- MODIFIED: Get info_sharing, but llm_personality is now per-echelon ---
|
| 216 |
+
info_sharing = state['info_sharing']
|
| 217 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 218 |
+
|
| 219 |
llm_raw_responses = {}
|
|
|
|
| 220 |
opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
|
| 221 |
opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
|
|
|
|
| 222 |
arrived_this_week = {name: 0 for name in echelon_order}
|
| 223 |
inventory_after_arrival = {}
|
| 224 |
+
|
| 225 |
factory_state = echelons["Factory"]
|
| 226 |
produced_units = 0
|
| 227 |
if state['factory_production_pipeline']:
|
| 228 |
produced_units = state['factory_production_pipeline'].popleft()
|
| 229 |
arrived_this_week["Factory"] = produced_units
|
| 230 |
inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
|
| 231 |
+
|
| 232 |
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 233 |
arrived_shipment = 0
|
| 234 |
if echelons[name]['incoming_shipments']:
|
| 235 |
arrived_shipment = echelons[name]['incoming_shipments'].popleft()
|
| 236 |
arrived_this_week[name] = arrived_shipment
|
| 237 |
inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
|
| 238 |
+
|
| 239 |
total_backlog_before_shipping = {}
|
| 240 |
for name in echelon_order:
|
| 241 |
incoming_order_for_this_week = 0
|
|
|
|
| 245 |
if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
|
| 246 |
echelons[name]['incoming_order'] = incoming_order_for_this_week
|
| 247 |
total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
|
| 248 |
+
|
| 249 |
decision_point_states = {}
|
| 250 |
for name in echelon_order:
|
| 251 |
decision_point_states[name] = {
|
|
|
|
| 253 |
'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
|
| 254 |
'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
|
| 255 |
}
|
| 256 |
+
|
| 257 |
current_week_orders = {}
|
| 258 |
for name in echelon_order:
|
| 259 |
e = echelons[name]; prompt_state = decision_point_states[name]
|
| 260 |
+
|
| 261 |
+
if name == human_role:
|
| 262 |
+
order_amount, raw_resp = human_final_order, "HUMAN_FINAL_INPUT"
|
| 263 |
else:
|
| 264 |
+
# --- MODIFIED: Get the specific agent's personality ---
|
| 265 |
+
e_personality = e['personality']
|
| 266 |
+
prompt = get_llm_prompt(prompt_state, week, e_personality, info_sharing, decision_point_states)
|
| 267 |
order_amount, raw_resp = get_llm_order_decision(prompt, name)
|
| 268 |
+
|
| 269 |
llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
|
| 270 |
+
|
| 271 |
state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
|
|
|
|
| 272 |
units_shipped = {name: 0 for name in echelon_order}
|
| 273 |
+
|
| 274 |
for name in echelon_order:
|
| 275 |
e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
|
| 276 |
e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
|
| 277 |
e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
|
| 278 |
+
|
| 279 |
if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
|
| 280 |
if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
|
| 281 |
if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
|
| 282 |
+
|
| 283 |
+
# --- MODIFIED: Update logging fields ---
|
| 284 |
log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
|
| 285 |
+
# Remove large state objects from log entry
|
| 286 |
del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
|
| 287 |
+
# 'llm_personality' is already gone from state
|
| 288 |
+
|
| 289 |
for name in echelon_order:
|
| 290 |
e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
|
| 291 |
+
for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']:
|
| 292 |
+
log_entry[f'{name}.{key}'] = e[key]
|
| 293 |
+
|
| 294 |
+
log_entry[f'{name}.personality'] = e['personality'] # <-- NEW: Log individual personality
|
| 295 |
log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
|
| 296 |
log_entry[f'{name}.opening_inventory'] = opening_inventories[name]; log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
|
| 297 |
log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name]
|
| 298 |
+
if name != 'Factory':
|
| 299 |
+
log_entry[f'{name}.arriving_next_week'] = list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0
|
| 300 |
+
else:
|
| 301 |
+
log_entry[f'{name}.production_completing_next_week'] = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
|
| 302 |
+
|
| 303 |
log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
|
| 304 |
+
|
| 305 |
state['logs'].append(log_entry)
|
|
|
|
| 306 |
state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
|
| 307 |
+
|
| 308 |
if state['week'] > WEEKS: state['game_running'] = False
|
| 309 |
|
| 310 |
def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
|
|
|
| 312 |
fig, axes = plt.subplots(4, 1, figsize=(12, 22))
|
| 313 |
fig.suptitle(title, fontsize=16)
|
| 314 |
echelons = ['Retailer', 'Wholesaler', 'Distributor', 'Factory']
|
| 315 |
+
|
| 316 |
plot_data = []
|
| 317 |
for _, row in df.iterrows():
|
| 318 |
for e in echelons:
|
|
|
|
| 320 |
'inventory': row.get(f'{e}.inventory', 0), 'order_placed': row.get(f'{e}.order_placed', 0),
|
| 321 |
'total_cost': row.get(f'{e}.total_cost', 0)})
|
| 322 |
plot_df = pd.DataFrame(plot_data)
|
| 323 |
+
|
| 324 |
inventory_pivot = plot_df.pivot(index='week', columns='echelon', values='inventory').reindex(columns=echelons)
|
| 325 |
inventory_pivot.plot(ax=axes[0], kind='line', marker='o', markersize=4); axes[0].set_title('Inventory Levels (End of Week)'); axes[0].grid(True, linestyle='--'); axes[0].set_ylabel('Stock (Units)')
|
| 326 |
+
|
| 327 |
order_pivot = plot_df.pivot(index='week', columns='echelon', values='order_placed').reindex(columns=echelons)
|
| 328 |
order_pivot.plot(ax=axes[1], style='--'); axes[1].plot(range(1, WEEKS + 1), [get_customer_demand(w) for w in range(1, WEEKS + 1)], label='Customer Demand', color='black', lw=2.5); axes[1].set_title('Order Quantities / Production Decisions'); axes[1].grid(True, linestyle='--'); axes[1].legend(); axes[1].set_ylabel('Ordered/Produced (Units)')
|
| 329 |
+
|
| 330 |
total_costs = plot_df.loc[plot_df.groupby('echelon')['week'].idxmax()]
|
| 331 |
total_costs = total_costs.set_index('echelon')['total_cost'].reindex(echelons, fill_value=0)
|
| 332 |
total_costs.plot(kind='bar', ax=axes[2], rot=0); axes[2].set_title('Total Cumulative Cost'); axes[2].set_ylabel('Cost ($)')
|
| 333 |
+
|
| 334 |
human_cols = [f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed']
|
| 335 |
human_df_cols = ['week'] + [col for col in human_cols if col in df.columns]
|
| 336 |
try:
|
|
|
|
| 340 |
else: raise ValueError("No human decision data columns found.")
|
| 341 |
except (KeyError, ValueError) as plot_err:
|
| 342 |
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')
|
| 343 |
+
|
| 344 |
plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
|
| 345 |
|
| 346 |
def save_logs_and_upload(state: dict):
|
|
|
|
| 373 |
# --- Game Setup & Instructions ---
|
| 374 |
if 'game_state' not in st.session_state or not st.session_state.game_state.get('game_running', False):
|
| 375 |
|
|
|
|
|
|
|
| 376 |
st.header("⚙️ Game Configuration")
|
| 377 |
c1, c2 = st.columns(2)
|
| 378 |
with c1:
|
| 379 |
+
# --- MODIFIED: Changed from llm_personality to locus_of_chaos ---
|
| 380 |
+
locus_of_chaos = st.selectbox(
|
| 381 |
+
"AI Team Composition (Locus of Chaos)",
|
| 382 |
+
('Downstream Chaos', 'Upstream Chaos'),
|
| 383 |
+
format_func=lambda x: x.replace('_', ' ').title(),
|
| 384 |
+
help=(
|
| 385 |
+
"**Downstream Chaos:** Your customers (Retailer, Wholesaler) are 'Human-like' (chaotic). Your supplier (Factory) is 'Rational'.\n\n"
|
| 386 |
+
"**Upstream Chaos:** Your customers (Retailer, Wholesaler) are 'Rational' (stable). Your supplier (Factory) is 'Human-like'."
|
| 387 |
+
)
|
| 388 |
+
)
|
| 389 |
with c2:
|
| 390 |
+
info_sharing = st.selectbox(
|
| 391 |
+
"Information Sharing Level",
|
| 392 |
+
('local', 'full'),
|
| 393 |
+
format_func=lambda x: x.title(),
|
| 394 |
+
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."
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
if st.button("🚀 Start Game", type="primary", disabled=(client is None)):
|
| 398 |
+
# --- MODIFIED: Pass locus_of_chaos to init ---
|
| 399 |
+
init_game_state(locus_of_chaos, info_sharing)
|
| 400 |
st.rerun()
|
| 401 |
|
| 402 |
# --- Main Game Interface ---
|
| 403 |
elif 'game_state' in st.session_state and st.session_state.game_state.get('game_running'):
|
| 404 |
state = st.session_state.game_state
|
| 405 |
week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
|
| 406 |
+
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 407 |
+
|
| 408 |
st.header(f"Week {week} / {WEEKS}")
|
| 409 |
+
# --- MODIFIED: Update subheader to use locus_of_chaos ---
|
| 410 |
+
st.subheader(f"Your Role: **{human_role}** | AI Mode: **{state['locus_of_chaos']}** | Information: **{state['info_sharing']}**")
|
| 411 |
st.markdown("---")
|
| 412 |
+
|
| 413 |
+
st.subheader("Supply Chain Status (Start of Week State)")
|
| 414 |
+
|
| 415 |
if info_sharing == 'full':
|
| 416 |
cols = st.columns(4)
|
| 417 |
+
for i, name in enumerate(echelon_order):
|
| 418 |
with cols[i]:
|
| 419 |
+
e = echelons[name]
|
| 420 |
icon = "👤" if name == human_role else "🤖"
|
| 421 |
+
|
|
|
|
| 422 |
if name == human_role:
|
|
|
|
| 423 |
st.markdown(f"##### **<span style='border: 1px solid #FF4B4B; padding: 2px 5px; border-radius: 3px;'>{icon} {name} (You)</span>**", unsafe_allow_html=True)
|
| 424 |
else:
|
| 425 |
st.markdown(f"##### {icon} {name}")
|
| 426 |
+
# --- NEW: Display the specific AI's personality ---
|
| 427 |
+
personality_label = e['personality'].replace('_', ' ').title()
|
| 428 |
+
st.caption(f"AI Type: **{personality_label}**")
|
| 429 |
+
# -------------------------------------------------
|
| 430 |
+
|
| 431 |
st.metric("Inventory (Opening)", e['inventory'])
|
| 432 |
st.metric("Backlog (Opening)", e['backlog'])
|
| 433 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
current_incoming_order = 0
|
| 435 |
if name == "Retailer":
|
| 436 |
current_incoming_order = get_customer_demand(week)
|
|
|
|
| 438 |
downstream_name = e['downstream_name']
|
| 439 |
if downstream_name:
|
| 440 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 441 |
+
|
| 442 |
+
st.write(f"Incoming Order (This Week): **{current_incoming_order}**")
|
| 443 |
+
|
|
|
|
| 444 |
if name == "Factory":
|
| 445 |
prod_completing_next = list(state['factory_production_pipeline'])[0] if state['factory_production_pipeline'] else 0
|
| 446 |
st.write(f"Completing Next Week: **{prod_completing_next}**")
|
| 447 |
else:
|
| 448 |
arriving_next = list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0
|
| 449 |
st.write(f"Arriving Next Week: **{arriving_next}**")
|
| 450 |
+
|
| 451 |
else: # Local Info Mode
|
| 452 |
st.info("In Local Information mode, you can only see your own status dashboard.")
|
| 453 |
e = echelons[human_role]
|
| 454 |
+
st.markdown(f"### 👤 **<span style='color:#FF4B4B;'>{human_role} (Your Dashboard - Start of Week State)</span>**", unsafe_allow_html=True)
|
| 455 |
col1, col2, col3, col4 = st.columns(4)
|
| 456 |
|
|
|
|
| 457 |
col1.metric("Inventory (Opening)", e['inventory'])
|
| 458 |
col2.metric("Backlog (Opening)", e['backlog'])
|
| 459 |
+
|
|
|
|
|
|
|
| 460 |
current_incoming_order = 0
|
| 461 |
downstream_name = e['downstream_name'] # Wholesaler
|
| 462 |
+
if downstream_name:
|
| 463 |
current_incoming_order = state['last_week_orders'].get(downstream_name, 0)
|
| 464 |
+
|
| 465 |
+
col3.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
|
| 466 |
col4.write(f"**Shipment Arriving (Next Week):**\n# {list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0}")
|
| 467 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
st.markdown("---")
|
| 469 |
st.header("Your Decision (Step 4)")
|
| 470 |
+
|
| 471 |
# Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
|
| 472 |
all_decision_point_states = {}
|
| 473 |
for name in echelon_order:
|
| 474 |
+
e_curr = echelons[name]
|
| 475 |
arrived = 0
|
| 476 |
+
if name == "Factory":
|
|
|
|
| 477 |
if state['factory_production_pipeline']: arrived = list(state['factory_production_pipeline'])[0]
|
| 478 |
+
else:
|
| 479 |
if e_curr['incoming_shipments']: arrived = list(e_curr['incoming_shipments'])[0]
|
| 480 |
+
|
|
|
|
| 481 |
inv_after_arrival = e_curr['inventory'] + arrived
|
| 482 |
+
|
|
|
|
| 483 |
inc_order_this_week = 0
|
| 484 |
if name == "Retailer": inc_order_this_week = get_customer_demand(week)
|
| 485 |
else:
|
| 486 |
ds_name = e_curr['downstream_name']
|
| 487 |
if ds_name: inc_order_this_week = state['last_week_orders'].get(ds_name, 0)
|
| 488 |
+
|
| 489 |
backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
|
| 490 |
+
|
| 491 |
all_decision_point_states[name] = {
|
| 492 |
'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
|
| 493 |
+
'incoming_order': inc_order_this_week,
|
| 494 |
'incoming_shipments': e_curr['incoming_shipments'].copy() if name != "Factory" else deque()
|
| 495 |
}
|
| 496 |
+
|
| 497 |
human_echelon_state_for_prompt = all_decision_point_states[human_role]
|
| 498 |
+
|
| 499 |
if state['decision_step'] == 'initial_order':
|
| 500 |
with st.form(key="initial_order_form"):
|
| 501 |
st.markdown("#### **Step 4a:** Based on the dashboard, submit your **initial** order to the Factory.")
|
| 502 |
+
initial_order = st.number_input("Your Initial Order Quantity:", min_value=0, step=1)
|
|
|
|
|
|
|
| 503 |
if st.form_submit_button("Submit Initial Order & See AI Suggestion", type="primary"):
|
|
|
|
| 504 |
state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
|
| 505 |
state['decision_step'] = 'final_order'
|
| 506 |
st.rerun()
|
| 507 |
+
|
| 508 |
elif state['decision_step'] == 'final_order':
|
| 509 |
st.success(f"Your initial order was: **{state['human_initial_order']}** units.")
|
| 510 |
+
|
| 511 |
+
# --- MODIFIED: Get the human's "partner" AI personality for the suggestion ---
|
| 512 |
+
# In our design, the human (Distributor) gets a suggestion from an AI *acting as* the Distributor.
|
| 513 |
+
# We must decide which personality this "suggestion AI" should have.
|
| 514 |
+
# For simplicity, we'll use the personality defined for the HUMAN'S ROLE in the `personalities` dict.
|
| 515 |
+
# ...wait, that's "HUMAN_PLAYER".
|
| 516 |
+
#
|
| 517 |
+
# --- CORRECTION / EXECUTIVE DECISION ---
|
| 518 |
+
# The *suggestion* AI should match the human's role. But what personality?
|
| 519 |
+
# Let's assume the "Suggestion AI" is a *separate* entity that matches the *dominant* mode of the other AIs.
|
| 520 |
+
# This is complex.
|
| 521 |
+
#
|
| 522 |
+
# --- SIMPLER, BETTER LOGIC ---
|
| 523 |
+
# The experiment is about interacting with AI. The human *is* the Distributor.
|
| 524 |
+
# The AI *suggestion* should come from an AI also *simulating* the Distributor role.
|
| 525 |
+
# What personality should it have?
|
| 526 |
+
# Let's make the suggestion AI's personality *also* dependent on the Locus of Chaos.
|
| 527 |
+
# In 'Downstream Chaos', the human is surrounded by 'human_like' AIs. Their suggestion should be 'human_like'.
|
| 528 |
+
# In 'Upstream Chaos', the human is surrounded by 'perfect_rational' AIs. Their suggestion should be 'perfect_rational'.
|
| 529 |
+
#
|
| 530 |
+
# The human (Distributor)'s customers are Retailer/Wholesaler.
|
| 531 |
+
# So, the "suggestion" AI's personality will match the personality of the human's *customers*.
|
| 532 |
|
| 533 |
+
if state['locus_of_chaos'] == 'Downstream Chaos':
|
| 534 |
+
suggestion_ai_personality = 'human_like' # Matches chaotic customers
|
| 535 |
+
else: # 'Upstream Chaos'
|
| 536 |
+
suggestion_ai_personality = 'perfect_rational' # Matches rational customers
|
| 537 |
+
# ------------------------------------------------
|
| 538 |
|
| 539 |
+
prompt_sugg = get_llm_prompt(human_echelon_state_for_prompt, week, suggestion_ai_personality, state['info_sharing'], all_decision_point_states)
|
| 540 |
+
ai_suggestion, _ = get_llm_order_decision(prompt_sugg, f"{human_role} (Suggestion)")
|
| 541 |
+
|
| 542 |
with st.form(key="final_order_form"):
|
| 543 |
+
st.markdown(f"#### **Step 4b:** An AI {suggestion_ai_personality.replace('_', ' ')} assistant suggests ordering **{ai_suggestion}** units.")
|
| 544 |
st.markdown("Considering the AI's advice, submit your **final** order to end the week. (This order will arrive in 3 weeks).")
|
| 545 |
+
st.number_input("Your Final Order Quantity:", min_value=0, step=1, key='final_order_input')
|
| 546 |
+
|
|
|
|
|
|
|
| 547 |
if st.form_submit_button("Submit Final Order & Advance to Next Week"):
|
| 548 |
+
final_order_value = st.session_state.get('final_order_input', 0)
|
|
|
|
| 549 |
final_order_value = int(final_order_value) if final_order_value is not None else 0
|
| 550 |
+
|
| 551 |
step_game(final_order_value, state['human_initial_order'], ai_suggestion)
|
| 552 |
+
|
|
|
|
| 553 |
if 'final_order_input' in st.session_state: del st.session_state.final_order_input
|
| 554 |
st.rerun()
|
| 555 |
+
|
| 556 |
st.markdown("---")
|
| 557 |
with st.expander("📖 Your Weekly Decision Log", expanded=False):
|
| 558 |
if not state.get('logs'):
|
|
|
|
| 571 |
'week', f'{human_role}.opening_inventory', f'{human_role}.opening_backlog',
|
| 572 |
f'{human_role}.arrived_this_week', f'{human_role}.incoming_order',
|
| 573 |
f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed',
|
| 574 |
+
f'{human_role}.arriving_next_week', f'{human_role}.weekly_cost'
|
| 575 |
]
|
| 576 |
final_cols_to_display = [col for col in ordered_display_cols_keys if col in history_df.columns]
|
| 577 |
+
if not final_cols_to_display:
|
| 578 |
st.write("No data columns available to display.")
|
| 579 |
else:
|
| 580 |
display_df = history_df[final_cols_to_display].rename(columns=human_cols)
|
|
|
|
| 583 |
st.dataframe(display_df.sort_values(by="Week", ascending=False), hide_index=True, use_container_width=True)
|
| 584 |
except Exception as e:
|
| 585 |
st.error(f"Error displaying weekly log: {e}")
|
| 586 |
+
|
| 587 |
try: st.sidebar.image(IMAGE_PATH, caption="Supply Chain Reference")
|
| 588 |
except FileNotFoundError: st.sidebar.warning("Image file not found.")
|
| 589 |
st.sidebar.header("Game Info")
|
|
|
|
| 599 |
state = st.session_state.game_state
|
| 600 |
try:
|
| 601 |
logs_df = pd.json_normalize(state['logs'])
|
| 602 |
+
# --- MODIFIED: Update plot title ---
|
| 603 |
fig = plot_results(
|
| 604 |
logs_df,
|
| 605 |
+
f"Beer Game (Human: {state['human_role']})\n(AI Mode: {state['locus_of_chaos']} | Info: {state['info_sharing']})",
|
| 606 |
state['human_role']
|
| 607 |
)
|
| 608 |
st.pyplot(fig)
|
| 609 |
save_logs_and_upload(state)
|
| 610 |
except Exception as e:
|
| 611 |
st.error(f"Error generating final report: {e}")
|
| 612 |
+
|
| 613 |
if st.button("✨ Start a New Game"):
|
| 614 |
del st.session_state.game_state
|
| 615 |
st.rerun()
|