paint-brush
Google Gemini로 LLM 지원서를 구축하는 방법~에 의해@alvinslee
1,790 판독값
1,790 판독값

Google Gemini로 LLM 지원서를 구축하는 방법

~에 의해 Alvin Lee9m2024/06/05
Read on Terminal Reader

너무 오래; 읽다

Google Gemini API를 사용하여 LLM 애플리케이션을 구축한 다음 해당 애플리케이션을 Heroku에 배포하는 방법에 대한 튜토리얼입니다.
featured image - Google Gemini로 LLM 지원서를 구축하는 방법
Alvin Lee HackerNoon profile picture

LLM에는 혁신의 가능성이 무궁무진한 것 같습니다. 나와 같다면 Expedia에 내장된 ChatGPT, 코드 작성을 위한 Copilot, 이미지 생성을 위한 DALL-E 등 GenAI 애플리케이션과 도구를 사용해 본 적이 있을 것입니다. 하지만 기술자로서 저는 LLM 기반 도구를 사용하는 것 이상의 일을 하고 싶습니다. 나는 내 자신을 만들고 싶다.


나는 DALL-E에게 "LLM으로 구축할 수 있는 모든 것에 대해 생각하는 컴퓨터 프로그래머의 수채화를 생성하라"고 말했습니다. 네, 꽤 정확해요.


모든 새로운 기술로 인해 빌더가 된다는 것은 간단하게 시작한다는 것을 의미합니다. 내가 배우고 있는 새로운 프로그래밍 언어나 내가 확인하고 있는 새로운 프레임워크는 모두 이와 같습니다. LLM으로 구축하는 것도 다르지 않습니다. 그래서 여기까지 살펴보겠습니다. 나는 Google Gemini와 상호작용하는 빠르고 간단한 API를 구축하여 효과적으로 나만의 작은 챗봇 도우미를 제공할 것입니다.


우리가 할 일은 다음과 같습니다:


  1. Google Gemini를 간략하게 소개합니다.
  2. 간단한 Node.js 애플리케이션을 빌드합니다.
  3. Heroku에 애플리케이션을 배포합니다.
  4. 테스트해보세요.

구글 제미니(Gemini)란 무엇인가?

대부분의 일반 소비자는 GPT-4 LLM을 기반으로 구축된 ChatGPT에 대해 알고 있습니다. 그러나 LLM의 경우 GPT-4만이 유일한 게임은 아닙니다. Google Gemini (이전에는 Bard로 알려짐)도 있습니다. 대부분의 성능 벤치마크(예: 다분야 대학 수준 추론 문제 또는 Python 코드 생성)에서 Gemini는 GPT-4보다 성능이 뛰어납니다.


쌍둥이 자리는 자신에 대해 무엇을 말합니까?


개발자로서 우리는 Google AI Studio 의 Gemini API를 통해 Gemini에 액세스할 수 있습니다. Python , JavaScript , SwiftAndroid 용 SDK도 있습니다.


괜찮은. 건물을 짓자.

Node.js 애플리케이션 빌드

우리의 Node.js 애플리케이션은 Gemini 챗봇처럼 작동하는 간단한 Express API 서버가 될 것입니다. 두 개의 끝점에서 수신됩니다. 먼저, /chat 에 대한 POST 요청( message 속성이 있는 JSON 페이로드 포함)은 메시지를 Gemini에 보낸 다음 응답을 반환합니다. 우리 애플리케이션은 Gemini와 계속해서 채팅 대화를 진행합니다. 이를 통해 우리의 챗봇은 우리를 위해 메모를 보관할 수 있는 유용한 조수로 변합니다.


둘째, POST 요청을 /reset 으로 보내면 채팅 대화가 처음부터 다시 시작되도록 재설정되어 이전 상호 작용에 대한 Gemini의 기억이 효과적으로 지워집니다.


이 코드 연습을 건너뛰려면 여기 내 GitHub 저장소 에서 모든 코드를 볼 수 있습니다.

애플리케이션 초기화

시작하려면 Node.js 애플리케이션을 초기화하고 종속성을 설치합니다.


 ~/project$ npm init -y && npm pkg set type="module" ~/project$ npm install @google/generative-ai dotenv express


그런 다음 package.json 파일의 scripts 에 다음을 추가합니다.


 "scripts": { "start": "node index.js" },


index.js 파일

우리 애플리케이션은 하나의 파일로 구성되어 있으며 매우 간단합니다. 한 번에 한 섹션씩 살펴보겠습니다.


