Skip to content
ai-sdk-core logo

AI SDK Core

ai-sdk-core

Expert guidance for AI SDK Core: text generation, structured data, tool calling (tool/dynamicTool), MCP integration (createMCPClient, Experimental_StdioMCPTransport), embeddings/reranking, provider setup, middleware, telemetry, and error handling. Use when building with generateText/streamText, g...

SKILL.md

Full skill instructions

AI SDK Core

Use AI SDK Core to generate text/​structured output, call tools, and connect to MCP servers with consistent APIs across providers.

Quick Start

pnpm add ai @ai-sdk/​openai zod@^4.3.5
import { generateText } from 'ai';

const { text } = await generateText({
  model: 'openai/​gpt-4o',
  prompt: 'Explain quantum computing in one paragraph.',
});

Function Selection

NeedFunctionStreaming
Text responsegenerateTextNo
Streaming textstreamTextYes
Structured JSONgenerateObjectNo
Streaming JSONstreamObjectYes
Embeddingsembed / embedManyNo
RerankrerankNo

Core Patterns

Generate Text

import { generateText } from 'ai';

const { text, usage } = await generateText({
  model: 'anthropic/​claude-sonnet-4.5',
  system: 'You are a helpful assistant.',
  prompt: 'What is the capital of France?',
});

Stream Text

import { streamText } from 'ai';

const result = streamText({
  model: 'openai/​gpt-4o',
  prompt: 'Write a short story.',
});

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

Generate Structured Data

import { generateObject } from 'ai';
import { z } from 'zod';

const { object } = await generateObject({
  model: 'openai/​gpt-4o',
  schema: z.object({
    recipe: z.object({
      name: z.string(),
      ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
      steps: z.array(z.string()),
    }),
  }),
  prompt: 'Generate a recipe for chocolate chip cookies.',
});

Tool Calling (Typed)

import { generateText, tool } from 'ai';
import { z } from 'zod';

const { text, toolCalls } = await generateText({
  model: 'openai/​gpt-4o',
  tools: {
    weather: tool({
      description: 'Get weather for a location',
      inputSchema: z.object({ location: z.string() }),
      execute: async ({ location }) => ({ temperature: 72, condition: 'sunny' }),
    }),
  },
  prompt: 'What is the weather in San Francisco?',
});

Dynamic Tools (Runtime Schemas)

import { dynamicTool } from 'ai';
import { z } from 'zod';

const customTool = dynamicTool({
  description: 'Execute a custom function',
  inputSchema: z.object({}),
  execute: async input => ({ ok: true, input }),
});

Multi-Step Tool Execution

import { generateText, stepCountIs } from 'ai';

const { steps } = await generateText({
  model: 'openai/​gpt-4o',
  tools: { search, analyze, summarize },
  stopWhen: stepCountIs(5),
  prompt: 'Research and summarize AI developments.',
});

Tooling Checklist

  • Use tool() for typed inputs and dynamicTool() for unknown schemas.
  • Use needsApproval for sensitive actions (tool-approval-request/​response flow).
  • Use stopWhen with stepCountIs/hasToolCall for multi-step loops.
  • Use prepareStep for per-step controls (model swap, toolChoice, activeTools, prompt compression).
  • Use experimental_context when tools need app-specific context.
  • Use inputExamples and strict to improve tool call reliability.

MCP Integration (Model Context Protocol)

  • Use createMCPClient() to load MCP tools, resources, and prompts.
  • Prefer HTTP transport for production; use Experimental_StdioMCPTransport only for local Node.js servers.
  • Close MCP clients after use (try/​finally or onFinish).

See references/​mcp-integration.md for transports, schema definition, outputSchema typing, and elicitation.

Reference Files

ReferenceWhen to Use
references/​text-generation.mdgenerateText/​streamText callbacks, streaming, response handling
references/​structured-data.mdgenerateObject/​streamObject, Output API, Zod patterns
references/​tool-calling.mdtool/​dynamicTool, approval flow, repair, activeTools, hooks
references/​dynamic-tools.mddynamicTool patterns, MCP + dynamic tools, large tool sets
references/​embeddings-rag.mdembed/​embedMany, rerank, chunking
references/​providers.mdOpenAI/​Anthropic/​Google setup, registry, AI Gateway
references/​middleware.mdwrapLanguageModel, built-in/​custom middleware
references/​mcp-integration.mdMCP client, transports, tools/​resources/​prompts/​elicitation
references/​production.mdTelemetry, error handling, testing, cost control
references/​migration.mdv6 upgrade notes

Error Handling

import { generateText, AI_APICallError } from 'ai';

try {
  await generateText({ model: 'openai/​gpt-4o', prompt: 'Hello' });
} catch (error) {
  if (error instanceof AI_APICallError) {
    console.error('API Error:', error.message);
  }
}

Provider Setup

import { openai } from '@ai-sdk/​openai';

const { text } = await generateText({
  model: openai('gpt-4o'),
  prompt: 'Hello!',
});

Version Guidance

  • Use AI SDK v6+ with matching provider packages.
  • Pin major versions in package.json to avoid breaking changes.

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View