const endTime = Date.now();
console.log(Total process completed in ${(endTime - startTime) / 1000} seconds);
}
main().catch(console.error);
documentation of embeddings:
Generative AI on Vertex AI
Documentation
API reference
Was this helpful?
Send feedbackText embeddings API
bookmark_border
The Text embeddings API converts textual data into numerical vectors. These vector representations are designed to capture the semantic meaning and context of the words they represent.
Each instance represents a single piece of text to be embedded.
TextEmbeddingInput
string
The text that you want to generate embeddings for.
auto_truncate
Optional: bool
When set to true, input text will be truncated. When set to false, an error is returned if the input text is longer than the maximum length supported by the model. Defaults to true.
output_dimensionality
Optional: int
Used to specify output embedding size. If set, output embeddings will be truncated to the size specified.
Request body
{
"instances": [
{
"task_type": "RETRIEVAL_DOCUMENT",
"title": "document title",
"content": "I would like embeddings for this text!"
},
]
}
Parameters
content
string
The text that you want to generate embeddings for.
task_type
Optional: string
Used to convey intended downstream application to help the model produce better embeddings. If left blank, the default used is RETRIEVAL_QUERY.
RETRIEVAL_QUERY
RETRIEVAL_DOCUMENT
SEMANTIC_SIMILARITY
CLASSIFICATION
CLUSTERING
QUESTION_ANSWERING
FACT_VERIFICATION
CODE_RETRIEVAL_QUERY
The task_type parameter is not supported for the textembedding-gecko@001 model.
For more information about task types, see Choose an embeddings task type.
title
Optional: string
Used to help the model produce better embeddings. Only valid with task_type=RETRIEVAL_DOCUMENT.
taskType
The following table describes the task_type parameter values and their use cases:
task_type Description
RETRIEVAL_QUERY Specifies the given text is a query in a search or retrieval setting.
RETRIEVAL_DOCUMENT Specifies the given text is a document in a search or retrieval setting.
SEMANTIC_SIMILARITY Specifies the given text is used for Semantic Textual Similarity (STS).
CLASSIFICATION Specifies that the embedding is used for classification.
CLUSTERING Specifies that the embedding is used for clustering.
QUESTION_ANSWERING Specifies that the query embedding is used for answering questions. Use RETRIEVAL_DOCUMENT for the document side.
FACT_VERIFICATION Specifies that the query embedding is used for fact verification.
CODE_RETRIEVAL_QUERY Specifies that the query embedding is used for code retrieval for Java and Python.
Retrieval Tasks:
Query: Use task_type=RETRIEVAL_QUERY to indicate that the input text is a search query. Corpus: Use task_type=RETRIEVAL_DOCUMENT to indicate that the input text is part of the document collection being searched.
Similarity Tasks:
Semantic similarity: Use task_type= SEMANTIC_SIMILARITY for both input texts to assess their overall meaning similarity.
Response body
{
"predictions": [
{
"embeddings": {
"statistics": {
"truncated": boolean,
"token_count": integer
},
"values": [ number ]
}
}
]
}
Response element Description
embeddings The result generated from input text.
statistics The statistics computed from the input text.
truncated Indicates if the input text was longer than max allowed tokens and truncated.
tokenCount Number of tokens of the input text.
values The values field contains the embedding vectors corresponding to the words in the input text.
Sample response
{
"predictions": [
{
"embeddings": {
"values": [
0.0058424929156899452,
0.011848051100969315,
0.032247550785541534,
-0.031829461455345154,
-0.055369812995195389,
...
],
"statistics": {
"token_count": 4,
"truncated": false
}
}
}
]
}
Examples
Embed a text string
Basic use case
The following example shows how to obtain the embedding of a text string.
REST
Python
Go
Java
Node.js
Before trying this sample, follow the Node.js setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI Node.js API reference documentation.
To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
callPredict();
}
Advanced Use Case
The following example demonstrates some advanced features
Use task_type and title to improve embedding quality.
Use parameters to control the behavior of the API.
Note: Feature support varies by model version. For example, task_type and title fields are not supported by textembedding-gecko@001. For best results, choose the latest available version.
REST
Python
Go
Java
Node.js
Before trying this sample, follow the Node.js setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI Node.js API reference documentation.
To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
Given the script above and the documentation for the embeddings used, write a node.js script that is going to go over each pain point of all demographs, save it and embed it. The goal is to group the most similar pain points to have a general sense of the most common pain points in general. Also make sure that the results are vizualized in an intuitive way
Certainly! Below is a Node.js script that processes pain points for all demographics, embeds them using the Google Vertex AI Text Embeddings API, clusters the embeddings to group similar pain points, and visualizes the clusters in an intuitive way.
Prerequisites:
Google Cloud Project: You need a Google Cloud project with the Vertex AI API enabled.
Authentication: Set up Application Default Credentials by running gcloud auth application-default login and ensure you have the necessary permissions.
Necessary Packages: Install the required Node.js packages using npm:
In the script, replace 'YOUR_PROJECT_ID' with your actual Google Cloud project ID:
const project = 'YOUR_PROJECT_ID'; // Replace with your project ID
Set Up Authentication:
Ensure you have set up the Google Cloud authentication credentials. You can do this by running:
gcloud auth application-default login
Prepare the Data File:
Ensure you have a pain_points_results.json file in the same directory as the script. The file should contain the pain points data structured per demographic and environment.
Clusters Visualization: Open the pain_points_clusters.html file in a web browser to view the scatter plot of clustered pain points.
Clustered Data: The clustered pain points with their assigned cluster IDs are saved in clustered_pain_points.json.
Explanation of the Script:
Data Loading (loadPainPoints): Reads the pain_points_results.json file and flattens the pain points into an array of objects, each containing the demographic, environment, and pain point text.
Generating Embeddings (getEmbeddings): Uses the Google Vertex AI Text Embeddings API to generate embeddings for the pain points. It processes the pain points in batches to comply with API limits.
Clustering (clusterEmbeddings): Applies k-means clustering to the embeddings to group similar pain points together.
Dimensionality Reduction (reduceDimensions): Reduces the high-dimensional embeddings to two dimensions using PCA for visualization purposes.
Visualization (visualizeClusters): Generates an HTML file (pain_points_clusters.html) that visualizes the clusters using Plotly.js. Each cluster is represented with a different color in the scatter plot.
Saving Results: Saves the clustered pain points with their cluster assignments to clustered_pain_points.json.
Notes:
Adjust Batch Size: You may need to adjust the batchSize variable in the getEmbeddings function based on the API's rate limits and payload size constraints.
API Limits and Error Handling: The script includes basic error handling for API requests. You can enhance it by implementing retry logic or more sophisticated error handling as needed.
Visualization Customization: The visualizeClusters function generates a basic scatter plot. You can customize the layout and styling of the plot by modifying the layout object and Plotly configuration.
Dependencies: This script uses @google-cloud/aiplatform for interacting with the Vertex AI API, ml-kmeans for clustering, and ml-pca for dimensionality reduction.
Example Output:
After running the script, you should see output similar to:
Open the pain_points_clusters.html file in your web browser to explore the clusters. Each point represents a pain point, and points in the same cluster are displayed in the same color.
Feel free to adjust the number of clusters in the clusterEmbeddings function or enhance the visualization as needed for your specific use case.
If you have any questions or need further assistance, please let me know!