|
| 1 | +# Copyright 2025 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 | +# http://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 | +from typing import Any |
| 18 | +from typing import Optional |
| 19 | + |
| 20 | +from google.api_core.exceptions import GoogleAPICallError |
| 21 | +import google.auth |
| 22 | +from google.cloud import discoveryengine_v1beta as discoveryengine |
| 23 | +from google.genai import types |
| 24 | + |
| 25 | +from .function_tool import FunctionTool |
| 26 | + |
| 27 | + |
| 28 | +class DiscoveryEngineSearchTool(FunctionTool): |
| 29 | + """Tool for searching the discovery engine.""" |
| 30 | + |
| 31 | + def __init__( |
| 32 | + self, |
| 33 | + data_store_id: Optional[str] = None, |
| 34 | + data_store_specs: Optional[ |
| 35 | + list[types.VertexAISearchDataStoreSpec] |
| 36 | + ] = None, |
| 37 | + search_engine_id: Optional[str] = None, |
| 38 | + filter: Optional[str] = None, |
| 39 | + max_results: Optional[int] = None, |
| 40 | + ): |
| 41 | + """Initializes the DiscoveryEngineSearchTool. |
| 42 | +
|
| 43 | + Args: |
| 44 | + data_store_id: The Vertex AI search data store resource ID in the format |
| 45 | + of |
| 46 | + "projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}". |
| 47 | + data_store_specs: Specifications that define the specific DataStores to be |
| 48 | + searched. It should only be set if engine is used. |
| 49 | + search_engine_id: The Vertex AI search engine resource ID in the format of |
| 50 | + "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}". |
| 51 | + filter: The filter to be applied to the search request. Default is None. |
| 52 | + max_results: The maximum number of results to return. Default is None. |
| 53 | + """ |
| 54 | + super().__init__(self.discovery_engine_search) |
| 55 | + if (data_store_id is None and search_engine_id is None) or ( |
| 56 | + data_store_id is not None and search_engine_id is not None |
| 57 | + ): |
| 58 | + raise ValueError( |
| 59 | + "Either data_store_id or search_engine_id must be specified." |
| 60 | + ) |
| 61 | + if data_store_specs is not None and search_engine_id is None: |
| 62 | + raise ValueError( |
| 63 | + "search_engine_id must be specified if data_store_specs is specified." |
| 64 | + ) |
| 65 | + |
| 66 | + self._serving_config = ( |
| 67 | + f"{data_store_id or search_engine_id}/servingConfigs/default_config" |
| 68 | + ) |
| 69 | + self._data_store_specs = data_store_specs |
| 70 | + self._search_engine_id = search_engine_id |
| 71 | + self._filter = filter |
| 72 | + self._max_results = max_results |
| 73 | + |
| 74 | + credentials, _ = google.auth.default() |
| 75 | + self._discovery_engine_client = discoveryengine.SearchServiceClient( |
| 76 | + credentials=credentials |
| 77 | + ) |
| 78 | + |
| 79 | + def discovery_engine_search( |
| 80 | + self, |
| 81 | + query: str, |
| 82 | + ) -> dict[str, Any]: |
| 83 | + """Search the discovery engine. |
| 84 | +
|
| 85 | + Args: |
| 86 | + query: The search query. |
| 87 | +
|
| 88 | + Returns: |
| 89 | + A dictionary containing the status of the request and the list of search |
| 90 | + results, which contains the title, url and content. |
| 91 | + """ |
| 92 | + request = discoveryengine.SearchRequest( |
| 93 | + serving_config=self._serving_config, |
| 94 | + query=query, |
| 95 | + content_search_spec=discoveryengine.SearchRequest.ContentSearchSpec( |
| 96 | + search_result_mode=discoveryengine.SearchRequest.ContentSearchSpec.SearchResultMode.CHUNKS, |
| 97 | + chunk_spec=discoveryengine.SearchRequest.ContentSearchSpec.ChunkSpec( |
| 98 | + num_previous_chunks=0, |
| 99 | + num_next_chunks=0, |
| 100 | + ), |
| 101 | + ), |
| 102 | + ) |
| 103 | + |
| 104 | + if self._data_store_specs: |
| 105 | + request.data_store_specs = self._data_store_specs |
| 106 | + if self._filter: |
| 107 | + request.filter = self._filter |
| 108 | + if self._max_results: |
| 109 | + request.page_size = self._max_results |
| 110 | + |
| 111 | + results = [] |
| 112 | + try: |
| 113 | + response = self._discovery_engine_client.search(request) |
| 114 | + for item in response.results: |
| 115 | + chunk = item.chunk |
| 116 | + if not chunk or not chunk.document_metadata: |
| 117 | + continue |
| 118 | + |
| 119 | + results.append({ |
| 120 | + "title": chunk.document_metadata.title, |
| 121 | + "url": chunk.document_metadata.uri, |
| 122 | + "content": chunk.content, |
| 123 | + }) |
| 124 | + except GoogleAPICallError as e: |
| 125 | + return {"status": "error", "error_message": str(e)} |
| 126 | + return {"status": "success", "results": results} |
0 commit comments