먼저 사용할 모든 패키지를 가져옵니다. 그런 다음 Google AI에서 SDK를 초기화합니다. Gemini-pro 모델을 사용하겠습니다. 마지막으로 startChat()을 호출하여 Google에서 다중 전환 대화 라고 부르는 새로운 ChatSession 인스턴스를 생성합니다.


 import 'dotenv/config'; import express from 'express'; import { GoogleGenerativeAI } from '@google/generative-ai'; const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); const model = genAI.getGenerativeModel({ model: "gemini-pro"}); let chat = model.startChat();


다음으로 API 서버인 새로운 Express 앱을 인스턴스화합니다.


 const app = express(); app.use(express.json())


그런 다음 /chat 엔드포인트에 대한 POST 요청에 대한 리스너를 설정합니다. JSON 페이로드 본문에 message 포함되어 있는지 확인합니다. 우리는 chat 개체를 사용하여 해당 메시지를 Gemini에 보냅니다. 그런 다음 Gemini의 응답 텍스트로 API 호출자에게 응답합니다.


 app.post('/chat', async (req, res) => { if ((typeof req.body.message) === 'undefined' || !req.body.message.length) { res.status(400).send('"message" missing in request body'); return; } const result = await chat.sendMessage(req.body.message); const response = await result.response; res.status(200).send(response.text()); })


ChatSession 을 사용하면 모든 API 호출에서 Gemini와의 상호 작용 기록이 저장되고 실행된다는 점을 명심하세요. Gemini에게 대화에 대한 "기억"을 제공하는 것은 상황에 도움이 됩니다.


하지만 Gemini가 완전히 다시 시작하고 이전 컨텍스트를 모두 잊어버리도록 하려면 어떻게 해야 할까요? 이를 위해 /reset 엔드포인트가 있습니다. 이것은 단순히 새로운 ChatSession 시작합니다.


 app.post('/reset', async (req, res) => { chat = model.startChat(); res.status(200).send('OK'); })


