검색
검색
공개 노트 검색
회원가입로그인

[UCA울산코딩아카데미] 오픈라우터 AI로 구글 gemma 모델에 무한 토큰 사용하기

306900613-01333db3-c27b-4044-88b3-9b2ffbe06415

구글 Gemma는 구글에서 제미나이 발표 후, 파인튜닝 (미세조정)을 할 수 있게 공개한 오픈소스 모델이다. gemma 모델이 나온 뒤에야 제미나이 1.0 프로모델에 튜닝 모델이 추가로 들어갔다. 아직 제미나이 울트라가 나오기 전이긴 하지만, 1.5 모델에 대한 튜닝 모델도 곧 나오리라 생각한다.

제미나이 튜닝모델의 이름은 gemini-1.0-pro-001 처럼 사용한다.

gemma4

model = genai.GenerativeModel(

model_name="gemini-1.0-pro-001",

generation_config=generation_config,

safety_settings=safety_settings)

코드 일부 발췌


model = genai.GenerativeModel(model_name="gemini-1.0-pro-001",
                              generation_config=generation_config,
                              safety_settings=safety_settings)

convo = model.start_chat(history=[
])

convo.send_message("make")
print(convo.last.text)

그런데 이 오픈소스로 공개한 Gemma 모델은 좀 개발자에게 불친철하다.

이게 이름만 빠른시작 가이드가 맞는지 모르겠다.

첫번째로 ai.googl.dev/gemma 에서 나오는 문구를 보고 있으면,

gemma6

일단 구글 자기네꺼라고 Kaggle 사이트 가입을 강제한다.

API_KEY를 Kaggle 사이트에서 받아서 써야하고, 주어진 샘플 코드를 돌리는 구글 코랩에도 kaggle의 시크릿키를 넣는 부분이 따로 있다. 일단 귀찮게이곳저곳 다니게 만들어놨다.

두번째, 가운데 화면은 구글 자기네거라고 Vertex AI에 가입을 유도한다.

신용카드 입력하고 프로젝트 이름 넣고 아니 이게 빠른 시작인가?

구글 제미나이 프로때는 안 하던 짓을 한다.

세번째, 마지막 화면은 Keras 3로 백엔드 프레임워크를 사용해서 Gemma 모델을 고유 도메인과 데이터에 맞게 조정하라는데 주어진 구글 코랩 예제부터 잘 안 돌아간다.

kaggle의 시크릿 키를 코랩의 좌측 크레덴셜 란 (열쇠모양)에 집어넣는거랑도 상관없다. keras3 패키지가 구글 코랩에서 설치가 잘 안 되는듯하다.

keras3에서 먼저 삐끗하니 이거 gemma 모델을 어디서 돌려야하는건지 난감하게 한다...

난 프랑소와 숄레 창시자가 쓴 케라스 책을 통해 케라스 2만 알고있으니 마음은 급하고, 진도는 안나가고....

gemma 서비스 개발한 쪽은 죄다 불친절하기만 하고 조금 답답하다.

ollama와 구글 gemma를 같이 쓰는 방법은 ulksancoding.com에서 확인바란다.

개발자들이 쉽게 이용하는 방법으로 ollama에서 gemma 2b와 7b를 이용하는 API 코딩에 대한 게시물을 만들었는데, 케라스 3는 도저히 테스트하기가 힘들어서 새로운 응용 방법을 두가지 더 개발했다.

그중 하나가 오늘 여기서 보게될 openrouter AI (오픈라우터 AI )이다.

오픈라우터는 perplexity나 poe처럼 유료로 사용되는 AI 모델들이 포진해있는데, 보통 사용한 토큰에 비례해서 비용을 지불해야하지만, 일단 필자가 알아낸 바에 의하면

모델명 뒤에 (Free)라고 붙어있는 AI 모델들에 대해서는 전혀 사용료를 지불하지않는다는 맹점이 있다.

구글의 Gemma 모델도 그중 하나다.

오픈라우터는 파이썬 , NODE.JS등의 샘플코드도 제공되지만, 독자적인 API_KEY도 발급해주는데, 다른 모델들과 달리 신용카드 입력 없이 발급이 가능하다.

그리고, 키를 만들때 No-limit로 값을 적지않고 빈칸으로 세팅해준다.

그러면 0$로 사용량이 찍히는 OpenROUTER API_KEY가 만들어진다.

gemma7_openrouter

각 API_KEY마다 응답결과 JSON의 Usage에서 나오던 총 토큰 사용량이 찍힌다.

gemma 모델은 0 달러이다.

gemma8_openrouter

파이썬 샘플코드 1

import requests
import json
import os 

