โœจ

Chatbot with Gemini API

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

๐Ÿ“‹ Suggested prerequisites

  • โ€ขGoogle account (Gmail)

What you'll build

You'll create your first AI chatbot using Google's Gemini API, which is completely free. The interesting part: the AI will write the code for you. You just copy, paste, and run. When you're done, you'll have a working chatbot in your terminal that answers any question. It's the first step to understanding how AI APIs work and creating your own intelligent applications.


Step 1: Open Google AI Studio

Go to aistudio.google.com and sign in with your Google account.

This is a chat with Gemini, Google's AI. Free.


Step 2: Ask it to write the code

Copy and paste this prompt:

I need a simple Node.js chatbot that:
- Uses the Gemini API
- Works in the terminal
- Maintains conversation history
- Reads the API key from the GEMINI_API_KEY environment variable

Give me the complete code and installation commands.

Press Enter and wait.

Gemini will write all the code for you. It will also tell you what commands to run.


Step 3: Get your API Key

  1. Open aistudio.google.com/apikey
  2. Click "Create API Key"
  3. Copy the key

Step 4: Configure the key in your system

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

Run this in the same terminal where you'll run the chatbot.


Step 5: Follow Gemini's instructions

Gemini gave you:

  1. Commands to create the project (mkdir, npm install, etc.)
  2. Code to paste into a file
  3. The filename (something like chatbot.js or index.mjs)
  4. The command to run it (something like node chatbot.js)

Follow its instructions step by step.

๐Ÿ’ก How do I create a file? Open your code editor (VS Code, Cursor, etc.), create a new file, paste the code, and save it with the name Gemini indicated.


Did it work?

If you see something like this, you made it:

You: Hello
Gemini: Hi! How can I help you?

If something failed

ErrorCauseSolution
API key not validKey copied wrong or expiredCheck at aistudio.google.com/apikey
Cannot find moduleMissing dependencyRun npm install @google/genai
node: command not foundNode.js not installedInstall from nodejs.org
npm: command not foundnpm not in PATHReinstall Node.js or restart terminal
GEMINI_API_KEY undefinedVariable not setRun export in the same terminal
SyntaxErrorCode copied incorrectlyCopy all the code again, don't cut
429 Too Many RequestsAPI limit reachedWait 1 minute or use another project
Gemini gives Python codeDidn't specify Node.jsAsk again: "in Node.js, not Python"

๐Ÿ’ก Important tip: If you closed the terminal, you need to run the export again. The variable only exists in that session.


What just happened?

  1. You asked an AI to write code
  2. The AI wrote it
  3. You ran it
  4. It works

You could have asked the same thing to ChatGPT, Claude, or any other AI chat. The result would be similar.


Experiment

Go back to Google AI Studio and try variations:

  • "...that responds like a pirate"
  • "...that helps me practice Spanish"
  • "...that's a math tutor"

The code changes. The process is the same.


๐Ÿ’ผ Real Case: Fintech Chatbot

If you want to adapt this chatbot for financial services, there are important security and compliance considerations.

Secure System Prompt

Add clear restrictions to the bot's behavior:

const systemPrompt = `You are a financial assistant. Strict rules:
- NEVER give specific investment advice ("buy X stock")
- NEVER request sensitive data (card numbers, passwords, CVV)
- Always recommend consulting with a certified financial advisor
- If you detect fraud or phishing intent, respond: "I cannot help with that"
- Include disclaimer: "This is general information, not financial advice"`;

// Use in the API call
const response = await ai.generateContent({
  systemInstruction: systemPrompt,
  contents: [{ role: "user", parts: [{ text: userMessage }] }]
});

Compliance Considerations

RequirementWhyHow to implement
LoggingRegulatory auditSave all conversations with timestamp
Rate limitingPrevent abuseMax 10 messages/minute per user
Visible disclaimerLegal protectionFooter: "Not financial advice"
Don't store sensitive dataPCI DSS / GDPRFilter before saving to logs

Audit Logging Example

const logConversation = async (userId, message, response) => {
  await db.insert('chat_logs', {
    user_id: userId,
    timestamp: new Date().toISOString(),
    user_message: sanitize(message), // Remove sensitive data
    bot_response: response,
    session_id: sessionId
  });
};

๐Ÿ“– Learn more about security in Authentication and Secure APIs


Next step

โ†’ Chatbot with Claude โ€” Same process, different AI


Want to understand more?

If you're interested in learning what an API is, what an LLM is, or how this works under the hood:

โ†’ What is an LLM? โ†’ Terminal basics