-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathviking_database.py
More file actions
396 lines (350 loc) · 13.4 KB
/
viking_database.py
File metadata and controls
396 lines (350 loc) · 13.4 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
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import io
import json
import os
import uuid
from typing import Any, BinaryIO, Literal, Optional, TextIO
import requests
import tos
from pydantic import BaseModel, Field
from volcengine.auth.SignerV4 import SignerV4
from volcengine.base.Request import Request
from volcengine.Credentials import Credentials
from veadk.config import getenv
from veadk.database.base_database import BaseDatabase
from veadk.utils.logger import get_logger
logger = get_logger(__name__)
# knowledge base domain
g_knowledge_base_domain = "api-knowledgebase.mlp.cn-beijing.volces.com"
# paths
create_collection_path = "/api/knowledge/collection/create"
search_knowledge_path = "/api/knowledge/collection/search_knowledge"
list_collections_path = "/api/knowledge/collection/list"
get_collections_path = "/api/knowledge/collection/info"
doc_add_path = "/api/knowledge/doc/add"
doc_info_path = "/api/knowledge/doc/info"
doc_del_path = "/api/collection/drop"
class VolcengineTOSConfig(BaseModel):
endpoint: Optional[str] = Field(
default=getenv("DATABASE_TOS_ENDPOINT", "tos-cn-beijing.volces.com"),
description="VikingDB TOS endpoint",
)
region: Optional[str] = Field(
default=getenv("DATABASE_TOS_REGION", "cn-beijing"),
description="VikingDB TOS region",
)
bucket: Optional[str] = Field(
default=getenv("DATABASE_TOS_BUCKET"),
description="VikingDB TOS bucket",
)
base_key: Optional[str] = Field(
default="veadk",
description="VikingDB TOS base key",
)
class VikingDatabaseConfig(BaseModel):
volcengine_ak: Optional[str] = Field(
default=getenv("VOLCENGINE_ACCESS_KEY"),
description="VikingDB access key",
)
volcengine_sk: Optional[str] = Field(
default=getenv("VOLCENGINE_SECRET_KEY"),
description="VikingDB secret key",
)
project: Optional[str] = Field(
default=getenv("DATABASE_VIKING_PROJECT"),
description="VikingDB project name",
)
region: Optional[str] = Field(
default=getenv("DATABASE_VIKING_REGION"),
description="VikingDB region",
)
tos: Optional[VolcengineTOSConfig] = Field(
default_factory=VolcengineTOSConfig,
description="VikingDB TOS configuration",
)
def prepare_request(
method, path, config: VikingDatabaseConfig, params=None, data=None, doseq=0
):
ak = config.volcengine_ak
sk = config.volcengine_sk
if params:
for key in params:
if (
type(params[key]) is int
or type(params[key]) is float
or type(params[key]) is bool
):
params[key] = str(params[key])
elif type(params[key]) is list:
if not doseq:
params[key] = ",".join(params[key])
r = Request()
r.set_shema("https")
r.set_method(method)
r.set_connection_timeout(10)
r.set_socket_timeout(10)
mheaders = {
"Accept": "application/json",
"Content-Type": "application/json",
}
r.set_headers(mheaders)
if params:
r.set_query(params)
r.set_path(path)
if data is not None:
r.set_body(json.dumps(data))
credentials = Credentials(ak, sk, "air", config.region)
SignerV4.sign(r, credentials)
return r
class VikingDatabase(BaseModel, BaseDatabase):
config: VikingDatabaseConfig = Field(
default_factory=VikingDatabaseConfig,
description="VikingDB configuration",
)
def _upload_to_tos(
self,
data: str | list[str] | TextIO | BinaryIO | bytes,
**kwargs: Any,
):
file_ext = kwargs.get(
"file_ext", ".pdf"
) # when bytes data, file_ext is required
ak = self.config.volcengine_ak
sk = self.config.volcengine_sk
tos_bucket = self.config.tos.bucket
tos_endpoint = self.config.tos.endpoint
tos_region = self.config.tos.region
tos_key = self.config.tos.base_key
client = tos.TosClientV2(ak, sk, tos_endpoint, tos_region, max_connections=1024)
if isinstance(data, str) and os.path.isfile(data): # Process file path
file_ext = os.path.splitext(data)[1]
new_key = f"{tos_key}/{str(uuid.uuid4())}{file_ext}"
with open(data, "rb") as f:
upload_data = f.read()
elif isinstance(
data,
(io.TextIOWrapper, io.BufferedReader), # file type: TextIO | BinaryIO
): # Process file stream
# Try to get the file extension from the file name, and use the default value if there is none
file_ext = ".unknown"
if hasattr(data, "name"):
_, file_ext = os.path.splitext(data.name)
new_key = f"{tos_key}/{str(uuid.uuid4())}{file_ext}"
if isinstance(data, TextIO):
# Encode the text stream content into bytes
upload_data = data.read().encode("utf-8")
else:
# Read the content of the binary stream
upload_data = data.read()
elif isinstance(data, str): # Process ordinary strings
new_key = f"{tos_key}/{str(uuid.uuid4())}.txt"
upload_data = data.encode("utf-8") # Encode as byte type
elif isinstance(data, list): # Process list of strings
new_key = f"{tos_key}/{str(uuid.uuid4())}.txt"
# Join the strings in the list with newlines and encode as byte type
upload_data = "\n".join(data).encode("utf-8")
elif isinstance(data, bytes): # Process bytes data
new_key = f"{tos_key}/{str(uuid.uuid4())}{file_ext}"
upload_data = data
else:
raise ValueError(f"Unsupported data type: {type(data)}")
resp = client.put_object(tos_bucket, new_key, content=upload_data)
tos_url = f"{tos_bucket}/{new_key}"
return resp.resp.status, tos_url
def _add_doc(self, collection_name: str, tos_url: str, doc_id: str, **kwargs: Any):
request_params = {
"collection_name": collection_name,
"project": self.config.project,
"add_type": "tos",
"doc_id": doc_id,
"tos_path": tos_url,
}
doc_add_req = prepare_request(
method="POST", path=doc_add_path, config=self.config, data=request_params
)
rsp = requests.request(
method=doc_add_req.method,
url="https://{}{}".format(g_knowledge_base_domain, doc_add_req.path),
headers=doc_add_req.headers,
data=doc_add_req.body,
)
result = rsp.json()
if result["code"] != 0:
logger.error(f"Error in add_doc: {result['message']}")
return {"error": result["message"]}
doc_add_data = result["data"]
if not doc_add_data:
raise ValueError(f"doc {doc_id} has no data.")
return doc_id
def add(
self,
data: str | list[str] | TextIO | BinaryIO | bytes,
collection_name: str,
**kwargs,
):
"""
Args:
data: str, file path or file stream: Both file or file.read() are acceptable.
**kwargs: collection_name(required)
Returns:
{
"tos_url": "tos://<bucket>/<key>",
"doc_id": "<doc_id>",
}
"""
status, tos_url = self._upload_to_tos(data=data, **kwargs)
if status != 200:
raise ValueError(f"Error in upload_to_tos: {status}")
doc_id = self._add_doc(
collection_name=collection_name,
tos_url=tos_url,
doc_id=str(uuid.uuid4()),
)
return {
"tos_url": f"tos://{tos_url}",
"doc_id": doc_id,
}
def delete(self, **kwargs: Any):
collection_name = kwargs.get("collection_name")
resource_id = kwargs.get("resource_id")
request_param = {"collection_name": collection_name, "resource_id": resource_id}
doc_del_req = prepare_request(
method="POST", path=doc_del_path, config=self.config, data=request_param
)
rsp = requests.request(
method=doc_del_req.method,
url="http://{}{}".format(g_knowledge_base_domain, doc_del_req.path),
headers=doc_del_req.headers,
data=doc_del_req.body,
)
result = rsp.json()
if result["code"] != 0:
logger.error(f"Error in add_doc: {result['message']}")
return {"error": result["message"]}
return {}
def query(self, query: str, **kwargs: Any) -> list[str]:
"""
Args:
query: query text
**kwargs: collection_name(required), top_k(optional, default 5)
Returns: list of str, the search result
"""
collection_name = kwargs.get("collection_name")
assert collection_name is not None, "collection_name is required"
request_params = {
"query": query,
"limit": int(kwargs.get("top_k", 5)),
"name": collection_name,
"project": self.config.project,
}
search_req = prepare_request(
method="POST",
path=search_knowledge_path,
config=self.config,
data=request_params,
)
resp = requests.request(
method=search_req.method,
url="https://{}{}".format(g_knowledge_base_domain, search_req.path),
headers=search_req.headers,
data=search_req.body,
)
result = resp.json()
if result["code"] != 0:
logger.error(f"Error in search_knowledge: {result['message']}")
raise ValueError(f"Error in search_knowledge: {result['message']}")
if not result["data"]["result_list"]:
raise ValueError(f"No results found for collection {collection_name}")
chunks = result["data"]["result_list"]
search_result = []
for chunk in chunks:
search_result.append(chunk["content"])
return search_result
def create_collection(
self,
collection_name: str,
description: str = "",
version: Literal[2, 4] = 4,
data_type: Literal[
"unstructured_data", "structured_data"
] = "unstructured_data",
chunking_strategy: Literal["custom_balance", "custom"] = "custom_balance",
chunk_length: int = 500,
merge_small_chunks: bool = True,
):
request_params = {
"name": collection_name,
"project": self.config.project,
"description": description,
"version": version,
"data_type": data_type,
"preprocessing": {
"chunking_strategy": chunking_strategy,
"chunk_length": chunk_length,
"merge_small_chunks": merge_small_chunks,
},
}
create_collection_req = prepare_request(
method="POST",
path=create_collection_path,
config=self.config,
data=request_params,
)
resp = requests.request(
method=create_collection_req.method,
url="https://{}{}".format(
g_knowledge_base_domain, create_collection_req.path
),
headers=create_collection_req.headers,
data=create_collection_req.body,
)
result = resp.json()
if result["code"] != 0:
logger.error(f"Error in create_collection: {result['message']}")
raise ValueError(f"Error in create_collection: {result['message']}")
return result
def collection_exists(self, collection_name: str) -> bool:
request_params = {
"project": self.config.project,
}
list_collections_req = prepare_request(
method="POST",
path=list_collections_path,
config=self.config,
data=request_params,
)
resp = requests.request(
method=list_collections_req.method,
url="https://{}{}".format(
g_knowledge_base_domain, list_collections_req.path
),
headers=list_collections_req.headers,
data=list_collections_req.body,
)
result = resp.json()
if result["code"] != 0:
logger.error(f"Error in list_collections: {result['message']}")
raise ValueError(f"Error in list_collections: {result['message']}")
collections = result["data"]["collection_list"]
if not collections:
raise ValueError(f"No collections found in project {self.config.project}.")
collection_list = set()
for collection in collections:
collection_list.add(collection["collection_name"])
# check the collection exist or not
if collection_name in collection_list:
return True
else:
return False