마지막으로 서버를 시작하여 청취를 시작합니다.


 const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`) })


참고로 이 전체 프로젝트는 단지 미니 데모일 뿐입니다. 프로덕션에 사용하기 위한 것이 아닙니다! 지금까지 제가 설계한 방식(인증 없이)으로 URL이 있는 사람은 누구나 /chat 에서 /reset 으로 요청을 보낼 수 있습니다. 프로덕션 설정에서는 적절한 인증이 이루어지며 각 사용자는 다른 누구도 조작할 수 없는 Gemini와의 대화에 대한 자체 인스턴스를 갖게 됩니다.

Gemini API 키 얻기

이제 거의 준비가 되었습니다. 마지막으로 필요한 것은 Gemini API에 액세스하기 위한 API 키입니다. API 키를 얻으려면 먼저 Google AI for Developers 계정 에 가입하세요.


로그인한 후 Google AI Studio 실행을 선택하여 새로운 Google Gemini 프로젝트를 시작하세요.



프로젝트 내에서 API 키 가져오기를 클릭하여 API 키 페이지로 이동합니다. 그런 다음 API 키 생성을 클릭하여 키를 생성합니다. 값을 복사합니다.


프로젝트에서 .env.template 파일을 .env 라는 새 파일로 복사합니다. Gemini API 키 값을 붙여넣으세요. .env 파일은 다음과 유사해야 합니다.


 GEMINI_API_KEY=ABCDEFGH0123456789_JJJ

로컬에서 애플리케이션 테스트

모든 것이 준비되면 로컬에서 서버를 가동하여 테스트할 수 있습니다.


 ~/project$ npm start > [email protected] start > node index.js Server is running on port 3000


다른 터미널에서 일부 컬 요청을 보낼 수 있습니다.


 $ curl -X POST -H 'content-type:application/json' \ --data '{"message":"I would like to bake a shepherds pie to feed 8 \ people. As you come up with a recipe, please keep a grocery \ list for me with all of the ingredients that I would need to \ purchase."}' \ http://localhost:3000/chat **Shepherd's Pie Recipe for 8** **Ingredients:** **For the Filling:** * 1 pound ground beef * 1/2 pound ground lamb * 2 medium onions, diced … **For the Mashed Potatoes:** * 3 pounds potatoes, peeled and quartered * 1/2 cup milk … **Instructions:** **For the Filling:** 1. Heat a large skillet over medium heat. Add the ground beef and lamb and cook until browned. … $ curl -X POST -H 'content-type:application/json' \ --data '{"message":"I also need to buy fresh basil, for a different dish (not the shepherds pie). Add that to my grocery list \ too."}' \ http://localhost:3000/chat **Updated Grocery List for Shepherd's Pie for 8, and Fresh Basil:** * 1 pound ground beef * 1/2 pound ground lamb * 2 medium onions * 2 carrots * 2 celery stalks * 1 bag frozen peas * 1 bag frozen corn * 1 tablespoon Worcestershire sauce * 1 teaspoon dried thyme * 1 cup beef broth * 1/4 cup tomato paste * 3 pounds potatoes * 1/2 cup milk * 1/4 cup butter * **Fresh basil** $ curl -X POST -H 'content-type:application/json' \ --data '{"message":"What items on my grocery list can I find in the \ produce section?"}' \ http://localhost:3000/chat The following items on your grocery list can be found in the produce section: * Onions * Carrots * Celery * Potatoes * Fresh basil $ curl -X POST http://localhost:3000/reset OK $ curl -X POST -H 'content-type:application/json' \ --data '{"message":"What items are on my grocery list?"}' \ http://localhost:3000/chat I do not have access to your grocery list, so I cannot give you the items on it.


작동 중입니다. 배포할 준비가 된 것 같습니다!

Heroku에 애플리케이션 배포

애플리케이션을 배포하기 위해 Heroku를 사용하기로 결정했습니다. 빠르고 간단하며 비용이 저렴합니다. 핵심적인 인프라 문제에 얽매이지 않고 몇 가지 간단한 단계만 거치면 클라우드에서 코드를 실행할 수 있습니다. 이렇게 하면 멋진 애플리케이션을 구축하는 데만 집중할 수 있습니다.


Heroku 계정에 가입하고 CLI를 설치한 후 배포하는 데 필요한 작업은 다음과 같습니다.

코드베이스에 Procfile 추가

Heroku에 애플리케이션 시작 방법을 알려주는 Procfile 이라는 파일을 포함해야 합니다. Procfile 의 내용은 다음과 같습니다.


 web: npm start


이 파일을 코드베이스 저장소에 커밋합니다.

Heroku에 로그인(CLI를 통해)

 ~/project$ heroku login

앱 만들기

 ~/project$ heroku create gemini-chatbot Creating ⬢ gemini-chatbot... done https://gemini-chatbot-1933c7b1f717.herokuapp.com/ | https://git.heroku.com/gemini-chatbot.git

Gemini API 키를 구성 환경 변수로 추가

 ~/project$ heroku config:add \ --app gemini-chatbot \ GEMINI_API_KEY=ABCDEFGH0123456789_JJJ Setting GEMINI_API_KEY and restarting ⬢ gemini-chatbot... done, v3 GEMINI_API_KEY: ABCDEFGH0123456789_JJJ

Heroku Remote에 코드 푸시

 ~/project$ git push heroku main ... remote: -----> Building on the Heroku-22 stack remote: -----> Determining which buildpack to use for this app remote: -----> Node.js app detected ... remote: -----> Build succeeded! remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: Done: 45.4M remote: -----> Launching... remote: Released v4 remote: https://gemini-chatbot-1933c7b1f717.herokuapp.com/ deployed to Heroku


그게 다야? 그게 다야.

배포된 애플리케이션 테스트

애플리케이션이 배포되면 Heroku 앱 URL로 일부 컬 요청을 보내겠습니다.


 $ curl -X POST -H 'content-type:application/json' \ --data '{"message":"If I ask you later for my PIN, remind me that it \ is 12345."}' \ https://gemini-chatbot-1933c7b1f717.herokuapp.com/chat Sure, if you ask me for your PIN later, I will remind you that it is 12345. **Please note that it is not a good idea to share your PIN with anyone, including me.** Your PIN is a secret code that should only be known to you. If someone else knows your PIN, they could access your account and withdraw your money. $ curl -X POST -H 'content-type:application/json' \ --data '{"message":"What is my PIN?"}' \ https://gemini-chatbot-1933c7b1f717.herokuapp.com/chat Your PIN is 12345. $ curl -X POST https://gemini-chatbot-1933c7b1f717.herokuapp.com/reset OK $ curl -X POST -H 'content-type:application/json' \ --data '{"message":"What is my PIN?"}' \ https://gemini-chatbot-1933c7b1f717.herokuapp.com/chat Unfortunately, I am unable to provide your personal PIN as I do not have access to your private information. If you can't remember it, I suggest you visit the bank or organization that issued the PIN to retrieve or reset it.


결론

지금은 LLM 기반 애플리케이션을 구축하기에 좋은 시기입니다. 파도를 타고!


우리는 Google Gemini 위에 간단한 LLM 기반 애플리케이션을 구축하는 방법을 살펴보았습니다. 간단한 챗봇 도우미는 기본이지만 Gemini API 및 관련 SDK에 익숙해질 수 있는 좋은 방법입니다. 그리고 배포에 Heroku를 사용하면 부차적인 문제를 덜고 중요한 곳에서 학습하고 구축하는 데 집중할 수 있습니다.