File size: 18,626 Bytes
4719066
2305b9f
 
4719066
 
 
2305b9f
 
4719066
 
 
2305b9f
 
 
4719066
 
 
 
 
 
 
2305b9f
 
4719066
 
ae350b5
 
4719066
 
 
 
 
 
 
2305b9f
4719066
 
 
 
2305b9f
4719066
2305b9f
 
 
4719066
2305b9f
 
 
 
ef4ebed
 
 
 
 
2305b9f
 
 
 
 
 
 
 
 
 
 
 
 
a5d93ec
 
2305b9f
 
 
 
 
 
 
ef4ebed
 
03d30a6
 
 
 
 
ef4ebed
 
03d30a6
ef4ebed
 
 
03d30a6
 
 
 
ef4ebed
03d30a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4719066
 
2305b9f
 
 
 
 
4719066
 
 
 
 
2305b9f
 
4719066
 
 
 
 
2305b9f
 
4719066
 
 
 
 
2305b9f
 
4719066
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2305b9f
4719066
 
 
 
2305b9f
 
 
 
 
 
 
ef4ebed
 
 
 
2305b9f
 
 
 
4719066
2305b9f
 
4719066
ef4ebed
4719066
2305b9f
 
 
 
 
 
 
 
 
4719066
 
 
2305b9f
 
 
 
 
 
4719066
 
2305b9f
4719066
 
2305b9f
4719066
2305b9f
4719066
 
2305b9f
4719066
 
2305b9f
4719066
 
 
 
 
 
a35bcd0
2305b9f
 
a5d93ec
a35bcd0
 
 
 
 
 
 
 
 
2305b9f
4719066
2305b9f
4719066
a35bcd0
4719066
2305b9f
4719066
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2305b9f
4719066
 
 
 
 
2305b9f
4719066
 
 
 
 
 
 
2305b9f
 
 
 
 
4719066
2305b9f
4719066
 
 
 
 
 
 
 
 
 
 
 
 
2305b9f
4719066
 
2305b9f
4719066
 
 
2305b9f
4719066
2305b9f
 
4719066
 
 
 
 
 
2305b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a35bcd0
 
 
 
 
 
 
 
 
 
2305b9f
 
 
 
a35bcd0
2305b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4719066
 
 
2305b9f
4719066
 
 
 
 
 
 
 
 
 
 
2305b9f
 
4719066
2305b9f
4719066
2305b9f
 
4719066
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2305b9f
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
"""
Baseline inference script for the OrgOS OpenEnv environment.
Runs all three workflows (A / B / C) and reports scores.

Required environment variables:
    API_BASE_URL   β€” LLM API endpoint (OpenAI-compatible)
    MODEL_NAME     β€” model identifier (default: gpt-4o-mini)
    HF_TOKEN       β€” API key for the LLM endpoint
    ENV_URL        β€” environment server URL (default: http://localhost:8000)

STDOUT FORMAT (OpenEnv spec):
    [START] task=<workflow_name> env=orgos-openenv model=<model>
    [STEP]  step=<n> action=<json> reward=<0.00> done=<true|false> error=<msg|null>
    [END]   task=<workflow_name> score=<0.00> steps=<n>
"""

import json
import os
import re
import sys
import time
from typing import AsyncGenerator, Dict, List, Optional

import httpx
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
# ------------------------------------------------------------------
# Config
# ------------------------------------------------------------------

API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
MODEL_NAME   = os.environ.get("MODEL_NAME",   "gpt-4o-mini")
HF_TOKEN     = os.environ.get("HF_TOKEN",     "")
ENV_URL      = os.environ.get("ENV_URL",       "http://localhost:8000")

if not HF_TOKEN:
    print("[WARNING] HF_TOKEN is not set β€” LLM calls may fail.", file=sys.stderr)

llm_client = OpenAI(api_key=HF_TOKEN or "sk-placeholder", base_url=API_BASE_URL)

