Spaces:
Sleeping
Sleeping
File size: 8,903 Bytes
578508e 30bdd62 578508e 752ff1f 578508e 30bdd62 578508e 30bdd62 578508e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | """Inference Script - EcoGrid OpenEnv
================================================
MANDATORY environment variables (injected by the validator):
API_BASE_URL The LiteLLM proxy endpoint.
HF_TOKEN Your API key for the proxy.
MODEL_NAME The model identifier to use for inference.
STDOUT FORMAT (exact - do not deviate):
[START] task=<task_name> env=<benchmark> model=<model_name>
[STEP] step=<n> action=<action_str> reward=<0.00> done=<true|false> error=<msg|null>
[END] success=<true|false> steps=<n> score=<0.000> rewards=<r1,r2,...,rn>
"""
import json
import os
import sys
from typing import List, Optional
from openai import OpenAI
from env.environment import EcoGridEnv
from env.action_utils import safe_grid_action
from env.tasks import BasicGridBalanceGrader, RenewableVariabilityGrader, CarbonConstrainedGrader
from models.schemas import GridAction, GridState
# -------------------------------------------------------------------
# MANDATORY: read from injected environment variables — no hardcoding.
# The validator checks that all LLM calls flow through API_BASE_URL.
# -------------------------------------------------------------------
API_BASE_URL: str = os.environ["API_BASE_URL"]
API_KEY: str = os.environ.get("API_KEY") or os.environ["HF_TOKEN"]
MODEL_NAME: str = os.environ.get("MODEL_NAME", "gpt-4o")
BENCHMARK: str = os.environ.get("BENCHMARK", "eco-grid-openenv")
SUCCESS_SCORE_THRESHOLD = 0.5
TASKS = ["easy", "medium", "hard"]
# Single shared client — always routed through the injected proxy URL.
_client = OpenAI(
base_url=API_BASE_URL,
api_key=API_KEY,
timeout=30.0,
max_retries=1,
)
# ---------------------------------------------------------------------------
# Logging helpers — exact format required by the validator
# ---------------------------------------------------------------------------
def log_start(task: str, env: str, model: str) -> None:
print(f"[START] task={task} env={env} model={model}", flush=True)
def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
error_val = error if error else "null"
print(
f"[STEP] step={step} action={action} reward={reward:.2f} "
f"done={str(done).lower()} error={error_val}",
flush=True,
)
def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
print(
f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}",
flush=True,
)
# ---------------------------------------------------------------------------
# Fallback policy
# ---------------------------------------------------------------------------
def _fallback_action(task_name: str, state: GridState) -> GridAction:
"""A safe fallback agent that performs reasonably well."""
avg_renewable_cap = (state.solar_capacity + state.wind_capacity) / 2.0
if state.demand > 0:
renewable_ratio = min(1.0, avg_renewable_cap / max(0.01, state.demand/100))
renewable_ratio = min(renewable_ratio, 1.0)
else:
renewable_ratio = 1.0
fossil_ratio = max(0.0, 1.0 - renewable_ratio)
if task_name == "hard" and state.carbon_budget_remaining < 200:
fossil_ratio = min(fossil_ratio, 0.4)
total = renewable_ratio + fossil_ratio
if total > 1.0:
if renewable_ratio > fossil_ratio:
fossil_ratio = 1.0 - renewable_ratio
else:
renewable_ratio = 1.0 - fossil_ratio
battery_action = 0.0
if state.demand > 100 and state.battery_level > 0.2:
battery_action = -0.8
elif state.demand < 60 and state.battery_level < 0.8:
battery_action = 0.8
return safe_grid_action(
renewable_ratio=renewable_ratio,
fossil_ratio=fossil_ratio,
battery_action=battery_action,
)
# ---------------------------------------------------------------------------
# LLM call — ALWAYS goes through the injected proxy (API_BASE_URL / _client)
# ---------------------------------------------------------------------------
def get_action_from_llm(state: GridState, task_name: str) -> GridAction:
"""Call the LLM via the injected proxy to choose a grid action."""
preferred = _fallback_action(task_name, state)
prompt = f"""
You are an expert energy grid operator managing a power grid.
Your goal is to balance renewable energy, fossil fuels, and battery storage to meet demand while minimising cost and carbon emissions.
CURRENT STATE:
{state.model_dump_json(indent=2)}
TASK: {task_name}
CONSTRAINTS:
- renewable_ratio + fossil_ratio <= 1.0
- battery_action must be between -1.0 (discharge) and 1.0 (charge)
- Grid stability target: >= 0.7
- Carbon budget remaining: {state.carbon_budget_remaining} kg CO2
Reason step-by-step internally about the best strategy, considering the current demand, available renewable capacity, and carbon budget.
Then, output ONLY a valid JSON object matching this schema, with no markdown fences:
{{
"renewable_ratio": float,
"fossil_ratio": float,
"battery_action": float
}}
"""
# This call MUST reach the proxy
response = _client.chat.completions.create(
model=MODEL_NAME,
messages=[
{"role": "user", "content": prompt},
],
temperature=0.2,
max_tokens=200,
stream=False,
)
content = (response.choices[0].message.content or "").strip()
if content.startswith("```json"):
content = content[7:-3]
elif content.startswith("```"):
content = content[3:-3]
data = json.loads(content)
return safe_grid_action(
renewable_ratio=data.get("renewable_ratio", preferred.renewable_ratio),
fossil_ratio=data.get("fossil_ratio", preferred.fossil_ratio),
battery_action=data.get("battery_action", preferred.battery_action),
)
# ---------------------------------------------------------------------------
# Main inference loop
# ---------------------------------------------------------------------------
def run_inference() -> None:
if not os.environ.get("API_BASE_URL"):
print("Warning: API_BASE_URL not set. Defaulting to localhost:8000.", file=sys.stderr, flush=True)
for task_name in TASKS:
env = EcoGridEnv()
env.reset(seed=42, task=task_name)
rewards: List[float] = []
steps_taken = 0
success = False
score = 0.001
done = False
log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)
try:
step = 1
while not done:
state = env.state()
error: Optional[str] = None
try:
action = get_action_from_llm(state, task_name)
# Create string representation for logging
action_str = json.dumps({
"ren": action.renewable_ratio,
"fos": action.fossil_ratio,
"bat": action.battery_action
})
except Exception as exc:
action = _fallback_action(task_name, state)
action_str = json.dumps({
"ren": action.renewable_ratio,
"fos": action.fossil_ratio,
"bat": action.battery_action
})
error = f"llm_error:{type(exc).__name__}"
try:
result = env.step(action)
reward = result.reward
done = result.done
except Exception as exc:
reward = 0.0
done = True
error = str(exc)
rewards.append(reward)
steps_taken = step
log_step(step=step, action=action_str, reward=reward, done=done, error=error)
step += 1
# Grade the episode
log = env.get_episode_log()
if task_name == "easy":
grader_result = BasicGridBalanceGrader.grade(log)
elif task_name == "medium":
grader_result = RenewableVariabilityGrader.grade(log)
else:
grader_result = CarbonConstrainedGrader.grade(log)
score = float(grader_result.score)
success = score >= SUCCESS_SCORE_THRESHOLD
except Exception as exc:
print(f"Fatal error in task {task_name}: {exc}", file=sys.stderr, flush=True)
success = False
score = 0.001
finally:
log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
if __name__ == "__main__":
run_inference()
|