### Start HTTP Server with Hono Source: https://ai-sdk.dev/cookbook/api-servers/hono This is a basic example of starting an HTTP server using Hono to listen on port 8080. It's used to test API endpoints. ```bash curl -X POST http://localhost:8080 ``` -------------------------------- ### Install Exa Web Search Tool Source: https://ai-sdk.dev/cookbook/node/web-search-agent Install the Exa AI SDK package using pnpm. ```bash pnpm install @exalabs/ai-sdk ``` -------------------------------- ### Install Perplexity Search Tool Source: https://ai-sdk.dev/cookbook/node/web-search-agent Install the Perplexity AI SDK package using pnpm. ```bash pnpm install @perplexity-ai/ai-sdk ``` -------------------------------- ### Install Project Dependencies Source: https://ai-sdk.dev/cookbook/guides/slackbot Install the necessary project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Install AI SDK and DeepSeek Provider Source: https://ai-sdk.dev/cookbook/guides/deepseek-v3-2 Install the necessary packages for the AI SDK and the DeepSeek provider. This is the first step before setting up the chat endpoint. ```bash pnpm install ai @ai-sdk/deepseek @ai-sdk/react ``` -------------------------------- ### Install jsonrepair Library Source: https://ai-sdk.dev/cookbook/node/repair-json-with-jsonrepair Install the jsonrepair library using pnpm. This is the first step before using it in your project. ```bash pnpm add jsonrepair ``` -------------------------------- ### Install Exa JS Client for Custom Tools Source: https://ai-sdk.dev/cookbook/node/web-search-agent Install the exa-js client library using pnpm for building custom web search tools. ```bash pnpm install exa-js ``` -------------------------------- ### Install Parallel Web AI SDK Tools Source: https://ai-sdk.dev/cookbook/node/web-search-agent Install the Parallel Web AI SDK tools package using pnpm. ```bash pnpm install @parallel-web/ai-sdk-tools ``` -------------------------------- ### Install Tavily AI SDK Source: https://ai-sdk.dev/cookbook/node/web-search-agent Install the Tavily AI SDK package using pnpm. ```bash pnpm install @tavily/ai-sdk ``` -------------------------------- ### Install AI SDK Packages for React Source: https://ai-sdk.dev/cookbook/guides/o3 Install the necessary AI SDK packages for use with React frameworks like Next.js. This command installs the core AI SDK, the OpenAI provider, and the React integration. ```bash pnpm install ai @ai-sdk/openai @ai-sdk/react ``` -------------------------------- ### Server-Side Multi-Step Text Streaming Source: https://ai-sdk.dev/cookbook/next/stream-text-multistep Implement multi-step streaming logic on the server. This example demonstrates controlling when start and finish events are sent to the client to manage different steps within a single assistant message. ```typescript import { convertToModelMessages, createUIMessageStream, createUIMessageStreamResponse, streamText, tool, } from 'ai'; import { z } from 'zod'; export async function POST(req: Request) { const { messages } = await req.json(); const stream = createUIMessageStream({ execute: async ({ writer }) => { // step 1 example: forced tool call const result1 = streamText({ model: 'openai/gpt-4o-mini', system: 'Extract the user goal from the conversation.', messages, toolChoice: 'required', // force the model to call a tool tools: { extractGoal: tool({ inputSchema: z.object({ goal: z.string() }), execute: async ({ goal }) => goal, // no-op extract tool }), }, }); // forward the initial result to the client without the finish event: writer.merge(result1.toUIMessageStream({ sendFinish: false })); // note: you can use any programming construct here, e.g. if-else, loops, etc. // workflow programming is normal programming with this approach. // example: continue stream with forced tool call from previous step const result2 = streamText({ // different system prompt, different model, no tools: model: 'openai/gpt-4o', system: 'You are a helpful assistant with a different system prompt. Repeat the extract user goal in your answer.', // continue the workflow stream with the messages from the previous step: messages: [ ...convertToModelMessages(messages), ...(await result1.response).messages, ], }); // forward the 2nd result to the client (incl. the finish event): writer.merge(result2.toUIMessageStream({ sendStart: false })); }, }); return createUIMessageStreamResponse({ stream }); } ``` -------------------------------- ### Install Vercel CLI Source: https://ai-sdk.dev/cookbook/guides/slackbot Installs the Vercel command-line interface globally. This is the first step for deploying your application using Vercel. ```bash pnpm install -g vercel ``` -------------------------------- ### Run Knowledge Base Setup Script Source: https://ai-sdk.dev/cookbook/node/knowledge-base-agent Execute the TypeScript setup script using tsx to populate your Upstash Search database with the essay content. ```bash pnpm tsx setup.ts ``` -------------------------------- ### Copy Environment Variables File Source: https://ai-sdk.dev/cookbook/guides/natural-language-postgres Copy the example environment variables file to .env. This file will contain your API keys and database credentials. ```bash cp .env.example .env ``` -------------------------------- ### Install AI SDK and Anthropic Provider Source: https://ai-sdk.dev/cookbook/guides/claude-4 Install the necessary packages for the AI SDK and the Anthropic provider in your Next.js project. ```bash pnpm install ai @ai-sdk/anthropic ``` -------------------------------- ### Install AI SDK and Google Provider Source: https://ai-sdk.dev/cookbook/guides/gemini Install the necessary packages for the AI SDK and the Google Generative AI provider in your Next.js project. ```bash pnpm install ai @ai-sdk/google ``` -------------------------------- ### Install AI SDK and Anthropic Provider Source: https://ai-sdk.dev/cookbook/guides/computer-use Install the necessary packages for the AI SDK and the Anthropic provider. This is a prerequisite for using Anthropic models and their tools. ```bash pnpm add ai @ai-sdk/anthropic ``` -------------------------------- ### Install Project Dependencies Source: https://ai-sdk.dev/cookbook/node/knowledge-base-agent Install the necessary packages for your project, including the AI SDK, OpenAI provider, Upstash Search client, and tsx for running TypeScript scripts. ```bash pnpm i ai zod @ai-sdk/openai @upstash/search pnpm i -D tsx ``` -------------------------------- ### Install AI SDK and OpenAI Provider Source: https://ai-sdk.dev/cookbook/guides/gpt-5 Install the necessary AI SDK packages and the OpenAI provider for your Next.js application. ```bash pnpm install ai @ai-sdk/openai @ai-sdk/react ``` -------------------------------- ### Basic Agent Setup with Tool Source: https://ai-sdk.dev/cookbook/next/track-agent-token-usage Sets up a basic ToolLoopAgent with a tool and defines a type-safe AgentUIMessage for frontend communication. This is the foundational step for building an agent. ```typescript import { type InferAgentUIMessage, ToolLoopAgent, tool } from 'ai'; import { z } from 'zod'; export const agent = new ToolLoopAgent({ model: 'anthropic/claude-haiku-4.5', tools: { greet: tool({ description: 'Greets a person by their name.', inputSchema: z.object({ name: z.string() }), execute: async ({ name }) => `Greeted ${name}`, }), }, }); export type AgentUIMessage = InferAgentUIMessage; ``` -------------------------------- ### Install MCP SDK Source: https://ai-sdk.dev/cookbook/next/mcp-tools Install the official TypeScript SDK for Model Context Protocol if you prefer to use the official transports. ```bash pnpm install @modelcontextprotocol/sdk ``` -------------------------------- ### Install Dependencies for Markdown Rendering Source: https://ai-sdk.dev/cookbook/next/markdown-chatbot-with-memoization Installs the necessary libraries for rendering and parsing Markdown in your Next.js project. ```bash npm install react-markdown marked ``` -------------------------------- ### Install Dependencies for Memory Tool Source: https://ai-sdk.dev/cookbook/guides/custom-memory-tool Install the necessary dependencies for building a custom memory tool. This includes the AI SDK, Zod for schema validation, and optionally 'just-bash' for bash-backed tools. ```bash pnpm add ai just-bash zod ``` -------------------------------- ### Run Development Server Source: https://ai-sdk.dev/cookbook/guides/multi-modal-chatbot Command to start the application's development server. This allows you to run and test your multi-modal chatbot locally. ```bash pnpm run dev ``` -------------------------------- ### Deploy App with Vercel Source: https://ai-sdk.dev/cookbook/guides/slackbot Initiates the deployment process for your application using the Vercel CLI. This command will guide you through the deployment steps. ```bash vercel deploy ``` -------------------------------- ### Install AI SDK Dependencies Source: https://ai-sdk.dev/cookbook/guides/multi-modal-chatbot Install the core AI SDK and its React package using your preferred package manager. These packages are essential for building AI-powered applications. ```bash pnpm add ai @ai-sdk/react ``` ```bash npm install ai @ai-sdk/react ``` ```bash yarn add ai @ai-sdk/react ``` ```bash bun add ai @ai-sdk/react ``` -------------------------------- ### Prompt for Explaining SQL Queries Source: https://ai-sdk.dev/cookbook/guides/natural-language-postgres This prompt guides the AI model to act as a SQL expert and explain generated queries in plain English, detailing each section of the query. ```txt You are a SQL (postgres) expert. Your job is to explain to the user the SQL query you wrote to retrieve the data they asked for. The table schema is as follows: unicorns ( id SERIAL PRIMARY KEY, company VARCHAR(255) NOT NULL UNIQUE, valuation DECIMAL(10, 2) NOT NULL, date_joined DATE, country VARCHAR(255) NOT NULL, city VARCHAR(255) NOT NULL, industry VARCHAR(255) NOT NULL, select_investors TEXT NOT NULL ); When you explain you must take a section of the query, and then explain it. Each "section" should be unique. So in a query like: "SELECT * FROM unicorns limit 20", the sections could be "SELECT *", "FROM UNICORNS", "LIMIT 20". If a section doesn't have any explanation, include it, but leave the explanation empty. ``` -------------------------------- ### Using Tools with Gemini 3 Source: https://ai-sdk.dev/cookbook/guides/gemini Example of using tool calling with the AI SDK and Gemini 3 for multi-step workflows. The `stepCountIs` function enables multi-step calling. ```typescript import { z } from 'zod'; import { generateText, tool, stepCountIs } from 'ai'; import { google } from '@ai-sdk/google'; const result = await generateText({ model: google('gemini-3-pro-preview'), prompt: 'What is the weather in San Francisco?', tools: { weather: tool({ description: 'Get the weather in a location', inputSchema: z.object({ location: z.string().describe('The location to get the weather for'), }), execute: async ({ location }) => ({ location, temperature: 72 + Math.floor(Math.random() * 21) - 10, }), }), }, stopWhen: stepCountIs(5), // enables multi-step calling }); console.log(result.text); console.log(result.steps); ``` -------------------------------- ### Navigate to Project Directory Source: https://ai-sdk.dev/cookbook/guides/multi-modal-chatbot Change into the newly created project directory. ```bash cd multi-modal-agent ``` -------------------------------- ### Clone Starter Repository Source: https://ai-sdk.dev/cookbook/guides/natural-language-postgres Clone the starter repository to begin the project. Ensure you check out the 'starter' branch. ```bash git clone https://github.com/vercel-labs/natural-language-postgres cd natural-language-postgres git checkout starter ``` -------------------------------- ### Run the Agent with Sandbox and Skills Source: https://ai-sdk.dev/cookbook/guides/agent-skills Demonstrates how to initialize a sandbox, discover skills, and run the agent with user input and specific options. The agent will use the provided sandbox and skills for its operations. ```typescript // Create sandbox (your filesystem/execution abstraction) const sandbox = createSandbox({ workingDirectory: process.cwd() }); // Discover skills at startup const skills = await discoverSkills(sandbox, [ '.agents/skills', '~/.config/agent/skills', ]); // Run the agent const result = await agent.run({ prompt: userMessage, options: { sandbox, skills }, }); ``` -------------------------------- ### Install Firecrawl JS SDK Source: https://ai-sdk.dev/cookbook/node/web-search-agent Install the necessary Firecrawl JavaScript SDK package using pnpm. ```bash pnpm install @mendable/firecrawl-js ``` -------------------------------- ### Initialize and Use MCP Clients Source: https://ai-sdk.dev/cookbook/node/mcp-tools Demonstrates initializing MCP clients for stdio, http, and sse transports, retrieving tools, and using them with text generation. Ensure to close clients after use to release resources. ```typescript import { createMCPClient } from '@ai-sdk/mcp'; import { generateText, stepCountIs } from 'ai'; import { Experimental_StdioMCPTransport } from '@ai-sdk/mcp/mcp-stdio'; import { openai } from '@ai-sdk/openai'; // Optional: Official transports if you prefer them // import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio'; // import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse'; // import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp'; let clientOne; let clientTwo; let clientThree; try { // Initialize an MCP client to connect to a `stdio` MCP server (local only): const transport = new Experimental_StdioMCPTransport({ command: 'node', args: ['src/stdio/dist/server.js'], }); const clientOne = await createMCPClient({ transport, }); // Connect to an HTTP MCP server directly via the client transport config const clientTwo = await createMCPClient({ transport: { type: 'http', url: 'http://localhost:3000/mcp', // optional: configure headers // headers: { Authorization: 'Bearer my-api-key' }, // optional: provide an OAuth client provider for automatic authorization // authProvider: myOAuthClientProvider, }, }); // Connect to a Server-Sent Events (SSE) MCP server directly via the client transport config const clientThree = await createMCPClient({ transport: { type: 'sse', url: 'http://localhost:3000/sse', // optional: configure headers // headers: { Authorization: 'Bearer my-api-key' }, // optional: provide an OAuth client provider for automatic authorization // authProvider: myOAuthClientProvider, }, }); // Alternatively, you can create transports with the official SDKs instead of direct config: // const httpTransport = new StreamableHTTPClientTransport(new URL('http://localhost:3000/mcp')); // clientTwo = await createMCPClient({ transport: httpTransport }); // const sseTransport = new SSEClientTransport(new URL('http://localhost:3000/sse')); // clientThree = await createMCPClient({ transport: sseTransport }); const toolSetOne = await clientOne.tools(); const toolSetTwo = await clientTwo.tools(); const toolSetThree = await clientThree.tools(); const tools = { ...toolSetOne, ...toolSetTwo, ...toolSetThree, // note: this approach causes subsequent tool sets to override tools with the same name }; const response = await generateText({ model: 'openai/gpt-4o', tools, stopWhen: stepCountIs(5), messages: [ { role: 'user', content: [{ type: 'text', text: 'Find products under $100' }], }, ], }); console.log(response.text); } catch (error) { console.error(error); } finally { await Promise.all([ clientOne.close(), clientTwo.close(), clientThree.close(), ]); } ``` -------------------------------- ### Initialize Tool Loop Agent Source: https://ai-sdk.dev/cookbook/guides/agent-skills Sets up the agent with a model, tools, call options schema, and a preparation function. The `prepareCall` function customizes instructions and context based on provided options. ```typescript const agent = new ToolLoopAgent({ model: yourModel, tools: { loadSkill: loadSkillTool, readFile: readFileTool, bash: bashTool, }, callOptionsSchema, prepareCall: ({ options, ...settings }) => ({ ...settings, instructions: `${settings.instructions}\n\n${buildSkillsPrompt(options.skills)}`, experimental_context: { sandbox: options.sandbox, skills: options.skills, }, }), }); ``` -------------------------------- ### Create Environment File Source: https://ai-sdk.dev/cookbook/guides/multi-modal-chatbot Create a .env.local file in the project root to store environment variables, such as your Vercel AI Gateway API key. ```bash touch .env.local ``` -------------------------------- ### Clone Starter Repository Source: https://ai-sdk.dev/cookbook/guides/rag-chatbot Clone the provided starter repository to begin building the RAG chatbot. This repository includes pre-configured Drizzle ORM, migrations, and a basic resource schema. ```bash git clone https://github.com/vercel/ai-sdk-rag-starter cd ai-sdk-rag-starter ``` -------------------------------- ### Message-level vs. Block-level Cache Control Example Source: https://ai-sdk.dev/cookbook/node/dynamic-prompt-caching Illustrates how the AI SDK translates message-level provider options to block-level cache control for Anthropic models. ```typescript ```ts // What you write (message-level) { role: 'user', content: [ { type: 'text', text: 'First part' }, { type: 'text', text: 'Second part' }, ], providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } }, }, } // What the SDK sends to Anthropic (block-level) { "role": "user", "content": [ { "type": "text", "text": "First part" }, { "type": "text", "text": "Second part", "cache_control": { "type": "ephemeral" } } ] } ``` ``` -------------------------------- ### Using the Web Search Tool Source: https://ai-sdk.dev/cookbook/guides/openai-responses Demonstrates how to enable the built-in web search tool for the model to access the internet for information. ```typescript import { openai } from '@ai-sdk/openai'; import { generateText } from 'ai'; const result = await generateText({ model: openai.responses('gpt-4o-mini'), prompt: 'What happened in San Francisco last week?', tools: { web_search_preview: openai.tools.webSearchPreview(), }, }); console.log(result.text); console.log(result.sources); ``` -------------------------------- ### Stream Text with Computer Tool Source: https://ai-sdk.dev/cookbook/guides/computer-use Utilize the `streamText` function for real-time responses that can incorporate the Computer Tool. This example shows opening a browser and navigating to a URL. ```typescript const result = streamText({ model: 'anthropic/claude-sonnet-4-20250514', prompt: 'Open the browser and navigate to vercel.com', tools: { computer: computerTool }, }); for await (const chunk of result.textStream) { console.log(chunk); } ``` -------------------------------- ### Stream Text with Chat Prompt Source: https://ai-sdk.dev/cookbook/node/stream-text-with-chat-prompt Use `streamText` to get real-time text responses from a chat model. Iterate over the `textStream` to process parts of the response as they arrive. ```typescript import { streamText } from 'ai'; const result = streamText({ model: 'openai/gpt-4o', maxOutputTokens: 1024, system: 'You are a helpful chatbot.', messages: [ { role: 'user', content: [{ type: 'text', text: 'Hello!' }], }, { role: 'assistant', content: [{ type: 'text', text: 'Hello! How can I help you today?' }], }, { role: 'user', content: [{ type: 'text', text: 'I need help with my computer.' }], }, ], }); for await (const textPart of result.textStream) { process.stdout.write(textPart); } ``` -------------------------------- ### Generate Text from Prompt Source: https://ai-sdk.dev/cookbook/node/generate-text Use the `generateText` function to get a text response from a specified model based on an input prompt. Ensure the 'ai' library is imported. ```typescript import { generateText } from 'ai'; const result = await generateText({ model: 'openai/gpt-4o', prompt: 'Why is the sky blue?', }); console.log(result); ``` -------------------------------- ### Run Agent and Record Conversation Source: https://ai-sdk.dev/cookbook/guides/custom-memory-tool Initializes the agent interaction by setting a prompt, recording the user's message, running the agent, and then recording the assistant's response. This demonstrates the basic loop of user input, agent processing, and response logging. ```typescript const prompt = 'Remember that my favorite editor is Neovim'; // Record the user message await appendConversation({ role: 'user', content: prompt, timestamp: new Date().toISOString(), }); // Run the agent (loops automatically on tool calls) const result = await memoryAgent.generate({ prompt }); // Record the assistant response await appendConversation({ role: 'assistant', content: result.text, timestamp: new Date().toISOString(), }); console.log(result.text); ``` -------------------------------- ### Configure AI with Server Actions and UI State Retrieval (Server) Source: https://ai-sdk.dev/cookbook/rsc/restore-messages-from-database Define server actions and implement `onGetUIState` to retrieve and transform stored messages for the client. ```tsx import { createAI } from '@ai-sdk/rsc'; import { ServerMessage, ClientMessage, continueConversation } from './actions'; import { Stock } from '@ai-studio/components/stock'; import { generateId } from 'ai'; export const AI = createAI({ actions: { continueConversation, }, onGetUIState: async () => { 'use server'; // Get the current AI state (stored messages) const history: ServerMessage[] = getAIState(); // Transform server messages into client messages return history.map(({ role, content }) => ({ id: generateId(), role, display: role === 'function' ? : content, })); }, }); ``` -------------------------------- ### Generate Text with OpenAI Responses API Source: https://ai-sdk.dev/cookbook/guides/openai-responses Use the AI SDK to call GPT-4o with the Responses API to generate text. Ensure you have the 'ai' and '@ai-sdk/openai' packages installed. ```typescript import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; const { text } = await generateText({ model: openai.responses('gpt-4o'), prompt: 'Explain the concept of quantum entanglement.', }); ``` -------------------------------- ### Call DeepSeek R1 with AI SDK Source: https://ai-sdk.dev/cookbook/guides/r1 This snippet shows the basic usage of the AI SDK to call the DeepSeek R1 model. Ensure you have the '@ai-sdk/deepseek' package installed. ```typescript import { deepseek } from '@ai-sdk/deepseek'; import { generateText } from 'ai'; const { reasoningText, text } = await generateText({ model: deepseek('deepseek-reasoner'), prompt: 'Explain quantum entanglement.', }); ``` -------------------------------- ### Stream UI Messages with Fastify Source: https://ai-sdk.dev/cookbook/api-servers/fastify Starts a Fastify server that streams UI messages generated by the AI SDK. Ensure the AI Gateway API key is set. ```typescript import { streamText } from 'ai'; import Fastify from 'fastify'; const fastify = Fastify({ logger: true }); fastify.post('/', async function (request, reply) { const result = streamText({ model: 'openai/gpt-4o', prompt: 'Invent a new holiday and describe its traditions.', }); reply.header('Content-Type', 'text/plain; charset=utf-8'); return reply.send(result.toUIMessageStream()); }); fastify.listen({ port: 8080 }); ``` -------------------------------- ### Integrate Dynamic Prompt Caching in Agent Source: https://ai-sdk.dev/cookbook/node/dynamic-prompt-caching Use the `prepareStep` callback with `generateText` and `maxSteps` to integrate dynamic prompt caching. This example demonstrates setting up tools and applying cache control messages. ```typescript import { anthropic, generateText, tool, } from 'ai'; import { z } from 'zod'; import { addCacheControlToMessages } from './add-cache-control-to-messages'; async function main() { const result = await generateText({ model: anthropic('claude-sonnet-4-5'), prompt: 'Help me analyze this codebase and suggest improvements.', maxSteps: 10, tools: { // your tools here analyzeFile: tool({ description: 'Analyze a file in the codebase', inputSchema: z.object({ path: z.string().describe('Path to the file'), }), execute: async ({ path }) => { // implementation return { analysis: `Analysis of ${path}` }; }, }), }, prepareStep: ({ messages, model }) => ({ messages: addCacheControlToMessages({ messages, model }), }), }); console.log(result.text); } main().catch(console.error); ``` -------------------------------- ### Seed the Database Source: https://ai-sdk.dev/cookbook/guides/natural-language-postgres Initialize and seed the database with the Unicorn Companies dataset. This command may take a while to complete. ```bash pnpm run seed ``` -------------------------------- ### Initialize AI with Saved Messages (Client) Source: https://ai-sdk.dev/cookbook/rsc/restore-messages-from-database Set up the AI component in the root layout to fetch and use saved messages as the initial AI state. ```tsx import { ServerMessage } from './actions'; import { AI } from './ai'; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { // Fetch stored messages from your database const savedMessages: ServerMessage[] = getSavedMessages(); return ( {children} ); } ``` -------------------------------- ### Chat Generation Component Source: https://ai-sdk.dev/cookbook/rsc/generate-text-with-chat-prompt A React component to display a conversation history and send new messages. It manages the conversation state and uses `continueConversation` to get model responses. ```tsx 'use client'; import { useState } from 'react'; import { Message, continueConversation } from './actions'; // Allow streaming responses up to 30 seconds export const maxDuration = 30; export default function Home() { const [conversation, setConversation] = useState([]); const [input, setInput] = useState(''); return (
{conversation.map((message, index) => (
{message.role}: {message.content}
))}
{ setInput(event.target.value); }} />
); } ```