이번에 프로젝트를 하면서 챗봇 기능이 있으면 좋겠다!라는 생각에 Gemini Open Api를 연결해서 챗봇 기능을 구현해 보았다.
그러면 어떻게 구현하고 연결했는지 과정을 살펴보도록 하자
1. Gemini API Key 발급받기
Google AI Studio
Google AI Studio is the fastest way to start building with Gemini, our next generation family of multimodal generative AI models.
aistudio.google.com
Go to Google AI Studio 버튼 클릭!
그 후 Get API Key를 클릭해서 API Key 만들기 버튼을 눌러준다.
만들 프로젝트를 선택해주면 API 키가 발급된 걸 확인할 수 있다!
이렇게 나오면 API 키를 발급 받는데 성공했다는 것을 볼 수 있다~
이제 Node.js 서버에서 Gemini API 호출을 처리해준다.
2. module 설치
npm install express cors body-parser google-genai
해당 프로젝트 파일에 있는 터미널에 위 명령어로 module을 다운받는다.
3. env 파일 설정
프로젝트 루트 위치에 .env 파일을 만들어 발급받은 API KEY를 저장해준다.
GEMINI_API_KEY=발급 받은 API 키
4. chatbotRoutes.js로 api 만들기! (node.js)
require('dotenv').config({ path: require('path').resolve(__dirname, '../../.env') });
const express = require('express')
const router = express.Router();
const genAI = require('@google/generative-ai');
const genAIClient = new genAI.GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAIClient.getGenerativeModel({ model: "gemini-1.5-flash" });
//chatbot api
router.post('/', async (req, res) => {
try {
const { message } = req.body;
const result = await model.generateContent(message)
const reply = result.response.text()
res.json({ reply })
} catch (err) {
console.error('gemini api error: ', err)
res.status(500).json({ error: 'Gemini api 호출 중 오류 발생' })
}
})
module.exports = router;
이 API의 역할
1. 사용자가 입력한 메시지를 /chatbot 경로로 post 요청함
2. chatRoutes.js가 그 요청을 받아 Goggle Gemini API에 메시지를 전달함
3. Gemini가 생성한 응답을 받아 프론트엔드에 다시 응답한다
5. 프론트에서 chatbotRoutes.js api 연결하기
import React from "react";
import { View, TextInput, Button, Text, ScrollView } from "react-native";
import { useState } from "react";
import axios from "axios";
type chatMsg = {
from: 'me' | 'ai';
text: string;
}
export default function ChatBot() {
const [userInput, setUserInput] = useState<string>('') // 사용자가 입력한 텍스트 저장
const [chatLog, setChatLog] = useState<chatMsg[]>([]) //이전 대화 내용 저장 배열
const sendMessage = async () => {
try {
const response = await axios.post('http://localhost:5000/chatbot', {
message: userInput,
})
setChatLog([...chatLog, //...chatLog : 이전 내용 복사해서 유지함
//채팅내용에 내 메세지랑 ai가 생성한 걸 동시에 추가하는 거임!
{ from: 'me', text: userInput }, // 내가 보낸 메세지
{ from: 'ai', text: response.data.reply }]); //ai가 답한 메세지
setUserInput('') //입력창 비우기
} catch (err) {
console.error('에러 발생 : ', err)
}
}
return (
<View style={{ flex: 1, padding: 16 }}>
<ScrollView style={{ flex: 1, height: 500 }}>
{chatLog.map((msg, idx) => (
<Text key={idx} style={{ marginVertical: 5, color: msg.from === 'me' ? 'blue' : 'green' }}>
{msg.from === 'me' ? '👤' : '🤖'} {msg.text}
</Text>
))}
</ScrollView>
<TextInput
value={userInput}
onChangeText={setUserInput}
placeholder="메세지를 입력하세요"
style={{ borderColor: '#ccc', borderWidth: 1, padding: 10, marginVertical: 10 }}
/>
<Button title="보내기" onPress={sendMessage} />
</View>
)
}
'API' 카테고리의 다른 글
Exchange Rate API를 활용해 환율 계산기 구현하기 (0) | 2025.05.15 |
---|