Spaces:
Sleeping
Sleeping
Update inference.py
#17
by rsaibhargav - opened
- inference.py +24 -33
inference.py
CHANGED
|
@@ -6,7 +6,6 @@ MANDATORY
|
|
| 6 |
- Defaults set only for API_BASE_URL and MODEL_NAME (not HF_TOKEN)
|
| 7 |
- Must be named inference.py at repo root
|
| 8 |
- Must use OpenAI client for all LLM calls
|
| 9 |
-
- Connects to the environment server at localhost:8000 (started by container)
|
| 10 |
|
| 11 |
STDOUT FORMAT
|
| 12 |
[START] task=<task_name> env=<benchmark> model=<model_name>
|
|
@@ -16,13 +15,11 @@ STDOUT FORMAT
|
|
| 16 |
|
| 17 |
import asyncio
|
| 18 |
import os
|
|
|
|
| 19 |
import textwrap
|
| 20 |
from typing import List, Optional
|
| 21 |
|
| 22 |
from openai import OpenAI
|
| 23 |
-
from dotenv import load_dotenv
|
| 24 |
-
|
| 25 |
-
load_dotenv()
|
| 26 |
|
| 27 |
from code_assessment_env import CodeAssessmentAction, CodeAssessmentEnv
|
| 28 |
|
|
@@ -31,16 +28,13 @@ if not HF_TOKEN:
|
|
| 31 |
raise ValueError("HF_TOKEN environment variable is required but not set.")
|
| 32 |
|
| 33 |
API_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
|
| 34 |
-
MODEL_NAME = os.getenv("MODEL_NAME", "
|
| 35 |
TASK_NAME = os.getenv("TASK_NAME", "ai_response_evaluation")
|
| 36 |
BENCHMARK = os.getenv("BENCHMARK", "code_assessment_env")
|
| 37 |
MAX_STEPS = 15
|
| 38 |
TEMPERATURE = 0.2
|
| 39 |
MAX_TOKENS = 200
|
| 40 |
-
SUCCESS_SCORE_THRESHOLD = 0.5
|
| 41 |
-
MAX_TOTAL_REWARD = 40.0
|
| 42 |
|
| 43 |
-
# ─── System prompts per task ────────────────────────────────────────────────
|
| 44 |
SYSTEM_PROMPTS = {
|
| 45 |
"correctness_check": textwrap.dedent("""\
|
| 46 |
You are an expert AI response evaluator.
|
|
@@ -104,7 +98,6 @@ SYSTEM_PROMPTS = {
|
|
| 104 |
}
|
| 105 |
|
| 106 |
|
| 107 |
-
# ─── Logging ────────────────────────────────────────────────────────────────
|
| 108 |
def log_start(task: str, env: str, model: str) -> None:
|
| 109 |
print(f"[START] task={task} env={env} model={model}", flush=True)
|
| 110 |
|
|
@@ -123,11 +116,11 @@ def log_end(success: bool, steps: int, rewards: List[float]) -> None:
|
|
| 123 |
print(f"[END] success={str(success).lower()} steps={steps} rewards={rewards_str}", flush=True)
|
| 124 |
|
| 125 |
|
| 126 |
-
# ─── Prompt building ───────────────────────────────────────────────────────
|
| 127 |
def build_user_prompt(
|
| 128 |
step: int,
|
| 129 |
task_type: str,
|
| 130 |
-
|
|
|
|
| 131 |
difficulty: str,
|
| 132 |
feedback: str,
|
| 133 |
is_correct: bool,
|
|
@@ -151,10 +144,12 @@ def build_user_prompt(
|
|
| 151 |
profile = "USER PROFILE: " + " | ".join(profile_parts) + "\n\n"
|
| 152 |
|
| 153 |
return textwrap.dedent(f"""\
|
| 154 |
-
Step {step}/
|
|
|
|
|
|
|
| 155 |
|
| 156 |
{profile}--- SCENARIO ---
|
| 157 |
-
{
|
| 158 |
--- END SCENARIO ---
|
| 159 |
|
| 160 |
Previous feedback: {status}
|
|
@@ -163,13 +158,13 @@ def build_user_prompt(
|
|
| 163 |
""")
|
| 164 |
|
| 165 |
|
| 166 |
-
# ─── LLM call ──────────────────────────────────────────────────────────────
|
| 167 |
def get_model_answer(
|
| 168 |
client: OpenAI,
|
| 169 |
history: List[dict],
|
| 170 |
step: int,
|
| 171 |
task_type: str,
|
| 172 |
-
|
|
|
|
| 173 |
difficulty: str,
|
| 174 |
feedback: str,
|
| 175 |
is_correct: bool,
|
|
@@ -180,7 +175,7 @@ def get_model_answer(
|
|
| 180 |
user_context: Optional[str],
|
| 181 |
) -> str:
|
| 182 |
user_prompt = build_user_prompt(
|
| 183 |
-
step, task_type,
|
| 184 |
feedback, is_correct, streak, problems_solved,
|
| 185 |
user_age, user_mood, user_context,
|
| 186 |
)
|
|
@@ -206,7 +201,6 @@ def get_model_answer(
|
|
| 206 |
return answer
|
| 207 |
|
| 208 |
|
| 209 |
-
# ─── Main loop ──────────────────────────────────────────────────────────────
|
| 210 |
async def main() -> None:
|
| 211 |
client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)
|
| 212 |
|
|
@@ -216,8 +210,8 @@ async def main() -> None:
|
|
| 216 |
rewards: List[float] = []
|
| 217 |
history: List[dict] = []
|
| 218 |
steps_taken = 0
|
| 219 |
-
score = 0.0
|
| 220 |
success = False
|
|
|
|
| 221 |
|
| 222 |
log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)
|
| 223 |
|
|
@@ -226,6 +220,8 @@ async def main() -> None:
|
|
| 226 |
obs = result.observation
|
| 227 |
|
| 228 |
for step in range(1, MAX_STEPS + 1):
|
|
|
|
|
|
|
| 229 |
if result.done:
|
| 230 |
break
|
| 231 |
|
|
@@ -234,7 +230,8 @@ async def main() -> None:
|
|
| 234 |
history=history,
|
| 235 |
step=step,
|
| 236 |
task_type=obs.task_type,
|
| 237 |
-
|
|
|
|
| 238 |
difficulty=obs.difficulty,
|
| 239 |
feedback=obs.feedback,
|
| 240 |
is_correct=obs.is_correct,
|
|
@@ -249,34 +246,28 @@ async def main() -> None:
|
|
| 249 |
result = await env.step(CodeAssessmentAction(answer=answer))
|
| 250 |
obs = result.observation
|
| 251 |
except Exception as exc:
|
| 252 |
-
log_step(step=step, action=answer[:60], reward=0.
|
| 253 |
-
steps_taken = step
|
| 254 |
break
|
| 255 |
|
| 256 |
-
reward = result.reward
|
| 257 |
done = result.done
|
| 258 |
|
| 259 |
rewards.append(reward)
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
action_str = f"{answer[:60]} | correct={obs.is_correct} | {obs.difficulty}"
|
| 263 |
-
log_step(step=step, action=action_str, reward=reward, done=done, error=None)
|
| 264 |
|
| 265 |
if done:
|
| 266 |
break
|
| 267 |
|
| 268 |
-
|
| 269 |
-
score = min(max(score, 0.0), 1.0)
|
| 270 |
-
success = score >= SUCCESS_SCORE_THRESHOLD
|
| 271 |
|
| 272 |
-
except Exception:
|
| 273 |
-
|
| 274 |
|
| 275 |
finally:
|
| 276 |
try:
|
| 277 |
await env.close()
|
| 278 |
-
except Exception:
|
| 279 |
-
|
| 280 |
log_end(success=success, steps=steps_taken, rewards=rewards)
|
| 281 |
|
| 282 |
|
|
|
|
| 6 |
- Defaults set only for API_BASE_URL and MODEL_NAME (not HF_TOKEN)
|
| 7 |
- Must be named inference.py at repo root
|
| 8 |
- Must use OpenAI client for all LLM calls
|
|
|
|
| 9 |
|
| 10 |
STDOUT FORMAT
|
| 11 |
[START] task=<task_name> env=<benchmark> model=<model_name>
|
|
|
|
| 15 |
|
| 16 |
import asyncio
|
| 17 |
import os
|
| 18 |
+
import sys
|
| 19 |
import textwrap
|
| 20 |
from typing import List, Optional
|
| 21 |
|
| 22 |
from openai import OpenAI
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
from code_assessment_env import CodeAssessmentAction, CodeAssessmentEnv
|
| 25 |
|
|
|
|
| 28 |
raise ValueError("HF_TOKEN environment variable is required but not set.")
|
| 29 |
|
| 30 |
API_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
|
| 31 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4.1-mini")
|
| 32 |
TASK_NAME = os.getenv("TASK_NAME", "ai_response_evaluation")
|
| 33 |
BENCHMARK = os.getenv("BENCHMARK", "code_assessment_env")
|
| 34 |
MAX_STEPS = 15
|
| 35 |
TEMPERATURE = 0.2
|
| 36 |
MAX_TOKENS = 200
|
|
|
|
|
|
|
| 37 |
|
|
|
|
| 38 |
SYSTEM_PROMPTS = {
|
| 39 |
"correctness_check": textwrap.dedent("""\
|
| 40 |
You are an expert AI response evaluator.
|
|
|
|
| 98 |
}
|
| 99 |
|
| 100 |
|
|
|
|
| 101 |
def log_start(task: str, env: str, model: str) -> None:
|
| 102 |
print(f"[START] task={task} env={env} model={model}", flush=True)
|
| 103 |
|
|
|
|
| 116 |
print(f"[END] success={str(success).lower()} steps={steps} rewards={rewards_str}", flush=True)
|
| 117 |
|
| 118 |
|
|
|
|
| 119 |
def build_user_prompt(
|
| 120 |
step: int,
|
| 121 |
task_type: str,
|
| 122 |
+
problem_description: str,
|
| 123 |
+
test_case_input: str,
|
| 124 |
difficulty: str,
|
| 125 |
feedback: str,
|
| 126 |
is_correct: bool,
|
|
|
|
| 144 |
profile = "USER PROFILE: " + " | ".join(profile_parts) + "\n\n"
|
| 145 |
|
| 146 |
return textwrap.dedent(f"""\
|
| 147 |
+
Step {step}/{MAX_STEPS} | Task: {task_type} | Difficulty: {difficulty.upper()} | Solved: {problems_solved} | Streak: {streak}
|
| 148 |
+
|
| 149 |
+
INSTRUCTIONS: {problem_description}
|
| 150 |
|
| 151 |
{profile}--- SCENARIO ---
|
| 152 |
+
{test_case_input}
|
| 153 |
--- END SCENARIO ---
|
| 154 |
|
| 155 |
Previous feedback: {status}
|
|
|
|
| 158 |
""")
|
| 159 |
|
| 160 |
|
|
|
|
| 161 |
def get_model_answer(
|
| 162 |
client: OpenAI,
|
| 163 |
history: List[dict],
|
| 164 |
step: int,
|
| 165 |
task_type: str,
|
| 166 |
+
problem_description: str,
|
| 167 |
+
test_case_input: str,
|
| 168 |
difficulty: str,
|
| 169 |
feedback: str,
|
| 170 |
is_correct: bool,
|
|
|
|
| 175 |
user_context: Optional[str],
|
| 176 |
) -> str:
|
| 177 |
user_prompt = build_user_prompt(
|
| 178 |
+
step, task_type, problem_description, test_case_input, difficulty,
|
| 179 |
feedback, is_correct, streak, problems_solved,
|
| 180 |
user_age, user_mood, user_context,
|
| 181 |
)
|
|
|
|
| 201 |
return answer
|
| 202 |
|
| 203 |
|
|
|
|
| 204 |
async def main() -> None:
|
| 205 |
client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)
|
| 206 |
|
|
|
|
| 210 |
rewards: List[float] = []
|
| 211 |
history: List[dict] = []
|
| 212 |
steps_taken = 0
|
|
|
|
| 213 |
success = False
|
| 214 |
+
result = None
|
| 215 |
|
| 216 |
log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)
|
| 217 |
|
|
|
|
| 220 |
obs = result.observation
|
| 221 |
|
| 222 |
for step in range(1, MAX_STEPS + 1):
|
| 223 |
+
steps_taken = step
|
| 224 |
+
|
| 225 |
if result.done:
|
| 226 |
break
|
| 227 |
|
|
|
|
| 230 |
history=history,
|
| 231 |
step=step,
|
| 232 |
task_type=obs.task_type,
|
| 233 |
+
problem_description=obs.problem_description,
|
| 234 |
+
test_case_input=obs.test_case_input,
|
| 235 |
difficulty=obs.difficulty,
|
| 236 |
feedback=obs.feedback,
|
| 237 |
is_correct=obs.is_correct,
|
|
|
|
| 246 |
result = await env.step(CodeAssessmentAction(answer=answer))
|
| 247 |
obs = result.observation
|
| 248 |
except Exception as exc:
|
| 249 |
+
log_step(step=step, action=answer[:60], reward=0.05, done=True, error=str(exc))
|
|
|
|
| 250 |
break
|
| 251 |
|
| 252 |
+
reward = result.reward if result.reward is not None else 0.05
|
| 253 |
done = result.done
|
| 254 |
|
| 255 |
rewards.append(reward)
|
| 256 |
+
log_step(step=step, action=answer[:60], reward=reward, done=done, error=None)
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
if done:
|
| 259 |
break
|
| 260 |
|
| 261 |
+
success = bool(result is not None and result.done and obs.problems_solved > 0)
|
|
|
|
|
|
|
| 262 |
|
| 263 |
+
except Exception as exc:
|
| 264 |
+
print(f"Episode error: {exc}", file=sys.stderr, flush=True)
|
| 265 |
|
| 266 |
finally:
|
| 267 |
try:
|
| 268 |
await env.close()
|
| 269 |
+
except Exception as exc:
|
| 270 |
+
print(f"Close error: {exc}", file=sys.stderr, flush=True)
|
| 271 |
log_end(success=success, steps=steps_taken, rewards=rewards)
|
| 272 |
|
| 273 |
|