Google Gemini Chat
AI-powered Q&A system for Express using Google Gemini API with fast and intelligent natural language responses.
Overview
A modern AI-powered Q&A component built with Google Gemini’s API and Express.js. It exposes a REST API endpoint that receives a user's question and returns an intelligent, context-aware answer powered by Google's Gemini models. Designed to be flexible, lightweight, and easy to integrate with any frontend application.
Installation
What This Does
Sets up an Express service for text-based Q&A powered by Google Gemini AI.
Files & Folders Created
| File / Path | Description |
|---|---|
| /src/config/gemini.js | Initializes Gemini client with API key. |
| /src/services/qnaService.js | Handles question requests and AI responses. |
| /src/routes/qna.js | Express route for /api/ai/qna endpoint. |
| .env.example | Configuration for Gemini API and model. |
| server.js | Example Express entry point. |
Files to be modified
| File / Path | Description |
|---|---|
| server.js | Adds QnA API route (/api/ai/qna). |
| .env | Adds GEMINI_API_KEY and MODEL_NAME configuration. |
Configuration
# Google Gemini API Configuration GEMINI_API_KEY=your-google-gemini-api-key MODEL_NAME=gemini-1.5-flash PORT=3001
Frontend Integration
Integrate the Q&A API easily with any frontend — especially Next.js — to power intelligent chatbot or assistant features.
Sends a user question to Gemini and returns an AI-generated response.
Example
1// Example (Next.js / React)
2import { useState } from 'react';
3
4export default function GeminiQnA() {
5 const [question, setQuestion] = useState('');
6 const [answer, setAnswer] = useState('');
7
8 async function askGemini() {
9 const res = await fetch('/api/ai/qna', {
10 method: 'POST',
11 headers: { 'Content-Type': 'application/json' },
12 body: JSON.stringify({ question })
13 });
14 const data = await res.json();
15 setAnswer(data.answer || 'Error: No response');
16 }
17
18 return (
19 <div className="space-y-4 max-w-md mx-auto p-4">
20 <h2 className="text-lg font-semibold text-foreground">Ask Google Gemini</h2>
21 <input
22 value={question}
23 onChange={(e) => setQuestion(e.target.value)}
24 placeholder="Ask a question..."
25 className="w-full border border-border bg-background/50 rounded-lg px-3 py-2 text-sm text-foreground"
26 />
27 <button
28 onClick={askGemini}
29 className="px-4 py-2 rounded-lg bg-emerald-500 text-white text-sm hover:bg-emerald-600 transition"
30 >
31 Ask
32 </button>
33 {answer && (
34 <div className="p-3 border border-border/40 bg-secondary/30 rounded-lg text-sm text-muted-foreground whitespace-pre-wrap">
35 <strong>Answer:</strong> {answer}
36 </div>
37 )}
38 </div>
39 );
40}Usage
1// Simple API request example
2const res = await fetch('/api/ai/qna', {
3 method: 'POST',
4 headers: { 'Content-Type': 'application/json' },
5 body: JSON.stringify({ question: 'What is quantum computing?' })
6});
7const data = await res.json();
8console.log('Gemini says:', data.answer);