Skip to Content
⭐ CraftJS is open source. Star on GitHub →
DocsAI API

AI API

The AI API provides endpoints for chat completions and text generation.

Chat Completions

Create a chat completion with streaming response.

POST /api/chat

Request Body:

{ "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Hello!" } ], "model": "gpt-4o", "chatId": "optional-chat-id" }

Parameters:

FieldTypeRequiredDescription
messagesarrayYesConversation history
modelstringNoModel ID (default: gpt-4o)
chatIdstringNoExisting chat ID to continue

Response:

Returns a streaming response with Server-Sent Events (SSE).

data: {"type":"text-delta","textDelta":"Hello"} data: {"type":"text-delta","textDelta":"!"} data: {"type":"text-delta","textDelta":" How"} data: {"type":"finish","finishReason":"stop"}

Headers:

X-Chat-Id: chat_123 X-RateLimit-Remaining: 9

Available Models

Model IDProviderDescription
gpt-4oOpenAILatest GPT-4 Omni
gpt-4o-miniOpenAISmaller, faster GPT-4
claude-sonnet-4AnthropicClaude Sonnet 4
claude-3-5-haikuAnthropicFast Claude model
gemini-2-flashGoogleGemini 2.0 Flash

Client Usage

"use client" import { useChat } from "ai/react" export function Chat() { const { messages, input, handleInputChange, handleSubmit, isLoading, error, } = useChat({ api: "/api/chat", body: { model: "gpt-4o", }, }) return ( <div> {messages.map((m) => ( <div key={m.id}> {m.role}: {m.content} </div> ))} <form onSubmit={handleSubmit}> <input value={input} onChange={handleInputChange} placeholder="Type a message..." /> <button type="submit" disabled={isLoading}> Send </button> </form> </div> ) }

Chat History

List Chats

Get all chats for the current user.

GET /api/chats

Response:

[ { "id": "chat_123", "title": "First chat", "model": "gpt-4o", "createdAt": "2024-01-01T00:00:00.000Z", "updatedAt": "2024-01-01T00:00:00.000Z" } ]

Get Chat Messages

Get messages for a specific chat.

GET /api/chats/[id]/messages

Response:

[ { "id": "msg_1", "chatId": "chat_123", "role": "user", "content": "Hello!", "createdAt": "2024-01-01T00:00:00.000Z" }, { "id": "msg_2", "chatId": "chat_123", "role": "assistant", "content": "Hello! How can I help you today?", "createdAt": "2024-01-01T00:00:01.000Z" } ]

Delete Chat

Delete a chat and all its messages.

DELETE /api/chats/[id]

Response:

{ "success": true }

Tool Calling

The AI can use tools when enabled. Tool calls are included in the stream:

data: {"type":"tool-call","toolCallId":"call_1","toolName":"weather","args":{"location":"San Francisco"}} data: {"type":"tool-result","toolCallId":"call_1","result":{"temperature":72,"conditions":"sunny"}} data: {"type":"text-delta","textDelta":"The weather in San Francisco is 72°F and sunny."}

Available Tools

ToolDescription
weatherGet current weather
searchSearch the web
calculatorPerform calculations

See Custom AI Tools for adding your own tools.

Error Handling

{ "error": "Rate limit exceeded", "code": "RATE_LIMITED", "details": { "remaining": 0, "reset": 1699999999999 } }
CodeDescription
RATE_LIMITEDToo many requests
INVALID_MODELUnknown model ID
CONTEXT_TOO_LONGMessage history too large
PROVIDER_ERRORAI provider returned an error

Usage Tracking

AI usage is tracked automatically:

{ "userId": "user_123", "model": "gpt-4o", "promptTokens": 100, "completionTokens": 50, "totalTokens": 150, "timestamp": "2024-01-01T00:00:00.000Z" }

Access your usage via:

GET /api/usage

Usage counts toward your plan limits. Check /api/usage/remaining for your current allowance.

Last updated on