OPENROUTER_API_KEY="skt-or..."
YOUR_SITE_URL ="ulsancoding.com"
YOUR_APP_NAME = "GemmaTest"
"
response = requests.post(
  url="https://openrouter.ai/api/v1/chat/completions",
  headers={
    "Authorization": f"Bearer {OPENROUTER_API_KEY}",
    "HTTP-Referer": f"{YOUR_SITE_URL}", # Optional, for including your app on openrouter.ai rankings.
    "X-Title": f"{YOUR_APP_NAME}", # Optional. Shows in rankings on openrouter.ai.
  },
  data=json.dumps({
    "model": "google/gemma-7b-it:free", # Optional
    "messages": [
      {"role": "user", "content": "do u know kpop girlgroup ive Ahn yoo jin?"}
    ]
  })
)

응답값은 다음처럼 나온다.

'''
{'id': 'gen-1zkYK1Y2FV4Q2XK2owQ6Atcfkx92', 
'model': 'google/gemma-7b-it:free', 
'created': 1710861218, 
'object': 'chat.completion', 
'choices': [
              {'message': 
                {'role': 'assistant', 
                 'content': 'Yes, I am familiar with IVE Ahn Yoo Jin, a member of the K-Pop girl group IVE. Here\'s a summary of what I know about her:\n\n**Ahn Yoo Jin:**\n\n* **Born:** January 3, 2003 (age 20)\n* **Nationality:** Korean\n* **Position:** Lead Vocalist, Lead Dancer, Visual\n* **Sub-unit:** IVE Vocal Team\n* **Known for:**\n    * **Powerful vocals:** Possesses a strong, clear, and versatile voice 
with a wide vocal range.\n    * **Sharp dancing:** Known for her precise dance moves and energetic performances.\n    * **Visual appeal:** Considered one of the most visually stunning members 
in IVE with a captivating beauty and graceful figure.\n    * **Tendency towards aegyo:** Known for her playful and humorous aegyo, sometimes bordering on cute and bubbly.\n    * **MCing:** Served as the MC for various music shows, showcasing her poise and charm.\n\n**Additional information:**\n\n* Ahn Yoo Jin debuted with IVE in November 2020.\n* Prior to debut, she participated in the "Finding Treasure 2" survival show.\n* She has received recognition for her strong vocal and dance skills, earning the title "Best Rookie Female Dancer" at the 2021 Korea First Brand Awards.\n* She is known for her bright personality and positive energy, influencing fans globally.\n\nOverall, Ahn Yoo Jin is a multi-talented and captivating member of IVE, known for her stunning visuals, powerful vocals, sharp dancing, and charming personality.'
                 }
               }
            ], 
'usage': {'prompt_tokens': 44, 'completion_tokens': 433, 'total_tokens': 477, 
           'total_cost': 0}}
'''

gemma10_openrouter

G-idle 여자아이들에 대해서 Gemma모델에게 물어본 뒤,

content부분만 뽑아내서 찍은 결과물이다.


Yes, I am familiar with G-Idle, a popular Korean girl group. I have access to vast amounts of information about them, including their members, their achievements, and their music. I can provide you with information on various topics about G-Idle, such as:

* **Members:** Their names, positions, birthdays, nationality, and roles in the group.
* **Achievements:** Awards won, records broken, and other notable accomplishments.
* **Music:** Their discography, music videos, and popular songs.
* **Career:** Their rise to popularity, their schedule, and their latest news.
* **Fandom:** G-Idle's fanbase, known as Aroha, and their impact on the K-Pop community.

Would you like me to share some information about G-Idle with you? Please let me know what you're interested in learning about.

openAI스타일로 코딩하는 것도 제공된다.

openAI스타일 파이썬코드-2


from openai import OpenAI
from os import getenv 

OPENROUTER_API_KEY="skt-or..."
YOUR_SITE_URL ="ulsancoding.com"
YOUR_APP_NAME = "GemmaTest

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url = "https://openrouter.ai/api/v1",
  api_key = OPENROUTER_API_KEY,
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="google/gemma-7b-it:free",
  messages=[
    {
      "role": "user",
      "content": "do u know kpop girlgroup ive Ahn yoo jin?",
    },
  ],
)


print(completion.choices[0].message.content)

더 자세한 것은 ulsancoding.com 게시물을 참고하기바란다.

파이썬 소스코드 두개의 다운로드가 추가로 있으며,

미스트랄 7B및 ollama 서비스등의 추가 게시물을 볼 수있다.

-----------------------------------

UCA울산코딩아카데미

ulsancoding.com

교육문의

052-708-0001

공유하기
카카오로 공유하기
페이스북 공유하기
트위터로 공유하기
url 복사하기
조회수 : 303
heart
T
페이지 기반 대답
AI Chat