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.
@@ -0,0 +1,180 @@
1
+ """OpenAI /v1/responses typed-event SSE dialect normalizer (covers llama.cpp #30773)."""
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
+ TERMINAL_EVENT_TO_STATUS = {
10
+ "response.completed": "completed",
11
+ "response.incomplete": "incomplete",
12
+ "response.failed": "failed",
13
+ }
14
+
15
+
16
+ def _parse_usage(obj: Any) -> Dict[str, Any]:
17
+ usage = empty_usage()
18
+ if not isinstance(obj, dict):
19
+ return usage
20
+ if is_strict_int(obj.get("input_tokens")) and obj["input_tokens"] >= 0:
21
+ usage["prompt_tokens"] = obj["input_tokens"]
22
+ if is_strict_int(obj.get("output_tokens")) and obj["output_tokens"] >= 0:
23
+ usage["completion_tokens"] = obj["output_tokens"]
24
+
25
+ od = obj.get("output_tokens_details")
26
+ reas = od.get("reasoning_tokens") if isinstance(od, dict) else None
27
+ if not (is_strict_int(reas) and reas >= 0):
28
+ reas = obj.get("reasoning_tokens")
29
+ if is_strict_int(reas) and reas >= 0:
30
+ usage["reasoning_tokens"] = reas
31
+
32
+ ind = obj.get("input_tokens_details")
33
+ cached = ind.get("cached_tokens") if isinstance(ind, dict) else None
34
+ if not (is_strict_int(cached) and cached >= 0):
35
+ cached = obj.get("cached_tokens")
36
+ if is_strict_int(cached) and cached >= 0:
37
+ usage["cached_tokens"] = cached
38
+ return usage
39
+
40
+
41
+ def _extract_item_tool(item: Dict[str, Any], out_idx: Optional[int], *, is_done_item: bool) -> Optional[Dict[str, Any]]:
42
+ if item.get("type") != "function_call":
43
+ return None
44
+ # Only record arguments_snapshot on done/terminal items (never treat initial output_item.added "" as final snapshot)
45
+ snap = item.get("arguments") if (is_done_item and isinstance(item.get("arguments"), str)) else None
46
+ return {
47
+ "index": out_idx,
48
+ "id": item.get("call_id") if isinstance(item.get("call_id"), str) else None,
49
+ "item_id": item.get("id") if isinstance(item.get("id"), str) else None,
50
+ "name": item.get("name") if isinstance(item.get("name"), str) else None,
51
+ "arguments_delta": "",
52
+ "is_args_delta_event": False,
53
+ "arguments_snapshot": snap,
54
+ "is_item_done_snapshot": is_done_item,
55
+ "is_args_done": False,
56
+ }
57
+
58
+
59
+ def normalize_frame(payload: Dict[str, Any], sse_event: Optional[str] = None) -> NormalizedDelta:
60
+ """Normalize one parsed OpenAI Responses SSE event."""
61
+ ev_type = payload.get("type") if isinstance(payload.get("type"), str) else (sse_event or "")
62
+ delta = NormalizedDelta()
63
+
64
+ if ev_type == "error" or ("error" in payload and payload["error"] is not None):
65
+ delta.phase = "ERROR"
66
+ delta.inband_error = str(payload.get("error") or payload)
67
+ return delta
68
+
69
+ if ev_type in ("response.output_text.delta", "response.refusal.delta"):
70
+ txt = payload.get("delta")
71
+ if isinstance(txt, str):
72
+ delta.text_delta = txt
73
+ delta.phase = "CONTENT" if delta.text_delta else "HANDSHAKE"
74
+ return delta
75
+
76
+ if ev_type in ("response.reasoning_summary_text.delta", "response.reasoning_text.delta"):
77
+ txt = payload.get("delta")
78
+ if isinstance(txt, str):
79
+ delta.reasoning_delta = txt
80
+ delta.phase = "REASONING" if delta.reasoning_delta else "HANDSHAKE"
81
+ return delta
82
+
83
+ if ev_type == "response.output_item.added":
84
+ item = payload.get("item")
85
+ out_idx = payload.get("output_index") if is_strict_int(payload.get("output_index")) else None
86
+ if isinstance(item, dict):
87
+ td = _extract_item_tool(item, out_idx, is_done_item=False)
88
+ if td is not None:
89
+ delta.tool_deltas.append(td)
90
+ delta.phase = "TOOL"
91
+ return delta
92
+ delta.phase = "HANDSHAKE"
93
+ return delta
94
+
95
+ if ev_type == "response.function_call_arguments.delta":
96
+ out_idx = payload.get("output_index") if is_strict_int(payload.get("output_index")) else None
97
+ arg_delta = payload.get("delta") if isinstance(payload.get("delta"), str) else ""
98
+ delta.tool_deltas.append(
99
+ {
100
+ "index": out_idx,
101
+ "id": payload.get("call_id") if isinstance(payload.get("call_id"), str) else None,
102
+ "item_id": payload.get("item_id") if isinstance(payload.get("item_id"), str) else None,
103
+ "name": None,
104
+ "arguments_delta": arg_delta,
105
+ "is_args_delta_event": True, # Track receipt even when arg_delta == ""
106
+ "arguments_snapshot": None,
107
+ "is_args_done": False,
108
+ }
109
+ )
110
+ delta.phase = "TOOL"
111
+ return delta
112
+
113
+ if ev_type == "response.function_call_arguments.done":
114
+ out_idx = payload.get("output_index") if is_strict_int(payload.get("output_index")) else None
115
+ arg_snap = payload.get("arguments") if isinstance(payload.get("arguments"), str) else None
116
+ delta.tool_deltas.append(
117
+ {
118
+ "index": out_idx,
119
+ "id": payload.get("call_id") if isinstance(payload.get("call_id"), str) else None,
120
+ "item_id": payload.get("item_id") if isinstance(payload.get("item_id"), str) else None,
121
+ "name": payload.get("name") if isinstance(payload.get("name"), str) else None,
122
+ "arguments_delta": "",
123
+ "is_args_delta_event": False,
124
+ "arguments_snapshot": arg_snap,
125
+ "is_args_done": True,
126
+ }
127
+ )
128
+ delta.closed_events.append("response.function_call_arguments.done")
129
+ delta.phase = "TOOL"
130
+ return delta
131
+
132
+ if ev_type == "response.output_item.done":
133
+ item = payload.get("item")
134
+ out_idx = payload.get("output_index") if is_strict_int(payload.get("output_index")) else None
135
+ delta.closed_events.append("response.output_item.done")
136
+ if isinstance(item, dict):
137
+ td = _extract_item_tool(item, out_idx, is_done_item=True)
138
+ if td is not None:
139
+ delta.tool_deltas.append(td)
140
+ delta.phase = "TOOL"
141
+ return delta
142
+ delta.phase = "HANDSHAKE"
143
+ return delta
144
+
145
+ if ev_type in TERMINAL_EVENT_TO_STATUS:
146
+ expected_status = TERMINAL_EVENT_TO_STATUS[ev_type]
147
+ resp = payload.get("response") if isinstance(payload.get("response"), dict) else {}
148
+ raw_status = resp.get("status")
149
+ if raw_status != expected_status:
150
+ delta.protocol_error = (
151
+ f"invalid_responses_terminal_status: event={ev_type} status={raw_status!r} expected={expected_status!r}"
152
+ )
153
+ delta.phase = "ERROR"
154
+ delta.terminal_status = str(raw_status) if raw_status is not None else "unknown"
155
+ delta.is_done_sentinel = False
156
+ delta.usage = _parse_usage(resp.get("usage"))
157
+ return delta
158
+
159
+ status = expected_status
160
+ inc = resp.get("incomplete_details") if isinstance(resp.get("incomplete_details"), dict) else {}
161
+ inc_reason = inc.get("reason") if isinstance(inc.get("reason"), str) else None
162
+
163
+ delta.phase = "TERMINAL"
164
+ delta.terminal_status = status
165
+ delta.finish_reason = inc_reason
166
+ delta.closed_events.append(ev_type)
167
+ delta.is_done_sentinel = True
168
+ delta.usage = _parse_usage(resp.get("usage"))
169
+
170
+ out_items = resp.get("output")
171
+ if isinstance(out_items, list):
172
+ for pos, item in enumerate(out_items):
173
+ if isinstance(item, dict):
174
+ td = _extract_item_tool(item, pos, is_done_item=True)
175
+ if td is not None:
176
+ delta.tool_deltas.append(td)
177
+ return delta
178
+
179
+ delta.phase = "HANDSHAKE"
180
+ return delta
@@ -0,0 +1,68 @@
1
+ """SGLang native /generate SSE dialect normalizer (covers SGLang #53119 / #50443)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+
7
+ from ..schema import NormalizedDelta, empty_usage, is_strict_int
8
+
9
+
10
+ def _parse_usage(meta: Any) -> Dict[str, Any]:
11
+ usage = empty_usage()
12
+ if not isinstance(meta, dict):
13
+ return usage
14
+ if is_strict_int(meta.get("prompt_tokens")) and meta["prompt_tokens"] >= 0:
15
+ usage["prompt_tokens"] = meta["prompt_tokens"]
16
+ if is_strict_int(meta.get("completion_tokens")) and meta["completion_tokens"] >= 0:
17
+ usage["completion_tokens"] = meta["completion_tokens"]
18
+ reas = meta.get("reasoning_tokens")
19
+ if is_strict_int(reas) and reas >= 0:
20
+ usage["reasoning_tokens"] = reas
21
+ cached = meta.get("cached_tokens")
22
+ if is_strict_int(cached) and cached >= 0:
23
+ usage["cached_tokens"] = cached
24
+ return usage
25
+
26
+
27
+ def normalize_frame(
28
+ payload: Dict[str, Any],
29
+ sse_event: Optional[str] = None,
30
+ *,
31
+ prev_text: str = "",
32
+ ) -> NormalizedDelta:
33
+ """Normalize one parsed SGLang /generate chunk (handles cumulative text & textless terminal meta_info)."""
34
+ meta = payload.get("meta_info") if isinstance(payload.get("meta_info"), dict) else {}
35
+ delta = NormalizedDelta(usage=_parse_usage(meta), is_cumulative_text=True)
36
+
37
+ if "error" in payload and payload["error"] is not None:
38
+ delta.phase = "ERROR"
39
+ delta.inband_error = str(payload["error"])
40
+ return delta
41
+
42
+ if isinstance(payload.get("text"), str):
43
+ cum = payload["text"]
44
+ if cum.startswith(prev_text):
45
+ delta.text_delta = cum[len(prev_text) :]
46
+ else:
47
+ # Non-monotonic prefix rewrite: keep literal string for forensic visibility
48
+ delta.text_delta = cum
49
+
50
+ fr_obj = meta.get("finish_reason")
51
+ if isinstance(fr_obj, dict) and isinstance(fr_obj.get("type"), str) and fr_obj["type"]:
52
+ delta.finish_reason = fr_obj["type"]
53
+ matched = fr_obj.get("matched")
54
+ if matched is not None and matched != "":
55
+ delta.matched_stop = matched
56
+ elif isinstance(fr_obj, str) and fr_obj:
57
+ delta.finish_reason = fr_obj
58
+
59
+ if delta.finish_reason:
60
+ delta.phase = "TERMINAL"
61
+ elif delta.text_delta:
62
+ delta.phase = "CONTENT"
63
+ elif any(v != "unknown" for v in delta.usage.values()):
64
+ delta.phase = "USAGE"
65
+ else:
66
+ delta.phase = "HANDSHAKE"
67
+
68
+ return delta