yimo-kit 0.1.0__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.
Files changed (70) hide show
  1. yimo/__init__.py +26 -0
  2. yimo/kit/__init__.py +98 -0
  3. yimo/kit/ai/__init__.py +110 -0
  4. yimo/kit/ai/_internal/__init__.py +27 -0
  5. yimo/kit/ai/_internal/failover.py +535 -0
  6. yimo/kit/ai/_internal/pool.py +526 -0
  7. yimo/kit/ai/_internal/rerank_transport.py +137 -0
  8. yimo/kit/ai/_internal/retry_after.py +51 -0
  9. yimo/kit/ai/_internal/sdk_client.py +463 -0
  10. yimo/kit/ai/_internal/service_base.py +115 -0
  11. yimo/kit/ai/_internal/types.py +28 -0
  12. yimo/kit/ai/agent/__init__.py +127 -0
  13. yimo/kit/ai/agent/approval.py +66 -0
  14. yimo/kit/ai/agent/errors.py +128 -0
  15. yimo/kit/ai/agent/loop.py +643 -0
  16. yimo/kit/ai/agent/mcp.py +278 -0
  17. yimo/kit/ai/agent/registry.py +203 -0
  18. yimo/kit/ai/agent/session.py +150 -0
  19. yimo/kit/ai/agent/skill.py +370 -0
  20. yimo/kit/ai/agent/types.py +161 -0
  21. yimo/kit/ai/chat_service.py +724 -0
  22. yimo/kit/ai/decision/__init__.py +57 -0
  23. yimo/kit/ai/decision/decima.py +853 -0
  24. yimo/kit/ai/decision/laya.py +552 -0
  25. yimo/kit/ai/embedding_service.py +198 -0
  26. yimo/kit/ai/exceptions.py +109 -0
  27. yimo/kit/ai/image_service.py +84 -0
  28. yimo/kit/ai/messages.py +105 -0
  29. yimo/kit/ai/model_builder.py +121 -0
  30. yimo/kit/ai/model_client.py +62 -0
  31. yimo/kit/ai/profiles.py +577 -0
  32. yimo/kit/ai/rerank_service.py +136 -0
  33. yimo/kit/ai/runner.py +1127 -0
  34. yimo/kit/common_kit.py +221 -0
  35. yimo/kit/config/__init__.py +44 -0
  36. yimo/kit/config/kit_config.py +210 -0
  37. yimo/kit/config/log_config.py +171 -0
  38. yimo/kit/crawl/__init__.py +71 -0
  39. yimo/kit/crawl/article_io.py +325 -0
  40. yimo/kit/crawl/article_models.py +172 -0
  41. yimo/kit/crawl/deepseek_kit.py +673 -0
  42. yimo/kit/crawl/web_article_kit.py +638 -0
  43. yimo/kit/crawl/wx_article_kit.py +692 -0
  44. yimo/kit/db/__init__.py +101 -0
  45. yimo/kit/db/audit.py +625 -0
  46. yimo/kit/db/base_db_kit.py +1265 -0
  47. yimo/kit/db/crud.py +423 -0
  48. yimo/kit/db/engine.py +235 -0
  49. yimo/kit/db/exceptions.py +45 -0
  50. yimo/kit/db/models/__init__.py +33 -0
  51. yimo/kit/db/models/base.py +56 -0
  52. yimo/kit/db/mysql_kit.py +348 -0
  53. yimo/kit/db/pg_kit.py +442 -0
  54. yimo/kit/db/query.py +338 -0
  55. yimo/kit/db/session.py +85 -0
  56. yimo/kit/db/sqlite_kit.py +462 -0
  57. yimo/kit/db/transaction.py +109 -0
  58. yimo/kit/docs/__init__.py +34 -0
  59. yimo/kit/docs/anydoc_kit.py +490 -0
  60. yimo/kit/docs/docx_kit.py +895 -0
  61. yimo/kit/docs/md2doc_kit.py +1801 -0
  62. yimo/kit/docs/mineru_kit.py +1497 -0
  63. yimo/kit/docs/rc_docparser_kit.py +654 -0
  64. yimo/kit/file_kit.py +518 -0
  65. yimo/kit/license_kit.py +533 -0
  66. yimo/kit/redis_kit.py +392 -0
  67. yimo_kit-0.1.0.dist-info/METADATA +1673 -0
  68. yimo_kit-0.1.0.dist-info/RECORD +70 -0
  69. yimo_kit-0.1.0.dist-info/WHEEL +4 -0
  70. yimo_kit-0.1.0.dist-info/licenses/LICENSE +201 -0
