Skip to content

Commit cd96fcd

Browse files
fix: improve operational error reporting across providers (#123)
* fix(deploy): report invalid Postgres port cleanly * fix(core): sanitize failures and surface trace errors * fix(gemini): classify provider errors from metadata * docs(progress): record PR #123 issue batch * fix(openai): honor rate limit retry headers * docs(progress): correct PR #123 commit count
1 parent 9d528a6 commit cd96fcd

17 files changed

Lines changed: 237 additions & 37 deletions

‎.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
# Optional: web_search is omitted from the tool registry when this is unset.

‎README.md‎

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

132133
### 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
@@ -405,7 +405,7 @@ async def _finalize_canceled(*, save_history: bool) -> None:
405405
f"Detected duplicate tool call loop: '{call.name}' called "
406406
f"{repeat_count} times with identical arguments within "
407407
f"the last {self.config.duplicate_tool_call_window} "
408-
f"tool calls: {call.arguments}"
408+
"tool calls with identical arguments."
409409
),
410410
steps_count=steps_count,
411411
total_input_tokens=total_input_tokens,
@@ -417,9 +417,7 @@ async def _finalize_canceled(*, save_history: bool) -> None:
417417
raise DuplicateToolCallLoopError(call.name, repeat_count)
418418
return res
419419

420-
logger.info(
421-
"Executing tool '%s' with args: %s", call.name, call.arguments
422-
)
420+
logger.info("Executing tool '%s'", call.name)
423421
result = await self.registry.execute(
424422
call,
425423
timeout_s=self.config.tool_timeout_s,
@@ -442,7 +440,7 @@ async def _finalize_canceled(*, save_history: bool) -> None:
442440
)
443441

444442
if self.trace is not None and hasattr(self.trace, "record"):
445-
with contextlib.suppress(Exception):
443+
try:
446444
trace_record = StepTrace(
447445
run_id=run_id,
448446
step_no=steps_count,
@@ -464,6 +462,13 @@ async def _finalize_canceled(*, save_history: bool) -> None:
464462
)
465463
await self.trace.record(trace_record)
466464
traced_turn_usage.add(steps_count)
465+
except Exception as exc:
466+
logger.warning(
467+
"Could not record tool trace (run_id=%s, step_no=%s): %s",
468+
run_id,
469+
steps_count,
470+
exc,
471+
)
467472
else:
468473
# No tool calls: this is the final answer, a provider refusal, or
469474
# 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/gemini.py‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,21 @@ def _enum_label(value: Any) -> str | None:
3636
return candidate if _ENUM_LABEL_REGEX.match(candidate) else None
3737

3838

39+
def _has_invalid_api_key_reason(details: Any) -> bool:
40+
"""Inspect structured Google error details for the API-key rejection reason."""
41+
if isinstance(details, dict):
42+
if details.get("reason") == "API_KEY_INVALID":
43+
return True
44+
return any(
45+
_has_invalid_api_key_reason(value)
46+
for key, value in details.items()
47+
if key in {"error", "details", "errors"}
48+
)
49+
if isinstance(details, list):
50+
return any(_has_invalid_api_key_reason(item) for item in details)
51+
return False
52+
53+
3954
class GeminiClient(LLMClient):
4055
"""LLM client adapter for Google Gemini models via google-genai."""
4156

