python-codex 0.6.2__py3-none-any.whl → 0.7.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.
- pycodex/agent.py +325 -314
- pycodex/bootstrap.py +8 -0
- pycodex/config.py +4 -2
- pycodex/context.py +32 -11
- pycodex/events.py +116 -7
- pycodex/model.py +214 -99
- pycodex/multi_agents.py +11 -40
- pycodex/prompts/models.json +351 -6
- pycodex/protocol.py +1 -0
- pycodex/runtime.py +173 -127
- pycodex/tools/__init__.py +1 -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 +15 -3
- pycodex/utils/compactor.py +28 -98
- pycodex/utils/compat.py +6 -0
- pycodex/utils/event_helpers.py +9 -0
- pycodex/utils/http_headers.py +25 -0
- pycodex/utils/model_metadata.py +5 -4
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/METADATA +34 -8
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/RECORD +35 -34
- responses_server/app.py +6 -0
- responses_server/config.py +4 -1
- responses_server/gemini_api.py +40 -13
- responses_server/messages_api.py +12 -6
- responses_server/payload_processors.py +1 -1
- responses_server/request_translation.py +55 -13
- responses_server/stream_router.py +9 -0
- responses_server/transport.py +24 -11
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/WHEEL +0 -0
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.dist-info}/entry_points.txt +0 -0
- {python_codex-0.6.2.dist-info → python_codex-0.7.0.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,22 @@ 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
|
|
19
|
+
from .utils.http_headers import build_http_headers
|
|
20
20
|
|
|
21
21
|
from .events import (
|
|
22
|
+
BASE_EVENT_HANDLER,
|
|
22
23
|
AssistantDeltaEvent,
|
|
24
|
+
EventScope,
|
|
23
25
|
ModelEvent,
|
|
26
|
+
ModelRequestInterrupted,
|
|
24
27
|
ModelRequestTimingEvent,
|
|
25
28
|
StreamErrorEvent,
|
|
26
29
|
TokenCountEvent,
|
|
27
30
|
ToolCalledEvent,
|
|
28
31
|
)
|
|
29
|
-
from .utils.model_metadata import model_metadata
|
|
32
|
+
from .utils.model_metadata import load_models_by_slug, model_metadata
|
|
30
33
|
from .protocol import (
|
|
31
34
|
AssistantMessage,
|
|
32
35
|
JSONDict,
|
|
@@ -43,7 +46,8 @@ from .utils import build_user_agent, uuid7_string
|
|
|
43
46
|
DEFAULT_ORIGINATOR = "pycodex"
|
|
44
47
|
RESPONSES_LITE_HEADER = "x-openai-internal-codex-responses-lite"
|
|
45
48
|
ModelStreamEventHandler = Callable[[ModelEvent], None]
|
|
46
|
-
|
|
49
|
+
RetryCodes = typing.Union[int, typing.FrozenSet[int], Literal["*"]]
|
|
50
|
+
NOOP_MODEL_STREAM_EVENT_HANDLER: "ModelStreamEventHandler" = BASE_EVENT_HANDLER
|
|
47
51
|
DEFAULT_STREAM_MAX_RETRIES = 5
|
|
48
52
|
DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000
|
|
49
53
|
INITIAL_RETRY_DELAY_SECONDS = 0.2
|
|
@@ -73,15 +77,23 @@ class ModelClient(Protocol):
|
|
|
73
77
|
) -> "ModelClient":
|
|
74
78
|
"""Construct an independent client for a child Agent."""
|
|
75
79
|
|
|
80
|
+
def stop_retry(self) -> "None":
|
|
81
|
+
"""Stop retrying after the issued request completes."""
|
|
82
|
+
|
|
76
83
|
async def complete(
|
|
77
84
|
self,
|
|
78
85
|
prompt: "Prompt",
|
|
79
|
-
event_handler: "ModelStreamEventHandler" = NOOP_MODEL_STREAM_EVENT_HANDLER,
|
|
80
86
|
) -> "ModelResponse":
|
|
81
|
-
"""Return the
|
|
87
|
+
"""Return the output items and any provider usage for this request."""
|
|
82
88
|
|
|
83
89
|
|
|
84
90
|
class ModelControl(ModelClient, Protocol):
|
|
91
|
+
retry_error_code: "typing.Optional[RetryCodes]"
|
|
92
|
+
last_error: "typing.Optional[Exception]"
|
|
93
|
+
|
|
94
|
+
def set_retry_error_code(self, code: "typing.Optional[RetryCodes]") -> "None":
|
|
95
|
+
"""Select error codes or '*' for infinite retries. None restores normal retries."""
|
|
96
|
+
|
|
85
97
|
@property
|
|
86
98
|
def endpoint(self) -> "str":
|
|
87
99
|
"""Return the active API base URL, safe for display."""
|
|
@@ -113,8 +125,25 @@ class ResponsesProviderConfig:
|
|
|
113
125
|
fallback_cooldown_seconds: "int" = 900
|
|
114
126
|
stream_first_data_timeout_ms: "typing.Union[int, None]" = None
|
|
115
127
|
compat_api: "str" = "none"
|
|
128
|
+
model_slug: "typing.Union[str, None]" = None
|
|
129
|
+
http_headers: "typing.Dict[str, str]" = field(default_factory=dict, repr=False)
|
|
130
|
+
env_http_headers: "typing.Dict[str, str]" = field(default_factory=dict)
|
|
131
|
+
model_catalog: "typing.Dict[str, JSONDict]" = field(
|
|
132
|
+
default_factory=load_models_by_slug, repr=False, compare=False,
|
|
133
|
+
)
|
|
116
134
|
|
|
117
135
|
def __post_init__(self):
|
|
136
|
+
for name in ("http_headers", "env_http_headers"):
|
|
137
|
+
headers = getattr(self, name)
|
|
138
|
+
if not isinstance(headers, dict) or any(
|
|
139
|
+
not isinstance(key, str) or not isinstance(value, str)
|
|
140
|
+
for key, value in headers.items()
|
|
141
|
+
):
|
|
142
|
+
raise ValueError(name + " must be a table of strings")
|
|
143
|
+
if self.model_slug is not None and (
|
|
144
|
+
not isinstance(self.model_slug, str) or self.model_slug not in self.model_catalog
|
|
145
|
+
):
|
|
146
|
+
raise ValueError("model_slug must name an entry in models.json")
|
|
118
147
|
if self.compat_api not in ("none", "chat_completions", "messages", "gemini"):
|
|
119
148
|
raise ValueError("compat_api must be none, chat_completions, messages or gemini")
|
|
120
149
|
cooldown = self.fallback_cooldown_seconds
|
|
@@ -140,6 +169,7 @@ class ResponsesProviderConfig:
|
|
|
140
169
|
@classmethod
|
|
141
170
|
def from_mapping(
|
|
142
171
|
cls, selected: "typing.Mapping[str, typing.Any]",
|
|
172
|
+
model_catalog: "typing.Union[typing.Dict[str, JSONDict], None]" = None,
|
|
143
173
|
) -> "ResponsesProviderConfig":
|
|
144
174
|
provider_name = selected.get("model_provider", "openai")
|
|
145
175
|
provider = selected.get("model_providers", {}).get(provider_name)
|
|
@@ -186,9 +216,13 @@ class ResponsesProviderConfig:
|
|
|
186
216
|
raise ValueError("fallback_models must be an array of non-empty model IDs")
|
|
187
217
|
return cls(
|
|
188
218
|
model=selected["model"],
|
|
219
|
+
model_catalog=load_models_by_slug() if model_catalog is None else model_catalog,
|
|
220
|
+
model_slug=selected.get("model_slug"),
|
|
189
221
|
provider_name=provider_name,
|
|
190
222
|
base_url=provider["base_url"],
|
|
191
223
|
api_key_env=api_key_env,
|
|
224
|
+
http_headers=provider.get("http_headers", {}),
|
|
225
|
+
env_http_headers=provider.get("env_http_headers", {}),
|
|
192
226
|
compat_api=compat_api,
|
|
193
227
|
wire_api=wire_api,
|
|
194
228
|
query_params=query_params,
|
|
@@ -228,7 +262,7 @@ class ResponsesProviderConfig:
|
|
|
228
262
|
return max(int(self.stream_idle_timeout_ms), 1) / 1000.0
|
|
229
263
|
|
|
230
264
|
def metadata(self) -> "typing.Union[JSONDict, None]":
|
|
231
|
-
return model_metadata(self.model)
|
|
265
|
+
return model_metadata(self.model_slug or self.model, self.model_catalog)
|
|
232
266
|
|
|
233
267
|
def use_responses_lite(self) -> "bool":
|
|
234
268
|
if self.responses_lite_override is not None:
|
|
@@ -358,12 +392,37 @@ def _filter_audio_inputs(items, metadata):
|
|
|
358
392
|
|
|
359
393
|
|
|
360
394
|
class ResponsesApiError(RuntimeError):
|
|
361
|
-
|
|
395
|
+
def __init__(
|
|
396
|
+
self,
|
|
397
|
+
message: "str",
|
|
398
|
+
http_status: "typing.Union[int, None]" = None,
|
|
399
|
+
error_code: "typing.Union[str, int, None]" = None,
|
|
400
|
+
) -> "None":
|
|
401
|
+
super().__init__(message)
|
|
402
|
+
self.http_status = http_status
|
|
403
|
+
self.error_code = error_code
|
|
404
|
+
|
|
405
|
+
def matches_code(self, code: "int") -> "bool":
|
|
406
|
+
return self.http_status == code or str(self.error_code) == str(code)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def matches_retry_codes(error: "Exception", codes: "RetryCodes") -> "bool":
|
|
410
|
+
if codes == "*":
|
|
411
|
+
return True
|
|
412
|
+
selected = (codes,) if isinstance(codes, int) else codes
|
|
413
|
+
return isinstance(error, ResponsesApiError) and any(
|
|
414
|
+
error.matches_code(code) for code in selected
|
|
415
|
+
)
|
|
362
416
|
|
|
363
417
|
|
|
364
418
|
class ContextLengthExceeded(ResponsesApiError):
|
|
365
|
-
def __init__(
|
|
366
|
-
|
|
419
|
+
def __init__(
|
|
420
|
+
self,
|
|
421
|
+
message: "str",
|
|
422
|
+
http_status: "typing.Union[int, None]" = None,
|
|
423
|
+
error_code: "typing.Union[str, int, None]" = None,
|
|
424
|
+
) -> "None":
|
|
425
|
+
super().__init__(message, http_status, error_code)
|
|
367
426
|
self.usage: "typing.Union[typing.Dict[str, int], None]" = None
|
|
368
427
|
self.token_limit: "typing.Union[int, None]" = None
|
|
369
428
|
requested = re.search(r"requested\s+([0-9,]+)\s+tokens", message, re.IGNORECASE)
|
|
@@ -404,8 +463,10 @@ class ResponsesRetryableError(ResponsesApiError):
|
|
|
404
463
|
self,
|
|
405
464
|
message: "str",
|
|
406
465
|
retry_delay_seconds: "typing.Union[float, None]" = None,
|
|
466
|
+
http_status: "typing.Union[int, None]" = None,
|
|
467
|
+
error_code: "typing.Union[str, int, None]" = None,
|
|
407
468
|
) -> "None":
|
|
408
|
-
super().__init__(message)
|
|
469
|
+
super().__init__(message, http_status, error_code)
|
|
409
470
|
self.retry_delay_seconds = retry_delay_seconds
|
|
410
471
|
|
|
411
472
|
|
|
@@ -447,12 +508,30 @@ class ResponsesModelClient:
|
|
|
447
508
|
openai_subagent: "typing.Union[str, None]" = None,
|
|
448
509
|
) -> "None":
|
|
449
510
|
self._config = config
|
|
511
|
+
self._provider_headers = build_http_headers(
|
|
512
|
+
config.http_headers, config.env_http_headers,
|
|
513
|
+
)
|
|
450
514
|
self._timeout_seconds = timeout_seconds
|
|
451
515
|
self._session_id = session_id or uuid7_string()
|
|
452
516
|
self.recording_metadata = ModelRecordingMetadata(originator, config.provider_name)
|
|
453
517
|
self._user_agent = user_agent or build_user_agent(originator)
|
|
454
518
|
self._openai_subagent = openai_subagent
|
|
455
519
|
self._model_cooldowns: "typing.Dict[str, float]" = {}
|
|
520
|
+
self.retry_error_code: "typing.Optional[RetryCodes]" = None
|
|
521
|
+
self.last_error: "typing.Optional[Exception]" = None
|
|
522
|
+
self._retry_wakeup: "typing.Union[asyncio.Event, None]" = None
|
|
523
|
+
self._retry_stopped = False
|
|
524
|
+
|
|
525
|
+
def set_retry_error_code(self, code: "typing.Optional[RetryCodes]") -> "None":
|
|
526
|
+
if code != self.retry_error_code:
|
|
527
|
+
self.retry_error_code = code
|
|
528
|
+
if self._retry_wakeup is not None:
|
|
529
|
+
self._retry_wakeup.set()
|
|
530
|
+
|
|
531
|
+
def stop_retry(self) -> "None":
|
|
532
|
+
if self._retry_wakeup is not None:
|
|
533
|
+
self._retry_stopped = True
|
|
534
|
+
self._retry_wakeup.set()
|
|
456
535
|
|
|
457
536
|
@property
|
|
458
537
|
def model(self) -> "str":
|
|
@@ -546,10 +625,13 @@ class ResponsesModelClient:
|
|
|
546
625
|
async def complete(
|
|
547
626
|
self,
|
|
548
627
|
prompt: "Prompt",
|
|
549
|
-
event_handler: "ModelStreamEventHandler" =
|
|
628
|
+
event_handler: "typing.Optional[ModelStreamEventHandler]" = None,
|
|
550
629
|
) -> "ModelResponse":
|
|
551
630
|
retries = 0
|
|
552
631
|
max_retries = self._config.effective_stream_max_retries()
|
|
632
|
+
self.last_error = None
|
|
633
|
+
self._retry_stopped = False
|
|
634
|
+
self._retry_wakeup = asyncio.Event()
|
|
553
635
|
models = tuple(dict.fromkeys((self.model,) + self._config.fallback_models))
|
|
554
636
|
now = monotonic()
|
|
555
637
|
self._model_cooldowns = {
|
|
@@ -570,74 +652,103 @@ class ResponsesModelClient:
|
|
|
570
652
|
if first_model == self.model
|
|
571
653
|
else self.with_overrides(model=first_model)
|
|
572
654
|
)
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
or retries >= max_retries
|
|
597
|
-
):
|
|
598
|
-
cooldown = self._config.fallback_cooldown_seconds
|
|
599
|
-
if len(models) > 1 and cooldown > 0:
|
|
600
|
-
self._model_cooldowns[request_client.model] = (
|
|
601
|
-
monotonic() + cooldown
|
|
602
|
-
)
|
|
603
|
-
fallback_model = next(fallback_models, None)
|
|
604
|
-
if fallback_model is None:
|
|
655
|
+
with EventScope.worker_events(event_handler) as worker_context:
|
|
656
|
+
try:
|
|
657
|
+
while True:
|
|
658
|
+
if self._retry_stopped:
|
|
659
|
+
raise ModelRequestInterrupted()
|
|
660
|
+
was_infinite = self.retry_error_code is not None
|
|
661
|
+
try:
|
|
662
|
+
response = await asyncio.to_thread(
|
|
663
|
+
worker_context.run, request_client._complete_sync, prompt,
|
|
664
|
+
)
|
|
665
|
+
except (asyncio.CancelledError, ModelRequestInterrupted):
|
|
666
|
+
raise
|
|
667
|
+
except Exception as exc:
|
|
668
|
+
self.last_error = exc
|
|
669
|
+
if self._retry_stopped:
|
|
670
|
+
raise ModelRequestInterrupted() from exc
|
|
671
|
+
infinite = self.retry_error_code is not None
|
|
672
|
+
if was_infinite and not infinite:
|
|
673
|
+
raise
|
|
674
|
+
if infinite:
|
|
675
|
+
if not matches_retry_codes(exc, self.retry_error_code):
|
|
676
|
+
raise
|
|
677
|
+
elif not isinstance(exc, (ResponsesRetryableError, ResponsesModelUnavailableError)):
|
|
605
678
|
raise
|
|
606
|
-
|
|
679
|
+
elif (
|
|
680
|
+
isinstance(exc, ResponsesModelUnavailableError)
|
|
681
|
+
or (isinstance(exc, ResponsesFirstDataTimeout) and len(models) > 1)
|
|
682
|
+
or retries >= max_retries
|
|
683
|
+
):
|
|
684
|
+
cooldown = self._config.fallback_cooldown_seconds
|
|
685
|
+
if len(models) > 1 and cooldown > 0:
|
|
686
|
+
self._model_cooldowns[request_client.model] = (
|
|
687
|
+
monotonic() + cooldown
|
|
688
|
+
)
|
|
689
|
+
fallback_model = next(fallback_models, None)
|
|
690
|
+
if fallback_model is None:
|
|
691
|
+
raise
|
|
692
|
+
EventScope.emit(
|
|
693
|
+
StreamErrorEvent(
|
|
694
|
+
f"Falling back: {request_client.model} -> {fallback_model}",
|
|
695
|
+
0,
|
|
696
|
+
max_retries,
|
|
697
|
+
0.0,
|
|
698
|
+
str(exc),
|
|
699
|
+
)
|
|
700
|
+
)
|
|
701
|
+
request_client = self.with_overrides(model=fallback_model)
|
|
702
|
+
retries = 0
|
|
703
|
+
continue
|
|
704
|
+
retries += 1
|
|
705
|
+
delay_seconds = (
|
|
706
|
+
exc.retry_delay_seconds
|
|
707
|
+
if isinstance(exc, ResponsesRetryableError) else None
|
|
708
|
+
)
|
|
709
|
+
if delay_seconds is None:
|
|
710
|
+
delay_seconds = self._retry_delay_seconds(retries)
|
|
711
|
+
self._retry_wakeup.clear()
|
|
712
|
+
EventScope.emit(
|
|
607
713
|
StreamErrorEvent(
|
|
608
|
-
f"
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
0
|
|
714
|
+
f"Reconnecting... {retries}/∞"
|
|
715
|
+
if infinite else f"Reconnecting... {retries}/{max_retries}",
|
|
716
|
+
retries,
|
|
717
|
+
0 if infinite else max_retries,
|
|
718
|
+
delay_seconds,
|
|
612
719
|
str(exc),
|
|
613
720
|
)
|
|
614
721
|
)
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
722
|
+
if delay_seconds > 0:
|
|
723
|
+
waiter = asyncio.ensure_future(self._retry_wakeup.wait())
|
|
724
|
+
try:
|
|
725
|
+
await asyncio.wait({waiter}, timeout=delay_seconds)
|
|
726
|
+
finally:
|
|
727
|
+
if not waiter.done():
|
|
728
|
+
waiter.cancel()
|
|
729
|
+
try:
|
|
730
|
+
await waiter
|
|
731
|
+
except asyncio.CancelledError:
|
|
732
|
+
pass
|
|
733
|
+
if self._retry_stopped:
|
|
734
|
+
raise ModelRequestInterrupted() from exc
|
|
735
|
+
if infinite and self.retry_error_code is None:
|
|
736
|
+
raise
|
|
737
|
+
if (
|
|
738
|
+
self.retry_error_code is not None
|
|
739
|
+
and not matches_retry_codes(exc, self.retry_error_code)
|
|
740
|
+
):
|
|
741
|
+
raise
|
|
742
|
+
else:
|
|
743
|
+
self._model_cooldowns.pop(request_client.model, None)
|
|
744
|
+
self.last_error = None
|
|
745
|
+
return response
|
|
746
|
+
finally:
|
|
747
|
+
self._retry_wakeup = None
|
|
636
748
|
|
|
637
749
|
def _complete_sync(
|
|
638
750
|
self,
|
|
639
751
|
prompt: "Prompt",
|
|
640
|
-
event_handler: "ModelStreamEventHandler",
|
|
641
752
|
) -> "ModelResponse":
|
|
642
753
|
payload = self._build_payload(prompt)
|
|
643
754
|
session_id = payload["prompt_cache_key"]
|
|
@@ -686,7 +797,7 @@ class ResponsesModelClient:
|
|
|
686
797
|
f"{error_body[:500]}"
|
|
687
798
|
)
|
|
688
799
|
if _is_context_length_error_message(error_body):
|
|
689
|
-
raise ContextLengthExceeded(message)
|
|
800
|
+
raise ContextLengthExceeded(message, http_status=response.status_code)
|
|
690
801
|
if response.status_code >= 500 or response.status_code in (408, 429):
|
|
691
802
|
raise ResponsesRetryableError(
|
|
692
803
|
message,
|
|
@@ -694,10 +805,11 @@ class ResponsesModelClient:
|
|
|
694
805
|
"rate_limit_exceeded" if response.status_code == 429 else "",
|
|
695
806
|
error_body,
|
|
696
807
|
),
|
|
808
|
+
http_status=response.status_code,
|
|
697
809
|
)
|
|
698
810
|
if response.status_code in (403, 404):
|
|
699
|
-
raise ResponsesModelUnavailableError(message)
|
|
700
|
-
raise ResponsesApiError(message)
|
|
811
|
+
raise ResponsesModelUnavailableError(message, http_status=response.status_code)
|
|
812
|
+
raise ResponsesApiError(message, http_status=response.status_code)
|
|
701
813
|
if first_timeout is not None:
|
|
702
814
|
remaining = first_timeout - (monotonic() - diagnostics.started_at)
|
|
703
815
|
if remaining <= 0:
|
|
@@ -714,7 +826,6 @@ class ResponsesModelClient:
|
|
|
714
826
|
tracked_lines = self._track_stream_lines(lines, diagnostics)
|
|
715
827
|
result = self._parse_stream(
|
|
716
828
|
tracked_lines,
|
|
717
|
-
event_handler,
|
|
718
829
|
diagnostics=diagnostics,
|
|
719
830
|
session_id=session_id,
|
|
720
831
|
)
|
|
@@ -740,7 +851,7 @@ class ResponsesModelClient:
|
|
|
740
851
|
exc.first_data_seconds = diagnostics.first_data_seconds
|
|
741
852
|
raise
|
|
742
853
|
finally:
|
|
743
|
-
|
|
854
|
+
EventScope.emit(ModelRequestTimingEvent(
|
|
744
855
|
self.model, monotonic() - diagnostics.started_at,
|
|
745
856
|
diagnostics.first_data_seconds, "completed" if completed else "failed",
|
|
746
857
|
))
|
|
@@ -804,7 +915,7 @@ class ResponsesModelClient:
|
|
|
804
915
|
session_id = self._session_id if prompt.session_id is None else prompt.session_id
|
|
805
916
|
use_responses_lite = self._config.use_responses_lite()
|
|
806
917
|
input_items = [item.serialize() for item in prompt.input]
|
|
807
|
-
_filter_audio_inputs(input_items,
|
|
918
|
+
_filter_audio_inputs(input_items, self._config.metadata())
|
|
808
919
|
if use_responses_lite:
|
|
809
920
|
_strip_image_details(input_items)
|
|
810
921
|
|
|
@@ -936,12 +1047,15 @@ class ResponsesModelClient:
|
|
|
936
1047
|
session_id = self._session_id if prompt.session_id is None else prompt.session_id
|
|
937
1048
|
headers = {
|
|
938
1049
|
"content-type": "application/json",
|
|
939
|
-
"accept": "text/event-stream",
|
|
940
|
-
"x-client-request-id": session_id,
|
|
941
|
-
"session_id": session_id,
|
|
942
1050
|
"originator": self.recording_metadata.originator,
|
|
943
1051
|
"user-agent": self._user_agent,
|
|
944
1052
|
}
|
|
1053
|
+
headers.update(self._provider_headers)
|
|
1054
|
+
headers.update({
|
|
1055
|
+
"accept": "text/event-stream",
|
|
1056
|
+
"x-client-request-id": session_id,
|
|
1057
|
+
"session_id": session_id,
|
|
1058
|
+
})
|
|
945
1059
|
api_key = self._config.api_key()
|
|
946
1060
|
if api_key is not None:
|
|
947
1061
|
headers["authorization"] = f"Bearer {api_key}"
|
|
@@ -960,10 +1074,11 @@ class ResponsesModelClient:
|
|
|
960
1074
|
|
|
961
1075
|
def _build_model_list_headers(self) -> "typing.Dict[str, str]":
|
|
962
1076
|
headers = {
|
|
963
|
-
"accept": "application/json",
|
|
964
1077
|
"originator": self.recording_metadata.originator,
|
|
965
1078
|
"user-agent": self._user_agent,
|
|
966
1079
|
}
|
|
1080
|
+
headers.update(self._provider_headers)
|
|
1081
|
+
headers["accept"] = "application/json"
|
|
967
1082
|
api_key = self._config.api_key()
|
|
968
1083
|
if api_key is not None:
|
|
969
1084
|
headers["authorization"] = f"Bearer {api_key}"
|
|
@@ -976,12 +1091,10 @@ class ResponsesModelClient:
|
|
|
976
1091
|
def _parse_stream(
|
|
977
1092
|
self,
|
|
978
1093
|
response,
|
|
979
|
-
event_handler: "ModelStreamEventHandler",
|
|
980
1094
|
diagnostics: "typing.Union[_StreamDiagnostics, None]" = None,
|
|
981
1095
|
session_id: "typing.Union[str, None]" = None,
|
|
982
1096
|
) -> "ModelResponse":
|
|
983
1097
|
items: "typing.List[typing.Union[typing.Union[AssistantMessage, ToolCall], ReasoningItem]]" = ([])
|
|
984
|
-
saw_completed = False
|
|
985
1098
|
last_event_type = ""
|
|
986
1099
|
|
|
987
1100
|
for event_name, data in self._iter_sse_events(response, diagnostics):
|
|
@@ -999,7 +1112,7 @@ class ResponsesModelClient:
|
|
|
999
1112
|
diagnostics.last_event_type = last_event_type
|
|
1000
1113
|
|
|
1001
1114
|
if event_type == "response.output_text.delta":
|
|
1002
|
-
|
|
1115
|
+
EventScope.emit(AssistantDeltaEvent(str(payload.get("delta", ""))))
|
|
1003
1116
|
continue
|
|
1004
1117
|
|
|
1005
1118
|
if event_type == "response.output_item.done":
|
|
@@ -1015,7 +1128,7 @@ class ResponsesModelClient:
|
|
|
1015
1128
|
else:
|
|
1016
1129
|
action_payload = {}
|
|
1017
1130
|
queries = action_payload.get("queries")
|
|
1018
|
-
|
|
1131
|
+
EventScope.emit(
|
|
1019
1132
|
ToolCalledEvent(
|
|
1020
1133
|
call_id=str(item_payload.get("id", "web_search")),
|
|
1021
1134
|
tool_name="web_search",
|
|
@@ -1051,7 +1164,7 @@ class ResponsesModelClient:
|
|
|
1051
1164
|
parsed = self._parse_output_item(item_payload)
|
|
1052
1165
|
if parsed is not None:
|
|
1053
1166
|
if isinstance(parsed, ToolCall):
|
|
1054
|
-
|
|
1167
|
+
EventScope.emit(ToolCalledEvent(parsed.call_id, parsed.name))
|
|
1055
1168
|
items.append(parsed)
|
|
1056
1169
|
if diagnostics is not None:
|
|
1057
1170
|
diagnostics.output_items_received += 1
|
|
@@ -1066,9 +1179,8 @@ class ResponsesModelClient:
|
|
|
1066
1179
|
usage = dict(response_usage)
|
|
1067
1180
|
elif isinstance(payload.get("usage"), dict):
|
|
1068
1181
|
usage = dict(payload["usage"])
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
break
|
|
1182
|
+
EventScope.emit(TokenCountEvent(usage))
|
|
1183
|
+
return ModelResponse(items=items, usage=usage)
|
|
1072
1184
|
|
|
1073
1185
|
if event_type == "response.incomplete":
|
|
1074
1186
|
partial_items = tuple(items)
|
|
@@ -1087,12 +1199,9 @@ class ResponsesModelClient:
|
|
|
1087
1199
|
if event_type == "response.failed":
|
|
1088
1200
|
self._raise_response_failed_error(payload, session_id)
|
|
1089
1201
|
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
)
|
|
1094
|
-
|
|
1095
|
-
return ModelResponse(items=items)
|
|
1202
|
+
raise ResponsesRetryableError(
|
|
1203
|
+
self._format_incomplete_stream_error(last_event_type, len(items), session_id)
|
|
1204
|
+
)
|
|
1096
1205
|
|
|
1097
1206
|
@staticmethod
|
|
1098
1207
|
def _parse_output_item(
|
|
@@ -1339,25 +1448,31 @@ class ResponsesModelClient:
|
|
|
1339
1448
|
)
|
|
1340
1449
|
|
|
1341
1450
|
message = str(error.get("message") or "responses stream failed")
|
|
1342
|
-
|
|
1451
|
+
error_code = error.get("code")
|
|
1452
|
+
if error_code is None:
|
|
1453
|
+
error_code = error.get("type")
|
|
1454
|
+
http_status = error.get("http_status")
|
|
1455
|
+
code = str(error_code or "").strip()
|
|
1343
1456
|
formatted = self._format_response_failed_error(message, code, session_id)
|
|
1344
1457
|
if code == "context_length_exceeded" or _is_context_length_error_message(
|
|
1345
1458
|
message
|
|
1346
1459
|
):
|
|
1347
|
-
raise ContextLengthExceeded(formatted)
|
|
1460
|
+
raise ContextLengthExceeded(formatted, http_status=http_status, error_code=error_code)
|
|
1348
1461
|
if code in {"model_not_found", "model_not_available", "permission_denied"}:
|
|
1349
|
-
raise ResponsesModelUnavailableError(formatted)
|
|
1462
|
+
raise ResponsesModelUnavailableError(formatted, http_status=http_status, error_code=error_code)
|
|
1350
1463
|
if code in {
|
|
1351
1464
|
"insufficient_quota",
|
|
1352
1465
|
"invalid_prompt",
|
|
1353
1466
|
"model_output_invalid",
|
|
1354
1467
|
"usage_not_included",
|
|
1355
1468
|
}:
|
|
1356
|
-
raise ResponsesApiError(formatted)
|
|
1469
|
+
raise ResponsesApiError(formatted, http_status=http_status, error_code=error_code)
|
|
1357
1470
|
|
|
1358
1471
|
raise ResponsesRetryableError(
|
|
1359
1472
|
formatted,
|
|
1360
1473
|
retry_delay_seconds=self._try_parse_retry_after_seconds(code, message),
|
|
1474
|
+
http_status=http_status,
|
|
1475
|
+
error_code=error_code,
|
|
1361
1476
|
)
|
|
1362
1477
|
|
|
1363
1478
|
def _format_incomplete_stream_error(
|
pycodex/multi_agents.py
CHANGED
|
@@ -9,17 +9,6 @@ from typing import TYPE_CHECKING
|
|
|
9
9
|
|
|
10
10
|
from .agent import Agent
|
|
11
11
|
from .context import ContextConfig
|
|
12
|
-
from .events import (
|
|
13
|
-
CommandStartedEvent,
|
|
14
|
-
CompactStartedEvent,
|
|
15
|
-
Event,
|
|
16
|
-
RuntimeUpdatedEvent,
|
|
17
|
-
SessionClosedEvent,
|
|
18
|
-
TurnCompletedEvent,
|
|
19
|
-
TurnFailedEvent,
|
|
20
|
-
TurnInterruptedEvent,
|
|
21
|
-
TurnStartedEvent,
|
|
22
|
-
)
|
|
23
12
|
from .protocol import AgentMessage, ConversationItem
|
|
24
13
|
from .tools import get_tools
|
|
25
14
|
from .tools.runtime_services import create_agent_runtime_environment
|
|
@@ -111,7 +100,10 @@ class AgentsManager:
|
|
|
111
100
|
agent.context_manager.agent_path = agent.agent_path
|
|
112
101
|
return runtime
|
|
113
102
|
|
|
114
|
-
def
|
|
103
|
+
def mark_used(self, agent_id):
|
|
104
|
+
self._runtimes.move_to_end(agent_id)
|
|
105
|
+
|
|
106
|
+
def notify_parents(self, agent_id):
|
|
115
107
|
parent_agent_id = self.get_parent_agent_id(agent_id)
|
|
116
108
|
while parent_agent_id is not None:
|
|
117
109
|
parent = self._runtimes[parent_agent_id]
|
|
@@ -184,7 +176,7 @@ class AgentsManager:
|
|
|
184
176
|
runtime.agent.tool_registry.runtime_environment.set_state_listener(None)
|
|
185
177
|
del self._runtimes[agent_id]
|
|
186
178
|
self._runtimes[parent_agent_id].publish_update("agents")
|
|
187
|
-
self.
|
|
179
|
+
self.notify_parents(parent_agent_id)
|
|
188
180
|
|
|
189
181
|
async def _make_spawn_room(self, caller_agent_id):
|
|
190
182
|
caller = self._runtimes[caller_agent_id]
|
|
@@ -285,7 +277,7 @@ class AgentsManager:
|
|
|
285
277
|
),
|
|
286
278
|
runtime.agent.model_client.reasoning_effort,
|
|
287
279
|
)
|
|
288
|
-
self.
|
|
280
|
+
self.notify_parents(runtime.agent.agent_id)
|
|
289
281
|
await runtime.start()
|
|
290
282
|
await self.send_message(
|
|
291
283
|
caller_agent_id, runtime.agent.agent_id, message, trigger_turn=True,
|
|
@@ -313,7 +305,7 @@ class AgentsManager:
|
|
|
313
305
|
recipient.message(item)
|
|
314
306
|
if trigger_turn:
|
|
315
307
|
recipient.trigger()
|
|
316
|
-
self.
|
|
308
|
+
self.mark_used(recipient_agent_id)
|
|
317
309
|
return ""
|
|
318
310
|
|
|
319
311
|
async def interrupt_agent(self, caller_agent_id, target):
|
|
@@ -369,33 +361,12 @@ class AgentsManager:
|
|
|
369
361
|
)
|
|
370
362
|
raise errors[0]
|
|
371
363
|
|
|
372
|
-
def
|
|
373
|
-
self._runtimes[agent_id]
|
|
374
|
-
if isinstance(event, (TurnStartedEvent, CompactStartedEvent, CommandStartedEvent)):
|
|
375
|
-
self._runtimes.move_to_end(agent_id)
|
|
376
|
-
text = None
|
|
377
|
-
if isinstance(event, TurnCompletedEvent):
|
|
378
|
-
text = event.output_text or ""
|
|
379
|
-
elif isinstance(event, TurnFailedEvent):
|
|
380
|
-
text = "Agent errored: {0}: {1}".format(event.error_type, event.error)
|
|
381
|
-
elif isinstance(event, RuntimeUpdatedEvent):
|
|
382
|
-
if event.reason == "agents":
|
|
383
|
-
return
|
|
384
|
-
elif not isinstance(
|
|
385
|
-
event,
|
|
386
|
-
(
|
|
387
|
-
TurnStartedEvent,
|
|
388
|
-
TurnInterruptedEvent,
|
|
389
|
-
CompactStartedEvent,
|
|
390
|
-
SessionClosedEvent,
|
|
391
|
-
),
|
|
392
|
-
):
|
|
393
|
-
return
|
|
364
|
+
def finish_turn(self, agent_id, final_answer):
|
|
394
365
|
parent_agent_id = self.get_parent_agent_id(agent_id)
|
|
395
|
-
if parent_agent_id is not None and
|
|
366
|
+
if parent_agent_id is not None and final_answer is not None:
|
|
396
367
|
parent = self._runtimes[parent_agent_id]
|
|
397
368
|
if parent.accepts_input:
|
|
398
369
|
parent.message(
|
|
399
|
-
self._message(agent_id, parent_agent_id,
|
|
370
|
+
self._message(agent_id, parent_agent_id, final_answer, "FINAL_ANSWER"),
|
|
400
371
|
)
|
|
401
|
-
self.
|
|
372
|
+
self.notify_parents(agent_id)
|