yimo/kit/common_kit.py ADDED
@@ -0,0 +1,221 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-08-22
21
+ """公共工具类,提供雪花算法 ID 生成和系统时间格式化功能
22
+
23
+ 重构说明(破坏性内部、外部零风险):
24
+ - 将原先 `_initialize` / `configure` / `_INITIALIZED` 三套冗余的初始化
25
+ 逻辑收敛为唯一的 `configure` 入口 + 惰性 `_ensure_initialized`。
26
+ - 用 `_DATACENTER_ID is None` 语义替代 `_INITIALIZED` 布尔标记,状态更清晰。
27
+ - 公开方法名与签名不变。
28
+ """
29
+
30
+ import threading
31
+ import time
32
+ from datetime import datetime
33
+ from random import randint
34
+
35
+
36
+ class CommonKit:
37
+ """公共工具类,提供分布式唯一 ID 生成和系统时间格式化功能
38
+
39
+ 雪花算法 ID 结构(共 63 位,符号位为 0):
40
+ - timestamp(41位):毫秒级时间戳,约可用 69 年
41
+ - datacenter_id(5位):数据中心 ID,有效范围 1-31
42
+ - machine_id(5位):机器 ID,有效范围 1-31
43
+ - sequence(12位):每毫秒内序列号,最大值 4095
44
+
45
+ 支持多线程并发调用,保证 ID 唯一性。
46
+ """
47
+
48
+ _TIMESTAMP_SHIFT: int = 22
49
+ _DATACENTER_ID_SHIFT: int = 17
50
+ _MACHINE_ID_SHIFT: int = 12
51
+
52
+ _MAX_DATACENTER_ID: int = 31
53
+ _MAX_MACHINE_ID: int = 31
54
+ _MAX_SEQUENCE: int = 4095
55
+
56
+ _EPOCH: int = 1577836800000
57
+
58
+ # None 表示尚未初始化(未调用 configure)
59
+ _DATACENTER_ID: int | None = None
60
+ _MACHINE_ID: int | None = None
61
+
62
+ _lock: threading.Lock = threading.Lock()
63
+
64
+ _last_timestamp: int = -1
65
+ _sequence: int = 0
66
+
67
+ @classmethod
68
+ def configure(cls, datacenter_id: int, machine_id: int) -> None:
69
+ """配置雪花算法的数据中心 ID 和机器 ID
70
+
71
+ Args:
72
+ datacenter_id: 数据中心 ID,有效范围 1-31
73
+ machine_id: 机器 ID,有效范围 1-31
74
+
75
+ Raises:
76
+ ValueError: 参数超出有效范围时抛出
77
+ """
78
+ if not (1 <= datacenter_id <= cls._MAX_DATACENTER_ID):
79
+ raise ValueError(
80
+ f"数据中心 ID 必须在 1-{cls._MAX_DATACENTER_ID} 之间,"
81
+ f"当前值: {datacenter_id}"
82
+ )
83
+ if not (1 <= machine_id <= cls._MAX_MACHINE_ID):
84
+ raise ValueError(
85
+ f"机器 ID 必须在 1-{cls._MAX_MACHINE_ID} 之间,当前值: {machine_id}"
86
+ )
87
+ with cls._lock:
88
+ cls._DATACENTER_ID = datacenter_id
89
+ cls._MACHINE_ID = machine_id
90
+
91
+ @classmethod
92
+ def _ensure_initialized(cls) -> None:
93
+ """惰性初始化:首次使用时采用默认配置 (1, 1)"""
94
+ if cls._DATACENTER_ID is None:
95
+ cls.configure(1, 1)
96
+
97
+ @classmethod
98
+ def _get_current_timestamp(cls) -> int:
99
+ """获取当前时间戳(毫秒)"""
100
+ return int(time.time() * 1000)
101
+
102
+ @classmethod
103
+ def _wait_for_next_millis(cls, last_timestamp: int) -> int:
104
+ """等待直到进入下一毫秒"""
105
+ timestamp = cls._get_current_timestamp()
106
+ while timestamp <= last_timestamp:
107
+ timestamp = cls._get_current_timestamp()
108
+ return timestamp
109
+
110
+ @classmethod
111
+ def generate_snowflake_id(
112
+ cls, datacenter_id: int | None = None, machine_id: int | None = None
113
+ ) -> int:
114
+ """生成雪花算法 ID(数值类型)
115
+
116
+ Args:
117
+ datacenter_id: 数据中心 ID(可选),有效范围 1-31,默认使用配置值
118
+ machine_id: 机器 ID(可选),有效范围 1-31,默认使用配置值
119
+
120
+ Returns:
121
+ int: 63 位雪花 ID 数值
122
+
123
+ Raises:
124
+ ValueError: 参数超出有效范围或时钟回拨时抛出
125
+ """
126
+ if datacenter_id is None or machine_id is None:
127
+ cls._ensure_initialized()
128
+ assert cls._DATACENTER_ID is not None
129
+ assert cls._MACHINE_ID is not None
130
+ if datacenter_id is None:
131
+ datacenter_id = cls._DATACENTER_ID
132
+ if machine_id is None:
133
+ machine_id = cls._MACHINE_ID
134
+
135
+ if not (1 <= datacenter_id <= cls._MAX_DATACENTER_ID):
136
+ raise ValueError(f"数据中心 ID 必须在 1-{cls._MAX_DATACENTER_ID} 之间")
137
+ if not (1 <= machine_id <= cls._MAX_MACHINE_ID):
138
+ raise ValueError(f"机器 ID 必须在 1-{cls._MAX_MACHINE_ID} 之间")
139
+
140
+ with cls._lock:
141
+ timestamp = cls._get_current_timestamp()
142
+
143
+ if timestamp < cls._last_timestamp:
144
+ raise ValueError(
145
+ f"时钟回拨检测:当前时间戳({timestamp})小于上次使用时间戳"
146
+ f"({cls._last_timestamp}),无法生成 ID,请检查系统时间"
147
+ )
148
+
149
+ if timestamp == cls._last_timestamp:
150
+ cls._sequence = (cls._sequence + 1) & cls._MAX_SEQUENCE
151
+ if cls._sequence == 0:
152
+ timestamp = cls._wait_for_next_millis(cls._last_timestamp)
153
+ else:
154
+ cls._sequence = 0
155
+
156
+ cls._last_timestamp = timestamp
157
+
158
+ return (
159
+ ((timestamp - cls._EPOCH) << cls._TIMESTAMP_SHIFT)
160
+ | (datacenter_id << cls._DATACENTER_ID_SHIFT)
161
+ | (machine_id << cls._MACHINE_ID_SHIFT)
162
+ | cls._sequence
163
+ )
164
+
165
+ @classmethod
166
+ def generate_snow_id(
167
+ cls, datacenter_id: int | None = None, machine_id: int | None = None
168
+ ) -> str:
169
+ """生成雪花算法 ID(字符串类型)
170
+
171
+ Args:
172
+ datacenter_id: 数据中心 ID(可选),有效范围 1-31,默认使用配置值
173
+ machine_id: 机器 ID(可选),有效范围 1-31,默认使用配置值
174
+
175
+ Returns:
176
+ str: 雪花 ID 字符串形式
177
+ """
178
+ return str(cls.generate_snowflake_id(datacenter_id, machine_id))
179
+
180
+ @staticmethod
181
+ def generate_timestamp_id() -> str:
182
+ """生成基于当前时间的唯一 ID(20 位)
183
+
184
+ 格式: YYYYMMDDHHMMSSfffRRR,后 3 位为随机数确保同毫秒内唯一性
185
+ """
186
+ timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]
187
+ random_suffix = randint(0, 999)
188
+ return f"{timestamp}{random_suffix:03d}"
189
+
190
+ @staticmethod
191
+ def format_current_time(format_pattern: str = "yyyyMMdd") -> str:
192
+ """格式化当前系统时间
193
+
194
+ 支持格式: yyyyMMdd, yyyyMMddhhmm, yyyyMMddhhmmss,
195
+ yyyy-MM-dd, yyyy-MM-dd hh:mm, yyyy-MM-dd hh:mm:ss
196
+ """
197
+ format_map = {
198
+ "yyyyMMdd": "%Y%m%d",
199
+ "yyyyMMddhhmm": "%Y%m%d%H%M",
200
+ "yyyyMMddhhmmss": "%Y%m%d%H%M%S",
201
+ "yyyy-MM-dd": "%Y-%m-%d",
202
+ "yyyy-MM-dd hh:mm": "%Y-%m-%d %H:%M",
203
+ "yyyy-MM-dd hh:mm:ss": "%Y-%m-%d %H:%M:%S",
204
+ }
205
+ if format_pattern not in format_map:
206
+ raise ValueError(
207
+ f"不支持的格式模式: {format_pattern},支持的格式有: "
208
+ f"{', '.join(format_map.keys())}"
209
+ )
210
+
211
+ try:
212
+ return time.strftime(format_map[format_pattern])
213
+ except Exception as e:
214
+ raise RuntimeError(f"获取系统时间失败: {e}")
215
+
216
+ @classmethod
217
+ def reset(cls) -> None:
218
+ """重置 ID 生成器状态"""
219
+ with cls._lock:
220
+ cls._last_timestamp = -1
221
+ cls._sequence = 0
@@ -0,0 +1,44 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-09-08
21
+ """Kit 配置子包:统一导出配置与日志入口"""
22
+
23
+ from yimo.kit.config.kit_config import Settings, get_settings
24
+ from yimo.kit.config.log_config import (
25
+ critical,
26
+ debug,
27
+ error,
28
+ get_default_logger,
29
+ info,
30
+ setup_logger,
31
+ warning,
32
+ )
33
+
34
+ __all__ = [
35
+ "Settings",
36
+ "get_settings",
37
+ "setup_logger",
38
+ "get_default_logger",
39
+ "debug",
40
+ "info",
41
+ "warning",
42
+ "error",
43
+ "critical",
44
+ ]
@@ -0,0 +1,210 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2025-04-19
21
+ # source: 迁移自 config/sys_config.py(kit 自包含配置,修改须与源文件评估双向同步)
22
+ """Kit 统一配置模块"""
23
+
24
+ from functools import lru_cache
25
+
26
+ from pydantic import Field
27
+ from pydantic_settings import BaseSettings
28
+
29
+
30
+ class Settings(BaseSettings):
31
+ LOG_LEVEL: str = Field(default="INFO")
32
+ LOG_TO_CONSOLE: bool = Field(default=True)
33
+ LOG_TO_FILE: bool = Field(default=False)
34
+ LOG_DIR: str = Field(default="./logs")
35
+ LOG_FILE: str = Field(default="app.log")
36
+
37
+ REDIS_HOST: str = Field(default="localhost")
38
+ REDIS_PORT: int = Field(default=6379)
39
+ REDIS_DB: int = Field(default=0)
40
+ REDIS_PASSWORD: str | None = Field(default=None)
41
+
42
+ # 数据库统一配置(PostgreSQL / MySQL 共用)
43
+ # 切换数据库只需修改 DEFAULT_DB_TYPE,无需修改连接参数
44
+ DEFAULT_DB_TYPE: str = Field(default="postgresql")
45
+
46
+ DB_HOST: str = Field(default="localhost")
47
+ # PostgreSQL 专用
48
+ DB_PORT: int = Field(default=5432)
49
+ DB_DATABASE: str = Field(default="postgres")
50
+ DB_USER: str = Field(default="admin")
51
+ DB_PASSWORD: str = Field(default="1qaz@WSX3edc")
52
+
53
+ # MySQL 专用覆盖(当端口/用户/库名与 PG 不同时使用)
54
+ MYSQL_PORT: int = Field(default=3306)
55
+ MYSQL_DATABASE: str = Field(default="mydb")
56
+ MYSQL_USER: str = Field(default="root")
57
+ MYSQL_CHARSET: str = Field(default="utf8mb4")
58
+
59
+ # SQLite 专用(切换到 SQLite 时取消注释)
60
+ SQLITE_DB_PATH: str = Field(default="./data/sqlite.db")
61
+
62
+ FILE_STORAGE_ROOT: str = Field(default="./data")
63
+
64
+ # AI 模型档案配置文件路径(chat/embedding/rerank/image 四类型多厂商档案)
65
+ AI_MODELS_CONFIG_PATH: str = Field(
66
+ default="./config/ai_models.json", description="AI 模型档案配置文件路径"
67
+ )
68
+
69
+ # MinerU 精准解析 API 配置(https://mineru.net/apiManage/docs)
70
+ MINERU_API_KEY: str | None = Field(
71
+ default=None, description="MinerU API Key(API 管理页面自建)"
72
+ )
73
+ MINERU_BASE_API_URL: str = Field(
74
+ default="https://mineru.net", description="MinerU API 基础地址"
75
+ )
76
+ MINERU_TIMEOUT: int = Field(
77
+ default=60, ge=1, le=600, description="单次 HTTP 请求连接超时(秒)"
78
+ )
79
+ MINERU_TRANSFER_TIMEOUT: int = Field(
80
+ default=300,
81
+ ge=1,
82
+ le=3600,
83
+ description="文件上传/结果下载的读取超时(秒)",
84
+ )
85
+ MINERU_POLL_INTERVAL: float = Field(
86
+ default=2.0, ge=0.5, description="任务轮询间隔(秒)"
87
+ )
88
+ MINERU_MAX_WAIT: int = Field(
89
+ default=600, ge=10, description="任务轮询总超时(秒),超时抛 MinerUError"
90
+ )
91
+
92
+ # Marker 本地解析配置(marker-pdf,PDF/图片→Markdown+Images,模型本地运行)
93
+ MARKER_MODE: str | None = Field(
94
+ default=None,
95
+ description=(
96
+ "解析模式:None=按设备自动(GPU→balanced,CPU/MPS→fast),"
97
+ "可设 balanced/fast"
98
+ ),
99
+ )
100
+ MARKER_HF_ENDPOINT: str = Field(
101
+ default="https://hf-mirror.com",
102
+ description="模型权重下载入口(默认国内镜像),置空则使用 HuggingFace 官方源",
103
+ )
104
+ MARKER_HF_DISABLE_XET: bool = Field(
105
+ default=True,
106
+ description="禁用 HF Xet 存储后端(国内镜像不支持,开启会导致权重下载挂起)",
107
+ )
108
+ MARKER_LLAMA_CPP_BINARY: str | None = Field(
109
+ default=None,
110
+ description="llama-server 可执行文件路径(None 时沿用系统 LLAMA_CPP_BINARY)",
111
+ )
112
+
113
+ # Laya 决策引擎配置(本地小模型,把任意文本变成 choice/score/noul 类型化决策)
114
+ LAYA_MODEL: str = Field(
115
+ default="multilingual",
116
+ description=(
117
+ "生效检查点:multilingual(多语言含中文)/ english / typed-decisions"
118
+ ),
119
+ )
120
+ LAYA_DEVICE: str | None = Field(
121
+ default=None,
122
+ description="推理设备(如 cpu / cuda),None 表示交给 laya 自动选择",
123
+ )
124
+ LAYA_HF_ENDPOINT: str = Field(
125
+ default="https://hf-mirror.com",
126
+ description="检查点权重下载入口(默认国内镜像),置空则使用 HuggingFace 官方源",
127
+ )
128
+ LAYA_HF_DISABLE_XET: bool = Field(
129
+ default=True,
130
+ description="禁用 HF Xet 存储后端(国内镜像不支持,开启会导致权重下载挂起)",
131
+ )
132
+ LAYA_PRELOAD: bool | None = Field(
133
+ default=None,
134
+ description="True 时创建 Router 后预热 LAYA_MODEL(只预热当前检查点),None/False 不预热",
135
+ )
136
+ LAYA_MAX_LOADED: int | None = Field(
137
+ default=None,
138
+ description="Router 同时驻留的检查点上限,None 沿用 laya 默认 2",
139
+ )
140
+
141
+ # Decima 决策模型配置(int8 ONNX,仅 CPU;选项乱序不变、置信度已标定)
142
+ DECIMA_MODEL: str = Field(
143
+ default="amyrmahdy/decima-small",
144
+ description=(
145
+ "HF repo id 或本地 ONNX 导出目录"
146
+ "(含 encoder.onnx / scorer.onnx / decima.json / tokenizer)"
147
+ ),
148
+ )
149
+ DECIMA_PRECISION: str = Field(
150
+ default="int8",
151
+ description="ONNX 精度:int8(127 MB,与 fp32 一致率 99.4%)/ fp32(489 MB)",
152
+ )
153
+ DECIMA_THREADS: int = Field(
154
+ default=1,
155
+ ge=1,
156
+ description=(
157
+ "ONNX Runtime intra-op 线程数;上游实测 batch-1 单线程最快,不建议调大"
158
+ ),
159
+ )
160
+ DECIMA_LANG: str = Field(
161
+ default="zh",
162
+ description=(
163
+ "传入 Question.lang;仅 fa/ar 有实质文本归一化,"
164
+ "中文/英文等价但影响选项缓存键"
165
+ ),
166
+ )
167
+ DECIMA_HF_ENDPOINT: str = Field(
168
+ default="https://hf-mirror.com",
169
+ description="权重下载入口(默认国内镜像),置空则使用 HuggingFace 官方源",
170
+ )
171
+ DECIMA_LOCAL_ONLY: bool = Field(
172
+ default=False,
173
+ description="True 时只用本地缓存、不联网(离线部署)",
174
+ )
175
+
176
+ # 文章抓取自检阈值(三个 *ArticleKit 共用):正文长度低于该值时给出非致命提示
177
+ # 0 表示关闭该判据(正文仍按实际长度全量返回,不做截断)
178
+ CRAWL_MIN_CONTENT_CHARS: int = Field(
179
+ default=500,
180
+ ge=0,
181
+ description="正文长度提示阈值(字符);0 = 关闭长度自检",
182
+ )
183
+
184
+ # DeepSeek Search / Fetch API 配置
185
+ # (https://api-docs.deepseek.com/zh-cn/guides/search;按请求次数计费)
186
+ DEEPSEEK_API_KEY: str | None = Field(
187
+ default=None, description="DeepSeek API Key(Search/Fetch 与模型对话共用同一套鉴权)"
188
+ )
189
+ DEEPSEEK_BASE_URL: str = Field(
190
+ default="https://api.deepseek.com", description="DeepSeek API 基础地址"
191
+ )
192
+ DEEPSEEK_TIMEOUT: int = Field(
193
+ default=60, ge=1, le=600, description="单次 HTTP 请求超时(秒)"
194
+ )
195
+ DEEPSEEK_MAX_RETRIES: int = Field(
196
+ default=2,
197
+ ge=0,
198
+ le=5,
199
+ description="408/429/5xx 重试次数(不含首次请求)",
200
+ )
201
+
202
+ class Config:
203
+ env_file = ".env"
204
+ env_file_encoding = "utf-8"
205
+ extra = "ignore"
206
+
207
+
208
+ @lru_cache()
209
+ def get_settings() -> Settings:
210
+ return Settings()
@@ -0,0 +1,171 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2025-04-19
21
+ # source: 迁移自 config/logger_config.py(kit 自包含日志,修改须与源文件评估双向同步)
22
+ """Kit 统一日志配置模块"""
23
+
24
+ import logging
25
+ import os
26
+ import sys
27
+ import threading
28
+ from logging.handlers import RotatingFileHandler
29
+
30
+ from yimo.kit.config.kit_config import get_settings
31
+
32
+ settings = get_settings()
33
+
34
+ DEFAULT_LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
35
+ DEFAULT_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
36
+
37
+ LOG_LEVEL_MAPPING = {
38
+ "DEBUG": logging.DEBUG,
39
+ "INFO": logging.INFO,
40
+ "WARNING": logging.WARNING,
41
+ "WARN": logging.WARNING,
42
+ "ERROR": logging.ERROR,
43
+ "CRITICAL": logging.CRITICAL,
44
+ "FATAL": logging.CRITICAL,
45
+ }
46
+
47
+
48
+ def ensure_log_dir(log_dir: str) -> None:
49
+ """确保日志目录存在"""
50
+ os.makedirs(log_dir, exist_ok=True)
51
+
52
+
53
+ # 同一日志文件路径共享单例文件 handler:
54
+ # 进程内该文件仅一个句柄,避免 Windows 下多句柄占用导致轮转必失败(WinError 32)。
55
+ # 参数策略 first-wins:maxBytes / backupCount / formatter 以首个创建者为准。
56
+ _file_handlers: dict[str, RotatingFileHandler] = {}
57
+ _file_handlers_lock = threading.Lock()
58
+
59
+
60
+ def _file_handler_cache_key(log_file_path: str) -> str:
61
+ """计算共享 handler 缓存 key(归一 Windows 大小写、分隔符与相对路径)"""
62
+ return os.path.normcase(os.path.abspath(log_file_path))
63
+
64
+
65
+ def _get_shared_file_handler(
66
+ log_file_path: str, max_bytes: int, backup_count: int, formatter: logging.Formatter
67
+ ) -> RotatingFileHandler:
68
+ """获取指定日志文件路径的共享文件 handler(不存在则创建)"""
69
+ key = _file_handler_cache_key(log_file_path)
70
+ with _file_handlers_lock:
71
+ handler = _file_handlers.get(key)
72
+ if handler is None:
73
+ handler = RotatingFileHandler(
74
+ log_file_path,
75
+ maxBytes=max_bytes,
76
+ backupCount=backup_count,
77
+ encoding="utf-8",
78
+ )
79
+ handler.setFormatter(formatter)
80
+ _file_handlers[key] = handler
81
+ return handler
82
+
83
+
84
+ def _reset_file_handlers() -> None:
85
+ """复位共享 handler 缓存(仅供测试隔离使用,不进 __all__)"""
86
+ with _file_handlers_lock:
87
+ _file_handlers.clear()
88
+
89
+
90
+ def setup_logger(
91
+ name: str | None = None,
92
+ log_level: str | None = None,
93
+ log_file: str | None = None,
94
+ log_format: str = DEFAULT_LOG_FORMAT,
95
+ date_format: str = DEFAULT_DATE_FORMAT,
96
+ max_bytes: int = 5 * 1024 * 1024,
97
+ backup_count: int = 5,
98
+ ) -> logging.Logger:
99
+ """设置全局统一的日志配置"""
100
+ logger = logging.getLogger(name)
101
+
102
+ level_str = log_level or settings.LOG_LEVEL
103
+ logger.setLevel(LOG_LEVEL_MAPPING.get(level_str.upper(), logging.INFO))
104
+
105
+ if logger.handlers:
106
+ return logger
107
+
108
+ formatter = logging.Formatter(log_format, datefmt=date_format)
109
+
110
+ if settings.LOG_TO_CONSOLE:
111
+ console_handler = logging.StreamHandler(sys.stdout)
112
+ console_handler.setFormatter(formatter)
113
+ logger.addHandler(console_handler)
114
+
115
+ if settings.LOG_TO_FILE:
116
+ ensure_log_dir(settings.LOG_DIR)
117
+ log_file_path = log_file or os.path.join(settings.LOG_DIR, settings.LOG_FILE)
118
+ file_handler = _get_shared_file_handler(
119
+ log_file_path,
120
+ max_bytes=max_bytes,
121
+ backup_count=backup_count,
122
+ formatter=formatter,
123
+ )
124
+ logger.addHandler(file_handler)
125
+
126
+ return logger
127
+
128
+
129
+ def get_default_logger(
130
+ name: str | None = None,
131
+ log_level: str | None = None,
132
+ log_file: str | None = None,
133
+ ) -> logging.Logger:
134
+ """获取默认配置的日志器"""
135
+ return setup_logger(name, log_level, log_file)
136
+
137
+
138
+ def debug(logger: logging.Logger, msg: str, *args, **kwargs) -> None:
139
+ """记录调试信息"""
140
+ logger.debug(msg, *args, **kwargs)
141
+
142
+
143
+ def info(logger: logging.Logger, msg: str, *args, **kwargs) -> None:
144
+ """记录一般信息"""
145
+ logger.info(msg, *args, **kwargs)
146
+
147
+
148
+ def warning(logger: logging.Logger, msg: str, *args, **kwargs) -> None:
149
+ """记录警告信息"""
150
+ logger.warning(msg, *args, **kwargs)
151
+
152
+
153
+ def error(logger: logging.Logger, msg: str, *args, **kwargs) -> None:
154
+ """记录错误信息"""
155
+ logger.error(msg, *args, **kwargs)
156
+
157
+
158
+ def critical(logger: logging.Logger, msg: str, *args, **kwargs) -> None:
159
+ """记录严重错误信息"""
160
+ logger.critical(msg, *args, **kwargs)
161
+
162
+
163
+ __all__ = [
164
+ "setup_logger",
165
+ "get_default_logger",
166
+ "debug",
167
+ "info",
168
+ "warning",
169
+ "error",
170
+ "critical",
171
+ ]