Skip to content

Commit 79409a5

Browse files
fix(core): sanitize failures and surface trace errors
1 parent eab2c09 commit 79409a5

12 files changed

Lines changed: 43 additions & 16 deletions

File tree

‎.env.example‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ OPENAI_API_KEY=your_openai_api_key_here
5050
LLM_MAX_RETRIES=3
5151
LLM_RETRY_BASE_DELAY_S=0.5
5252
LLM_RETRY_MAX_DELAY_S=10
53+
RETRY_AFTER_FALLBACK_S=60
5354

5455
# External Tools & Sandboxing
5556
SEARCH_API_KEY=your_search_api_key_here

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ API_KEYS=dev_key_1,dev_key_2
126126
LLM_MAX_RETRIES=3
127127
LLM_RETRY_BASE_DELAY_S=0.5
128128
LLM_RETRY_MAX_DELAY_S=10
129+
RETRY_AFTER_FALLBACK_S=60
129130
```
130131

131132
### 4. Running with Docker Compose (Recommended)

‎agentkit/config.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,11 @@ class Settings(BaseSettings):
238238
gt=0,
239239
description="Maximum delay in seconds between LLM retry attempts.",
240240
)
241+
RETRY_AFTER_FALLBACK_S: int = Field(
242+
default=60,
243+
gt=0,
244+
description="Retry-After fallback in seconds when a provider omits it.",
245+
)
241246
FILE_TOOL_BASE_DIR: str = Field(
242247
default="/tmp/agentkit_sandbox",
243248
description="Base directory for sandboxed file reading operations.",

‎agentkit/core/agent.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ async def _finalize_and_return(result: RunResult) -> RunResult:
355355
f"Detected duplicate tool call loop: '{call.name}' called "
356356
f"{repeat_count} times with identical arguments within "
357357
f"the last {self.config.duplicate_tool_call_window} "
358-
f"tool calls: {call.arguments}"
358+
"tool calls with identical arguments."
359359
),
360360
steps_count=steps_count,
361361
total_input_tokens=total_input_tokens,
@@ -367,9 +367,7 @@ async def _finalize_and_return(result: RunResult) -> RunResult:
367367
raise DuplicateToolCallLoopError(call.name, repeat_count)
368368
return res
369369

370-
logger.info(
371-
"Executing tool '%s' with args: %s", call.name, call.arguments
372-
)
370+
logger.info("Executing tool '%s'", call.name)
373371
result = await self.registry.execute(
374372
call,
375373
timeout_s=self.config.tool_timeout_s,
@@ -392,7 +390,7 @@ async def _finalize_and_return(result: RunResult) -> RunResult:
392390
)
393391

394392
if self.trace is not None and hasattr(self.trace, "record"):
395-
with contextlib.suppress(Exception):
393+
try:
396394
trace_record = StepTrace(
397395
run_id=run_id,
398396
step_no=steps_count,
@@ -405,6 +403,13 @@ async def _finalize_and_return(result: RunResult) -> RunResult:
405403
output_tokens=response.usage.output_tokens,
406404
)
407405
await self.trace.record(trace_record)
406+
except Exception as exc:
407+
logger.warning(
408+
"Could not record tool trace (run_id=%s, step_no=%s): %s",
409+
run_id,
410+
steps_count,
411+
exc,
412+
)
408413
else:
409414
# No tool calls: this is the final answer, a provider refusal, or
410415
# an empty completion. Only a non-empty answer is a success; the

‎agentkit/llm/factory.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ def create_llm_client_from_settings(settings: Settings) -> LLMClient:
7474
provider=provider,
7575
api_key=api_key,
7676
model=settings.LLM_MODEL,
77+
**(
78+
{"retry_after_fallback_s": settings.RETRY_AFTER_FALLBACK_S}
79+
if provider == "openai"
80+
else {}
81+
),
7782
)
7883

7984
if provider in ("gemini", "openai") and settings.LLM_MAX_RETRIES > 0:

‎agentkit/llm/openai.py‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import inspect
44
import json
55
import logging
6-
import os
76
import uuid
87
from typing import Any
98

@@ -25,25 +24,26 @@ def __init__(
2524
api_key: str | None = None,
2625
model: str = "gpt-4o",
2726
client: Any | None = None,
27+
retry_after_fallback_s: int = 60,
2828
) -> None:
2929
"""Initialize the OpenAI client adapter.
3030
3131
Args:
32-
api_key: OpenAI API key. If omitted, uses OPENAI_API_KEY environment variable.
32+
api_key: OpenAI API key supplied by application settings.
3333
model: OpenAI model identifier (default: gpt-4o).
3434
client: Optional pre-configured AsyncOpenAI client instance (useful for mocking).
35+
retry_after_fallback_s: Fallback delay when a rate limit response has no header.
3536
"""
3637
self.model = model
37-
self.api_key = api_key or os.getenv("OPENAI_API_KEY")
38+
self.api_key = api_key
39+
self.retry_after_fallback_s = retry_after_fallback_s
3840

3941
if client is not None:
4042
self._client = client
4143
elif self.api_key:
4244
self._client = openai.AsyncOpenAI(api_key=self.api_key)
4345
else:
44-
raise AuthenticationError(
45-
"OpenAI API key not configured. Set OPENAI_API_KEY environment variable or pass api_key."
46-
)
46+
raise AuthenticationError("OpenAI API key is not configured in application settings.")
4747

4848
async def aclose(self) -> None:
4949
"""Close the underlying AsyncOpenAI client and its connection pool."""
@@ -126,7 +126,8 @@ async def chat(
126126
except openai.AuthenticationError as exc:
127127
raise AuthenticationError(f"OpenAI authentication failed: {exc}") from exc
128128
except openai.RateLimitError as exc:
129-
raise RateLimitExceededError(retry_after=60) from exc
129+
retry_after = getattr(exc, "retry_after", None) or self.retry_after_fallback_s
130+
raise RateLimitExceededError(retry_after=int(retry_after)) from exc
130131
except openai.OpenAIError as exc:
131132
status_code = getattr(exc, "status_code", None)
132133
raise LLMProviderError(

‎docker-compose.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ services:
133133
- LLM_MAX_RETRIES=${LLM_MAX_RETRIES:-3}
134134
- LLM_RETRY_BASE_DELAY_S=${LLM_RETRY_BASE_DELAY_S:-0.5}
135135
- LLM_RETRY_MAX_DELAY_S=${LLM_RETRY_MAX_DELAY_S:-10}
136+
- RETRY_AFTER_FALLBACK_S=${RETRY_AFTER_FALLBACK_S:-60}
136137
# No default key. An unset or empty API_KEYS leaves the api service to fail at
137138
# startup on Settings validation rather than running with a published key.
138139
# Compose keeps ${VAR:-} so `down`, `ps` and `logs` still work without it.

‎docs/DEPLOY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ API_KEYS=${API_KEYS}
217217
FILE_TOOL_BASE_DIR=/tmp/agentkit_sandbox
218218
RUN_TIMEOUT_S=60
219219
LLM_MAX_RETRIES=3
220+
RETRY_AFTER_FALLBACK_S=60
220221
ENVFILE
221222
222223
chmod 600 /opt/agentkit/.env

‎tests/unit/test_agent_loop_detector.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ def search_query(q: str) -> str:
6060
assert result.status == RunStatus.FAILED
6161
assert "duplicate tool call loop" in (result.failure_reason or "").lower()
6262
assert "search_query" in (result.failure_reason or "")
63+
assert "python" not in (result.failure_reason or "")
6364
assert result.final_answer is None
6465

6566

‎tests/unit/test_llm_factory.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,14 @@ def test_create_from_settings_openai() -> None:
7171
LLM_MODEL="gpt-4o",
7272
OPENAI_API_KEY="test-openai-key",
7373
LLM_MAX_RETRIES=2,
74+
RETRY_AFTER_FALLBACK_S=23,
7475
)
7576
client = create_llm_client_from_settings(settings)
7677
assert isinstance(client, RetryingLLMClient)
7778
assert isinstance(client._client, OpenAIClient)
7879
assert client.model == "gpt-4o"
7980
assert client._max_retries == 2
81+
assert client._client.retry_after_fallback_s == 23
8082

8183

8284
def test_create_from_settings_zero_retries() -> None:

0 commit comments

Comments
 (0)