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.
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();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.
Yes, for production bots. Store the full message history so conversations survive server restarts and can be reviewed later for quality assurance.
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.
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.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.