ychanakya12 commited on
Commit
366df60
·
1 Parent(s): db4cb95

Strategic Stabilization: Balancing skill retention and aggressive growth

Browse files
Files changed (3) hide show
  1. app_ui.py +129 -0
  2. inference.py +31 -9
  3. requirements.txt +0 -0
app_ui.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import pandas as pd
4
+ from openai import OpenAI
5
+ from inference import run_task, TASKS, API_BASE_URL, API_KEY
6
+
7
+ # -- App Logic -----------------------------------------------------------------
8
+
9
+ def launch_ceo_simulation(task_id):
10
+ if not API_KEY:
11
+ return "ERROR: HF_TOKEN missing.", None, None, None
12
+
13
+ client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
14
+
15
+ # State for UI
16
+ history = []
17
+ budget_data = []
18
+ rep_data = []
19
+
20
+ def on_step(data):
21
+ if "done" in data:
22
+ return
23
+
24
+ step = data["step"]
25
+ obs = data["obs"]
26
+ thought = data["thought"]
27
+
28
+ # Update history
29
+ history.append({
30
+ "Quarter": obs.quarter,
31
+ "Budget": obs.budget,
32
+ "Reputation": obs.reputation,
33
+ "Market": obs.market_phase.value,
34
+ "Thought": thought
35
+ })
36
+
37
+ budget_data.append([obs.quarter, obs.budget])
38
+ rep_data.append([obs.quarter, obs.reputation])
39
+
40
+ # Yield updates to Gradio
41
+ try:
42
+ # We wrap the generator in a yield loop for Gradio
43
+ gen_data = {"step": 0, "logs": ""}
44
+
45
+ def ui_callback(d):
46
+ gen_data["last"] = d
47
+
48
+ # Run the task in a separate way or just yield manually
49
+ # Since run_task is synchronous but we want live updates,
50
+ # we refactor run_task to be a generator in a real app,
51
+ # but here we'll simulate the live feel by yielding at the end or
52
+ # using a simple queue if needed.
53
+ # For this version, let's keep it robust.
54
+
55
+ import threading
56
+ import time
57
+
58
+ results_queue = []
59
+ def queue_callback(d):
60
+ results_queue.append(d)
61
+
62
+ thread = threading.Thread(target=run_task, args=(client, task_id, queue_callback))
63
+ thread.start()
64
+
65
+ while thread.is_alive() or results_queue:
66
+ if results_queue:
67
+ data = results_queue.pop(0)
68
+ if "done" in data:
69
+ yield (
70
+ f"### Task Complete! \n**Final Score: {data.get('score', 0):.3f}**",
71
+ pd.DataFrame(history),
72
+ pd.DataFrame(budget_data, columns=["Quarter", "Budget"]),
73
+ pd.DataFrame(rep_data, columns=["Quarter", "Reputation"])
74
+ )
75
+ break
76
+
77
+ obs = data["obs"]
78
+ on_step(data)
79
+
80
+ status_md = f"""
81
+ ## 🏢 CEO Dashboard: {task_id}
82
+ **Quarter**: {obs.quarter} | **Budget**: ${obs.budget:,.0F} | **Reputation**: {obs.reputation:.2f}
83
+ **Market**: {obs.market_phase.value.upper()}
84
+ ---
85
+ **CEO THOUGHTS**:
86
+ > {data['thought']}
87
+ """
88
+
89
+ yield (
90
+ status_md,
91
+ pd.DataFrame(history),
92
+ pd.DataFrame(budget_data, columns=["Quarter", "Budget"]),
93
+ pd.DataFrame(rep_data, columns=["Quarter", "Reputation"])
94
+ )
95
+ time.sleep(0.1)
96
+
97
+ except Exception as e:
98
+ yield f"Error: {str(e)}", None, None, None
99
+
100
+ # -- UI Layout -----------------------------------------------------------------
101
+
102
+ with gr.Blocks(title="AI CEO Dashboard") as demo:
103
+ gr.Markdown("# 🏢 AI Strategic CEO Dashboard")
104
+ gr.Markdown("### Meta PyTorch Hackathon — Business Simulation")
105
+
106
+ with gr.Row():
107
+ task_input = gr.Dropdown(choices=TASKS, value=TASKS[0], label="Select Business Task")
108
+ run_btn = gr.Button("🚀 Start CEO Strategy", variant="primary")
109
+
110
+ status_display = gr.Markdown("Click Start to begin the simulation...")
111
+
112
+ with gr.Tabs():
113
+ with gr.TabItem("📊 Financial Pulse"):
114
+ with gr.Row():
115
+ budget_plot = gr.LinePlot(x="Quarter", y="Budget", title="Budget Growth")
116
+ rep_plot = gr.LinePlot(x="Quarter", y="Reputation", title="Reputation Trend")
117
+
118
+ with gr.TabItem("📋 Strategy Log"):
119
+ log_table = gr.Dataframe(headers=["Quarter", "Budget", "Reputation", "Market", "Thought"], wrap=True)
120
+
121
+ run_btn.click(
122
+ fn=launch_ceo_simulation,
123
+ inputs=[task_input],
124
+ outputs=[status_display, log_table, budget_plot, rep_plot]
125
+ )
126
+
127
+ if __name__ == "__main__":
128
+ demo.queue()
129
+ demo.launch(server_name="0.0.0.0", server_port=7861)
inference.py CHANGED
@@ -49,15 +49,16 @@ SYSTEM_PROMPT = textwrap.dedent("""
49
  - Task 'four_quarter_growth': Score = 70% Growth + 30% Reputation. Target 30% growth.
50
  - Task 'adversarial_resilience': Score = Survival (25%) + Profit (25%) + Reputation (20%) + Low Burnout (15%) + Rep Target Bonus (15%).
51
 
52
- TASK-SPECIFIC MANUAL (GUARANTEE 0.5+):
53
  1. 'single_quarter_survival': (1 Turn Only)
54
- - YOU MUST FIRE 3 DEVELOPERS (Fire_count: 3). Saving $24k is MANDATORY.
55
- - YOU MUST ACCEPT A PROJECT. Do not skip. Pick the highest ROI.
56
- - USE PREMIUM tech stack.
57
  2. 'four_quarter_growth' & 'adversarial_resilience': (Multi-Turn)
58
- - If Budget < $30,000: DO NOT accept any project.
59
- - Fire 2 devs on turn 1 to lower the burn rate immediately.
60
- - Accept projects with Success > 65%.
 
61
 
62
  JSON response format:
63
  {
@@ -139,7 +140,7 @@ def parse_action(response_text: str, observation) -> CEOAction:
139
 
140
  return action
141
 
142
- def run_task(client: OpenAI, task_id: str) -> None:
143
  log_start(task_id)
144
 
145
  env = BusinessSimEnv.from_docker_image(
@@ -151,10 +152,13 @@ def run_task(client: OpenAI, task_id: str) -> None:
151
  steps_taken = 0
152
  success = False
153
  score = 0.5
 
154
 
155
  try:
156
  result = env.reset()
157
  obs = result.observation
 
 
158
 
159
  hint = None
160
  for step in range(1, MAX_STEPS + 1):
@@ -173,6 +177,15 @@ def run_task(client: OpenAI, task_id: str) -> None:
173
  temperature = TEMPERATURE,
174
  )
175
  response = completion.choices[0].message.content or ""
 
 
 
 
 
 
 
 
 
176
  action = parse_action(response, obs)
177
 
178
  result = env.step(action)
@@ -189,6 +202,15 @@ def run_task(client: OpenAI, task_id: str) -> None:
189
 
190
  rewards.append(reward)
191
  log_step(step, "ceo_decision", reward, done, None)
 
 
 
 
 
 
 
 
 
192
 
193
  if done:
194
  break
@@ -206,11 +228,11 @@ def run_task(client: OpenAI, task_id: str) -> None:
206
  success = score >= SUCCESS_THRESHOLD
207
 
208
  except Exception as e:
209
- # Emergency end
210
  score = 0.1
211
  success = False
212
  finally:
213
  log_end(success, steps_taken, score, rewards)
 
214
  env.close()
215
 
216
  def main():
 
49
  - Task 'four_quarter_growth': Score = 70% Growth + 30% Reputation. Target 30% growth.
50
  - Task 'adversarial_resilience': Score = Survival (25%) + Profit (25%) + Reputation (20%) + Low Burnout (15%) + Rep Target Bonus (15%).
51
 
52
+ TASK-SPECIFIC MANUAL (STABILIZATION MODE):
53
  1. 'single_quarter_survival': (1 Turn Only)
54
+ - ACTION: Fire 2 developers (not 3). Keep skill high.
55
+ - SELECTION: Accept the project with the LOWEST Risk.
56
+ - TECH: Premium.
57
  2. 'four_quarter_growth' & 'adversarial_resilience': (Multi-Turn)
58
+ - ON QUARTER 1: Fire 1 developer. Reduce cost to ~$32k while keeping power.
59
+ - TRAINING: If Skill < 0.65, spend $20,000 on Training immediately.
60
+ - SELECTION: You are FORBIDDEN from accepting projects with Success Probability < 70%.
61
+ - IF NO SAFE PROJECTS: Simply wait, fire one more dev next turn, and look for a safer deal.
62
 
63
  JSON response format:
64
  {
 
140
 
141
  return action
142
 
143
+ def run_task(client: OpenAI, task_id: str, callback=None) -> None:
144
  log_start(task_id)
145
 
146
  env = BusinessSimEnv.from_docker_image(
 
152
  steps_taken = 0
153
  success = False
154
  score = 0.5
155
+ thought = ""
156
 
157
  try:
158
  result = env.reset()
159
  obs = result.observation
160
+
161
+ if callback: callback({"step": 0, "obs": obs, "thought": "Initializing CEO Agent..."})
162
 
163
  hint = None
164
  for step in range(1, MAX_STEPS + 1):
 
177
  temperature = TEMPERATURE,
178
  )
179
  response = completion.choices[0].message.content or ""
180
+
181
+ # Extract thought for UI
182
+ try:
183
+ clean = re.sub(r"```(?:json)?|```", "", response).strip()
184
+ match = re.search(r"\{.*\}", clean, re.DOTALL)
185
+ thought = json.loads(match.group()).get("thought_process", "")
186
+ except:
187
+ thought = response[:200]
188
+
189
  action = parse_action(response, obs)
190
 
191
  result = env.step(action)
 
202
 
203
  rewards.append(reward)
204
  log_step(step, "ceo_decision", reward, done, None)
205
+
206
+ if callback:
207
+ callback({
208
+ "step": step,
209
+ "obs": obs,
210
+ "thought": thought,
211
+ "reward": reward,
212
+ "action": action.model_dump()
213
+ })
214
 
215
  if done:
216
  break
 
228
  success = score >= SUCCESS_THRESHOLD
229
 
230
  except Exception as e:
 
231
  score = 0.1
232
  success = False
233
  finally:
234
  log_end(success, steps_taken, score, rewards)
235
+ if callback: callback({"done": True, "score": score, "success": success})
236
  env.close()
237
 
238
  def main():
requirements.txt CHANGED
Binary files a/requirements.txt and b/requirements.txt differ