### Install Dependencies and Run Locally Source: https://github.com/vercel/chatbot/blob/main/README.md Commands to install dependencies, migrate the database, and start the development server. Ensure environment variables are set up correctly. ```bash pnpm install pnpm db:migrate # Setup database or apply latest database changes pnpm dev ``` -------------------------------- ### Install, Migrate, Develop, Build, and Start Chatbot Source: https://github.com/vercel/chatbot/blob/main/_autodocs/architecture.md Standard commands for managing the chatbot project dependencies, database, development server, and production builds. ```bash # Install dependencies pnpm install ``` ```bash # Run migrations pnpm db:migrate ``` ```bash # Start development pnpm dev ``` ```bash # Build for production pnpm build ``` ```bash # Run production build pnpm start ``` -------------------------------- ### GET /api/models Source: https://github.com/vercel/chatbot/blob/main/_autodocs/endpoints.md Retrieve a list of available AI models that can be used. ```APIDOC ## GET /api/models ### Description Retrieve a list of available AI models. ### Method GET ### Endpoint /api/models ### Response #### Success Response (200) - **id** (string) - Model identifier (e.g., "moonshotai/kimi-k2.5") - **name** (string) - Display name - **provider** (string) - Provider name - **description** (string) - Model description - **capabilities** (object) - Model capabilities - **tools** (boolean) - **vision** (boolean) - **reasoning** (boolean) #### Response Example ```json [ { "id": "moonshotai/kimi-k2.5", "name": "Kimi 2.5", "provider": "Moonshot AI", "description": "A powerful language model.", "capabilities": { "tools": true, "vision": false, "reasoning": true } } ] ``` ``` -------------------------------- ### Default Suggestion Messages Source: https://github.com/vercel/chatbot/blob/main/_autodocs/configuration.md An array of default starter suggestions provided to users. These are typically displayed at the beginning of a chat session to guide user interaction. ```typescript export const suggestions = [ "What are the advantages of using Next.js?", "Write code to demonstrate Dijkstra's algorithm", "Help me write an essay about Silicon Valley", "What is the weather in San Francisco?", ]; ``` -------------------------------- ### GET Handler Endpoints Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Handles NextAuth.js GET requests for session checks and provider configurations. ```APIDOC ## GET /api/auth/session ### Description Get the current user session. ### Method GET ### Endpoint /api/auth/session ``` ```APIDOC ## GET /api/auth/providers ### Description List all configured authentication providers. ### Method GET ### Endpoint /api/auth/providers ``` ```APIDOC ## GET /api/auth/csrf ### Description Retrieve the Cross-Site Request Forgery (CSRF) token. ### Method GET ### Endpoint /api/auth/csrf ``` -------------------------------- ### Regular System Prompt Source: https://github.com/vercel/chatbot/blob/main/_autodocs/configuration.md This prompt is used for AI models that do not support tool usage. It guides the AI to be a helpful assistant, keep responses concise, and act immediately on requests. ```plaintext You are a helpful assistant. Keep responses concise and direct. When asked to write, create, or build something, do it immediately. Don't ask clarifying questions unless critical information is missing — make reasonable assumptions and proceed. ``` -------------------------------- ### getTitleModel Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Gets the dedicated model for chat title generation, using Kimi K2.5 via AI Gateway. ```APIDOC ## getTitleModel(): LanguageModel ### Description Gets the dedicated model for chat title generation. ### Returns `LanguageModel` — AI SDK language model instance ### Model Uses `titleModel` (Kimi K2.5) via AI Gateway ### Example ```typescript import { getTitleModel } from "@/lib/ai/providers"; const titleModel = getTitleModel(); const { text } = await generateText({ model: titleModel, system: titlePrompt, prompt: userMessage }); ``` ``` -------------------------------- ### Generate Hashed Password with Bcrypt Source: https://github.com/vercel/chatbot/blob/main/_autodocs/configuration.md Utility function for hashing passwords using bcrypt with a salt. Ensure bcrypt is installed and configured. ```typescript export function generateHashedPassword(password: string) { const salt = genSaltSync(10); const hash = hashSync(password, salt); return hash; } ``` -------------------------------- ### getLanguageModel Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Gets a language model instance from the configured provider. Returns a mock model in test environments or a model from Vercel AI Gateway otherwise. ```APIDOC ## getLanguageModel(modelId: string): LanguageModel ### Description Gets a language model instance from the configured provider. ### Parameters #### Path Parameters - **modelId** (string) - Required - Model identifier (e.g., "openai/gpt-4") ### Returns `LanguageModel` — AI SDK language model instance ### Example ```typescript import { getLanguageModel } from "@/lib/ai/providers"; const model = getLanguageModel("moonshotai/kimi-k2.5"); const result = await streamText({ model, messages: [...] }); ``` ``` -------------------------------- ### Get User by Email Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-database.md Retrieves a user record by email address. Expects 0 or 1 result. Ensure the email is a valid string. ```typescript import { getUser } from "@/lib/db/queries"; const users = await getUser("user@example.com"); if (users.length > 0) { console.log(users[0].id, users[0].email); } ``` -------------------------------- ### Get Available AI Models Source: https://github.com/vercel/chatbot/blob/main/_autodocs/endpoints.md Retrieves a list of all available AI models that can be used by the chatbot. The response includes model details such as ID, name, provider, description, and capabilities. ```typescript const response = await fetch("/api/models"); const models = await response.json(); ``` -------------------------------- ### Get Language Model Instance Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Retrieve a language model instance for use with AI SDK functions. Handles test environments by returning a mock model. ```typescript import { getLanguageModel } from "@/lib/ai/providers"; const model = getLanguageModel("moonshotai/kimi-k2.5"); const result = await streamText({ model, messages: [...] }); ``` -------------------------------- ### Get Weather Data Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Retrieves current weather information for a specified city or coordinates. Requires city name or latitude/longitude. Returns detailed weather data or an error object. ```typescript { latitude: number; longitude: number; current: { temperature_2m: number; // ... other weather fields }; hourly: { temperature_2m: number[] }; daily: { sunrise: string[]; sunset: string[] }; timezone: string; cityName?: string; // If city was provided } ``` ```typescript { error: string; // e.g., "Could not find coordinates for 'InvalidCity'" } ``` ```typescript import { getWeather } from "@/lib/ai/tools/get-weather"; const weather = await getWeather({ city: "San Francisco" }); // Or with coordinates: const weather2 = await getWeather({ latitude: 37.7749, longitude: -122.4194 }); ``` -------------------------------- ### signIn(provider, options?) Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Initiates the sign-in process with a specified provider. Supports 'credentials' (email/password) and 'guest' modes. ```APIDOC ## signIn(provider, options?) ### Description Initiates sign-in with specified provider. ### Parameters #### Path Parameters - **provider** (string) - Required - Provider ID: `"credentials"` or `"guest"` - **options** (SignInOptions) - Optional - Additional options ### Provider IDs - `"credentials"` — Email/password login - Requires: `email`, `password`, `redirect: false` - `"guest"` — Guest mode - No credentials needed ### Options ```typescript { email?: string; // For credentials provider password?: string; // For credentials provider redirect?: boolean; // Whether to redirect after signin (default: true) } ``` ### Example ```typescript import { signIn } from "@/app/(auth)/auth"; // Email/password await signIn("credentials", { email: "user@example.com", password: "password123", redirect: false }); // Guest mode await signIn("guest", { redirect: false }); ``` ``` -------------------------------- ### NextAuth GET Handler Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Handles NextAuth.js GET requests for session checks and provider configurations. Use for accessing session data or listing available authentication providers. ```typescript export const { handlers: { GET }, ... } = NextAuth({...}) ``` -------------------------------- ### Initiate Sign-In with Credentials Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Initiates a sign-in process using email and password. Requires 'credentials' provider and provides options for email, password, and redirect behavior. Set `redirect: false` to handle redirection manually. ```typescript import { signIn } from "@/app/(auth)/auth"; // Email/password await signIn("credentials", { email: "user@example.com", password: "password123", redirect: false }); ``` -------------------------------- ### Generate System Prompt with Hints and Tools Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Constructs a comprehensive system prompt that includes base instructions, request hints (like location), and tool-calling instructions if supported. ```typescript import { systemPrompt } from "@/lib/ai/prompts"; const prompt = systemPrompt({ requestHints: { latitude: 37.7749, longitude: -122.4194, city: "San Francisco", country: "United States" }, supportsTools: true }); const result = await streamText({ model, system: prompt, messages: [...] }); ``` -------------------------------- ### User Registration Workflow Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Illustrates the steps for user registration, including form submission, account creation, session establishment, and redirection. Handles success, existing user, and invalid data scenarios. ```typescript // 1. User submits signup form const result = await register({ status: "idle" }, formData); if (result.status === "success") { // 2. Account created, session established // 3. Redirect to dashboard (handled by form) } else if (result.status === "user_exists") { // Show: Email already registered } else if (result.status === "invalid_data") { // Show: Invalid email format or short password } ``` -------------------------------- ### GET /api/document Source: https://github.com/vercel/chatbot/blob/main/_autodocs/endpoints.md Retrieves all versions of a specific document identified by its ID. ```APIDOC ## GET /api/document?id={docId} ### Description Retrieve all versions of a document. ### Method GET ### Endpoint /api/document #### Query Parameters - **id** (string (UUID)) - Required - Document ID ### Response #### Success Response (200) - **id** (string (UUID)) - **createdAt** (Date) - **title** (string) - **content** (string | null) - **kind** ("text" | "code" | "image" | "sheet") - **userId** (string (UUID)) ### Request Example ```typescript const response = await fetch("/api/document?id=doc-123"); const documents = await response.json(); ``` ``` -------------------------------- ### Initiate Sign-In as Guest Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Initiates a sign-in process for guest users. No credentials are required. The `redirect` option can be set to `false` to manage redirection manually. ```typescript import { signIn } from "@/app/(auth)/auth"; // Guest mode await signIn("guest", { redirect: false }); ``` -------------------------------- ### GET /api/suggestions Source: https://github.com/vercel/chatbot/blob/main/_autodocs/endpoints.md Retrieve edit suggestions for a specific document. Requires a document ID as a query parameter. ```APIDOC ## GET /api/suggestions?documentId={docId} ### Description Retrieve edit suggestions for a document. This endpoint requires the `documentId` to be provided as a query parameter. ### Method GET ### Endpoint /api/suggestions #### Query Parameters - **documentId** (string (UUID)) - Required - Document ID to fetch suggestions for ### Response #### Success Response (200) - **id** (string (UUID)) - Description - **documentId** (string (UUID)) - Description - **documentCreatedAt** (Date) - Description - **originalText** (string) - Description - **suggestedText** (string) - Description - **description** (string) - Optional - Description - **isResolved** (boolean) - Description - **userId** (string (UUID)) - Description - **createdAt** (Date) - Description #### Response Example ```json [ { "id": "uuid-string", "documentId": "doc-123", "documentCreatedAt": "2023-10-27T10:00:00Z", "originalText": "Original content.", "suggestedText": "Suggested content.", "description": "Optional description.", "isResolved": false, "userId": "user-uuid", "createdAt": "2023-10-27T10:05:00Z" } ] ``` #### Error Responses - **400**: Missing `documentId` parameter - **401**: User not authenticated - **403**: Suggestions belong to another user ``` -------------------------------- ### Fetching Model Capabilities Source: https://github.com/vercel/chatbot/blob/main/_autodocs/configuration.md Demonstrates how to fetch model capabilities at runtime using the getCapabilities() function from the AI Gateway. This determines enabled tools and reasoning output inclusion. ```typescript const modelCapabilities = await getCapabilities(); const capabilities = modelCapabilities[chatModel]; const isReasoningModel = capabilities?.reasoning === true; const supportsTools = capabilities?.tools === true; ``` -------------------------------- ### Get Votes Source: https://github.com/vercel/chatbot/blob/main/_autodocs/endpoints.md Retrieves all votes (upvotes/downvotes) for messages within a specified chat. Requires chat ID and authentication. ```APIDOC ## GET /api/vote?chatId={chatId} ### Description Retrieve all votes (upvotes/downvotes) for messages in a chat. ### Method GET ### Endpoint /api/vote ### Parameters #### Query Parameters - **chatId** (string (UUID)) - Required - Chat ID to fetch votes for ### Response #### Success Response (200) - **Array** - An array of vote objects. #### Response Example ```json [ { "chatId": "string (UUID)", "messageId": "string (UUID)", "isUpvoted": boolean } ] ``` ### Status Codes - `200`: Votes retrieved successfully - `400`: Missing `chatId` parameter - `401`: User not authenticated - `403`: Chat belongs to another user - `404`: Chat not found ``` -------------------------------- ### Initialize Drizzle ORM with PostgreSQL Client Source: https://github.com/vercel/chatbot/blob/main/_autodocs/configuration.md Sets up the Drizzle ORM instance by connecting to a PostgreSQL database using the provided URL. Ensure the POSTGRES_URL environment variable is set. ```typescript const client = postgres(process.env.POSTGRES_URL ?? ""); const db = drizzle(client); ``` -------------------------------- ### Get Chat History Source: https://github.com/vercel/chatbot/blob/main/_autodocs/endpoints.md Retrieve paginated chat history for the authenticated user. Supports forward and backward pagination. ```APIDOC ## GET /api/history?limit=10&starting_after=chatId&ending_before=chatId ### Description Retrieve paginated chat history for the authenticated user. ### Method GET ### Endpoint /api/history ### Parameters #### Query Parameters - **limit** (number) - Optional - Number of chats per page (max 50) - **starting_after** (string (UUID)) - Optional - Cursor for forward pagination - **ending_before** (string (UUID)) - Optional - Cursor for backward pagination ### Response #### Success Response (200) - **chats** (Array<{id: string (UUID); createdAt: Date; title: string; userId: string (UUID); visibility: "public" | "private";}>) - List of chat objects. - **hasMore** (boolean) - True if more chats exist beyond limit. ### Response Example ```json { "chats": [ { "id": "string (UUID)", "createdAt": "Date", "title": "string", "userId": "string (UUID)", "visibility": "public" | "private" } ], "hasMore": true } ``` ### Error Handling - **400**: Both `starting_after` and `ending_before` provided - **401**: User not authenticated ``` -------------------------------- ### Build Process with Database Migrations Source: https://github.com/vercel/chatbot/blob/main/_autodocs/configuration.md Defines the build script to run database migrations before initiating the Next.js build process. ```json { "scripts": { "build": "tsx lib/db/migrate && next build" } } ``` -------------------------------- ### Get Messages Source: https://github.com/vercel/chatbot/blob/main/_autodocs/endpoints.md Retrieves all messages within a specified chat. Handles cases where the chat might not exist or the user does not have access. ```APIDOC ## GET /api/messages?chatId={chatId} ### Description Retrieve all messages in a chat. ### Method GET ### Endpoint /api/messages ### Parameters #### Query Parameters - **chatId** (string (UUID)) - Required - Chat ID to fetch messages from ### Response #### Success Response (200) - **messages** (Array) - Array of message objects. - **visibility** (string) - Visibility of the chat ('public' | 'private'). - **userId** (string (UUID)) - The ID of the user who owns the chat. - **isReadonly** (boolean) - Indicates if the chat is read-only for the current user. #### Response Example ```json { "messages": [ { "id": "string (UUID)", "chatId": "string (UUID)", "role": "user" | "assistant" | "system", "parts": [], "attachments": [], "createdAt": "Date", "metadata": { "createdAt": "string (ISO 8601)" } } ], "visibility": "public" | "private", "userId": "string (UUID)", "isReadonly": boolean } ``` ### Status Codes - `200`: Messages retrieved - `400`: Missing `chatId` parameter - `403`: Chat is private and user is not owner ``` -------------------------------- ### systemPrompt Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Generates the system prompt for the chat model, including artifact and tool instructions based on request hints and tool support. ```APIDOC ## systemPrompt(options: {requestHints: RequestHints; supportsTools: boolean}): string ### Description Generates the system prompt for the chat model, including artifact and tool instructions. ### Parameters #### Path Parameters - **requestHints** (RequestHints) - Required - Geographic/request context - **supportsTools** (boolean) - Required - Whether model supports tool calling ### Returns `string` — Full system prompt text ### Content - Regular prompt (base instructions) - Request hints (location info) - Artifacts prompt (if tools supported) ### Example ```typescript import { systemPrompt } from "@/lib/ai/prompts"; const prompt = systemPrompt({ requestHints: { latitude: 37.7749, longitude: -122.4194, city: "San Francisco", country: "United States" }, supportsTools: true }); const result = await streamText({ model, system: prompt, messages: [...] }); ``` ``` -------------------------------- ### Get Document by ID Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-database.md Retrieves the most recent version of a document using its unique ID. Returns undefined if the document is not found. ```typescript import { getDocumentById } from "@/lib/db/queries"; const doc = await getDocumentById({ id: "doc-123" }); ``` -------------------------------- ### getCapabilities() Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Fetches model capabilities, including support for tools, vision, and reasoning, from the AI Gateway. The results are cached for 24 hours. A fallback is provided if the fetch fails. ```APIDOC ## getCapabilities() ### Description Fetches model capabilities from AI Gateway (tools, vision, reasoning). ### Returns `Promise>` ### Caching Cached for 24 hours (86400 seconds) via Next.js `revalidate` ### Fallback Returns `{tools: false, vision: false, reasoning: false}` if fetch fails ### Example ```typescript import { getCapabilities } from "@/lib/ai/models"; const capabilities = await getCapabilities(); const modelCaps = capabilities["openai/gpt-4"]; if (modelCaps?.tools) { console.log("Model supports tool calling"); } ``` ``` -------------------------------- ### Get Chat by ID Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-database.md Retrieves a single chat record by its unique ID. Returns the chat object or null if not found. ```typescript import { getChatById } from "@/lib/db/queries"; const chat = await getChatById({ id: "chat-123" }); if (chat) { console.log(chat.title); } ``` -------------------------------- ### artifactsPrompt Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Tool usage instructions for artifact creation and editing, outlining key rules for tool invocation and content generation. ```APIDOC ## artifactsPrompt ### Description Tool usage instructions for artifact creation and editing. ### Key Rules 1. Call only ONE tool per response 2. Never output artifact content in chat after tool call 3. Use `createDocument` for initial creation 4. Use `editDocument` for find-and-replace edits 5. Use `updateDocument` only for full rewrites 6. Use `requestSuggestions` only when explicitly asked ``` -------------------------------- ### User Registration Server Action Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Use this Server Action for user registration and email/password signup. It validates email and password, handling cases where the user already exists or data is invalid. ```typescript import { register } from "@/app/(auth)/actions"; const formData = new FormData(); formData.set("email", "newuser@example.com"); formData.set("password", "securePassword123"); const result = await register({ status: "idle" }, formData); if (result.status === "user_exists") { // Show error: email already registered } ``` -------------------------------- ### Get Chat History Source: https://github.com/vercel/chatbot/blob/main/_autodocs/README.md Retrieves a paginated list of chat history objects. Supports limiting the number of results returned. ```APIDOC ## GET /api/history ### Description Retrieves a paginated list of chat history. ### Method GET ### Endpoint /api/history ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of chat objects to return. ``` -------------------------------- ### Guest Login Workflow Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Describes the client-side initiation of a guest login via a POST request and the implicit server-side handling by NextAuth.js, including user creation and session establishment. ```typescript // Client-side const response = await fetch("/api/auth/signin/guest", { method: "POST", redirect: "follow" }); // Server-side (implicit via NextAuth) // 1. Guest authorize called // 2. createGuestUser() generates account // 3. Session created // 4. Redirect to app ``` -------------------------------- ### Get Error Message by Code Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-utilities.md Retrieve a user-facing error message for a given composite error code. Import getMessageByErrorCode before use. ```typescript import { getMessageByErrorCode } from "@/lib/errors"; const msg = getMessageByErrorCode("rate_limit:chat"); // "You've reached the message limit. Come back in 1 hour to continue chatting." ``` -------------------------------- ### Create a Document via API Source: https://github.com/vercel/chatbot/blob/main/_autodocs/README.md Demonstrates creating a document, either through an AI tool call or a direct API POST request. The document is saved to the database and a UUID is generated. ```typescript // Client (via AI tool, not direct API call) // Model calls: createDocument({ title: "My Script", kind: "code" }) // Document saved to database, UUID generated // Stream events sent to UI // If manual save needed: const response = await fetch("/api/document?id=doc-uuid", { method: "POST", body: JSON.stringify({ content: "...", title: "My Script", kind: "code" }) }); // See: endpoints.md - POST /api/document ``` -------------------------------- ### Get Votes by Chat ID Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-database.md Retrieve all votes for messages within a specified chat. This function returns an array of vote records. ```typescript import { getVotesByChatId } from "@/lib/db/queries"; const votes = await getVotesByChatId({ id: "chat-123" }); ``` -------------------------------- ### Database Command Scripts Source: https://github.com/vercel/chatbot/blob/main/_autodocs/configuration.md Provides scripts for managing database migrations, schema generation, and accessing the Drizzle Studio. ```json { "db:migrate": "npx tsx lib/db/migrate.ts", "db:generate": "drizzle-kit generate", "db:studio": "drizzle-kit studio", "db:push": "drizzle-kit push" } ``` -------------------------------- ### Create New User Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-database.md Creates a new user with a hashed password. The password should be provided as a plain-text string and will be hashed before storage. Ensure email and password are valid strings. ```typescript import { createUser } from "@/lib/db/queries"; await createUser("newuser@example.com", "securePassword123"); ``` -------------------------------- ### Get All Document Versions by ID Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-database.md Retrieves all historical versions of a document, ordered chronologically by creation time. Requires the document's ID. ```typescript import { getDocumentsById } from "@/lib/db/queries"; const allVersions = await getDocumentsById({ id: "doc-123" }); ``` -------------------------------- ### createUser(email: string, password: string): Promise Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-database.md Creates a new user with a hashed password. This function is used to register new users in the system. ```APIDOC ## createUser(email: string, password: string): Promise ### Description Creates a new user with a hashed password. This function is used to register new users in the system. ### Parameters #### Path Parameters - **email** (string) - Required - User email address - **password** (string) - Required - Plain-text password (hashed before storage) ### Returns `Promise` - Void on success ### Throws `ChatbotError("bad_request:database", "Failed to create user")` ### Example ```typescript import { createUser } from "@/lib/db/queries"; await createUser("newuser@example.com", "securePassword123"); ``` ``` -------------------------------- ### register Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Server Action for user registration and email/password signup. It processes form data for email and password, returning a status that reflects the registration outcome. ```APIDOC ## register(state: RegisterActionState, formData: FormData): Promise ### Description Server Action for user registration and email/password signup. It processes form data for email and password, returning a status that reflects the registration outcome. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ##### Parameters - **state** (RegisterActionState) - Required - Current form state - **formData** (FormData) - Required - Form data with `email` and `password` fields ##### Request Fields - **email** (string) - Required - Valid email address - **password** (string) - Required - Password (plain text, min 6 chars) ### Request Example ```typescript import { register } from "@/app/(auth)/actions"; const formData = new FormData(); formData.set("email", "newuser@example.com"); formData.set("password", "securePassword123"); const result = await register({ status: "idle" }, formData); if (result.status === "user_exists") { // Show error: email already registered } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the outcome of the registration attempt. Possible values: "idle", "in_progress", "success", "failed", "user_exists", "invalid_data" #### Response Example ```json { "status": "success" | "failed" | "user_exists" | "invalid_data" } ``` ### Status Values - `"success"` — Account created and logged in - `"failed"` — Server error during registration or login - `"user_exists"` — Email already registered - `"invalid_data"` — Zod validation failed ``` -------------------------------- ### regularPrompt Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Base instruction prompt for all conversations, emphasizing conciseness and directness. ```APIDOC ## regularPrompt ### Description Base instruction prompt for all conversations. ### Content ``` You are a helpful assistant. Keep responses concise and direct. When asked to write, create, or build something, do it immediately. Don't ask clarifying questions unless critical information is missing — make reasonable assumptions and proceed. ``` ``` -------------------------------- ### Get Title Generation Model Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Obtain the dedicated language model optimized for generating chat titles. This model is accessed via the AI Gateway. ```typescript import { getTitleModel } from "@/lib/ai/providers"; const titleModel = getTitleModel(); const { text } = await generateText({ model: titleModel, system: titlePrompt, prompt: userMessage }); ``` -------------------------------- ### codePrompt Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Instruction for code generation, specifying requirements for self-contained, executable scripts with print/console output and no external dependencies. ```APIDOC ## codePrompt ### Description Instruction for code generation. ### Content Specifies requirements for self-contained, executable scripts with print/console output and no external dependencies. ``` -------------------------------- ### Get Document Timestamp by Index Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-utilities.md Retrieves the creation timestamp of a document from an array of versions. Returns the current date if the index is out of bounds or the document array is falsy. ```typescript import { getDocumentTimestampByIndex } from "@/lib/utils"; const allVersions = await getDocumentsById({ id: "doc-123" }); const latestTimestamp = getDocumentTimestampByIndex(allVersions, 0); ``` -------------------------------- ### Get Stream IDs by Chat ID Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-database.md Retrieves all stream IDs associated with a specific chat ID. Useful for fetching all stream records for a given conversation. ```typescript import { getStreamIdsByChatId } from "@/lib/db/queries"; const streamIds = await getStreamIdsByChatId({ chatId: "chat-123" }); ``` -------------------------------- ### getAllGatewayModels() Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Fetches all language models available from the Vercel AI Gateway, including their capabilities. This data is cached for 24 hours, and an empty array is returned if the fetch operation fails. ```APIDOC ## getAllGatewayModels() ### Description Fetches all language models available from Vercel AI Gateway. ### Returns `Promise` ### Caching 24 hours ### Fallback Returns empty array if fetch fails ### Example ```typescript import { getAllGatewayModels } from "@/lib/ai/models"; const allModels = await getAllGatewayModels(); const gptModels = allModels.filter(m => m.provider === "openai"); ``` ``` -------------------------------- ### titlePrompt Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Instruction for generating concise chat titles (2-5 words) summarizing the user's message, outputting only the title text. ```APIDOC ## titlePrompt ### Description Instruction for generating concise chat titles. ### Content ``` Generate a short chat title (2-5 words) summarizing the user's message. Output ONLY the title text. No prefixes, no formatting. ``` ### Examples - "what's the weather in nyc" → "Weather in NYC" - "help me write an essay" → "Space Essay Help" ``` -------------------------------- ### Get Active Chat Models Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Retrieves a list of currently available chat models. Use this to display available options to users or for dynamic model selection. ```typescript import { getActiveModels } from "@/lib/ai/models"; const models = getActiveModels(); models.forEach(m => console.log(m.id, m.name)); ``` -------------------------------- ### Get Document Suggestions Source: https://github.com/vercel/chatbot/blob/main/_autodocs/endpoints.md Retrieves edit suggestions for a specific document using its ID. Ensure the documentId is provided as a query parameter. The response is an array of suggestion objects. ```typescript const response = await fetch("/api/suggestions?documentId=doc-123"); const suggestions = await response.json(); ``` -------------------------------- ### Database Versioning with Composite Keys Source: https://github.com/vercel/chatbot/blob/main/_autodocs/architecture.md Manage document versions efficiently using a composite key `(id, createdAt)` in the database. This approach enables versioning without requiring multiple columns, allowing for easy retrieval of all versions, the latest version, or deletion of versions after a specific timestamp. ```typescript // Document table uses composite key: (id, createdAt) // Enables versioning without multiple columns // Create new version await saveDocument({id, title, kind, content, userId}); // Get all versions const allVersions = await getDocumentsById({id}); // Returns chronological list // Get latest const latest = await getDocumentById({id}); // Returns most recent version // Delete versions after timestamp await deleteDocumentsByIdAfterTimestamp({id, timestamp}); ``` -------------------------------- ### Artifacts System Prompt for Tool-Enabled Models Source: https://github.com/vercel/chatbot/blob/main/_autodocs/configuration.md This prompt is designed for AI models that support tool usage. It instructs the AI on how to handle artifact creation and editing, emphasizing the use of specific tools and rules for each. ```plaintext Only call ONE tool per response Never output artifact content in chat after calling tool Use `createDocument` for initial content creation Use `editDocument` for targeted changes (find-and-replace) Use `updateDocument` only for full rewrites Use `requestSuggestions` only when explicitly asked ``` -------------------------------- ### Get Paginated Chats by User ID Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-database.md Retrieves a paginated list of chat history for a specific user using cursor-based pagination. Useful for displaying chat lists. ```typescript import { getChatsByUserId } from "@/lib/db/queries"; const { chats, hasMore } = await getChatsByUserId({ id: "user-123", limit: 10, startingAfter: null }); ``` -------------------------------- ### Get Chat History from API Source: https://github.com/vercel/chatbot/blob/main/_autodocs/README.md Client-side code to fetch paginated chat history from the API. The response includes a list of chats and a flag indicating if more history is available. ```typescript // Client const response = await fetch("/api/history?limit=20"); const { chats, hasMore } = await response.json(); // Returns paginated Chat objects // See: endpoints.md - GET /api/history ``` -------------------------------- ### Available Chat Models Configuration Source: https://github.com/vercel/chatbot/blob/main/_autodocs/configuration.md Lists available chat models with their properties such as ID, name, provider, description, and fallback order. This configuration is used to select and manage AI models. ```typescript const chatModels: ChatModel[] = [ { id: "deepseek/deepseek-v3.2", name: "DeepSeek V3.2", provider: "deepseek", description: "Fast and capable model with tool use", gatewayOrder: ["bedrock", "deepinfra"], }, // ... more models ]; ``` -------------------------------- ### Fetch Data with SWR Wrapper Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-utilities.md Fetch wrapper for SWR client-side data fetching with error handling. Throws `ChatbotError` on non-ok responses. ```typescript import { fetcher } from "@/lib/utils"; import useSWR from "swr"; const { data } = useSWR("/api/history?limit=20", fetcher); ``` -------------------------------- ### Guest Provider for Anonymous Access Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Enable guest access by creating a guest user with an auto-generated email and password. This is useful for temporary or anonymous user sessions. ```typescript Credentials({ id: "guest", credentials: {}, async authorize() { const [guestUser] = await createGuestUser(); return { ...guestUser, type: "guest" }; }, }) ``` -------------------------------- ### User Login Server Action Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Use this Server Action for user email/password login. It handles form data containing 'email' and 'password' and returns a status indicating success, failure, or invalid data. ```typescript import { login } from "@/app/(auth)/actions"; const formData = new FormData(); formData.set("email", "user@example.com"); formData.set("password", "password123"); const result = await login({ status: "idle" }, formData); if (result.status === "success") { // Redirect to dashboard } ``` -------------------------------- ### login Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Server Action for user email/password login. It handles form data containing email and password, returning a status indicating the outcome of the login attempt. ```APIDOC ## login(state: LoginActionState, formData: FormData): Promise ### Description Server Action for user email/password login. It handles form data containing email and password, returning a status indicating the outcome of the login attempt. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ##### Parameters - **state** (LoginActionState) - Required - Current form state - **formData** (FormData) - Required - Form data with `email` and `password` fields ##### Request Fields - **email** (string) - Required - Valid email address - **password** (string) - Required - Password (plain text, min 6 chars) ### Request Example ```typescript import { login } from "@/app/(auth)/actions"; const formData = new FormData(); formData.set("email", "user@example.com"); formData.set("password", "password123"); const result = await login({ status: "idle" }, formData); if (result.status === "success") { // Redirect to dashboard } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the outcome of the login attempt. Possible values: "idle", "in_progress", "success", "failed", "invalid_data" #### Response Example ```json { "status": "success" | "failed" | "invalid_data" } ``` ### Status Values - `"success"` — Login successful, session created - `"failed"` — Email/password mismatch or server error - `"invalid_data"` — Zod validation failed (email format or password length) ``` -------------------------------- ### Get Current User Session Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Retrieves the current user's session information. Returns null if no active session exists or if the session has expired. Ensure the session object is checked for user properties before accessing them. ```typescript import { auth } from "@/app/(auth)/auth"; const session = await auth(); if (!session?.user) { // User not authenticated redirect("/login"); } console.log(session.user.id, session.user.type); ``` -------------------------------- ### sheetPrompt Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Instruction for spreadsheet generation, specifying CSV format with clear headers, realistic data, and consistent formatting. ```APIDOC ## sheetPrompt ### Description Instruction for spreadsheet generation. ### Content Specifies CSV format with clear headers, realistic data, and consistent formatting. ``` -------------------------------- ### Sign in with email and password Source: https://github.com/vercel/chatbot/blob/main/_autodocs/endpoints.md Allows users to sign in using their email and password credentials. This endpoint is handled by the NextAuth.js credentials provider. ```APIDOC ## POST /api/auth/signin ### Description Sign in with email and password credentials. ### Method POST ### Endpoint /api/auth/signin ### Request Handled by NextAuth.js credentials provider ``` -------------------------------- ### Next.js Chatbot Project Structure Source: https://github.com/vercel/chatbot/blob/main/_autodocs/architecture.md This outlines the directory structure for the Next.js chatbot application, detailing the organization of routes, libraries, components, and artifact handlers. ```tree chatbot/ ├── app/ # Next.js App Router │ ├── (auth)/ # Authentication routes (grouped) │ │ ├── actions.ts # Server actions: login, register │ │ ├── auth.ts # NextAuth.js configuration │ │ ├── auth.config.ts # Auth pages and callbacks │ │ ├── api/auth/... # NextAuth.js API routes │ │ ├── login/ # Login page │ │ └── register/ # Registration page │ │ │ └── (chat)/ # Chat routes (grouped) │ ├── actions.ts # Server actions: title generation, visibility │ ├── page.tsx # Chat interface │ ├── [id]/ # Individual chat routes │ └── api/ │ ├── chat/ # POST /api/chat (main chat endpoint) │ ├── history/ # GET/DELETE chat history │ ├── messages/ # GET messages by chat ID │ ├── document/ # CRUD document artifacts │ ├── vote/ # GET/PATCH message votes │ ├── suggestions/ # GET document suggestions │ ├── models/ # GET available models │ └── files/ # File upload handling │ ├── lib/ # Shared utilities │ ├── ai/ # AI integration │ │ ├── models.ts # Model definitions │ │ ├── providers.ts # Provider selection │ │ ├── prompts.ts # System prompts │ │ ├── entitlements.ts # Rate limits by user type │ │ └── tools/ # AI tool definitions │ │ ├── create-document.ts │ │ ├── edit-document.ts │ │ ├── update-document.ts │ │ ├── get-weather.ts │ │ └── request-suggestions.ts │ │ │ ├── db/ # Database layer │ │ ├── schema.ts # Drizzle ORM schema │ │ ├── queries.ts # Database query functions │ │ ├── utils.ts # Password hashing utilities │ │ └── migrate.ts # Migration runner │ │ │ ├── types.ts # TypeScript type definitions │ ├── utils.ts # UI and general utilities │ ├── errors.ts # Error handling │ ├── ratelimit.ts # Rate limiting │ ├── constants.ts # Application constants │ └── editor/ # Document editor utilities │ ├── components/ # React components │ ├── ai-elements/ # AI-specific components │ │ ├── code-block.tsx │ │ ├── conversation.tsx │ │ ├── message.tsx │ │ ├── model-selector.tsx │ │ └── ... │ │ │ └── chat/ # Chat interface components │ ├── artifact.tsx # Artifact display │ ├── app-sidebar.tsx # Sidebar navigation │ └── ... │ ├── artifacts/ # Artifact handlers (documents, images, sheets, code) │ ├── code/ │ │ ├── client.tsx │ │ └── server.ts │ ├── image/ │ ├── sheet/ │ ├── text/ │ └── ... │ ├── package.json # Dependencies ├── tsconfig.json # TypeScript config ├── drizzle.config.ts # Drizzle ORM config └── .env.example # Environment template ``` -------------------------------- ### createDocument Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-ai.md Allows AI to create new artifacts such as code, text, sheets, or images. ```APIDOC ## createDocument(options: {session: Session; dataStream: UIMessageStreamWriter; modelId: string}): Tool ### Description Tool for AI to create new artifacts (code, text, sheets, images). ### Parameters #### Path Parameters - **session** (Session) - User session from auth - **dataStream** (UIMessageStreamWriter) - Stream for sending updates to client - **modelId** (string) - ID of the model creating the document ### Input Schema ```typescript { title: string; // Artifact title kind: "text" | "code" | "sheet" | "image"; // Artifact type } ``` ### Returns `Tool` ```typescript { id: string; // UUID for document title: string; // Document title kind: ArtifactKind; content: string; // Confirmation message } ``` ### Behavior 1. Generates UUID for document 2. Writes transient data to stream (kind, id, title) 3. Calls document handler based on kind 4. Writes finish signal ### Stream Events Sent - `data-kind` — Document type - `data-id` — Document UUID - `data-title` — Document title - `data-clear` — Clear signal - `data-finish` — Completion signal ### Example ```typescript // AI tool definition (not called directly by developers): tools: { createDocument: createDocument({ session, dataStream, modelId: "moonshotai/kimi-k2.5" }) } // Model calls it with: { title: "My Script", kind: "code" } ``` ``` -------------------------------- ### Credentials Provider for Email/Password Authentication Source: https://github.com/vercel/chatbot/blob/main/_autodocs/api-reference-auth.md Implement email and password authentication using the Credentials provider. This snippet includes user retrieval, password comparison with bcrypt for timing attack prevention, and returning a user object. ```typescript Credentials({ credentials: { email: { label: "Email", type: "email" }, password: { label: "Password", type: "password" }, }, async authorize(credentials) { const email = String(credentials.email ?? ""); const password = String(credentials.password ?? ""); const users = await getUser(email); if (users.length === 0) { await compare(password, DUMMY_PASSWORD); // Timing attack prevention return null; } const [user] = users; if (!user.password) { await compare(password, DUMMY_PASSWORD); return null; } const passwordsMatch = await compare(password, user.password); if (!passwordsMatch) { return null; } return { ...user, type: "regular" }; }, }) ``` -------------------------------- ### Server Components and Server Actions in TypeScript Source: https://github.com/vercel/chatbot/blob/main/_autodocs/architecture.md Utilize Server Components for rendering and Server Actions for data mutations. This pattern allows direct database access and authentication on the server, reducing JavaScript bundles and enabling type-safe data passing. ```typescript // app/(chat)/page.tsx is a Server Component export default async function ChatPage() { const session = await auth(); // Can call async directly const chats = await getChatsByUserId({id: session.user.id}); return ( ); } // Server Action in app/(chat)/actions.ts "use server"; export async function deleteChat(id: string) { const session = await auth(); // Can access session await deleteChatById({id}); // Can call database functions } ``` -------------------------------- ### Instantiating ChatbotError Source: https://github.com/vercel/chatbot/blob/main/_autodocs/errors.md Demonstrates how to instantiate a `ChatbotError` with a composite error code and an optional cause message. This is typically done within a try-catch block to handle potential exceptions. ```typescript import { ChatbotError } from "@/lib/errors"; try { // ... } catch (error) { throw new ChatbotError("bad_request:api", "Invalid chat ID format"); } ```