# ------------------------------------------------------------------
# System prompt
# ------------------------------------------------------------------

SYSTEM_PROMPT = """\
You are OrgOS Agent β€” an enterprise workflow automation agent.
You operate across four SaaS applications: Jira, Zendesk, Salesforce, and Workday.

Each turn you receive a JSON observation with:
  - workflow_goal    : the task you must complete
  - pending_steps    : remaining steps in the workflow
  - app_states       : current state of each app
  - schema_hints     : field renames in effect this episode (e.g. {"jira.priority": "severity"})
  - active_rules     : current SLA / approval thresholds
  - message          : feedback from the last action
  - current_score    : your cumulative score (0.001–0.999)

Respond ONLY with a valid JSON object β€” no markdown, no explanation.

Action format:
  {"app": "<app>", "operation": "<op>", "args": {...}}

Available apps and key operations:
  jira:       get_issue, create_issue, update_status, set_priority, assign_owner,
              add_label, link_zendesk_ticket, close_issue, list_issues
  zendesk:    get_ticket, acknowledge_ticket, set_urgency, assign_agent,
              escalate_to_jira, resolve_ticket, add_note, list_tickets,
              create_agent_profile
  salesforce: get_account, list_accounts, update_deal_stage, flag_churn_risk,
              assign_account_owner, log_interaction, get_opportunity
  workday:    get_employee, list_employees, provision_access, log_sla_event,
              request_budget_approval, create_onboarding_task, complete_task

CRITICAL RULES:
1. Read schema_hints FIRST β€” if "jira.priority" β†’ "severity", use "severity" not "priority" in args.
2. Complete ALL pending_steps in order.
3. Do not repeat a successful action.
4. When an operation creates a new resource (e.g. create_issue returns issue_id "JIRA-051"),
   use THAT returned ID for all subsequent operations on that resource β€” not a pre-existing ID.
5. If an operation fails, read the message carefully and adapt.
6. Use list_* operations to discover record IDs when needed β€” never assume an ID.
7. Stop when pending_steps is empty or done=true.

Example actions:
  # Workflow A (bug fix) β€” discover then chain ticket_id and returned issue_id:
  {"app": "zendesk", "operation": "list_tickets", "args": {"state": "new"}}
  {"app": "zendesk", "operation": "acknowledge_ticket", "args": {"ticket_number": "<ticket_number from list_tickets>"}}
  {"app": "jira", "operation": "create_issue", "args": {"title": "Bug fix for <customer>", "linked_zendesk": "<ticket_number>"}}
  # β†’ create_issue returns {"issue_id": "JIRA-051", ...} β€” use JIRA-051 for assign_owner below
  {"app": "jira", "operation": "assign_owner", "args": {"issue_id": "<issue_id from create_issue>", "assignee": "<engineer>"}}

  # Workflow B (onboarding) β€” find the pending employee, then thread employee_id + territory:
  {"app": "workday", "operation": "list_employees", "args": {"status": "pending"}}
  # β†’ returns exactly one record. Capture employee_id (e.g. "EMP-NEW-001") AND territory (e.g. "west").
  {"app": "workday", "operation": "create_onboarding_task", "args": {"employee_id": "<employee_id from list>"}}
  {"app": "workday", "operation": "provision_access", "args": {"employee_id": "<employee_id from list>", "app_name": "jira"}}
  # SF: assign that employee as owner of an account in THEIR territory:
  {"app": "salesforce", "operation": "list_accounts", "args": {"territory": "<territory from list_employees>"}}
  {"app": "salesforce", "operation": "assign_account_owner", "args": {"account_id": "<account_id from list>", "owner": "<employee_id from list>"}}
  # Jira: assign an open issue to the new hire's employee_id:
  {"app": "jira", "operation": "list_issues", "args": {"status": "open"}}
  {"app": "jira", "operation": "assign_owner", "args": {"issue_id": "<issue_id from list>", "assignee": "<employee_id from list_employees>"}}

  # Workflow C (churn) β€” discover the at-risk account, then scope all queries to it:
  {"app": "salesforce", "operation": "list_accounts", "args": {"health": "red"}}
  {"app": "salesforce", "operation": "flag_churn_risk", "args": {"account_id": "<account_id from list>"}}
  {"app": "zendesk", "operation": "get_ticket", "args": {"customer_id": "<account_id from list>"}}
  {"app": "jira", "operation": "list_issues", "args": {"customer_id": "<account_id from list>"}}
  {"app": "salesforce", "operation": "assign_account_owner", "args": {"account_id": "<account_id from list>", "owner": "<engineer>"}}
"""

