Skip to main content

Your Java service does not need a second AI client

Updated 2 min readMarkdown

Every gateway integration eventually faces the same question: do we adopt the gateway's own client library, with its own types and its own learning curve, or do we keep the client we have? nRouter's Java SDK guide is interesting because it refuses the trade-off. The SDK's entire job is one static factory call — after that, you are holding the standard OpenAI Java client.

What the integration actually looks like

Dependency. ai.nrouter:nrouter-sdk:3.1.2 from Maven Central, in pom.xml or as a Gradle implementation line. A pinned release.

Configuration. Export NROUTER_API_KEY. Call NRouter.create(). It reads the environment, targets https://api.nrouter.ai/v1, and returns a configured OpenAIClient (com.openai.client.OpenAIClient).

Requests. Unchanged OpenAI Java: ChatCompletionCreateParams.builder().model(...).addMessage(...).build(), passed to client.chat().completions().create(params). Builder-typed, compiler-checked, identical to the code a team already has in production if it uses the OpenAI Java SDK today.

Streaming. createStreaming(params) returns chunks as a stream; .stream().forEach(chunk -> chunk.choices().get(0).delta().content().ifPresent(System.out::print)) is the whole consumer.

Where the gateway shows up

Two places, both small:

  1. Routing preferences. With model("nrouter/auto"), attach nrouter_optimize ("quality", "balanced" or "cost") via putAdditionalBodyProperty, plus nrouter_cost_band ("low", "mid", "high") when optimising for cost. Preferences on the standard request object — not a second API.
  2. Error causes. Exceptions stay the standard ladder — BadRequestException, AuthenticationException, RateLimitException, OpenAIException — while gateway-specific causes such as guardrail_blocked and cost_band_unsatisfiable arrive inside the BadRequestException message, where a catch block can branch on them.

The client is documented thread-safe, so a single instance can be a Spring bean or a shared static for the service.

Why this shape matters

SDK surface area is a liability. Every proprietary type a gateway introduces is a type your team must learn, mock in tests, and unwind if you ever leave. By returning the standard client, this SDK keeps the exit cost at "change the factory call" and the adoption cost at "read one page". That is a defensible engineering position, and it is rarer than it should be.

Full guide: https://nrouter.ai/docs/sdks/java

About the author

  • nRouter is a managed LLM gateway: one OpenAI-compatible API key, with smart routing, automatic failover, guardrails, virtual keys, and per-key budgets enforced in the request path.

No comments yet. Be the first to comment.

More from this blog