Gemini API로 Gemma 실행

Gemini API는 애플리케이션 개발이나 프로토타입 제작에 사용할 수 있는 프로그래밍 API로서 Gemma에 호스팅된 액세스를 제공합니다. 이 API는 생성형 AI 작업을 처리하기 위해 Gemma 및 웹 서비스의 자체 로컬 인스턴스를 설정하는 대신 사용할 수 있는 편리한 대안입니다.

다음 예에서는 Gemini API와 함께 Gemma를 사용하는 방법을 보여줍니다.

Python

from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

response = client.models.generate_content(
    model="gemma-4-31b-it",
    contents="Roses are red...",
)

print(response.text)

Node.js

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY"});

const response = await ai.models.generateContent({
  model: "gemma-4-31b-it",
  contents: "Roses are red...",
});
console.log(response.text);

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemma-4-31b-it:generateContent?key=YOUR_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
  "contents": [{
    "parts":[{"text": "Roses are red..."}]
    }]
   }'

API 키 가져오기

모바일, 웹, 클라우드 서비스와 같은 다양한 플랫폼에서 여러 프로그래밍 언어를 사용하여 Gemini API에 액세스할 수 있습니다. Gemini API SDK 패키지에 관한 자세한 내용은 Gemini API SDK 다운로드 페이지를 참고하세요. Gemini API에 대한 일반적인 소개는 Gemini API 빠른 시작을 참고하세요.

생각 중

Gemma 4는 다단계 추론을 최적화하는 내부 '사고 과정'을 활용하여 알고리즘 코딩 및 고급 수학 증명과 같이 논리적으로 까다로운 도메인에서 우수한 성능을 제공합니다.

Gemma 4는 이 기능의 사용 설정 또는 사용 중지를 엄격하게 지원하지만, API에서는 사고 수준을 "high"로 설정하여 이 기능을 사용 설정합니다.

다음 예는 사고 과정을 활성화하는 방법을 보여줍니다.

Python

from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

response = client.models.generate_content(
    model="gemma-4-31b-it",
    contents="What is the water formula?",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(thinking_level="high")
    ),
)

print(response.text)

Node.js

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY"});

const response = await ai.models.generateContent({
  model: "gemma-4-31b-it",
  contents: "What is the water formula?",
  config: {
    thinkingConfig: {
      thinkingLevel: ThinkingLevel.HIGH,
    },
  },
});
console.log(response.text);

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemma-4-31b-it:generateContent?key=YOUR_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
  "contents": [{
    "parts":[{"text": "What is the water formula?"}]
    }],
    "generationConfig": {
      "thinkingConfig": {
            "thinkingLevel": "high"
      }
    }
   }'

사고에 대해 자세히 알아보기

이미지 이해

Gemma 4 모델은 이미지를 처리할 수 있으므로 과거에 도메인별 모델이 필요했던 많은 최첨단 개발자 사용 사례를 지원합니다.

다음 예시에서는 Gemini API와 함께 Gemma 이미지 입력을 사용하는 방법을 보여줍니다.

Python

from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

my_file = client.files.upload(file="path/to/sample.jpg")

response = client.models.generate_content(
    model="gemma-4-31b-it",
    contents=[my_file, "Caption this image."],
)

print(response.text)

Node.js

import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });

const myfile = await ai.files.upload({
  file: "path/to/sample.jpg",
  config: { mimeType: "image/jpeg" },
});

const response = await ai.models.generateContent({
  model: "gemma-4-31b-it",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
    "Caption this image.",
  ]),
});
console.log(response.text);
 ```

REST

IMAGE_PATH="cats-and-dogs.jpg"
MIME_TYPE=$(file -b --mime-type "${IMAGE_PATH}")
NUM_BYTES=$(wc -c < "${IMAGE_PATH}")
DISPLAY_NAME=IMAGE

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=YOUR_API_KEY" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${IMAGE_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq -r ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemma-4-31b-it:generateContent?key=YOUR_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"file_data":{"mime_type": "'"${MIME_TYPE}"'", "file_uri": "'"${file_uri}"'"}},
          {"text": "Caption this image."}]
        }]
      }' 2> /dev/null > response.json

cat response.json
echo

jq -r ".candidates[].content.parts[].text" response.json

이미지 이해에 대해 자세히 알아보세요.