WORKFLOW_NAMES = {
    "A": "workflow-a-bug-fix",
    "B": "workflow-b-onboarding",
    "C": "workflow-c-churn-alert",
}

# ------------------------------------------------------------------
# OpenEnv stdout logging helpers
# ------------------------------------------------------------------

def log_start(task: str, env_name: str, model: str) -> None:
    print(f"[START] task={task} env={env_name} 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:.4f} "
        f"done={str(done).lower()} error={error_val}",
        flush=True,
    )


def log_end(task_name: str, score: float, steps: int) -> None:
    safe_score = max(0.001, min(0.999, float(score)))
    print(f"[END] task={task_name} score={safe_score:.4f} steps={steps}", flush=True)


# ------------------------------------------------------------------
# HTTP helpers
# ------------------------------------------------------------------

def api_post(path: str, payload: dict = None) -> dict:
    url  = ENV_URL.rstrip("/") + path
    resp = httpx.post(url, json=payload or {}, timeout=30)
    resp.raise_for_status()
    return resp.json()


def api_get(path: str) -> dict:
    url  = ENV_URL.rstrip("/") + path
    resp = httpx.get(url, timeout=10)
    resp.raise_for_status()
    return resp.json()


# ------------------------------------------------------------------
# Observation formatter
# ------------------------------------------------------------------

def obs_to_text(obs: dict) -> str:
    lines = [
        f"current_score:  {obs['current_score']}",
        f"step_count:     {obs['step_count']}",
        f"workflow_id:    {obs['workflow_id']}",
        "",
        "=== WORKFLOW GOAL ===",
        obs["workflow_goal"],
        "",
        "=== PENDING STEPS ===",
        "\n".join(f"  - {s}" for s in obs["pending_steps"]) or "  (all steps complete!)",
        "",
        "=== SCHEMA HINTS (use these field names) ===",
        json.dumps(obs["schema_hints"], indent=2) if obs["schema_hints"] else "  (no drift β€” use canonical names)",
        "",
        "=== ACTIVE RULES ===",
        json.dumps(obs["active_rules"], indent=2),
        "",
        "=== LAST MESSAGE ===",
        obs["message"],
        "",
        "=== APP STATES ===",
    ]
    for app_name, view in obs.get("app_states", {}).items():
        lines.append(f"  [{app_name.upper()}]")
        lines.append(f"  {view}")
        lines.append("")
    if obs.get("rule_violations"):
        lines.append("=== RULE VIOLATIONS (fix these!) ===")
        for v in obs["rule_violations"]:
            lines.append(f"  ⚠  {v}")
        lines.append("")
    return "\n".join(lines)


# ------------------------------------------------------------------
# Single-workflow inference loop
# ------------------------------------------------------------------

