שימוש במסד נתונים של Weaviate עם RAG Engine

בדף הזה מוסבר איך לקשר את מאגר המידע של RAG Engine למסד הנתונים של Weaviate.

אפשר גם לעקוב באמצעות ה-notebook הזה RAG Engine with Weaviate.

אתם יכולים להשתמש במופע של מסד הנתונים Weaviate, שהוא מסד נתונים בקוד פתוח, עם RAG Engine כדי ליצור אינדקס ולבצע חיפוש דמיון מבוסס-וקטורים. חיפוש דמיון הוא דרך למצוא קטעי טקסט שדומים לטקסט שמחפשים, ונדרש שימוש במודל הטמעה. מודל ההטמעה יוצר נתוני וקטור לכל קטע טקסט שמושווה. חיפוש הדמיון משמש לאחזור הקשרים סמנטיים להארקה כדי להחזיר את התוכן המדויק ביותר מ-LLM.

בעזרת RAG Engine, אתם יכולים להמשיך להשתמש במופע של מסד נתונים וקטורי בניהול מלא, שאתם אחראים להקצאת המשאבים שלו. מנוע RAG משתמש במסד הנתונים הווקטורי לאחסון, לניהול אינדקס ולחיפוש.

לתשומת ליבכם

לפני שמשתמשים במסד הנתונים של Weaviate, כדאי לבצע את השלבים הבאים:

  1. צריך ליצור, להגדיר ולפרוס את מופע מסד הנתונים ואת האוסף של Weaviate. פועלים לפי ההוראות במאמר יצירת אוסף Weaviate כדי להגדיר אוסף על סמך הסכימה.
  2. צריך לספק מפתח Weaviate API, שמאפשר ל-RAG Engine ליצור אינטראקציה עם מסד הנתונים של Weaviate. ‫RAG Engine תומך במפתחות API מבוססי AuthN ו-AuthZ, שמתחברים למסד הנתונים של Weaviate ותומכים בחיבור HTTPS.
  3. מנוע RAG לא מאחסן את מפתח ה-API של Weaviate ולא מנהל אותו. במקום זאת, צריך לבצע את הפעולות הבאות:
    1. מאחסנים את המפתח ב-Secret Manager. Google Cloud
    2. מעניקים לחשבון השירות של הפרויקט הרשאות גישה לסוד.
    3. נותנים למנוע RAG גישה לשם המשאב של הסוד.
    4. כשאתם מבצעים אינטראקציה עם מסד הנתונים של Weaviate, מנוע RAG ניגש למשאב הסודי באמצעות חשבון השירות שלכם.
  4. יש מיפוי של אחד לאחד בין קורפוס מנוע ה-RAG לבין אוסף Weaviate. קבצי RAG מאוחסנים באוסף של מסד נתונים Weaviate. כשמתבצעת קריאה ל-CreateRagCorpus API או ל-UpdateRagCorpus API, מאגר המידע של RAG משויך לאוסף מסדי הנתונים.
  5. בנוסף לחיפושים סמנטיים מבוססי-הטמעה צפופה, מנוע ה-RAG תומך גם בחיפוש היברידי דרך מסד נתונים של Weaviate. אפשר גם לשנות את המשקל בין דמיון וקטורי צפוף לדליל בחיפוש היברידי.

הקצאת מסד הנתונים של Weaviate

לפני שמשתמשים במסד הנתונים Weaviate עם RAG Engine, צריך לבצע את הפעולות הבאות:

  1. מגדירים ופורסים את מופע מסד הנתונים של Weaviate.
  2. מכינים את נקודת הקצה מסוג HTTPS.
  3. יוצרים את האוסף ב-Weaviate.
  4. משתמשים במפתח ה-API כדי להקצות את Weaviate באמצעות AuthN ו-AuthZ.
  5. מקצים את חשבון השירות של RAG Engine.

הגדרה ופריסה של מופע מסד הנתונים של Weaviate

צריך לפעול לפי ההוראות שבמדריך למתחילים של Weaviate. אבל אתם יכולים להשתמש בGoogle Cloud מדריך Marketplace, שהוא אופציונלי.

אתם יכולים להגדיר את מופע Weaviate בכל מקום, כל עוד נקודת הקצה של Weaviate נגישה להגדרה ולפריסה בפרויקט. לאחר מכן תוכלו לנהל באופן מלא את המכונה של מסד הנתונים Weaviate.

מכיוון ש-RAG Engine לא מעורב בשום שלב במחזור החיים של מופע מסד הנתונים של Weaviate, אתם אחראים להעניק הרשאות ל-RAG Engine כדי שהוא יוכל לאחסן נתונים במסד הנתונים של Weaviate ולחפש בהם. באחריותכם גם לוודא שמנוע RAG יכול להשתמש בנתונים במסד הנתונים. לדוגמה, אם תשנו את הנתונים, RAG Engine לא יהיה אחראי להתנהגויות לא צפויות כתוצאה מהשינויים האלה.

הכנת נקודת הקצה של HTTPS

במהלך הקצאת Weaviate, חשוב לוודא שיוצרים נקודת קצה של HTTPS. אומנם יש תמיכה בחיבורי HTTP, אבל אנחנו מעדיפים שהתנועה של RAG Engine ומסד הנתונים של Weaviate תשתמש בחיבור HTTPS.

יצירת אוסף Weaviate

מכיוון שיש מיפוי של אחד לאחד בין קורפוס RAG Engine לבין אוסף Weaviate, צריך ליצור אוסף במסד הנתונים של Weaviate לפני שמקשרים את האוסף לקורפוס RAG Engine. השיוך החד-פעמי הזה מתבצע כששולחים קריאה ל-API‏ CreateRagCorpus או ל-API‏ UpdateRagCorpus.

כשיוצרים אוסף ב-Weaviate, צריך להשתמש בסכימה הבאה:

שם המאפיין סוג נתונים
fileId text
corpusId text
chunkId text
chunkDataType text
chunkData text
fileOriginalUri text

משתמשים במפתח ה-API כדי להקצות את Weaviate באמצעות AuthN ו-AuthZ

הקצאת מפתח Weaviate API כוללת את השלבים הבאים:

  1. יוצרים את מפתח ה-API של Weaviate.
  2. מגדירים את Weaviate באמצעות מפתח ה-API של Weaviate.
  3. מאחסנים את מפתח ה-API של Weaviate ב-Secret Manager.

יצירת מפתח API

מנוע RAG יכול להתחבר למופעים של מסד הנתונים שלכם ב-Weaviate רק באמצעות מפתח ה-API שלכם לצורך אימות והרשאה. כדי להגדיר אימות מבוסס מפתח API במופע של מסד הנתונים Weaviate, צריך לפעול לפי המדריך הרשמי של Weaviate לאימות.

אם כדי ליצור את מפתח Weaviate API נדרש מידע על זהות שמשויך ל-RAG Engine, צריך ליצור את הקורפוס הראשון ולהשתמש בחשבון השירות של RAG Engine כזהות.

אחסון מפתח ה-API ב-Secret Manager

