๐ŸŸข

Chatbot with OpenAI API

๐Ÿง‘โ€๐ŸŽ“ Apprenticeโฑ๏ธ 15 minutes

๐Ÿ“‹ Suggested prerequisites

  • โ€ขChatbot with Gemini completed
  • โ€ขCredit card (for API)

What you'll build

You'll complete the trio by creating a chatbot with OpenAI's API, the creators of ChatGPT. The process is identical to Gemini and Claude: get API key, create the code, run it. When you're done, you'll know how to connect to the three main AI providers: Gemini, Claude, and OpenAI. You'll have the flexibility to choose any provider based on costs, capabilities, or project preferences.

โš ๏ธ Note: OpenAI API requires adding credits. Minimum $5 USD.


Step 1: Get your OpenAI API Key

  1. Go to platform.openai.com
  2. Create an account or sign in
  3. Go to API Keys (left menu)
  4. Click Create new secret key
  5. Copy the key (only shown once)

Step 2: Add credits

  1. Go to Settings โ†’ Billing
  2. Add a payment method
  3. Add credits (minimum $5)

๐Ÿ’ก $5 USD is enough for thousands of messages with GPT-4o-mini.


Step 3: Ask an AI to write the code

Open Google AI Studio, ChatGPT, or any AI chat.

Copy and paste this prompt:

I need a simple Node.js chatbot that:
- Uses the OpenAI API (GPT-4o-mini)
- Works in the terminal
- Maintains conversation history
- Reads the API key from the OPENAI_API_KEY environment variable

Give me the complete code and installation commands.

Step 4: Configure the key in your system

SystemCommand
macOS/Linuxexport OPENAI_API_KEY="your-key-here"
Windows PowerShell$env:OPENAI_API_KEY="your-key-here"

Step 5: Follow the instructions

The AI gave you:

  1. Commands to create the project
  2. Code for the file
  3. The command to run it

Follow its instructions step by step.


Did it work?

You: Hello GPT
GPT: Hello! How can I help you?

If something failed

ErrorCauseSolution
invalid_api_keyWrong keyCheck at platform.openai.com/api-keys
insufficient_quotaNo creditsAdd credits in Billing
Cannot find moduleMissing SDKRun npm install openai
rate_limit_exceededToo many requestsWait a few seconds
model_not_foundWrong modelUse gpt-4o-mini or gpt-4o

Comparison: Which one to use?

APICostStrengthBest for
GeminiFreeEasy to startLearning, prototypes
Claude~$3/M tokensCode, reasoningSerious development
OpenAI~$0.15/M tokensVersatile, ecosystemProduction, plugins

๐Ÿ’ก For learning, use Gemini. For serious projects, try all three and choose.


What's next?

You've completed the cloud API trio. Now you can:

โ†’ Local Chatbot with Ollama โ€” 100% private, no internet โ†’ Chat with Web UI โ€” Give it a nice face


Want to understand more?

โ†’ What is an LLM?