✳ainav.

tutorials

Wire a first streaming assistant with AI SDK or Genkit

A documentation-based walk through the current official minimal paths for a first streaming in-app assistant: AI SDK with Next.js App Router, and Genkit TypeScript flows. Request/response data flows and named error checks are included. Example code was not executed. npm registry versions on 10 November 2026: ai@7.0.166, genkit@1.44.0.

Wire a first streaming assistant with AI SDK or Genkit

If you want a first streaming reply inside an app you already own, you need an official minimal path — language, provider, environment variable, request/response flow, and the error points the docs actually name — not another model-chat review. AI SDK (Vercel’s ai package) and Genkit (Google’s open-source SDK) both do that job. They are not hosted models, and they are not interchangeable drop-in files. If you would rather start from a hosted app builder, that is a different article: Bolt vs Lovable vs v0 for AI App Builders.

How this article was written

Official AI SDK docs on ai-sdk.dev and Genkit docs on genkit.dev were opened first-hand on 10 November 2026 (Asia/Shanghai) and rechecked on 1 December 2026 (Asia/Shanghai). On 10 November 2026, the public npm registry reported ai@7.0.166 and genkit@1.44.0. The 1 December 2026 recheck reported ai@7.0.186 and genkit@1.44.0. The code below is copied in structure from those official pages. None of it was executed in this session. Model IDs, hook names, and helper functions are the ones on the pages that day; they change, so re-read the live docs for the version you install. No API keys were created. Examples use placeholder environment variables only, and they stay on the server.

Official minimal path: AI SDK and Next.js App Router

The current AI SDK Next.js App Router quickstart, opened on 10 November 2026 and rechecked on 1 December 2026, requires Node.js 22+ and, in that guide, a Vercel AI Gateway key. Official setup:

  1. Scaffold a Next.js app with the App Router (the guide uses pnpm create next-app@latest).
  2. Install ai, @ai-sdk/react, and zod. The Gateway provider ships with ai.
  3. Put the key in .env.local as AI_GATEWAY_API_KEY. Do not expose it to the browser or commit it.
  4. Add a Route Handler at app/api/chat/route.ts that reads messages, calls streamText, and returns a UI message stream.
  5. On the client, call useChat from @ai-sdk/react and send with sendMessage.

Official route shape from that quickstart (example, not executed):

// Example from the official AI SDK Next.js App Router quickstart.
// Not executed for this article. Use a placeholder key only, on the server.
import {
  streamText,
  UIMessage,
  convertToModelMessages,
  createUIMessageStreamResponse,
  toUIMessageStream,
} from 'ai';

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();

  const result = streamText({
    model: "anthropic/claude-sonnet-5.5",
    messages: await convertToModelMessages(messages),
  });

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  });
}

The model string "anthropic/claude-sonnet-5.5" is the official quickstart’s example, via the default Gateway provider. It is not a recommendation, and it may not be the current Gateway catalog entry the day you ship. The same official page shows a direct-provider alternative: pnpm add @ai-sdk/openai, then openai('gpt-6-astra'). Keep secrets in server environment variables either way (OPENAI_API_KEY or the provider’s documented name).

Official client shape from the same guide: a "use client" page, const { messages, sendMessage } = useChat(), and render message.parts (at least type === 'text'). useChat posts to /api/chat by default.

Data flow: the browser holds UI messages → POST /api/chat with the UIMessage[] history → the route converts them with convertToModelMessages → streamText calls the model provider → toUIMessageStream / createUIMessageStreamResponse streams parts back → useChat appends parts to the UI. The key never belongs in that client bundle.

Error and validation points named in official AI SDK docs:

  • Wrap generateText and simple textStream consumption in try/catch.
  • For streams that support error parts, iterate result.stream and handle part.type === 'error' (including StreamProviderError.isInstance, and its statusCode / isRetryable fields), plus abort and tool-error.
  • maxRetries covers failures while starting a model call. streamRetries (official, opt-in) retries well-formed provider errors after streaming has begun; omit it and that recovery is off. Retries can add latency and cost, and they cannot undo provider-executed tools.
  • onAbort runs when a stream is aborted; onEnd runs on normal completion — official docs say onEnd is not called on abort.
  • A missing or invalid Gateway key will fail on the server; treat HTTP 401/403 from the provider as a configuration error, not as something to retry blindly into a paid loop.

Official minimal path: Genkit TypeScript flows

Genkit’s TypeScript docs present a flow as the unit you run from the CLI, the Developer UI, and an HTTP server. Official languages on the get-started page include TypeScript, Go, Dart, and Python; this article follows the TypeScript flow and streaming pages only.

A documented minimal server path:

  1. Install genkit and a model plugin. The official flows page uses @genkit-ai/google-genai.
  2. Create a genkit() instance with that plugin. Put the provider key in a server environment variable (Firebase examples use a secret named GOOGLE_AI_API_KEY). Never send it to the client.
  3. ai.defineFlow with Zod inputSchema and outputSchema. Official guidance is to wrap those schemas in z.object(...).
  4. Inside the flow, ai.generate or ai.generateStream. If you requested structured output.schema and output is null, official examples throw ("Response doesn't satisfy schema.").
  5. For streaming, set streamSchema, take sendChunk from the flow’s side channel, and iterate generateStream. Callers use flow.stream(input) then for await (const chunk of response.stream), and await response.output for the final value.
  6. Local Developer UI, from the official flows page: genkit start -- tsx --watch src/your-code.ts (the tools page also shows npx genkit start -- npx tsx --watch src/index.ts). Open the documented local UI, run the flow, and inspect the trace. Official CLI: genkit flow:run menuSuggestionFlow '{"theme": "French"}' and -s for streaming.

Official streaming fragment (example, not executed):

// Example structure from official Genkit "Defining AI workflows".
// Not executed for this article. Placeholder theme only.
const response = menuSuggestionStreamingFlow.stream({ theme: "Danube" });
for await (const chunk of response.stream) {
  console.log("chunk", chunk);
}
const output = await response.output;

Data flow: a client, the CLI, or the Developer UI sends an input that must match inputSchema → the flow runs pre-steps, generate / generateStream, and post-steps → sendChunk emits streamSchema values → the complete return value must match outputSchema. You can wrap non-Genkit work in ai.run(...) so it appears as a trace step (the official menu-retrieval example).

Error and validation points from official Genkit docs:

  • Input that fails inputSchema should never enter the model call; fix the client payload.
  • Structured generation: if output == null, official samples throw rather than return a partial object.
  • Deployed callable functions: official Firebase wrapping uses onCallGenkit with secrets and an authPolicy (the docs show hasClaim('email_verified')). Do not ship a callable without an auth policy because an example omitted it.
  • startFlowServer({ flows: [...] }) serves HTTP endpoints. The official default local example uses localhost port 3400 and the flow path /menuSuggestionFlow (do not treat that as a public URL). Official curl uses POST with {"data": {"theme": "banana"}} and Accept: text/event-stream for streaming. Protect that server the same way you would any API; the bare startFlowServer snippet is a local or correctly locked-down deploy, not a public unauthenticated chat box.

What you still have to decide

Neither official path chooses your log retention, evaluation set, or production identity model for you. Keep provider keys on the server, decide whether Gateway or a direct provider package is the right auth boundary, and decide whether Genkit’s Developer UI or traces are allowed against real user prompts. Re-check the installed ai or genkit version against the docs you copy from; the registry versions noted above are a same-day snapshot, not a pin this article installed.