Usługa Vertex AI

Usługa Vertex AI umożliwia korzystanie z interfejsu Vertex AI API w Apps Script. Ta interfejs API zapewnia dostęp do Gemini i innych modeli generatywnej AI do generowania tekstu, obrazów i innych treści.

Aby zacząć korzystać z tej zaawansowanej usługi, wypróbuj szybki start.

Wymagania wstępne

Plik referencyjny

Więcej informacji o tej usłudze znajdziesz w dokumentacji interfejsu Vertex AI API. Podobnie jak wszystkie usługi zaawansowane w Apps Script, usługa Vertex AI korzysta z tych samych obiektów, metod i parametrów co publiczny interfejs API.

Przykładowy kod

Poniższy przykładowy kod korzysta z wersji 1 interfejsu Vertex AI API.

Generuj tekst

Ten przykładowy kod pokazuje, jak poprosić model Gemini 2.5 Flash o wygenerowanie tekstu. Funkcja zwraca dane wyjściowe do dziennika wykonania Apps Script.

/**
 * Main entry point to test the Vertex AI integration.
 */
function main() {
  const prompt = 'What is Apps Script in one sentence?';

  try {
    const response = callVertexAI(prompt);
    console.log(`Response: ${response}`);
  } catch (error) {
    console.error(`Failed to call Vertex AI: ${error.message}`);
  }
}

/**
 * Calls the Vertex AI Gemini model.
 *
 * @param {string} prompt - The user's input prompt.
 * @return {string} The text generated by the model.
 */
function callVertexAI(prompt) {
  // Configuration
  const projectId = 'GOOGLE_CLOUD_PROJECT_ID';
  const region = 'us-central1';
  const modelName = 'gemini-2.5-flash';

  const model = `projects/${projectId}/locations/${region}/publishers/google/models/${modelName}`;

  const payload = {
    contents: [{
      role: 'user',
      parts: [{
        text: prompt
      }]
    }],
    generationConfig: {
      temperature: 0.1,
      maxOutputTokens: 2048
    }
  };

  // Execute the request using the Vertex AI Advanced Service
  const response = VertexAI.Endpoints.generateContent(payload, model);

  // Use optional chaining for safe property access
  return response?.candidates?.[0]?.content?.parts?.[0]?.text || 'No response generated.';
}

Zastąp GOOGLE_CLOUD_PROJECT_ID identyfikatorem projektu projektu Cloud.

Generowanie tekstu za pomocą konta usługi

Poniższy przykład pokazuje, jak wygenerować tekst, uwierzytelniając się jako projekt Apps Script za pomocą konta usługi.

/**
 * Main entry point to test the Vertex AI integration.
 */
function main() {
  const prompt = 'What is Apps Script in one sentence?';

  try {
    const response = callVertexAI(prompt);
    console.log(`Response: ${response}`);
  } catch (error) {
    console.error(`Failed to call Vertex AI: ${error.message}`);
  }
}

/**
 * Calls the Vertex AI Gemini model.
 *
 * @param {string} prompt - The user's input prompt.
 * @return {string} The text generated by the model.
 */
function callVertexAI(prompt) {
  const service = getServiceAccountService();

  // Configuration
  const projectId = 'GOOGLE_CLOUD_PROJECT_ID';
  const region = 'us-central1';
  const modelName = 'gemini-2.5-flash';

  const model = `projects/${projectId}/locations/${region}/publishers/google/models/${modelName}`;

  const payload = {
    contents: [{
      role: 'user',
      parts: [{
        text: prompt
      }]
    }],
    generationConfig: {
      temperature: 0.1,
      maxOutputTokens: 2048
    }
  };

  // Execute the request using the Vertex AI Advanced Service
  const response = VertexAI.Endpoints.generateContent(
    payload,
    model,
    {},
    // Authenticate with the service account token.
    { Authorization: `Bearer ${service.getAccessToken()}` },
  );

  // Use optional chaining for safe property access
  return response?.candidates?.[0]?.content?.parts?.[0]?.text || 'No response generated.';
}

/**
 * Get a new OAuth2 service for a given service account.
 */
function getServiceAccountService() {
  const serviceAccountKeyString = PropertiesService.getScriptProperties().getProperty('SERVICE_ACCOUNT_KEY');

  if (!serviceAccountKeyString) {
    throw new Error('SERVICE_ACCOUNT_KEY property is not set. Please follow the setup instructions.');
  }

  const serviceAccountKey = JSON.parse(serviceAccountKeyString);

  const CLIENT_EMAIL = serviceAccountKey.client_email;
  const PRIVATE_KEY = serviceAccountKey.private_key;
  const SCOPES = ['https://www.googleapis.com/auth/cloud-platform'];

  return OAuth2.createService('ServiceAccount')
      .setTokenUrl('https://oauth2.googleapis.com/token')
      .setPrivateKey(PRIVATE_KEY)
      .setIssuer(CLIENT_EMAIL)
      .setPropertyStore(PropertiesService.getScriptProperties())
      .setScope(SCOPES);
}