DEV Community

nRouter
nRouter

Posted on Originally published at nrouter.ai

One Patched Client: Putting an Instructor Workload Behind a Gateway

Every Instructor extraction in a codebase flows through one object: the patched client you build once with instructor.from_openai. That makes it the natural seam for a gateway. Change the one definition, and every extraction downstream inherits the new behaviour — fallbacks, caching, telemetry — without a single call site being edited.

The setup

import os
from openai import OpenAI
import instructor
from pydantic import BaseModel, Field

client = instructor.from_openai(
    OpenAI(
        base_url="https://api.nrouter.ai/v1",
        api_key=os.environ["NROUTER_API_KEY"],
        timeout=30.0,
        max_retries=2,
    )
)

class UserProfile(BaseModel):
    name: str = Field(description="Full name of the person")
    age: int = Field(description="Age in years")

profile = client.chat.completions.create(
    model="gpt-5.4-mini",
    response_model=UserProfile,
    max_retries=3,
    messages=[{"role": "user", "content": "Extract: Ada Lovelace, 36"}],
)
Enter fullscreen mode Exit fullscreen mode

Install line, for completeness: pip install instructor openai pydantic nrouter-sdk.

Two retry systems that do not overlap

This is the part people get wrong, so it is worth stating plainly.

Instructor's max_retries re-asks the model when the output fails validation. The call worked; the answer had the wrong shape. Retrying with the validation error in view fixes the answer.

A gateway fallback handles the opposite failure: the call itself failed — provider error, timeout, nothing came back. Re-asking a model that is down does not help, so the gateway swaps models. Fallbacks are named per request in extra_body, or you hand routing to nrouter/auto with nrouter_optimize set to quality, balanced or cost (plus a nrouter_cost_band under cost).

Validation retries fix answers. Fallbacks fix calls. Keeping them separate is what makes the pairing clean.

Caching the repeats

Document pipelines generate near-identical extractions all day. Pass "nrouter_cache": True in extra_body and an exact repeat of an earlier request is answered from cache instead of being generated again.

The record on every response

Responses carry x-nr-request-id, x-nr-model, x-nr-cost-status and x-nr-request-cost — which model answered and what the call settled at, without a separate logging layer. Guardrails run server-side before generation, so a blocked prompt or invalid parameters surface as openai.BadRequestError; rate limits surface as openai.RateLimitError, the cue to back off.

Full walkthrough: the Instructor guide.

Top comments (0)