Spaces:
Sleeping
Sleeping
Update inference.py
Browse files- inference.py +56 -87
inference.py
CHANGED
|
@@ -1,114 +1,83 @@
|
|
| 1 |
import os
|
| 2 |
-
import json
|
| 3 |
import asyncio
|
| 4 |
-
import traceback
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
from openai import OpenAI
|
| 7 |
from environment import CloudCostEnv
|
| 8 |
-
from flask import Flask, jsonify, request
|
| 9 |
|
| 10 |
load_dotenv()
|
| 11 |
|
| 12 |
-
|
| 13 |
-
env
|
|
|
|
| 14 |
|
| 15 |
-
def
|
| 16 |
-
print(f"[START] task={task} env={env_name} model={model}", flush=True)
|
| 17 |
-
|
| 18 |
-
def log_step(step, action, reward, done, error=None):
|
| 19 |
error_val = error if error else "null"
|
| 20 |
-
|
|
|
|
| 21 |
|
| 22 |
-
def log_end(success, steps, score, rewards):
|
| 23 |
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
|
| 24 |
print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}", flush=True)
|
| 25 |
|
|
|
|
| 26 |
SYSTEM_PROMPT = "You are a Cloud Infrastructure AI. Manage the cluster by choosing actions: 0(Stay), 1(Add Server), 2(Remove), 3(Toggle Spot). Reply with ONLY the integer."
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
loop = asyncio.new_event_loop()
|
| 36 |
-
asyncio.set_event_loop(loop)
|
| 37 |
-
return loop.run_until_complete(coro)
|
| 38 |
-
|
| 39 |
-
@app.route('/health', methods=['GET'])
|
| 40 |
-
def health():
|
| 41 |
-
return jsonify({"status": "ok"}), 200
|
| 42 |
|
| 43 |
-
@app.route('/reset', methods=['POST'])
|
| 44 |
-
def reset():
|
| 45 |
-
global env
|
| 46 |
-
print("[DEBUG] /reset called", flush=True)
|
| 47 |
try:
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
| 54 |
)
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
state_data = json.loads(state.model_dump_json())
|
| 59 |
-
elif hasattr(state, '__dict__'):
|
| 60 |
-
state_data = state.__dict__
|
| 61 |
-
else:
|
| 62 |
-
state_data = str(state)
|
| 63 |
-
|
| 64 |
-
print("[DEBUG] /reset success", flush=True)
|
| 65 |
-
return jsonify({"status": "ok", "state": state_data}), 200
|
| 66 |
-
|
| 67 |
except Exception as e:
|
| 68 |
-
|
| 69 |
-
print(f"[ERROR] /reset crashed:\n{full_error}", flush=True)
|
| 70 |
-
return jsonify({
|
| 71 |
-
"status": "error",
|
| 72 |
-
"message": str(e),
|
| 73 |
-
"trace": full_error
|
| 74 |
-
}), 500
|
| 75 |
|
| 76 |
-
|
| 77 |
-
def
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
return jsonify({"status": "error", "message": "Call /reset first"}), 400
|
| 82 |
-
|
| 83 |
-
data = request.get_json()
|
| 84 |
-
action = int(data.get("action", 0))
|
| 85 |
-
state, reward, done = run_async(env.step(action))
|
| 86 |
-
log_step(step=1, action=str(action), reward=reward, done=done)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
state_data = json.loads(state.model_dump_json())
|
| 92 |
-
elif hasattr(state, '__dict__'):
|
| 93 |
-
state_data = state.__dict__
|
| 94 |
-
else:
|
| 95 |
-
state_data = str(state)
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
"reward": reward,
|
| 100 |
-
"done": done
|
| 101 |
-
}), 200
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
except Exception as e:
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
"status": "error",
|
| 108 |
-
"message": str(e),
|
| 109 |
-
"trace": full_error
|
| 110 |
-
}), 500
|
| 111 |
|
| 112 |
if __name__ == "__main__":
|
| 113 |
-
|
| 114 |
-
app.run(host="0.0.0.0", port=8080, debug=False)
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import asyncio
|
|
|
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
from openai import OpenAI
|
| 5 |
from environment import CloudCostEnv
|
|
|
|
| 6 |
|
| 7 |
load_dotenv()
|
| 8 |
|
| 9 |
+
# --- MANDATORY LOGGING FUNCTIONS (Don't Change) ---
|
| 10 |
+
def log_start(task: str, env: str, model: str) -> None:
|
| 11 |
+
print(f"[START] task={task} env={env} model={model}", flush=True)
|
| 12 |
|
| 13 |
+
def log_step(step: int, action: str, reward: float, done: bool, error=None) -> None:
|
|
|
|
|
|
|
|
|
|
| 14 |
error_val = error if error else "null"
|
| 15 |
+
done_val = str(done).lower()
|
| 16 |
+
print(f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}", flush=True)
|
| 17 |
|
| 18 |
+
def log_end(success: bool, steps: int, score: float, rewards: list) -> None:
|
| 19 |
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
|
| 20 |
print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}", flush=True)
|
| 21 |
|
| 22 |
+
# --- SYSTEM PROMPT ---
|
| 23 |
SYSTEM_PROMPT = "You are a Cloud Infrastructure AI. Manage the cluster by choosing actions: 0(Stay), 1(Add Server), 2(Remove), 3(Toggle Spot). Reply with ONLY the integer."
|
| 24 |
|
| 25 |
+
# --- GET ACTION FROM LLM ---
|
| 26 |
+
async def get_action_from_llama(state):
|
| 27 |
+
api_base = os.getenv("API_BASE_URL")
|
| 28 |
+
api_key = os.getenv("HF_TOKEN")
|
| 29 |
+
model_name = os.getenv("MODEL_NAME")
|
| 30 |
+
client = OpenAI(base_url=api_base, api_key=api_key)
|
| 31 |
+
state_data = state.model_dump_json() if hasattr(state, 'model_dump_json') else str(state)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
try:
|
| 34 |
+
response = client.chat.completions.create(
|
| 35 |
+
model=model_name,
|
| 36 |
+
messages=[
|
| 37 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 38 |
+
{"role": "user", "content": f"Current State: {state_data}"}
|
| 39 |
+
],
|
| 40 |
+
max_tokens=10
|
| 41 |
)
|
| 42 |
+
action_text = response.choices[0].message.content.strip()
|
| 43 |
+
action_int = int(''.join(filter(str.isdigit, action_text))[0])
|
| 44 |
+
return action_int, action_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
except Exception as e:
|
| 46 |
+
return 0, f"Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
# --- MAIN AGENT LOOP ---
|
| 49 |
+
async def main():
|
| 50 |
+
api_base = os.getenv("API_BASE_URL")
|
| 51 |
+
api_key = os.getenv("HF_TOKEN")
|
| 52 |
+
model_name = os.getenv("MODEL_NAME")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
task_id = "daily_peaks"
|
| 55 |
+
env = CloudCostEnv(task="medium")
|
| 56 |
+
log_start(task=task_id, env="CloudEnv-v1", model=model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
rewards = []
|
| 59 |
+
state = await env.reset()
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
try:
|
| 62 |
+
for step in range(1, 21):
|
| 63 |
+
action_int, action_text = await get_action_from_llama(state)
|
| 64 |
+
state, reward, done = await env.step(action_int)
|
| 65 |
+
log_step(step=step, action=str(action_int), reward=reward, done=done)
|
| 66 |
+
rewards.append(reward)
|
| 67 |
+
if done:
|
| 68 |
+
break
|
| 69 |
+
|
| 70 |
+
avg_score = sum(rewards) / len(rewards) if rewards else 0
|
| 71 |
+
log_end(
|
| 72 |
+
success=(avg_score >= 0.7),
|
| 73 |
+
steps=len(rewards),
|
| 74 |
+
score=avg_score,
|
| 75 |
+
rewards=rewards
|
| 76 |
+
)
|
| 77 |
except Exception as e:
|
| 78 |
+
log_step(step=0, action="error", reward=0.0, done=True, error=str(e))
|
| 79 |
+
finally:
|
| 80 |
+
await env.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
if __name__ == "__main__":
|
| 83 |
+
asyncio.run(main())
|
|
|