Agent Platform SDK for Node.js

repository·main·Indexed 41 days ago

https://github.com/googleapis/nodejs-agentplatform

Vertex Generative AI client for Node.js (version 0.11.0) that allows developers to build AI-powered applications by managing and versioning prompts via the Gemini API on Google Cloud's Agent Platform. The SDK provides tools for managing skills, prompts, and sandboxed environments, and integrates with the @google-cloud/vertexai package for generative model capabilities, including function calling, grounding with Google Search, and token counting.

Tokens
17.4K
Snippets
65
Records
85
Agent score
50%

What's inside Agent Platform

  1. Use Grounding with Google Search or Vertex AI Search (Preview)

    main

    Grounding is a preview feature that connects model output to verifiable sources to reduce hallucinations. You can access these features via the vertexAI.preview namespace.

    Google Search Grounding

    Pass a googleSearchRetrieval tool to the generateContent method to enable Google Search grounding.

    Vertex AI Search Grounding

    Pass a retrieval tool containing a vertexAiSearch configuration with your specific datastore path to enable grounding against your own data stores.

    // Google Search Grounding
    const googleSearchRetrievalTool = {
      googleSearchRetrieval: {
        disableAttribution: false,
      },
    };
    const result = await generativeModelPreview.generateContent({
      contents: [{role: 'user', parts: [{text: 'Why is the sky blue?'}]}],
      tools: [googleSearchRetrievalTool],
    });
    
    // Vertex AI Search Grounding
    const vertexAIRetrievalTool = {
      retrieval: {
        vertexAiSearch: {
          datastore: 'projects/.../locations/.../collections/.../dataStores/...',
        },
        disableAttribution: false,
      },
    };
    const result = await generativeModelPreview.generateContent({
      contents: [{role: 'user', parts: [{text: 'Why is the sky blue?'}]}],
      tools: [vertexAIRetrievalTool],
    });
  2. Prerequisites for using the Agent Platform SDK

    main

    Before using the SDK, ensure you meet the following requirements:

    1. Node.js: Version 22 or above.
    2. Google Cloud Project: A selected or newly created project with billing enabled.
    3. API: The Agent Platform API (aiplatform.googleapis.com) must be enabled.
    4. Authentication:
      • Install and initialize the gcloud CLI.
      • Create local application default credentials by running:
      gcloud auth application-default login
  3. Configure custom authentication for VertexAI

    main

    If you need to specify custom authentication options instead of using the default environment-based authentication, pass a googleAuthOptions object when instantiating the VertexAI class. The options should follow the GoogleAuthOptions interface from the google-auth-library.

    const { VertexAI } = require('@google-cloud/vertexai');
    const { GoogleAuthOptions } = require('google-auth-library');
    
    const vertexAI = new VertexAI({
      googleAuthOptions: {
        // your GoogleAuthOptions interface
      }
    });
  4. Implement Function Calling with Vertex AI

    main

    The Vertex AI SDK supports function calling via sendMessage, sendMessageStream, generateContent, and generateContentStream. You can implement this using a chat session (recommended) or by providing a full conversation history in a single request.

    To use function calling, you must:

    1. Declare the function: Define the function's name, description, and parameters using FunctionDeclarationSchemaType.
    2. Pass tools to the model: Include the declarations in the tools parameter of your request or chat session.
    3. Handle the response: When the model returns a functionCall, execute your local logic and send the result back to the model using a functionResponse part.
    const functionDeclarations = [
      {
        functionDeclarations: [
          {
            name: "get_current_weather",
            description: 'get weather in a given location',
            parameters: {
              type: FunctionDeclarationSchemaType.OBJECT,
              properties: {
                location: {type: FunctionDeclarationSchemaType.STRING},
                unit: {
                  type: FunctionDeclarationSchemaType.STRING,
                  enum: ['celsius', 'fahrenheit'],
                },
              },
              required: ['location'],
            },
          },
        ],
      },
    ];
    
    // Example of sending a follow-up with the function result
    const functionResponseParts = [
      {
        functionResponse: {
          name: "get_current_weather",
          response: {name: "get_current_weather", content: {weather: "super nice"}},
        },
      },
    ];
    
    // Using sendMessageStream in a chat session
    const chat = generativeModel.startChat({
      tools: functionDeclarations,
    });
    const streamingResult = await chat.sendMessageStream('What is the weather in Boston?');
    // ... process stream ...
    await chat.sendMessageStream(functionResponseParts);
    // ... process second stream ...
  5. Include System Instructions

    main

    System instructions provide additional context or persona to the model. You can include them in two ways:

    1. During Model Instantiation: Set the systemInstruction property when calling getGenerativeModel. This applies to all requests made with that model instance.
    2. Per Request: Include the systemInstruction object in the request payload passed to generateContent.
    // During instantiation
    const generativeModel = vertexAI.getGenerativeModel({
        model: textModel,
        systemInstruction: {
          role: 'system',
          parts: [{"text": `For example, you are a helpful customer service agent.`}]
        },
    });
    
    // In a specific request
    const request = {
      contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}],
      systemInstruction: { role: 'system', parts: [{ text: `For example, you are a helpful customer service agent.` }] },
    };
    const result = await generativeModel.generateContent(request);
  6. Access Sessions and Sandboxes via AgentEngines

    main

    The AgentEngines class acts as a container for two main functional sub-modules:

    1. sessions: An instance of the Sessions class used to manage agent interaction sessions.
    2. sandboxes: An instance of the Sandboxes class used to manage sandboxed environments.

    When using sandboxes, if an agent engine name is not explicitly provided, the SDK automatically attempts to resolve or create a shared "default" agent engine named default-agent-platform-sandbox-host to optimize resource reuse.

  7. How to instantiate a GenerativeModel

    main

    The GenerativeModel class should not be instantiated directly. Instead, use the vertexai.getGenerativeModel() method. The model is configured using GetGenerativeModelParams, which includes:

    • model: The model ID (e.g., gemini-1.0-pro) or a full resource name.
    • project: Your Google Cloud project ID.
    • location: The Vertex AI location (e.g., us-central1).
    • generationConfig: Configuration for generation parameters.
    • safetySettings: Safety filter settings.
    • tools: Tools for function calling.
    • systemInstruction: Instructions to guide the model's behavior.
  8. Use preview features via the preview namespace

    main

    For generative AI features that are currently in Preview, use the preview property on your VertexAI instance. The preview namespace provides access to VertexAIPreview methods.

    Key methods in preview:

    • getGenerativeModel(modelParams: ModelParams, requestOptions?: RequestOptions): Returns a GenerativeModelPreview instance.
    • getGenerativeModelFromCachedContent(cachedContent: CachedContent, modelParams?: Partial<ModelParams>, requestOptions?: RequestOptions): Returns a GenerativeModelPreview instance configured to use a specific CachedContent resource. This is useful for reducing latency and costs when using large contexts.
    const vertexAI = new VertexAI({project: 'my-project', location: 'us-central1'});
    
    // Accessing preview models
    const generativeModelPreview = vertexAI.preview.getGenerativeModel({
      model: 'gemini-1.0-pro',
    });
  9. Constraints on sendMessage request parts

    main

    When using sendMessage or sendMessageStream, the request can be a string or an array of string | Part. However, there is a strict constraint regarding FunctionResponsePart:

    You cannot mix FunctionResponsePart with other part types (like TextPart) within a single message request.

    If you attempt to send a message containing both a function response and other content types, the SDK will throw a ClientError with the message: "Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message."