thisisgini commited on
Commit
587c962
·
verified ·
1 Parent(s): 10a96d6

Update inference.py

Browse files
Files changed (1) hide show
  1. inference.py +80 -45
inference.py CHANGED
@@ -1,61 +1,96 @@
 
1
  import os
2
  import json
3
- import asyncio
 
4
  from openai import OpenAI
 
5
 
6
- # 1. MANDATORY START TAG
7
- # Use os.getenv only for the model name to allow for validator flexibility
 
 
8
  MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
9
- print(f"[START] task=ecommerce_lifecycle_v1 env=scaler_ecommerce_bot model={MODEL_NAME}", flush=True)
10
 
11
- def run_inference(data):
12
- """Bridge for the FastAPI server"""
13
- return asyncio.run(execute_agent_logic(data))
 
 
 
14
 
15
- async def execute_agent_logic(data):
16
- # 2. STRICT ENVIRONMENT VARIABLE USE
17
- # Do not use fallbacks like "https://router.huggingface.co/v1" here.
18
- # The validator MUST inject these for the proxy check to work.
19
- try:
20
- api_base = os.environ["API_BASE_URL"]
21
- api_key = os.environ["API_KEY"]
22
- except KeyError as e:
23
- # This will show up in your HF Container logs if the validator fails to inject
24
- print(f"[DEBUG] Missing infrastructure variable: {e}", flush=True)
25
- # Fallback to HF_TOKEN only as a last resort for local testing
26
- api_base = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
27
- api_key = os.getenv("API_KEY") or os.getenv("HF_TOKEN")
28
-
29
- # 3. INITIALIZE OPENAI CLIENT
30
- client = OpenAI(
31
- base_url=api_base,
32
- api_key=api_key
33
- )
34
-
35
- query = data.get("query", "No query provided")
36
-
37
  try:
38
- # 4. THE PROXY CALL
39
- # Using the client this way ensures traffic hits the LiteLLM proxy
40
  completion = client.chat.completions.create(
41
  model=MODEL_NAME,
42
  messages=[
43
- {"role": "system", "content": "You are an ecommerce agent. Respond in JSON: {'reply': str, 'action': str}"},
44
- {"role": "user", "content": query}
45
  ],
46
- response_format={ "type": "json_object" }
 
47
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- decision = json.loads(completion.choices[0].message.content)
50
- action = decision.get("action", "none")
51
-
52
- # 5. EMIT MANDATORY LOGS FOR SCORING
53
- print(f"[STEP] step=1 action={action} reward=1.00 done=true error=null", flush=True)
54
- print(f"[END] success=true steps=1 score=1.00 rewards=1.00", flush=True)
55
 
56
- return decision
 
 
57
 
58
- except Exception as e:
59
- print(f"[STEP] step=1 action=error reward=0.00 done=true error={str(e)}", flush=True)
60
- print(f"[END] success=false steps=1 score=0.00 rewards=0.00", flush=True)
61
- return {"reply": "Connection failed", "status": "error"}
 
1
+ import asyncio
2
  import os
3
  import json
4
+ import textwrap
5
+ from typing import List, Optional
6
  from openai import OpenAI
7
+ from my_env_v4 import MyEnvV4Action, MyEnvV4Env
8
 
9
+ # 1. INFRASTRUCTURE CONFIGURATION
10
+ # Prioritize injected variables to pass Phase 2 Deep Validation
11
+ API_KEY = os.getenv("API_KEY") or os.getenv("HF_TOKEN")
12
+ API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
13
  MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
14
+ IMAGE_NAME = os.getenv("IMAGE_NAME")
15
 
16
+ # Task Metadata
17
+ TASK_NAME = "ecommerce_lifecycle_v1"
18
+ BENCHMARK = "scaler_ecommerce_bot"
19
+ MAX_STEPS = 1
20
+ TEMPERATURE = 0.7
21
+ MAX_TOKENS = 150
22
 
23
+ # 2. LOGGING HELPERS (Mandatory for Scaler parsing)
24
+ def log_start(task: str, env: str, model: str) -> None:
25
+ print(f"[START] task={task} env={env} model={model}", flush=True)
26
+
27
+ def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
28
+ error_val = error if error else "null"
29
+ done_val = str(done).lower()
30
+ print(f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}", flush=True)
31
+
32
+ def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
33
+ rewards_str = ",".join(f"{r:.2f}" for r in rewards)
34
+ print(f"[END] success={str(success).lower()} steps={steps} score={score:.2f} rewards={rewards_str}", flush=True)
35
+
36
+ # 3. LLM INTERACTION LOGIC
37
+ def get_model_message(client: OpenAI, history: List[str]) -> str:
 
 
 
 
 
 
 
38
  try:
39
+ # Mandatory Proxy Call
 
40
  completion = client.chat.completions.create(
41
  model=MODEL_NAME,
42
  messages=[
43
+ {"role": "system", "content": "You are an e-commerce assistant. Respond with the action to take."},
44
+ {"role": "user", "content": "Handle this request: refund for order 101."}
45
  ],
46
+ temperature=TEMPERATURE,
47
+ max_tokens=MAX_TOKENS,
48
  )
49
+ return (completion.choices[0].message.content or "").strip()
50
+ except Exception as exc:
51
+ print(f"[DEBUG] Model request failed: {exc}", flush=True)
52
+ return "escalate_to_human"
53
+
54
+ # 4. AGENT LOOP
55
+ async def main() -> None:
56
+ # Initialize client using injected infrastructure variables
57
+ client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
58
+ env = await MyEnvV4Env.from_docker_image(IMAGE_NAME)
59
+
60
+ history: List[str] = []
61
+ rewards: List[float] = []
62
+ steps_taken = 0
63
+ score = 0.0
64
+ success = False
65
+
66
+ log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)
67
+
68
+ try:
69
+ result = await env.reset() # Handled by server /reset
70
+
71
+ for step in range(1, MAX_STEPS + 1):
72
+ if result.done:
73
+ break
74
+
75
+ message = get_model_message(client, history)
76
+ result = await env.step(MyEnvV4Action(message=message))
77
+
78
+ reward = result.reward or 0.0
79
+ log_step(step=step, action=message, reward=reward, done=result.done, error=None)
80
+
81
+ rewards.append(reward)
82
+ steps_taken = step
83
+ history.append(f"Step {step}: {message} -> {reward}")
84
+
85
+ if result.done:
86
+ break
87
 
88
+ score = sum(rewards) / len(rewards) if rewards else 0.0
89
+ success = score >= 1.0
 
 
 
 
90
 
91
+ finally:
92
+ await env.close()
93
+ log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
94
 
95
+ if __name__ == "__main__":
96
+ asyncio.run(main())