Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **An LLM reply cut off at the output cap is sent once more instead of
failing its call.** A generation that runs away until `max_tokens`
(`finish_reason` `length`) usually finishes when the identical request is
sent again, so every LLM call -- the episode extraction inside
`/memory/add` included -- now resends it once before giving up, rather than
losing the memcell's episode or failing the background extraction.
`[llm] truncated_reply_retries` (default `1`; settable per task in
`[llm.<task>]` and in `[multimodal]`) sets how many times. It is counted
apart from `invalid_reply_retries`, and a retry never raises `max_tokens`:
a reply that is long by nature reaches the cap again and still fails, which
a larger `max_tokens` for that task fixes. A reply blocked by
`content_filter` is not resent.

- **A resent `/memory/add` no longer cuts the same messages twice** (#274).
Messages were deduplicated only against the session buffer, so a client
retrying after a timeout re-sent messages the first call had already cut
Expand Down
69 changes: 35 additions & 34 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,19 +157,52 @@ Zilliz Cloud endpoint; a Milvus Lite filesystem path is rejected.
| `model` | string | `"gpt-4.1-mini"` | No | LLM model identifier. |
| `api_key` | string | — | **Yes** | API key for the LLM provider. |
| `base_url` | string | — | No | Custom endpoint URL (OpenAI-compatible). |
| `timeout_seconds` | float | `60.0` | No | Deadline of one request. One add or flush may spend up to `(invalid_reply_retries + 1) × timeout_seconds` per extraction call plus the client's own retries, so size reverse-proxy and client timeouts accordingly; raise it for slow self-hosted endpoints. |
| `timeout_seconds` | float | `60.0` | No | Deadline of one request. One add or flush may spend up to `(invalid_reply_retries + truncated_reply_retries + 1) × timeout_seconds` per extraction call plus the client's own retries, so size reverse-proxy and client timeouts accordingly; raise it for slow self-hosted endpoints. |
| `invalid_reply_retries` | int | `1` | No | Extra attempts of the identical request after a reply that fails validation. |
| `truncated_reply_retries` | int | `1` | No | Extra attempts of the identical request after a reply that reached the output cap (`finish_reason` `length`), counted apart from `invalid_reply_retries`. A runaway generation usually finishes when sent again; a reply long by nature reaches the cap again and needs a larger `max_tokens`, which no retry raises. A reply blocked by `content_filter` is never resent. |
| `response_format_mode` | string | `"json_schema"` | No | How the reply format is requested: `json_schema` (strict schema), `json_object` (JSON mode) or `prompt_only`. |
| `extra` | table | `{}` | No | Provider-specific request fields merged into every call. Non-standard fields must sit under `extra_body` (the OpenAI SDK rejects unknown top-level names). |
| `temperature` | float | unset | No | Sent only when a call names none; unset, the request carries no temperature. A default, never an override: agentic search keeps the temperatures it sets per call. |
| `max_tokens` | int | unset | No | Output cap sent only when a call names none; unset, the request carries none. A reasoning model bills its thinking against it. |
| `sdk_max_retries` | int | unset | No | Transport retries inside the OpenAI SDK; unset keeps the SDK default. They multiply with `invalid_reply_retries`. |
| `sdk_max_retries` | int | unset | No | Transport retries inside the OpenAI SDK; unset keeps the SDK default. They multiply with `invalid_reply_retries` and `truncated_reply_retries`. |

`[llm]` is the only LLM section you need: every task below uses it unless its
own section says otherwise. `[llm]` and its task sections reject unknown keys
-- a typo fails startup with the list of valid names, instead of being ignored
while the task quietly keeps `[llm]`'s model.

#### NVIDIA NIM

[NVIDIA NIM](https://build.nvidia.com/) serves an OpenAI-compatible Chat
Completions API, so it plugs into `[llm]` like OpenRouter does: set the model,
key, and base URL. Model ids use the `<publisher>/<model>` form; pick one from
the endpoint's `/models` list.

```toml
[llm]
model = "nvidia/nemotron-3.5-super-vl-120b-a12b"
api_key = "<NVIDIA_API_KEY>"
base_url = "https://integrate.api.nvidia.com/v1"
```

Or keep the key out of the file and pass your `NVIDIA_API_KEY` through the
environment:

```bash
export EVEROS_LLM__API_KEY="$NVIDIA_API_KEY"
export EVEROS_LLM__BASE_URL=https://integrate.api.nvidia.com/v1
export EVEROS_LLM__MODEL=nvidia/nemotron-3.5-super-vl-120b-a12b
```

Other hosted models you can use include `nvidia/nemotron-3-ultra-550b-a55b`
and `nvidia/nemotron-3.5-lightning-30b-a3b`. For a self-hosted NIM, point
`base_url` at your deployment instead (for example
`http://localhost:8000/v1`) and set `model` to the id it serves.

The default `response_format_mode = "json_schema"` sends a strict JSON schema
with every extraction call. If your NIM model rejects or ignores it, set
`response_format_mode = "json_object"`, or `"prompt_only"` as the last resort.

### `[llm.<task>]`

Each place EverOS calls an LLM is a *task*. An optional `[llm.<task>]` section
Expand Down Expand Up @@ -317,38 +350,6 @@ Episodes are folded one owner at a time. A run folds the episode that triggered
|---|---|---|---|---|
| `max_episodes_per_call` | int | `10` | No | Most episodes one extraction call folds, the triggering one included; `1` folds each alone. |

#### NVIDIA NIM

[NVIDIA NIM](https://build.nvidia.com/) serves an OpenAI-compatible Chat
Completions API, so it plugs into `[llm]` like OpenRouter does: set the model,
key, and base URL. Model ids use the `<publisher>/<model>` form; pick one from
the endpoint's `/models` list.

```toml
[llm]
model = "nvidia/nemotron-3.5-super-vl-120b-a12b"
api_key = "<NVIDIA_API_KEY>"
base_url = "https://integrate.api.nvidia.com/v1"
```

Or keep the key out of the file and pass your `NVIDIA_API_KEY` through the
environment:

```bash
export EVEROS_LLM__API_KEY="$NVIDIA_API_KEY"
export EVEROS_LLM__BASE_URL=https://integrate.api.nvidia.com/v1
export EVEROS_LLM__MODEL=nvidia/nemotron-3.5-super-vl-120b-a12b
```

Other hosted models you can use include `nvidia/nemotron-3-ultra-550b-a55b`
and `nvidia/nemotron-3.5-lightning-30b-a3b`. For a self-hosted NIM, point
`base_url` at your deployment instead (for example
`http://localhost:8000/v1`) and set `model` to the id it serves.

The default `response_format_mode = "json_schema"` sends a strict JSON schema
with every extraction call. If your NIM model rejects or ignores it, set
`response_format_mode = "json_object"`, or `"prompt_only"` as the last resort.

### `[multimodal]`

| Field | Type | Default | Required | Description |
Expand Down
5 changes: 3 additions & 2 deletions src/everos/component/llm/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ class LLMCallError(LLMServiceError):

Reasons:
``refusal``: the upstream flagged a refusal (contract §3.4).
``cut_short``: the upstream reported ``length`` / ``content_filter``;
the identical request hits the same cap again (contract §3.5).
``cut_short``: the upstream reported ``content_filter``, or reported
``length`` on every attempt ``truncated_reply_retries`` allowed
(contract §3.5).
``no_content``: the upstream answered without content.
``invalid_reply``: no reply validated against ``response_format``
within the attempt budget (contract §7.1).
Expand Down
6 changes: 6 additions & 0 deletions src/everos/component/llm/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ class LLMClientConfig:
extra: Request fields merged into every call.
response_format_mode: How the reply format is requested.
invalid_reply_retries: Extra attempts after an unusable reply.
truncated_reply_retries: Extra attempts after a reply that reached the
output cap.
temperature: Sent when a call names none; ``None`` leaves it out.
max_tokens: Sent when a call names none; ``None`` leaves it out.
"""
Expand All @@ -100,6 +102,7 @@ class LLMClientConfig:
extra: dict[str, Any] = field(default_factory=dict)
response_format_mode: ResponseFormatMode = "json_schema"
invalid_reply_retries: int = 1
truncated_reply_retries: int = 1
temperature: float | None = None
max_tokens: int | None = None

Expand Down Expand Up @@ -215,6 +218,7 @@ def llm_client_config(resolution: LLMTaskResolution) -> LLMClientConfig:
extra=dict(cfg.extra),
response_format_mode=cfg.response_format_mode,
invalid_reply_retries=cfg.invalid_reply_retries,
truncated_reply_retries=cfg.truncated_reply_retries,
temperature=cfg.temperature,
max_tokens=cfg.max_tokens,
)
Expand Down Expand Up @@ -243,6 +247,7 @@ def build_llm_provider(
extra=config.extra,
response_format_mode=config.response_format_mode,
invalid_reply_retries=config.invalid_reply_retries,
truncated_reply_retries=config.truncated_reply_retries,
observer=observer,
)

Expand Down Expand Up @@ -292,6 +297,7 @@ def resolve_multimodal_config(settings: Settings) -> LLMClientConfig:
base_url=cfg.base_url,
response_format_mode=cfg.response_format_mode,
invalid_reply_retries=cfg.invalid_reply_retries,
truncated_reply_retries=cfg.truncated_reply_retries,
)


Expand Down
101 changes: 69 additions & 32 deletions src/everos/component/llm/openai_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@
``model_dump()``, multimodal parts included (§3.2).
2. ``_send`` -- one SDK call; transport retries are the SDK's ``max_retries``.
``asyncio.CancelledError`` is never caught (§3.3).
3. ``_check_upstream`` -- a flagged refusal, ``length`` / ``content_filter``
or absent content raises (§3.4, §3.5); no choice and ``abort`` / ``error``
fail only this attempt.
3. ``_check_upstream`` -- a flagged refusal, ``content_filter`` or absent
content raises (§3.4, §3.5); a ``length`` cut-off, no choice and ``abort``
/ ``error`` fail only this attempt.
4. ``_validate`` -- ``model_validate_json`` against the caller's
``response_format``; a mismatch fails only this attempt (§7.1). A reply
that validates once its trailing commas are removed is returned repaired.
5. ``_request_valid_reply`` -- at most ``1 + invalid_reply_retries`` attempts
of the identical request, each completion reported to the observer.
5. ``_request_valid_reply`` -- the identical request again after a failed
attempt, within two budgets: ``truncated_reply_retries`` after a ``length``
cut-off, ``invalid_reply_retries`` after any other. Each completion is
reported to the observer.
"""

from __future__ import annotations
Expand Down Expand Up @@ -49,13 +51,20 @@

ResponseFormatMode = Literal["json_schema", "json_object", "prompt_only"]

# The identical request hits the same output cap or the same filter again.
_CUT_SHORT_REASONS: Final = frozenset({"length", "content_filter"})
# The identical request meets the same filter again.
_FILTERED_REASONS: Final = frozenset({"content_filter"})

# The generation reached the output cap. A sampled reply that ran away usually
# finishes when sent again; one long by nature reaches the cap again, which only
# a larger max_tokens fixes, and no retry raises it (§3.1).
_CAPPED_REASONS: Final = frozenset({"length"})

# vLLM-style gateways report these when the server gave up on a generation it
# could have finished, so the identical request may well succeed.
_ABORTED_REASONS: Final = frozenset({"abort", "error"})

type _ResendableReason = Literal["invalid_reply", "transport", "cut_short"]


class _AttemptFailedError(Exception):
"""This attempt's reply is unusable, but resending the request may help.
Expand All @@ -70,11 +79,11 @@ def __init__(
self,
message: str,
*,
reason: Literal["invalid_reply", "transport"],
reason: _ResendableReason,
error_count: int | None = None,
) -> None:
super().__init__(message)
self.reason: Literal["invalid_reply", "transport"] = reason
self.reason: _ResendableReason = reason
self.error_count = error_count


Expand Down Expand Up @@ -104,12 +113,16 @@ class OpenAIProvider:
``prompt_only`` nothing (the prompt alone asks for JSON).
invalid_reply_retries: Extra attempts after an attempt whose reply
fails validation, carries no choice, or was aborted upstream.
truncated_reply_retries: Extra attempts after an attempt whose reply
reached the output cap (``finish_reason`` ``length``), counted
apart from ``invalid_reply_retries``.
observer: Notified of every completion received, failed ones included.
http_client: Passed to ``openai.AsyncOpenAI``; tests inject an
``httpx.AsyncClient`` over ``httpx.MockTransport`` here.

Raises:
ValueError: If ``invalid_reply_retries`` is negative.
ValueError: If ``invalid_reply_retries`` or ``truncated_reply_retries``
is negative.
"""

def __init__(
Expand All @@ -125,19 +138,23 @@ def __init__(
extra: Mapping[str, Any] | None = None,
response_format_mode: ResponseFormatMode = "json_schema",
invalid_reply_retries: int = 1,
truncated_reply_retries: int = 1,
observer: LLMCallObserver | None = None,
http_client: httpx.AsyncClient | None = None,
) -> None:
if invalid_reply_retries < 0:
raise ValueError(
f"invalid_reply_retries must be >= 0, got {invalid_reply_retries}"
)
for name, retries in (
("invalid_reply_retries", invalid_reply_retries),
("truncated_reply_retries", truncated_reply_retries),
):
if retries < 0:
raise ValueError(f"{name} must be >= 0, got {retries}")
self._model = model
self._temperature = temperature
self._max_tokens = max_tokens
self._extra: dict[str, Any] = dict(extra or {})
self._response_format_mode: ResponseFormatMode = response_format_mode
self._invalid_reply_retries = invalid_reply_retries
self._truncated_reply_retries = truncated_reply_retries
self._observer: LLMCallObserver = observer or NullObserver()
client_kwargs: dict[str, Any] = {
"api_key": api_key,
Expand Down Expand Up @@ -212,25 +229,37 @@ def _build_request(
async def _request_valid_reply(
self, request: dict[str, Any], response_format: type[BaseModel]
) -> str:
"""Send ``request`` until a reply passes every check, a bounded number of times.
"""Send ``request`` until a reply passes every check, within two budgets.

A reply cut off at the output cap spends ``truncated_reply_retries``;
every other failed attempt spends ``invalid_reply_retries``. Neither
spends the other's, so a runaway generation cannot use up the resend an
unparsable reply needs, nor the other way round.

Raises:
LLMCallError: As in :meth:`achat`.
"""
attempts = 1 + self._invalid_reply_retries
failure: _AttemptFailedError | None = None
for attempt in range(1, attempts + 1):
retries_left = {
"cut_short": self._truncated_reply_retries,
"other": self._invalid_reply_retries,
}
attempt = 0
while True:
attempt += 1
try:
return await self._attempt(request, response_format, attempt)
except _AttemptFailedError as exc:
failure = exc
self._log_failed_attempt(exc, attempt, attempts)
# Chained to the last ValidationError, if that is what failed last.
raise LLMCallError(
f"no usable reply in {attempts} attempts (model={self._model!r}, "
f"response_format_mode={self._response_format_mode!r}): {failure}",
reason=failure.reason if failure else "invalid_reply",
) from (failure.__cause__ if failure else None)
except _AttemptFailedError as failure:
budget = "cut_short" if failure.reason == "cut_short" else "other"
self._log_failed_attempt(failure, attempt, retries_left[budget])
if not retries_left[budget]:
# Chained to the ValidationError, if that is what failed.
raise LLMCallError(
f"no usable reply in {attempt} attempts "
f"(model={self._model!r}, response_format_mode="
f"{self._response_format_mode!r}): {failure}",
reason=failure.reason,
) from failure.__cause__
retries_left[budget] -= 1

async def _attempt(
self, request: dict[str, Any], response_format: type[BaseModel], attempt: int
Expand Down Expand Up @@ -273,15 +302,16 @@ def _observe(self, completion: ChatCompletion, attempt: int) -> None:
)

def _log_failed_attempt(
self, failure: _AttemptFailedError, attempt: int, attempts: int
self, failure: _AttemptFailedError, attempt: int, retries_left: int
) -> None:
"""Log a failed attempt; ``retries_left`` is its budget's, 0 = giving up."""
logger.warning(
"llm_attempt_failed",
reason=failure.reason,
detail=str(failure),
error_count=failure.error_count,
attempt=attempt,
attempts=attempts,
retries_left=retries_left,
model=self._model,
response_format_mode=self._response_format_mode,
)
Expand All @@ -291,8 +321,9 @@ def _check_upstream(completion: ChatCompletion) -> str:
"""Return the reply text unless the upstream reported it unusable.

Raises:
_AttemptFailedError: No choice, or a generation aborted upstream.
LLMCallError: A flagged refusal, a cut-short generation, or no content.
_AttemptFailedError: No choice, a generation that reached the output
cap, or one aborted upstream.
LLMCallError: A flagged refusal, a filtered generation, or no content.
"""
# OpenRouter answers some upstream rejections with a 200 and no choices.
if not completion.choices:
Expand All @@ -307,12 +338,18 @@ def _check_upstream(completion: ChatCompletion) -> str:
f"upstream refused (model={completion.model!r})", reason="refusal"
)
# Before the content too: a reply cut right after its closing brace parses.
if choice.finish_reason in _CUT_SHORT_REASONS:
if choice.finish_reason in _FILTERED_REASONS:
raise LLMCallError(
f"generation cut short (model={completion.model!r}, "
f"finish_reason={choice.finish_reason!r})",
reason="cut_short",
)
if choice.finish_reason in _CAPPED_REASONS:
raise _AttemptFailedError(
f"generation cut short (model={completion.model!r}, "
f"finish_reason={choice.finish_reason!r})",
reason="cut_short",
)
if choice.finish_reason in _ABORTED_REASONS:
raise _AttemptFailedError(
f"generation aborted upstream (finish_reason={choice.finish_reason!r})",
Expand Down
Loading