|
| 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 | +import os |
| 16 | + |
| 17 | +from vertexai.generative_models import GenerationResponse |
| 18 | + |
| 19 | +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") |
| 20 | + |
| 21 | + |
| 22 | +def generate_content_with_rag( |
| 23 | + corpus_name: str, |
| 24 | +) -> GenerationResponse: |
| 25 | + # [START generativeaionvertexai_rag_generate_content] |
| 26 | + |
| 27 | + from vertexai.preview import rag |
| 28 | + from vertexai.preview.generative_models import GenerativeModel, Tool |
| 29 | + import vertexai |
| 30 | + |
| 31 | + # TODO(developer): Update and un-comment below lines |
| 32 | + # PROJECT_ID = "your-project-id" |
| 33 | + # corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}" |
| 34 | + |
| 35 | + # Initialize Vertex AI API once per session |
| 36 | + vertexai.init(project=PROJECT_ID, location="us-central1") |
| 37 | + |
| 38 | + rag_retrieval_tool = Tool.from_retrieval( |
| 39 | + retrieval=rag.Retrieval( |
| 40 | + source=rag.VertexRagStore( |
| 41 | + rag_resources=[ |
| 42 | + rag.RagResource( |
| 43 | + rag_corpus=corpus_name, |
| 44 | + # Optional: supply IDs from `rag.list_files()`. |
| 45 | + # rag_file_ids=["rag-file-1", "rag-file-2", ...], |
| 46 | + ) |
| 47 | + ], |
| 48 | + similarity_top_k=3, # Optional |
| 49 | + vector_distance_threshold=0.5, # Optional |
| 50 | + ), |
| 51 | + ) |
| 52 | + ) |
| 53 | + |
| 54 | + rag_model = GenerativeModel( |
| 55 | + model_name="gemini-1.5-flash-001", tools=[rag_retrieval_tool] |
| 56 | + ) |
| 57 | + response = rag_model.generate_content("Why is the sky blue?") |
| 58 | + print(response.text) |
| 59 | + # Example response: |
| 60 | + # The sky appears blue due to a phenomenon called Rayleigh scattering. |
| 61 | + # Sunlight, which contains all colors of the rainbow, is scattered |
| 62 | + # by the tiny particles in the Earth's atmosphere.... |
| 63 | + # ... |
| 64 | + |
| 65 | + # [END generativeaionvertexai_rag_generate_content] |
| 66 | + |
| 67 | + return response |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + generate_content_with_rag( |
| 72 | + "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}" |
| 73 | + ) |
0 commit comments