이 빠른 시작에서는 원하는 언어로 Google Gen AI SDK를 설치한 후 첫 번째 API 요청을 실행하는 방법을 보여줍니다. 샘플은 인증에 API 키를 사용하는지 또는 애플리케이션 기본 사용자 인증 정보(ADC)를 사용하는지에 따라 약간 다릅니다.
인증 방법 선택하기
시작하기 전에
애플리케이션 기본 사용자 인증 정보를 설정하지 않은 경우 애플리케이션 기본 사용자 인증 정보 구성을 참조하세요.
환경 설정
Python
-
Python 3.9 이상을 사용하여 Google Gen AI SDK 설치:
pip install -q -U google-genai
-
환경 변수를 설정합니다.
export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
REST
환경 변수를 설정합니다.
export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
첫 번째 요청하기
generateContent
메서드를 사용하여 Vertex AI의 Gemini API에 요청을 보냅니다.
Python
from google import genai client = genai.Client(vertexai=True, project="${GOOGLE_CLOUD_PROJECT}", location="global") response = client.models.generate_content( model="gemini-2.0-flash", contents="Explain how AI works in a few words" ) print(response.text)
REST
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://aiplatform.googleapis.com/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/global/publishers/google/models/gemini-2.0-flash-001:generateContent -d \ $'{ "contents": { "role": "user", "parts": { "text": "Explain how AI works in a few words" } } }'
이미지 생성
Gemini는 대화 방식으로 이미지를 생성하고 처리할 수 있습니다. 텍스트, 이미지 또는 둘 다를 조합해 Gemini에 프롬프트를 제공하여 이미지 생성 및 수정과 같은 다양한 이미지 관련 작업을 실행할 수 있습니다. 다음 코드는 설명 프롬프트를 기반으로 이미지를 생성하는 방법을 보여줍니다.
구성에 responseModalities: ["TEXT", "IMAGE"]
를 포함해야 합니다. 이러한 모델에서는 이미지 전용 출력이 지원되지 않습니다.
Python
from google import genai from google.genai import types from PIL import Image from io import BytesIO import base64 client = genai.Client(vertexai=True, project="${GOOGLE_CLOUD_PROJECT}", location="global") contents = ('Hi, can you create an image of the Eiffel tower with fireworks in the background?') response = client.models.generate_content( model="gemini-2.0-flash-preview-image-generation", contents=contents, config=types.GenerateContentConfig( response_modalities=['TEXT', 'IMAGE'] ) ) for part in response.candidates[0].content.parts: if part.text is not None: print(part.text) elif part.inline_data is not None: image = Image.open(BytesIO((part.inline_data.data))) image.save('gemini-native-image.png') image.show()
REST
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://aiplatform.googleapis.com/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/global/publishers/google/models/gemini-2.0-flash-preview-image-generation:generateContent -d \ $'{ "contents": { "role": "user", "parts": { "text": "Can you create an image of the Eiffel tower with fireworks in the background?" } }, "generationConfig": { "responseModalities":["TEXT","IMAGE"] } }'
이미지 이해
Gemini는 이미지도 이해할 수 있습니다. 다음 코드는 이전 섹션에서 생성된 이미지를 사용하고 다른 모델을 사용하여 이미지에 관한 정보를 추론합니다.
Python
from google import genai from google.genai import types with open("gemini-native-image.png", "rb") as f: image = f.read() client = genai.Client(vertexai=True, project="${GOOGLE_CLOUD_PROJECT}", location="global") response = client.models.generate_content( model="gemini-flash-2.0", contents=[ Part.from_bytes(data=image, mime_type="image/png"), "Write a short and engaging blog post based on this picture.", ], ) print(response.text) ''' Okay, here's a short and engaging blog post inspired by the image: **Paris Aglow: A Night to Remember!** WOW! Just look at this image. Fireworks exploding over Paris, the Eiffel Tower brilliantly lit – can you imagine a more magical sight? This is Paris at its most dazzling, a city transformed into a canvas of light and color. The Eiffel Tower, the iconic symbol of Paris, stands proud amidst the spectacle. It's illuminated in blue, adding to the magical atmosphere of the celebrations. Whether it's a special occasion, a national holiday, or just a spontaneous celebration of life, Paris knows how to put on a show. This image is a reminder of the city's enduring beauty and its power to inspire awe. Have you ever witnessed the magic of Paris? Let me know in the comments! '''
REST
-
사용 중인 이미지의 셸 변수를 설정합니다.
export B64_BASE_IMAGE=YOUR_B64_ENCODED_IMAGE
-
다음 명령어를 실행합니다.
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://aiplatform.googleapis.com/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/global/publishers/google/models/gemini-2.0-flash:generateContent -d \ $'{ "contents": [ { "role": "user", "parts": [ {"text": "Write a short and engaging blog post based on this picture."}, {"inlineData": { "data": "${B64_BASE_IMAGE}", "mimeType": "image/png", } } ] } ] }'
코드 실행
Vertex AI 코드 실행 기능의 Gemini API를 사용하면 모델이 Python 코드를 생성 및 실행하고 최종 출력을 도출할 때까지 결과를 반복적으로 학습할 수 있습니다. Vertex AI는 함수 호출과 유사하게 도구로서 코드 실행을 제공합니다. 이 코드 실행 기능을 사용하면 코드 기반 추론의 이점을 활용하며 텍스트 출력을 생성하는 애플리케이션을 빌드할 수 있습니다. 예를 들면 다음과 같습니다.
Python
from google import genai from google.genai import types client = genai.Client(vertexai=True, project="${GOOGLE_CLOUD_PROJECT}", location="global") response = client.models.generate_content( model="gemini-2.0-flash", contents="What is the sum of the first 50 prime numbers? " "Generate and run code for the calculation, and make sure you get all 50.", config=types.GenerateContentConfig( tools=[types.Tool(code_execution=types.ToolCodeExecution)] ), ) for part in response.candidates[0].content.parts: if part.text is not None: print(part.text) if part.executable_code is not None: print(part.executable_code.code) if part.code_execution_result is not None: print(part.code_execution_result.output)
REST
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://us-central1-aiplatform.googleapis.com/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/us-central1/publishers/google/models/gemini-2.0-flash-001:generateContent -d \ $'{ "tools": [{'codeExecution': {}}], "contents": { "role": "user", "parts": { "text": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50." } }, }'
코드 실행의 더 많은 예시는 코드 실행 문서를 참조하세요.
다음 단계
이제 첫 번째 API 요청을 실행했으므로 프로덕션 코드에 더 고급 Vertex AI 기능을 설정하는 방법을 보여주는 다음 가이드를 살펴보세요.