Back to all snippets
Library/Node.js/AI Chatbot Basic Setup
typescriptbeginnerchatbotopenaiapiconversation

How to implement AI Chatbot Basic Setup in Typescript

Minimal chatbot with message history and system prompt

Quick Answer

Maintain a `messages` array with user and assistant messages, pass it to OpenAI API, and append the response to keep context for the next turn.

Code Snippet

1import OpenAI from 'openai';
2import * as readline from 'readline';
3
4const client = new OpenAI({
5  apiKey: process.env.OPENAI_API_KEY,
6});
7
8const messages: OpenAI.Messages.ChatCompletionMessageParam[] = [
9  {
10    role: 'system',
11    content: 'You are a helpful assistant. Be concise and friendly.',
12  },
13];
14
15async function chat(userMessage: string): Promise<string> {
16  messages.push({
17    role: 'user',
18    content: userMessage,
19  });
20
21  const response = await client.chat.completions.create({
22    model: 'gpt-4o-mini',
23    messages,
24    temperature: 0.7,
25  });
26
27  const assistantMessage = response.choices[0].message.content || '';
28  messages.push({
29    role: 'assistant',
30    content: assistantMessage,
31  });
32
33  return assistantMessage;
34}
35
36// Simple CLI interface
37async function main() {
38  const rl = readline.createInterface({
39    input: process.stdin,
40    output: process.stdout,
41  });
42
43  console.log('Chatbot ready. Type your message (or "exit" to quit):\n');
44
45  const prompt = () => {
46    rl.question('You: ', async (input) => {
47      if (input.toLowerCase() === 'exit') {
48        rl.close();
49        return;
50      }
51
52      const response = await chat(input);
53      console.log(`\nAssistant: ${response}\n`);
54      prompt();
55    });
56  };
57
58  prompt();
59}
60
61main();

What is AI Chatbot Basic Setup?

A chatbot is just a stateful conversation — you accumulate messages (user asks, assistant responds) and feed the full history to OpenAI so it understands context. This snippet shows how to build a simple command-line chatbot that remembers its conversation. Extend it with persistence (database) or a web interface.

How It Works

  1. 1Initialise a `messages` array with a system prompt
  2. 2On each user input, append a user message to the array
  3. 3Call OpenAI with the full message history
  4. 4Append the assistant's response to keep context for the next turn

Common Use Cases

  • Command-line chatbots - Interactive CLI conversations
  • Slack/Discord bots - Conversational bots with persistent state
  • Customer support - AI agents that remember conversation context
  • Educational tools - Tutoring chatbots that adapt to the student

Key Benefits

  • Minimal setup — just manage a message array
  • Full context — OpenAI sees the entire conversation history
  • Easy to extend — add persistence, logging, rate limiting
  • Works with any OpenAI model

Common Mistakes to Avoid

  • Not including the system prompt — without it, the AI has no personality or instructions.
  • Letting messages grow unbounded — after 50+ messages, trim old ones to save tokens and reduce latency.
  • Not handling API errors — wrap calls in try/catch and implement exponential backoff for rate limits.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more typescript examples

Frequently Asked Questions

Should I persist messages to a database?

Yes, for production bots. Store the full message history so conversations survive server restarts and can be reviewed later for quality assurance.

How do I prevent the bot from being jailbroken?

Use a clear system prompt that constrains the bot's behavior. Monitor outputs for signs of jailbreaking. Consider adding moderation filters via OpenAI's moderation API.

About This Typescript Code Snippet

This free typescript code snippet for ai chatbot basic setup is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement ai chatbot basic setup quickly and correctly.

All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.

Tags: chatbot, openai, api, conversation  | Language: typescript  | Difficulty: beginner  | Category: Node.js

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.