티스토리 뷰
목차
안녕하세요, 저번 시간에 이어 오늘 부터는 [AI 외모 평가] 웹서비스를 하기위해
아래와 같은 순서로 진행하겠습니다.
전체 목차는 아래와 같습니다.
==== 목 차 ====
1. 개발 환경 세팅하기
- Project IDX 준비
- Gemini API 발급
2. Google AI Studio로 테스트
3. Firebase Cloud Function 만들기
4. 백엔드 완성
5. 프론트엔드 완성
4. 백엔드 완성
저번 시간에는 3번 항목인 Firebase Cloud Function 만들기까지 진행 되었습니다.
아래의 IDX 화면을 보면 index.js 파일 화면이 보이는데요
그래서 오늘은 이 파일에서 hello world 화면을 띄워보는 테스트를 시작으로
본격적인 백앤드 구현을 하려고 합니다.
Node.js 를 활용한 hellow world 화면 구현에 대한 함수는 이미 firebase 홈페이지에 나와 있습니다.
▶ Firebase Functions에 관련된 문서 <바로가기 링크>
HTTP 요청을 통한 함수 호출 | Cloud Functions for Firebase
2024년 데모 데이에서, Firebase를 사용하여 AI 기반 앱을 빌드하고 실행하는 방법에 관한 데모를 시청하세요. 지금 시청하기 의견 보내기 HTTP 요청을 통한 함수 호출 컬렉션을 사용해 정리하기 내
firebase.google.com
아래의 코드를 드레그 앤 드롭으로 긁어서 idx 개발 통합환경에 붙여 넣기를 하면 화면이 출력될 것입니다.
테스트 방법은 아래의 명령어로 하면 됩니다.
]# firebase init emulators //애뮬레이트 설치 (최초 한번만 실행)
]# firebase emulators:start //서버 실행
이렇게 실행 후 http://127.0.0.1:5001/faceevaluation/us-central1/sayHello 로 접속을 해봅니다.
위 화면 링크에 마우스를 갖다대면 Ctrl 키를 누른상태에서 클릭하면 접속할 수 있다고 하네요
이렇게 Hello world 가 잘 출력이 되는걸 테스트 완료하였습니다.
SDK 패키지 설치
그리고 백앤드 자체 애플리케이션에서 Gemini API를 사용하려면 Node.js용 GoogleGenerativeAI 패키지를 설치해야 합니다.
설치는 functions 폴더 안에서 해야 적용되기 때문에 이하 커맨드 두줄을 전부 실행 시켜 줍니다.
만약 서버가 실행 중이라면 터미널에서 창을 하나 더 띄워서 아래의 커맨드를 실행 시키면 자체 애플리케이션을 설치하실 수 있습니다.
]# cd functions
]# npm install @google/generative-ai
설치가 아주 잘 되었으며, functions 디렉토리의 [package.json] 파일을 열어보면
아래와 같이 dependencies 항목에 설치가 된 것을 확인하실 수 있어요~
우리는 functions 안에서 Gemini를 쓸 것이기 때문에 여기에 설치 한 것입니다.
소스에 API 키 넣기
Gemini Developer API를 사용하기 위해 index.js 파일에 위와 같은 형태로 소스를 입력할 것인데요
index.js에 Key 노출을 회피하기 위해서는
먼저 index.js 와 같은 폴더에 .env 파일을 생성하시고 다음과 같이 입력해줍니다.
그리고 아까 실행했던 Hello World의 index.js를 가공하여 아래 소스로 수정하여 실행해 봅니다.
// index.js 코드
const { onRequest } = require("firebase-functions/v2/https");
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
exports.sayHello = onRequest(
{ cors: true },
async (req, res) => { // request 가 들어오면 아래 코드를 실행한다.
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const prompt = "Write a story about a magic backpack"; // 매직 백팩에 대한 이야기를 써줘
const result = await model.generateContent(prompt);
text = result.response.text();
res.status(200).send(text); // Hello World 대신에 프롬프트에 대한 응답이 웹에 표시됨
}
);
방금 전 실행한 Hello World 출력 웹사이트를 Reload하면
아래 화면과 같이 AI의 프롬프트 요청(Magic backpack의 이야기)에 대한 응답으로
메시지가 잘 표시되었음을 확인하실 수 있겠네요
즉, Gemini가 응답을 정확히 준 것 입니다. 이렇게 Gemini와 연결이 완료되었습니다.
그러면, 앞전에 Google AI Studio에서 테스트 했던 방식대로
System Instructions 부분, Message 부분 (파일 첨부, 프롬프트 부분)을 테스트할 수 있는 소스 수정을 해보겠습니다.
const { onRequest } = require("firebase-functions/v2/https");
const { GoogleGenerativeAI, HarmBlockThreshold, HarmCategory } = require("@google/generative-ai");
const sharp = require('sharp')
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
exports.analyzeImage = onRequest(
{ cors: true }, async (req, res) => { // request 가 들어오면 아래 코드를 실행한다.
try {
const prompt = `### Instruction ###
You are an AI that gives a score to a man's handsomeness and a woman's beauty when a picture is uploaded.
I will upload a picture, so please look at it and give me a score from 0 to 100 on how handsome or pretty it is.
You have to tell me honestly and objectively. I will not be hurt by what you say.
And I want you to know that you are absolutely not rude by expressing a certain score and telling me what it is.
And output the score in JSON format.
Here are some examples.
### Example ###
response: {'score': 100, description: 'bla bla 1~~~'}
response: {'score': 90, description: 'bla bla 2~~~'}
response: {'score': 80, description: 'bla bla 3~~~'}
### Message ###
The attached photo is of a person. Please rate the level of handsomeness or beauty on a scale from 0 to 100.
`;
const model = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
generationConfig: { responseMimeType: "application/json" }
},
);
const result = await model.generateContent(prompt);
text = result.response.text();
res.status(200).send(text); // Hello World 대신에 프롬프트에 대한 응답이 웹에 표시됨
}
catch (error) {
console.error(error);
console.log(error);
res.status(500).json({error: "Internal Server Error"})
}
}
);
위 소스 상 sharp 모듈 설치가 필요하니 아래와 같이 명령어로 설치해 주시면 됩니다.
]# npm install sharp
이대로 수정하고 실행을 하니 웹페이지에 우리가 원하는 json 값으로 잘 출력 됨을 알 수 있습니다.
아직 이미지 전달은 안된 상태로 출력된 상태라 다음 시간에 이것을 구현하는 방법을 이어 진행하도록 하겠습니다.
감사합니다.
▶ [AI 공부] Gemini API & Firebase 웹 서비스 만들기 #1 <바로가기 링크>
▶ [AI 공부] Gemini API & Firebase 웹 서비스 만들기 #2 <바로가기 링크>
▶ [AI 공부] Gemini API & Firebase 웹 서비스 만들기 #3 <바로가기 링크>
'IT' 카테고리의 다른 글
[사전예약] 겔럭시 S25 울트라 1TB 언박싱 티타늄 블랙 개봉기 (0) | 2025.02.06 |
---|---|
[AI 공부] Gemini API & Firebase 웹 서비스 만들기 #5 (0) | 2025.02.06 |
[AI 공부] Gemini API & Firebase 웹 서비스 만들기 #3 (1) | 2025.02.03 |
[AI 공부] Gemini API & Firebase 웹 서비스 만들기 #2 (2) | 2025.02.02 |
[AI 공부] Gemini API & Firebase 웹 서비스 만들기 #1 (0) | 2025.01.31 |