Skip to content
Skills Library
Programming · Building & coding

ai-sdk

/ai-sdk

Use when building with stable Vercel AI SDK v5 in TypeScript or React, including text and UI streaming, tool calling, multi-step execution, structured output, UIMessage conversion, and useChat client flows.

Licence
MIT
Last repository change
11.11.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
2
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 11.11.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Use when building with stable Vercel AI SDK v5 in TypeScript or React, including text and UI streaming, tool calling, multi-step execution, structured output, UIMessage conversion, and useChat client flows.

Original author description

Use when building with stable Vercel AI SDK v5 in TypeScript or React, including text and UI streaming, tool calling, multi-step execution, structured output, UIMessage conversion, and useChat client flows.

How it works

  1. When to Use
  2. Core Patterns
  3. Anti-Patterns
Original SKILL.md headings · 212 lines, 755 words
SKILL.md preview
---
name: ai-sdk
description: Use when building with stable Vercel AI SDK v5 in TypeScript or React, including text and UI streaming, tool calling, multi-step execution, structured output, UIMessage conversion, and useChat client flows.
verified: 2026-08
---

# AI SDK v5

Use stable AI SDK v5 APIs. Check installed package versions before changing an existing project.
Treat every model identifier below as a placeholder; choose a project-specific model from current
provider documentation and project evals.

## When to Use

- Build text generation or streaming in TypeScript and Next.js route handlers.
- Stream typed UI messages to React clients.
- Add server-side or client-side tools and multi-step tool loops.
- Produce schema-validated output with Zod.
- Implement chat with `useChat` from `@ai-sdk/react`.

## Core Patterns

### Generate and Stream Text

```typescript
import { generateText, streamText } from "ai";
import { openai } from "@ai-sdk/openai";

const model = openai("gpt-5.2"); // Placeholder; model choice is project-specific.

const { text } = await generateText({
  model,
  system: "Answer precisely.",
  prompt: "Summarize the incident in three bullets.",
});

const result = streamText({
  model,
  prompt: "Explain the remediation plan.",
});

for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}
```

Handle provider and validation failures at the boundary. Record model choice, latency, token use,
and retries when the application has production requirements.

### Define Tools

Use `tool()` and validate inputs with `inputSchema`.

```typescript
import { generateText, tool } from "ai";
import { z } from "zod";

const result = await generateText({
  model,
  prompt: "What is the weather in Bangkok?",
  tools: {
    getWeather: tool({
      description: "Get current weather for a city.",
      inputSchema: z.object({
        city: z.string().min(1),
      }),
      execute: async ({ city }) => weatherService.current(city),
    }),
  },
});
```

Keep side-effecting tools narrow, authorized, observable, and idempotent. Validate tool results
before passing external data back to the model.

### Run Multiple Steps

Use `stopWhen: stepCountIs(n)` on `generateText` or `streamText`.

```typescript
import { stepCountIs, streamText } from "ai";

const result = streamText({
  model,
  messages,
  tools,
  stopWhen: stepCountIs(5),
});
```

Treat the limit as a safety bound, not a target. Structured output adds one generation step, so
raise the count by one when combining it with a bounded tool loop.

### Stream UI Messages from a Route Handler

Route handlers receive `UIMessage[]`. Convert them before sending them to the model, then return a
UI message stream response.

```typescript
import {
  convertToModelMessages,
  streamText,
  type UIMessage,
} from "ai";
import { openai } from "@ai-sdk/openai";

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

  const result = streamText({
    model: openai("gpt-5.2"), // Placeholder; model choice is project-specific.
    messages: convertToModelMessages(messages),
  });

  return result.toUIMessageStreamResponse();
}
```

### Use Chat in React

Manage form state in the component. `useChat` manages messages and transport, not the input field.

```tsx
"use client";

import { useState } from "react";
import { useChat } from "@ai-sdk/react";
import {
  DefaultChatTransport,
  lastAssistantMessageIsCompleteWithToolCalls,
} from "ai";

export function Chat() {
  const [input, setInput] = useState("");
  const { messages, sendMessage, addToolOutput } = useChat({
    transport: new DefaultChatTransport({ api: "/api/chat" }),
    onToolCall({ toolCall }) {
      if (toolCall.toolName === "getBrowserLocale") {
        addToolOutput({
          tool: "getBrowserLocale",
          toolCallId: toolCall.toolCallId,
          output: navigator.language,
        });
      }
    },
    sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
  });

  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        const text = input.trim();
        if (!text) return;
        sendMessage({ text });
        setInput("");
      }}
    >
      {messages.map((message) => (
        <div key={message.id}>{message.role}</div>
      ))}
      <input value={input} onChange={(event) => setInput(event.target.value)} />
      <button type="submit">Send</button>
    </form>
  );
}
```

