API Vertex AI Gemini

При разработке генеративных ИИ-решений с помощью Gemini разработчики выбирают между Gemini Developer API и Vertex AI Gemini API .

Gemini Developer API обеспечивает простой способ создания, производства и масштабирования приложений Gemini. Vertex AI предлагает комплексную экосистему корпоративных функций и сервисов для создания и развертывания приложений генеративного ИИ, поддерживаемых Google Cloud Platform.

Хотя лучший выбор зависит от ваших потребностей, мы недавно упростили переключение между этими сервисами. Gemini Developer API и Vertex AI Gemini API теперь доступны через унифицированный Google Gen AI SDK , что обеспечивает большую гибкость.

Сравнение кодов

Ниже приведены некоторые сравнительные примеры кода Gemini Developer API и Vertex AI для быстрого запуска генерации текста.

Питон

Вы можете получить доступ к Gemini Developer API и Vertex AI через библиотеку google-genai . Инструкции по установке библиотеки см. на странице библиотек .

from google import genai

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

response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Explain how AI works in a few words"
)
print(response.text)
from google import genai

client = genai.Client(
    vertexai=True, project='your-project-id', location='us-central1'
)

response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Explain how AI works in a few words"
)
print(response.text)

JavaScript и TypeScript

Вы можете получить доступ к Gemini Developer API и Vertex AI через библиотеку @google/genai . Инструкции по установке библиотеки см. на странице библиотек .

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

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

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: "Explain how AI works in a few words",
  });
  console.log(response.text);
}

main();
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({
  vertexai: true,
  project: 'your_project',
  location: 'your_location',
});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: "Explain how AI works in a few words",
  });
  console.log(response.text);
}

main();

Идти

Вы можете получить доступ к Gemini Developer API и Vertex AI через библиотеку google.golang.org/genai . Инструкции по установке библиотеки см. на странице библиотек .

import (
  "context"
  "encoding/json"
  "fmt"
  "log"
  "google.golang.org/genai"
)

// Your Google API key
const apiKey = "your-api-key"

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, &genai.ClientConfig{
    APIKey:  apiKey,
    Backend: genai.BackendGeminiAPI,
  })

  // Call the GenerateContent method.
  result, err := client.Models.GenerateContent(ctx, "gemini-2.0-flash", genai.Text("Tell me about New York?"), nil)

}
import (
  "context"
  "encoding/json"
  "fmt"
  "log"
  "google.golang.org/genai"
)

// Your GCP project
const project = "your-project"

// A GCP location like "us-central1"
const location = "some-gcp-location"

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, &genai.ClientConfig
  {
        Project:  project,
      Location: location,
      Backend:  genai.BackendVertexAI,
  })

  // Call the GenerateContent method.
  result, err := client.Models.GenerateContent(ctx, "gemini-2.0-flash", genai.Text("Tell me about New York?"), nil)

}

Другие варианты использования и платформы

Для других платформ и вариантов использования обратитесь к руководствам по конкретным вариантам использования в документации API разработчика Gemini и документации Vertex AI .

Вопросы миграции

При миграции:

Если вам больше не нужно использовать ключ Gemini API для Gemini Developer API, следуйте рекомендациям по безопасности и удалите его.

Чтобы удалить ключ API:

  1. Откройте страницу учетных данных Google Cloud API .

  2. Найдите ключ API, который вы хотите удалить, и нажмите значок « Действия» .

  3. Выберите Удалить ключ API .

  4. В модальном окне «Удалить учетные данные» выберите «Удалить» .

    Удаление ключа API занимает несколько минут для распространения. После завершения распространения любой трафик, использующий удаленный ключ API, отклоняется.

Следующие шаги