agentic-kit-common 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of agentic-kit-common might be problematic. Click here for more details.

File without changes
@@ -0,0 +1,113 @@
1
+ import os
2
+ import yaml
3
+ import json
4
+ import logging
5
+ from typing import Dict, Any, List
6
+
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ def load_config(config_path: str = None) -> Dict[str, Any]:
11
+ """从配置文件加载配置信息,支持多重路径查找"""
12
+
13
+ if config_path is not None:
14
+ # 如果指定了配置路径,直接使用
15
+ return _load_single_config(config_path)
16
+
17
+ # 多重路径查找策略
18
+ search_paths = _get_config_search_paths()
19
+
20
+ for path in search_paths:
21
+ if os.path.exists(path):
22
+ logger.info(f"找到配置文件: {path}")
23
+ return _load_single_config(path)
24
+
25
+ logger.warning(f"在以下路径中都未找到配置文件: {search_paths}")
26
+ return {}
27
+
28
+ def _get_config_search_paths() -> List[str]:
29
+ """获取配置文件的搜索路径列表"""
30
+ current_file = os.path.abspath(__file__)
31
+ paths = []
32
+
33
+ # 1. 包根目录 (agentic_kit_common/)
34
+ package_root = os.path.dirname(os.path.dirname(current_file))
35
+ paths.extend([
36
+ os.path.join(package_root, 'conf.yaml'),
37
+ os.path.join(package_root, 'config.yaml'),
38
+ os.path.join(package_root, 'config.json')
39
+ ])
40
+
41
+ # 2. 项目根目录的上一层(如果包在子目录中)
42
+ project_parent = os.path.dirname(package_root)
43
+ paths.extend([
44
+ os.path.join(project_parent, 'conf.yaml'),
45
+ os.path.join(project_parent, 'config.yaml'),
46
+ os.path.join(project_parent, 'config.json')
47
+ ])
48
+
49
+ # 3. 当前工作目录
50
+ cwd = os.getcwd()
51
+ paths.extend([
52
+ os.path.join(cwd, 'conf.yaml'),
53
+ os.path.join(cwd, 'config.yaml'),
54
+ os.path.join(cwd, 'config.json')
55
+ ])
56
+
57
+ # 4. 用户主目录
58
+ home_dir = os.path.expanduser('~')
59
+ paths.extend([
60
+ os.path.join(home_dir, '.agentic_kit_common', 'conf.yaml'),
61
+ os.path.join(home_dir, '.agentic_kit_common', 'config.yaml'),
62
+ os.path.join(home_dir, '.agentic_kit_common', 'config.json')
63
+ ])
64
+
65
+ # 5. 环境变量指定的路径
66
+ env_config_path = os.environ.get('AGENTIC_KIT_CONFIG')
67
+ if env_config_path:
68
+ paths.insert(0, env_config_path) # 环境变量路径优先级最高
69
+
70
+ # 6. /etc 系统配置目录 (Linux/Mac)
71
+ if os.name != 'nt': # 非Windows系统
72
+ paths.extend([
73
+ '/etc/agentic_kit_common/conf.yaml',
74
+ '/etc/agentic_kit_common/config.yaml',
75
+ '/etc/agentic_kit_common/config.json'
76
+ ])
77
+
78
+ return paths
79
+
80
+ def _load_single_config(config_path: str) -> Dict[str, Any]:
81
+ """加载单个配置文件"""
82
+ if not os.path.exists(config_path):
83
+ logger.warning(f"配置文件不存在: {config_path}")
84
+ return {}
85
+
86
+ try:
87
+ with open(config_path, 'r', encoding='utf-8') as f:
88
+ if config_path.endswith('.yaml') or config_path.endswith('.yml'):
89
+ config = yaml.safe_load(f)
90
+ elif config_path.endswith('.json'):
91
+ config = json.load(f)
92
+ else:
93
+ logger.error(f"不支持的配置文件格式: {config_path}")
94
+ return {}
95
+
96
+ logger.info(f"成功加载配置文件: {config_path}")
97
+ return config or {}
98
+
99
+ except Exception as e:
100
+ logger.error(f"读取配置文件失败: {config_path}, 错误: {str(e)}")
101
+ return {}
102
+
103
+ def get_config_info() -> Dict[str, Any]:
104
+ """获取配置加载信息,用于调试"""
105
+ search_paths = _get_config_search_paths()
106
+ info = {
107
+ 'search_paths': search_paths,
108
+ 'existing_paths': [path for path in search_paths if os.path.exists(path)],
109
+ 'current_file': __file__,
110
+ 'working_directory': os.getcwd(),
111
+ 'env_config_path': os.environ.get('AGENTIC_KIT_CONFIG')
112
+ }
113
+ return info
@@ -0,0 +1,684 @@
1
+ import os
2
+ from typing import Optional, BinaryIO, Union, List, Dict
3
+ from datetime import timedelta
4
+ from minio import Minio
5
+ from minio.error import S3Error
6
+ from io import BytesIO
7
+ import logging
8
+ from urllib3.exceptions import HTTPError
9
+
10
+ # 配置日志
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class MinioManager:
16
+ """
17
+ MinIO 客户端封装类
18
+
19
+ 提供对 MinIO 的常用操作封装,包括:
20
+ - 文件上传/下载
21
+ - 文件管理(列表/删除/检查存在)
22
+ - 生成预签名URL
23
+ - 桶管理
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ endpoint: str,
29
+ access_key: str,
30
+ secret_key: str,
31
+ secure: bool = False,
32
+ region: Optional[str] = None,
33
+ http_client=None
34
+ ):
35
+ """
36
+ 初始化 MinIO 客户端
37
+
38
+ :param endpoint: MinIO 服务器地址 (e.g. 'play.min.io:9000')
39
+ :param access_key: 访问密钥
40
+ :param secret_key: 秘密密钥
41
+ :param secure: 是否使用 HTTPS (默认 False)
42
+ :param region: 区域名称 (可选)
43
+ :param http_client: 自定义 HTTP 客户端 (可选)
44
+ """
45
+ self.endpoint = endpoint
46
+ self.access_key = access_key
47
+ self.secret_key = secret_key
48
+ self.secure = secure
49
+ self.region = region
50
+ self.http_client = http_client
51
+
52
+ # 初始化 MinIO 客户端
53
+ self._client = Minio(
54
+ endpoint=endpoint,
55
+ access_key=access_key,
56
+ secret_key=secret_key,
57
+ secure=secure,
58
+ region=region,
59
+ http_client=http_client
60
+ )
61
+
62
+ def upload_file(
63
+ self,
64
+ bucket_name: str,
65
+ object_name: str,
66
+ file_path: str,
67
+ content_type: str = "application/octet-stream",
68
+ metadata: Optional[Dict] = None,
69
+ part_size: int = 10 * 1024 * 1024 # 10MB
70
+ ) -> bool:
71
+ """
72
+ 上传文件到 MinIO
73
+
74
+ :param bucket_name: 桶名称
75
+ :param object_name: 对象名称 (包含路径)
76
+ :param file_path: 本地文件路径
77
+ :param content_type: 文件内容类型
78
+ :param metadata: 元数据字典 (可选)
79
+ :param part_size: 分片大小 (字节)
80
+ :return: 是否成功
81
+ """
82
+ try:
83
+ if not os.path.isfile(file_path):
84
+ logger.error(f"File not found: {file_path}")
85
+ return False
86
+
87
+ # 确保桶存在
88
+ self._ensure_bucket_exists(bucket_name)
89
+
90
+ # 获取文件大小
91
+ file_size = os.path.getsize(file_path)
92
+
93
+ # 上传文件
94
+ self._client.fput_object(
95
+ bucket_name=bucket_name,
96
+ object_name=object_name,
97
+ file_path=file_path,
98
+ content_type=content_type,
99
+ metadata=metadata,
100
+ part_size=part_size
101
+ )
102
+
103
+ logger.info(
104
+ f"Successfully uploaded {file_path} as {object_name} to bucket {bucket_name}. "
105
+ f"File size: {file_size} bytes"
106
+ )
107
+ return True
108
+ except (S3Error, HTTPError) as e:
109
+ logger.error(f"Error uploading file {file_path} to MinIO: {str(e)}")
110
+ return False
111
+ except Exception as e:
112
+ logger.error(f"Unexpected error uploading file: {str(e)}")
113
+ return False
114
+
115
+ def upload_data(
116
+ self,
117
+ bucket_name: str,
118
+ object_name: str,
119
+ data: Union[bytes, BinaryIO],
120
+ length: int,
121
+ content_type: str = "application/octet-stream",
122
+ metadata: Optional[Dict] = None,
123
+ part_size: int = 10 * 1024 * 1024 # 10MB
124
+ ) -> bool:
125
+ """
126
+ 上传二进制数据到 MinIO
127
+
128
+ :param bucket_name: 桶名称
129
+ :param object_name: 对象名称 (包含路径)
130
+ :param data: 二进制数据或文件流
131
+ :param length: 数据长度
132
+ :param content_type: 内容类型
133
+ :param metadata: 元数据字典 (可选)
134
+ :param part_size: 分片大小 (字节)
135
+ :return: 是否成功
136
+ """
137
+ try:
138
+ # 确保桶存在
139
+ self._ensure_bucket_exists(bucket_name)
140
+
141
+ if isinstance(data, bytes):
142
+ data = BytesIO(data)
143
+
144
+ self._client.put_object(
145
+ bucket_name=bucket_name,
146
+ object_name=object_name,
147
+ data=data,
148
+ length=length,
149
+ content_type=content_type,
150
+ metadata=metadata,
151
+ part_size=part_size
152
+ )
153
+
154
+ logger.info(
155
+ f"Successfully uploaded data as {object_name} to bucket {bucket_name}. "
156
+ f"Data length: {length} bytes"
157
+ )
158
+ return True
159
+ except (S3Error, HTTPError) as e:
160
+ logger.error(f"Error uploading data to MinIO: {str(e)}")
161
+ return False
162
+ except Exception as e:
163
+ logger.error(f"Unexpected error uploading data: {str(e)}")
164
+ return False
165
+
166
+ def download_file(
167
+ self,
168
+ bucket_name: str,
169
+ object_name: str,
170
+ file_path: str
171
+ ) -> bool:
172
+ """
173
+ 从 MinIO 下载文件到本地
174
+
175
+ :param bucket_name: 桶名称
176
+ :param object_name: 对象名称 (包含路径)
177
+ :param file_path: 本地保存路径
178
+ :return: 是否成功
179
+ """
180
+ try:
181
+ # 确保目录存在
182
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
183
+
184
+ self._client.fget_object(
185
+ bucket_name=bucket_name,
186
+ object_name=object_name,
187
+ file_path=file_path
188
+ )
189
+
190
+ logger.info(
191
+ f"Successfully downloaded {object_name} from bucket {bucket_name} to {file_path}"
192
+ )
193
+ return True
194
+ except (S3Error, HTTPError) as e:
195
+ logger.error(f"Error downloading file {object_name} from MinIO: {str(e)}")
196
+ return False
197
+ except Exception as e:
198
+ logger.error(f"Unexpected error downloading file: {str(e)}")
199
+ return False
200
+
201
+ def download_data(
202
+ self,
203
+ bucket_name: str,
204
+ object_name: str
205
+ ) -> Optional[bytes]:
206
+ """
207
+ 从 MinIO 下载对象为二进制数据
208
+
209
+ :param bucket_name: 桶名称
210
+ :param object_name: 对象名称 (包含路径)
211
+ :return: 二进制数据或 None (如果失败)
212
+ """
213
+ try:
214
+ response = self._client.get_object(
215
+ bucket_name=bucket_name,
216
+ object_name=object_name
217
+ )
218
+
219
+ data = response.read()
220
+ response.close()
221
+ response.release_conn()
222
+
223
+ logger.info(
224
+ f"Successfully downloaded {object_name} from bucket {bucket_name}. "
225
+ f"Data length: {len(data)} bytes"
226
+ )
227
+ return data
228
+ except (S3Error, HTTPError) as e:
229
+ logger.error(f"Error downloading data {object_name} from MinIO: {str(e)}")
230
+ return None
231
+ except Exception as e:
232
+ logger.error(f"Unexpected error downloading data: {str(e)}")
233
+ return None
234
+
235
+ def list_objects(
236
+ self,
237
+ bucket_name: str,
238
+ prefix: str = "",
239
+ recursive: bool = False
240
+ ) -> List[Dict]:
241
+ """
242
+ 列出桶中的对象
243
+
244
+ :param bucket_name: 桶名称
245
+ :param prefix: 对象前缀 (可选)
246
+ :param recursive: 是否递归列出 (默认 False)
247
+ :return: 对象信息列表
248
+ """
249
+ try:
250
+ objects = self._client.list_objects(
251
+ bucket_name=bucket_name,
252
+ prefix=prefix,
253
+ recursive=recursive
254
+ )
255
+
256
+ result = []
257
+ for obj in objects:
258
+ result.append({
259
+ "name": obj.object_name,
260
+ "size": obj.size,
261
+ "last_modified": obj.last_modified,
262
+ "etag": obj.etag,
263
+ "is_dir": obj.is_dir
264
+ })
265
+
266
+ logger.info(
267
+ f"Listed {len(result)} objects from bucket {bucket_name} with prefix '{prefix}'"
268
+ )
269
+ return result
270
+ except (S3Error, HTTPError) as e:
271
+ logger.error(f"Error listing objects in bucket {bucket_name}: {str(e)}")
272
+ return []
273
+ except Exception as e:
274
+ logger.error(f"Unexpected error listing objects: {str(e)}")
275
+ return []
276
+
277
+ def delete_object(
278
+ self,
279
+ bucket_name: str,
280
+ object_name: str
281
+ ) -> bool:
282
+ """
283
+ 删除 MinIO 中的对象
284
+
285
+ :param bucket_name: 桶名称
286
+ :param object_name: 对象名称 (包含路径)
287
+ :return: 是否成功
288
+ """
289
+ try:
290
+ self._client.remove_object(
291
+ bucket_name=bucket_name,
292
+ object_name=object_name
293
+ )
294
+
295
+ logger.info(f"Successfully deleted {object_name} from bucket {bucket_name}")
296
+ return True
297
+ except (S3Error, HTTPError) as e:
298
+ logger.error(f"Error deleting object {object_name} from MinIO: {str(e)}")
299
+ return False
300
+ except Exception as e:
301
+ logger.error(f"Unexpected error deleting object: {str(e)}")
302
+ return False
303
+
304
+ def delete_objects(
305
+ self,
306
+ bucket_name: str,
307
+ object_names: List[str]
308
+ ) -> bool:
309
+ """
310
+ 批量删除 MinIO 中的对象
311
+
312
+ :param bucket_name: 桶名称
313
+ :param object_names: 对象名称列表
314
+ :return: 是否成功
315
+ """
316
+ try:
317
+ errors = self._client.remove_objects(
318
+ bucket_name=bucket_name,
319
+ object_names=object_names
320
+ )
321
+
322
+ # 检查是否有删除错误
323
+ has_errors = False
324
+ for error in errors:
325
+ logger.error(f"Error deleting object {error.object_name}: {error.message}")
326
+ has_errors = True
327
+
328
+ if has_errors:
329
+ return False
330
+
331
+ logger.info(f"Successfully deleted {len(object_names)} objects from bucket {bucket_name}")
332
+ return True
333
+ except (S3Error, HTTPError) as e:
334
+ logger.error(f"Error deleting objects from MinIO: {str(e)}")
335
+ return False
336
+ except Exception as e:
337
+ logger.error(f"Unexpected error deleting objects: {str(e)}")
338
+ return False
339
+
340
+ def object_exists(
341
+ self,
342
+ bucket_name: str,
343
+ object_name: str
344
+ ) -> bool:
345
+ """
346
+ 检查对象是否存在
347
+
348
+ :param bucket_name: 桶名称
349
+ :param object_name: 对象名称 (包含路径)
350
+ :return: 是否存在
351
+ """
352
+ try:
353
+ self._client.stat_object(
354
+ bucket_name=bucket_name,
355
+ object_name=object_name
356
+ )
357
+ return True
358
+ except S3Error as e:
359
+ if e.code == "NoSuchKey":
360
+ return False
361
+ logger.error(f"Error checking object existence: {str(e)}")
362
+ return False
363
+ except Exception as e:
364
+ logger.error(f"Unexpected error checking object existence: {str(e)}")
365
+ return False
366
+
367
+ def get_presigned_url(
368
+ self,
369
+ bucket_name: str,
370
+ object_name: str,
371
+ expires: timedelta = timedelta(days=7),
372
+ method: str = "GET"
373
+ ) -> Optional[str]:
374
+ """
375
+ 生成预签名 URL
376
+
377
+ :param bucket_name: 桶名称
378
+ :param object_name: 对象名称 (包含路径)
379
+ :param expires: URL 过期时间 (默认 7 天)
380
+ :param method: HTTP 方法 ("GET" 或 "PUT")
381
+ :return: 预签名 URL 或 None (如果失败)
382
+ """
383
+ try:
384
+ url = self._client.get_presigned_url(
385
+ method=method,
386
+ bucket_name=bucket_name,
387
+ object_name=object_name,
388
+ expires=expires
389
+ )
390
+
391
+ logger.info(f"Generated presigned URL for {object_name} in bucket {bucket_name}")
392
+ return url
393
+ except (S3Error, HTTPError) as e:
394
+ logger.error(f"Error generating presigned URL: {str(e)}")
395
+ return None
396
+ except Exception as e:
397
+ logger.error(f"Unexpected error generating presigned URL: {str(e)}")
398
+ return None
399
+
400
+ def create_bucket(
401
+ self,
402
+ bucket_name: str,
403
+ location: Optional[str] = None,
404
+ object_lock: bool = False
405
+ ) -> bool:
406
+ """
407
+ 创建桶
408
+
409
+ :param bucket_name: 桶名称
410
+ :param location: 区域位置 (可选)
411
+ :param object_lock: 是否启用对象锁定
412
+ :return: 是否成功
413
+ """
414
+ try:
415
+ self._client.make_bucket(
416
+ bucket_name=bucket_name,
417
+ location=location,
418
+ object_lock=object_lock
419
+ )
420
+
421
+ logger.info(f"Successfully created bucket {bucket_name}")
422
+ return True
423
+ except (S3Error, HTTPError) as e:
424
+ logger.error(f"Error creating bucket {bucket_name}: {str(e)}")
425
+ return False
426
+ except Exception as e:
427
+ logger.error(f"Unexpected error creating bucket: {str(e)}")
428
+ return False
429
+
430
+ def delete_bucket(
431
+ self,
432
+ bucket_name: str,
433
+ force: bool = False
434
+ ) -> bool:
435
+ """
436
+ 删除桶
437
+
438
+ :param bucket_name: 桶名称
439
+ :param force: 是否强制删除非空桶 (默认 False)
440
+ :return: 是否成功
441
+ """
442
+ try:
443
+ if force:
444
+ # 先删除桶中的所有对象
445
+ objects = self.list_objects(bucket_name, recursive=True)
446
+ object_names = [obj["name"] for obj in objects]
447
+ if object_names:
448
+ self.delete_objects(bucket_name, object_names)
449
+
450
+ self._client.remove_bucket(bucket_name)
451
+
452
+ logger.info(f"Successfully deleted bucket {bucket_name}")
453
+ return True
454
+ except (S3Error, HTTPError) as e:
455
+ logger.error(f"Error deleting bucket {bucket_name}: {str(e)}")
456
+ return False
457
+ except Exception as e:
458
+ logger.error(f"Unexpected error deleting bucket: {str(e)}")
459
+ return False
460
+
461
+ def bucket_exists(
462
+ self,
463
+ bucket_name: str
464
+ ) -> bool:
465
+ """
466
+ 检查桶是否存在
467
+
468
+ :param bucket_name: 桶名称
469
+ :return: 是否存在
470
+ """
471
+ try:
472
+ return self._client.bucket_exists(bucket_name)
473
+ except (S3Error, HTTPError) as e:
474
+ logger.error(f"Error checking bucket existence: {str(e)}")
475
+ return False
476
+ except Exception as e:
477
+ logger.error(f"Unexpected error checking bucket existence: {str(e)}")
478
+ return False
479
+
480
+ def _ensure_bucket_exists(
481
+ self,
482
+ bucket_name: str,
483
+ location: Optional[str] = None
484
+ ) -> bool:
485
+ """
486
+ 确保桶存在,如果不存在则创建
487
+
488
+ :param bucket_name: 桶名称
489
+ :param location: 区域位置 (可选)
490
+ :return: 是否成功
491
+ """
492
+ if self.bucket_exists(bucket_name):
493
+ return True
494
+
495
+ return self.create_bucket(bucket_name, location)
496
+
497
+ def get_object_metadata(
498
+ self,
499
+ bucket_name: str,
500
+ object_name: str
501
+ ) -> Optional[Dict]:
502
+ """
503
+ 获取对象元数据
504
+
505
+ :param bucket_name: 桶名称
506
+ :param object_name: 对象名称 (包含路径)
507
+ :return: 元数据字典或 None (如果失败)
508
+ """
509
+ try:
510
+ stat = self._client.stat_object(
511
+ bucket_name=bucket_name,
512
+ object_name=object_name
513
+ )
514
+
515
+ metadata = {
516
+ "size": stat.size,
517
+ "last_modified": stat.last_modified,
518
+ "content_type": stat.content_type,
519
+ "metadata": stat.metadata,
520
+ "version_id": stat.version_id,
521
+ "etag": stat.etag
522
+ }
523
+
524
+ logger.info(f"Retrieved metadata for {object_name} in bucket {bucket_name}")
525
+ return metadata
526
+ except (S3Error, HTTPError) as e:
527
+ logger.error(f"Error getting object metadata: {str(e)}")
528
+ return None
529
+ except Exception as e:
530
+ logger.error(f"Unexpected error getting object metadata: {str(e)}")
531
+ return None
532
+
533
+ def copy_object(
534
+ self,
535
+ source_bucket: str,
536
+ source_object: str,
537
+ dest_bucket: str,
538
+ dest_object: str,
539
+ metadata: Optional[Dict] = None
540
+ ) -> bool:
541
+ """
542
+ 复制对象
543
+
544
+ :param source_bucket: 源桶名称
545
+ :param source_object: 源对象名称
546
+ :param dest_bucket: 目标桶名称
547
+ :param dest_object: 目标对象名称
548
+ :param metadata: 新元数据 (可选)
549
+ :return: 是否成功
550
+ """
551
+ try:
552
+ self._ensure_bucket_exists(dest_bucket)
553
+
554
+ self._client.copy_object(
555
+ bucket_name=dest_bucket,
556
+ object_name=dest_object,
557
+ source=f"/{source_bucket}/{source_object}",
558
+ metadata=metadata
559
+ )
560
+
561
+ logger.info(
562
+ f"Successfully copied {source_bucket}/{source_object} "
563
+ f"to {dest_bucket}/{dest_object}"
564
+ )
565
+ return True
566
+ except (S3Error, HTTPError) as e:
567
+ logger.error(f"Error copying object: {str(e)}")
568
+ return False
569
+ except Exception as e:
570
+ logger.error(f"Unexpected error copying object: {str(e)}")
571
+ return False
572
+
573
+ def list_buckets(self) -> List[Dict]:
574
+ """
575
+ 列出所有桶
576
+
577
+ :return: 桶信息列表
578
+ """
579
+ try:
580
+ buckets = self._client.list_buckets()
581
+
582
+ result = []
583
+ for bucket in buckets:
584
+ result.append({
585
+ "name": bucket.name,
586
+ "creation_date": bucket.creation_date
587
+ })
588
+
589
+ logger.info(f"Listed {len(result)} buckets")
590
+ return result
591
+ except (S3Error, HTTPError) as e:
592
+ logger.error(f"Error listing buckets: {str(e)}")
593
+ return []
594
+ except Exception as e:
595
+ logger.error(f"Unexpected error listing buckets: {str(e)}")
596
+ return []
597
+
598
+ def set_bucket_policy(
599
+ self,
600
+ bucket_name: str,
601
+ policy: Union[str, Dict]
602
+ ) -> bool:
603
+ """
604
+ 设置桶策略
605
+
606
+ :param bucket_name: 桶名称
607
+ :param policy: 策略 JSON 字符串或字典
608
+ :return: 是否成功
609
+ """
610
+ try:
611
+ if isinstance(policy, dict):
612
+ import json
613
+ policy = json.dumps(policy)
614
+
615
+ self._client.set_bucket_policy(
616
+ bucket_name=bucket_name,
617
+ policy=policy
618
+ )
619
+
620
+ logger.info(f"Successfully set policy for bucket {bucket_name}")
621
+ return True
622
+ except (S3Error, HTTPError) as e:
623
+ logger.error(f"Error setting bucket policy: {str(e)}")
624
+ return False
625
+ except Exception as e:
626
+ logger.error(f"Unexpected error setting bucket policy: {str(e)}")
627
+ return False
628
+
629
+ def get_bucket_policy(
630
+ self,
631
+ bucket_name: str
632
+ ) -> Optional[Dict]:
633
+ """
634
+ 获取桶策略
635
+
636
+ :param bucket_name: 桶名称
637
+ :return: 策略字典或 None (如果失败)
638
+ """
639
+ try:
640
+ policy = self._client.get_bucket_policy(bucket_name)
641
+ import json
642
+ return json.loads(policy)
643
+ except (S3Error, HTTPError) as e:
644
+ logger.error(f"Error getting bucket policy: {str(e)}")
645
+ return None
646
+ except Exception as e:
647
+ logger.error(f"Unexpected error getting bucket policy: {str(e)}")
648
+ return None
649
+
650
+ def set_object_metadata(
651
+ self,
652
+ bucket_name: str,
653
+ object_name: str,
654
+ metadata: Dict
655
+ ) -> bool:
656
+ """
657
+ 设置对象元数据
658
+
659
+ :param bucket_name: 桶名称
660
+ :param object_name: 对象名称
661
+ :param metadata: 元数据字典
662
+ :return: 是否成功
663
+ """
664
+ try:
665
+ # 获取当前对象元数据
666
+ stat = self._client.stat_object(bucket_name, object_name)
667
+
668
+ # 复制对象以更新元数据
669
+ self._client.copy_object(
670
+ bucket_name=bucket_name,
671
+ object_name=object_name,
672
+ source=f"/{bucket_name}/{object_name}",
673
+ metadata=metadata,
674
+ metadata_directive="REPLACE"
675
+ )
676
+
677
+ logger.info(f"Successfully updated metadata for {object_name} in bucket {bucket_name}")
678
+ return True
679
+ except (S3Error, HTTPError) as e:
680
+ logger.error(f"Error setting object metadata: {str(e)}")
681
+ return False
682
+ except Exception as e:
683
+ logger.error(f"Unexpected error setting object metadata: {str(e)}")
684
+ return False
File without changes
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentic-kit-common
3
+ Version: 0.0.1
4
+ Summary: Common utilities and tools for agentic kit ecosystem, including MinIO manager and other shared components
5
+ Home-page:
6
+ Author: manson
7
+ Author-email: manson.li3307@gmail.com
8
+ Keywords: AI,LLM,Agent,MinIO,Storage,Common,Utilities
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Classifier: Topic :: System :: Distributed Computing
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: OS Independent
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ Requires-Dist: minio
20
+ Requires-Dist: urllib3
21
+ Requires-Dist: pydantic
22
+ Requires-Dist: requests
23
+ Requires-Dist: langchain_core
24
+ Requires-Dist: langgraph
25
+ Requires-Dist: langchain_community
26
+ Requires-Dist: langchain_experimental
27
+ Dynamic: author
28
+ Dynamic: author-email
29
+ Dynamic: classifier
30
+ Dynamic: description
31
+ Dynamic: description-content-type
32
+ Dynamic: keywords
33
+ Dynamic: requires-dist
34
+ Dynamic: requires-python
35
+ Dynamic: summary
36
+
37
+ # agentic_kit_common
38
+
39
+
40
+
41
+ ## Getting started
42
+
43
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
44
+
45
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
46
+
47
+ ## Add your files
48
+
49
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
50
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
51
+
52
+ ```
53
+ cd existing_repo
54
+ git remote add origin https://gitlab.aimanthor.com/shared/agentic_kit_common.git
55
+ git branch -M main
56
+ git push -uf origin main
57
+ ```
58
+
59
+ ## Integrate with your tools
60
+
61
+ - [ ] [Set up project integrations](https://git.aimanthor.com/shared/agentic_kit_common/-/settings/integrations)
62
+
63
+ ## Collaborate with your team
64
+
65
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
66
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
67
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
68
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
69
+ - [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
70
+
71
+ ## Test and Deploy
72
+
73
+ Use the built-in continuous integration in GitLab.
74
+
75
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
76
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
77
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
78
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
79
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
80
+
81
+ ***
82
+
83
+ # Editing this README
84
+
85
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
86
+
87
+ ## Suggestions for a good README
88
+
89
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
90
+
91
+ ## Name
92
+ Choose a self-explaining name for your project.
93
+
94
+ ## Description
95
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
96
+
97
+ ## Badges
98
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
99
+
100
+ ## Visuals
101
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
102
+
103
+ ## Installation
104
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
105
+
106
+ ## Usage
107
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
108
+
109
+ ## Support
110
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
111
+
112
+ ## Roadmap
113
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
114
+
115
+ ## Contributing
116
+ State if you are open to contributions and what your requirements are for accepting them.
117
+
118
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
119
+
120
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
121
+
122
+ ## Authors and acknowledgment
123
+ Show your appreciation to those who have contributed to the project.
124
+
125
+ ## License
126
+ For open source projects, say how it is licensed.
127
+
128
+ ## Project status
129
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,10 @@
1
+ agentic_kit_common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ agentic_kit_common/Minio_db/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ agentic_kit_common/Minio_db/config.py,sha256=VMcvfWnuWZKr_p0rC57i90jTq-XVsRuVzfEIe1C7Drg,3804
4
+ agentic_kit_common/Minio_db/minio_manager.py,sha256=PzoUWn0YqXTHx1UClbkwLkIUmv5O4aSDc7eVf08qOzs,21494
5
+ test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ test/test_minio.py,sha256=W86h_2BpesePI_9-nIiL8eAHrrXUwVJOjvYkAuNzyhU,2338
7
+ agentic_kit_common-0.0.1.dist-info/METADATA,sha256=qyqGtMaoNDtMW3cEQ83MYwNgy8bkSK5U4LXlYLqVTGs,7428
8
+ agentic_kit_common-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ agentic_kit_common-0.0.1.dist-info/top_level.txt,sha256=nEKDlp84vqKSVWssGcxyuIsTqWLhMo45xqMs2GK4Dgg,24
10
+ agentic_kit_common-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ agentic_kit_common
2
+ test
test/__init__.py ADDED
File without changes
test/test_minio.py ADDED
@@ -0,0 +1,75 @@
1
+ import unittest
2
+ from datetime import timedelta
3
+ from pathlib import Path
4
+ import sys
5
+
6
+ project_root = Path(__file__).parent.parent
7
+ sys.path.insert(0, str(project_root))
8
+
9
+ from agentic_kit_common.Minio_db.minio_manager import MinioManager
10
+ from agentic_kit_common.Minio_db.config import load_config
11
+
12
+
13
+ class MyTestCase(unittest.TestCase):
14
+ def test_minio_list_obj(self):
15
+ config = load_config().get('minio', {})
16
+ # 初始化客户端
17
+ minio_client = MinioManager(
18
+ endpoint=config.get('ENDPOINT'),
19
+ access_key=config.get('ACCESS_KEY'),
20
+ secret_key=config.get('SECRET_KEY'),
21
+ secure=config.get('SECURE', False)
22
+ )
23
+ # 列出对象
24
+ objects = minio_client.list_objects("my-bucket", prefix="path/")
25
+ for obj in objects:
26
+ print(obj)
27
+ print(f"Object: {obj['name']}, Size: {obj['size']}")
28
+
29
+ def test_minio(self):
30
+ config = load_config().get('minio', {})
31
+
32
+ # 初始化客户端
33
+ minio_client = MinioManager(
34
+ endpoint=config.get('ENDPOINT'),
35
+ access_key=config.get('ACCESS_KEY'),
36
+ secret_key=config.get('SECRET_KEY'),
37
+ secure=config.get('SECURE', False)
38
+ )
39
+
40
+ if not minio_client.bucket_exists("my-bucket"):
41
+ minio_client.create_bucket("my-bucket")
42
+
43
+ # 上传文件
44
+ minio_client.upload_file(
45
+ bucket_name="my-bucket",
46
+ object_name="/path/下载.png",
47
+ file_path="/Users/manson/Downloads/下载.png"
48
+ )
49
+
50
+ # 下载文件
51
+ minio_client.download_file(
52
+ bucket_name="my-bucket",
53
+ object_name="/path/下载.png",
54
+ file_path="/Users/manson/Downloads/下载2.png"
55
+ )
56
+
57
+ # 列出对象
58
+ objects = minio_client.list_objects("my-bucket", prefix="path")
59
+ for obj in objects:
60
+ print(f"Object: {obj['name']}, Size: {obj['size']}")
61
+
62
+ # 生成预签名URL
63
+ url = minio_client.get_presigned_url(
64
+ bucket_name="my-bucket",
65
+ object_name="/path/下载.png",
66
+ expires=timedelta(hours=1)
67
+ )
68
+ print(f"Download URL: {url}")
69
+
70
+ # 删除对象
71
+ # minio_client.delete_object("my-bucket", "/path/下载.png")
72
+
73
+
74
+ if __name__ == '__main__':
75
+ unittest.main()