ITADN
googleapis/nodejs-agentplatform
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈

Gemini Enterprise Agent Platform SDK for Node.js 快速入门

Node.js 的 Agent Platform SDK 允许您使用 Gemini API 构建 AI 驱动的功能和应用程序。同时支持 TypeScript 和 JavaScript。

有关 Agent Platform 上可用 Gemini 模型的最新列表,请参阅 Agent Platform 文档中的 Model information 页面。

开始之前

  1. 确保您的 node.js 版本为 22 或更高。

  2. 选择创建 一个 Google Cloud 项目。

  3. 为您的项目启用计费

  4. 启用 Agent Platform API

  5. 安装 gcloud CLI

  6. 初始化 gcloud CLI

  7. 为您的用户账户创建本地身份验证凭据:

    gcloud auth application-default login

google-auth-library-node.js GitHub 仓库中的 GoogleAuthOptions 接口列出了接受的身份验证选项列表。

安装 SDK

运行以下命令安装 Node.js 的 Agent Platform SDK:

npm install @google-cloud/agentplatform

实例化 Agent Platform 客户端

首先,导入 Client 类:

import { Client } from '@google-cloud/agentplatform';

然后实例化一个客户端:

const client: Client = new Client({
  project: 'my-cloud-project',
  location: 'my-cloud-location',
});

Prompts

首先将你的 prompt 定义为一个 JS 对象或 Prompt 对象。然后调用 createVersion

const prompt = {
  promptData: {
    contents: [{ parts: [{ text: 'Hello, {name}! How are you?' }] }],
    systemInstruction: { parts: [{ text: 'Please answer in a short sentence.' }] },
    variables: [
      { name: { text: 'Alice' } },
    ],
    model: 'gemini-2.5-flash',
  },
};

const promptResource = await client.prompts.createVersion({
  prompt: prompt,
});

请注意,您还可以使用类型化对象来定义您的提示。用于此目的的一些类型(ContentPart)来自 Gen AI SDK(@google/genai)。

import { Prompt } from '@google-cloud/agentplatform';
import { Part, Content } from '@google/genai';

const prompt: Prompt = {
  promptData: {
    contents: [{ parts: [{ text: 'Hello, {name}! How are you?' } as Part] } as Content],
    systemInstruction: { parts: [{ text: 'Please answer in a short sentence.' } as Part] } as Content,
    variables: [
      { name: { text: 'Alice' } as Part },
    ],
    model: 'gemini-2.5-flash',
  },
};

const promptResource = await client.prompts.createVersion({
  prompt: prompt,
});

通过调用 get() 并使用 promptId 来检索提示。

const dataset = (promptResource as any)._dataset;
const promptId = dataset?.name?.split('/').pop() || 'YOUR_PROMPT_ID';

const retrievedPrompt = await client.prompts.get({
  promptId: promptId,
});

在创建或获取提示词后,您可以使用 Gen AI SDK(@google/genai)调用 models.generateContent() 并使用该提示词。

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

// Create a Client in the Gen AI SDK
const genaiClient = new GoogleGenAI({ vertexai: true, project: 'your-project', location: 'your-location' });

// Call generateContent() with the prompt
if (retrievedPrompt.promptData?.contents) {
  const response = await genaiClient.models.generateContent({
    model: retrievedPrompt.promptData.model || 'gemini-2.5-flash',
    contents: retrievedPrompt.promptData.contents,
    config: {
      systemInstruction: retrievedPrompt.promptData.systemInstruction,
      ...(retrievedPrompt.promptData.generationConfig || {}),
    },
  });
  console.log(response.text);
}

许可证

本仓库的内容受 Apache License, version 2.0 许可