### Install and Run AI SDK Zustand Example Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Bash commands to install dependencies and start the development server for the AI SDK Zustand example. Requires Node.js and npm to be installed. ```bash # Install dependencies npm install # Start the development server npm run dev # Open http://localhost:3000 ``` -------------------------------- ### Install AI SDK OCR Tool Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/ocr/README.md Installs the AI SDK OCR tool package using npm or bun. This is the first step to using the OCR functionality. ```bash npm install @ai-sdk-tools/ocr # or bun add @ai-sdk-tools/ocr ``` -------------------------------- ### Install @ai-sdk-tools/artifacts and @ai-sdk-tools/store Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/artifacts/README.md Install the necessary packages for artifact streaming and message state management. Both @ai-sdk-tools/artifacts and @ai-sdk-tools/store are required for full functionality. ```bash npm install @ai-sdk-tools/artifacts @ai-sdk-tools/store ``` -------------------------------- ### Install @ai-sdk-tools/memory package (bash) Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/memory/README.md Installs the core memory library using a package manager of your choice. Supports npm, yarn, pnpm, and bun. Run the command in your project directory before using any providers. ```bash npm install @ai-sdk-tools/memory\n# or\nyarn add @ai-sdk-tools/memory\n# or\npnpm add @ai-sdk-tools/memory\n# or\nbun add @ai-sdk-tools/memory ``` -------------------------------- ### Install AI SDK Tools Memory and Drizzle ORM Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/memory/DRIZZLE.md Installs the necessary packages for the Drizzle Provider and Drizzle ORM using npm, bun, pnpm, or yarn. Also includes instructions for installing specific database drivers. ```bash npm install @ai-sdk-tools/memory drizzle-orm # or bun add @ai-sdk-tools/memory drizzle-orm # or pnpm add @ai-sdk-tools/memory drizzle-orm # or yarn add @ai-sdk-tools/memory drizzle-orm # PostgreSQL npm install @vercel/postgres # or npm install @neondatabase/serverless # MySQL npm install @planetscale/database # SQLite npm install better-sqlite3 ``` -------------------------------- ### Installing @ai-sdk-tools/store Package Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/store/README.md Install the store package using npm or bun for high-performance AI SDK integration. This command adds the dependency to your project without additional configuration. It supports both Node.js and Bun package managers. ```bash npm install @ai-sdk-tools/store # or bun add @ai-sdk-tools/store ``` -------------------------------- ### Install @ai-sdk-tools/agents Package Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/agents/README.md Installs the necessary packages for multi-agent orchestration using AI SDK v5, including the agents package, AI SDK core, and Zod for schema validation. ```bash npm install @ai-sdk-tools/agents ai zod ``` -------------------------------- ### Install ai-sdk-tools Package and Dependencies Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/ai-sdk-tools/README.md Install the main ai-sdk-tools package and its peer dependencies. The main package includes all tools with namespaced exports, while peer dependencies provide required functionality for AI SDK integration, React components, and schema validation. ```bash npm install ai-sdk-tools ``` ```bash npm install ai @ai-sdk/react react react-dom zod zustand ``` ```bash npm install @ai-sdk-tools/agents npm install @ai-sdk-tools/artifacts npm install @ai-sdk-tools/cache npm install @ai-sdk-tools/devtools npm install @ai-sdk-tools/memory npm install @ai-sdk-tools/store ``` -------------------------------- ### Install @ai-sdk-tools/cache with npm or bun Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/cache/README.md Installs the caching library using either npm or bun package managers. This is the first step to enabling caching for your AI SDK tools. ```bash npm install @ai-sdk-tools/cache # or bun add @ai-sdk-tools/cache ``` -------------------------------- ### Install @ai-sdk-tools/debug package using npm Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/debug/README.md Installs the debug utilities package from npm registry. No additional dependencies are required. This command adds the package to your project for immediate use. ```bash npm install @ai-sdk-tools/debug ``` -------------------------------- ### Install AI SDK Tools packages using npm Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/README.md Provides npm commands to install the unified package or individual sub‑packages. Run these in a bash-compatible terminal. No additional dependencies are required beyond npm. ```bash npm install ai-sdk-tools ``` ```bash npm i @ai-sdk-tools/store ``` ```bash npm i @ai-sdk-tools/devtools ``` ```bash npm i @ai-sdk-tools/artifacts @ai-sdk-tools/store ``` ```bash npm i @ai-sdk-tools/agents ai zod ``` ```bash npm i @ai-sdk-tools/cache ``` ```bash npm i @ai-sdk-tools/memory ``` -------------------------------- ### Implement Tool Calls with Weather Calculator and Search Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Implementation examples of three different tools - weather information, mathematical calculations, and search functionality. Each tool uses Zod for parameter validation and async execution functions. ```tsx // Weather Tool getWeather: tool({ description: 'Get current weather information', parameters: z.object({ location: z.string().describe('The location to get weather for'), }), execute: async ({ location }) => { // Mock weather API call return mockWeatherData[location.toLowerCase()]; }, }) // Calculator Tool calculate: tool({ description: 'Perform mathematical calculations', parameters: z.object({ expression: z.string().describe('Mathematical expression to evaluate'), }), execute: async ({ expression }) => { // Safe expression evaluation return { result: eval(sanitizedExpression), expression }; }, }) // Search Tool search: tool({ description: 'Search for information', parameters: z.object({ query: z.string().describe('Search query'), limit: z.number().optional().describe('Max results (default: 3)'), }), execute: async ({ query, limit = 3 }) => { // Mock search results return { results: mockResults.slice(0, limit) }; }, }) ``` -------------------------------- ### Reusable Cache Configuration Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/cache/README.md Configure a reusable cache function for consistent setup across your application. This example demonstrates setting up a Redis cache backend and exporting a configured `cached` function. ```APIDOC ## Reusable Cache Configuration For consistent setup across your app, create a configured cache function: ```typescript // src/lib/cache.ts import { cached as baseCached, createCacheBackend } from '@ai-sdk-tools/cache'; import { getContext } from '@/ai/context'; // Create cache backend const cacheBackend = createCacheBackend({ type: 'redis', redis: { client: Redis.createClient({ url: process.env.REDIS_URL }), keyPrefix: 'my-app:', }, }); // Export configured cache function export function cached(tool: T, options = {}) { return baseCached(tool, { store: cacheBackend, cacheKey: () => { const currentUser = getCurrentUser(); return `team:${currentUser.teamId}:user:${currentUser.id}`; }, ttl: 30 * 60 * 1000, // 30 minutes debug: process.env.NODE_ENV === 'development', ...options, }); } // Throughout your app import { cached } from '@/lib/cache'; export const myTool = cached(originalTool); ``` ``` -------------------------------- ### Install AI SDK Devtools Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/devtools/README.md Installs the main AI SDK Devtools package using npm. This is the primary package required for utilizing the debugging and monitoring features. ```bash npm install @ai-sdk-tools/devtools ``` -------------------------------- ### Next.js with Neon and DrizzleProvider Setup Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/memory/DRIZZLE.md TypeScript setup for a Next.js application using Neon serverless database and Drizzle ORM. Includes database connection configuration and DrizzleProvider initialization for memory storage. ```typescript // lib/db.ts import { neon } from "@neondatabase/serverless"; import { drizzle } from "drizzle-orm/neon-http"; const sql = neon(process.env.DATABASE_URL!); export const db = drizzle(sql); // lib/memory.ts import { DrizzleProvider } from "@ai-sdk-tools/memory"; import { db } from "./db"; import { workingMemory, messages } from "./schema"; export const memoryProvider = new DrizzleProvider(db, { workingMemoryTable: workingMemory, messagesTable: messages, }); ``` -------------------------------- ### useChatIsLoading Hook API Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Hook that provides loading state information with optional store ID support. ```APIDOC ## useChatIsLoading(storeId?) ### Description Hook to get the loading state of the chat interface. ### Method HOOK ### Parameters #### Path Parameters - **storeId** (string) - Optional - Identifier for specific chat store ### Response #### Returns - **isLoading** (boolean) - True when chat is processing ``` -------------------------------- ### OCR API Usage Example Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/ocr/README.md Provides an example of calling the `ocr` function with specific options. It shows how to configure providers (Mistral, Gemini), set retry counts, and define a timeout for the operation. ```typescript const result = await ocr(imageBuffer, 'invoice', { providers: { mistral: { model: 'mistral-medium-latest' }, gemini: { model: 'gemini-1.5-pro' } }, retries: 3, timeout: 20000 }); ``` -------------------------------- ### Install Optional Store Integration for AI SDK Devtools Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/devtools/README.md Installs the optional store package for AI SDK Devtools, which enhances state debugging capabilities, particularly for Zustand stores. This package is a peer dependency and works seamlessly with the main devtools package. ```bash npm install @ai-sdk-tools/store ``` -------------------------------- ### Combining Hooks Example Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/artifacts/README.md Demonstrates how to effectively use both `useArtifact` and `useArtifacts` hooks together in a React component for comprehensive artifact management and display. ```APIDOC ## Combining Both Hooks ### Description Illustrates how to use both `useArtifact` for specific data display and `useArtifacts` for global notifications and overviews within a single component. ### Method Combination of `useArtifact` and `useArtifacts` (React Hooks) ### Request Example ```tsx import { useArtifact, useArtifacts } from '@ai-sdk-tools/artifacts/client'; function DashboardWithAnalysis() { // Listen to all artifacts for notifications and analytics useArtifacts({ onData: (artifactType, data) => { console.log('Artifact updated:', artifactType, data); // Example: Send to analytics or show toast notifications if (data.status === 'complete') { toast.success(`${artifactType} analysis complete!`); } } }); // Consume a specific artifact for detailed display const { data: burnRateData, status: burnRateStatus } = useArtifact(burnRateArtifact); // Get a general overview of the latest artifacts const { latest } = useArtifacts(); return (
{/* Overview section */}
{Object.entries(latest).map(([type, artifact]) => (

{type}

{artifact.status}
))}
{/* Detailed section for a specific artifact */} {burnRateData && ( )}
); } ``` ``` -------------------------------- ### Selective Selectors for Optimized Re-renders Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Examples of optimized selectors that prevent unnecessary component re-renders by only updating when specific state changes. Includes built-in selectors and custom property selectors. ```tsx // Only re-renders when message count changes const messageCount = useChatMessageCount(); // Only re-renders when loading state changes const isLoading = useChatIsLoading(); // Custom selector - only re-renders when tool calls change const toolCallCount = useChatProperty( (state) => state.messages.reduce((count, message) => { const toolCalls = message.parts?.filter(part => part.type.startsWith('tool-')) || []; return count + toolCalls.length; }, 0) ); ``` -------------------------------- ### Configure Drizzle Kit for Migrations (Bash) Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/memory/DRIZZLE.md Provides the necessary commands to install Drizzle Kit and configure its migration settings. This involves creating a `drizzle.config.ts` file specifying the schema location, output directory, database dialect, and credentials. ```bash npm install -D drizzle-kit ``` ```typescript import type { Config } from "drizzle-kit"; export default { schema: "./src/schema.ts", out: "./drizzle", dialect: "postgresql", // or "mysql" or "sqlite" dbCredentials: { url: process.env.DATABASE_URL!, }, } satisfies Config; ``` ```bash npx drizzle-kit generate npx drizzle-kit migrate ``` -------------------------------- ### Standard Redis Cache Configuration Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/cache/README.md Sets up caching with a standard Redis client instance. This example demonstrates connecting to a local Redis server and configuring a custom cache key prefix and TTL. ```typescript import Redis from "redis"; import { createCached } from '@ai-sdk-tools/cache'; const cached = createCached({ cache: Redis.createClient({ url: "redis://localhost:6379" }), keyPrefix: "my-app:", ttl: 30 * 60 * 1000, }); ``` -------------------------------- ### Setup Multi-Provider Agents in TypeScript Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/agents/README.md Initializes agents with models from different providers (Anthropic, OpenAI, Google) for specialized tasks like research, writing, and editing. Depends on @ai-sdk libraries for provider integrations. Takes no direct inputs but configures models and instructions; outputs configured agent instances. Limited to supported providers and models. ```typescript import { openai } from '@ai-sdk/openai'; import { anthropic } from '@ai-sdk/anthropic'; import { google } from '@ai-sdk/google'; const researchAgent = new Agent({ name: 'Researcher', model: anthropic('claude-3-5-sonnet-20241022'), // Excellent reasoning instructions: 'Research topics thoroughly.', }); const writerAgent = new Agent({ name: 'Writer', model: openai('gpt-4o'), // Great at creative writing instructions: 'Create engaging content.', }); const editorAgent = new Agent({ name: 'Editor', model: google('gemini-1.5-pro'), // Strong at review instructions: 'Review and improve content.', handoffs: [writerAgent], // Can send back for rewrites }); const pipeline = new Agent({ name: 'Content Manager', model: openai('gpt-4o-mini'), // Efficient orchestrator instructions: 'Coordinate content creation.', handoffs: [researchAgent, writerAgent, editorAgent], }); ``` -------------------------------- ### Set Up API Route with Typed Context Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/artifacts/README.md Set up a serverless API route to handle chat requests, define a typed context, and integrate AI SDK tools. This example uses `createTypedContext` for type safety and streams responses using `createUIMessageStreamResponse`. ```typescript import { createTypedContext, BaseContext } from '@ai-sdk-tools/artifacts'; import { createUIMessageStream, createUIMessageStreamResponse, streamText } from 'ai'; import { openai } from '@ai-sdk/openai'; // Define your context type interface MyContext extends BaseContext { userId: string; permissions: string[]; config: { theme: 'light' | 'dark' }; } // Create typed context helpers const { setContext, getContext } = createTypedContext(); export const POST = async (req: Request) => { const { messages } = await req.json(); const stream = createUIMessageStream({ execute: ({ writer }) => { // Set typed context setContext({ writer, userId: req.headers.get('user-id') || 'anonymous', permissions: ['read', 'write'], config: { theme: 'dark' } }); const result = streamText({ model: openai('gpt-4'), messages, tools: { analyzeBurnRate } }); writer.merge(result.toUIMessageStream()); } }); return createUIMessageStreamResponse({ stream }); }; ``` -------------------------------- ### useChatProperty Hook API Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Custom selector hook for fine-grained control over chat property re-renders. ```APIDOC ## useChatProperty(selector, storeId?) ### Description Custom selector hook allowing fine-grained control over what triggers component re-renders. ### Method HOOK ### Parameters #### Path Parameters - **selector** (function) - Required - Selector function - **storeId** (string) - Optional - Identifier for specific chat store #### Generic Parameters - **T** (type) - Optional - Input type for selector - **R** (type) - Optional - Return type for selector ### Response #### Returns - **property** (any) - Selected property based on selector function ``` -------------------------------- ### Migrate from @ai-sdk/react to @ai-sdk-tools/store Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Shows the minimal import change required to migrate from @ai-sdk/react to @ai-sdk-tools/store. This provides global state access, better performance with selective re-renders, multiple chat instance support, and custom store integration capabilities while maintaining full API compatibility. ```tsx // Before import { useChat } from '@ai-sdk/react' // After - ONLY CHANGE NEEDED import { useChat } from '@ai-sdk-tools/store' ``` -------------------------------- ### Initialize Memory Providers (TypeScript) Source: https://context7.com/midday-ai/ai-sdk-tools/llms.txt Demonstrates how to initialize different memory providers for AI agents. Includes setup for InMemory (development), DrizzleProvider (PostgreSQL, MySQL, SQLite), and UpstashProvider (Redis). It also shows how to configure working memory and conversation history. ```typescript import { InMemoryProvider, DrizzleProvider, UpstashProvider } from '@ai-sdk-tools/memory'; import { drizzle } from 'drizzle-orm/vercel-postgres'; import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'; import { Redis } from '@upstash/redis'; // Development setup with InMemory provider const memory = new InMemoryProvider(); const appContext = buildAppContext({ userId: "user-123", metadata: { chatId: "chat_abc123", userId: "user-123", }, memory: { provider: memory, workingMemory: { enabled: true, scope: 'chat', // or 'user' for cross-conversation memory template: `# Working Memory ## Key Facts - [Important information] ## Preferences - [User preferences] `, }, history: { enabled: true, limit: 10, // Last 10 messages }, }, }); // Production setup with Drizzle (PostgreSQL, MySQL, SQLite) const workingMemory = pgTable('working_memory', { id: text('id').primaryKey(), scope: text('scope').notNull(), chatId: text('chat_id'), userId: text('user_id'), content: text('content').notNull(), updatedAt: timestamp('updated_at').notNull(), }); const messages = pgTable('conversation_messages', { id: serial('id').primaryKey(), chatId: text('chat_id').notNull(), userId: text('user_id'), role: text('role').notNull(), content: text('content').notNull(), timestamp: timestamp('timestamp').notNull(), }); const db = drizzle(sql); const drizzleMemory = new DrizzleProvider(db, { workingMemoryTable: workingMemory, messagesTable: messages, }); // Production setup with Upstash (Serverless/Edge) const redis = Redis.fromEnv(); const upstashMemory = new UpstashProvider(redis); // Or use Redis for traditional instances (self-hosted, Redis Cloud, AWS ElastiCache) import Redis from 'ioredis'; import { RedisProvider } from '@ai-sdk-tools/memory/redis'; const redisClient = new Redis(process.env.REDIS_URL); const redisMemory = new RedisProvider(redisClient, { prefix: 'my-app:memory:', messageTtl: 60 * 60 * 24 * 30 // 30 days TTL }); // Use with agents (automatic integration) const triageAgent = new Agent({ name: 'triage', model: openai('gpt-4o'), instructions: 'Route user requests to specialists', handoffs: [supportAgent, billingAgent], lastMessages: 20, // Limit conversation history to last 20 messages (optional) memory: { provider: drizzleMemory, workingMemory: { enabled: true, scope: 'chat' }, history: { enabled: true, limit: 10 } } }); // Agent automatically: // 1. Loads working memory into system prompt // 2. Provides updateWorkingMemory tool to the LLM // 3. Captures conversation history export async function POST(req: Request) { const { messages, chatId } = await req.json(); return triageAgent.toUIMessageStream({ messages, context: { userId: 'user-123', metadata: { chatId } } }); } ``` -------------------------------- ### Streaming Tools with Artifacts Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/cache/README.md Demonstrates how to create complex streaming tools that generate artifacts. This example shows a `burnRateAnalysis` tool that streams data and updates an artifact with charts and metrics. ```APIDOC ## Streaming Tools with Artifacts ```typescript import { createCached } from '@ai-sdk-tools/cache'; // Complex streaming tool with artifacts const burnRateAnalysis = tool({ description: 'Generate comprehensive burn rate analysis', parameters: z.object({ companyId: z.string(), months: z.number(), }), execute: async function* ({ companyId, months }) { // Create streaming artifact const analysis = burnRateArtifact.stream({ stage: "loading", // ... artifact data }); yield { text: "Starting analysis..." }; // Update artifact with charts, metrics await analysis.update({ chart: { monthlyData: [...] }, metrics: { burnRate: 50000, runway: 18 }, }); yield { text: "Analysis complete", forceStop: true }; }, }); const cached = createCached({ cache: Redis.fromEnv() }); const cachedAnalysis = cached(burnRateAnalysis); // First call: Full streaming + artifact creation // Cached calls: Instant artifact restoration + complete result ``` ``` -------------------------------- ### Split Components for Chat Functionality Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Demonstrates the main chat component orchestrating individual sub-components for focused concerns like message display, input handling, and status indicators. This approach enables better performance and easier maintenance. ```tsx // Main chat component orchestrates everything // Individual components handle specific concerns // Display messages with custom types // Input with metadata support // Real-time status display ``` -------------------------------- ### Initialize Chat with @ai-sdk-tools/store Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/artifacts/README.md Initialize the chat component using the `useChat` hook from @ai-sdk-tools/store, which serves as a drop-in replacement for @ai-sdk/react. This setup is crucial for integrating the chat UI and enabling artifact display. ```tsx import { useChat } from '@ai-sdk-tools/store'; // Drop-in replacement for @ai-sdk/react import { DefaultChatTransport } from 'ai'; function ChatComponent() { // Initialize chat (same API as @ai-sdk/react) const { messages, input, handleInputChange, handleSubmit } = useChat({ transport: new DefaultChatTransport({ api: '/api/chat' }) }); return (
{/* Your chat UI */} {/* Artifacts work from any component */}
); } ``` -------------------------------- ### Configure Multi-Agent Orchestration with Handoffs Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/ai-sdk-tools/README.md Create specialized AI agents that can hand off conversations to each other based on context. This example demonstrates a support agent routing billing queries to a dedicated billing agent, with bidirectional handoff capabilities for seamless customer service automation. ```typescript import { Agent } from 'ai-sdk-tools'; import { openai } from '@ai-sdk/openai'; const supportAgent = new Agent({ model: openai('gpt-4'), name: 'SupportAgent', instructions: 'You handle customer support queries.', }); const billingAgent = new Agent({ model: openai('gpt-4'), name: 'BillingAgent', instructions: 'You handle billing and payment issues.', handoff: [supportAgent], // Can hand off back to support }); // Support agent can route to billing supportAgent.handoff = [billingAgent]; const result = await supportAgent.generateText({ prompt: 'I need help with my invoice', }); ``` -------------------------------- ### Auto-Routing with Pattern Matching (TypeScript) Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/agents/README.md This example enables programmatic routing to agents based on keyword or regex matches without full LLM overhead. It uses the matchOn property in agents and orchestrators; input is a prompt, output is the routed result. Limitations include potential false positives from regex patterns and reliance on predefined match rules for accuracy. ```typescript const mathAgent = new Agent({ name: 'Math Tutor', model: openai('gpt-4o'), instructions: 'You help with math problems.', matchOn: ['calculate', 'math', 'equation', /\d+\s*[\+\-\*\/]\s*\d+/], }); const historyAgent = new Agent({ name: 'History Tutor', model: openai('gpt-4o'), instructions: 'You help with history questions.', matchOn: ['history', 'war', 'civilization', /\d{4}/], // Years }); const orchestrator = new Agent({ name: 'Smart Router', model: openai('gpt-4o-mini'), // Efficient for routing instructions: 'Route to specialists. Fall back to handling general questions.', handoffs: [mathAgent, historyAgent], }); // Automatically routes to mathAgent based on pattern match const result = await orchestrator.generate({ prompt: 'What is 15 * 23?', }); ``` -------------------------------- ### useChat Hook API Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Main chat hook with custom type support. Provides core chat functionality with global state management. ```APIDOC ## useChat() ### Description Main chat hook with custom types that provides chat functionality with global state management. ### Method HOOK ### Parameters #### Generic Parameters - **T** (type) - Optional - Custom type for message extension ### Response #### Returns Object containing chat functions and state: - **messages** (array) - Array of chat messages - **input** (string) - Current input value - **handleInputChange** (function) - Input change handler - **handleSubmit** (function) - Submit handler - **isLoading** (boolean) - Loading state - **setError** (function) - Error setter - **error** (Error|undefined) - Current error #### Response Example { messages: [], input: '', handleInputChange: () => {}, handleSubmit: () => {}, isLoading: false, setError: () => {}, error: undefined } ``` -------------------------------- ### Create an AI Tool with Artifact Streaming Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/artifacts/README.md Create an AI tool that utilizes the defined artifact for streaming updates. This example demonstrates how to access typed context, stream partial updates, and complete the artifact with final data. ```typescript // Use direct AI SDK tool format const analyzeBurnRate = { description: 'Analyze company burn rate', inputSchema: z.object({ company: z.string() }), execute: async ({ company }: { company: string }) => { // Access typed context in tools const context = getContext(); // Fully typed as MyContext console.log('Processing for user:', context.userId); console.log('Theme:', context.config.theme); const analysis = burnRateArtifact.stream({ title: `${company} Analysis for ${context.userId}`, stage: 'loading', monthlyBurn: 50000, runway: 12 }); // Stream updates analysis.progress = 0.5; await analysis.update({ stage: 'processing' }); // Complete await analysis.complete({ title: `${company} Analysis`, stage: 'complete', monthlyBurn: 45000, runway: 14, data: [{ month: '2024-01', burnRate: 50000 }] }); return 'Analysis complete'; } }; ``` -------------------------------- ### Vercel AI SDK with Vercel Postgres using DrizzleProvider Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/memory/DRIZZLE.md TypeScript example showing how to initialize a Drizzle database instance with Vercel Postgres and configure the DrizzleProvider for memory management within an AI SDK Agent. Requires `@ai-sdk-tools/memory` and `@ai-sdk-tools/agents`. ```typescript import { drizzle } from "drizzle-orm/vercel-postgres"; import { sql } from "@vercel/postgres"; import { DrizzleProvider } from "@ai-sdk-tools/memory"; import { Agent } from "@ai-sdk-tools/agents"; const db = drizzle(sql); const memoryProvider = new DrizzleProvider(db, { workingMemoryTable: workingMemory, messagesTable: messages, }); const agent = new Agent({ name: "assistant", // ... config memory: { provider: memoryProvider }, }); ``` -------------------------------- ### Add Tools to Agents with AI SDK Tools (TypeScript) Source: https://context7.com/midday-ai/ai-sdk-tools/llms.txt Shows how to define and attach custom tools to an agent. The example creates a 'calculator' tool using Zod for schema definition and a simple JavaScript `eval` function for execution. This allows the 'Math Tutor' agent to perform calculations when needed. ```typescript const calculatorTool = tool({ description: 'Perform mathematical calculations', parameters: z.object({ expression: z.string(), }), execute: async ({ expression }) => { return eval(expression); }, }); const mathAgent = new Agent({ name: 'Math Tutor', model: openai('gpt-4o'), instructions: 'Help with math problems using the calculator tool.', tools: { calculator: calculatorTool, }, maxTurns: 10 }); ``` -------------------------------- ### Implement Guardrails for Input/Output with AI SDK Tools (TypeScript) Source: https://context7.com/midday-ai/ai-sdk-tools/llms.txt Demonstrates how to add safety guardrails to agents to control input and output. The 'Moderated Agent' example includes `inputGuardrails` to block profanity and `outputGuardrails` to redact sensitive information. It also shows setting `permissions` for tool usage, like limiting calls to a `writeData` tool. ```typescript const moderatedAgent = new Agent({ name: 'Moderated Agent', model: openai('gpt-4o'), instructions: 'Answer questions helpfully.', inputGuardrails: [ async (input) => { if (containsProfanity(input)) { return { pass: false, action: 'block', message: 'Input violates content policy' }; } return { pass: true }; } ], outputGuardrails: [ async (output) => { if (containsSensitiveInfo(output)) { return { pass: false, action: 'modify', modifiedOutput: redactSensitiveInfo(output) }; } return { pass: true }; } ], permissions: { allowed: ['readData', 'writeData'], maxCallsPerTool: { writeData: 5 } } }); ``` -------------------------------- ### Stream AI Tools with Artifacts and Caching Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/cache/README.md Demonstrates how to create a complex streaming AI tool that generates artifacts. It utilizes caching to store and retrieve analysis results instantly, improving performance for repeated requests. The example shows artifact streaming with stages and updates, followed by caching the tool for faster access. ```typescript import { createCached } from '@ai-sdk-tools/cache'; // Complex streaming tool with artifacts const burnRateAnalysis = tool({ description: 'Generate comprehensive burn rate analysis', parameters: z.object({ companyId: z.string(), months: z.number(), }), execute: async function* ({ companyId, months }) { // Create streaming artifact const analysis = burnRateArtifact.stream({ stage: "loading", // ... artifact data }); yield { text: "Starting analysis..." }; // Update artifact with charts, metrics await analysis.update({ chart: { monthlyData: [...] }, metrics: { burnRate: 50000, runway: 18 }, }); yield { text: "Analysis complete", forceStop: true }; }, }); const cached = createCached({ cache: Redis.fromEnv() }); const cachedAnalysis = cached(burnRateAnalysis); // First call: Full streaming + artifact creation // Cached calls: Instant artifact restoration + complete result ``` -------------------------------- ### Create and Orchestrate Specialized Agents with AI SDK Tools (TypeScript) Source: https://context7.com/midday-ai/ai-sdk-tools/llms.txt Demonstrates how to define multiple specialized agents (Researcher, Writer, Editor) with different AI models and instructions. It then sets up an orchestrator agent to manage workflows, including automatic routing based on defined patterns. The example shows how to use these agents in an API route for streaming responses and also for generating direct responses. ```typescript import { Agent } from '@ai-sdk-tools/agents'; import { openai } from '@ai-sdk/openai'; import { anthropic } from '@ai-sdk/anthropic'; import { tool } from 'ai'; import { z } from 'zod'; // Create specialized agents with different models const researchAgent = new Agent({ name: 'Researcher', model: anthropic('claude-3-5-sonnet-20241022'), instructions: 'Research topics thoroughly and gather comprehensive information.', matchOn: ['research', 'find information', 'investigate', /what is|who is/i] }); const writerAgent = new Agent({ name: 'Writer', model: openai('gpt-4o'), instructions: 'Create engaging, well-structured content based on research.', matchOn: ['write', 'create content', 'draft', 'compose'] }); const editorAgent = new Agent({ name: 'Editor', model: openai('gpt-4o'), instructions: 'Review and improve content quality, grammar, and structure.', handoffs: [writerAgent] // Can send back for rewrites }); // Create orchestrator with automatic routing const orchestrator = new Agent({ name: 'Content Manager', model: openai('gpt-4o-mini'), instructions: 'Coordinate content creation workflow. Route tasks to appropriate specialists.', handoffs: [researchAgent, writerAgent, editorAgent], maxTurns: 20 }); // Use in API route with streaming export async function POST(req: Request) { const { messages } = await req.json(); return orchestrator.toUIMessageStream({ messages, maxRounds: 5, maxSteps: 10, strategy: 'auto', // Automatic routing based on matchOn patterns onEvent: async (event) => { if (event.type === 'agent-handoff') { console.log(`Handoff: ${event.from} → ${event.to}`); } if (event.type === 'agent-complete') { console.log(`Completed in ${event.totalRounds} rounds`); } } }); } // Generate response without streaming const result = await orchestrator.generate({ prompt: 'Research and write an article about quantum computing', }); console.log(result.text); console.log(`Handled by: ${result.finalAgent}`); console.log(`Handoffs: ${result.handoffs.length}`); ``` -------------------------------- ### Initialize Redis Provider with redis package (TypeScript) Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/memory/README.md Sets up a RedisProvider using the official redis package. Demonstrates async connection handling and optional configuration for key prefixing and message TTL. ```typescript import { createClient } from "redis";\nimport { RedisProvider } from "@ai-sdk-tools/memory/redis";\n\nconst redis = createClient({ url: process.env.REDIS_URL });\nawait redis.connect();\nconst memory = new RedisProvider(redis, {\n prefix: "my-app:memory:",\n messageTtl: * 60 * 24 * 30, // Optional: 30 days TTL for messages (default: no expiration)\n}); ``` -------------------------------- ### Initialize Redis Provider with ioredis (TypeScript) Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/memory/README.md Creates a RedisProvider using theored client for traditional Redis deployments. Connects to a Redis instance via URL and supplies the client to the memory provider. ```typescript import Redis from "ioredis";\nimport { RedisProvider } from "@ai-sdk-tools/memory/redis";\n\nconst redis = new Redis(process.env.REDIS_URL);\nconst memory = new RedisProvider(redis); ``` -------------------------------- ### Create and Use Basic Agent (TypeScript) Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/agents/README.md This snippet demonstrates creating a single AI agent using the @ai-sdk-tools/agents library and the OpenAI model. It requires importing Agent and openai, with input as a prompt string and output as the generated text. Limitations include model rate limits and dependency on OpenAI API. ```typescript import { Agent } from '@ai-sdk-tools/agents'; import { openai } from '@ai-sdk/openai'; const agent = new Agent({ name: 'Assistant', model: openai('gpt-4o'), instructions: 'You are a helpful assistant.', }); // Generate response const result = await agent.generate({ prompt: 'What is 2+2?', }); console.log(result.text); // "4" ``` -------------------------------- ### useChatError Hook API Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Hook to retrieve error state from chat with optional store ID parameter. ```APIDOC ## useChatError(storeId?) ### Description Hook to get the current error state from the chat system. ### Method HOOK ### Parameters #### Path Parameters - **storeId** (string) - Optional - Identifier for specific chat store ### Response #### Returns - **error** (Error|undefined) - Current error object if exists ``` -------------------------------- ### useChatStatus Hook API Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Hook to retrieve current chat status with optional store ID parameter. ```APIDOC ## useChatStatus(storeId?) ### Description Hook to get current chat status such as 'loading', 'idle', or 'error'. ### Method HOOK ### Parameters #### Path Parameters - **storeId** (string) - Optional - Identifier for specific chat store ### Response #### Returns - **status** (string) - Current chat status ``` -------------------------------- ### useChatSendMessage Hook API Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Hook that returns the send message function with optional store ID support. ```APIDOC ## useChatSendMessage(storeId?) ### Description Hook to get the send message function for dispatching messages to the chat store. ### Method HOOK ### Parameters #### Path Parameters - **storeId** (string) - Optional - Identifier for specific chat store ### Response #### Returns - **sendMessage** (function) - Function to send messages ``` -------------------------------- ### useChatMessages Hook API Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Hook to retrieve messages array from chat store with optional store ID parameter. ```APIDOC ## useChatMessages(storeId?) ### Description Hook to get messages array from the chat store with support for custom types and store identification. ### Method HOOK ### Parameters #### Path Parameters - **storeId** (string) - Optional - Identifier for specific chat store #### Generic Parameters - **T** (type) - Optional - Custom message type ### Response #### Returns - **messages** (array) - Array of chat messages #### Response Example [ { id: '1', role: 'user', content: 'Hello' } ] ``` -------------------------------- ### Build Complex Multi-Agent Handoffs in TypeScript Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/agents/README.md Demonstrates a multi-agent system for affordability analysis, using handoffs between research, financial, and assistant agents with tools for web search and data retrieval. Imports from @ai-sdk-tools/agents and @ai-sdk/openai. Processes user queries like 'Can I afford a Tesla Model Y?'; outputs coordinated analysis. Depends on available tools and handoff configurations; may be limited by model capabilities. ```typescript import { Agent, handoff, removeAllTools, keepLastNMessages } from '@ai-sdk-tools/agents'; import { openai } from '@ai-sdk/openai'; // Research Specialist - gathers current product information const researchSpecialist = new Agent({ name: 'Research Specialist', model: openai('gpt-4o-mini'), instructions: `You research current product information and pricing. Provide detailed findings for other agents.`, tools: { webSearch: webSearchTool, }, }); // Financial Analyst - evaluates affordability const financialAnalyst = new Agent({ name: 'Financial Analyst', model: openai('gpt-4o-mini'), instructions: `You analyze financial affordability based on user data and research. Use previous conversation context to provide comprehensive analysis.`, tools: { getFinancialData: getFinancialDataTool, }, }); // Main Assistant with configured handoffs const assistant = new Agent({ name: 'Assistant', model: openai('gpt-4o-mini'), instructions: `Help users determine if they can afford major purchases. Coordinate research and financial analysis for comprehensive answers.`, handoffs: [ // Research first, remove tool calls to keep context clean handoff(researchSpecialist, { inputFilter: removeAllTools, }), // Then financial analysis, keep recent context handoff(financialAnalyst, { inputFilter: keepLastNMessages(10), }), ], }); // Usage: "Can I afford a Tesla Model Y?" // 1. Assistant → Research Specialist (searches for Tesla pricing) // 2. Research Specialist → Financial Analyst (reads pricing, gets user's financial data) // 3. Financial Analyst provides comprehensive affordability analysis ``` -------------------------------- ### Define a Type-Safe Artifact with Zod Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/artifacts/README.md Define a custom artifact using the `artifact` function from @ai-sdk-tools/artifacts and Zod for schema validation. This example defines a 'burn-rate' artifact with specific properties and types. ```typescript import { artifact } from '@ai-sdk-tools/artifacts'; import { z } from 'zod'; const burnRateArtifact = artifact('burn-rate', z.object({ title: z.string(), stage: z.enum(['loading', 'processing', 'complete']).default('loading'), monthlyBurn: z.number(), runway: z.number(), data: z.array(z.object({ month: z.string(), burnRate: z.number() })).default([]) })); ``` -------------------------------- ### Multiple Chat Instances with Custom Types Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/apps/website/README.md Implementation of multiple specialized chat instances with different message types and store IDs. Each chat can be accessed independently from any component using their unique identifiers. ```tsx import { DefaultChatTransport } from 'ai'; // Weather-focused chat useChat({ transport: new DefaultChatTransport({ api: '/api/chat' }), storeId: 'weather-chat', }); // Calculator-focused chat useChat({ transport: new DefaultChatTransport({ api: '/api/chat' }), storeId: 'calculator-chat', }); // Access from any component const weatherMessages = useChatMessages('weather-chat'); const calculatorMessages = useChatMessages('calculator-chat'); ``` -------------------------------- ### Initialize Upstash Provider for Serverless (TypeScript) Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/memory/README.md Creates an UpstashProvider using the @upstash/redis client, ideal for edge or serverless environments where HTTP REST is required. Includes optional prefix and TTL settings. ```typescript import { Redis } from "@upstash/redis";\nimport {stashProvider } from "@ai-sdk-tools/memory/upstash";\n\nconst redis = Redis.fromEnv();\nconst memory = new UpstashProvider(redis, {\n prefix: "my-app:memory:",\n messageTtl: 60 * 60 * 24 * 30, // Optional: 30 days TTL for messages (default: no expiration)\n}); ``` -------------------------------- ### Wrapping App with Store Provider Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/store/README.md Use the Provider component to wrap your application, initializing the store with optional initial messages. This enables global state access without prop drilling. Depends on @ai-sdk-tools/store import. ```tsx import { Provider } from '@ai-sdk-tools/store'; function App() { return ( ); } ``` ```tsx ``` -------------------------------- ### Initialize Drizzle Provider for MySQL (PlanetScale) Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/memory/DRIZZLE.md Connects to a PlanetScale database using the provided URL and initializes the Drizzle ORM client. It then sets up the DrizzleProvider with MySQL-specific table definitions. ```typescript import { connect } from "@planetscale/database"; import { drizzle } from "drizzle-orm/planetscale-serverless"; import { mysqlTable, int, varchar, text, timestamp, } from "drizzle-orm/mysql-core"; import { DrizzleProvider } from "@ai-sdk-tools/memory"; const connection = connect({ url: process.env.DATABASE_URL }); const db = drizzle(connection); const workingMemory = mysqlTable("working_memory", { id: varchar("id", { length: 255 }).primaryKey(), scope: varchar("scope", { length: 50 }).notNull(), chatId: varchar("chat_id", { length: 255 }), userId: varchar("user_id", { length: 255 }), content: text("content").notNull(), updatedAt: timestamp("updated_at").notNull(), }); const messages = mysqlTable("conversation_messages", { id: int("id").primaryKey().autoincrement(), chatId: varchar("chat_id", { length: 255 }).notNull(), userId: varchar("user_id", { length: 255 }), role: varchar("role", { length: 50 }).notNull(), content: text("content").notNull(), timestamp: timestamp("timestamp").notNull(), }); const memoryProvider = new DrizzleProvider(db, { workingMemoryTable: workingMemory, messagesTable: messages, }); ``` -------------------------------- ### Import modules from AI SDK Tools in TypeScript Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/README.md Shows how to import server‑side and client‑side utilities from the ai-sdk-tools package. Requires TypeScript support and the installed package. These imports enable agents, artifacts, caching, and devtools in your code. ```typescript // Server-side import { Agent, artifact, cached } from 'ai-sdk-tools'; // Client-side import { useChat, useArtifact, AIDevtools } from 'ai-sdk-tools/client'; ``` -------------------------------- ### Redis Cache with Upstash for Production Source: https://github.com/midday-ai/ai-sdk-tools/blob/main/packages/cache/README.md Configures caching using an Upstash Redis client. This setup is suitable for production environments, allowing for centralized and persistent caching with a specified time-to-live (TTL). ```typescript import { Redis } from "@upstash/redis"; import { createCached } from '@ai-sdk-tools/cache'; // Just pass your Redis client! const cached = createCached({ cache: Redis.fromEnv(), // That's it! ttl: 30 * 60 * 1000, // 30 minutes }); const weatherTool = cached(expensiveWeatherTool); ```