ai newsDi., 1. Dez.

Vercel AI SDK: Provider-Objekt macht Gateway-Integration zum Einzeiler

Im Vercel AI SDK wird ein Modell als Provider-Objekt übergeben, nicht als selbst konstruierter Client. Diese Stelle eignet sich ideal, um einen Gateway dazwischenzuschalten, mit nur einer Datei.

dev.toMontag 09:20 · 30.11.DE1 Min. Lesezeit
Bild: dev.to

The Vercel AI SDK's best design decision is easy to overlook: a model is a provider object you pass in, not a client you construct inside your handlers. That seam is exactly where a gateway fits — and fitting one in takes one file.

npm install ai @ai-sdk/openai zod Enter fullscreen mode Exit fullscreen mode Keep a virtual key in.env.local, then define the provider once:

// lib/ai.ts import { createOpenAI } from "@ai-sdk/openai"; export const nrouter = createOpenAI ( { apiKey: process. env. NROUTER_API_KEY, baseURL: "https://api.nrouter.ai/v1", } ); Enter fullscreen mode Exit fullscreen mode The OpenAI provider accepts a base URL, and the gateway answers at that address in the OpenAI wire format. The SDK's view of the world doesn't move.

import { streamText } from "ai"; import { nrouter } from "@/lib/ai"; export async function POST ( req: Request ) { const { messages } = await req. json ( ); const result = streamText ( { model: nrouter ( "gpt-5.4-mini" ), messages } ); return result. toDataStreamResponse ( ); } Enter fullscreen mode Exit fullscreen mode Streaming, the client hooks and the data protocol are untouched, on the Edge Runtime or Node.js.

Three things that otherwise become application code:

Error handling stays idiomatic: an onError callback on streamText sees gateway stream errors, and HTTP errors follow the gateway's documented shape.

Nothing in the app becomes gateway-shaped. You keep the SDK you chose; the routing, fallback and accounting concerns move to the layer whose job they are.

Originaltitel: One provider object: putting the Vercel AI SDK behind a gatewayQuelle: dev.to (dev.to). Original öffnen