python-codex 0.6.3__py3-none-any.whl → 0.7.1__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.
- pycodex/agent.py +325 -321
- pycodex/config.py +19 -2
- pycodex/context.py +24 -9
- pycodex/events.py +127 -7
- pycodex/model.py +269 -95
- pycodex/multi_agents.py +13 -42
- pycodex/prompts/models.json +8 -8
- pycodex/protocol.py +4 -2
- pycodex/runtime.py +227 -131
- pycodex/tools/__init__.py +3 -3
- pycodex/tools/clock_manager.py +0 -7
- pycodex/tools/exec_command_tool.py +16 -5
- pycodex/tools/exec_runtime.py +5 -1
- pycodex/tools/goal_manager.py +25 -32
- pycodex/tools/runtime_services.py +21 -11
- pycodex/tools/unified_exec_manager.py +46 -3
- pycodex/utils/compactor.py +28 -101
- pycodex/utils/compat.py +6 -0
- pycodex/utils/event_helpers.py +47 -0
- pycodex/utils/history.py +22 -7
- pycodex/utils/model_metadata.py +5 -4
- pycodex/utils/session_persist.py +6 -2
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/METADATA +40 -13
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/RECORD +30 -30
- responses_server/app.py +4 -0
- responses_server/gemini_api.py +26 -7
- responses_server/transport.py +12 -5
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/WHEEL +0 -0
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.3.dist-info → python_codex-0.7.1.dist-info}/licenses/LICENSE +0 -0
pycodex/model.py
CHANGED
|
@@ -2,7 +2,6 @@ import asyncio
|
|
|
2
2
|
import json
|
|
3
3
|
import os
|
|
4
4
|
import re
|
|
5
|
-
import threading
|
|
6
5
|
import typing
|
|
7
6
|
import urllib.parse
|
|
8
7
|
import uuid
|
|
@@ -15,18 +14,23 @@ from typing import Callable
|
|
|
15
14
|
import requests
|
|
16
15
|
from urllib3.exceptions import ReadTimeoutError
|
|
17
16
|
|
|
18
|
-
from .utils.compat import Protocol
|
|
17
|
+
from .utils.compat import Literal, Protocol
|
|
19
18
|
from .utils.codex_config import DEFAULT_CODEX_CONFIG_PATH, read_codex_config
|
|
20
19
|
from .utils.http_headers import build_http_headers
|
|
21
20
|
|
|
22
21
|
from .events import (
|
|
22
|
+
BASE_EVENT_HANDLER,
|
|
23
23
|
AssistantDeltaEvent,
|
|
24
|
+
EventScope,
|
|
24
25
|
ModelEvent,
|
|
26
|
+
ModelRequestInterrupted,
|
|
25
27
|
ModelRequestTimingEvent,
|
|
28
|
+
ReasoningEvent,
|
|
26
29
|
StreamErrorEvent,
|
|
27
30
|
TokenCountEvent,
|
|
28
31
|
ToolCalledEvent,
|
|
29
32
|
)
|
|
33
|
+
from .utils.event_helpers import reasoning_item_text
|
|
30
34
|
from .utils.model_metadata import load_models_by_slug, model_metadata
|
|
31
35
|
from .protocol import (
|
|
32
36
|
AssistantMessage,
|
|
@@ -44,7 +48,8 @@ from .utils import build_user_agent, uuid7_string
|
|
|
44
48
|
DEFAULT_ORIGINATOR = "pycodex"
|
|
45
49
|
RESPONSES_LITE_HEADER = "x-openai-internal-codex-responses-lite"
|
|
46
50
|
ModelStreamEventHandler = Callable[[ModelEvent], None]
|
|
47
|
-
|
|
51
|
+
RetryCodes = typing.Union[int, typing.FrozenSet[int], Literal["*"]]
|
|
52
|
+
NOOP_MODEL_STREAM_EVENT_HANDLER: "ModelStreamEventHandler" = BASE_EVENT_HANDLER
|
|
48
53
|
DEFAULT_STREAM_MAX_RETRIES = 5
|
|
49
54
|
DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000
|
|
50
55
|
INITIAL_RETRY_DELAY_SECONDS = 0.2
|
|
@@ -74,15 +79,23 @@ class ModelClient(Protocol):
|
|
|
74
79
|
) -> "ModelClient":
|
|
75
80
|
"""Construct an independent client for a child Agent."""
|
|
76
81
|
|
|
82
|
+
def stop_retry(self) -> "None":
|
|
83
|
+
"""Stop retrying after the issued request completes."""
|
|
84
|
+
|
|
77
85
|
async def complete(
|
|
78
86
|
self,
|
|
79
87
|
prompt: "Prompt",
|
|
80
|
-
event_handler: "ModelStreamEventHandler" = NOOP_MODEL_STREAM_EVENT_HANDLER,
|
|
81
88
|
) -> "ModelResponse":
|
|
82
|
-
"""Return the
|
|
89
|
+
"""Return the output items and any provider usage for this request."""
|
|
83
90
|
|
|
84
91
|
|
|
85
92
|
class ModelControl(ModelClient, Protocol):
|
|
93
|
+
retry_error_code: "typing.Optional[RetryCodes]"
|
|
94
|
+
last_error: "typing.Optional[Exception]"
|
|
95
|
+
|
|
96
|
+
def set_retry_error_code(self, code: "typing.Optional[RetryCodes]") -> "None":
|
|
97
|
+
"""Select error codes or '*' for infinite retries. None restores normal retries."""
|
|
98
|
+
|
|
86
99
|
@property
|
|
87
100
|
def endpoint(self) -> "str":
|
|
88
101
|
"""Return the active API base URL, safe for display."""
|
|
@@ -117,6 +130,9 @@ class ResponsesProviderConfig:
|
|
|
117
130
|
model_slug: "typing.Union[str, None]" = None
|
|
118
131
|
http_headers: "typing.Dict[str, str]" = field(default_factory=dict, repr=False)
|
|
119
132
|
env_http_headers: "typing.Dict[str, str]" = field(default_factory=dict)
|
|
133
|
+
model_catalog: "typing.Dict[str, JSONDict]" = field(
|
|
134
|
+
default_factory=load_models_by_slug, repr=False, compare=False,
|
|
135
|
+
)
|
|
120
136
|
|
|
121
137
|
def __post_init__(self):
|
|
122
138
|
for name in ("http_headers", "env_http_headers"):
|
|
@@ -127,7 +143,7 @@ class ResponsesProviderConfig:
|
|
|
127
143
|
):
|
|
128
144
|
raise ValueError(name + " must be a table of strings")
|
|
129
145
|
if self.model_slug is not None and (
|
|
130
|
-
not isinstance(self.model_slug, str) or self.model_slug not in
|
|
146
|
+
not isinstance(self.model_slug, str) or self.model_slug not in self.model_catalog
|
|
131
147
|
):
|
|
132
148
|
raise ValueError("model_slug must name an entry in models.json")
|
|
133
149
|
if self.compat_api not in ("none", "chat_completions", "messages", "gemini"):
|
|
@@ -155,6 +171,7 @@ class ResponsesProviderConfig:
|
|
|
155
171
|
@classmethod
|
|
156
172
|
def from_mapping(
|
|
157
173
|
cls, selected: "typing.Mapping[str, typing.Any]",
|
|
174
|
+
model_catalog: "typing.Union[typing.Dict[str, JSONDict], None]" = None,
|
|
158
175
|
) -> "ResponsesProviderConfig":
|
|
159
176
|
provider_name = selected.get("model_provider", "openai")
|
|
160
177
|
provider = selected.get("model_providers", {}).get(provider_name)
|
|
@@ -201,6 +218,7 @@ class ResponsesProviderConfig:
|
|
|
201
218
|
raise ValueError("fallback_models must be an array of non-empty model IDs")
|
|
202
219
|
return cls(
|
|
203
220
|
model=selected["model"],
|
|
221
|
+
model_catalog=load_models_by_slug() if model_catalog is None else model_catalog,
|
|
204
222
|
model_slug=selected.get("model_slug"),
|
|
205
223
|
provider_name=provider_name,
|
|
206
224
|
base_url=provider["base_url"],
|
|
@@ -246,7 +264,7 @@ class ResponsesProviderConfig:
|
|
|
246
264
|
return max(int(self.stream_idle_timeout_ms), 1) / 1000.0
|
|
247
265
|
|
|
248
266
|
def metadata(self) -> "typing.Union[JSONDict, None]":
|
|
249
|
-
return model_metadata(self.model_slug or self.model)
|
|
267
|
+
return model_metadata(self.model_slug or self.model, self.model_catalog)
|
|
250
268
|
|
|
251
269
|
def use_responses_lite(self) -> "bool":
|
|
252
270
|
if self.responses_lite_override is not None:
|
|
@@ -376,15 +394,46 @@ def _filter_audio_inputs(items, metadata):
|
|
|
376
394
|
|
|
377
395
|
|
|
378
396
|
class ResponsesApiError(RuntimeError):
|
|
379
|
-
|
|
397
|
+
def __init__(
|
|
398
|
+
self,
|
|
399
|
+
message: "str",
|
|
400
|
+
http_status: "typing.Union[int, None]" = None,
|
|
401
|
+
error_code: "typing.Union[str, int, None]" = None,
|
|
402
|
+
) -> "None":
|
|
403
|
+
super().__init__(message)
|
|
404
|
+
self.http_status = http_status
|
|
405
|
+
self.error_code = error_code
|
|
406
|
+
|
|
407
|
+
def matches_code(self, code: "int") -> "bool":
|
|
408
|
+
return self.http_status == code or str(self.error_code) == str(code)
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def matches_retry_codes(error: "Exception", codes: "RetryCodes") -> "bool":
|
|
412
|
+
if codes == "*":
|
|
413
|
+
return True
|
|
414
|
+
selected = (codes,) if isinstance(codes, int) else codes
|
|
415
|
+
return isinstance(error, ResponsesApiError) and any(
|
|
416
|
+
error.matches_code(code) for code in selected
|
|
417
|
+
)
|
|
380
418
|
|
|
381
419
|
|
|
382
420
|
class ContextLengthExceeded(ResponsesApiError):
|
|
383
|
-
def __init__(
|
|
384
|
-
|
|
421
|
+
def __init__(
|
|
422
|
+
self,
|
|
423
|
+
message: "str",
|
|
424
|
+
http_status: "typing.Union[int, None]" = None,
|
|
425
|
+
error_code: "typing.Union[str, int, None]" = None,
|
|
426
|
+
) -> "None":
|
|
427
|
+
super().__init__(message, http_status, error_code)
|
|
385
428
|
self.usage: "typing.Union[typing.Dict[str, int], None]" = None
|
|
386
429
|
self.token_limit: "typing.Union[int, None]" = None
|
|
387
430
|
requested = re.search(r"requested\s+([0-9,]+)\s+tokens", message, re.IGNORECASE)
|
|
431
|
+
if requested is None:
|
|
432
|
+
requested = re.search(
|
|
433
|
+
r"input\s+token\s+count(?:\s*:\s*|\s*\()([0-9,]+)",
|
|
434
|
+
message,
|
|
435
|
+
re.IGNORECASE,
|
|
436
|
+
)
|
|
388
437
|
if requested is not None:
|
|
389
438
|
total = int(requested.group(1).replace(",", ""))
|
|
390
439
|
self.usage = {"total_tokens": total, "input_tokens": total}
|
|
@@ -401,6 +450,12 @@ class ContextLengthExceeded(ResponsesApiError):
|
|
|
401
450
|
message,
|
|
402
451
|
re.IGNORECASE,
|
|
403
452
|
)
|
|
453
|
+
if limit is None:
|
|
454
|
+
limit = re.search(
|
|
455
|
+
r"maximum\s+number\s+of\s+tokens\s+allowed\s*(?:is\s*|\()([0-9,]+)",
|
|
456
|
+
message,
|
|
457
|
+
re.IGNORECASE,
|
|
458
|
+
)
|
|
404
459
|
if limit is not None:
|
|
405
460
|
self.token_limit = int(limit.group(1).replace(",", ""))
|
|
406
461
|
|
|
@@ -422,8 +477,10 @@ class ResponsesRetryableError(ResponsesApiError):
|
|
|
422
477
|
self,
|
|
423
478
|
message: "str",
|
|
424
479
|
retry_delay_seconds: "typing.Union[float, None]" = None,
|
|
480
|
+
http_status: "typing.Union[int, None]" = None,
|
|
481
|
+
error_code: "typing.Union[str, int, None]" = None,
|
|
425
482
|
) -> "None":
|
|
426
|
-
super().__init__(message)
|
|
483
|
+
super().__init__(message, http_status, error_code)
|
|
427
484
|
self.retry_delay_seconds = retry_delay_seconds
|
|
428
485
|
|
|
429
486
|
|
|
@@ -474,6 +531,21 @@ class ResponsesModelClient:
|
|
|
474
531
|
self._user_agent = user_agent or build_user_agent(originator)
|
|
475
532
|
self._openai_subagent = openai_subagent
|
|
476
533
|
self._model_cooldowns: "typing.Dict[str, float]" = {}
|
|
534
|
+
self.retry_error_code: "typing.Optional[RetryCodes]" = None
|
|
535
|
+
self.last_error: "typing.Optional[Exception]" = None
|
|
536
|
+
self._retry_wakeup: "typing.Union[asyncio.Event, None]" = None
|
|
537
|
+
self._retry_stopped = False
|
|
538
|
+
|
|
539
|
+
def set_retry_error_code(self, code: "typing.Optional[RetryCodes]") -> "None":
|
|
540
|
+
if code != self.retry_error_code:
|
|
541
|
+
self.retry_error_code = code
|
|
542
|
+
if self._retry_wakeup is not None:
|
|
543
|
+
self._retry_wakeup.set()
|
|
544
|
+
|
|
545
|
+
def stop_retry(self) -> "None":
|
|
546
|
+
if self._retry_wakeup is not None:
|
|
547
|
+
self._retry_stopped = True
|
|
548
|
+
self._retry_wakeup.set()
|
|
477
549
|
|
|
478
550
|
@property
|
|
479
551
|
def model(self) -> "str":
|
|
@@ -567,10 +639,13 @@ class ResponsesModelClient:
|
|
|
567
639
|
async def complete(
|
|
568
640
|
self,
|
|
569
641
|
prompt: "Prompt",
|
|
570
|
-
event_handler: "ModelStreamEventHandler" =
|
|
642
|
+
event_handler: "typing.Optional[ModelStreamEventHandler]" = None,
|
|
571
643
|
) -> "ModelResponse":
|
|
572
644
|
retries = 0
|
|
573
645
|
max_retries = self._config.effective_stream_max_retries()
|
|
646
|
+
self.last_error = None
|
|
647
|
+
self._retry_stopped = False
|
|
648
|
+
self._retry_wakeup = asyncio.Event()
|
|
574
649
|
models = tuple(dict.fromkeys((self.model,) + self._config.fallback_models))
|
|
575
650
|
now = monotonic()
|
|
576
651
|
self._model_cooldowns = {
|
|
@@ -591,74 +666,103 @@ class ResponsesModelClient:
|
|
|
591
666
|
if first_model == self.model
|
|
592
667
|
else self.with_overrides(model=first_model)
|
|
593
668
|
)
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
or retries >= max_retries
|
|
618
|
-
):
|
|
619
|
-
cooldown = self._config.fallback_cooldown_seconds
|
|
620
|
-
if len(models) > 1 and cooldown > 0:
|
|
621
|
-
self._model_cooldowns[request_client.model] = (
|
|
622
|
-
monotonic() + cooldown
|
|
623
|
-
)
|
|
624
|
-
fallback_model = next(fallback_models, None)
|
|
625
|
-
if fallback_model is None:
|
|
669
|
+
with EventScope.worker_events(event_handler) as worker_context:
|
|
670
|
+
try:
|
|
671
|
+
while True:
|
|
672
|
+
if self._retry_stopped:
|
|
673
|
+
raise ModelRequestInterrupted()
|
|
674
|
+
was_infinite = self.retry_error_code is not None
|
|
675
|
+
try:
|
|
676
|
+
response = await asyncio.to_thread(
|
|
677
|
+
worker_context.run, request_client._complete_sync, prompt,
|
|
678
|
+
)
|
|
679
|
+
except (asyncio.CancelledError, ModelRequestInterrupted):
|
|
680
|
+
raise
|
|
681
|
+
except Exception as exc:
|
|
682
|
+
self.last_error = exc
|
|
683
|
+
if self._retry_stopped:
|
|
684
|
+
raise ModelRequestInterrupted() from exc
|
|
685
|
+
infinite = self.retry_error_code is not None
|
|
686
|
+
if was_infinite and not infinite:
|
|
687
|
+
raise
|
|
688
|
+
if infinite:
|
|
689
|
+
if not matches_retry_codes(exc, self.retry_error_code):
|
|
690
|
+
raise
|
|
691
|
+
elif not isinstance(exc, (ResponsesRetryableError, ResponsesModelUnavailableError)):
|
|
626
692
|
raise
|
|
627
|
-
|
|
693
|
+
elif (
|
|
694
|
+
isinstance(exc, ResponsesModelUnavailableError)
|
|
695
|
+
or (isinstance(exc, ResponsesFirstDataTimeout) and len(models) > 1)
|
|
696
|
+
or retries >= max_retries
|
|
697
|
+
):
|
|
698
|
+
cooldown = self._config.fallback_cooldown_seconds
|
|
699
|
+
if len(models) > 1 and cooldown > 0:
|
|
700
|
+
self._model_cooldowns[request_client.model] = (
|
|
701
|
+
monotonic() + cooldown
|
|
702
|
+
)
|
|
703
|
+
fallback_model = next(fallback_models, None)
|
|
704
|
+
if fallback_model is None:
|
|
705
|
+
raise
|
|
706
|
+
EventScope.emit(
|
|
707
|
+
StreamErrorEvent(
|
|
708
|
+
f"Falling back: {request_client.model} -> {fallback_model}",
|
|
709
|
+
0,
|
|
710
|
+
max_retries,
|
|
711
|
+
0.0,
|
|
712
|
+
str(exc),
|
|
713
|
+
)
|
|
714
|
+
)
|
|
715
|
+
request_client = self.with_overrides(model=fallback_model)
|
|
716
|
+
retries = 0
|
|
717
|
+
continue
|
|
718
|
+
retries += 1
|
|
719
|
+
delay_seconds = (
|
|
720
|
+
exc.retry_delay_seconds
|
|
721
|
+
if isinstance(exc, ResponsesRetryableError) else None
|
|
722
|
+
)
|
|
723
|
+
if delay_seconds is None:
|
|
724
|
+
delay_seconds = self._retry_delay_seconds(retries)
|
|
725
|
+
self._retry_wakeup.clear()
|
|
726
|
+
EventScope.emit(
|
|
628
727
|
StreamErrorEvent(
|
|
629
|
-
f"
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
0
|
|
728
|
+
f"Reconnecting... {retries}/∞"
|
|
729
|
+
if infinite else f"Reconnecting... {retries}/{max_retries}",
|
|
730
|
+
retries,
|
|
731
|
+
0 if infinite else max_retries,
|
|
732
|
+
delay_seconds,
|
|
633
733
|
str(exc),
|
|
634
734
|
)
|
|
635
735
|
)
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
736
|
+
if delay_seconds > 0:
|
|
737
|
+
waiter = asyncio.ensure_future(self._retry_wakeup.wait())
|
|
738
|
+
try:
|
|
739
|
+
await asyncio.wait({waiter}, timeout=delay_seconds)
|
|
740
|
+
finally:
|
|
741
|
+
if not waiter.done():
|
|
742
|
+
waiter.cancel()
|
|
743
|
+
try:
|
|
744
|
+
await waiter
|
|
745
|
+
except asyncio.CancelledError:
|
|
746
|
+
pass
|
|
747
|
+
if self._retry_stopped:
|
|
748
|
+
raise ModelRequestInterrupted() from exc
|
|
749
|
+
if infinite and self.retry_error_code is None:
|
|
750
|
+
raise
|
|
751
|
+
if (
|
|
752
|
+
self.retry_error_code is not None
|
|
753
|
+
and not matches_retry_codes(exc, self.retry_error_code)
|
|
754
|
+
):
|
|
755
|
+
raise
|
|
756
|
+
else:
|
|
757
|
+
self._model_cooldowns.pop(request_client.model, None)
|
|
758
|
+
self.last_error = None
|
|
759
|
+
return response
|
|
760
|
+
finally:
|
|
761
|
+
self._retry_wakeup = None
|
|
657
762
|
|
|
658
763
|
def _complete_sync(
|
|
659
764
|
self,
|
|
660
765
|
prompt: "Prompt",
|
|
661
|
-
event_handler: "ModelStreamEventHandler",
|
|
662
766
|
) -> "ModelResponse":
|
|
663
767
|
payload = self._build_payload(prompt)
|
|
664
768
|
session_id = payload["prompt_cache_key"]
|
|
@@ -707,7 +811,7 @@ class ResponsesModelClient:
|
|
|
707
811
|
f"{error_body[:500]}"
|
|
708
812
|
)
|
|
709
813
|
if _is_context_length_error_message(error_body):
|
|
710
|
-
raise ContextLengthExceeded(message)
|
|
814
|
+
raise ContextLengthExceeded(message, http_status=response.status_code)
|
|
711
815
|
if response.status_code >= 500 or response.status_code in (408, 429):
|
|
712
816
|
raise ResponsesRetryableError(
|
|
713
817
|
message,
|
|
@@ -715,10 +819,11 @@ class ResponsesModelClient:
|
|
|
715
819
|
"rate_limit_exceeded" if response.status_code == 429 else "",
|
|
716
820
|
error_body,
|
|
717
821
|
),
|
|
822
|
+
http_status=response.status_code,
|
|
718
823
|
)
|
|
719
824
|
if response.status_code in (403, 404):
|
|
720
|
-
raise ResponsesModelUnavailableError(message)
|
|
721
|
-
raise ResponsesApiError(message)
|
|
825
|
+
raise ResponsesModelUnavailableError(message, http_status=response.status_code)
|
|
826
|
+
raise ResponsesApiError(message, http_status=response.status_code)
|
|
722
827
|
if first_timeout is not None:
|
|
723
828
|
remaining = first_timeout - (monotonic() - diagnostics.started_at)
|
|
724
829
|
if remaining <= 0:
|
|
@@ -735,7 +840,6 @@ class ResponsesModelClient:
|
|
|
735
840
|
tracked_lines = self._track_stream_lines(lines, diagnostics)
|
|
736
841
|
result = self._parse_stream(
|
|
737
842
|
tracked_lines,
|
|
738
|
-
event_handler,
|
|
739
843
|
diagnostics=diagnostics,
|
|
740
844
|
session_id=session_id,
|
|
741
845
|
)
|
|
@@ -761,7 +865,7 @@ class ResponsesModelClient:
|
|
|
761
865
|
exc.first_data_seconds = diagnostics.first_data_seconds
|
|
762
866
|
raise
|
|
763
867
|
finally:
|
|
764
|
-
|
|
868
|
+
EventScope.emit(ModelRequestTimingEvent(
|
|
765
869
|
self.model, monotonic() - diagnostics.started_at,
|
|
766
870
|
diagnostics.first_data_seconds, "completed" if completed else "failed",
|
|
767
871
|
))
|
|
@@ -1001,13 +1105,44 @@ class ResponsesModelClient:
|
|
|
1001
1105
|
def _parse_stream(
|
|
1002
1106
|
self,
|
|
1003
1107
|
response,
|
|
1004
|
-
event_handler: "ModelStreamEventHandler",
|
|
1005
1108
|
diagnostics: "typing.Union[_StreamDiagnostics, None]" = None,
|
|
1006
1109
|
session_id: "typing.Union[str, None]" = None,
|
|
1007
1110
|
) -> "ModelResponse":
|
|
1008
1111
|
items: "typing.List[typing.Union[typing.Union[AssistantMessage, ToolCall], ReasoningItem]]" = ([])
|
|
1009
|
-
saw_completed = False
|
|
1010
1112
|
last_event_type = ""
|
|
1113
|
+
reasoning_item_id: "typing.Union[object, None]" = None
|
|
1114
|
+
raw_reasoning_chunks: "typing.List[str]" = []
|
|
1115
|
+
summary_index: "typing.Union[object, None]" = None
|
|
1116
|
+
summary_chunks: "typing.List[str]" = []
|
|
1117
|
+
last_reasoning = ""
|
|
1118
|
+
last_reasoning_emit_at: "typing.Union[float, None]" = None
|
|
1119
|
+
|
|
1120
|
+
def flush_reasoning(force: "bool" = True) -> "None":
|
|
1121
|
+
nonlocal last_reasoning, last_reasoning_emit_at
|
|
1122
|
+
if not raw_reasoning_chunks and not summary_chunks:
|
|
1123
|
+
return
|
|
1124
|
+
now = monotonic()
|
|
1125
|
+
if (
|
|
1126
|
+
not force
|
|
1127
|
+
and last_reasoning_emit_at is not None
|
|
1128
|
+
and now - last_reasoning_emit_at < 0.08
|
|
1129
|
+
):
|
|
1130
|
+
return
|
|
1131
|
+
raw_text = "".join(raw_reasoning_chunks)
|
|
1132
|
+
text = raw_text if raw_text.strip() else "".join(summary_chunks)
|
|
1133
|
+
if text.strip() and text != last_reasoning:
|
|
1134
|
+
last_reasoning = text
|
|
1135
|
+
last_reasoning_emit_at = now
|
|
1136
|
+
EventScope.emit(ReasoningEvent(text))
|
|
1137
|
+
|
|
1138
|
+
def clear_reasoning_state() -> "None":
|
|
1139
|
+
nonlocal reasoning_item_id, summary_index, last_reasoning, last_reasoning_emit_at
|
|
1140
|
+
reasoning_item_id = None
|
|
1141
|
+
raw_reasoning_chunks.clear()
|
|
1142
|
+
summary_index = None
|
|
1143
|
+
summary_chunks.clear()
|
|
1144
|
+
last_reasoning = ""
|
|
1145
|
+
last_reasoning_emit_at = None
|
|
1011
1146
|
|
|
1012
1147
|
for event_name, data in self._iter_sse_events(response, diagnostics):
|
|
1013
1148
|
if not data:
|
|
@@ -1024,10 +1159,37 @@ class ResponsesModelClient:
|
|
|
1024
1159
|
diagnostics.last_event_type = last_event_type
|
|
1025
1160
|
|
|
1026
1161
|
if event_type == "response.output_text.delta":
|
|
1027
|
-
|
|
1162
|
+
flush_reasoning()
|
|
1163
|
+
clear_reasoning_state()
|
|
1164
|
+
EventScope.emit(AssistantDeltaEvent(str(payload.get("delta", ""))))
|
|
1165
|
+
continue
|
|
1166
|
+
|
|
1167
|
+
if event_type in (
|
|
1168
|
+
"response.reasoning_text.delta",
|
|
1169
|
+
"response.reasoning_summary_text.delta",
|
|
1170
|
+
):
|
|
1171
|
+
item_id = payload.get("item_id")
|
|
1172
|
+
if item_id != reasoning_item_id:
|
|
1173
|
+
flush_reasoning()
|
|
1174
|
+
clear_reasoning_state()
|
|
1175
|
+
reasoning_item_id = item_id
|
|
1176
|
+
|
|
1177
|
+
if event_type == "response.reasoning_text.delta":
|
|
1178
|
+
raw_reasoning_chunks.append(str(payload.get("delta", "")))
|
|
1179
|
+
else:
|
|
1180
|
+
part_index = payload.get("summary_index", 0)
|
|
1181
|
+
if part_index != summary_index:
|
|
1182
|
+
flush_reasoning()
|
|
1183
|
+
summary_index = part_index
|
|
1184
|
+
summary_chunks.clear()
|
|
1185
|
+
if not raw_reasoning_chunks:
|
|
1186
|
+
last_reasoning_emit_at = None
|
|
1187
|
+
summary_chunks.append(str(payload.get("delta", "")))
|
|
1188
|
+
flush_reasoning(force=False)
|
|
1028
1189
|
continue
|
|
1029
1190
|
|
|
1030
1191
|
if event_type == "response.output_item.done":
|
|
1192
|
+
flush_reasoning()
|
|
1031
1193
|
item_payload = payload.get("item", {})
|
|
1032
1194
|
if (
|
|
1033
1195
|
isinstance(item_payload, dict)
|
|
@@ -1040,7 +1202,7 @@ class ResponsesModelClient:
|
|
|
1040
1202
|
else:
|
|
1041
1203
|
action_payload = {}
|
|
1042
1204
|
queries = action_payload.get("queries")
|
|
1043
|
-
|
|
1205
|
+
EventScope.emit(
|
|
1044
1206
|
ToolCalledEvent(
|
|
1045
1207
|
call_id=str(item_payload.get("id", "web_search")),
|
|
1046
1208
|
tool_name="web_search",
|
|
@@ -1075,14 +1237,21 @@ class ResponsesModelClient:
|
|
|
1075
1237
|
|
|
1076
1238
|
parsed = self._parse_output_item(item_payload)
|
|
1077
1239
|
if parsed is not None:
|
|
1078
|
-
if isinstance(parsed,
|
|
1079
|
-
|
|
1240
|
+
if isinstance(parsed, ReasoningItem):
|
|
1241
|
+
streamed_raw = "".join(raw_reasoning_chunks) if item_payload.get("id") == reasoning_item_id else ""
|
|
1242
|
+
text = reasoning_item_text(parsed, streamed_raw)
|
|
1243
|
+
if text and text != last_reasoning:
|
|
1244
|
+
EventScope.emit(ReasoningEvent(text))
|
|
1245
|
+
clear_reasoning_state()
|
|
1246
|
+
elif isinstance(parsed, ToolCall):
|
|
1247
|
+
EventScope.emit(ToolCalledEvent(parsed.call_id, parsed.name))
|
|
1080
1248
|
items.append(parsed)
|
|
1081
1249
|
if diagnostics is not None:
|
|
1082
1250
|
diagnostics.output_items_received += 1
|
|
1083
1251
|
continue
|
|
1084
1252
|
|
|
1085
1253
|
if event_type == "response.completed":
|
|
1254
|
+
flush_reasoning()
|
|
1086
1255
|
response_payload = payload.get("response")
|
|
1087
1256
|
usage = None
|
|
1088
1257
|
if isinstance(response_payload, dict):
|
|
@@ -1091,11 +1260,11 @@ class ResponsesModelClient:
|
|
|
1091
1260
|
usage = dict(response_usage)
|
|
1092
1261
|
elif isinstance(payload.get("usage"), dict):
|
|
1093
1262
|
usage = dict(payload["usage"])
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
break
|
|
1263
|
+
EventScope.emit(TokenCountEvent(usage))
|
|
1264
|
+
return ModelResponse(items=items, usage=usage)
|
|
1097
1265
|
|
|
1098
1266
|
if event_type == "response.incomplete":
|
|
1267
|
+
flush_reasoning()
|
|
1099
1268
|
partial_items = tuple(items)
|
|
1100
1269
|
reason = self._response_incomplete_reason(payload)
|
|
1101
1270
|
raise ResponsesIncompleteError(
|
|
@@ -1112,12 +1281,9 @@ class ResponsesModelClient:
|
|
|
1112
1281
|
if event_type == "response.failed":
|
|
1113
1282
|
self._raise_response_failed_error(payload, session_id)
|
|
1114
1283
|
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
)
|
|
1119
|
-
|
|
1120
|
-
return ModelResponse(items=items)
|
|
1284
|
+
raise ResponsesRetryableError(
|
|
1285
|
+
self._format_incomplete_stream_error(last_event_type, len(items), session_id)
|
|
1286
|
+
)
|
|
1121
1287
|
|
|
1122
1288
|
@staticmethod
|
|
1123
1289
|
def _parse_output_item(
|
|
@@ -1364,25 +1530,31 @@ class ResponsesModelClient:
|
|
|
1364
1530
|
)
|
|
1365
1531
|
|
|
1366
1532
|
message = str(error.get("message") or "responses stream failed")
|
|
1367
|
-
|
|
1533
|
+
error_code = error.get("code")
|
|
1534
|
+
if error_code is None:
|
|
1535
|
+
error_code = error.get("type")
|
|
1536
|
+
http_status = error.get("http_status")
|
|
1537
|
+
code = str(error_code or "").strip()
|
|
1368
1538
|
formatted = self._format_response_failed_error(message, code, session_id)
|
|
1369
1539
|
if code == "context_length_exceeded" or _is_context_length_error_message(
|
|
1370
1540
|
message
|
|
1371
1541
|
):
|
|
1372
|
-
raise ContextLengthExceeded(formatted)
|
|
1542
|
+
raise ContextLengthExceeded(formatted, http_status=http_status, error_code=error_code)
|
|
1373
1543
|
if code in {"model_not_found", "model_not_available", "permission_denied"}:
|
|
1374
|
-
raise ResponsesModelUnavailableError(formatted)
|
|
1544
|
+
raise ResponsesModelUnavailableError(formatted, http_status=http_status, error_code=error_code)
|
|
1375
1545
|
if code in {
|
|
1376
1546
|
"insufficient_quota",
|
|
1377
1547
|
"invalid_prompt",
|
|
1378
1548
|
"model_output_invalid",
|
|
1379
1549
|
"usage_not_included",
|
|
1380
1550
|
}:
|
|
1381
|
-
raise ResponsesApiError(formatted)
|
|
1551
|
+
raise ResponsesApiError(formatted, http_status=http_status, error_code=error_code)
|
|
1382
1552
|
|
|
1383
1553
|
raise ResponsesRetryableError(
|
|
1384
1554
|
formatted,
|
|
1385
1555
|
retry_delay_seconds=self._try_parse_retry_after_seconds(code, message),
|
|
1556
|
+
http_status=http_status,
|
|
1557
|
+
error_code=error_code,
|
|
1386
1558
|
)
|
|
1387
1559
|
|
|
1388
1560
|
def _format_incomplete_stream_error(
|
|
@@ -1516,6 +1688,8 @@ def _is_context_length_error_message(message: "str") -> "bool":
|
|
|
1516
1688
|
or "maximum context length" in lower
|
|
1517
1689
|
or "exceeds the context window" in lower
|
|
1518
1690
|
or "exceeded the context window" in lower
|
|
1691
|
+
or "exceeds the maximum number of tokens" in lower
|
|
1692
|
+
or "exceeded the maximum number of tokens" in lower
|
|
1519
1693
|
)
|
|
1520
1694
|
|
|
1521
1695
|
|