מפתח API מכיל פרטים אישיים מזהים רגישים (SPII), שחלים עליהם דרישות משפטיות. אם נתוני ה-SPII ייחשפו או שגורמים לא רצויים יקבלו גישה אליהם או יעשו בהם שימוש לרעה, אותו אדם עלול להיפגע או שעלול להיגרם לו נזק. כדי לצמצם את הסיכונים לאדם פרטי בזמן השימוש ב-RAG Engine, אל תשמרו את מפתח ה-API ואל תנהלו אותו, והימנעו משיתוף של מפתח ה-API הלא מוצפן.

כדי להגן על נתוני SPII, צריך:

  1. מאחסנים את מפתח ה-API ב-Secret Manager.
  2. נותנים לחשבון השירות של RAG Engine את ההרשאות לסודות שלכם, ומנהלים את בקרת הגישה ברמת משאב הסוד.
    1. עוברים אל ההרשאות של הפרויקט.
    2. מפעילים את האפשרות Include Google-provided role grants (הכללת תפקידים שניתנו על ידי Google).
    3. מוצאים את חשבון השירות, שמופיע בפורמט

      service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com

    4. עורכים את חשבונות המשתמשים של חשבון השירות.
    5. מוסיפים לחשבון השירות את התפקיד Secret Manager Secret Accessor.
  3. במהלך היצירה או העדכון של קורפוס ה-RAG, מעבירים את שם משאב הסוד למנוע ה-RAG ומאחסנים את שם משאב הסוד.

כששולחים בקשות API למופעים של מסד הנתונים Weaviate, מנוע ה-RAG משתמש בכל חשבון שירות כדי לקרוא את מפתח ה-API שמתאים למשאבים הסודיים ב-Secret Manager מהפרויקטים.

הקצאת חשבון השירות של RAG Engine

כשיוצרים את המשאב הראשון בפרויקט, RAG Engine יוצר חשבון שירות ייעודי. אפשר למצוא את חשבון השירות בדף IAM של הפרויקט. חשבון השירות הוא בפורמט הבא:

service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com

לדוגמה, service-123456789@gcp-sa-vertex-rag.iam.gserviceaccount.com.

כשמשלבים עם מסד הנתונים של Weaviate, חשבון השירות משמש בתרחישים הבאים:

  • אתם יכולים להשתמש בחשבון השירות כדי ליצור את מפתח ה-API של Weaviate לצורך אימות. במקרים מסוימים, כדי ליצור מפתח API לא נדרש מידע על המשתמש, ולכן לא צריך חשבון שירות כדי ליצור את מפתח ה-API.
  • אתם יכולים לקשר את חשבון השירות שלכם למפתח ה-API במסד הנתונים של Weaviate כדי להגדיר את האימות (AuthN) וההרשאה (AuthZ). עם זאת, חשבון השירות לא נדרש.
  • אפשר לאחסן את מפתח ה-API ב-Secret Manager בפרויקט, ולתת לחשבון השירות הרשאות למשאבי הסודות האלה.
  • מנוע RAG משתמש בחשבונות שירות כדי לגשת למפתח ה-API מ-Secret Manager בפרויקטים שלכם.

הגדרה של סביבת המסוף ב- Google Cloud

כאן אפשר ללמוד איך להגדיר את הסביבה

כדי להגדיר את הסביבה, בוחרים אחת מהכרטיסיות הבאות:

Python

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  6. במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

    בחלק התחתון של Google Cloud המסוף יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

  7. אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  8. כדי להתקין או לעדכן את Agent Platform SDK for Python, מריצים את הפקודה הבאה:

    pip3 install --upgrade "google-cloud-aiplatform>=1.38"
        

Node.js

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  6. במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

    בחלק התחתון של Google Cloud המסוף יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

  7. אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  8. כדי להתקין או לעדכן את Agent Platform SDK ל-Node.js, מריצים את הפקודה הבאה:

    npm install @google-cloud/vertexai
        

Java

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  6. במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

    בחלק התחתון של Google Cloud המסוף יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

  7. אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  8. כדי להוסיף את google-cloud-vertexai כתלות, מוסיפים את הקוד המתאים לסביבה שלכם:

    ‫Maven עם BOM

    מוסיפים את קוד ה-HTML הבא לקובץ pom.xml:

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.32.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-vertexai</artifactId>
      </dependency>
    </dependencies>
                

    ‫Maven בלי BOM

    מוסיפים את קוד ה-HTML הבא לקובץ pom.xml:

    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-vertexai</artifactId>
      <version>0.4.0</version>
    </dependency>
                

    ‫Gradle ללא BOM

    מוסיפים את הנתונים הבאים אל build.gradle

    implementation 'com.google.cloud:google-cloud-vertexai:0.4.0'

Go

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  6. במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

    בחלק התחתון של Google Cloud המסוף יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

  7. אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  8. כדאי לעיין בחבילות ה-API של Agent Platform שזמינות ב-Go כדי להחליט איזו חבילה הכי מתאימה לצרכים של הפרויקט:

    • Package cloud.google.com/go/vertexai (מומלץ)

      vertexai היא חבילה שנכתבה על ידי בני אדם ומספקת גישה ליכולות ולתכונות נפוצות.

      החבילה הזו מומלצת כנקודת התחלה לרוב המפתחים שמשתמשים ב-Agent Platform API. כדי לגשת ליכולות ולתכונות שעדיין לא נכללות בחבילה הזו, צריך להשתמש ב-aiplatform שנוצר באופן אוטומטי.

    • Package cloud.google.com/go/aiplatform

      aiplatform היא חבילה שנוצרה אוטומטית.

      החבילה הזו מיועדת לפרויקטים שנדרשת בהם גישה ליכולות ולתכונות של Agent Platform API שעדיין לא מסופקות על ידי חבילת vertexai שנכתבה על ידי בני אדם.

  9. כדי להתקין את חבילת Go הרצויה בהתאם לצרכים של הפרויקט, מריצים אחת מהפקודות הבאות:

    # Human authored package. Recommended for most developers.
    go get cloud.google.com/go/vertexai
        
    # Auto-generated package. go get cloud.google.com/go/aiplatform

C#

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  6. במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

    בחלק התחתון של Google Cloud המסוף יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

  7. אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

REST

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  6. במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

    בחלק התחתון של Google Cloud המסוף יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

  7. מגדירים משתני סביבה על ידי הזנת הפקודה הבאה. מחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloud .
    MODEL_ID="gemini-3.5-flash"
    PROJECT_ID="PROJECT_ID"
        
  8. הקצאת נקודת הקצה:
    gcloud beta services identity create --service=aiplatform.googleapis.com --project=${PROJECT_ID}
        
  9. אופציונלי: אם אתם משתמשים ב-Cloud Shell ומתבקשים לאשר את Cloud Shell, לוחצים על Authorize.

הכנת קורפוס RAG

כדי לגשת לנתונים ממסד הנתונים של Weaviate, ל-RAG Engine צריכה להיות גישה לקורפוס RAG. בקטע הזה מוסבר איך ליצור מאגר ידע יחיד של RAG ומאגרי ידע נוספים של RAG.

שימוש בממשקי API‏ CreateRagCorpus ו-UpdateRagCorpus

