Skip to content

API Reference parrot.clients.nvidia.client

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.clients.nvidia.client

View source

Nvidia NIM client for AI-Parrot.

Extends OpenAIBaseClient to route requests through Nvidia's OpenAI-compatible NIM gateway at https://integrate.api.nvidia.com/v1.

All completion, streaming, tool-calling, retry, and invoke logic is inherited from OpenAIBaseClient unchanged. Two Nvidia-specific affordances are added:

  1. The enable_thinking keyword on ask / ask_stream that injects chat_template_kwargs into extra_body for reasoning-capable models such as nvidia/nemotron-3-nano-omni-30b-a3b-reasoning.
  2. A free_tier flag (default True) that throttles outbound requests to Nvidia's free-endpoint quota of 40 requests per minute. Set free_tier=False — or NVIDIA_FREE_TIER=false in the environment — for paid/self-hosted NIM endpoints that carry no such cap.

Alias AIMessage

Re-exported from parrot.models.AIMessage.

Attribute FREE_TIER_RPM

Type: int

Attribute INJECTABLE_EXTRA_BODY_PARAMS

Type: tuple[str, ...]

Attribute INJECTABLE_SAMPLING_PARAMS

Type: tuple[str, ...]

Class NvidiaClient

Client for Nvidia NIM's OpenAI-compatible API gateway.

Routes all requests through https://integrate.api.nvidia.com/v1 and resolves the API key from the constructor argument or the NVIDIA_API_KEY environment variable (via navconfig.config).

All inherited OpenAI machinery — ask, ask_stream, invoke, _chat_completion, tool calling, structured output, and retry — works without modification.

Two Nvidia-specific affordances are layered on top:

Thinking flags. The enable_thinking shortcut on ask / ask_stream injects chat_template_kwargs into extra_body for reasoning-capable models (e.g. nvidia/nemotron-3-nano-omni-30b-a3b-reasoning). It is propagated to _chat_completion via an async context variable so that no changes to the parent's call signatures are required.

Free-tier rate limiting. Nvidia's free NIM endpoints cap traffic at 40 requests per minute. With free_tier=True (the default) every outbound request first reserves a slot in a :class:SlidingWindowRateLimiter, async-sleeping when the window is saturated so the quota is never exceeded. Set free_tier=False for paid or self-hosted NIM endpoints to remove the cap entirely. The limiter covers ask, invoke, ask_stream, and every other path routed through _chat_completion; each retry attempt consumes its own slot, since a retry is a real request. Inherited OpenAI-only vision helpers (e.g. ask_to_image) call the SDK directly and are therefore not counted.

Example::

client = NvidiaClient(model=NvidiaModel.GLM_5_2)
response = await client.ask(
    "Explain gradient descent.",
    enable_thinking=True,
)

# Paid endpoint — no throttling.
paid = NvidiaClient(free_tier=False)

