Installation

Install the Kontext SDK:
npm install @kontext.dev/kontext-sdk

Setup

Create a simple Express server with Kontext:
server.js
import express from 'express';
import { Persona } from '@kontext.dev/kontext-sdk';

const app = express();
app.use(express.json());

// Initialize Kontext
const persona = new Persona({
  apiKey: process.env.KONTEXT_API_KEY
});

// Context endpoint
app.post('/api/context', async (req, res) => {
  const { userId, task } = req.body;
  
  try {
    const context = await persona.getContext({
      userId,
      task: task || 'chat',
      maxTokens: 2000
    });
    
    res.json(context);
  } catch (error) {
    if (error.code === 'UNAUTHORIZED_USER') {
      res.status(401).json({ error: 'User needs to connect Gmail' });
    } else {
      res.status(500).json({ error: 'Internal server error' });
    }
  }
});

// Chat endpoint with AI integration
app.post('/api/chat', async (req, res) => {
  const { userId, message } = req.body;
  
  try {
    // Get personalized context
    const context = await persona.getContext({
      userId,
      task: 'chat'
    });
    
    // Use with OpenAI (or any AI provider)
    const completion = await openai.chat.completions.create({
      model: 'gpt-4',
      messages: [
        { role: 'system', content: context.systemPrompt },
        { role: 'user', content: message }
      ]
    });
    
    res.json({ 
      response: completion.choices[0].message.content 
    });
  } catch (error) {
    console.error('Chat error:', error);
    res.status(500).json({ error: 'Failed to generate response' });
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Environment Variables

.env
KONTEXT_API_KEY=ktext_your_api_key_here
OPENAI_API_KEY=sk-your-openai-key

Using with TypeScript

server.ts
import express, { Request, Response } from 'express';
import { Persona, Context } from '@kontext.dev/kontext-sdk';

const app = express();
app.use(express.json());

const persona = new Persona({
  apiKey: process.env.KONTEXT_API_KEY!
});

interface ChatRequest {
  userId: string;
  message: string;
}

app.post('/api/chat', async (req: Request<{}, {}, ChatRequest>, res: Response) => {
  const { userId, message } = req.body;
  
  try {
    const context: Context = await persona.getContext({
      userId,
      task: 'chat'
    });
    
    // Your AI integration here
    res.json({ context });
  } catch (error) {
    res.status(500).json({ error: 'Server error' });
  }
});

Error Handling

app.post('/api/context', async (req, res) => {
  try {
    const context = await persona.getContext(req.body);
    res.json(context);
  } catch (error) {
    // Handle specific errors
    switch (error.code) {
      case 'UNAUTHORIZED_USER':
        res.status(401).json({ 
          error: 'User not connected',
          code: 'UNAUTHORIZED_USER' 
        });
        break;
      case 'INVALID_USER_ID':
        res.status(400).json({ 
          error: 'Invalid user ID',
          code: 'INVALID_USER_ID' 
        });
        break;
      case 'RATE_LIMITED':
        res.status(429).json({ 
          error: 'Too many requests',
          code: 'RATE_LIMITED' 
        });
        break;
      default:
        res.status(500).json({ 
          error: 'Internal server error' 
        });
    }
  }
});

Complete Example

See our GitHub repository for a complete Node.js/Express example with:
  • User authentication
  • Gmail connection flow
  • Personalized chat API
  • Error handling
  • TypeScript support