Do not await `addToolOutput` inside `onToolCall`; waiting there deadlocks the client tool flow.
Use `sendAutomaticallyWhen` when completed client tool calls should resume generation.

### Produce Structured Output

Use `experimental_output: Output.object({ schema })` when text generation or tools must finish with
a typed object.

```typescript
import { generateText, Output, stepCountIs, tool } from "ai";
import { z } from "zod";

const schema = z.object({
  answer: z.string(),
  sources: z.array(z.string()),
});

const result = await generateText({
  model,
  prompt: "Research the question, then return the final answer.",
  tools: {
    lookup: tool({
      description: "Look up an approved source.",
      inputSchema: z.object({ query: z.string() }),
      execute: async ({ query }) => sourceIndex.lookup(query),
    }),
  },
  stopWhen: stepCountIs(6), // Five tool-loop steps plus one structured-output step.
  experimental_output: Output.object({ schema }),
});

const typedAnswer = result.experimental_output;
```

For pure structured generation without tools or surrounding text, `generateObject` and
`streamObject` remain available in v5.

## Anti-Patterns

- Do not use the v4 tool field `parameters:`; use `inputSchema`.
- Do not use `maxSteps`; use `stopWhen: stepCountIs(n)`.
- Do not return `toDataStreamResponse`; return `toUIMessageStreamResponse` for UI chat streams.
- Do not expect `useChat` to expose or manage `input`, `handleInputChange`, or form submission.
- Do not copy gpt-4o-era model identifiers into examples; use placeholders and make model choice
  project-specific.
- Do not await client `addToolOutput` from inside `onToolCall`.

AI SDK 6 is in beta (`ToolLoopAgent`, stable `output` parameter); this skill covers stable v5.
Files in this package (2)
  • SKILL.md 6 KB
  • agents/openai.yaml 1 KB

Versions

RepositoryScoreLicence
This page · LineLuLan/line-harness100MIT
vercel-labs/ai100Apache-2.0
laguagu/claude-code-nextjs-skills100MIT
TerminalSkills/skills98Apache-2.0
solidSpoon/DashPlayer95AGPL-3.0

Database snapshot: 13.11.2026 · package version 92e6956a25a2 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100vercel-ai-sdk
    Vercel AI SDK for building chat interfaces with streaming. Use when implementing useChat hook, handling tool calls, streaming responses, or building chat UI. Triggers on useChat, @ai-sdk/react, UIMessage, ChatStatus, streamText, toUIMessageStreamResponse, addToolOutput, onToolCall, sendMessage.
  • 98vercel-ai-sdk-streaming
    Vercel AI SDK 5 (`ai` + `@ai-sdk/*` providers) — streamText/generateText/generateObject, useChat hook with streaming UI, structured outputs with Zod, tool calling and multi-step agents, provider abstraction (Anthropic/OpenAI/Google/Mistral), middleware, RAG patterns, Edge…
  • 100vercel-ai-sdk
    Decision guide for the Vercel AI SDK (`ai` and `@ai-sdk/*`) in TypeScript, covering the version matrix, agent loop, structured output, tool approval, streaming, testing, and migration traps. Use when building or upgrading AI SDK code.
  • 100ai-sdk-6
    Vercel AI SDK v6 development, for projects already on ai@6. Use when building or maintaining AI agents, chatbots, tool integrations, streaming apps, or structured output in a v6 codebase. New projects and ai@7 code use ai-sdk-7; an unknown version goes through ai-sdk. Covers…
  • 100laravel-ai-sdk
    Use when integrating AI agents, tool calling, embeddings, structured output, or streaming in Laravel 13 via the `laravel/ai` package.
  • 100analyticscli-ts-sdk
    Use when integrating or upgrading the AnalyticsCLI TypeScript SDK in web, TypeScript, React Native, or Expo apps.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.