|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +# [START generativeaionvertexai_embedding_code_retrieval] |
| 18 | +from vertexai.language_models import TextEmbeddingInput, TextEmbeddingModel |
| 19 | + |
| 20 | +MODEL_NAME = "text-embedding-preview-0815" |
| 21 | +DIMENSIONALITY = 256 |
| 22 | + |
| 23 | + |
| 24 | +def embed_text( |
| 25 | + texts: list[str] = ["Retrieve a function that adds two numbers"], |
| 26 | + task: str = "CODE_RETRIEVAL_QUERY", |
| 27 | + model_name: str = "text-embedding-preview-0815", |
| 28 | + dimensionality: int | None = 256, |
| 29 | +) -> list[list[float]]: |
| 30 | + """Embeds texts with a pre-trained, foundational model.""" |
| 31 | + model = TextEmbeddingModel.from_pretrained(model_name) |
| 32 | + inputs = [TextEmbeddingInput(text, task) for text in texts] |
| 33 | + kwargs = dict(output_dimensionality=dimensionality) if dimensionality else {} |
| 34 | + embeddings = model.get_embeddings(inputs, **kwargs) |
| 35 | + # Example response: |
| 36 | + # [[0.025890009477734566, -0.05553026497364044, 0.006374752148985863,...], |
| 37 | + return [embedding.values for embedding in embeddings] |
| 38 | + |
| 39 | + |
| 40 | +if __name__ == "__main__": |
| 41 | + # Embeds code block with a pre-trained, foundational model. |
| 42 | + # Using this function to calculate the embedding for corpus. |
| 43 | + texts = ["Retrieve a function that adds two numbers"] |
| 44 | + task = "CODE_RETRIEVAL_QUERY" |
| 45 | + code_block_embeddings = embed_text( |
| 46 | + texts=texts, task=task, model_name=MODEL_NAME, dimensionality=DIMENSIONALITY |
| 47 | + ) |
| 48 | + |
| 49 | + # Embeds code retrieval with a pre-trained, foundational model. |
| 50 | + # Using this function to calculate the embedding for query. |
| 51 | + texts = [ |
| 52 | + "def func(a, b): return a + b", |
| 53 | + "def func(a, b): return a - b", |
| 54 | + "def func(a, b): return (a ** 2 + b ** 2) ** 0.5", |
| 55 | + ] |
| 56 | + task = "RETRIEVAL_DOCUMENT" |
| 57 | + code_query_embeddings = embed_text( |
| 58 | + texts=texts, task=task, model_name=MODEL_NAME, dimensionality=DIMENSIONALITY |
| 59 | + ) |
| 60 | + |
| 61 | +# [END generativeaionvertexai_embedding_code_retrieval] |
0 commit comments