feat(skills): add vercel-ai-sdk-expert skill for generative UI and tool calling (#220)
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
Generated at: 2026-02-08T00:00:00.000Z
|
||||
|
||||
Total skills: 1270
|
||||
Total skills: 1271
|
||||
|
||||
## architecture (78)
|
||||
|
||||
@@ -165,7 +165,7 @@ calculations | startup, business, analyst, market, opportunity | startup, busine
|
||||
| `warren-buffett` | Agente que simula Warren Buffett — o maior investidor do seculo XX e XXI, CEO da Berkshire Hathaway, discipulo de Benjamin Graham e socio intelectual de Char... | persona, investing, value-investing, business | persona, investing, value-investing, business, warren, buffett, agente, que, simula, maior, investidor, do |
|
||||
| `whatsapp-automation` | Automate WhatsApp Business tasks via Rube MCP (Composio): send messages, manage templates, upload media, and handle contacts. Always search tools first for c... | whatsapp | whatsapp, automation, automate, business, tasks, via, rube, mcp, composio, send, messages, upload |
|
||||
|
||||
## data-ai (226)
|
||||
## data-ai (227)
|
||||
|
||||
| Skill | Description | Tags | Triggers |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -393,6 +393,7 @@ Scope::with_data, save state, load state, serde,
|
||||
| `using-neon` | Guides and best practices for working with Neon Serverless Postgres. Covers getting started, local development with Neon, choosing a connection method, Neon ... | using, neon | using, neon, guides, working, serverless, postgres, covers, getting, started, local, development, choosing |
|
||||
| `vector-database-engineer` | Expert in vector databases, embedding strategies, and semantic search implementation. Masters Pinecone, Weaviate, Qdrant, Milvus, and pgvector for RAG applic... | vector, database | vector, database, engineer, databases, embedding, semantic, search, masters, pinecone, weaviate, qdrant, milvus |
|
||||
| `vector-index-tuning` | Optimize vector index performance for latency, recall, and memory. Use when tuning HNSW parameters, selecting quantization strategies, or scaling vector sear... | vector, index, tuning | vector, index, tuning, optimize, performance, latency, recall, memory, hnsw, parameters, selecting, quantization |
|
||||
| `vercel-ai-sdk-expert` | Expert in the Vercel AI SDK. Covers Core API (generateText, streamText), UI hooks (useChat, useCompletion), tool calling, and streaming UI components with Re... | vercel, ai, sdk | vercel, ai, sdk, covers, core, api, generatetext, streamtext, ui, hooks, usechat, usecompletion |
|
||||
| `vexor` | Vector-powered CLI for semantic file search with a Claude/Codex skill | vexor | vexor, vector, powered, cli, semantic, file, search, claude, codex, skill |
|
||||
| `vibe-code-auditor` | Audit rapidly generated or AI-produced code for structural flaws, fragility, and production risks. | vibe, code, auditor | vibe, code, auditor, audit, rapidly, generated, ai, produced, structural, flaws, fragility, risks |
|
||||
| `videodb-skills` | Upload, stream, search, edit, transcribe, and generate AI video and audio using the VideoDB SDK. | [video, editing, transcription, subtitles, search, streaming, ai-generation, media] | [video, editing, transcription, subtitles, search, streaming, ai-generation, media], videodb, skills, upload, stream |
|
||||
|
||||
208
README.md
208
README.md
@@ -1,7 +1,7 @@
|
||||
<!-- registry-sync: version=7.0.1; skills=1270; stars=21187; updated_at=2026-03-07T09:22:00+00:00 -->
|
||||
# 🌌 Antigravity Awesome Skills: 1,270+ Agentic Skills for Claude Code, Gemini CLI, Cursor, Copilot & More
|
||||
<!-- registry-sync: version=7.0.1; skills=1271; stars=21189; updated_at=2026-03-07T09:27:46+00:00 -->
|
||||
# 🌌 Antigravity Awesome Skills: 1,271+ Agentic Skills for Claude Code, Gemini CLI, Cursor, Copilot & More
|
||||
|
||||
> **The Ultimate Collection of 1,270+ Universal Agentic Skills for AI Coding Assistants — Claude Code, Gemini CLI, Codex CLI, Antigravity IDE, GitHub Copilot, Cursor, OpenCode, AdaL**
|
||||
> **The Ultimate Collection of 1,271+ Universal Agentic Skills for AI Coding Assistants — Claude Code, Gemini CLI, Codex CLI, Antigravity IDE, GitHub Copilot, Cursor, OpenCode, AdaL**
|
||||
|
||||
[](https://github.com/sickn33/antigravity-awesome-skills/stargazers)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
@@ -18,7 +18,12 @@
|
||||
[](apps/web-app)
|
||||
[](https://buymeacoffee.com/sickn33)
|
||||
|
||||
**Antigravity Awesome Skills** is a curated, battle-tested library of **1,270+ high-performance agentic skills** designed to work seamlessly across the major AI coding assistants.
|
||||
<<<<<<< HEAD
|
||||
**Antigravity Awesome Skills** is a curated, battle-tested library of **1,271+ high-performance agentic skills** designed to work seamlessly across the major AI coding assistants.
|
||||
=======
|
||||
**Antigravity Awesome Skills** is a curated, battle-tested library of **1,207+ high-performance agentic skills** designed to work seamlessly across the major AI coding assistants.
|
||||
|
||||
> > > > > > > HEAD@{1}
|
||||
|
||||
**Welcome to the V7.0.1 21k Stars Patch Release!** This repository gives your agent reusable playbooks for planning, coding, debugging, testing, security review, infrastructure work, product thinking, and much more.
|
||||
|
||||
@@ -26,6 +31,112 @@
|
||||
|
||||
## Table of Contents
|
||||
|
||||
<<<<<<< add-skill-vercel-ai-sdk-expert
|
||||
|
||||
- [🚀 New Here? Start Here!](#new-here-start-here)
|
||||
- [📖 Complete Usage Guide](docs/USAGE.md) - **Start here if confused after installation!**
|
||||
- [🔌 Compatibility & Invocation](#compatibility--invocation)
|
||||
- [🛠️ Installation](#installation)
|
||||
- [🧯 Troubleshooting](#troubleshooting)
|
||||
- [🎁 Curated Collections (Bundles)](#curated-collections)
|
||||
- [🧭 Antigravity Workflows](#antigravity-workflows)
|
||||
- [📦 Features & Categories](#features--categories)
|
||||
- [📚 Browse 1,271+ Skills](#browse-1271-skills)
|
||||
- [🤝 How to Contribute](#how-to-contribute)
|
||||
- [💬 Community](#community)
|
||||
- [☕ Support the Project](#support-the-project)
|
||||
- [🏆 Credits & Sources](#credits--sources)
|
||||
- [👥 Repo Contributors](#repo-contributors)
|
||||
- [⚖️ License](#license)
|
||||
- [🌟 Star History](#star-history)
|
||||
|
||||
---
|
||||
|
||||
## New Here? Start Here!
|
||||
|
||||
**Welcome to the V6.10.0 Interactive Web Edition.** This isn't just a list of scripts; it's a complete operating system for your AI Agent.
|
||||
|
||||
### 1. 🐣 Context: What is this?
|
||||
|
||||
**Antigravity Awesome Skills** (Release 6.10.0) is a massive upgrade to your AI's capabilities.
|
||||
|
||||
AI Agents (like Claude Code, Cursor, or Gemini) are smart, but they lack **specific tools**. They don't know your company's "Deployment Protocol" or the specific syntax for "AWS CloudFormation".
|
||||
**Skills** are small markdown files that teach them how to do these specific tasks perfectly, every time.
|
||||
|
||||
### 2. ⚡️ Quick Start (1 minute)
|
||||
|
||||
Install once; then use Starter Packs in [docs/BUNDLES.md](docs/BUNDLES.md) to focus on your role.
|
||||
|
||||
1. **Install**:
|
||||
|
||||
```bash
|
||||
# Default: ~/.gemini/antigravity/skills (Antigravity global). Use --path for other locations.
|
||||
npx antigravity-awesome-skills
|
||||
```
|
||||
|
||||
2. **Verify**:
|
||||
|
||||
```bash
|
||||
test -d ~/.gemini/antigravity/skills && echo "Skills installed in ~/.gemini/antigravity/skills"
|
||||
```
|
||||
|
||||
3. **Run your first skill**:
|
||||
|
||||
> "Use **@brainstorming** to plan a SaaS MVP."
|
||||
|
||||
4. **Pick a bundle**:
|
||||
- **Web Dev?** start with `Web Wizard`.
|
||||
- **Security?** start with `Security Engineer`.
|
||||
- **General use?** start with `Essentials`.
|
||||
|
||||
### 3. 🧠 How to use
|
||||
|
||||
Once installed, just ask your agent naturally:
|
||||
|
||||
> "Use the **@brainstorming** skill to help me plan a SaaS."
|
||||
> "Run **@lint-and-validate** on this file."
|
||||
|
||||
👉 **NEW:** [**Complete Usage Guide - Read This First!**](docs/USAGE.md) (answers: "What do I do after installation?", "How do I execute skills?", "What should prompts look like?")
|
||||
|
||||
👉 **[Full Getting Started Guide](docs/GETTING_STARTED.md)**
|
||||
|
||||
---
|
||||
|
||||
## Compatibility & Invocation
|
||||
|
||||
These skills follow the universal **SKILL.md** format and work with any AI coding assistant that supports agentic skills.
|
||||
|
||||
| Tool | Type | Invocation Example | Path |
|
||||
| :-------------- | :--- | :-------------------------------- | :-------------------------------------------------------------------- |
|
||||
| **Claude Code** | CLI | `>> /skill-name help me...` | `.claude/skills/` |
|
||||
| **Gemini CLI** | CLI | `(User Prompt) Use skill-name...` | `.gemini/skills/` |
|
||||
| **Codex CLI** | CLI | `(User Prompt) Use skill-name...` | `.codex/skills/` |
|
||||
| **Kiro CLI** | CLI | `(Auto) Skills load on-demand` | Global: `~/.kiro/skills/` · Workspace: `.kiro/skills/` |
|
||||
| **Kiro IDE** | IDE | `/skill-name or (Auto)` | Global: `~/.kiro/skills/` · Workspace: `.kiro/skills/` |
|
||||
| **Antigravity** | IDE | `(Agent Mode) Use skill...` | Global: `~/.gemini/antigravity/skills/` · Workspace: `.agent/skills/` |
|
||||
| **Cursor** | IDE | `@skill-name (in Chat)` | `.cursor/skills/` |
|
||||
| **Copilot** | Ext | `(Paste content manually)` | N/A |
|
||||
| **OpenCode** | CLI | `opencode run @skill-name` | `.agents/skills/` |
|
||||
| **AdaL CLI** | CLI | `(Auto) Skills load on-demand` | `.adal/skills/` |
|
||||
|
||||
> [!TIP]
|
||||
> **Default installer path**: `~/.gemini/antigravity/skills` (Antigravity global). Use `--path ~/.agent/skills` for workspace-specific install. For manual clone, `.agent/skills/` works as workspace path for Antigravity.
|
||||
> **OpenCode Path Update**: opencode path is changed to `.agents/skills` for global skills. See [Place Files](https://opencode.ai/docs/skills/#place-files) directive on OpenCode Docs.
|
||||
|
||||
> [!WARNING]
|
||||
> **Windows Users**: this repository uses **symlinks** for official skills.
|
||||
> See [Troubleshooting](#troubleshooting) for the exact fix.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
To use these skills with **Claude Code**, **Gemini CLI**, **Codex CLI**, **Kiro CLI**, **Kiro IDE**, **Cursor**, **Antigravity**, **OpenCode**, or **AdaL**:
|
||||
|
||||
### Option A: npx (recommended)
|
||||
|
||||
=======
|
||||
|
||||
- [Quick Start](#quick-start)
|
||||
- [Choose Your Tool](#choose-your-tool)
|
||||
- [What This Repo Includes](#what-this-repo-includes)
|
||||
@@ -46,6 +157,7 @@
|
||||
## Quick Start
|
||||
|
||||
1. Install once:
|
||||
> > > > > > > main
|
||||
|
||||
```bash
|
||||
npx antigravity-awesome-skills
|
||||
@@ -126,10 +238,98 @@ Use @brainstorming to turn this product idea into a concrete MVP plan.
|
||||
Use @security-auditor to review this API endpoint for auth and validation risks.
|
||||
```
|
||||
|
||||
## <<<<<<< add-skill-vercel-ai-sdk-expert
|
||||
|
||||
## Curated Collections
|
||||
|
||||
**Bundles** are curated groups of skills for a specific role or goal (for example: `Web Wizard`, `Security Engineer`, `OSS Maintainer`).
|
||||
|
||||
They help you avoid picking from 1006+ skills one by one.
|
||||
|
||||
### ⚠️ Important: Bundles Are NOT Separate Installations!
|
||||
|
||||
**Common confusion:** "Do I need to install each bundle separately?"
|
||||
|
||||
**Answer: NO!** Here's what bundles actually are:
|
||||
|
||||
**What bundles ARE:**
|
||||
|
||||
- ✅ Recommended skill lists organized by role
|
||||
- ✅ Curated starting points to help you decide what to use
|
||||
- ✅ Time-saving shortcuts for discovering relevant skills
|
||||
|
||||
**What bundles are NOT:**
|
||||
|
||||
- ❌ Separate installations or downloads
|
||||
- ❌ Different git commands
|
||||
- ❌ Something you need to "activate"
|
||||
|
||||
### How to use bundles:
|
||||
|
||||
1. **Install the repository once** (you already have all skills)
|
||||
2. **Browse bundles** in [docs/BUNDLES.md](docs/BUNDLES.md) to find your role
|
||||
3. **Pick 3-5 skills** from that bundle to start using in your prompts
|
||||
4. **Reference them in your conversations** with your AI (e.g., "Use @brainstorming...")
|
||||
|
||||
For detailed examples of how to actually use skills, see the [**Usage Guide**](docs/USAGE.md).
|
||||
|
||||
### Examples:
|
||||
|
||||
- Building a SaaS MVP: `Essentials` + `Full-Stack Developer` + `QA & Testing`.
|
||||
- Hardening production: `Security Developer` + `DevOps & Cloud` + `Observability & Monitoring`.
|
||||
- Shipping OSS changes: `Essentials` + `OSS Maintainer`.
|
||||
|
||||
## Antigravity Workflows
|
||||
|
||||
Bundles help you choose skills. Workflows help you execute them in order.
|
||||
|
||||
- Use bundles when you need curated recommendations by role.
|
||||
- Use workflows when you need step-by-step execution for a concrete goal.
|
||||
|
||||
Start here:
|
||||
|
||||
- [docs/WORKFLOWS.md](docs/WORKFLOWS.md): human-readable playbooks.
|
||||
- [data/workflows.json](data/workflows.json): machine-readable workflow metadata.
|
||||
|
||||
Initial workflows include:
|
||||
|
||||
- Ship a SaaS MVP
|
||||
- Security Audit for a Web App
|
||||
- Build an AI Agent System
|
||||
- QA and Browser Automation (with optional `@go-playwright` support for Go stacks)
|
||||
|
||||
## Features & Categories
|
||||
|
||||
The repository is organized into specialized domains to transform your AI into an expert across the entire software development lifecycle:
|
||||
|
||||
| Category | Focus | Example skills |
|
||||
| :------------- | :------------------------------------------------- | :------------------------------------------------------------------------------ |
|
||||
| Architecture | System design, ADRs, C4, and scalable patterns | `architecture`, `c4-context`, `senior-architect` |
|
||||
| Business | Growth, pricing, CRO, SEO, and go-to-market | `copywriting`, `pricing-strategy`, `seo-audit` |
|
||||
| Data & AI | LLM apps, RAG, agents, observability, analytics | `rag-engineer`, `prompt-engineer`, `langgraph` |
|
||||
| Development | Language mastery, framework patterns, code quality | `typescript-expert`, `python-patterns`, `react-patterns` |
|
||||
| General | Planning, docs, product ops, writing, guidelines | `brainstorming`, `doc-coauthoring`, `writing-plans` |
|
||||
| Infrastructure | DevOps, cloud, serverless, deployment, CI/CD | `docker-expert`, `aws-serverless`, `vercel-deployment` |
|
||||
| Security | AppSec, pentesting, vuln analysis, compliance | `api-security-best-practices`, `sql-injection-testing`, `vulnerability-scanner` |
|
||||
| Testing | TDD, test design, fixes, QA workflows | `test-driven-development`, `testing-patterns`, `test-fixing` |
|
||||
| Workflow | Automation, orchestration, jobs, agents | `workflow-automation`, `inngest`, `trigger-dev` |
|
||||
|
||||
Counts change as new skills are added. For the current full registry, see [CATALOG.md](CATALOG.md).
|
||||
|
||||
## Browse 1,271+ Skills
|
||||
|
||||
We have moved the full skill registry to a dedicated catalog to keep this README clean, and we've also introduced an interactive **Web App**!
|
||||
|
||||
### 🌐 Interactive Skills Web App
|
||||
|
||||
# A modern web interface to explore, search, and use the 1006+ skills directly from your browser.
|
||||
|
||||
```text
|
||||
Use @doc-coauthoring to rewrite our setup guide for first-time contributors.
|
||||
```
|
||||
|
||||
> > > > > > > main
|
||||
|
||||
## Browse 1,270+ Skills
|
||||
|
||||
- Open the interactive browser in [`apps/web-app`](apps/web-app).
|
||||
|
||||
@@ -298,6 +298,7 @@
|
||||
"uniprot-database",
|
||||
"uv-package-manager",
|
||||
"varlock",
|
||||
"vercel-ai-sdk-expert",
|
||||
"viral-generator-builder",
|
||||
"voice-ai-development",
|
||||
"web-artifacts-builder",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"generatedAt": "2026-02-08T00:00:00.000Z",
|
||||
"total": 1270,
|
||||
"total": 1271,
|
||||
"skills": [
|
||||
{
|
||||
"id": "00-andruia-consultant",
|
||||
@@ -29234,6 +29234,32 @@
|
||||
],
|
||||
"path": "skills/vector-index-tuning/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "vercel-ai-sdk-expert",
|
||||
"name": "vercel-ai-sdk-expert",
|
||||
"description": "Expert in the Vercel AI SDK. Covers Core API (generateText, streamText), UI hooks (useChat, useCompletion), tool calling, and streaming UI components with React and Next.js.",
|
||||
"category": "data-ai",
|
||||
"tags": [
|
||||
"vercel",
|
||||
"ai",
|
||||
"sdk"
|
||||
],
|
||||
"triggers": [
|
||||
"vercel",
|
||||
"ai",
|
||||
"sdk",
|
||||
"covers",
|
||||
"core",
|
||||
"api",
|
||||
"generatetext",
|
||||
"streamtext",
|
||||
"ui",
|
||||
"hooks",
|
||||
"usechat",
|
||||
"usecompletion"
|
||||
],
|
||||
"path": "skills/vercel-ai-sdk-expert/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "vercel-automation",
|
||||
"name": "vercel-automation",
|
||||
|
||||
222
skills/vercel-ai-sdk-expert/SKILL.md
Normal file
222
skills/vercel-ai-sdk-expert/SKILL.md
Normal file
@@ -0,0 +1,222 @@
|
||||
---
|
||||
name: vercel-ai-sdk-expert
|
||||
description: "Expert in the Vercel AI SDK. Covers Core API (generateText, streamText), UI hooks (useChat, useCompletion), tool calling, and streaming UI components with React and Next.js."
|
||||
risk: safe
|
||||
source: community
|
||||
date_added: "2026-03-06"
|
||||
---
|
||||
|
||||
# Vercel AI SDK Expert
|
||||
|
||||
You are a production-grade Vercel AI SDK expert. You help developers build AI-powered applications, chatbots, and generative UI experiences primarily using Next.js and React. You are an expert in both the `ai` (AI SDK Core) and `@ai-sdk/react` (AI SDK UI) packages. You understand streaming, language model integration, system prompts, tool calling (function calling), and structured data generation.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Use when adding AI chat or text generation features to a React or Next.js app
|
||||
- Use when streaming LLM responses to a frontend UI
|
||||
- Use when implementing tool calling / function calling with an LLM
|
||||
- Use when returning structured data (JSON) from an LLM using `generateObject`
|
||||
- Use when building AI-powered generative UIs (streaming React components)
|
||||
- Use when migrating from direct OpenAI/Anthropic API calls to the unified AI SDK
|
||||
- Use when troubleshooting streaming issues with `useChat` or `streamText`
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Why Vercel AI SDK?
|
||||
|
||||
The Vercel AI SDK is a unified framework that abstracts away provider-specific APIs (OpenAI, Anthropic, Google Gemini, Mistral). It provides two main layers:
|
||||
1. **AI SDK Core (`ai`)**: Server-side functions to interact with LLMs (`generateText`, `streamText`, `generateObject`).
|
||||
2. **AI SDK UI (`@ai-sdk/react`)**: Frontend hooks to manage chat state and streaming (`useChat`, `useCompletion`).
|
||||
|
||||
## Server-Side Generation (Core API)
|
||||
|
||||
### Basic Text Generation
|
||||
|
||||
```typescript
|
||||
import { generateText } from "ai";
|
||||
import { openai } from "@ai-sdk/openai";
|
||||
|
||||
// Returns the full string once completion is done (no streaming)
|
||||
const { text, usage } = await generateText({
|
||||
model: openai("gpt-4o"),
|
||||
system: "You are a helpful assistant evaluating code.",
|
||||
prompt: "Review the following python code...",
|
||||
});
|
||||
|
||||
console.log(text);
|
||||
console.log(`Tokens used: ${usage.totalTokens}`);
|
||||
```
|
||||
|
||||
### Streaming Text
|
||||
|
||||
```typescript
|
||||
// app/api/chat/route.ts (Next.js App Router API Route)
|
||||
import { streamText } from 'ai';
|
||||
import { openai } from '@ai-sdk/openai';
|
||||
|
||||
// Allow streaming responses up to 30 seconds
|
||||
export const maxDuration = 30;
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { messages } = await req.json();
|
||||
|
||||
const result = streamText({
|
||||
model: openai('gpt-4o'),
|
||||
system: 'You are a friendly customer support bot.',
|
||||
messages,
|
||||
});
|
||||
|
||||
// Automatically converts the stream to a readable web stream
|
||||
return result.toDataStreamResponse();
|
||||
}
|
||||
```
|
||||
|
||||
### Structured Data (JSON) Generation
|
||||
|
||||
```typescript
|
||||
import { generateObject } from 'ai';
|
||||
import { openai } from '@ai-sdk/openai';
|
||||
import { z } from 'zod';
|
||||
|
||||
const { object } = await generateObject({
|
||||
model: openai('gpt-4o-2024-08-06'), // Use models good at structured output
|
||||
system: 'Extract information from the receipt text.',
|
||||
prompt: receiptText,
|
||||
// Pass a Zod schema to enforce output structure
|
||||
schema: z.object({
|
||||
storeName: z.string(),
|
||||
totalAmount: z.number(),
|
||||
items: z.array(z.object({
|
||||
name: z.string(),
|
||||
price: z.number(),
|
||||
})),
|
||||
date: z.string().describe("ISO 8601 date format"),
|
||||
}),
|
||||
});
|
||||
|
||||
// `object` is automatically fully typed according to the Zod schema!
|
||||
console.log(object.totalAmount);
|
||||
```
|
||||
|
||||
## Frontend UI Hooks
|
||||
|
||||
### `useChat` (Conversational UI)
|
||||
|
||||
```tsx
|
||||
// app/page.tsx (Next.js Client Component)
|
||||
"use client";
|
||||
|
||||
import { useChat } from "ai/react";
|
||||
|
||||
export default function Chat() {
|
||||
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
|
||||
api: "/api/chat", // Points to the streamText route created above
|
||||
// Optional callbacks
|
||||
onFinish: (message) => console.log("Done streaming:", message),
|
||||
onError: (error) => console.error(error)
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-screen max-w-md mx-auto p-4">
|
||||
<div className="flex-1 overflow-y-auto mb-4">
|
||||
{messages.map((m) => (
|
||||
<div key={m.id} className={`mb-4 ${m.role === 'user' ? 'text-right' : 'text-left'}`}>
|
||||
<span className={`p-2 rounded-lg inline-block ${m.role === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}>
|
||||
{m.target || m.content}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="flex gap-2">
|
||||
<input
|
||||
value={input}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Say something..."
|
||||
className="flex-1 p-2 border rounded"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<button type="submit" disabled={isLoading} className="bg-black text-white p-2 rounded">
|
||||
Send
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Tool Calling (Function Calling)
|
||||
|
||||
Tools allow the LLM to interact with your code, fetching external data or performing actions before responding to the user.
|
||||
|
||||
### Server-Side Tool Definition
|
||||
|
||||
```typescript
|
||||
// app/api/chat/route.ts
|
||||
import { streamText, tool } from 'ai';
|
||||
import { openai } from '@ai-sdk/openai';
|
||||
import { z } from 'zod';
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { messages } = await req.json();
|
||||
|
||||
const result = streamText({
|
||||
model: openai('gpt-4o'),
|
||||
messages,
|
||||
tools: {
|
||||
getWeather: tool({
|
||||
description: 'Get the current weather in a given location',
|
||||
parameters: z.object({
|
||||
location: z.string().describe('The city and state, e.g. San Francisco, CA'),
|
||||
unit: z.enum(['celsius', 'fahrenheit']).optional(),
|
||||
}),
|
||||
// Execute runs when the LLM decides to call this tool
|
||||
execute: async ({ location, unit = 'celsius' }) => {
|
||||
// Fetch from your actual weather API or database
|
||||
const temp = location.includes("San Francisco") ? 15 : 22;
|
||||
return `The weather in ${location} is ${temp}° ${unit}.`;
|
||||
},
|
||||
}),
|
||||
},
|
||||
// Allows the LLM to call tools automatically in a loop until it has the answer
|
||||
maxSteps: 5,
|
||||
});
|
||||
|
||||
return result.toDataStreamResponse();
|
||||
}
|
||||
```
|
||||
|
||||
### UI for Multi-Step Tool Calls
|
||||
|
||||
When using `maxSteps`, the `useChat` hook will display intermediate tool calls if you handle them in the UI.
|
||||
|
||||
```tsx
|
||||
// Inside the `useChat` messages.map loop
|
||||
{m.role === 'assistant' && m.toolInvocations?.map((toolInvocation) => (
|
||||
<div key={toolInvocation.toolCallId} className="text-sm text-gray-500">
|
||||
{toolInvocation.state === 'result' ? (
|
||||
<p>✅ Fetched weather for {toolInvocation.args.location}</p>
|
||||
) : (
|
||||
<p>⏳ Fetching weather for {toolInvocation.args.location}...</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
- ✅ **Do:** Use `openai('gpt-4o')` or `anthropic('claude-3-5-sonnet-20240620')` format (from specific provider packages like `@ai-sdk/openai`) instead of the older edge runtime wrappers.
|
||||
- ✅ **Do:** Provide a strict Zod `schema` and a clear `system` prompt when using `generateObject()`.
|
||||
- ✅ **Do:** Set `maxDuration = 30` (or higher if on Pro) in Next.js API routes that use `streamText`, as LLMs take time to stream responses and Vercel's default is 10-15s.
|
||||
- ✅ **Do:** Use `tool()` with comprehensive `description` tags on Zod parameters, as the LLM relies entirely on those strings to understand when and how to call the tool.
|
||||
- ✅ **Do:** Enable `maxSteps: 5` (or similar) when providing tools, otherwise the LLM won't be able to reply to the user *after* seeing the tool result!
|
||||
- ❌ **Don't:** Forget to return `result.toDataStreamResponse()` in Next.js App Router API routes when using `streamText`; standard JSON responses will break chunking.
|
||||
- ❌ **Don't:** Blindly trust the output of `generateObject` without validation, even though Zod forces the shape — always handle failure states using `try/catch`.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Problem:** The streaming chat cuts off abruptly after 10-15 seconds.
|
||||
**Solution:** The serverless function timed out. Add `export const maxDuration = 30;` (or whatever your plan limit is) to the Next.js API route file.
|
||||
|
||||
**Problem:** "Tool execution failed" or the LLM didn't return an answer after using a tool.
|
||||
**Solution:** `streamText` stops immediately after a tool call completes unless you provide `maxSteps`. Set `maxSteps: 2` (or higher) to let the LLM see the tool result and construct a final text response.
|
||||
@@ -11989,6 +11989,16 @@
|
||||
"source": "community",
|
||||
"date_added": "2026-02-27"
|
||||
},
|
||||
{
|
||||
"id": "vercel-ai-sdk-expert",
|
||||
"path": "skills/vercel-ai-sdk-expert",
|
||||
"category": "uncategorized",
|
||||
"name": "vercel-ai-sdk-expert",
|
||||
"description": "Expert in the Vercel AI SDK. Covers Core API (generateText, streamText), UI hooks (useChat, useCompletion), tool calling, and streaming UI components with React and Next.js.",
|
||||
"risk": "safe",
|
||||
"source": "community",
|
||||
"date_added": "2026-03-06"
|
||||
},
|
||||
{
|
||||
"id": "vercel-automation",
|
||||
"path": "skills/vercel-automation",
|
||||
|
||||
Reference in New Issue
Block a user