כשקוראים לממשקי ה-API‏ CreateRagCorpus ו-UpdateRagCorpus, צריך לציין את השדות הבאים:

  • rag_vector_db_config.weaviate: אחרי שקוראים ל-CreateRagCorpus API, נבחרת ההגדרה של מסד הנתונים הווקטורי. ההגדרה של מסד הנתונים הווקטורי מכילה את כל שדות ההגדרה. אם השדה rag_vector_db_config.weaviate לא מוגדר, ברירת המחדל היא rag_vector_db_config.rag_managed_db.
  • weaviate.http_endpoint: נקודת הקצה (endpoint) של Weaviate ב-HTTPS או ב-HTTP נוצרת במהלך הקצאת המשאבים של מופע מסד הנתונים של Weaviate.
  • weaviate.collection_name: השם של האוסף שנוצר במהלך הקצאת המשאבים של מופע Weaviate. השם חייב להתחיל באות גדולה.
  • api_auth.api_key_config: ההגדרה מציינת שימוש במפתח API כדי לאשר את הגישה למאגר הנתונים הווקטורי.
  • api_key_config.api_key_secret_version: שם המשאב של הסוד שמאוחסן ב-Secret Manager, שמכיל את מפתח ה-API של Weaviate.

אתם יכולים ליצור את מאגר המידע של RAG ולקשר אותו לאוסף Weaviate במופע של מסד הנתונים. עם זאת, יכול להיות שתצטרכו את חשבון השירות כדי ליצור את מפתח ה-API ולהגדיר את מופע מסד הנתונים של Weaviate. כשיוצרים את מאגר המידע הראשון של RAG, נוצר חשבון השירות. אחרי שיוצרים את מאגר ה-RAG הראשון, יכול להיות שהשיוך בין מסד הנתונים של Weaviate לבין מפתח ה-API לא יהיה מוכן לשימוש ביצירה של מאגר RAG נוסף.

למקרה שמסד הנתונים ומפתח ההצפנה לא מוכנים לשיוך למאגר המידע של RAG, צריך לבצע את הפעולות הבאות במאגר המידע של RAG:

  1. מגדירים את השדה weaviate ב-rag_vector_db_config.

    • אי אפשר לשנות את מסד הנתונים הווקטורי המשויך.
    • משאירים את השדות http_endpoint ו-collection_name ריקים. אפשר לעדכן את שני השדות האלה בשלב מאוחר יותר.
  2. אם מפתח ה-API לא מאוחסן ב-Secret Manager, אפשר להשאיר את השדה api_auth ריק. כששולחים קריאה ל-API‏ UpdateRagCorpus, אפשר לעדכן את השדה api_auth. כדי להשתמש ב-Weaviate, צריך לבצע את הפעולות הבאות:

    1. מגדירים את api_key_config בשדה api_auth.
    2. מגדירים את api_key_secret_version של מפתח Weaviate API ב-Secret Manager. השדה api_key_secret_version הוא בפורמט הבא:

      projects/{project}/secrets/{secret}/versions/{version}

  3. אם מציינים שדות שאפשר להגדיר רק פעם אחת, כמו http_endpoint או collection_name, אי אפשר לשנות אותם אלא אם מוחקים את מאגר ה-RAG ויוצרים אותו מחדש. אפשר לעדכן שדות אחרים, כמו השדה של מפתח ה-API ‏api_key_secret_version.

  4. כשמתקשרים אל UpdateRagCorpus, אפשר להגדיר את השדה vector_db. הערך vector_db צריך להיות weaviate בקריאה ל-CreateRagCorpus API. אחרת, המערכת בוחרת באפשרות RAG Managed Database, שהיא ברירת המחדל. אי אפשר לשנות את האפשרות הזו כשמתקשרים אל UpdateRagCorpus ה-API. כשמתקשרים אל UpdateRagCorpus והשדה vector_db מוגדר באופן חלקי, אפשר לעדכן את השדות שמסומנים כניתנים לשינוי (נקראים גם משתנים).

בטבלה הזו מפורטים WeaviateConfig השדות שניתנים לשינוי ושלא ניתן לשנות שמשמשים בקוד.

שם השדה ניתן לשינוי או שלא ניתן לשינוי
http_endpoint לא ניתן לשינוי אחרי ההגדרה
collection_name לא ניתן לשינוי אחרי ההגדרה
api_key_authentication ניתן לשינוי

יצירת מאגר המידע הראשון של RAG

אם חשבון השירות של RAG Engine לא קיים, צריך לבצע את הפעולות הבאות:

  1. יוצרים קורפוס RAG ב-RAG Engine עם הגדרת Weaviate ריקה, שמתחילה את הקצאת המשאבים של RAG Engine כדי ליצור חשבון שירות.
  2. בוחרים שם לחשבון השירות של RAG Engine בפורמט הבא:

    service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com

    לדוגמה, service-123456789@gcp-sa-vertex-rag.iam.gserviceaccount.com.

  3. באמצעות חשבון השירות, ניגשים לסוד שמאוחסן ב-Secret Manager של הפרויקט, שמכיל את מפתח Weaviate API.
  4. אחרי שהקצאת המשאבים של Weaviate מסתיימת, מקבלים את הפרטים הבאים:
    • נקודת הקצה של Weaviate ב-HTTPS או ב-HTTP.
    • השם של אוסף Weaviate.
  5. מפעילים את CreateRagCorpus API כדי ליצור מאגר RAG עם הגדרת Weaviate ריקה, ומפעילים את UpdateRagCorpus API כדי לעדכן את מאגר ה-RAG עם המידע הבא:
    • נקודת הקצה של Weaviate ב-HTTPS או ב-HTTP.
    • השם של אוסף Weaviate.
    • שם המשאב של מפתח ה-API.

יצירת מאגר מידע נוסף של RAG

אם חשבון השירות של RAG Engine קיים, מבצעים את הפעולות הבאות:

  1. אפשר למצוא את חשבון השירות של מנוע ה-RAG בהרשאות הפרויקט.
  2. מפעילים את האפשרות Include Google-provided role grants (הכללת תפקידים שניתנו על ידי Google).
  3. בוחרים שם לחשבון השירות של RAG Engine בפורמט הבא:

    service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com

  4. באמצעות חשבון השירות, ניגשים לסוד שמאוחסן ב-Secret Manager של הפרויקט, שמכיל את מפתח Weaviate API.
  5. במהלך הקצאת המשאבים ב-Weaviate, מקבלים את הפרטים הבאים:
    • נקודת הקצה של Weaviate ב-HTTPS או ב-HTTP.
    • השם של אוסף Weaviate.
  6. יוצרים קורפוס RAG ב-RAG Engine ומתחברים לאוסף Weaviate באמצעות אחת מהפעולות הבאות:
    1. מבצעים קריאה ל-API‏ CreateRagCorpus כדי ליצור מאגר RAG עם הגדרות Weaviate מאוכלסות, וזו האפשרות המומלצת.
    2. מבצעים קריאה ל-CreateRagCorpus API כדי ליצור מאגר RAG עם הגדרת Weaviate ריקה, ומבצעים קריאה ל-UpdateRagCorpus API כדי לעדכן את מאגר ה-RAG עם המידע הבא:
      • נקודת קצה (endpoint) של HTTP במסד נתונים של Weaviate
      • שם האוסף ב-Weaviate
      • מפתח API

דוגמאות