def run_workflow(workflow_id: str) -> float:
    task_name = WORKFLOW_NAMES.get(workflow_id, f"workflow-{workflow_id.lower()}")

    print(f"\n{'='*60}", file=sys.stderr)
    print(f"  Running Workflow {workflow_id}", file=sys.stderr)
    print(f"{'='*60}", file=sys.stderr)

    result  = api_post("/reset", {"workflow_id": workflow_id})
    obs     = result["observation"]
    history: List[dict] = []
    steps_taken = 0

    log_start(task=task_name, env_name="orgos-openenv", model=MODEL_NAME)

    try:
        for step_num in range(1, 60):
            if obs["done"]:
                break

            obs_text = obs_to_text(obs)
            history.append({"role": "user", "content": obs_text})

            # Trim history β€” keep last 20, ensure it starts with a user message
            if len(history) > 20:
                history = history[-20:]
            if history and history[0]["role"] != "user":
                history = history[1:]

            # Inject system prompt into first user message (Gemma/models without system role)
            messages_for_llm = list(history)
            if messages_for_llm:
                messages_for_llm[0] = {
                    "role": "user",
                    "content": SYSTEM_PROMPT + "\n\n---\n\n" + messages_for_llm[0]["content"],
                }

            try:
                response = llm_client.chat.completions.create(
                    model       = MODEL_NAME,
                    messages    = messages_for_llm,
                    temperature = 0.0,
                    max_tokens  = 300,
                )
                action_str = response.choices[0].message.content.strip()
            except Exception as exc:
                print(f"  Step {step_num}: LLM call failed: {exc}", file=sys.stderr)
                log_step(step_num, "null", 0.0, True, str(exc))
                break

            history.append({"role": "assistant", "content": action_str})

            # Parse action JSON
            action = None
            try:
                action = json.loads(action_str)
            except json.JSONDecodeError:
                m = re.search(r"\{.*\}", action_str, re.DOTALL)
                if m:
                    try:
                        action = json.loads(m.group())
                    except Exception:
                        pass

            if action is None:
                print(f"  Step {step_num}: Could not parse action JSON.", file=sys.stderr)
                log_step(step_num, action_str, -0.05, False, "json_parse_error")
                break

            action_label = json.dumps(action, separators=(",", ":"))
            print(
                f"  Step {step_num:2d} | score={obs['current_score']:.4f} | {action_label}",
                file=sys.stderr,
            )

            result      = api_post("/step", action)
            obs         = result["observation"]
            step_reward = result["reward"]
            done        = result["done"]
            error_msg   = (
                obs["message"]
                if obs.get("rule_violations") or step_reward < 0
                else None
            )

            print(f"           β†’ {obs['message']}", file=sys.stderr)

            steps_taken = step_num
            log_step(
                step   = step_num,
                action = action_label,
                reward = step_reward,
                done   = done,
                error  = error_msg,
            )

            if done:
                break

            time.sleep(0.2)

    finally:
        final = obs.get("current_score", 0.001) if isinstance(obs, dict) else 0.001
        log_end(task_name=task_name, score=final, steps=steps_taken)

    final_score = obs["current_score"]
    wf_done     = not obs.get("pending_steps")
    print(
        f"\n  Workflow {workflow_id} final score: {final_score:.4f}  "
        f"steps: {obs['step_count']}  completed: {wf_done}",
        file=sys.stderr,
    )
    return final_score


# ------------------------------------------------------------------
# Async generator for SSE streaming from the UI
# ------------------------------------------------------------------

