Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

vercel-ai-sdk

БесплатноБез исполняемых скриптовНе проверен

Comprehensive guide to Vercel AI SDK for building AI-powered applications with text generation, streaming, tool calling, autonomous agents, and React UI…

diegosouzapwот diegosouzapw★ 68 звёзд на GitHub

Об этом скилле

Vercel AI SDK Expert

Build production-ready AI applications with streaming, tool calling, autonomous agents, and polished UI components. This skill covers the AI SDK Core (text generation, structured output, tools), AI SDK UI (React hooks), AI SDK RSC (experimental server components), and AI Elements (pre-built UI components).

Installation

# Core SDK + Anthropic provider (recommended)
npm install ai @ai-sdk/anthropic zod

# React hooks for UI
npm install @ai-sdk/react

# AI Elements components (requires shadcn/ui)
npx ai-elements@latest add message prompt-input conversation

Prerequisites:

  • Node.js 18+
  • Next.js (App Router recommended)
  • Anthropic API key: ANTHROPIC_API_KEY in .env.local
  • For AI Elements: shadcn/ui, Tailwind CSS 4, React 19

Quick Start: Chat with Tools

// app/api/chat/route.ts
import { anthropic } from "@ai-sdk/anthropic";
import { streamText, tool } from "ai";
import { z } from "zod";

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

  const result = streamText({
    model: anthropic("claude-sonnet-4-5"),
    messages,
    tools: {
      getWeather: tool({
        description: "Get weather for a location",
        parameters: z.object({
          location: z.string(),
        }),
        execute: async ({ location }) => ({
          temperature: 72,
          condition: "sunny",
        }),
      }),
    },
  });

  return result.toDataStreamResponse();
}
// app/page.tsx
'use client';
import { useChat } from '@ai-sdk/react';
import { Message, PromptInput } from '@/components/ai-elements';

export default function Chat() {
  const { messages, sendMessage, status } = useChat();

  return (
    <div>
      {messages.map(msg => (
        <Message key={msg.id} from={msg.role}>
          {msg.content}
        </Message>
      ))}
      <PromptInput
        onSubmit={({ text }) => sendMessage({ content: text })}
        disabled={status === 'streaming'}
      />
    </div>
  );
}

Core Concepts

1. Text Generation

streamText() - Stream responses for interactive UIs

  • Real-time token streaming to client
  • Tool calling with automatic execution
  • Callbacks: onChunk, onFinish, onStepFinish
  • Returns: toDataStreamResponse(), textStream, fullStream

generateText() - Synchronous generation for non-interactive tasks

  • Await full completion (drafts, summaries, agents)
  • Tool calling with multiple rounds
  • Returns: text, toolCalls, toolResults, usage, steps

generateObject() - Structured output with Zod schema validation

  • Extract typed data from unstructured input
  • Returns: object, usage, warnings

See references/core-api.md for full API reference.

2. Tool Calling

Define tools with tool() helper:

tool({
  description: "Present options to user as buttons",
  parameters: z.object({
    question: z.string(),
    options: z.array(z.string()),
  }),
  execute: async ({ question, options }) => {
    return { selected: null }; // UI-only tool
  },
});

Key Patterns:

  • Multi-step: Use maxSteps or stopWhen for tool loops
  • UI-only tools: Return minimal data, render in client
  • Programmatic tools (Anthropic): Tools callable from code execution

See references/agents.md for workflow patterns.

3. Autonomous Agents

ToolLoopAgent - Multi-step autonomous agent

import { ToolLoopAgent } from "ai/agents";

const agent = new ToolLoopAgent({
  model: anthropic("claude-sonnet-4-5"),
  instructions: systemPrompt,
  tools: { searchDocs, updateSpec, scheduleCall },
  stopWhen: (result) => {
    // Stop when UI-only tool called
    return result.steps.some(
      (step) =>
        "toolCalls" in step &&
        step.toolCalls.some((tc) => tc.toolName === "scheduleCall"),
    );
  },
});

const result = await agent.execute({ messages });
return createAgentUIStreamResponse({ result }).toUIMessageStreamResponse();

See references/agents.md for loop control and oyster patterns.

4. React Hooks (AI SDK UI)

useChat() - Complete chat interface state management

  • Messages: Array of UIMessage with parts (text, tool-call, tool-result)
  • sendMessage(): Send with optional files, metadata
  • Status: 'ready' | 'submitted' | 'streaming' | 'error'
  • Transports: DefaultChatTransport (HTTP), DirectChatTransport (in-process)
const { messages, sendMessage, status, stop, reload } = useChat({
  api: "/api/chat",
  onToolCall: ({ toolCall }) => {
    if (toolCall.toolName === "updateSpec") {
      setSpec(toolCall.input);
    }
  },
});

See references/ui-hooks.md for full hook APIs.

5. AI Elements Components

Pre-built, customizable components built on shadcn/ui:

  • <Message> - Container with role-based styling (from="user" | "assistant")
  • **`<Me
Полный SKILL.md на GitHub

Установить vercel-ai-sdk в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

metadata.json

FAQ

Что делает скилл vercel-ai-sdk?

Comprehensive guide to Vercel AI SDK for building AI-powered applications with text generation, streaming, tool calling, autonomous agents, and React UI integration. Use when working with AI SDK, Vercel AI, useChat, streamText, generateText, generateObject, tool calling, LLM tools, AI agents, streaming chat, chatbots, AI Elements, PromptInput, Message components, streamUI, or building conversational interfaces with language models. Focuses on Anthropic Claude with extended thinking, prompt caching, and code execution.

Как установить скилл vercel-ai-sdk?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл vercel-ai-sdk запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить vercel-ai-sdk с