svigneshskillsoft commited on
Commit
a917c60
·
1 Parent(s): 6f4a9e5

Fix GPT OSS reasoning token budget

Browse files
Files changed (1) hide show
  1. agent.py +158 -29
agent.py CHANGED
@@ -29,6 +29,9 @@ API_URL = "https://agents-course-unit4-scoring.hf.space"
29
  TEXT_MODEL = os.getenv("TEXT_MODEL", "openai/gpt-oss-120b:cerebras")
30
  VISION_MODEL = os.getenv("VISION_MODEL", "Qwen/Qwen2.5-VL-72B-Instruct")
31
  ASR_MODEL = os.getenv("ASR_MODEL", "openai/whisper-large-v3")
 
 
 
32
  HTTP_HEADERS = {
33
  "User-Agent": (
34
  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
@@ -50,7 +53,9 @@ TEXT_MODELS = _model_candidates(
50
  TEXT_MODEL,
51
  "TEXT_MODELS",
52
  [
53
- "openai/gpt-oss-120b:fireworks-ai",
 
 
54
  "openai/gpt-oss-120b",
55
  "openai/gpt-oss-20b",
56
  ],
@@ -61,6 +66,10 @@ VISION_MODELS = _model_candidates(
61
  ["Qwen/Qwen2.5-VL-72B-Instruct"],
62
  )
63
 
 
 
 
 
64
  SYSTEM_PROMPT = """
65
  You are solving one GAIA Level 1 benchmark question. Work carefully from the
66
  question and supplied evidence. The answer is checked using exact matching.
@@ -88,6 +97,41 @@ def clean_answer(value: Any) -> str:
88
  return answer
89
 
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  def reverse_hint(question: str) -> str:
92
  reversed_text = question[::-1]
93
  common = ("the", "this", "answer", "write", "word", "opposite")
@@ -384,32 +428,111 @@ class ResearchAgent:
384
  max_tokens: int = 600,
385
  vision: bool = False,
386
  ) -> str:
387
- """Try multiple provider routes instead of retrying the same HTTP 403."""
 
 
 
 
 
 
 
 
388
  candidates = [model] if model else (VISION_MODELS if vision else TEXT_MODELS)
389
  errors: list[str] = []
390
  for candidate in candidates:
391
- try:
392
- completion = self.openai.chat.completions.create(
393
- model=candidate,
394
- messages=messages,
395
- temperature=0,
396
- max_tokens=max_tokens,
397
- )
398
- content = completion.choices[0].message.content or ""
399
- if content.strip():
400
- return content
401
- errors.append(f"{candidate}: empty response")
402
- except Exception as error:
403
- status = getattr(error, "status_code", None)
404
- response = getattr(error, "response", None)
405
- if status is None and response is not None:
406
- status = getattr(response, "status_code", None)
407
- detail = str(error).replace("\n", " ")[:350]
408
- errors.append(f"{candidate}: HTTP {status or '?'} {detail}")
409
- # Authorization/provider denials are deterministic; immediately
410
- # fail over. Briefly back off only for transient server/rate errors.
411
- if status in {408, 409, 429, 500, 502, 503, 504}:
412
- time.sleep(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
 
414
  joined = " | ".join(errors)
415
  if any("HTTP 403" in item for item in errors):
@@ -421,15 +544,21 @@ class ResearchAgent:
421
  raise RuntimeError(f"All inference routes failed: {joined}")
422
 
423
  def preflight(self) -> str:
424
- """Fail once, before 20 tasks, with an actionable authorization error."""
425
  response = self.chat(
426
  [
427
  {"role": "system", "content": "Return only OK."},
428
  {"role": "user", "content": "Reply with OK."},
429
  ],
430
- max_tokens=8,
 
 
 
431
  )
432
- return clean_answer(response)
 
 
 
433
 
434
  def plan_queries(self, question: str) -> list[str]:
435
  prompt = (
@@ -444,7 +573,7 @@ class ResearchAgent:
444
  {"role": "system", "content": "You produce focused search queries as strict JSON."},
445
  {"role": "user", "content": prompt},
446
  ],
447
- max_tokens=350,
448
  )
449
  queries = parse_json_object(result).get("queries", [])
450
  queries = [str(item).strip() for item in queries if str(item).strip()]
@@ -552,7 +681,7 @@ class ResearchAgent:
552
  {"role": "system", "content": SYSTEM_PROMPT},
553
  {"role": "user", "content": user_prompt},
554
  ],
555
- max_tokens=500,
556
  )
557
  answer = clean_answer(raw)
558
  if not answer:
 
29
  TEXT_MODEL = os.getenv("TEXT_MODEL", "openai/gpt-oss-120b:cerebras")
30
  VISION_MODEL = os.getenv("VISION_MODEL", "Qwen/Qwen2.5-VL-72B-Instruct")
31
  ASR_MODEL = os.getenv("ASR_MODEL", "openai/whisper-large-v3")
32
+ GPT_OSS_REASONING_EFFORT = os.getenv("GPT_OSS_REASONING_EFFORT", "low")
33
+ GPT_OSS_MIN_OUTPUT_TOKENS = int(os.getenv("GPT_OSS_MIN_OUTPUT_TOKENS", "512"))
34
+ GPT_OSS_MAX_OUTPUT_TOKENS = int(os.getenv("GPT_OSS_MAX_OUTPUT_TOKENS", "4096"))
35
  HTTP_HEADERS = {
36
  "User-Agent": (
37
  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
 
53
  TEXT_MODEL,
54
  "TEXT_MODELS",
55
  [
56
+ # Keep the verified Cerebras route first. Let the HF router auto-select
57
+ # next, then use 20B as the low-cost fallback. Fireworks is intentionally
58
+ # not a default because this account's route returned HTTP 402.
59
  "openai/gpt-oss-120b",
60
  "openai/gpt-oss-20b",
61
  ],
 
66
  ["Qwen/Qwen2.5-VL-72B-Instruct"],
67
  )
68
 
69
+
70
+ class OutputBudgetExhausted(RuntimeError):
71
+ """The provider succeeded, but hidden reasoning consumed the output budget."""
72
+
73
  SYSTEM_PROMPT = """
74
  You are solving one GAIA Level 1 benchmark question. Work carefully from the
75
  question and supplied evidence. The answer is checked using exact matching.
 
97
  return answer
98
 
99
 
100
+ def message_text(message: Any) -> str:
101
+ """Extract only final assistant content, never hidden reasoning fields."""
102
+ content = getattr(message, "content", None)
103
+ if isinstance(content, str):
104
+ return content
105
+ if isinstance(content, list):
106
+ parts: list[str] = []
107
+ for item in content:
108
+ if isinstance(item, dict):
109
+ text = item.get("text") or item.get("content")
110
+ else:
111
+ text = getattr(item, "text", None) or getattr(item, "content", None)
112
+ if isinstance(text, str):
113
+ parts.append(text)
114
+ return "".join(parts)
115
+ return ""
116
+
117
+
118
+ def completion_diagnostics(completion: Any) -> tuple[str, str, int | None]:
119
+ """Return final content, finish reason, and provider-reported reasoning tokens."""
120
+ choice = completion.choices[0]
121
+ content = message_text(choice.message)
122
+ finish_reason = str(getattr(choice, "finish_reason", "") or "")
123
+ usage = getattr(completion, "usage", None)
124
+ if isinstance(usage, dict):
125
+ details = usage.get("completion_tokens_details")
126
+ else:
127
+ details = getattr(usage, "completion_tokens_details", None) if usage else None
128
+ if isinstance(details, dict):
129
+ reasoning_tokens = details.get("reasoning_tokens")
130
+ else:
131
+ reasoning_tokens = getattr(details, "reasoning_tokens", None) if details else None
132
+ return content, finish_reason, reasoning_tokens
133
+
134
+
135
  def reverse_hint(question: str) -> str:
136
  reversed_text = question[::-1]
137
  common = ("the", "this", "answer", "write", "word", "opposite")
 
428
  max_tokens: int = 600,
429
  vision: bool = False,
430
  ) -> str:
431
+ """Call inference with gpt-oss-aware reasoning and truncation handling.
432
+
433
+ gpt-oss counts hidden reasoning against ``max_tokens``. A successful
434
+ HTTP response can therefore contain ``content=None`` and
435
+ ``finish_reason='length'`` when the reasoning phase consumes the whole
436
+ budget. That is not a provider failure: retry the SAME provider with a
437
+ larger budget, and never fall through to a billable fallback merely for
438
+ this condition.
439
+ """
440
  candidates = [model] if model else (VISION_MODELS if vision else TEXT_MODELS)
441
  errors: list[str] = []
442
  for candidate in candidates:
443
+ is_gpt_oss = "gpt-oss" in candidate.lower()
444
+ budget = max(max_tokens, GPT_OSS_MIN_OUTPUT_TOKENS) if is_gpt_oss else max_tokens
445
+ budgets = [budget]
446
+ if is_gpt_oss and budget < GPT_OSS_MAX_OUTPUT_TOKENS:
447
+ expanded = min(max(budget * 4, 2048), GPT_OSS_MAX_OUTPUT_TOKENS)
448
+ if expanded > budget:
449
+ budgets.append(expanded)
450
+
451
+ partial_content = ""
452
+ provider_failed = False
453
+ for attempt_number, current_budget in enumerate(budgets, start=1):
454
+ try:
455
+ request: dict[str, Any] = {
456
+ "model": candidate,
457
+ "messages": messages,
458
+ "temperature": 0,
459
+ "max_tokens": current_budget,
460
+ }
461
+ if is_gpt_oss:
462
+ # The HF router forwards this OpenAI-compatible control to
463
+ # Cerebras. Low effort leaves more output budget for the
464
+ # exact-match final answer while retaining useful reasoning.
465
+ request["extra_body"] = {
466
+ "reasoning_effort": GPT_OSS_REASONING_EFFORT,
467
+ }
468
+ completion = self.openai.chat.completions.create(**request)
469
+ content, finish_reason, reasoning_tokens = completion_diagnostics(completion)
470
+ print(
471
+ f"Inference response: model={candidate}, budget={current_budget}, "
472
+ f"finish={finish_reason or 'unknown'}, reasoning_tokens={reasoning_tokens}, "
473
+ f"final_chars={len(content)}"
474
+ )
475
+
476
+ if content.strip() and finish_reason != "length":
477
+ return content
478
+
479
+ if content.strip():
480
+ # Preserve actual final content. Prefer a same-provider retry
481
+ # for a complete answer, but return this content if the retry
482
+ # cannot improve it.
483
+ partial_content = content
484
+
485
+ if finish_reason == "length":
486
+ if attempt_number < len(budgets):
487
+ print(
488
+ f"{candidate} succeeded but exhausted its output budget; "
489
+ f"retrying the same provider with {budgets[attempt_number]} tokens."
490
+ )
491
+ continue
492
+ if partial_content.strip():
493
+ print(
494
+ f"{candidate} reached the maximum budget; preserving its "
495
+ "available final content instead of switching providers."
496
+ )
497
+ return partial_content
498
+ raise OutputBudgetExhausted(
499
+ f"{candidate} returned HTTP success but used the full "
500
+ f"{current_budget}-token completion budget before emitting final content "
501
+ f"(reasoning_tokens={reasoning_tokens}). Increase "
502
+ "GPT_OSS_MAX_OUTPUT_TOKENS; this is truncation, not provider failure."
503
+ )
504
+
505
+ if content.strip():
506
+ return content
507
+ errors.append(
508
+ f"{candidate}: successful response had no final content "
509
+ f"(finish_reason={finish_reason or 'unknown'}, reasoning_tokens={reasoning_tokens})"
510
+ )
511
+ break
512
+ except OutputBudgetExhausted:
513
+ # Our explicit no-content/length error must not trigger a
514
+ # fallback provider (for example Fireworks with HTTP 402).
515
+ raise
516
+ except Exception as error:
517
+ status = getattr(error, "status_code", None)
518
+ response = getattr(error, "response", None)
519
+ if status is None and response is not None:
520
+ status = getattr(response, "status_code", None)
521
+ detail = str(error).replace("\n", " ")[:350]
522
+ errors.append(f"{candidate}: HTTP {status or '?'} {detail}")
523
+ provider_failed = True
524
+ if partial_content.strip():
525
+ print(
526
+ f"The same-provider completion retry failed; preserving the "
527
+ f"final content already returned by {candidate}."
528
+ )
529
+ return partial_content
530
+ if status in {408, 409, 429, 500, 502, 503, 504}:
531
+ time.sleep(2)
532
+ break
533
+
534
+ if partial_content.strip() and not provider_failed:
535
+ return partial_content
536
 
537
  joined = " | ".join(errors)
538
  if any("HTTP 403" in item for item in errors):
 
544
  raise RuntimeError(f"All inference routes failed: {joined}")
545
 
546
  def preflight(self) -> str:
547
+ """Verify both authorization and a real final-content response."""
548
  response = self.chat(
549
  [
550
  {"role": "system", "content": "Return only OK."},
551
  {"role": "user", "content": "Reply with OK."},
552
  ],
553
+ # 256 requested here, then chat() enforces the 512-token gpt-oss
554
+ # minimum. The previous 8/20-token checks could spend everything on
555
+ # hidden reasoning and incorrectly report working Cerebras as failed.
556
+ max_tokens=256,
557
  )
558
+ result = clean_answer(response)
559
+ if not result:
560
+ raise RuntimeError("Inference preflight returned no final content.")
561
+ return result
562
 
563
  def plan_queries(self, question: str) -> list[str]:
564
  prompt = (
 
573
  {"role": "system", "content": "You produce focused search queries as strict JSON."},
574
  {"role": "user", "content": prompt},
575
  ],
576
+ max_tokens=1024,
577
  )
578
  queries = parse_json_object(result).get("queries", [])
579
  queries = [str(item).strip() for item in queries if str(item).strip()]
 
681
  {"role": "system", "content": SYSTEM_PROMPT},
682
  {"role": "user", "content": user_prompt},
683
  ],
684
+ max_tokens=2048,
685
  )
686
  answer = clean_answer(raw)
687
  if not answer: