inferdiff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
inferdiff/detectors.py ADDED
@@ -0,0 +1,423 @@
1
+ """Pure deterministic silent-failure detectors (D1..D5) with zero-false-positive guards."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, List, Optional, Set
7
+
8
+ from .schema import TraceDocument, is_strict_int, safe_utf8_len
9
+
10
+ D1 = "D1"
11
+ D2 = "D2"
12
+ D3 = "D3"
13
+ D4 = "D4"
14
+ D5 = "D5"
15
+
16
+ VALID_AUDIT_DETECTORS = frozenset({D1, D2, D3, D4})
17
+
18
+ DETECTOR_NAMES = {
19
+ D1: "UNCLOSED_TOOL_CALL_SUCCESS",
20
+ D2: "GHOST_BUDGET_EMPTY_OUTPUT",
21
+ D3: "SILENT_SHORT_GENERATION",
22
+ D4: "STREAM_PREMATURE_EOF",
23
+ D5: "BENCHMARK_ILLUSION_ALERT",
24
+ }
25
+
26
+
27
+ @dataclass
28
+ class Finding:
29
+ detector_id: str
30
+ code: str
31
+ severity: str # "P0" | "P1"
32
+ message: str
33
+ frame_seq: Optional[int] = None
34
+ evidence: Dict[str, Any] = field(default_factory=dict)
35
+
36
+ def to_dict(self) -> Dict[str, Any]:
37
+ return {
38
+ "detector_id": self.detector_id,
39
+ "code": self.code,
40
+ "severity": self.severity,
41
+ "message": self.message,
42
+ "frame_seq": self.frame_seq,
43
+ "evidence": self.evidence,
44
+ }
45
+
46
+
47
+ def _last_terminal_seq(doc: TraceDocument) -> Optional[int]:
48
+ for frame in reversed(doc.frames):
49
+ norm = frame.norm or {}
50
+ if norm.get("finish_reason") or norm.get("terminal_status"):
51
+ return frame.seq
52
+ for frame in reversed(doc.frames):
53
+ norm = frame.norm or {}
54
+ if norm.get("phase") == "TERMINAL":
55
+ return frame.seq
56
+ return doc.frames[-1].seq if doc.frames else None
57
+
58
+
59
+ def _has_inband_error(doc: TraceDocument) -> bool:
60
+ return any((f.norm or {}).get("phase") == "ERROR" or (f.norm or {}).get("inband_error") for f in doc.frames)
61
+
62
+
63
+ def detect_d1(doc: TraceDocument) -> List[Finding]:
64
+ """D1 (P0): Tool call JSON unclosed/invalid, conflicting, mismatched, or missing Responses .done while claiming success."""
65
+ if doc.header.response_meta.get("status_code") != 200:
66
+ return []
67
+ asm = doc.summary.assembled
68
+ tool_calls = asm.get("tool_calls") or []
69
+ if not tool_calls:
70
+ return []
71
+
72
+ finish_reason = asm.get("finish_reason", "unknown")
73
+ terminal_status = asm.get("terminal_status", "unknown")
74
+ claims_success = (finish_reason in ("stop", "tool_calls")) or (terminal_status == "completed")
75
+ if not claims_success:
76
+ return []
77
+
78
+ findings: List[Finding] = []
79
+ dialect = doc.header.dialect
80
+ term_seq = _last_terminal_seq(doc)
81
+
82
+ for tc in tool_calls:
83
+ invalid_json = tc.get("json_valid") is False
84
+ saw_delta = tc.get("saw_args_delta")
85
+ if saw_delta is None:
86
+ saw_delta = tc.get("saw_args_done_event") is False
87
+ missing_done = (
88
+ dialect == "openai-responses"
89
+ and bool(saw_delta)
90
+ and tc.get("saw_args_done_event") is False
91
+ )
92
+ args_mismatch = bool(tc.get("args_mismatch"))
93
+ identity_conflict = bool(tc.get("identity_conflict"))
94
+
95
+ if invalid_json or missing_done or args_mismatch or identity_conflict:
96
+ reasons: List[str] = []
97
+ if invalid_json:
98
+ reasons.append(f"json_valid=false ({tc.get('json_error')})")
99
+ if missing_done:
100
+ reasons.append("missing response.function_call_arguments.done")
101
+ if args_mismatch:
102
+ reasons.append(str(tc.get("args_mismatch_detail") or "streamed arguments mismatch final snapshot"))
103
+ if identity_conflict:
104
+ reasons.append("conflicting tool call identity on shared index")
105
+
106
+ cite_seq = tc.get("last_seq") if is_strict_int(tc.get("last_seq")) else term_seq
107
+ if missing_done and term_seq is not None:
108
+ cite_seq = term_seq
109
+ findings.append(
110
+ Finding(
111
+ detector_id=D1,
112
+ code=DETECTOR_NAMES[D1],
113
+ severity="P0",
114
+ message=(
115
+ f"Tool call #{tc.get('index')} ({tc.get('name') or 'unnamed'}) reported terminal "
116
+ f"'{terminal_status if terminal_status != 'unknown' else finish_reason}' with "
117
+ + " and ".join(reasons)
118
+ ),
119
+ frame_seq=cite_seq,
120
+ evidence={
121
+ "tool_index": tc.get("index"),
122
+ "tool_name": tc.get("name"),
123
+ "raw_args_bytes": safe_utf8_len(tc.get("raw_arguments") or ""),
124
+ "json_valid": tc.get("json_valid"),
125
+ "json_error": tc.get("json_error"),
126
+ "saw_args_delta": tc.get("saw_args_delta"),
127
+ "saw_args_done_event": tc.get("saw_args_done_event"),
128
+ "args_mismatch": args_mismatch,
129
+ "identity_conflict": identity_conflict,
130
+ "finish_reason": finish_reason,
131
+ "terminal_status": terminal_status,
132
+ },
133
+ )
134
+ )
135
+ return findings
136
+
137
+
138
+ def detect_d2(doc: TraceDocument) -> List[Finding]:
139
+ """D2 (P0): HTTP 200 with empty visible content and no tools despite consumed budget / reasoning / stop."""
140
+ if doc.header.response_meta.get("status_code") != 200:
141
+ return []
142
+ if _has_inband_error(doc):
143
+ return []
144
+ asm = doc.summary.assembled
145
+ content_text = asm.get("content_text") or ""
146
+ tool_calls = asm.get("tool_calls") or []
147
+ if content_text.strip() != "" or len(tool_calls) > 0:
148
+ return []
149
+
150
+ finish_reason = asm.get("finish_reason", "unknown")
151
+ matched_stop = asm.get("matched_stop")
152
+ eff = doc.header.request.get("effective_params") or {}
153
+ stop_conditions = eff.get("stop_conditions") or []
154
+ usage = asm.get("reported_usage") or {}
155
+ comp_tokens = usage.get("completion_tokens")
156
+ reasoning_text = asm.get("reasoning_text") or ""
157
+ has_unclosed_think = bool(asm.get("has_unclosed_think"))
158
+
159
+ # Spec §4.2: nonempty reasoning predicate (any reasoning characters or unclosed <think>)
160
+ has_reasoning = (reasoning_text != "") or has_unclosed_think
161
+
162
+ # Observed stop-match guard: only suppress D2 when the reported matched_stop actually
163
+ # corresponds to one of the request's configured stop conditions (strict type match).
164
+ matched_configured_stop = (
165
+ matched_stop is not None
166
+ and any(
167
+ (type(matched_stop) is type(sc)) and (matched_stop == sc)
168
+ for sc in stop_conditions
169
+ )
170
+ )
171
+ if matched_configured_stop and not has_reasoning:
172
+ return []
173
+
174
+ has_tokens = is_strict_int(comp_tokens) and comp_tokens >= 1
175
+ stopped_empty = finish_reason == "stop"
176
+
177
+ if has_tokens or has_reasoning or stopped_empty:
178
+ return [
179
+ Finding(
180
+ detector_id=D2,
181
+ code=DETECTOR_NAMES[D2],
182
+ severity="P0",
183
+ message=(
184
+ f"HTTP 200 returned empty visible content and 0 tool calls "
185
+ f"(completion_tokens={comp_tokens}, reasoning_chars={len(reasoning_text)}, "
186
+ f"unclosed_think={has_unclosed_think}, finish_reason={finish_reason})"
187
+ ),
188
+ frame_seq=_last_terminal_seq(doc),
189
+ evidence={
190
+ "completion_tokens": comp_tokens,
191
+ "reasoning_chars": len(reasoning_text),
192
+ "has_unclosed_think": has_unclosed_think,
193
+ "finish_reason": finish_reason,
194
+ "terminal_status": asm.get("terminal_status"),
195
+ "matched_stop": matched_stop,
196
+ },
197
+ )
198
+ ]
199
+ return []
200
+
201
+
202
+ def detect_d3(doc: TraceDocument) -> List[Finding]:
203
+ """D3 (P1): Fixed-length benchmark (ignore_eos=true, no effective stop) generated fewer tokens than budget."""
204
+ if doc.header.response_meta.get("status_code") != 200:
205
+ return []
206
+ eff = doc.header.request.get("effective_params") or {}
207
+ if eff.get("ignore_eos") is not True:
208
+ return []
209
+ budget = eff.get("max_budget_tokens")
210
+ if not (is_strict_int(budget) and budget > 0):
211
+ return []
212
+ if eff.get("stop_conditions"):
213
+ return []
214
+
215
+ asm = doc.summary.assembled
216
+ usage = asm.get("reported_usage") or {}
217
+ comp = usage.get("completion_tokens")
218
+ if not is_strict_int(comp):
219
+ return []
220
+ if comp < budget:
221
+ return [
222
+ Finding(
223
+ detector_id=D3,
224
+ code=DETECTOR_NAMES[D3],
225
+ severity="P1",
226
+ message=(
227
+ f"Fixed-length request (ignore_eos=true, budget={budget}) produced only "
228
+ f"{comp}/{budget} completion tokens (finish_reason={asm.get('finish_reason')})"
229
+ ),
230
+ frame_seq=_last_terminal_seq(doc),
231
+ evidence={
232
+ "requested_budget": budget,
233
+ "completion_tokens": comp,
234
+ "finish_reason": asm.get("finish_reason"),
235
+ "saw_textless_usage_frame": bool(asm.get("saw_textless_usage_frame")),
236
+ },
237
+ )
238
+ ]
239
+ return []
240
+
241
+
242
+ def detect_d4(doc: TraceDocument) -> List[Finding]:
243
+ """D4 (P0): HTTP 2xx stream ended prematurely, violated terminal order, or used unsupported 2xx status (e.g. 204)."""
244
+ status_code = doc.header.response_meta.get("status_code")
245
+ if not is_strict_int(status_code) or status_code < 200 or status_code >= 300:
246
+ return []
247
+
248
+ reasons: List[str] = []
249
+ if status_code != 200:
250
+ reasons.append(f"unexpected_2xx_status={status_code}")
251
+
252
+ parse_errors = [(f.seq, f.parse_error) for f in doc.frames if f.parse_error]
253
+ asm = doc.summary.assembled
254
+ protocol_violations = asm.get("protocol_violations") or []
255
+ no_terminal_state = (
256
+ not _has_inband_error(doc)
257
+ and asm.get("finish_reason", "unknown") == "unknown"
258
+ and asm.get("terminal_status", "unknown") == "unknown"
259
+ )
260
+ if not doc.summary.eof_clean:
261
+ reasons.append("eof_clean=false (missing terminal sentinel, framing error, or socket dropped)")
262
+ if parse_errors:
263
+ reasons.append(f"parse_errors={parse_errors[:3]}")
264
+ if protocol_violations:
265
+ reasons.append(f"protocol_violations={protocol_violations[:3]}")
266
+ if no_terminal_state:
267
+ reasons.append("missing finish_reason and terminal_status")
268
+
269
+ if reasons:
270
+ first_err_seq = parse_errors[0][0] if parse_errors else (doc.frames[-1].seq if doc.frames else None)
271
+ return [
272
+ Finding(
273
+ detector_id=D4,
274
+ code=DETECTOR_NAMES[D4],
275
+ severity="P0",
276
+ message=f"HTTP {status_code} stream terminated uncleanly: " + "; ".join(reasons),
277
+ frame_seq=first_err_seq,
278
+ evidence={
279
+ "status_code": status_code,
280
+ "eof_clean": doc.summary.eof_clean,
281
+ "total_frames": doc.summary.total_frames,
282
+ "parse_errors": parse_errors,
283
+ "protocol_violations": protocol_violations,
284
+ "finish_reason": asm.get("finish_reason"),
285
+ "terminal_status": asm.get("terminal_status"),
286
+ },
287
+ )
288
+ ]
289
+ return []
290
+
291
+
292
+ def _max_consecutive_burst_run(doc: TraceDocument) -> int:
293
+ """Return length of longest contiguous run of sub-0.5ms elapsed intervals between text delta frames."""
294
+ max_run = 0
295
+ cur_run = 0
296
+ prev_delta_t_ms: Optional[float] = None
297
+ for f in doc.frames:
298
+ has_text = bool((f.norm or {}).get("text_delta"))
299
+ if not has_text:
300
+ continue
301
+ if prev_delta_t_ms is not None and (f.t_rel_ms - prev_delta_t_ms) < 0.5:
302
+ cur_run += 1
303
+ if cur_run > max_run:
304
+ max_run = cur_run
305
+ else:
306
+ cur_run = 0
307
+ prev_delta_t_ms = f.t_rel_ms
308
+ return max_run
309
+
310
+
311
+ def detect_d5(
312
+ before: TraceDocument,
313
+ after: TraceDocument,
314
+ *,
315
+ ignore_timing: bool = False,
316
+ min_delta_ms: float = 0.0,
317
+ ) -> List[Finding]:
318
+ """D5 (P1): Benchmark illusion alert when after latency drops >50%."""
319
+ if ignore_timing:
320
+ return []
321
+ b_time = before.summary.timing
322
+ a_time = after.summary.timing
323
+ b_total = b_time.get("total_ms")
324
+ a_total = a_time.get("total_ms")
325
+ b_ttft = b_time.get("ttft_effective_ms")
326
+ a_ttft = a_time.get("ttft_effective_ms")
327
+
328
+ total_drop = (
329
+ isinstance(b_total, (int, float))
330
+ and isinstance(a_total, (int, float))
331
+ and b_total > 0
332
+ and (b_total - a_total) >= min_delta_ms
333
+ and a_total < 0.5 * b_total
334
+ )
335
+ ttft_drop = (
336
+ isinstance(b_ttft, (int, float))
337
+ and isinstance(a_ttft, (int, float))
338
+ and b_ttft > 0
339
+ and (b_ttft - a_ttft) >= min_delta_ms
340
+ and a_ttft < 0.5 * b_ttft
341
+ )
342
+ if not (total_drop or ttft_drop):
343
+ return []
344
+
345
+ sub_reasons: List[str] = []
346
+ evidence: Dict[str, Any] = {
347
+ "before_total_ms": b_total,
348
+ "after_total_ms": a_total,
349
+ "before_ttft_effective_ms": b_ttft,
350
+ "after_ttft_effective_ms": a_ttft,
351
+ }
352
+
353
+ # (a) Asymmetric cached_tokens jump (requires reported cache evidence — never fabricate from unknown)
354
+ b_usage = before.summary.assembled.get("reported_usage") or {}
355
+ a_usage = after.summary.assembled.get("reported_usage") or {}
356
+ b_cached = b_usage.get("cached_tokens", "unknown")
357
+ a_cached = a_usage.get("cached_tokens", "unknown")
358
+ evidence["before_cached_tokens"] = b_cached
359
+ evidence["after_cached_tokens"] = a_cached
360
+ if is_strict_int(a_cached) and a_cached > 0 and (not is_strict_int(b_cached) or a_cached > b_cached):
361
+ sub_reasons.append(f"D5a asymmetric cached_tokens jump ({b_cached} -> {a_cached})")
362
+
363
+ # (b) After output volume collapsed below 50% of before
364
+ b_comp = b_usage.get("completion_tokens")
365
+ a_comp = a_usage.get("completion_tokens")
366
+ b_bytes = before.summary.assembled.get("content_utf8_bytes", 0)
367
+ a_bytes = after.summary.assembled.get("content_utf8_bytes", 0)
368
+ if is_strict_int(b_comp) and is_strict_int(a_comp) and b_comp > 0 and a_comp < 0.5 * b_comp:
369
+ sub_reasons.append(f"D5b output token collapse ({a_comp}/{b_comp} tokens)")
370
+ elif b_bytes > 0 and a_bytes < 0.5 * b_bytes:
371
+ sub_reasons.append(f"D5b output byte collapse ({a_bytes}/{b_bytes} bytes)")
372
+
373
+ # (c) Burst-pulse distortion (avg bytes/frame doubled + consecutive sub-0.5ms burst cluster)
374
+ b_df = max(1, int(before.summary.assembled.get("observed_delta_frames") or 0))
375
+ a_df = max(1, int(after.summary.assembled.get("observed_delta_frames") or 0))
376
+ b_avg = b_bytes / b_df if b_bytes > 0 else 0.0
377
+ a_avg = a_bytes / a_df if a_bytes > 0 else 0.0
378
+ burst_run = _max_consecutive_burst_run(after)
379
+ if b_avg > 0 and a_avg >= 2.0 * b_avg and burst_run >= 2:
380
+ sub_reasons.append(
381
+ f"D5c bursty multi-token frames (avg {b_avg:.1f}B -> {a_avg:.1f}B, {burst_run} consecutive intervals dt<0.5ms)"
382
+ )
383
+ evidence["max_consecutive_burst_intervals"] = burst_run
384
+
385
+ if not sub_reasons:
386
+ return []
387
+
388
+ return [
389
+ Finding(
390
+ detector_id=D5,
391
+ code=DETECTOR_NAMES[D5],
392
+ severity="P1",
393
+ message="Benchmark speedup >50% flagged as potential illusion: " + "; ".join(sub_reasons),
394
+ frame_seq=None,
395
+ evidence={**evidence, "sub_reasons": sub_reasons},
396
+ )
397
+ ]
398
+
399
+
400
+ def audit_trace(doc: TraceDocument, *, only: Optional[Set[str]] = None) -> List[Finding]:
401
+ """Run D1..D4 (or validated subset via `only`) on a single TraceDocument."""
402
+ if only is not None:
403
+ normalized = {d.strip().upper() for d in only if d.strip()}
404
+ unknown = sorted(normalized - VALID_AUDIT_DETECTORS)
405
+ if not normalized or unknown:
406
+ raise ValueError(
407
+ f"Invalid --only detector selection: {sorted(only)!r} (valid for audit: D1, D2, D3, D4)"
408
+ )
409
+ active = normalized
410
+ else:
411
+ active = set(VALID_AUDIT_DETECTORS)
412
+
413
+ findings: List[Finding] = []
414
+ if D1 in active:
415
+ findings.extend(detect_d1(doc))
416
+ if D2 in active:
417
+ findings.extend(detect_d2(doc))
418
+ if D3 in active:
419
+ findings.extend(detect_d3(doc))
420
+ if D4 in active:
421
+ findings.extend(detect_d4(doc))
422
+ findings.sort(key=lambda f: (0 if f.severity == "P0" else 1, f.detector_id))
423
+ return findings
@@ -0,0 +1,41 @@
1
+ """Streaming dialect detection and normalization registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+
7
+ from ..schema import NormalizedDelta
8
+ from . import ollama_ndjson, openai_chat, openai_responses, sglang_native
9
+
10
+
11
+ def detect_dialect(url_path: str, content_type: str = "") -> str:
12
+ """Infer dialect from URL path and Content-Type when --dialect=auto."""
13
+ path = url_path.rstrip("/").lower()
14
+ ct = content_type.split(";", 1)[0].strip().lower()
15
+ if path.endswith("/v1/responses") or path.endswith("/responses"):
16
+ return "openai-responses"
17
+ if path.endswith("/v1/chat/completions") or path.endswith("/chat/completions"):
18
+ return "openai-chat"
19
+ if path.endswith("/api/chat") or path.endswith("/api/generate") or ct == "application/x-ndjson":
20
+ return "ollama-ndjson"
21
+ if path.endswith("/generate"):
22
+ return "sglang-native"
23
+ return "openai-chat"
24
+
25
+
26
+ def normalize_payload(
27
+ dialect: str,
28
+ payload: Dict[str, Any],
29
+ *,
30
+ sse_event: Optional[str] = None,
31
+ prev_text: str = "",
32
+ ) -> NormalizedDelta:
33
+ if dialect == "openai-chat":
34
+ return openai_chat.normalize_frame(payload, sse_event)
35
+ if dialect == "openai-responses":
36
+ return openai_responses.normalize_frame(payload, sse_event)
37
+ if dialect == "sglang-native":
38
+ return sglang_native.normalize_frame(payload, sse_event, prev_text=prev_text)
39
+ if dialect == "ollama-ndjson":
40
+ return ollama_ndjson.normalize_frame(payload, sse_event)
41
+ raise ValueError(f"Unsupported dialect: {dialect!r}")
@@ -0,0 +1,94 @@
1
+ """Ollama /api/chat and /api/generate NDJSON dialect normalizer (covers Ollama #17274)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from ..schema import NormalizedDelta, empty_usage, is_strict_int
9
+
10
+
11
+ def normalize_frame(payload: Dict[str, Any], sse_event: Optional[str] = None) -> NormalizedDelta:
12
+ """Normalize one NDJSON line from Ollama /api/chat or /api/generate."""
13
+ usage = empty_usage()
14
+ if is_strict_int(payload.get("prompt_eval_count")) and payload["prompt_eval_count"] >= 0:
15
+ usage["prompt_tokens"] = payload["prompt_eval_count"]
16
+ if is_strict_int(payload.get("eval_count")) and payload["eval_count"] >= 0:
17
+ usage["completion_tokens"] = payload["eval_count"]
18
+
19
+ delta = NormalizedDelta(usage=usage)
20
+
21
+ if "error" in payload and payload["error"] is not None:
22
+ delta.phase = "ERROR"
23
+ delta.inband_error = str(payload["error"])
24
+ return delta
25
+
26
+ msg = payload.get("message") if isinstance(payload.get("message"), dict) else {}
27
+ # /api/chat uses message.content / message.thinking / message.tool_calls
28
+ # /api/generate uses top-level response / thinking
29
+ text = msg.get("content") if isinstance(msg.get("content"), str) else payload.get("response")
30
+ if isinstance(text, str) and text != "":
31
+ delta.text_delta = text
32
+
33
+ thinking = msg.get("thinking") if isinstance(msg.get("thinking"), str) else payload.get("thinking")
34
+ if isinstance(thinking, str) and thinking != "":
35
+ delta.reasoning_delta = thinking
36
+
37
+ tcalls = msg.get("tool_calls")
38
+ if isinstance(tcalls, list):
39
+ tool_deltas: List[Dict[str, Any]] = []
40
+ for tc in tcalls:
41
+ if not isinstance(tc, dict):
42
+ continue
43
+ fn = tc.get("function") if isinstance(tc.get("function"), dict) else {}
44
+ args = fn.get("arguments")
45
+ if isinstance(args, dict):
46
+ try:
47
+ arg_str = json.dumps(args, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
48
+ except (ValueError, TypeError, OverflowError):
49
+ delta.protocol_error = "invalid_ollama_tool_arguments"
50
+ arg_str = ""
51
+ elif isinstance(args, str):
52
+ arg_str = args
53
+ else:
54
+ arg_str = ""
55
+ # Ollama streaming emits complete tool calls per chunk with frame-local positions;
56
+ # mark append mode so consecutive chunks accumulate distinct calls instead of colliding.
57
+ raw_idx = tc.get("index") if is_strict_int(tc.get("index")) else None
58
+ raw_id = tc.get("id") if isinstance(tc.get("id"), str) and tc.get("id") else None
59
+ tool_deltas.append(
60
+ {
61
+ "index": raw_idx,
62
+ "id": raw_id,
63
+ "item_id": None,
64
+ "name": fn.get("name") if isinstance(fn.get("name"), str) else None,
65
+ "arguments_delta": "",
66
+ "is_args_delta_event": False,
67
+ "arguments_snapshot": arg_str,
68
+ "is_args_done": True,
69
+ "tool_accumulate_mode": "append",
70
+ }
71
+ )
72
+ delta.tool_deltas = tool_deltas
73
+
74
+ done = payload.get("done") is True
75
+ done_reason = payload.get("done_reason") if isinstance(payload.get("done_reason"), str) and payload.get("done_reason") else None
76
+ if done:
77
+ delta.is_done_sentinel = True
78
+ delta.closed_events.append("ollama.done")
79
+ delta.terminal_status = "completed"
80
+ # Preserve absent done_reason as "unknown" instead of fabricating "stop"
81
+ delta.finish_reason = done_reason if done_reason is not None else "unknown"
82
+ delta.phase = "TERMINAL"
83
+ return delta
84
+
85
+ if delta.tool_deltas:
86
+ delta.phase = "TOOL"
87
+ elif delta.reasoning_delta and not delta.text_delta:
88
+ delta.phase = "REASONING"
89
+ elif delta.text_delta:
90
+ delta.phase = "CONTENT"
91
+ else:
92
+ delta.phase = "HANDSHAKE"
93
+
94
+ return delta
@@ -0,0 +1,113 @@
1
+ """OpenAI /v1/chat/completions SSE dialect normalizer (llama-server, vLLM, SGLang, LiteLLM)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from ..schema import NormalizedDelta, empty_usage, is_strict_int
8
+
9
+
10
+ def _parse_usage(obj: Any) -> Dict[str, Any]:
11
+ usage = empty_usage()
12
+ if not isinstance(obj, dict):
13
+ return usage
14
+ if is_strict_int(obj.get("prompt_tokens")) and obj["prompt_tokens"] >= 0:
15
+ usage["prompt_tokens"] = obj["prompt_tokens"]
16
+ if is_strict_int(obj.get("completion_tokens")) and obj["completion_tokens"] >= 0:
17
+ usage["completion_tokens"] = obj["completion_tokens"]
18
+
19
+ cd = obj.get("completion_tokens_details")
20
+ reas = cd.get("reasoning_tokens") if isinstance(cd, dict) else None
21
+ if not (is_strict_int(reas) and reas >= 0):
22
+ reas = obj.get("reasoning_tokens")
23
+ if is_strict_int(reas) and reas >= 0:
24
+ usage["reasoning_tokens"] = reas
25
+
26
+ pd = obj.get("prompt_tokens_details")
27
+ cached = pd.get("cached_tokens") if isinstance(pd, dict) else None
28
+ if not (is_strict_int(cached) and cached >= 0):
29
+ cached = obj.get("cached_tokens")
30
+ if is_strict_int(cached) and cached >= 0:
31
+ usage["cached_tokens"] = cached
32
+ return usage
33
+
34
+
35
+ def normalize_frame(payload: Dict[str, Any], sse_event: Optional[str] = None) -> NormalizedDelta:
36
+ """Normalize one parsed OpenAI Chat Completions JSON chunk."""
37
+ delta = NormalizedDelta(usage=_parse_usage(payload.get("usage")))
38
+
39
+ if "error" in payload and payload["error"] is not None:
40
+ delta.phase = "ERROR"
41
+ delta.inband_error = str(payload["error"])
42
+ return delta
43
+
44
+ choices = payload.get("choices")
45
+ if not isinstance(choices, list) or not choices:
46
+ # vLLM include_usage trailing chunk has choices: [] with usage
47
+ has_usage = any(v != "unknown" for v in delta.usage.values())
48
+ delta.phase = "USAGE" if has_usage else "HANDSHAKE"
49
+ return delta
50
+
51
+ ch0 = choices[0] if isinstance(choices[0], dict) else {}
52
+ d = ch0.get("delta") if isinstance(ch0.get("delta"), dict) else {}
53
+
54
+ content = d.get("content")
55
+ refusal = d.get("refusal")
56
+ if isinstance(content, str) and content != "":
57
+ delta.text_delta = content
58
+ elif isinstance(refusal, str) and refusal != "":
59
+ delta.text_delta = refusal
60
+
61
+ reas = d.get("reasoning_content")
62
+ if not isinstance(reas, str) or reas == "":
63
+ reas = d.get("reasoning")
64
+ if isinstance(reas, str) and reas != "":
65
+ delta.reasoning_delta = reas
66
+
67
+ tcalls = d.get("tool_calls")
68
+ tool_deltas: List[Dict[str, Any]] = []
69
+ if isinstance(tcalls, list):
70
+ for pos, tc in enumerate(tcalls):
71
+ if not isinstance(tc, dict):
72
+ continue
73
+ fn = tc.get("function") if isinstance(tc.get("function"), dict) else {}
74
+ idx = tc.get("index") if is_strict_int(tc.get("index")) else pos
75
+ raw_arg = fn.get("arguments")
76
+ has_arg_field = isinstance(raw_arg, str)
77
+ tool_deltas.append(
78
+ {
79
+ "index": idx,
80
+ "id": tc.get("id") if isinstance(tc.get("id"), str) else None,
81
+ "item_id": None,
82
+ "name": fn.get("name") if isinstance(fn.get("name"), str) else None,
83
+ "arguments_delta": raw_arg if has_arg_field else "",
84
+ "is_args_delta_event": has_arg_field and raw_arg != "",
85
+ "arguments_snapshot": None,
86
+ "is_args_done": False,
87
+ }
88
+ )
89
+ delta.tool_deltas = tool_deltas
90
+
91
+ fin = ch0.get("finish_reason")
92
+ if isinstance(fin, str) and fin:
93
+ delta.finish_reason = fin
94
+
95
+ # vLLM / SGLang OpenAI-compatible servers emit stop_reason when an explicit user stop matched
96
+ stop_reason = ch0.get("stop_reason")
97
+ if stop_reason is not None and stop_reason != "":
98
+ delta.matched_stop = stop_reason
99
+
100
+ if delta.finish_reason:
101
+ delta.phase = "TERMINAL"
102
+ elif delta.tool_deltas:
103
+ delta.phase = "TOOL"
104
+ elif delta.reasoning_delta and not delta.text_delta:
105
+ delta.phase = "REASONING"
106
+ elif delta.text_delta:
107
+ delta.phase = "CONTENT"
108
+ elif any(v != "unknown" for v in delta.usage.values()):
109
+ delta.phase = "USAGE"
110
+ else:
111
+ delta.phase = "HANDSHAKE"
112
+
113
+ return delta