githubEdit

AI Assistant with SvelteKit

Build an AI-powered chat assistant with SvelteKit and JamAI Base

1. Introduction

This comprehensive tutorial will guide you through building a full-stack AI chat assistant application using SvelteKit and the JamAI Base TypeScript SDK. The application uses JamAI Base Chat Tables to create an intelligent conversational AI that can process text and images.

What We'll Build

An AI-powered chat application that allows users to:

  1. Create and manage multiple chat conversations

  2. Send text messages to an AI assistant

  3. Upload and share images in conversations

  4. Receive real-time streaming responses from AI

  5. View and organize conversation history

  6. Experience a modern, responsive chat interface

Key Features

  • Modern SvelteKit with file-based routing and server-side rendering

  • Svelte 5 with the latest runes API

  • TypeScript for type safety

  • Tailwind CSS 4 for styling with modern UI

  • Real-time Streaming for AI responses

  • Image Upload with preview and validation

  • Conversation Management with create, rename, and delete

  • Responsive Design for mobile and desktop

  • JamAI Base Chat Tables for AI conversation management

Prerequisites

Before starting, you'll need:

  • Node.js 18.x or higher installed

  • Basic knowledge of Svelte and TypeScript

  • Project ID and Personal Access Token (PAT) from JamAI Base

  • A code editor (VS Code recommended)

2. Project Setup

2.1 Create SvelteKit Project

First, create a new SvelteKit project:

When prompted, select:

  • Which Svelte app template? SvelteKit demo app

  • Add type checking with TypeScript? Yes, using TypeScript syntax

  • Add ESLint? Yes

  • Add Prettier? Yes

  • Add Vitest? No (optional)

  • Add Playwright? No (optional)

2.2 Install Dependencies

Install the required packages:

Dependencies:

  • jamaibase - JamAI Base TypeScript SDK for AI operations

  • @tailwindcss/vite - Tailwind CSS 4 with Vite integration

2.3 Configure Tailwind CSS

Create src/routes/layout.css:

2.4 Project Structure

Your project structure should look like this:

3. Getting Your Credentials

3.1 Get Your Personal Access Token (PAT)

  1. Click on your username in the top right

  2. Select Account Settings

  3. Navigate to Personal Access Token section

  4. Click Create Personal Access Token

  5. Copy and save your token securely

3.2 Get Your Project ID

  1. In the JamAI Base dashboard, navigate to your project

  2. Look at the browser URL: https://cloud.jamaibase.com/project/{PROJECT_ID}

  3. Copy the Project ID from the URL

3.3 Configure Environment Variables

Create a .env file in your project root:

circle-info

Important: Never commit .env to version control. Add it to your .gitignore file.

4. Core Configuration

4.1 Create Type Definitions

Create src/lib/types.ts:

4.2 Create Constants Configuration

Create src/lib/config/constants.ts:

Key Configuration Points:

  • AGENT_ID: The name of your Chat Table in JamAI Base

  • MODEL: The LLM model to use (gpt-4o-mini is cost-effective and fast)

  • SYSTEM_PROMPT: Defines the AI assistant's personality and behavior

  • COLUMNS: Maps to the Chat Table columns in JamAI Base

4.3 Initialize JamAI Client

Create src/lib/server/jamai-client.ts:

Key Points:

  • Uses singleton pattern for efficient client management

  • Validates environment variables on initialization

  • Uses SvelteKit's $env/static/private for secure server-side env vars

  • Provides helper function to unwrap JamAI's data structure

5. Building the API Routes

5.1 Conversations List & Create Route

Create src/routes/api/conversations/+server.ts:

What this does:

  • ensureAgentExists(): Automatically creates the Chat Table if it doesn't exist

  • GET: Lists all conversations associated with the agent

  • POST: Creates a new conversation with an optional title

  • Handles streaming response to extract conversation ID

5.2 Single Conversation Route (Get, Delete & Rename)

Create src/routes/api/conversations/[id]/+server.ts:

5.3 Messages Route (List & Send)

Create src/routes/api/conversations/[id]/messages/+server.ts:

What this does:

  • GET: Fetches all messages in a conversation, unwrapping JamAI's data structure

  • Fetches thumbnail URLs for images in batch for performance

  • POST: Sends a new message and returns a streaming response

  • Handles both text and image inputs

  • Streams AI responses in real-time

5.4 File Upload Route

Create src/routes/api/upload/+server.ts:

What this does:

  • Accepts multipart form data with an image file

  • Validates file type and size

  • Uploads to JamAI Base storage

  • Generates and returns thumbnail URL for preview

6. Building the Store

6.1 Create Chat Store

Create src/lib/stores/chat-store.ts:

Key Features:

  • Manages all application state in a centralized store

  • Provides functions for all chat operations

  • Handles real-time streaming with message updates

  • Uses Svelte's reactive stores for automatic UI updates

7. Building the UI Components

7.1 Chat Messages Component

Create src/lib/components/ChatMessages.svelte:

7.2 Message Input Component

Create src/lib/components/MessageInput.svelte:

7.3 Chat Sidebar Component

Create src/lib/components/ChatSidebar.svelte:

8. Building the Pages

8.1 Create Chat Page

Create src/routes/chat/+page.svelte:

8.2 Create Chat Layout

Create src/routes/chat/+layout.svelte:

8.3 Create Home Page

Create src/routes/+page.svelte:

8.4 Create Root Layout

Create src/routes/+layout.svelte:

9. Running the Application

9.1 Start Development Server

The application will start at http://localhost:5173arrow-up-right

9.2 Test the Application

  1. Visit Home Page

  2. Create a Conversation

    • Click "New Chat" button in the sidebar

    • Wait for conversation to be created

  3. Send Messages

    • Type a message in the input box

    • Press Enter or click Send button

    • Watch the AI response stream in real-time

  4. Upload Images

    • Click the attachment icon

    • Select an image file (JPEG, PNG, GIF, or WebP)

    • Add text if desired

    • Send the message

  5. Manage Conversations

    • Click on any conversation in sidebar to switch

    • Hover over conversation to see Rename and Delete buttons

    • Rename by clicking the edit icon

    • Delete by clicking the trash icon

9.3 First Run

On the first API call, the application will automatically:

  1. Connect to JamAI Base using your credentials

  2. Create the "simple-chat" Chat Table if it doesn't exist

  3. Configure the AI column with the specified model and prompts

Check your terminal logs to see the table creation process.

10. How It Works

10.1 Architecture Overview

10.2 Data Flow

  1. Conversation Creation

    • User clicks "New Chat"

    • API ensures Chat Table exists

    • Creates conversation in JamAI Base

    • Returns conversation ID

  2. Message Sending

    • User types message and optionally attaches image

    • If image: uploads to JamAI Base, gets URI

    • Sends message to conversation

    • JamAI Base processes through LLM

    • Streams response back to client

  3. Streaming Response

    • Server creates ReadableStream

    • Chunks are sent as they're generated

    • Client updates UI in real-time via Svelte stores

    • Final message stored in Chat Table

10.3 JamAI Base Chat Table Structure

The "simple-chat" table has the following schema:

Column Name
Type
Description

Image

Input (image)

Optional image from user

User

Input (str)

User's message text

AI

LLM Output (str)

AI-generated response

Each conversation is stored separately, with messages as rows in the table.

Chat Table Configuration:

  • Model: openai/gpt-4o-mini (fast and cost-effective)

  • System Prompt: Defines AI behavior

  • Prompt Template: References user message and image using variables

  • Temperature: 0.7 (balanced creativity and consistency)

  • Max Tokens: 2000 (sufficient for most responses)

11. Customization

11.1 Modify AI Behavior

To change the AI's personality, edit src/lib/config/constants.ts:

11.2 Change LLM Model

You can use different models for different capabilities:

Model Recommendations:

  • gpt-4o-mini: Best balance of cost and performance

  • gpt-4o: Highest quality, best for complex tasks

  • claude-3-5-sonnet: Excellent for code and analysis

  • Llama-3.3-70B: Open-source, cost-effective

