Skip to content

Commit adf4bfa

Browse files
authored
Merge pull request #57 from context-labs/add-llm-retries
Add more retries
2 parents 1fbcb9f + c326bdd commit adf4bfa

2 files changed

Lines changed: 49 additions & 1 deletion

File tree

engine/agents/openai_agent_runner.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from openai import (
88
APIConnectionError,
9+
APIError,
910
APIStatusError,
1011
APITimeoutError,
1112
AsyncOpenAI,
@@ -25,6 +26,8 @@ def _is_retriable_llm_error(exc: BaseException) -> bool:
2526
return True
2627
if isinstance(exc, APIStatusError):
2728
return exc.status_code >= 500
29+
if isinstance(exc, APIError):
30+
return True
2831
return False
2932

3033

tests/unit/agents/test_openai_agent_runner.py

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import httpx
44
import pytest
5-
from openai import APIConnectionError, AsyncOpenAI, BadRequestError
5+
from openai import APIConnectionError, APIError, AsyncOpenAI, BadRequestError
66

77
from engine.agents.agent_context import AgentContext
88
from engine.agents.agent_execution import AgentExecution
@@ -444,6 +444,51 @@ async def raise_connection(*, agent, input, context):
444444
assert call_count == 10
445445

446446

447+
@pytest.mark.asyncio
448+
async def test_runner_retries_plain_api_error_from_backend() -> None:
449+
bus = EngineOutputBus()
450+
ctx = _context()
451+
execution = AgentExecution(
452+
agent_id="root",
453+
agent_name="root",
454+
depth=0,
455+
parent_agent_id=None,
456+
parent_tool_call_id=None,
457+
)
458+
459+
call_count = 0
460+
fake_request = httpx.Request("POST", "https://api.openai.com/v1/responses")
461+
462+
async def fail_then_recover(*, agent, input, context):
463+
nonlocal call_count
464+
call_count += 1
465+
if call_count == 1:
466+
raise APIError(
467+
message=(
468+
"Backend returned unexpected response. Please contact Microsoft for help."
469+
),
470+
request=fake_request,
471+
body=None,
472+
)
473+
return _FakeStream([_assistant_event("answer\n<final/>")])
474+
475+
runner = OpenAiAgentRunner(
476+
run_streamed=fail_then_recover,
477+
client=_DUMMY_CLIENT,
478+
)
479+
480+
await runner.run(
481+
sdk_agent=object(),
482+
agent_context=ctx,
483+
agent_execution=execution,
484+
output_bus=bus,
485+
is_root=True,
486+
)
487+
488+
assert call_count == 2
489+
assert execution.consecutive_llm_failures == 0
490+
491+
447492
class _RaisingStream:
448493
"""Yields nothing and raises ``exc`` on the first iteration step."""
449494

0 commit comments

Comments
 (0)