New

Chatbot with Memory

Build a chatbot that remembers conversation context across messages.

What We're Building

A chatbot that maintains conversation context, remembers user information, and persists memory across page reloads using session storage.

Setup

bash
npm install openai

API Route (Next.js)

app/api/chat/route.ts
import OpenAI from 'openai';
import { NextRequest, NextResponse } from 'next/server';

// Initialize client
const client = new OpenAI({
  baseURL: 'https://www.superagentstack.com/api/v1',
  apiKey: process.env.OPENROUTER_KEY!,
  defaultHeaders: { 'superAgentKey': process.env.SUPER_AGENT_KEY! },
});

export async function POST(req: NextRequest) {
  const { message, sessionId } = await req.json();

  // Create completion with memory enabled
  const response = await client.chat.completions.create({
    model: 'openai/gpt-4o-mini',
    messages: [{ role: 'user', content: message }],
    sessionId: sessionId,      // Enable session memory
    saveToMemory: true,        // Save messages to memory
    autoMemory: true,          // Enable "remember" commands
  });

  return NextResponse.json({
    message: response.choices[0].message.content,
  });
}

Frontend Component

components/Chatbot.tsx
'use client';
import { useState, useEffect } from 'react';

interface Message {
  role: 'user' | 'assistant';
  content: string;
}

export function Chatbot() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  
  // Persist session ID across page reloads
  const [sessionId] = useState(() => {
    if (typeof window !== 'undefined') {
      const stored = sessionStorage.getItem('chatSessionId');
      if (stored) return stored;
      const newId = crypto.randomUUID();
      sessionStorage.setItem('chatSessionId', newId);
      return newId;
    }
    return crypto.randomUUID();
  });

  const sendMessage = async () => {
    if (!input.trim() || loading) return;
    
    const userMessage = input;
    setInput('');
    setMessages(prev => [...prev, { role: 'user', content: userMessage }]);
    setLoading(true);

    try {
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: userMessage, sessionId }),
      });
      
      const data = await res.json();
      setMessages(prev => [...prev, { role: 'assistant', content: data.message }]);
    } catch (error) {
      console.error('Chat error:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col h-[500px] border rounded-lg">
      {/* Messages */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.map((msg, i) => (
          <div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
            <div className={`max-w-[80%] p-3 rounded-lg ${
              msg.role === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-100'
            }`}>
              {msg.content}
            </div>
          </div>
        ))}
        {loading && <div className="text-gray-500">Thinking...</div>}
      </div>
      
      {/* Input */}
      <div className="border-t p-4 flex gap-2">
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && sendMessage()}
          placeholder="Type a message..."
          className="flex-1 border rounded px-3 py-2"
        />
        <button onClick={sendMessage} disabled={loading} className="px-4 py-2 bg-blue-500 text-white rounded">
          Send
        </button>
      </div>
    </div>
  );
}

Memory in Action

Try saying "My name is Sarah" then later ask "What's my name?" - the AI will remember! You can also use commands like "Remember that I prefer dark mode".

Features Demonstrated

  • Session Memory: Conversation persists within the session
  • Session Persistence: Session ID stored in sessionStorage survives page reloads
  • Explicit Commands: Users can say "remember" to store facts
  • Auto Memory: Important information is automatically detected and stored