A simple Node.js application that demonstrates how to use OpenAI's Chat Completions API to create a basic chatbot.
- 🤖 Integration with OpenAI's GPT models (GPT-4.1 or GPT-4o)
- 💬 Simple chat completion example
- 🔧 Environment variable configuration
- 📦 Modern ES modules support
- Node.js (Latest LTS version)
- An OpenAI API key
-
Clone this repository:
git clone https://github.com/javascriptcebu/simple-chat cd simple-chat -
Install dependencies using bun (recommended) or npm:
# Using bun (recommended) bun install # Or using npm npm install
-
Set up your environment variables:
# Create a .env file in the root directory touch .env -
Add your OpenAI API key to the
.envfile:OPENAI_API_KEY=your_openai_api_key_here
Run the chat application:
# Using bun (recommended)
bun start
# Or using npm
npm startThe application will send a predefined message to the OpenAI API and display the response in the console.
OPENAI_API_KEY: Your OpenAI API key (required)
You can modify the model used in chat.js:
model: "gpt-4.1", // or "gpt-4o"Available models:
gpt-4.1- Fast and cost-effectivegpt-4o- More capable but slower and more expensive
simple-chat/
├── chat.js # Main application file
├── package.json # Project dependencies and scripts
├── .env # Environment variables (create this)
├── .gitignore # Git ignore rules
└── README.md # This file
To customize the chat behavior, modify the messages array in chat.js:
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Your custom message here' },
];- openai: Official OpenAI Node.js library
- dotenv: Loads environment variables from .env file
- Visit OpenAI's website
- Sign up or log in to your account
- Navigate to the API section
- Generate a new API key
- Copy the key and add it to your
.envfile
- "API key not found" error: Make sure your
.envfile contains the correctOPENAI_API_KEY - Module import errors: Ensure you're using Node.js version 14 or higher
- Network errors: Check your internet connection and API key validity
If you encounter any issues, please check:
- Your OpenAI API key is valid and has sufficient credits
- Your Node.js version is compatible
- All dependencies are properly installed