# Free endpoint, but fail fast instead of waiting more than 5s.
strict = NvidiaClient(rate_limit_max_wait=5.0)
Parameter Type Default Description
api_key Optional[str] None Nvidia NIM API key. Falls back to NVIDIA_API_KEY env var (resolved via navconfig.config).
free_tier Optional[bool] None When True (default), throttle requests to requests_per_minute. When None, the value is read from the NVIDIA_FREE_TIER env var, itself defaulting to True. :data:~parrot.clients.nvidia.models.FREE_TIER_MODELS lists the models NVIDIA publishes as free preview endpoints — the ones this throttle exists for. Note that a free endpoint answers 503 ResourceExhausted when it is at capacity; that is saturation, not a bad model id, and the right response is to retry rather than switch models.
requests_per_minute Optional[int] None Requests allowed per 60s window while free_tier is active. Defaults to :data:FREE_TIER_RPM (40).
rate_limit_max_wait Optional[float] None Maximum seconds to wait for a free-tier slot. None (default) waits as long as necessary; a number makes the client raise :class:NvidiaRateLimitError rather than block past that budget.
seed Optional[int] None Default sampling seed for reproducibility, overridable per call.
reasoning_budget Optional[int] None Default cap on the tokens a reasoning model may spend on reasoning_content before it must answer, overridable per call. None (default) sends nothing and lets NIM apply its own per-model default.
**kwargs {} Additional arguments passed to OpenAIBaseClient / AbstractClient. Notably timeout (defaults to :attr:_default_timeout, 300s — reasoning calls are slow) and max_tokens (defaults to :attr:_default_max_tokens, 65536 — reasoning shares the answer's budget).

Attributes:

Attribute Type Description
client_type str
client_name str
provider_keys tuple[str, ...]
models type[Enum]
free_tier bool
requests_per_minute int
rate_limit_max_wait Optional[float]
seed Optional[int]
reasoning_budget Optional[int]

Method NvidiaClient.ask

Submit a prompt and return the full response.

Identical to OpenAIBaseClient.ask with two additions:

  1. An enable_thinking shortcut that injects chat_template_kwargs into extra_body for reasoning-capable models (e.g. nvidia/nemotron-3-nano-omni-30b-a3b-reasoning).
  2. top_p and seed support. OpenAIBaseClient.ask has a fixed signature with no **kwargs, so passing either to it raises TypeError; both are accepted here and merged into the request inside _chat_completion.

All of it travels via async context variables, so the parent's call signature is preserved.

ask(prompt: str, *, enable_thinking: bool = False, clear_thinking: bool = False, top_p: Optional[float] = None, seed: Optional[int] = None, reasoning_budget: Optional[int] = None, **kwargs) -> AIMessage

Parameter Type Default Description
prompt str User message text.
enable_thinking bool False When True, add extra_body["chat_template_kwargs"]["enable_thinking"] = True.
clear_thinking bool False Forwarded to clear_thinking in the payload when enable_thinking is True.
top_p Optional[float] None Nucleus-sampling value. Defaults to the top_p passed to the constructor; when neither is given, none is sent and the endpoint's own default applies.
seed Optional[int] None Sampling seed for reproducibility. Defaults to the seed passed to the constructor.
reasoning_budget Optional[int] None Maximum tokens a reasoning model may spend on reasoning_content before answering. Defaults to the constructor's value; when neither is given, NIM's own per-model default applies.
**kwargs {} All other keyword arguments delegated to OpenAIBaseClient.ask (e.g. model, temperature, system_prompt, session_id).

Returns: AIMessage — AIMessage with the model response. For reasoning models the thinking trace is available on AIMessage.reasoning, kept separate from the answer in AIMessage.output.

Method NvidiaClient.ask_stream

Submit a prompt and stream response chunks.

Identical to OpenAIBaseClient.ask_stream with the same enable_thinking shortcut as ask. For reasoning-capable models (e.g. nvidia/nemotron-3-nano-omni-30b-a3b-reasoning) each chunk may carry a delta.reasoning_content field in addition to delta.content.

The flags are forwarded to _chat_completion via an async context variable, so the parent's call signature is preserved.

FEAT-438 (TASK-2298/2300): ask_stream now routes through _chat_completion (the single completion funnel), so the free-tier slot is reserved there — no separate reservation is made here, which would otherwise double-count against the 40 rpm quota.

top_p, seed and reasoning_budget ARE supported here. They previously raised NotImplementedError because ask_stream did not set the _sampling_ctx context variable that _chat_completion reads. Once TASK-2298 routed the streaming path through _chat_completion as well, that limitation became stale plumbing rather than a real constraint: the injection point is shared, so setting the same context variable here is all it took. This matters most for reasoning models, whose natural mode is streaming.

ask_stream(prompt: str, *, enable_thinking: bool = False, clear_thinking: bool = False, top_p: Optional[float] = None, seed: Optional[int] = None, reasoning_budget: Optional[int] = None, **kwargs) -> AsyncIterator[str]

Parameter Type Default Description
prompt str User message text.
enable_thinking bool False When True, inject reasoning flags into extra_body.
clear_thinking bool False Forwarded to clear_thinking in the payload when enable_thinking is True.
top_p Optional[float] None Nucleus-sampling value. Defaults to the constructor's.
seed Optional[int] None Sampling seed for reproducibility. Defaults to the constructor's.
reasoning_budget Optional[int] None Maximum tokens spent on reasoning before answering. Defaults to the constructor's.
**kwargs {} All other keyword arguments delegated to OpenAIBaseClient.ask_stream (e.g. model, temperature, system_prompt, session_id).

Returns: AsyncIterator[str]

Raises:

  • NvidiaRateLimitError — If rate_limit_max_wait is set and no free-tier slot became available within that budget.

Alias NvidiaModel

Re-exported from parrot.clients.nvidia.models.NvidiaModel.

Class NvidiaRateLimitError

Raised when a free-tier slot could not be acquired within max_wait.

Only raised when :class:NvidiaClient was constructed with an explicit rate_limit_max_wait. With the default (None) the client waits as long as necessary instead of raising.

Parameter Type Default Description
message str Human-readable error description.
*args () Forwarded to :class:~parrot.exceptions.ParrotError.
retry_after Optional[float] None Seconds the caller should wait before retrying, when known.
**kwargs {} Forwarded to :class:~parrot.exceptions.ParrotError.

Attributes:

Attribute Type Description
retry_after Optional[float] Seconds until a slot is expected to free up, or None.

Alias OpenAIBaseClient

Re-exported from parrot.clients.openai_base.OpenAIBaseClient.

Alias ParrotError

Re-exported from parrot.exceptions.ParrotError.

Attribute RATE_LIMIT_WINDOW

Type: float

Class SlidingWindowRateLimiter

Async sliding-window rate limiter.

Admits at most limit acquisitions in any trailing window seconds. Unlike a fixed-window counter, a sliding window cannot be defeated by bursting across a window boundary, which matters because Nvidia measures its 40 rpm free-tier quota continuously.

Timestamps come from the running event loop's monotonic clock (loop.time()), so the limiter is unaffected by wall-clock adjustments.

The limiter is not shared between instances: each :class:NvidiaClient owns its own window. Nvidia enforces the quota per account, so N clients sharing one API key can collectively exceed 40 rpm.

Example::

limiter = SlidingWindowRateLimiter(limit=40, window=60.0)
waited = await limiter.acquire()
Parameter Type Default Description
limit int Maximum number of acquisitions per window. Must be >= 1.
window float RATE_LIMIT_WINDOW Window length in seconds. Must be > 0.

Attributes:

Attribute Type Description
limit int Maximum acquisitions allowed per window.
window float Window length in seconds.

Method SlidingWindowRateLimiter.current_usage

Return how many acquisitions currently occupy the window.

Intended for logging and tests; the value is a snapshot and may be stale as soon as it is returned. Must be called from inside a running event loop, since the window is measured on that loop's clock.

current_usage() -> int

Returns: int — Number of hits still inside the trailing window.

Raises:

  • RuntimeError — If called with no running event loop.

Method SlidingWindowRateLimiter.acquire

Reserve one slot, sleeping while the window is saturated.

acquire(max_wait: Optional[float] = None) -> float

Parameter Type Default Description
max_wait Optional[float] None Maximum total seconds to wait. None waits as long as necessary. When the projected wait exceeds this budget the call raises instead of sleeping, and no slot is consumed.

Returns: float — Total seconds spent waiting (0.0 when a slot was free).

Raises:

  • NvidiaRateLimitError — If a slot could not be reserved within max_wait seconds.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally