-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathcontext_grounding_service.py
More file actions
405 lines (345 loc) · 13.1 KB
/
context_grounding_service.py
File metadata and controls
405 lines (345 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import json
from typing import Any, Dict, List, Optional
from pydantic import TypeAdapter
from .._config import Config
from .._execution_context import ExecutionContext
from .._folder_context import FolderContext
from .._utils import Endpoint, RequestSpec
from .._utils.constants import (
HEADER_FOLDER_KEY,
HEADER_FOLDER_PATH,
ORCHESTRATOR_STORAGE_BUCKET_DATA_SOURCE,
)
from ..models import IngestionInProgressException
from ..models.context_grounding import ContextGroundingQueryResponse
from ..models.context_grounding_index import ContextGroundingIndex
from ._base_service import BaseService
from .folder_service import FolderService
class ContextGroundingService(FolderContext, BaseService):
"""Service for managing semantic automation contexts in UiPath.
Context Grounding is a feature that helps in understanding and managing the
semantic context in which automation processes operate. It provides capabilities
for indexing, retrieving, and searching through contextual information that
can be used to enhance AI-enabled automation.
This service requires a valid folder key to be set in the environment, as
context grounding operations are always performed within a specific folder
context.
"""
def __init__(
self,
config: Config,
execution_context: ExecutionContext,
folders_service: FolderService,
) -> None:
self._folders_service = folders_service
super().__init__(config=config, execution_context=execution_context)
def retrieve(self, name: str) -> Optional[ContextGroundingIndex]:
"""Retrieve context grounding index information by its name.
This method fetches details about a specific context index, which can be
used to understand what type of contextual information is available for
automation processes.
Args:
name (str): The name of the context index to retrieve.
Returns:
Optional[ContextGroundingIndex]: The index information, including its configuration and metadata if found, otherwise None.
"""
spec = self._retrieve_spec(name)
response = self.request(
spec.method,
spec.endpoint,
params=spec.params,
).json()
return next(
(
ContextGroundingIndex.model_validate(item)
for item in response["value"]
if item["name"] == name
),
None,
)
async def retrieve_async(self, name: str) -> Optional[ContextGroundingIndex]:
"""Retrieve asynchronously context grounding index information by its name.
This method fetches details about a specific context index, which can be
used to understand what type of contextual information is available for
automation processes.
Args:
name (str): The name of the context index to retrieve.
Returns:
Optional[ContextGroundingIndex]: The index information, including its configuration and metadata if found, otherwise None.
"""
spec = self._retrieve_spec(name)
response = (
await self.request_async(
spec.method,
spec.endpoint,
params=spec.params,
)
).json()
return next(
(
ContextGroundingIndex.model_validate(item)
for item in response["value"]
if item["name"] == name
),
None,
)
def retrieve_by_id(self, id: str) -> Any:
"""Retrieve context grounding index information by its ID.
This method provides direct access to a context index using its unique
identifier, which can be more efficient than searching by name.
Args:
id (str): The unique identifier of the context index.
Returns:
Any: The index information, including its configuration and metadata.
"""
spec = self._retrieve_by_id_spec(id)
return self.request(
spec.method,
spec.endpoint,
params=spec.params,
).json()
async def retrieve_by_id_async(self, id: str) -> Any:
"""Retrieve asynchronously context grounding index information by its ID.
This method provides direct access to a context index using its unique
identifier, which can be more efficient than searching by name.
Args:
id (str): The unique identifier of the context index.
Returns:
Any: The index information, including its configuration and metadata.
"""
spec = self._retrieve_by_id_spec(id)
response = await self.request_async(
spec.method,
spec.endpoint,
params=spec.params,
)
return response.json()
def search(
self,
name: str,
query: str,
number_of_results: int = 10,
) -> List[ContextGroundingQueryResponse]:
"""Search for contextual information within a specific index.
This method performs a semantic search against the specified context index,
helping to find relevant information that can be used in automation processes.
The search is powered by AI and understands natural language queries.
Args:
name (str): The name of the context index to search in.
query (str): The search query in natural language.
number_of_results (int, optional): Maximum number of results to return.
Defaults to 10.
Returns:
List[ContextGroundingQueryResponse]: A list of search results, each containing
relevant contextual information and metadata.
"""
index = self.retrieve(name)
if index and index.in_progress_ingestion():
raise IngestionInProgressException(index_name=name)
spec = self._search_spec(name, query, number_of_results)
response = self.request(
spec.method,
spec.endpoint,
content=spec.content,
)
return TypeAdapter(List[ContextGroundingQueryResponse]).validate_python(
response.json()
)
async def search_async(
self,
name: str,
query: str,
number_of_results: int = 10,
) -> List[ContextGroundingQueryResponse]:
"""Search asynchronously for contextual information within a specific index.
This method performs a semantic search against the specified context index,
helping to find relevant information that can be used in automation processes.
The search is powered by AI and understands natural language queries.
Args:
name (str): The name of the context index to search in.
query (str): The search query in natural language.
number_of_results (int, optional): Maximum number of results to return.
Defaults to 10.
Returns:
List[ContextGroundingQueryResponse]: A list of search results, each containing
relevant contextual information and metadata.
"""
index = self.retrieve(name)
if index and index.in_progress_ingestion():
raise IngestionInProgressException(index_name=name)
spec = self._search_spec(name, query, number_of_results)
response = await self.request_async(
spec.method,
spec.endpoint,
content=spec.content,
)
return TypeAdapter(List[ContextGroundingQueryResponse]).validate_python(
response.json()
)
def get_or_create_index(
self,
name: str,
*,
description: Optional[str] = None,
storage_bucket_name: str,
file_name_glob: Optional[str] = None,
storage_bucket_folder_path: Optional[str] = None,
) -> ContextGroundingIndex:
spec = self._create_spec(
name,
description,
storage_bucket_name,
file_name_glob,
storage_bucket_folder_path,
)
index = self.retrieve(name=name)
if index:
return index
response = self.request(
spec.method,
spec.endpoint,
content=spec.content,
headers=spec.headers,
).json()
return ContextGroundingIndex.model_validate(response)
async def get_or_create_index_async(
self,
name: str,
*,
description: Optional[str] = None,
storage_bucket_name: str,
file_name_glob: Optional[str] = None,
storage_bucket_folder_path: Optional[str] = None,
) -> ContextGroundingIndex:
index = await self.retrieve_async(name=name)
if index:
return index
spec = self._create_spec(
name,
description,
storage_bucket_name,
file_name_glob,
storage_bucket_folder_path,
)
response = (
await self.request_async(
spec.method,
spec.endpoint,
content=spec.content,
headers=spec.headers,
)
).json()
return ContextGroundingIndex.model_validate(response)
def ingest_data(self, index: ContextGroundingIndex) -> None:
if not index.id:
return
spec = self._ingest_spec(index.id)
self.request(
spec.method,
spec.endpoint,
headers=spec.headers,
)
async def ingest_data_async(self, index: ContextGroundingIndex) -> None:
if not index.id:
return
spec = self._ingest_spec(index.id)
await self.request_async(
spec.method,
spec.endpoint,
headers=spec.headers,
)
def delete_index(self, index: ContextGroundingIndex) -> None:
if not index.id:
return
spec = self._delete_by_id_spec(index.id)
self.request(
spec.method,
spec.endpoint,
headers=spec.headers,
)
async def delete_index_async(self, index: ContextGroundingIndex) -> None:
if not index.id:
return
spec = self._delete_by_id_spec(index.id)
await self.request_async(
spec.method,
spec.endpoint,
headers=spec.headers,
)
@property
def custom_headers(self) -> Dict[str, str]:
self._folder_key = self._folder_key or (
self._folders_service.retrieve_key_by_folder_path(self._folder_path)
if self._folder_path
else None
)
if self._folder_key is None:
raise ValueError(
f"Neither the folder key nor the folder path is set ({HEADER_FOLDER_KEY}, {HEADER_FOLDER_PATH})"
)
return self.folder_headers
def _ingest_spec(self, key: str) -> RequestSpec:
return RequestSpec(
method="POST", endpoint=Endpoint(f"/ecs_/v2/indexes/{key}/ingest")
)
def _retrieve_spec(self, name: str) -> RequestSpec:
return RequestSpec(
method="GET",
endpoint=Endpoint("/ecs_/v2/indexes"),
params={"$filter": f"Name eq '{name}'"},
)
def _create_spec(
self,
name: str,
description: Optional[str],
storage_bucket_name: Optional[str],
file_name_glob: Optional[str],
storage_bucket_folder_path: Optional[str],
) -> RequestSpec:
storage_bucket_folder_path = (
storage_bucket_folder_path
if storage_bucket_folder_path
else self._folder_path
)
return RequestSpec(
method="POST",
endpoint=Endpoint("/ecs_/v2/indexes/create"),
content=json.dumps(
{
"name": name,
"description": description,
"dataSource": {
"@odata.type": ORCHESTRATOR_STORAGE_BUCKET_DATA_SOURCE,
"folder": storage_bucket_folder_path,
"bucketName": storage_bucket_name,
"fileNameGlob": file_name_glob
if file_name_glob is not None
else "*",
"directoryPath": "/",
},
}
),
)
def _retrieve_by_id_spec(self, id: str) -> RequestSpec:
return RequestSpec(
method="GET",
endpoint=Endpoint(f"/ecs_/v2/indexes/{id}"),
)
def _delete_by_id_spec(self, id: str) -> RequestSpec:
return RequestSpec(
method="DELETE",
endpoint=Endpoint(f"/ecs_/v2/indexes/{id}"),
)
def _search_spec(
self, name: str, query: str, number_of_results: int = 10
) -> RequestSpec:
return RequestSpec(
method="POST",
endpoint=Endpoint("/ecs_/v1/search"),
content=json.dumps(
{
"query": {"query": query, "numberOfResults": number_of_results},
"schema": {"name": name},
}
),
)