בקטע הזה מוצג קוד לדוגמה שממחיש איך להגדיר את מסד הנתונים של Weaviate, את Secret Manager, את מאגר המידע של RAG ואת קובץ ה-RAG. יש גם קוד לדוגמה שמראה איך לייבא קבצים, לאחזר הקשר, ליצור תוכן ולמחוק את מאגר ה-RAG ואת קובצי ה-RAG.

כדי להשתמש במחברת RAG API של Model Garden, אפשר לעיין במאמר בנושא שימוש ב-Weaviate עם Llama 3.

הגדרת מסד הנתונים של Weaviate

בדוגמת הקוד הזו אפשר לראות איך מגדירים את נתוני Weaviate ואת Secret Manager.

REST

# TODO(developer): Update the variables.
# The HTTPS/HTTP Weaviate endpoint you created during provisioning.
HTTP_ENDPOINT_NAME="https://your.weaviate.endpoint.com"

# Your Weaviate API Key.
WEAVIATE_API_KEY="example-api-key"

# Select your Weaviate collection name, which roughly corresponds to a Agent Platform Knowledge Engine Corpus.
# For example, "MyCollectionName"
# Note that the first letter needs to be capitalized.
# Otherwise, Weavaite will capitalize it for you.
WEAVIATE_COLLECTION_NAME="MyCollectionName"

# Create a collection in Weaviate which includes the required schema fields shown below.
echo '{
  "class": "'${WEAVIATE_COLLECTION_NAME}'",
  "properties": [
    { "name": "fileId", "dataType": [ "string" ] },
    { "name": "corpusId", "dataType": [ "string" ] },
    { "name": "chunkId", "dataType": [ "string" ] },
    { "name": "chunkDataType", "dataType": [ "string" ] },
    { "name": "chunkData", "dataType": [ "string" ] },
    { "name": "fileOriginalUri", "dataType": [ "string" ] }
  ]
}' | curl \
    -X POST \
    -H 'Content-Type: application/json' \
    -H "Authorization: Bearer "${WEAVIATE_API_KEY} \
    -d @- \
    ${HTTP_ENDPOINT_NAME}/v1/schema

הגדרת Secret Manager

כדי להגדיר את Secret Manager, צריך להפעיל אותו ולהגדיר הרשאות.

יצירת סוד

כדי להפעיל את Secret Manager:

המסוף

  1. עוברים לדף Secret Manager.

    מעבר אל Secret Manager

  2. לוחצים על + Create Secret (יצירת סוד).

  3. מזינים את השם של הסוד. שמות של סודות יכולים להכיל רק אותיות באנגלית (A-Z), ספרות (0-9), מקפים (-) וקווים תחתונים (_).

  4. השדות הבאים הם אופציונליים:

    1. כדי להעלות את הקובץ עם הסוד, לוחצים על עיון.
    2. כדאי לקרוא את מדיניות השכפול.
    3. אם רוצים לנהל ידנית את המיקומים של הסוד, מסמנים את התיבה Manually manage locations for this secret (ניהול ידני של המיקומים של הסוד הזה). צריך לבחור לפחות אזור אחד.
    4. בוחרים את אפשרות ההצפנה.
    5. אם רוצים להגדיר ידנית את תקופת הרוטציה, מסמנים את התיבה הגדרת תקופת הרוטציה.
    6. אם רוצים לציין נושאים לפרסום או להרשמה כדי לקבל התראות על אירועים, לוחצים על הוספת נושאים.
    7. כברירת מחדל, הסוד אף פעם לא פג תוקף. אם רוצים להגדיר תאריך תפוגה, מסמנים את התיבה הגדרת תאריך תפוגה.
    8. כברירת מחדל, גרסאות של סודות מושמדות לפי בקשה. כדי לדחות את ההשמדה של גרסאות סודיות, מסמנים את התיבה הגדרת משך הזמן לדחיית ההשמדה.
    9. אם רוצים להשתמש בתוויות כדי לארגן ולסווג את הסודות, לוחצים על + הוספת תווית.
    10. אם רוצים להשתמש בהערות כדי לצרף מטא-נתונים לא מזהים לסודות, לוחצים על + הוספת הערה.
  5. לוחצים על Create secret (יצירת סוד).

REST

# Create a secret in SecretManager.
curl "https://secretmanager.googleapis.com/v1/projects/${PROJECT_ID}/secrets?secretId=${SECRET_NAME}" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --data "{\"replication\": {\"automatic\": {}}}"

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

# Import the Secret Manager client library.
from google.cloud import secretmanager


def create_secret(
    project_id: str, secret_id: str, ttl: Optional[str] = None
) -> secretmanager.Secret:
    """
    Create a new secret with the given name. A secret is a logical wrapper
    around a collection of secret versions. Secret versions hold the actual
    secret material.

     Args:
        project_id (str): The project ID where the secret is to be created.
        secret_id (str): The ID to assign to the new secret. This ID must be unique within the project.
        ttl (Optional[str]): An optional string that specifies the secret's time-to-live in seconds with
                             format (e.g., "900s" for 15 minutes). If specified, the secret
                             versions will be automatically deleted upon reaching the end of the TTL period.

    Returns:
        secretmanager.Secret: An object representing the newly created secret, containing details like the
                              secret's name, replication settings, and optionally its TTL.

    Example:
        # Create a secret with automatic replication and no TTL
        new_secret = create_secret("my-project", "my-new-secret")

        # Create a secret with a TTL of 30 days
        new_secret_with_ttl = create_secret("my-project", "my-timed-secret", "7776000s")
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}"

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {"replication": {"automatic": {}}, "ttl": ttl},
        }
    )

    # Print the new secret name.
    print(f"Created secret: {response.name}")

הגדרת ההרשאות

צריך להעניק לחשבון השירות הרשאות ל-Secret Manager.

המסוף

  1. בקטע IAM & Admin במסוף Google Cloud , מוצאים את חשבון השירות ולוחצים על סמל העיפרון כדי לערוך אותו.

  2. בשדה Role (תפקיד), בוחרים באפשרות Secret Manager Secret Accessor (גישה לסודות ב-Secret Manager).

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

def iam_grant_access(
    project_id: str, secret_id: str, member: str
) -> iam_policy_pb2.SetIamPolicyRequest:
    """
    Grant the given member access to a secret.
    """

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the secret.
    name = client.secret_path(project_id, secret_id)

    # Get the current IAM policy.
    policy = client.get_iam_policy(request={"resource": name})

    # Add the given member with access permissions.
    policy.bindings.add(role="roles/secretmanager.secretAccessor", members=[member])

    # Update the IAM Policy.
    new_policy = client.set_iam_policy(request={"resource": name, "policy": policy})

    # Print data about the secret.
    print(f"Updated IAM policy on {secret_id}")

הוספת גרסה של סוד

REST

# TODO(developer): Update the variables.
# Select a resource name for your Secret, which contains your API Key.
SECRET_NAME="MyWeaviateApiKeySecret"

# Your Weaviate API Key.
WEAVIATE_API_KEY="example-api-key"
# Encode your WEAVIATE_API_KEY using base 64.
SECRET_DATA=$(echo ${WEAVIATE_API_KEY} | base64)

# Create a new version of your secret which uses SECRET_DATA as payload
curl "https://secretmanager.googleapis.com/v1/projects/${PROJECT_ID}/secrets/${SECRET_NAME}:addVersion" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --data "{\"payload\": {\"data\": \"${SECRET_DATA}\"}}"

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import secretmanager
import google_crc32c  # type: ignore


def add_secret_version(
    project_id: str, secret_id: str, payload: str
) -> secretmanager.SecretVersion:
    """
    Add a new secret version to the given secret with the provided payload.
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent secret.
    parent = client.secret_path(project_id, secret_id)

    # Convert the string payload into a bytes. This step can be omitted if you
    # pass in bytes instead of a str for the payload argument.
    payload_bytes = payload.encode("UTF-8")

    # Calculate payload checksum. Passing a checksum in add-version request
    # is optional.
    crc32c = google_crc32c.Checksum()
    crc32c.update(payload_bytes)

    # Add the secret version.
    response = client.add_secret_version(
        request={
            "parent": parent,
            "payload": {
                "data": payload_bytes,
                "data_crc32c": int(crc32c.hexdigest(), 16),
            },
        }
    )

    # Print the new secret version name.
    print(f"Added secret version: {response.name}")

