Spaces:
Sleeping
Sleeping
Commit ·
c357a18
1
Parent(s): 51fe7a3
Updated inference and added logging as per the task requirement
Browse files- environment.py +2 -2
- inference.py +254 -0
- logger.py +36 -0
environment.py
CHANGED
|
@@ -98,8 +98,8 @@ class EmailSortingEnvironment:
|
|
| 98 |
components: Dict[str, float] = {}
|
| 99 |
total = 0.0
|
| 100 |
|
| 101 |
-
cat_given = action.
|
| 102 |
-
urg_given = action.
|
| 103 |
|
| 104 |
if cat_given == email.get("correct_category"):
|
| 105 |
components["category_correct"] = 0.15
|
|
|
|
| 98 |
components: Dict[str, float] = {}
|
| 99 |
total = 0.0
|
| 100 |
|
| 101 |
+
cat_given = action.category.value if action.category else None
|
| 102 |
+
urg_given = action.urgency.value if action.urgency else None
|
| 103 |
|
| 104 |
if cat_given == email.get("correct_category"):
|
| 105 |
components["category_correct"] = 0.15
|
inference.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_dotenv()
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import sys
|
| 8 |
+
from typing import Any, Dict, List, Literal, Optional
|
| 9 |
+
import httpx
|
| 10 |
+
from openai import OpenAI
|
| 11 |
+
from pydantic import BaseModel, ConfigDict
|
| 12 |
+
from logger import log_start, log_step, log_end
|
| 13 |
+
|
| 14 |
+
API_BASE_URL: str = os.getenv("API_BASE_URL") or "https//router.huggingface.co/v1"
|
| 15 |
+
MODEL_NAME: str = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-7B-Instruct"
|
| 16 |
+
API_KEY: str = os.getenv("OPENAI_API_KEY", "")
|
| 17 |
+
HF_TOKEN: str = os.getenv("HF_TOKEN", "")
|
| 18 |
+
ENV_BASE_URL: str = os.getenv("ENV_BASE_URL", "http://localhost:7860")
|
| 19 |
+
TASKS = ["email_classification", "response_drafting", "support_session"]
|
| 20 |
+
MAX_STEPS_FALLBACK = 60
|
| 21 |
+
BENCHMARK = "Sieve"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ClassifyOutput(BaseModel):
|
| 25 |
+
model_config = ConfigDict(extra="forbid")
|
| 26 |
+
category: Literal[
|
| 27 |
+
"billing", "technical", "general", "spam", "account", "feature_request"
|
| 28 |
+
]
|
| 29 |
+
urgency: Literal["high", "medium", "low"]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class RespondOutput(BaseModel):
|
| 33 |
+
model_config = ConfigDict(extra="forbid")
|
| 34 |
+
response_text: str
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class SessionOutput(BaseModel):
|
| 38 |
+
model_config = ConfigDict(extra="forbid")
|
| 39 |
+
email_id: str
|
| 40 |
+
action_type: Literal["respond", "escalate", "archive"]
|
| 41 |
+
category: Literal[
|
| 42 |
+
"billing", "technical", "general", "spam", "account", "feature_request"
|
| 43 |
+
]
|
| 44 |
+
urgency: Literal["high", "medium", "low"]
|
| 45 |
+
response_text: Optional[str] = None
|
| 46 |
+
escalation_reason: Optional[str] = None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def strict_schema(output_cls: type[BaseModel]) -> dict:
|
| 50 |
+
schema = output_cls.model_json_schema()
|
| 51 |
+
if "properties" in schema:
|
| 52 |
+
schema["required"] = list(schema["properties"].keys())
|
| 53 |
+
schema["additionalProperties"] = False
|
| 54 |
+
return schema
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def structured_call(client: OpenAI, messages: list, output_cls: type[BaseModel]):
|
| 58 |
+
response = client.chat.completions.create(
|
| 59 |
+
model=MODEL_NAME,
|
| 60 |
+
messages=messages,
|
| 61 |
+
response_format={
|
| 62 |
+
"type": "json_schema",
|
| 63 |
+
"json_schema": {
|
| 64 |
+
"name": output_cls.__name__,
|
| 65 |
+
"schema": strict_schema(output_cls),
|
| 66 |
+
"strict": True,
|
| 67 |
+
},
|
| 68 |
+
},
|
| 69 |
+
temperature=0,
|
| 70 |
+
)
|
| 71 |
+
return output_cls.model_validate_json(response.choices[0].message.content)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def llm_action(
|
| 75 |
+
observation: Dict[str, Any], task_id: str, client: OpenAI
|
| 76 |
+
) -> Dict[str, Any]:
|
| 77 |
+
current = observation.get("current_email") or {}
|
| 78 |
+
queue: List[Dict] = observation.get("email_queue", [])
|
| 79 |
+
|
| 80 |
+
try:
|
| 81 |
+
if task_id == "email_classification":
|
| 82 |
+
result = structured_call(
|
| 83 |
+
client,
|
| 84 |
+
messages=[
|
| 85 |
+
{
|
| 86 |
+
"role": "system",
|
| 87 |
+
"content": "Classify customer support emails by category and urgency.",
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"role": "user",
|
| 91 |
+
"content": f"Subject: {current.get('subject', '')}\nBody: {current.get('body', '')}",
|
| 92 |
+
},
|
| 93 |
+
],
|
| 94 |
+
output_cls=ClassifyOutput,
|
| 95 |
+
)
|
| 96 |
+
return {
|
| 97 |
+
"action_type": "classify",
|
| 98 |
+
"category": result.category,
|
| 99 |
+
"urgency": result.urgency,
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
if task_id == "response_drafting":
|
| 103 |
+
result = structured_call(
|
| 104 |
+
client,
|
| 105 |
+
messages=[
|
| 106 |
+
{
|
| 107 |
+
"role": "system",
|
| 108 |
+
"content": (
|
| 109 |
+
"Write a professional, empathetic customer support response. "
|
| 110 |
+
"Address the issue directly, include relevant details (timelines, links, case refs). "
|
| 111 |
+
"Minimum 80 words."
|
| 112 |
+
),
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"role": "user",
|
| 116 |
+
"content": f"Subject: {current.get('subject', '')}\nBody: {current.get('body', '')}",
|
| 117 |
+
},
|
| 118 |
+
],
|
| 119 |
+
output_cls=RespondOutput,
|
| 120 |
+
)
|
| 121 |
+
return {"action_type": "respond", "response_text": result.response_text}
|
| 122 |
+
|
| 123 |
+
if task_id == "support_session":
|
| 124 |
+
queue_str = "\n".join(
|
| 125 |
+
f"{e['id']} | VIP={e.get('sender_tier') == 'vip'} | {e['subject'][:70]}"
|
| 126 |
+
for e in queue[:15]
|
| 127 |
+
)
|
| 128 |
+
result = structured_call(
|
| 129 |
+
client,
|
| 130 |
+
messages=[
|
| 131 |
+
{
|
| 132 |
+
"role": "system",
|
| 133 |
+
"content": (
|
| 134 |
+
"You manage a customer support queue. Pick the single highest-priority email.\n"
|
| 135 |
+
"Priority: 1) VIP=True first 2) security/breach → escalate "
|
| 136 |
+
"3) billing/technical → respond 4) feature requests/spam → archive"
|
| 137 |
+
),
|
| 138 |
+
},
|
| 139 |
+
{"role": "user", "content": queue_str},
|
| 140 |
+
],
|
| 141 |
+
output_cls=SessionOutput,
|
| 142 |
+
)
|
| 143 |
+
action: Dict[str, Any] = {
|
| 144 |
+
"action_type": result.action_type,
|
| 145 |
+
"email_id": result.email_id,
|
| 146 |
+
"category": result.category,
|
| 147 |
+
"urgency": result.urgency,
|
| 148 |
+
}
|
| 149 |
+
if result.response_text:
|
| 150 |
+
action["response_text"] = result.response_text
|
| 151 |
+
if result.escalation_reason:
|
| 152 |
+
action["escalation_reason"] = result.escalation_reason
|
| 153 |
+
return action
|
| 154 |
+
|
| 155 |
+
except Exception as exc:
|
| 156 |
+
raise RuntimeError(f"LLM call failed for task '{task_id}': {exc}") from exc
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def get_task_max_steps(http: httpx.Client, task_id: str) -> int:
|
| 160 |
+
try:
|
| 161 |
+
tasks = http.get("/tasks").json().get("tasks", [])
|
| 162 |
+
for t in tasks:
|
| 163 |
+
if t["id"] == task_id:
|
| 164 |
+
return t["max_steps"]
|
| 165 |
+
except Exception:
|
| 166 |
+
pass
|
| 167 |
+
return MAX_STEPS_FALLBACK
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def run_task(task_id: str, client: OpenAI) -> Dict[str, Any]:
|
| 171 |
+
http = httpx.Client(base_url=ENV_BASE_URL, timeout=30.0)
|
| 172 |
+
max_steps = get_task_max_steps(http, task_id)
|
| 173 |
+
|
| 174 |
+
log_start(task_id, BENCHMARK, MODEL_NAME)
|
| 175 |
+
|
| 176 |
+
resp = http.post("/reset", params={"task_id": task_id})
|
| 177 |
+
resp.raise_for_status()
|
| 178 |
+
obs = resp.json()
|
| 179 |
+
|
| 180 |
+
done = False
|
| 181 |
+
steps = 0
|
| 182 |
+
rewards: List[float] = []
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
while not done and steps < max_steps:
|
| 186 |
+
action = llm_action(obs, task_id, client)
|
| 187 |
+
|
| 188 |
+
resp = http.post("/step", json=action)
|
| 189 |
+
resp.raise_for_status()
|
| 190 |
+
result = resp.json()
|
| 191 |
+
|
| 192 |
+
obs = result["observation"]
|
| 193 |
+
reward = result["reward"]["value"]
|
| 194 |
+
done = result["done"]
|
| 195 |
+
error = result.get("info", {}).get("error") or None
|
| 196 |
+
steps += 1
|
| 197 |
+
rewards.append(reward)
|
| 198 |
+
|
| 199 |
+
log_step(steps, action, reward, done, error)
|
| 200 |
+
|
| 201 |
+
grader = http.get("/grader").json()
|
| 202 |
+
score = grader.get("score", 0.0)
|
| 203 |
+
log_end(success=score > 0.0, steps=steps, rewards=rewards)
|
| 204 |
+
|
| 205 |
+
except Exception as exc:
|
| 206 |
+
print(f"Episode error ({task_id}): {exc}", file=sys.stderr)
|
| 207 |
+
log_end(success=False, steps=steps, rewards=rewards)
|
| 208 |
+
score = 0.0
|
| 209 |
+
|
| 210 |
+
return {
|
| 211 |
+
"task_id": task_id,
|
| 212 |
+
"score": score,
|
| 213 |
+
"steps": steps,
|
| 214 |
+
"total_reward": round(sum(rewards), 4),
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def main() -> None:
|
| 219 |
+
if not API_KEY:
|
| 220 |
+
print("Error: OPENAI_API_KEY is not set.", file=sys.stderr)
|
| 221 |
+
sys.exit(1)
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
|
| 225 |
+
except Exception as exc:
|
| 226 |
+
print(f"Error: could not initialise OpenAI client: {exc}", file=sys.stderr)
|
| 227 |
+
sys.exit(1)
|
| 228 |
+
|
| 229 |
+
print(f"Agent : {MODEL_NAME}", file=sys.stderr)
|
| 230 |
+
print(f"API base : {API_BASE_URL}", file=sys.stderr)
|
| 231 |
+
print(f"Env URL : {ENV_BASE_URL}", file=sys.stderr)
|
| 232 |
+
|
| 233 |
+
results: List[Dict[str, Any]] = []
|
| 234 |
+
for task_id in TASKS:
|
| 235 |
+
print(f"Running {task_id} ...", file=sys.stderr)
|
| 236 |
+
try:
|
| 237 |
+
result = run_task(task_id, client)
|
| 238 |
+
results.append(result)
|
| 239 |
+
print(
|
| 240 |
+
f" score={result['score']} steps={result['steps']}", file=sys.stderr
|
| 241 |
+
)
|
| 242 |
+
except Exception as exc:
|
| 243 |
+
print(f" ERROR: {exc}", file=sys.stderr)
|
| 244 |
+
results.append(
|
| 245 |
+
{"task_id": task_id, "score": 0.0, "steps": 0, "error": str(exc)}
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
avg = round(sum(r.get("score", 0.0) for r in results) / len(results), 3)
|
| 249 |
+
summary = {"agent": MODEL_NAME, "results": results, "average_score": avg}
|
| 250 |
+
print(json.dumps(summary, indent=2), file=sys.stderr)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
main()
|
logger.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def log_start(task_id: str, benchmark: str, model_name: str) -> None:
|
| 5 |
+
print(f"[START] task={task_id} env={benchmark} model={model_name}", flush=True)
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def log_step(
|
| 9 |
+
step: int, action: Dict[str, Any], reward: float, done: bool, error: Optional[str]
|
| 10 |
+
) -> None:
|
| 11 |
+
action_str = action_to_str(action)
|
| 12 |
+
done_str = "true" if done else "false"
|
| 13 |
+
error_str = error if error else "null"
|
| 14 |
+
print(
|
| 15 |
+
f"[STEP] step={step} action={action_str} reward={reward:.2f} done={done_str} error={error_str}",
|
| 16 |
+
flush=True,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def log_end(success: bool, steps: int, rewards: List[float]) -> None:
|
| 21 |
+
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
|
| 22 |
+
success_str = "true" if success else "false"
|
| 23 |
+
print(
|
| 24 |
+
f"[END] success={success_str} steps={steps} rewards={rewards_str}", flush=True
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def action_to_str(action: Dict[str, Any]) -> str:
|
| 29 |
+
parts = [action.get("action_type", "skip")]
|
| 30 |
+
if action.get("email_id"):
|
| 31 |
+
parts.append(action["email_id"])
|
| 32 |
+
if action.get("category"):
|
| 33 |
+
parts.append(action["category"])
|
| 34 |
+
if action.get("urgency"):
|
| 35 |
+
parts.append(action["urgency"])
|
| 36 |
+
return ":".join(parts)
|