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.

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.