Use Weaviate with Llama 3

במחברת Model Garden RAG API נדגים איך להשתמש ב-Agent Platform SDK for Python עם קורפוס Weaviate ומודל Llama 3. כדי להשתמש במחברת, צריך לבצע את הפעולות הבאות:

  1. הגדרת מסד הנתונים של Weaviate

  2. הגדרת Secret Manager.

  3. שימוש ב-Model Garden RAG API notebook.

דוגמאות נוספות זמינות במאמר דוגמאות.

יצירת מאגר מידע של RAG

בדוגמת הקוד הזו אפשר לראות איך ליצור מאגר מידע של RAG ולהגדיר את מופע Weaviate כמאגר נתוני הווקטורים שלו.

REST

  # TODO(developer): Update the variables.
  PROJECT_ID = "YOUR_PROJECT_ID"
  # The HTTPS/HTTP Weaviate endpoint you created during provisioning.
  HTTP_ENDPOINT_NAME="https://your.weaviate.endpoint.com"

  # Your Weaviate collection name, which roughly corresponds to a Agent Platform Knowledge Engine Corpus.
  # For example, "MyCollectionName"
  # Note that the first letter needs to be capitalized.
  # Otherwise, Weaviate will capitalize it for you.
  WEAVIATE_COLLECTION_NAME="MyCollectionName"

  # The resource name of your Weaviate API Key your Secret.
  SECRET_NAME="MyWeaviateApiKeySecret"
  # The Secret Manager resource name containing the API Key for your Weaviate endpoint.
  # For example, projects/{project}/secrets/{secret}/versions/latest
  APIKEY_SECRET_VERSION="projects/${PROJECT_ID}/secrets/${SECRET_NAME}/versions/latest"

  # Select a Corpus display name.
  CORPUS_DISPLAY_NAME="SpecialCorpus"

  # Call CreateRagCorpus API and set all Vector DB Config parameters for Weaviate to create a new corpus associated to your selected Weaviate collection.
  curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora \
  -d '{
        "display_name" : '\""${CORPUS_DISPLAY_NAME}"\"',
        "rag_vector_db_config" : {
                "weaviate": {
                      "http_endpoint": '\""${HTTP_ENDPOINT_NAME}"\"',
                      "collection_name": '\""${WEAVIATE_COLLECTION_NAME}"\"'
                },
          "api_auth" : {
                  "api_key_config": {
                        "api_key_secret_version": '\""${APIKEY_SECRET_VERSION}"\"'
                  }
          }
        }
    }'

  # TODO(developer): Update the variables.
  # Get operation_id returned in CreateRagCorpus.
  OPERATION_ID="your-operation-id"

  # Poll Operation status until done = true in the response.
  curl -X GET \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
  https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/operations/${OPERATION_ID}

  # Call ListRagCorpora API to verify the RAG corpus is created successfully.
  curl -sS -X GET \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora"

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import agentplatform
from agentplatform import types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# weaviate_http_endpoint = "weaviate-http-endpoint"
# weaviate_collection_name = "weaviate-collection-name"
# weaviate_api_key_secret_manager_version = "projects/{PROJECT_ID}/secrets/{SECRET_NAME}/versions/latest"
# display_name = "test_corpus"
# description = "Corpus Description"

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-central1")

# Configure embedding model (Optional)
embedding_model_config = types.RagEmbeddingModelConfig(
    vertex_prediction_endpoint=types.RagEmbeddingModelConfigVertexPredictionEndpoint(
        endpoint="publishers/google/models/text-embedding-004"
    )
)

# Configure Vector DB
vector_db = types.RagVectorDbConfigWeaviate(
    http_endpoint=weaviate_http_endpoint,
    collection_name=weaviate_collection_name,
)

corpus = client.rag.create_corpus(
    rag_corpus=types.RagCorpus(
        display_name=display_name,
        description=description,
        rag_embedding_model_config=embedding_model_config,
        rag_vector_db_config=types.RagVectorDbConfig(
            weaviate=vector_db
        ),
    )
)
print(corpus)
# Example response:
# RagCorpus(name='projects/1234567890/locations/us-central1/ragCorpora/1234567890',
# display_name='test_corpus', description='Corpus Description', embedding_model_config=...
# ...

שימוש בקובץ RAG

RAG API מטפל בהעלאה, בייבוא, ברישום ובמחיקה של הקובץ.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: .
  • LOCATION: האזור שבו הבקשה תעובד.
  • RAG_CORPUS_ID: המזהה של משאב RagCorpus.
  • INPUT_FILE: הנתיב של קובץ מקומי.
  • FILE_DISPLAY_NAME: השם המוצג של RagFile.
  • RAG_FILE_DESCRIPTION: התיאור של RagFile.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/media:upload

גוף בקשת JSON:

