diff --git a/CHANGELOG.md b/CHANGELOG.md index c53aceea0..4efc94569 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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.]` 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 diff --git a/docs/configuration.md b/docs/configuration.md index c655732d3..4ee3e5ba1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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 `/` form; pick one from +the endpoint's `/models` list. + +```toml +[llm] +model = "nvidia/nemotron-3.5-super-vl-120b-a12b" +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.]` Each place EverOS calls an LLM is a *task*. An optional `[llm.]` section @@ -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 `/` form; pick one from -the endpoint's `/models` list. - -```toml -[llm] -model = "nvidia/nemotron-3.5-super-vl-120b-a12b" -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 | diff --git a/src/everos/component/llm/errors.py b/src/everos/component/llm/errors.py index 0926014bc..3b5550ddb 100644 --- a/src/everos/component/llm/errors.py +++ b/src/everos/component/llm/errors.py @@ -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). diff --git a/src/everos/component/llm/factory.py b/src/everos/component/llm/factory.py index 9899c10a7..9c26b40eb 100644 --- a/src/everos/component/llm/factory.py +++ b/src/everos/component/llm/factory.py @@ -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. """ @@ -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 @@ -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, ) @@ -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, ) @@ -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, ) diff --git a/src/everos/component/llm/openai_provider.py b/src/everos/component/llm/openai_provider.py index f20f9e666..7bd3ce301 100644 --- a/src/everos/component/llm/openai_provider.py +++ b/src/everos/component/llm/openai_provider.py @@ -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 @@ -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. @@ -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 @@ -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__( @@ -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, @@ -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 @@ -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, ) @@ -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: @@ -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})", diff --git a/src/everos/config/default.toml b/src/everos/config/default.toml index 877290154..6706d539a 100644 --- a/src/everos/config/default.toml +++ b/src/everos/config/default.toml @@ -89,8 +89,13 @@ base_url = "https://openrouter.ai/api/v1" # response_format_mode = "json_schema" # Extra attempts of the identical request after a reply that fails validation. # invalid_reply_retries = 1 -# Deadline of one request in seconds. Raise it for slow self-hosted endpoints; -# one extraction call may take up to (invalid_reply_retries + 1) x this. +# Extra attempts after a reply that reached the output cap (max_tokens), counted +# apart from invalid_reply_retries: a runaway generation usually finishes when sent +# again. A reply long by nature needs a larger max_tokens, which no retry raises. +# truncated_reply_retries = 1 +# Deadline of one request in seconds. Raise it for slow self-hosted endpoints; one +# extraction call may take up to +# (invalid_reply_retries + truncated_reply_retries + 1) x this. # timeout_seconds = 60.0 # Sent only when a call names none (agentic search keeps its own temperatures); # left unset, the request carries neither. @@ -179,6 +184,7 @@ max_concurrency = 4 # See [llm]. # response_format_mode = "json_schema" # invalid_reply_retries = 1 +# truncated_reply_retries = 1 # file:// content-item support (read locally by EverOS, not everalgo). # file_uri_allow_dirs: empty = allow any readable file (local-first default); # list base dirs to confine reads when the API is exposed. diff --git a/src/everos/config/settings.py b/src/everos/config/settings.py index 2051bac92..0be5b2afa 100644 --- a/src/everos/config/settings.py +++ b/src/everos/config/settings.py @@ -212,7 +212,8 @@ class LLMTask(StrEnum): it gets one bounded attempt: the reply is a one-word label (64 tokens, no room for a model that thinks first), and a slow or unusable reply is given up after 3 seconds rather than resent -- the SDK retries are 0 so the deadline is the -whole wait. +whole wait. A reply cut off at the 64-token cap is still sent once more, as for +every task: ``truncated_reply_retries`` has no task default. The decider runs inside a search request, so one round's deadline and retry budget are bounded by the caller waiting on it, not by ``[llm]``'s @@ -329,6 +330,13 @@ class LLMClientSettings(BaseModel): validation against the operator's model, has no choice, or was aborted by the server. Bounded here, cheaply, rather than by rerunning the whole operator; ``0`` hands the first failure straight to the caller.""" + truncated_reply_retries: int = Field(default=1, ge=0) + """Extra attempts of the identical request after a reply that reached the + output cap (``finish_reason`` ``length``), counted apart from + ``invalid_reply_retries``. A sampled reply that ran away to the cap usually + finishes when sent again; one that is long by nature reaches it again, which + only a larger ``max_tokens`` fixes -- a retry never raises it. ``0`` hands + the cut-off reply straight to the caller.""" temperature: float | None = None """Sampling temperature sent when an operator's call names none. @@ -341,8 +349,8 @@ class LLMClientSettings(BaseModel): out of the request. A reasoning model bills its thinking against it.""" sdk_max_retries: int | None = Field(default=None, ge=0) """Transport retries inside the OpenAI SDK; ``None`` keeps the SDK default. - They multiply with ``invalid_reply_retries`` and with any retry an operator - layers on top.""" + They multiply with ``invalid_reply_retries``, ``truncated_reply_retries`` + and any retry an operator layers on top.""" class LLMTaskSettings(BaseModel): @@ -365,6 +373,7 @@ class LLMTaskSettings(BaseModel): extra: dict[str, Any] | None = None response_format_mode: ResponseFormatMode | None = None invalid_reply_retries: int | None = Field(default=None, ge=0) + truncated_reply_retries: int | None = Field(default=None, ge=0) temperature: float | None = None max_tokens: int | None = Field(default=None, ge=1) sdk_max_retries: int | None = Field(default=None, ge=0) @@ -593,6 +602,9 @@ class MultimodalSettings(BaseModel): invalid_reply_retries: int = Field(default=1, ge=0) """Extra attempts after an unusable reply. See :attr:`LLMClientSettings.invalid_reply_retries`.""" + truncated_reply_retries: int = Field(default=1, ge=0) + """Extra attempts after a reply that reached the output cap. See + :attr:`LLMClientSettings.truncated_reply_retries`.""" # ``file://`` content-item support (read locally by EverOS, not everalgo). file_uri_allow_dirs: list[str] = [] diff --git a/tests/unit/test_component/test_llm/test_client.py b/tests/unit/test_component/test_llm/test_client.py index cc606b93c..ae8b16f0c 100644 --- a/tests/unit/test_component/test_llm/test_client.py +++ b/tests/unit/test_component/test_llm/test_client.py @@ -88,6 +88,7 @@ def test_llm_section_reaches_the_factory() -> None: extra={"extra_body": {"x": 1}}, response_format_mode="json_object", invalid_reply_retries=3, + truncated_reply_retries=2, temperature=0.3, max_tokens=16384, sdk_max_retries=1, @@ -103,6 +104,7 @@ def test_llm_section_reaches_the_factory() -> None: extra={"extra_body": {"x": 1}}, response_format_mode="json_object", invalid_reply_retries=3, + truncated_reply_retries=2, temperature=0.3, max_tokens=16384, ) diff --git a/tests/unit/test_component/test_llm/test_factory.py b/tests/unit/test_component/test_llm/test_factory.py index 463c9a2d4..e9d3bc0df 100644 --- a/tests/unit/test_component/test_llm/test_factory.py +++ b/tests/unit/test_component/test_llm/test_factory.py @@ -25,10 +25,15 @@ def test_builds_openai_provider() -> None: def test_passes_response_format_mode_and_retries() -> None: provider = build_llm_provider( - _config(response_format_mode="prompt_only", invalid_reply_retries=4) + _config( + response_format_mode="prompt_only", + invalid_reply_retries=4, + truncated_reply_retries=2, + ) ) assert provider._response_format_mode == "prompt_only" assert provider._invalid_reply_retries == 4 + assert provider._truncated_reply_retries == 2 def test_passes_endpoint_fields_to_the_sdk_client() -> None: diff --git a/tests/unit/test_component/test_llm/test_llm_task_resolution.py b/tests/unit/test_component/test_llm/test_llm_task_resolution.py index b9f6fae32..b39e246cc 100644 --- a/tests/unit/test_component/test_llm/test_llm_task_resolution.py +++ b/tests/unit/test_component/test_llm/test_llm_task_resolution.py @@ -39,6 +39,7 @@ "extra", "response_format_mode", "invalid_reply_retries", + "truncated_reply_retries", "temperature", "max_tokens", "sdk_max_retries", @@ -76,6 +77,7 @@ def _effective(settings: Settings, task: LLMTask) -> dict[str, Any]: "extra": {"extra_body": {"own": True}}, "response_format_mode": "prompt_only", "invalid_reply_retries": 3, + "truncated_reply_retries": 2, "temperature": 0.7, "max_tokens": 2048, "sdk_max_retries": 4, @@ -456,3 +458,14 @@ async def test_the_deciders_default_request_sets_no_output_cap( await _send(_providers(_settings())[LLMTask.DECIDER]) (body,) = wire assert sorted(body) == ["messages", "model", "response_format"] + + +@pytest.mark.parametrize("task", list(LLMTask)) +def test_every_task_takes_the_truncated_reply_retries_of_llm(task: LLMTask) -> None: + """No task has a default of its own for it, the language and decider included.""" + assert ( + _effective(_settings({"truncated_reply_retries": 3}), task)[ + "truncated_reply_retries" + ] + == 3 + ) diff --git a/tests/unit/test_component/test_llm/test_nvidia_endpoint.py b/tests/unit/test_component/test_llm/test_nvidia_endpoint.py index 1b3860ee2..c7dd21cc5 100644 --- a/tests/unit/test_component/test_llm/test_nvidia_endpoint.py +++ b/tests/unit/test_component/test_llm/test_nvidia_endpoint.py @@ -1,9 +1,11 @@ -"""NVIDIA NIM -- an ``[llm]`` section pointed at NIM reaches the SDK client. +"""NVIDIA NIM -- an ``[llm]`` section pointed at NIM reaches every task's client. NIM serves the OpenAI Chat Completions protocol, so it needs no provider of its -own: ``resolve_llm_config`` + ``build_llm_provider`` turn the section into an -``OpenAIProvider`` whose ``openai.AsyncOpenAI`` client carries NIM's base URL, -key, and model. No request is sent. +own, and ``[llm]`` is the base every ``[llm.]`` is laid over: with no task +section set, every task resolves to NIM's base URL, key, and model. The +bootstrap's path -- ``resolve_llm_tasks`` + ``llm_client_config`` + +``build_llm_task_providers`` -- then hands each task an ``OpenAIProvider`` whose +``openai.AsyncOpenAI`` client carries them. No request is sent. """ from __future__ import annotations @@ -11,52 +13,70 @@ from pydantic import SecretStr from everos.component.llm import ( + LLMClientConfig, OpenAIProvider, - build_llm_provider, + build_llm_task_providers, + llm_client_config, observer_for, - resolve_llm_config, + resolve_llm_tasks, ) -from everos.config import Settings +from everos.config import LLMTask, Settings from everos.config.settings import LLMSettings NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1" NVIDIA_MODEL = "nvidia/nemotron-3.5-super-vl-120b-a12b" +NVIDIA_KEY = "nvidia-test-key" def _settings(base_url: str = NVIDIA_BASE_URL) -> Settings: return Settings( llm=LLMSettings( model=NVIDIA_MODEL, - api_key=SecretStr("nvidia-test-key"), + api_key=SecretStr(NVIDIA_KEY), base_url=base_url, ) ) -def test_nvidia_section_resolves_to_its_endpoint() -> None: - config = resolve_llm_config(_settings()) +def _configs(settings: Settings) -> dict[LLMTask, LLMClientConfig]: + return { + task: llm_client_config(resolution) + for task, resolution in resolve_llm_tasks(settings).items() + } - assert config.model == NVIDIA_MODEL - assert config.api_key == "nvidia-test-key" - assert config.base_url == NVIDIA_BASE_URL +def _providers(settings: Settings) -> dict[LLMTask, OpenAIProvider]: + """Every task's provider, assembled as the bootstrap assembles them.""" + return build_llm_task_providers(_configs(settings), observer=observer_for(settings)) -def test_nvidia_endpoint_reaches_the_sdk_client() -> None: - settings = _settings() - provider = build_llm_provider( - resolve_llm_config(settings), observer=observer_for(settings) - ) +def _sdk_endpoint(provider: OpenAIProvider) -> tuple[str, str, str]: + """The base URL, key, and model the provider's SDK client sends.""" + client = provider._client + return str(client.base_url), client.api_key, provider._model + + +def test_nvidia_section_resolves_to_its_endpoint_for_every_task() -> None: + configs = _configs(_settings()) + + assert { + task: (config.base_url, config.api_key, config.model) + for task, config in configs.items() + } == dict.fromkeys(LLMTask, (NVIDIA_BASE_URL, NVIDIA_KEY, NVIDIA_MODEL)) - assert isinstance(provider, OpenAIProvider) - assert str(provider._client.base_url) == f"{NVIDIA_BASE_URL}/" - assert provider._client.api_key == "nvidia-test-key" - assert provider._model == NVIDIA_MODEL + +def test_nvidia_endpoint_reaches_every_tasks_sdk_client() -> None: + providers = _providers(_settings()) + + assert all(isinstance(p, OpenAIProvider) for p in providers.values()) + assert { + task: _sdk_endpoint(provider) for task, provider in providers.items() + } == dict.fromkeys(LLMTask, (f"{NVIDIA_BASE_URL}/", NVIDIA_KEY, NVIDIA_MODEL)) def test_self_hosted_nim_base_url_is_kept() -> None: - provider = build_llm_provider( - resolve_llm_config(_settings(base_url="http://localhost:8000/v1")) - ) + providers = _providers(_settings(base_url="http://localhost:8000/v1")) - assert str(provider._client.base_url) == "http://localhost:8000/v1/" + assert { + task: str(provider._client.base_url) for task, provider in providers.items() + } == dict.fromkeys(LLMTask, "http://localhost:8000/v1/") diff --git a/tests/unit/test_component/test_llm/test_openai_provider.py b/tests/unit/test_component/test_llm/test_openai_provider.py index 22dfdadbc..4b85b1b4a 100644 --- a/tests/unit/test_component/test_llm/test_openai_provider.py +++ b/tests/unit/test_component/test_llm/test_openai_provider.py @@ -104,17 +104,65 @@ async def test_refusal_raises_refusal() -> None: assert info.value.reason == "refusal" -@pytest.mark.parametrize("finish_reason", ["length", "content_filter"]) -async def test_cut_short_raises_without_retry(finish_reason: str) -> None: - upstream = _Upstream(_completion(_VALID, finish_reason=finish_reason)) +async def test_a_filtered_reply_raises_cut_short_without_a_resend() -> None: + upstream = _Upstream(_completion(_VALID, finish_reason="content_filter")) with pytest.raises(LLMCallError) as info: - await _provider(upstream, invalid_reply_retries=3).achat( + await _provider( + upstream, invalid_reply_retries=3, truncated_reply_retries=3 + ).achat(_prompt(), response_format=_Reply) + assert info.value.reason == "cut_short" + assert len(upstream.bodies) == 1 + + +async def test_a_reply_cut_off_at_the_cap_is_sent_again_unchanged() -> None: + """The resend is the identical request: ``max_tokens`` is never raised.""" + upstream = _Upstream(_completion(_VALID, finish_reason="length"), _completion()) + text = await _provider(upstream, truncated_reply_retries=1).achat( + _prompt(), response_format=_Reply, max_tokens=512 + ) + assert text == _VALID + assert len(upstream.bodies) == 2 + assert upstream.bodies[0] == upstream.bodies[1] + assert upstream.bodies[1]["max_tokens"] == 512 + + +async def test_a_reply_cut_off_past_its_budget_raises_cut_short() -> None: + upstream = _Upstream( + _completion(_VALID, finish_reason="length"), + _completion(_VALID, finish_reason="length"), + ) + with pytest.raises(LLMCallError) as info: + await _provider(upstream, truncated_reply_retries=1).achat( _prompt(), response_format=_Reply ) assert info.value.reason == "cut_short" + assert len(upstream.bodies) == 2 + + +async def test_no_truncated_reply_retries_fails_the_first_cut_off() -> None: + upstream = _Upstream(_completion(_VALID, finish_reason="length")) + with pytest.raises(LLMCallError) as info: + await _provider( + upstream, invalid_reply_retries=3, truncated_reply_retries=0 + ).achat(_prompt(), response_format=_Reply) + assert info.value.reason == "cut_short" assert len(upstream.bodies) == 1 +async def test_a_cut_off_and_an_invalid_reply_spend_separate_budgets() -> None: + """One retry each: the cut-off does not use up the invalid reply's resend.""" + upstream = _Upstream( + _completion("not json"), + _completion(_VALID, finish_reason="length"), + _completion(), + ) + text = await _provider( + upstream, invalid_reply_retries=1, truncated_reply_retries=1 + ).achat(_prompt(), response_format=_Reply) + assert text == _VALID + assert len(upstream.bodies) == 3 + + async def test_absent_content_raises_no_content() -> None: upstream = _Upstream(_completion(None)) with pytest.raises(LLMCallError) as info: @@ -162,9 +210,12 @@ async def test_resendable_upstream_failures( assert info.value.reason == "transport" -def test_negative_invalid_reply_retries_rejected() -> None: - with pytest.raises(ValueError, match="invalid_reply_retries"): - OpenAIProvider(model="m", api_key="k", invalid_reply_retries=-1) +@pytest.mark.parametrize( + "retries", ["invalid_reply_retries", "truncated_reply_retries"] +) +def test_negative_retries_rejected(retries: str) -> None: + with pytest.raises(ValueError, match=retries): + OpenAIProvider(model="m", api_key="k", **{retries: -1}) # ---------------------------------------------------------------------------