Spaces:
No application file
No application file
File size: 8,799 Bytes
87278d0 448e111 c121634 55c9d42 956f8c8 55c9d42 448e111 c121634 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 943d84a 87278d0 943d84a 87278d0 943d84a 87278d0 943d84a 87278d0 943d84a 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 87278d0 448e111 943d84a 448e111 55c9d42 448e111 956f8c8 448e111 55c9d42 448e111 55c9d42 3392045 448e111 956f8c8 448e111 943d84a 55c9d42 448e111 55c9d42 448e111 55c9d42 448e111 956f8c8 448e111 55c9d42 448e111 55c9d42 956f8c8 05b75ac 55c9d42 05b75ac 3392045 55c9d42 05b75ac 55c9d42 448e111 3392045 448e111 | 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 | #!/usr/bin/env python3
"""
SupportEnv Inference Script - OpenEnv Competition Submission
This script runs the baseline agent on all required tasks (easy, medium, hard).
It uses the OpenAI client with environment variables for configuration.
REQUIRED ENVIRONMENT VARIABLES:
API_BASE_URL: The API endpoint for the LLM
MODEL_NAME: The model identifier to use for inference
HF_TOKEN: Your Hugging Face / API key
OUTPUT FORMAT (STRICT):
[START] task=<task_id> env=<env_url> model=<model_name>
[STEP] step=<n> action=<action_type> reward=<r> done=<bool> error=<error_or_null>
[END] success=<bool> steps=<n> score=<s> rewards=[r1,r2,...]
"""
import os
import re
import json
import textwrap
from typing import List, Optional, Dict, Any
from openai import OpenAI
from client import SupportEnv
from models import SupportAction, SupportObservation
# Environment variables as per OpenEnv spec
API_BASE_URL = os.getenv("API_BASE_URL", "https://api-inference.huggingface.co/v1/")
API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "your-hf-token")
MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4o")
MAX_STEPS = 10
TEMPERATURE = 0.0
MAX_TOKENS = 500
# Fallback action for error cases
FALLBACK_ACTION = SupportAction(
action_type="respond",
content="I apologize, but I am unable to process your request at this time."
)
# System prompt for the LLM agent
SYSTEM_PROMPT = textwrap.dedent(
"""
You are an AI customer support agent controlling a support environment.
Your goal is to resolve customer tickets efficiently and accurately.
Reply with exactly one action in JSON format.
The action MUST follow this schema:
{
"action_type": "classify" | "respond" | "escalate" | "request_info" | "resolve" | "lookup_kb",
"content": "the content for the action",
"confidence": float (between 0.0 and 1.0)
}
Action Types:
- classify: Categories are 'billing', 'technical', 'account', or 'general'.
- respond: Send a message to the customer.
- request_info: Ask the customer for more details.
- lookup_kb: Search internal knowledge-base for relevant articles.
- escalate: Escalate to a human agent.
- resolve: Close the ticket when the issue is fully addressed.
Wait for the environment to respond after each action.
Do not include explanations or any other text.
"""
).strip()
# =============================================================================
# LOGGING FUNCTIONS (STRICT FORMAT - REQUIRED BY COMPETITION)
# =============================================================================
def log_start(task: str, env: str, model: str) -> None:
"""Log start of task execution - REQUIRED FORMAT: [START] ..."""
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) -> None:
"""Log step execution - REQUIRED FORMAT: [STEP] ..."""
error_val = error if error else "null"
done_val = str(done).lower()
print(f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}", flush=True)
def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
"""Log end of task execution - REQUIRED FORMAT: [END] ..."""
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)
# =============================================================================
# PROMPT BUILDING
# =============================================================================
def build_user_prompt(step: int, obs: SupportObservation, history: List[str]) -> str:
"""Build the user prompt for the LLM."""
history_str = "\n".join(history[-5:]) if history else "None"
prompt = textwrap.dedent(
f"""
Step: {step}
Ticket Subject: {obs.ticket_subject}
Customer: {obs.customer_name}
Customer Sentiment: {obs.customer_sentiment:.2f}
Ticket Text:
{obs.ticket_text}
Current Status:
- Classified: {obs.is_classified}
- Category: {obs.current_classification or 'Not classified yet'}
- Steps Remaining: {obs.steps_remaining}
Interaction History:
{history_str}
Reply with exactly one action JSON.
"""
).strip()
return prompt
# =============================================================================
# ACTION PARSING
# =============================================================================
def parse_model_action(response_text: str) -> SupportAction:
"""Parse LLM response into a SupportAction."""
try:
match = re.search(r'\{.*\}', response_text, re.DOTALL)
if match:
json_str = match.group(0)
data = json.loads(json_str)
return SupportAction(
action_type=data.get("action_type", "respond"),
content=data.get("content", ""),
confidence=data.get("confidence", 1.0)
)
return FALLBACK_ACTION
except Exception:
return FALLBACK_ACTION
def main() -> None:
# Use OpenAI client as mandated
client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
# Environment URL (HuggingFace Space or Local)
env_url = os.getenv("SUPPORT_ENV_URL", "http://localhost:7860")
env = SupportEnv(base_url=env_url)
# Run episodes on all 3 difficulties as mandated
for difficulty in ["easy", "medium", "hard"]:
task_name = f"support_triage_{difficulty}"
log_start(task=task_name, env="SupportEnv", model=MODEL_NAME)
history: List[str] = []
rewards: List[float] = []
steps_taken = 0
success = False
final_score = 0.01
try:
with env.sync() as conn:
result = conn.reset(difficulty=difficulty, seed=42)
observation = result.observation
for step_idx in range(1, MAX_STEPS + 1):
steps_taken = step_idx
if result.done:
break
user_prompt = build_user_prompt(step_idx, observation, history)
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_prompt}
]
try:
completion = client.chat.completions.create(
model=MODEL_NAME,
messages=messages,
temperature=TEMPERATURE,
max_tokens=MAX_TOKENS,
)
response_text = completion.choices[0].message.content or ""
action = parse_model_action(response_text)
except Exception as e:
action = FALLBACK_ACTION
result = conn.step(action)
observation = result.observation
rewards.append(float(result.reward or 0.0))
history.append(f"Step {step_idx}: {action.action_type}({action.content[:30]})")
log_step(
step=step_idx,
action=action.action_type,
reward=float(result.reward or 0.0),
done=bool(result.done),
error=None
)
if result.done:
break
# Fetch final grade from environment
import requests
try:
grader_url = f"{env_url}/grader"
session_id = getattr(conn, 'session_id', getattr(result, 'session_id', None))
grade_resp = requests.post(grader_url, json={"session_id": session_id}, timeout=30)
if grade_resp.status_code == 200:
grade_data = grade_resp.json()
final_score = float(grade_data.get('score', 0.01))
success = bool(grade_data.get('passed', False))
except Exception:
pass
log_end(success=success, steps=steps_taken, score=final_score, rewards=rewards)
except Exception as e:
log_end(success=False, steps=steps_taken, score=0.01, rewards=rewards)
if __name__ == "__main__":
main()
|