@@ -186,9 +201,17 @@ async def chat(
186201
)
187202
except Exception as exc:
188203
err_str = str(exc)
189-
if "API_KEY_INVALID" in err_str or "unauthenticated" in err_str.lower():
204+
status_code = getattr(exc, "code", None)
205+
if status_code is None:
206+
status_code = getattr(exc, "status_code", None)
207+
provider_status = getattr(exc, "status", None)
208+
details = getattr(exc, "details", None)
209+
if (
210+
provider_status in {"UNAUTHENTICATED", "PERMISSION_DENIED"}
211+
or _has_invalid_api_key_reason(details)
212+
or status_code == 401
213+
):
190214
raise AuthenticationError(f"Gemini API key is invalid: {err_str}") from exc
191-
status_code = getattr(exc, "code", getattr(exc, "status_code", None))
192215
raise LLMProviderError(
193216
provider="gemini",
194217
message=err_str,

‎agentkit/llm/openai.py‎

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
import inspect
44
import json
55
import logging
6-
import os
6+
import math
77
import uuid
8+
from datetime import UTC, datetime
9+
from email.utils import parsedate_to_datetime
810
from typing import Any
911

1012
import openai
@@ -17,6 +19,42 @@
1719
logger = logging.getLogger(__name__)
1820

1921

22+
def _retry_after_seconds(exc: openai.RateLimitError, fallback_s: int) -> int:
23+
"""Return the provider's retry delay, or the configured fallback if absent/invalid."""
24+
response = getattr(exc, "response", None)
25+
headers = getattr(response, "headers", None)
26+
if headers is None:
27+
return fallback_s
28+
29+
retry_after_ms = headers.get("retry-after-ms")
30+
if retry_after_ms is not None:
31+
try:
32+
delay_s = float(retry_after_ms) / 1000
33+
except (TypeError, ValueError):
34+
delay_s = math.nan
35+
if math.isfinite(delay_s) and delay_s >= 0:
36+
return math.ceil(delay_s)
37+
38+
retry_after = headers.get("retry-after")
39+
if retry_after is None:
40+
return fallback_s
41+
42+
try:
43+
delay_s = float(retry_after)
44+
except (TypeError, ValueError):
45+
try:
46+
retry_at = parsedate_to_datetime(retry_after)
47+
except (TypeError, ValueError, OverflowError):
48+
return fallback_s
49+
if retry_at.tzinfo is None:
50+
retry_at = retry_at.replace(tzinfo=UTC)
51+
delay_s = (retry_at - datetime.now(UTC)).total_seconds()
52+
53+
if not math.isfinite(delay_s):
54+
return fallback_s
55+
return max(0, math.ceil(delay_s))
56+
57+
2058
class OpenAIClient(LLMClient):
2159
"""LLM client adapter for OpenAI chat completion models via openai SDK."""
2260

@@ -25,25 +63,26 @@ def __init__(
2563
api_key: str | None = None,
2664
model: str = "gpt-4o",
2765
client: Any | None = None,
66+
retry_after_fallback_s: int = 60,
2867
) -> None:
2968
"""Initialize the OpenAI client adapter.
3069
3170
Args:
32-
api_key: OpenAI API key. If omitted, uses OPENAI_API_KEY environment variable.
71+
api_key: OpenAI API key supplied by application settings.
3372
model: OpenAI model identifier (default: gpt-4o).
3473
client: Optional pre-configured AsyncOpenAI client instance (useful for mocking).
74+
retry_after_fallback_s: Fallback delay when a rate limit response has no header.
3575
"""
3676
self.model = model
37-
self.api_key = api_key or os.getenv("OPENAI_API_KEY")
77+
self.api_key = api_key
78+
self.retry_after_fallback_s = retry_after_fallback_s
3879

3980
if client is not None:
4081
self._client = client
4182
elif self.api_key:
4283
self._client = openai.AsyncOpenAI(api_key=self.api_key)
4384
else:
44-
raise AuthenticationError(
45-
"OpenAI API key not configured. Set OPENAI_API_KEY environment variable or pass api_key."
46-
)
85+
raise AuthenticationError("OpenAI API key is not configured in application settings.")
4786

4887
async def aclose(self) -> None:
4988
"""Close the underlying AsyncOpenAI client and its connection pool."""
@@ -126,7 +165,8 @@ async def chat(
126165
except openai.AuthenticationError as exc:
127166
raise AuthenticationError(f"OpenAI authentication failed: {exc}") from exc
128167
except openai.RateLimitError as exc:
129-
raise RateLimitExceededError(retry_after=60) from exc
168+
retry_after = _retry_after_seconds(exc, self.retry_after_fallback_s)
169+
raise RateLimitExceededError(retry_after=retry_after) from exc
130170
except openai.OpenAIError as exc:
131171
status_code = getattr(exc, "status_code", None)
132172
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

‎docs/PROGRESS.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ This document tracks execution progress across all backlog tasks, including pull
8080
| ROADMAP-02 | ROADMAP | SQL Markdown Cell Escaping | `fix/roadmap-02-03-04-tools-hardening` | #120 | 1 | Done | Cells escaped (`\|`, `\n`, `\uXXXX` controls) and length-capped before markdown output; closes #94 |
8181
| ROADMAP-03 | ROADMAP | read_file Read-After-Stat Race | `fix/roadmap-02-03-04-tools-hardening` | #120 | 1 | Done | Byte cap enforced on a bounded `read(max_bytes + 1)` in one open; closes #95 |
8282
| ROADMAP-04 | ROADMAP | Calculator Non-Finite Result Guard | `fix/roadmap-02-03-04-tools-hardening` | #120 | 1 | Done | `math.isfinite` result check, inf literals rejected, pow pair guard named; closes #96 |
83+
| GH-92/111/113 | OPS | Operational Error Reporting | `fix/error-reporting-issues` | #123 | 6 | In Review | Invalid Postgres ports, sanitized agent failures and logged trace writes, settings-based OpenAI fallback, structured Gemini classification; addresses #92, #111 and item 5 of #113 |
8384

8485
---
8586

@@ -515,3 +516,9 @@ This document tracks execution progress across all backlog tasks, including pull
515516
- **PR**: `fix/roadmap-02-03-04-tools-hardening` — PR #120 (three `fix(tools)` commits, squash-merged; docs rows in this commit)
516517
- **Commits**: 3 (+1 docs)
517518
- **Notes**: Closed the first three `ROADMAP` issues filed from the 2026-10-27 assessment. **#94** — `format_rows_as_markdown` now routes every cell (and column name) through `_format_cell`/`_escape_cell_text`: backslash first, then `|` → `\|`, newline/CR/tab → `\n`/`\r`/`\t`, every other C0/DEL control character → `\uXXXX`, and a rendered-length cap `MAX_CELL_CHARS` (200) with a `[Truncated]` marker, so a database value can no longer forge table rows, columns or prompt structure (stored prompt injection). **#95** — `read_sandboxed_file` enforces the byte cap on the bytes actually read (`read(max_bytes + 1)` from a single open) instead of a `stat().st_size` check + second open; oversize keeps the same user-visible phrase, an exact-cap file stays fully readable, and a regression test stands in for the race by lying about `st_size` (the old code returned the full oversized file). **#96** — `safe_calculate` rejects non-finite float results (`1e308 * 10 ** 3` no longer renders `inf` into the prompt) and non-finite float literals (`1e999` parses to inf) at the operand boundary; the `Pow` guard's bare `1000`/`100` literals became `MAX_POW_BASE_MAGNITUDE`/`MAX_POW_PAIR_EXPONENT` with unchanged values. 11 tests added (`test_tool_sql_readonly.py`, `test_tool_read_file.py`, `test_tool_calculator.py`); suite moved from 483 to 494 passing.
519+
520+
### PR #123: Operational Error Reporting (#92 / #111 / #113 item 5)
521+
- **Status**: In Review
522+
- **PR**: https://github.com/getdownandcode/AgentKit/pull/123
523+
- **Commits**: 6 (three issue-specific fixes, initial progress bookkeeping, review fix, and this commit correcting the count)
524+
- **Notes**: **#92** — `audit_credentials()` now catches the `ValueError` raised by component-mode Postgres URL resolution for a malformed `POSTGRES_PORT`, reports one stable `POSTGRES_PORT is not a valid integer.` problem, and continues the audit without a traceback. **#111** — duplicate-tool failure reasons keep the tool name and loop category without echoing arguments; execution logs no longer include raw arguments; trace-sink errors are logged at `WARNING` with `run_id`/`step_no` while the run continues; OpenAI credentials come only from `Settings`, and rate-limit handling honors the `retry-after-ms` and `retry-after` response headers (numeric seconds or HTTP-date) before using the configured `RETRY_AFTER_FALLBACK_S` (default 60). A Codex review follow-up added regression coverage for header precedence, milliseconds conversion, malformed headers, fallback and HTTP-date parsing. **#113 item 5** — Gemini error classification inspects structured API status/reason fields and selects `code` only when non-null before falling back to `status_code`. Regression tests also cover malformed port input, sensitive failure reasons, trace logging, configured retry fallback, and structured Gemini errors. Verified: full `pytest` suite passes (real-infrastructure tier skipped because disabled), `ruff check .`, `ruff format --check .`, and `mypy agentkit` pass. The other six independent #113 findings remain outside this PR.

0 commit comments

Comments
 (0)