{
 "rag_file": {
  "display_name": "FILE_DISPLAY_NAME",
  "description": "RAG_FILE_DESCRIPTION"
 }
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם INPUT_FILE ומריצים את הפקודה הבאה:

curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @INPUT_FILE \
"https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/media:upload"

PowerShell

שומרים את גוף הבקשה בקובץ בשם INPUT_FILE ומריצים את הפקודה הבאה:

$headers = @{  }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile INPUT_FILE `
-Uri "https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/media:upload" | Select-Object -Expand Content
תגובה מוצלחת מחזירה את משאב RagFile. הרכיב האחרון בשדה RagFile.name הוא rag_file_id שנוצר על ידי השרת.

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"
# path = "path/to/local/file.txt"
# display_name = "file_display_name"

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-east4")

rag_file = client.rag.upload_file(
    corpus_name=corpus_name,
    path=path,
    display_name=display_name,
)
print(rag_file)
# RagFile(name='projects/[PROJECT_ID]/locations/us-central1/ragCorpora/1234567890/ragFiles/09876543',
#  display_name='file_display_name')

ייבוא קובצי RAG

אפשר לייבא קבצים ותיקיות מ-Drive או מ-Cloud Storage.

REST

משתמשים ב-response.metadata כדי להציג כשלים חלקיים, זמן בקשה וזמן תגובה באובייקט response של ה-SDK.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: .
  • LOCATION: האזור שבו הבקשה תעובד.
  • RAG_CORPUS_ID: המזהה של משאב RagCorpus.
  • GCS_URIS: רשימה של מיקומי Cloud Storage. דוגמה: gs://my-bucket1, gs://my-bucket2.
  • DRIVE_RESOURCE_ID: המזהה של משאב Drive. דוגמאות:
    • https://drive.google.com/file/d/ABCDE
    • https://drive.google.com/corp/drive/u/0/folders/ABCDEFG
  • DRIVE_RESOURCE_TYPE: סוג המשאב ב-Drive. אפשרויות:
    • RESOURCE_TYPE_FILE – קובץ
    • RESOURCE_TYPE_FOLDER – תיקייה
  • CHUNK_SIZE: אופציונלי: מספר הטוקנים שכל מקטע צריך להכיל.
  • CHUNK_OVERLAP: אופציונלי: מספר האסימונים שחופפים בין חלקי הטקסט.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import

גוף בקשת JSON:

{
  "import_rag_files_config": {
    "gcs_source": {
      "uris": GCS_URIS
    },
    "google_drive_source": {
      "resource_ids": {
        "resource_id": DRIVE_RESOURCE_ID,
        "resource_type": DRIVE_RESOURCE_TYPE
      },
    }
  }
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$headers = @{  }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import" | Select-Object -Expand Content
תגובה מוצלחת מחזירה את משאב ImportRagFilesOperationMetadata.

בדוגמה הבאה מוצג איך לייבא קובץ מ-Cloud Storage. משתמשים בשדה הבקרה max_embedding_requests_per_min כדי להגביל את הקצב שבו RAG Engine קורא למודל ההטמעה במהלך תהליך יצירת האינדקס ImportRagFiles. ערך ברירת המחדל של השדה הוא 1000 שיחות לדקה.

// Cloud Storage bucket/file location.
// Such as "gs://rag-e2e-test/"
GCS_URIS=YOUR_GCS_LOCATION

// Enter the QPM rate to limit RAG's access to your embedding model
// Example: 1000
EMBEDDING_MODEL_QPM_RATE=MAX_EMBEDDING_REQUESTS_PER_MIN_LIMIT

// ImportRagFiles
// Import a single Cloud Storage file or all files in a Cloud Storage bucket.
// Input: ENDPOINT, PROJECT_ID, RAG_CORPUS_ID, GCS_URIS
// Output: ImportRagFilesOperationMetadataNumber
// Use ListRagFiles to find the server-generated rag_file_id.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${ENDPOINT}/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/ragCorpora/${RAG_CORPUS_ID}/ragFiles:import \
-d '{
  "import_rag_files_config": {
    "gcs_source": {
      "uris": '\""${GCS_URIS}"\"'
    },
    "rag_file_chunking_config": {
      "chunk_size": 512
    },
    "max_embedding_requests_per_min": '"${EMBEDDING_MODEL_QPM_RATE}"'
  }
}'

// Poll the operation status.
// The response contains the number of files imported.
OPERATION_ID=OPERATION_ID
poll_op_wait ${OPERATION_ID}

הדוגמה הבאה מדגימה איך מייבאים קובץ מ-Drive. משתמשים בשדה הבקרה max_embedding_requests_per_min כדי להגביל את הקצב שבו מנוע RAG קורא למודל ההטמעה במהלך ImportRagFiles תהליך יצירת האינדקס. ערך ברירת המחדל של השדה הוא 1000 שיחות לדקה.

// Google Drive folder location.
FOLDER_RESOURCE_ID=YOUR_GOOGLE_DRIVE_FOLDER_RESOURCE_ID

// Enter the QPM rate to limit RAG's access to your embedding model
// Example: 1000
EMBEDDING_MODEL_QPM_RATE=MAX_EMBEDDING_REQUESTS_PER_MIN_LIMIT

// ImportRagFiles
// Import all files in a Google Drive folder.
// Input: ENDPOINT, PROJECT_ID, RAG_CORPUS_ID, FOLDER_RESOURCE_ID
// Output: ImportRagFilesOperationMetadataNumber
// Use ListRagFiles to find the server-generated rag_file_id.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${ENDPOINT}/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/ragCorpora/${RAG_CORPUS_ID}/ragFiles:import \
-d '{
  "import_rag_files_config": {
    "google_drive_source": {
      "resource_ids": {
        "resource_id": '\""${FOLDER_RESOURCE_ID}"\"',
        "resource_type": "RESOURCE_TYPE_FOLDER"
      }
    },
    "max_embedding_requests_per_min": '"${EMBEDDING_MODEL_QPM_RATE}"'
  }
}'

// Poll the operation status.
// The response contains the number of files imported.
OPERATION_ID=OPERATION_ID
poll_op_wait ${OPERATION_ID}

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform
from agentplatform import types

from google.genai import types as genai_types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"

# Supports Google Cloud Storage and Google Drive Links
# paths = ["https://drive.google.com/file/d/123", "gs://my_bucket/my_files_dir/*"]

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-central1")

response = client.rag.import_files(
    name=corpus_name,
    import_config=types.ImportRagFilesConfig(
        gcs_source=genai_types.GcsSource(uris=[paths[1]]),
        google_drive_source=types.GoogleDriveSource(
            resource_ids=[
                types.GoogleDriveSourceResourceId(
                    resource_id=paths[0],
                    resource_type=types.ResourceType.RESOURCE_TYPE_FILE
                )
            ]
        ), # optional
        rag_file_transformation_config=types.RagFileTransformationConfig(
            rag_file_chunking_config=types.RagFileChunkingConfig(
                chunk_size=512,
                chunk_overlap=100,
            )
        ), # optional
        max_embedding_requests_per_min=900, # optional
    )
)

print(f"Imported {response.imported_rag_files_count} files.")
# Example response:
# Imported 2 files.

איך מקבלים קובץ RAG

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: .
  • LOCATION: האזור שבו הבקשה תעובד.
  • RAG_CORPUS_ID: המזהה של משאב RagCorpus.
  • RAG_FILE_ID: המזהה של משאב RagFile.

ה-method של ה-HTTP וכתובת ה-URL:

GET https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X GET \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID"

PowerShell

מריצים את הפקודה הבאה:

$headers = @{  }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID" | Select-Object -Expand Content
תגובה מוצלחת מחזירה את משאב RagFile.

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# file_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}/ragFiles/{rag_file_id}"

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-central1")

rag_file = client.rag.get_file(name=file_name)
print(rag_file)
# Example response:
# RagFile(name='projects/1234567890/locations/us-central1/ragCorpora/11111111111/ragFiles/22222222222',
# display_name='file_display_name', description='file description')

הצגת רשימה של קובצי RAG

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: .
  • LOCATION: האזור שבו הבקשה תעובד.
  • RAG_CORPUS_ID: המזהה של משאב RagCorpus.
  • PAGE_SIZE: גודל הדף הסטנדרטי של הרשימה. אפשר לשנות את מספר התוצאות RagFiles שמוחזרות בכל דף על ידי עדכון הפרמטר page_size.
  • PAGE_TOKEN: אסימון דף הרשימה הרגיל. בדרך כלל מתקבל באמצעות ListRagFilesResponse.next_page_token של הקריאה הקודמת ל-VertexRagDataService.ListRagFiles.

ה-method של ה-HTTP וכתובת ה-URL:

GET https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles?page_size=PAGE_SIZE&page_token=PAGE_TOKEN

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X GET \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles?page_size=PAGE_SIZE&page_token=PAGE_TOKEN"

PowerShell

מריצים את הפקודה הבאה:

$headers = @{  }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles?page_size=PAGE_SIZE&page_token=PAGE_TOKEN" | Select-Object -Expand Content
אמור להתקבל קוד סטטוס של הצלחה (2xx) יחד עם רשימה של RagFiles במסגרת RAG_CORPUS_ID שצוין.

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-central1")

files_response = client.rag.list_files(name=corpus_name)
for file in files_response.rag_files:
    print(file.display_name)
    print(file.name)
# Example response:
# g-drive_file.txt
# projects/1234567890/locations/us-central1/ragCorpora/111111111111/ragFiles/222222222222
# g_cloud_file.txt
# projects/1234567890/locations/us-central1/ragCorpora/111111111111/ragFiles/333333333333

מחיקת קובץ RAG

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: .
  • LOCATION: האזור שבו הבקשה תעובד.
  • RAG_CORPUS_ID: המזהה של משאב RagCorpus.
  • RAG_FILE_ID: המזהה של משאב RagFile. פורמט: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file_id}

ה-method של ה-HTTP וכתובת ה-URL:

DELETE https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X DELETE \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID"

PowerShell

מריצים את הפקודה הבאה:

$headers = @{  }

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID" | Select-Object -Expand Content
תגובה מוצלחת מחזירה את משאב DeleteOperationMetadata.

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# file_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}/ragFiles/{rag_file_id}"

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-central1")

client.rag.delete_file(name=file_name)
print(f"File {file_name} deleted.")
# Example response:
# Successfully deleted the RagFile.
# File projects/1234567890/locations/us-central1/ragCorpora/1111111111/ragFiles/2222222222 deleted.

אחזור הקשר

כשמשתמש שואל שאלה או מספק פרומפט, רכיב האחזור ב-RAG מחפש במאגר הידע שלו מידע שרלוונטי לשאילתה.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION: האזור שבו הבקשה תעובד.
  • PROJECT_ID: .
  • RAG_CORPUS_RESOURCE: השם של משאב RagCorpus. פורמט: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}
  • VECTOR_DISTANCE_THRESHOLD: רק הקשרים עם מרחק וקטורי קטן יותר מהסף מוחזרים.
  • TEXT: טקסט השאילתה כדי לקבל הקשרים רלוונטיים.
  • SIMILARITY_TOP_K: מספר ההקשרים העליונים לאחזור.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts

גוף בקשת JSON:

{
 "vertex_rag_store": {
    "rag_resources": {
      "rag_corpus": "RAG_CORPUS_RESOURCE",
    },
    "vector_distance_threshold": 0.8
  },
  "query": {
   "text": "TEXT",
   "similarity_top_k": SIMILARITY_TOP_K
  }
 }

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$headers = @{  }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts" | Select-Object -Expand Content
אמור להתקבל קוד סטטוס של הצלחה (2xx) ורשימה של RagFiles קשורים.

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform

from agentplatform import types
from google.genai import types as genai_types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/[PROJECT_ID]/locations/us-central1/ragCorpora/[rag_corpus_id]"

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-east4")

response = client.rag.retrieve_contexts(
    vertex_rag_store=genai_types.VertexRagStore(
        rag_resources=[
            genai_types.VertexRagStoreRagResource(
                rag_corpus=corpus_name,
                # Optional: supply IDs from `rag.list_files()`.
                # rag_file_ids=["rag-file-1", "rag-file-2", ...],
            )
        ],
    ),
    query=types.RagQuery(
        text="Hello World!",
        rag_retrieval_config=genai_types.RagRetrievalConfig(
            top_k=10,
            filter=genai_types.RagRetrievalConfigFilter(
                vector_distance_threshold=0.5
            ),
        ),
    )
)
print(response)
# Example response:
# contexts {
#   contexts {
#     source_uri: "gs://your-bucket-name/file.txt"
#     text: "....
#   ....

יצירת תוכן

חיזוי שולט בשיטת ה-LLM שיוצרת תוכן.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: .
  • LOCATION: האזור שבו הבקשה תעובד.
  • MODEL_ID: מודל LLM ליצירת תוכן. לדוגמה: gemini-3.5-flash
  • GENERATION_METHOD: שיטה של LLM ליצירת תוכן. אפשרויות: generateContent, ‏ streamGenerateContent
  • INPUT_PROMPT: הטקסט שנשלח למודל שפה גדול (LLM) ליצירת תוכן. כדאי לנסות להשתמש בהנחיה שרלוונטית לקובצי ה-RAG שהועלו.
  • RAG_CORPUS_RESOURCE: השם של משאב RagCorpus. פורמט: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}
  • SIMILARITY_TOP_K: אופציונלי: מספר ההקשרים העליונים לאחזור.
  • VECTOR_DISTANCE_THRESHOLD: אופציונלי: מוחזרים הקשרים עם מרחק וקטורי קטן יותר מערך הסף.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD

גוף בקשת JSON:

{
 "contents": {
  "role": "user",
  "parts": {
    "text": "INPUT_PROMPT"
  }
 },
 "tools": {
  "retrieval": {
   "disable_attribution": false,
   "vertex_rag_store": {
    "rag_resources": {
      "rag_corpus": "RAG_CORPUS_RESOURCE",
    },
    "similarity_top_k": SIMILARITY_TOP_K,
    "vector_distance_threshold": VECTOR_DISTANCE_THRESHOLD
   }
  }
 }
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$headers = @{  }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD" | Select-Object -Expand Content
תשובה מוצלחת מחזירה את התוכן שנוצר עם ציטוטים.

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


from google import genai
from google.genai import types as genai_types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"

rag_retrieval_tool = genai_types.Tool(
    retrieval=genai_types.Retrieval(
        vertex_rag_store=genai_types.VertexRagStore(
            rag_resources=[
                genai_types.VertexRagStoreRagResource(
                    rag_corpus=corpus_name
                )
            ],
            rag_retrieval_config=genai_types.RagRetrievalConfig(
                top_k=10,
                filter=genai_types.RagRetrievalConfigFilter(
                    vector_distance_threshold=0.5
                ),
            ),
        ),
    )
)

# Create a GenAI SDK client to make a generate_content request
genai_client = genai.Client(enterprise=True, project=PROJECT_ID, location="us-central1")

response = genai_client.models.generate_content(
    model="gemini-2.5-pro",
    contents="Why is the sky blue?",
    config=genai_types.GenerateContentConfig(
        tools=[rag_retrieval_tool]
    )
)
print(response.text)
# Example response:
#   The sky appears blue due to a phenomenon called Rayleigh scattering.
#   Sunlight, which contains all colors of the rainbow, is scattered
#   by the tiny particles in the Earth's atmosphere....
#   ...

חיפוש היברידי נתמך במסד הנתונים של Weaviate, שמשלב חיפושים סמנטיים וחיפושים לפי מילות מפתח כדי לשפר את הרלוונטיות של תוצאות החיפוש. במהלך אחזור תוצאות החיפוש, שילוב של ציוני דמיון מחיפוש סמנטי (וקטור צפוף) ומחיפוש מילות מפתח (וקטור דליל) יוצר את התוצאות הסופיות המדורגות.

חיפוש היברידי באמצעות RAG Engine Retrieval API

זוהי דוגמה להפעלת חיפוש היברידי באמצעות RAG Engine retrieval API.

REST

  # TODO(developer): Update the variables.
  PROJECT_ID = "YOUR_PROJECT_ID"
  # The HTTPS/HTTP Weaviate endpoint you created during provisioning.
  HTTP_ENDPOINT_NAME="https://your.weaviate.endpoint.com"

  # Your Weaviate collection name, which roughly corresponds to a Agent Platform Knowledge Engine Corpus.
  # For example, "MyCollectionName"
  # Note that the first letter needs to be capitalized.
  # Otherwise, Weaviate will capitalize it for you.
  WEAVIATE_COLLECTION_NAME="MyCollectionName"

  # The resource name of your Weaviate API Key your Secret.
  SECRET_NAME="MyWeaviateApiKeySecret"
  # The Secret Manager resource name containing the API Key for your Weaviate endpoint.
  # For example, projects/{project}/secrets/{secret}/versions/latest
  APIKEY_SECRET_VERSION="projects/${PROJECT_ID}/secrets/${SECRET_NAME}/versions/latest"

  # Select a Corpus display name.
  CORPUS_DISPLAY_NAME="SpecialCorpus"

  # Call CreateRagCorpus API and set all Vector DB Config parameters for Weaviate to create a new corpus associated to your selected Weaviate collection.
  curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora \
  -d '{
        "display_name" : '\""${CORPUS_DISPLAY_NAME}"\"',
        "rag_vector_db_config" : {
                "weaviate": {
                      "http_endpoint": '\""${HTTP_ENDPOINT_NAME}"\"',
                      "collection_name": '\""${WEAVIATE_COLLECTION_NAME}"\"'
                },
          "api_auth" : {
                  "api_key_config": {
                        "api_key_secret_version": '\""${APIKEY_SECRET_VERSION}"\"'
                  }
          }
        }
    }'

  # TODO(developer): Update the variables.
  # Get operation_id returned in CreateRagCorpus.
  OPERATION_ID="your-operation-id"

  # Poll Operation status until done = true in the response.
  curl -X GET \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
  https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/operations/${OPERATION_ID}

  # Call ListRagCorpora API to verify the RAG corpus is created successfully.
  curl -sS -X GET \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora"

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform

from agentplatform import types
from google.genai import types as genai_types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/[PROJECT_ID]/locations/us-central1/ragCorpora/[rag_corpus_id]"

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-east4")

response = client.rag.retrieve_contexts(
    vertex_rag_store=genai_types.VertexRagStore(
        rag_resources=[
            genai_types.VertexRagStoreRagResource(
                rag_corpus=corpus_name,
                # Optional: supply IDs from `rag.list_files()`.
                # rag_file_ids=["rag-file-1", "rag-file-2", ...],
            )
        ],
    ),
    query=types.RagQuery(
        text="Hello World!",
        rag_retrieval_config=genai_types.RagRetrievalConfig(
            top_k=10,
            filter=genai_types.RagRetrievalConfigFilter(
                vector_distance_threshold=0.5
            ),
        ),
    )
)
print(response)
# Example response:
# contexts {
#   contexts {
#     source_uri: "gs://your-bucket-name/file.txt"
#     text: "....
#   ....

שימוש בחיפוש היברידי ובמנוע RAG ליצירה מבוססת

זוהי דוגמה לשימוש בחיפוש היברידי ובמנוע RAG ליצירת תוכן מבוסס.

REST

  # TODO(developer): Update the variables.
  PROJECT_ID = "YOUR_PROJECT_ID"
  # The HTTPS/HTTP Weaviate endpoint you created during provisioning.
  HTTP_ENDPOINT_NAME="https://your.weaviate.endpoint.com"

  # Your Weaviate collection name, which roughly corresponds to a Agent Platform Knowledge Engine Corpus.
  # For example, "MyCollectionName"
  # Note that the first letter needs to be capitalized.
  # Otherwise, Weaviate will capitalize it for you.
  WEAVIATE_COLLECTION_NAME="MyCollectionName"

  # The resource name of your Weaviate API Key your Secret.
  SECRET_NAME="MyWeaviateApiKeySecret"
  # The Secret Manager resource name containing the API Key for your Weaviate endpoint.
  # For example, projects/{project}/secrets/{secret}/versions/latest
  APIKEY_SECRET_VERSION="projects/${PROJECT_ID}/secrets/${SECRET_NAME}/versions/latest"

  # Select a Corpus display name.
  CORPUS_DISPLAY_NAME="SpecialCorpus"

  # Call CreateRagCorpus API and set all Vector DB Config parameters for Weaviate to create a new corpus associated to your selected Weaviate collection.
  curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora \
  -d '{
        "display_name" : '\""${CORPUS_DISPLAY_NAME}"\"',
        "rag_vector_db_config" : {
                "weaviate": {
                      "http_endpoint": '\""${HTTP_ENDPOINT_NAME}"\"',
                      "collection_name": '\""${WEAVIATE_COLLECTION_NAME}"\"'
                },
          "api_auth" : {
                  "api_key_config": {
                        "api_key_secret_version": '\""${APIKEY_SECRET_VERSION}"\"'
                  }
          }
        }
    }'

  # TODO(developer): Update the variables.
  # Get operation_id returned in CreateRagCorpus.
  OPERATION_ID="your-operation-id"

  # Poll Operation status until done = true in the response.
  curl -X GET \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
  https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/operations/${OPERATION_ID}

  # Call ListRagCorpora API to verify the RAG corpus is created successfully.
  curl -sS -X GET \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora"

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


from google import genai
from google.genai import types as genai_types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"

rag_retrieval_tool = genai_types.Tool(
    retrieval=genai_types.Retrieval(
        vertex_rag_store=genai_types.VertexRagStore(
            rag_resources=[
                genai_types.VertexRagStoreRagResource(
                    rag_corpus=corpus_name
                )
            ],
            rag_retrieval_config=genai_types.RagRetrievalConfig(
                top_k=10,
                filter=genai_types.RagRetrievalConfigFilter(
                    vector_distance_threshold=0.5
                ),
            ),
        ),
    )
)

# Create a GenAI SDK client to make a generate_content request
genai_client = genai.Client(enterprise=True, project=PROJECT_ID, location="us-central1")

response = genai_client.models.generate_content(
    model="gemini-2.5-pro",
    contents="Why is the sky blue?",
    config=genai_types.GenerateContentConfig(
        tools=[rag_retrieval_tool]
    )
)
print(response.text)
# Example response:
#   The sky appears blue due to a phenomenon called Rayleigh scattering.
#   Sunlight, which contains all colors of the rainbow, is scattered
#   by the tiny particles in the Earth's atmosphere....
#   ...

המאמרים הבאים