11.3 Add File Type Support

To support more file types, edit src/lib/config/constants.ts:

11.4 Customize UI Styling

The application uses Tailwind CSS. Customize colors and styles by editing components. For example, to change the primary color:

12. Deployment

12.1 Deploy to Vercel

  1. Push to GitHub

  2. Deploy on Vercel

    • Click "Import Project"

    • Select your GitHub repository

    • Add environment variables:

      • JAMAI_API_KEY

      • JAMAI_PROJECT_ID

    • Click "Deploy"

  3. Verify Deployment

    • Visit your deployment URL

    • Test conversation creation and messaging

12.2 Environment Variables in Production

circle-exclamation

13. Troubleshooting

Common Issues

Issue: "Missing JamAI credentials" error

Solution:

  • Verify .env exists in project root

  • Check variable names: JAMAI_API_KEY and JAMAI_PROJECT_ID

  • Restart development server after adding env variables


Issue: Conversation creation fails

Solution:

  • Check your JamAI Base credentials are valid

  • Ensure Project ID is correct

  • Check browser console for detailed error messages


Issue: Image upload fails

Solution:

  • Ensure image is under 10MB

  • Check file type is supported (JPEG, PNG, GIF, WebP)

  • Verify upload endpoint is accessible


Issue: Streaming response not working

Solution:

  • Check browser supports Server-Sent Events

  • Verify API route returns proper streaming headers

  • Check network tab for streaming data


Issue: Messages not displaying

Solution:

  • Check conversation ID is valid

  • Verify messages API returns data

  • Check browser console for errors

  • Try refreshing the page

14. Best Practices

Security

  1. Protect API Keys

    • Never commit .env

    • Use environment variables in production

    • Rotate API keys periodically

  2. Validate Input

    • Always validate file types and sizes

    • Sanitize user inputs

    • Implement rate limiting for production

  3. Error Handling

    • Never expose sensitive error details

    • Log errors server-side

    • Provide user-friendly error messages

Performance

  1. Optimize API Calls

    • Use batch operations when possible

    • Implement proper caching strategies

    • Minimize unnecessary re-fetches

  2. Image Optimization

    • Compress images before upload

    • Use thumbnail URLs for previews

    • Lazy load images in message history

  3. Streaming

    • Always use streaming for AI responses

    • Handle connection errors gracefully

    • Show loading indicators during streaming

Code Quality

  1. TypeScript

    • Define interfaces for all data structures

    • Avoid any types

    • Use strict mode

  2. Components

    • Keep components focused and reusable

    • Use Svelte 5 runes for reactivity

    • Proper TypeScript types for props

  3. Testing

    • Add unit tests for utility functions

    • Test API routes

    • Implement E2E tests for critical flows

15. Next Steps

Enhancements to Try

  1. User Authentication

    • Add user accounts with SvelteKit auth

    • Personal conversation history per user

    • Multi-user support

  2. Advanced Features

    • Message search functionality

    • Export conversation to PDF

    • Voice input support

    • Code syntax highlighting

  3. File Support

    • Support PDF documents

    • Handle multiple file uploads

    • Document analysis capabilities

  4. UI Enhancements

    • Dark mode toggle

    • Emoji picker

    • Message reactions

    • Typing indicators

  5. Analytics

    • Track conversation metrics

    • Monitor API usage

    • User engagement analytics

16. Resources

17. Support

If you encounter issues or have questions:

  1. Review this tutorial's troubleshooting section

  2. Contact JamAI Base support

Conclusion

You've successfully built a full-stack AI chat assistant application using:

  • SvelteKit with file-based routing and SSR

  • Svelte 5 with modern runes API

  • JamAI Base for AI conversation management

  • TypeScript for type safety

  • Tailwind CSS 4 for modern UI

  • Real-time Streaming for instant AI responses

The application demonstrates how to leverage JamAI Base Chat Tables to create sophisticated AI-powered applications with minimal backend complexity. You can now extend this foundation to build more complex conversational AI systems.

Happy building!

Last updated

Was this helpful?