async def run_workflow_generator(
    workflow_id: str = "A",
    env_ref=None,
) -> AsyncGenerator[dict, None]:
    """
    Async generator that runs one inference episode and yields
    SSE-friendly event dicts for the dashboard UI.

    Each yielded dict has a "type" key:
      "reset"  β€” episode started
      "step"   β€” one action taken
      "done"   β€” episode ended
      "error"  β€” something went wrong
    """
    import asyncio

    if env_ref is None:
        # Fall back to HTTP if no direct env reference
        result = api_post("/reset", {"workflow_id": workflow_id})
    else:
        from models import OrgOSAction as _Action
        obs_obj = env_ref.reset(workflow_id=workflow_id)
        result  = {"observation": obs_obj.model_dump(), "reward": obs_obj.reward, "done": False}

    obs     = result["observation"]
    history: List[dict] = []

    yield {"type": "reset", "observation": obs, "workflow_id": workflow_id}
    await asyncio.sleep(0)

    for step_num in range(1, 60):
        if obs["done"]:
            break

        obs_text = obs_to_text(obs)
        history.append({"role": "user", "content": obs_text})
        if len(history) > 20:
            history = history[-20:]
        if history and history[0]["role"] != "user":
            history = history[1:]

        # Inject system prompt into first user message (Gemma/models without system role)
        messages_for_llm = list(history)
        if messages_for_llm:
            messages_for_llm[0] = {
                "role": "user",
                "content": SYSTEM_PROMPT + "\n\n---\n\n" + messages_for_llm[0]["content"],
            }

        try:
            response = llm_client.chat.completions.create(
                model       = MODEL_NAME,
                messages    = messages_for_llm,
                temperature = 0.0,
                max_tokens  = 300,
            )
            action_str = response.choices[0].message.content.strip()
        except Exception as exc:
            yield {"type": "error", "step": step_num, "message": str(exc)}
            break

        history.append({"role": "assistant", "content": action_str})

        action = None
        try:
            action = json.loads(action_str)
        except json.JSONDecodeError:
            m = re.search(r"\{.*\}", action_str, re.DOTALL)
            if m:
                try:
                    action = json.loads(m.group())
                except Exception:
                    pass

        if action is None:
            yield {"type": "error", "step": step_num, "message": "JSON parse error"}
            break

        if env_ref is None:
            result = api_post("/step", action)
        else:
            from models import OrgOSAction as _Action
            try:
                act     = _Action(**action)
                obs_obj = env_ref.step(act)
                result  = {
                    "observation": obs_obj.model_dump(),
                    "reward":      obs_obj.reward,
                    "done":        obs_obj.done,
                }
            except Exception as exc:
                yield {"type": "error", "step": step_num, "message": str(exc)}
                break

        obs         = result["observation"]
        step_reward = result["reward"]
        done        = result["done"]

        yield {
            "type":        "step",
            "step":        step_num,
            "action":      action,
            "observation": obs,
            "reward":      step_reward,
            "done":        done,
        }
        await asyncio.sleep(0)

        if done:
            break

    yield {
        "type":        "done",
        "final_score": obs.get("current_score", 0.001),
        "steps":       obs.get("step_count", step_num),
        "completed":   not obs.get("pending_steps"),
    }


# ------------------------------------------------------------------
# Main β€” run all three workflows sequentially
# ------------------------------------------------------------------

def main():
    print("OrgOS OpenEnv β€” Baseline Inference", file=sys.stderr)
    print(f"Model : {MODEL_NAME}", file=sys.stderr)
    print(f"Env   : {ENV_URL}", file=sys.stderr)

    try:
        health = api_get("/health")
        assert health.get("status") in ("ok", "healthy"), f"Unexpected status: {health}"
        print("Health check: OK\n", file=sys.stderr)
    except Exception as exc:
        print(f"[ERROR] Environment not reachable at {ENV_URL}: {exc}", file=sys.stderr)
        sys.exit(1)

    scores: Dict[str, float] = {}
    for wf_id in ["A", "B", "C"]:
        try:
            scores[f"workflow_{wf_id}"] = run_workflow(wf_id)
        except Exception as exc:
            print(f"[ERROR] Workflow {wf_id} failed: {exc}", file=sys.stderr)
            scores[f"workflow_{wf_id}"] = 0.001

    print("\n" + "="*60, file=sys.stderr)
    print("  BASELINE RESULTS", file=sys.stderr)
    print("="*60, file=sys.stderr)
    for k, v in scores.items():
        print(f"  {k}: {v:.4f}", file=sys.stderr)
    avg = round(sum(scores.values()) / len(scores), 4)
    print(f"  average: {avg:.4f}", file=sys.stderr)
    print("="*60, file=sys.stderr)

    with open("baseline_scores.json", "w") as f:
        json.dump({"scores": scores, "average": avg}, f, indent=2)
    print("\nScores written to baseline_scores.json", file=sys.stderr)


if __name__ == "__main__":
    main()