Neste guia de início rápido, mostramos como instalar o SDK da IA do Google para sua língua e fazer sua primeira solicitação de API. Os exemplos variam um pouco dependendo se você está usando uma chave de API ou credenciais padrão do aplicativo (ADC) para autenticação.
Escolha o método de autenticação:
Antes de começar
Se você não tiver configurado as credenciais padrão do aplicativo, consulte Configurar as credenciais padrão do aplicativo.
Configurar o ambiente
Python
-
Usando o Python 3.9 ou mais recente, instale o SDK de IA generativa do Google:
pip install -q -U google-genai
-
Defina as variáveis de ambiente:
export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
REST
Defina as variáveis de ambiente:
export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
Faça sua primeira solicitação
Use o método
generateContent
para enviar uma solicitação à API Gemini na Vertex AI:
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" } } }'
Gerar imagens
O Gemini pode gerar e processar imagens em conversas. Você pode solicitar o Gemini com texto, imagens ou uma combinação de ambos para realizar várias tarefas relacionadas a imagens, como geração e edição. O código abaixo demonstra como gerar uma imagem com base em uma solicitação descritiva:
Inclua responseModalities: ["TEXT", "IMAGE"]
na
configuração. Esses modelos não oferecem suporte para saídas somente de imagem.
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"] } }'
Compreensão de imagens
O Gemini também entende imagens. O código a seguir usa a imagem gerada na seção anterior e um modelo diferente para inferir informações sobre a imagem:
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
-
Defina uma variável de shell para a imagem que você está usando:
export B64_BASE_IMAGE=YOUR_B64_ENCODED_IMAGE
-
Execute este comando:
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", } } ] } ] }'
Execução de código
A API Gemini no recurso de execução de código da Vertex AI permite que o modelo gere e execute código Python e aprenda de forma iterativa com os resultados até chegar a uma saída final. A Vertex AI inclui a execução de código como uma ferramenta, semelhante à chamada de função. Use esse recurso para criar aplicativos que usam o raciocínio baseado em código e que produzem saídas de texto. Exemplo:
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." } }, }'
Para conferir mais exemplos de execução de código, consulte a documentação de execução de código.
A seguir
Agora que você fez sua primeira solicitação de API, confira os seguintes guias que mostram como configurar recursos mais avançados da Vertex AI para o código de produção: