使用 RAG Engine 將 Agent Search 做為檢索後端

本頁面介紹如何將 Agent Search 整合至 RAG Engine。

Agent Search 可協助您在 Gemini Enterprise Agent Platform RAG 應用程式中檢索及管理資料。將 Agent Search 做為檢索後端,可提升效能、擴充性和整合便利性。

  • 提升效能和擴充性:Agent Search 的設計宗旨是處理大量資料,並將延遲時間降至最低。這表示 RAG 應用程式的回應速度會更快,效能也會提升,特別是在處理複雜或廣泛的知識庫時。

  • 簡化資料管理:從各種來源匯入資料,例如網站、BigQuery 資料集和 Cloud Storage 值區,簡化資料擷取程序

  • 完美整合:Agent Platform 內建與 Agent Search 的整合功能,可讓您選取 Agent Search 做為 RAG 應用程式的語料庫後端。這可簡化整合程序,並確保元件之間的相容性達到最佳狀態。

  • 提升 LLM 輸出內容品質:使用 Agent Search 的檢索功能,可確保 RAG 應用程式從語料庫檢索最相關的資訊,進而生成更準確且資訊豐富的 LLM 輸出內容。

Agent Search 結合了深度資訊檢索、自然語言處理,以及最新的大型語言模型 (LLM) 處理功能,有助於理解使用者意圖,並傳回最符合需求的結果。

透過 Agent Search,您可以運用有權控管的資料,建構媲美 Google 水準的搜尋應用程式。

如要設定 Agent Search,請按照下列步驟操作:

  1. 建立搜尋資料儲存庫

  2. 建立搜尋應用程式

將 Agent Search 做為 RAG Engine 的檢索後端

設定 Agent Search 後,請按照下列步驟將其設為 RAG 應用程式的擷取後端。

將 Agent Search 設為檢索後端,建立 RAG 語料庫

這些程式碼範例說明如何將 Agent Search 設定為 RAG 語料庫的檢索後端。

REST

如要使用指令列建立 RAG 語料庫,請按照下列步驟操作:

  1. 建立 RAG 語料庫

    請替換程式碼範例中使用的下列變數:

    • PROJECT_ID:專案的 ID。 Google Cloud
    • LOCATION:處理要求的區域。
    • DISPLAY_NAME:要建立的 RAG 語料庫顯示名稱。
    • ENGINE_NAME:Agent Search 引擎或 Agent Search 資料儲存庫的完整資源名稱。例如,假設使用者要求系統 將文字從英文翻譯成法文

      projects/PROJECT_NUMBER/locations/LOCATION/collections/default_collection/engines/ENGINE_NAME/servingConfigs/default_search

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora" \
    -d '{
      "display_name" : "DISPLAY_NAME",
      "vertex_ai_search_config" : {
        "serving_config": "ENGINE_NAME/servingConfigs/default_search"
      }
    }'
    
  2. 監控進度

    請替換程式碼範例中使用的下列變數:

    • PROJECT_ID:專案的 ID。 Google Cloud
    • LOCATION:處理要求的區域。
    • OPERATION_ID:RAG 語料庫建立作業的 ID。
    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID"
    

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Agent Platform 快速入門導覽課程」中的 Python 設定說明操作。

如要向 Agent Platform 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。


import agentplatform
from agentplatform import types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# vertex_ai_search_engine_name = "projects/{PROJECT_ID}/locations/{LOCATION}/collections/default_collection/engines/{ENGINE_ID}"
# display_name = "test_corpus"
# description = "Corpus Description"

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

# Configure Search
vertex_ai_search_config = types.VertexAiSearchConfig(
    serving_config=f"{vertex_ai_search_engine_name}/servingConfigs/default_search",
)

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

使用 RAG API 擷取背景資訊

建立 RAG 語料庫後,即可透過 RetrieveContexts API 從 Agent Search 檢索相關內容。

REST

這個程式碼範例示範如何使用 REST 擷取環境。

請替換程式碼範例中使用的下列變數:

  • PROJECT_ID:專案的 ID。 Google Cloud
  • LOCATION:處理要求的區域。
  • RAG_CORPUS_RESOURCE:RAG 語料庫資源的名稱。

    格式: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}.

  • TEXT:要取得相關情境的查詢文字。
curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts" \
  -d '{
    "vertex_rag_store": {
      "rag_resources": {
        "rag_corpus": "RAG_CORPUS_RESOURCE"
      }
    },
    "query": {
      "text": "TEXT"
    }
  }'

Python

如要瞭解如何安裝或更新 Vertex AI SDK for Python,請參閱「安裝 Vertex AI SDK for 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: "....
#   ....

使用 Agent Platform Gemini API 生成內容

REST

如要使用 Gemini 模型生成內容,請呼叫 Agent Platform GenerateContent API。在要求中指定 RAG_CORPUS_RESOURCE,即可自動從 Agent Search 擷取資料。

請替換程式碼範例中使用的下列變數:

  • PROJECT_ID:專案的 ID。 Google Cloud

  • LOCATION:處理要求的區域。

  • MODEL_ID:用於生成內容的 LLM 模型。例如:gemini-2.0-flash

  • GENERATION_METHOD:用於生成內容的 LLM 方法。 例如 generateContentstreamGenerateContent

  • INPUT_PROMPT:傳送至 LLM 的文字,用於生成內容。請嘗試使用與 Agent Search 中的文件相關的提示。

  • RAG_CORPUS_RESOURCE:RAG 語料庫資源的名稱。格式: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}

  • SIMILARITY_TOP_K:(選填) 要擷取的重要上下文數量。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD" \
    -d '{
      "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
          }
        }
      }
    }'
    

Python

如要瞭解如何安裝或更新 Vertex AI SDK for Python,請參閱「安裝 Vertex AI SDK for 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....
#   ...

後續步驟