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
@@ -0,0 +1,1673 @@
1
+ Metadata-Version: 2.5
2
+ Name: yimo-kit
3
+ Version: 0.1.0
4
+ Summary: Yimo Kit——统一数据库访问层(PG/MySQL/SQLite)与 AI/Redis/文件/文档/向量工具集
5
+ Author-email: 溢墨修心(Yimo) <changhongyuan@126.com>
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Keywords: ai,kit,mysql,postgresql,redis,sqlalchemy,sqlite,sqlmodel,yimo,向量检索,工具集,开发工具,数据库
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Natural Language :: Chinese (Simplified)
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Topic :: Database
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.13
21
+ Requires-Dist: cryptography>=46.0.7
22
+ Requires-Dist: pydantic-settings>=2.16.3
23
+ Requires-Dist: pydantic>=2.14.3
24
+ Requires-Dist: sqlalchemy~=2.0.55
25
+ Requires-Dist: sqlmodel>=0.0.50
26
+ Provides-Extra: agent
27
+ Requires-Dist: fastmcp-slim[client]<5,>=4.2.1; extra == 'agent'
28
+ Requires-Dist: httpx>=0.28.1; extra == 'agent'
29
+ Requires-Dist: openai<4,>=3.54; extra == 'agent'
30
+ Requires-Dist: python-dotenv>=1.2.4; extra == 'agent'
31
+ Requires-Dist: pyyaml>=6.0.3; extra == 'agent'
32
+ Provides-Extra: ai
33
+ Requires-Dist: httpx>=0.28.1; extra == 'ai'
34
+ Requires-Dist: openai<4,>=3.54; extra == 'ai'
35
+ Requires-Dist: python-dotenv>=1.2.4; extra == 'ai'
36
+ Provides-Extra: anydoc
37
+ Requires-Dist: firecrawl-anydoc>=0.2.4; extra == 'anydoc'
38
+ Requires-Dist: pikepdf>=10.18.2; extra == 'anydoc'
39
+ Provides-Extra: decima
40
+ Requires-Dist: decima-ai>=2.5.1; extra == 'decima'
41
+ Requires-Dist: huggingface-hub<2,>=1.5; extra == 'decima'
42
+ Requires-Dist: onnxruntime>=1.32.0; extra == 'decima'
43
+ Provides-Extra: docx
44
+ Requires-Dist: docxtpl>=0.20.2; extra == 'docx'
45
+ Provides-Extra: docx-parse
46
+ Requires-Dist: rc-docparser>=0.2.2; extra == 'docx-parse'
47
+ Provides-Extra: laya
48
+ Requires-Dist: huggingface-hub<2,>=1.5; extra == 'laya'
49
+ Requires-Dist: laya>=0.4.35; extra == 'laya'
50
+ Provides-Extra: md2doc
51
+ Requires-Dist: markdown-it-py>=4.3.0; extra == 'md2doc'
52
+ Requires-Dist: pillow>=13.0.0; extra == 'md2doc'
53
+ Requires-Dist: pimd[pdfa]>=2.2.5; extra == 'md2doc'
54
+ Provides-Extra: mineru
55
+ Requires-Dist: requests>=2.34.2; extra == 'mineru'
56
+ Provides-Extra: mysql
57
+ Requires-Dist: pymysql>=1.2.4; extra == 'mysql'
58
+ Provides-Extra: pg
59
+ Requires-Dist: psycopg2-binary>=2.9.13; extra == 'pg'
60
+ Provides-Extra: recommended
61
+ Requires-Dist: decima-ai>=2.5.1; extra == 'recommended'
62
+ Requires-Dist: docxtpl>=0.20.2; extra == 'recommended'
63
+ Requires-Dist: firecrawl-anydoc>=0.2.4; extra == 'recommended'
64
+ Requires-Dist: httpx>=0.28.1; extra == 'recommended'
65
+ Requires-Dist: huggingface-hub<2,>=1.5; extra == 'recommended'
66
+ Requires-Dist: laya>=0.4.35; extra == 'recommended'
67
+ Requires-Dist: markdown-it-py>=4.3.0; extra == 'recommended'
68
+ Requires-Dist: numpy>=2.5.5; extra == 'recommended'
69
+ Requires-Dist: onnxruntime>=1.32.0; extra == 'recommended'
70
+ Requires-Dist: openai<4,>=3.54; extra == 'recommended'
71
+ Requires-Dist: pikepdf>=10.18.2; extra == 'recommended'
72
+ Requires-Dist: pimd[pdfa]>=2.2.5; extra == 'recommended'
73
+ Requires-Dist: psycopg2-binary>=2.9.13; extra == 'recommended'
74
+ Requires-Dist: pymysql>=1.2.4; extra == 'recommended'
75
+ Requires-Dist: python-dotenv>=1.2.4; extra == 'recommended'
76
+ Requires-Dist: rc-docparser>=0.2.2; extra == 'recommended'
77
+ Requires-Dist: redis>=8.1.0; extra == 'recommended'
78
+ Requires-Dist: requests>=2.34.2; extra == 'recommended'
79
+ Requires-Dist: sqliteai-vector>=1.2.0; extra == 'recommended'
80
+ Requires-Dist: trafilatura>=2.3.1; extra == 'recommended'
81
+ Provides-Extra: redis
82
+ Requires-Dist: redis>=8.1.0; extra == 'redis'
83
+ Provides-Extra: sqliteai
84
+ Requires-Dist: numpy>=2.5.5; extra == 'sqliteai'
85
+ Requires-Dist: sqliteai-vector>=1.2.0; extra == 'sqliteai'
86
+ Provides-Extra: web-article
87
+ Requires-Dist: trafilatura>=2.3.1; extra == 'web-article'
88
+ Description-Content-Type: text/markdown
89
+
90
+ # yimo-kit
91
+
92
+ Yimo 统一工具集(Kit 体系),供 Python 项目开箱即用:
93
+
94
+ - **统一数据库访问层**:PostgreSQL / MySQL / SQLite,三个 Kit API 完全一致,切换数据库只改一行 import;内置审计字段自动填充(`created_*` / `updated_*` / `deleted`)与软删除查询过滤;
95
+ - **AI 多模型服务池**:chat / embedding / rerank / image 四类能力,多厂商候选链 + 故障自动转移;
96
+ - **工具集**:Redis / 文件 / 雪花 ID / 离线授权签发与校验 / 文档互转 / Word 模板填充 / MinerU 解析 / 离线 docx 解析(md + images/) / Laya 类型化决策 / Decima 决策模型(选项乱序不变、置信度可门控) / 微信公众号文章抓取存储 / 通用网页文章抓取存储 / DeepSeek 搜索与抓取。
97
+
98
+ > 要求 Python 3.13+
99
+
100
+ ## 模块与方法入口
101
+
102
+ | 模块 | 类 / 入口 | 能力 | 需要 extra |
103
+ |------|-----------|------|-----------|
104
+ | `yimo.kit.config` | `get_settings` / `get_default_logger` | 配置单例与统一日志 | 无 |
105
+ | `yimo.kit.db` | `SQLiteKit` / `PgKit` / `MySqlKit` / `CRUDBase` | 统一 CRUD、原生 SQL、原生表操作、事务、表管理 | `pg` / `mysql` / `sqliteai` |
106
+ | `yimo.kit.ai` | `AI`(同步门面)/ 4 个原生异步 Service | 对话 / 向量化 / 重排序 / 文生图 | `ai` |
107
+ | `yimo.kit.ai.agent` | `Agent` / `ToolRegistry` / `SkillRegistry` / `McpServerConfig` / `Session` | MCP client(HTTP / stdio)+ Skill 包加载 + 模型驱动工具循环 | `agent` |
108
+ | `yimo.kit.redis_kit` | `RedisKit` | Redis string / hash / list / set / zset | `redis` |
109
+ | `yimo.kit.file_kit` | `FileKit` | 文件与目录读写、移动、遍历 | 无 |
110
+ | `yimo.kit.common_kit` | `CommonKit` | 雪花 ID、时间戳 ID、时间格式化 | 无 |
111
+ | `yimo.kit.license_kit` | `LicenseKit` / `LicenseVerifier` | Ed25519 离线授权:密钥对、机器码、签发、验签(签名 → 产品 → 机器码 → 有效期) | 无 |
112
+ | `yimo.kit.docs.anydoc_kit` | `AnyDocKit` | docx / pdf / xlsx 等 → Markdown | `anydoc` |
113
+ | `yimo.kit.docs.docx_kit` | `DocxKit` | Word 模板动态填充(章节 / 列表 / 表格) | `docx` |
114
+ | `yimo.kit.docs.rc_docparser_kit` | `RcDocParserKit` | 离线 docx → Markdown + Images(无模型) | `docx-parse` |
115
+ | `yimo.kit.docs.md2doc_kit` | `Md2DocKit` | Markdown → Word / PDF / HTML(含图片) | `md2doc` |
116
+ | `yimo.kit.docs.mineru_kit` | `MinerUKit` | MinerU 文档解析(精准 + Agent 轻量) | `mineru` |
117
+ | `yimo.kit.ai.decision.laya` | `LayaKit` | 类型化决策:choice / multi_choice 多选 / score / noul,另含 decide 多字段 / decide_batch 批量 / predict_long 长文本 | `laya` |
118
+ | `yimo.kit.ai.decision.decima` | `DecimaKit` | 决策模型:choice / score / noul / multi_choice(原生 rank);选项乱序不变、置信度可门控;另含 predict / predict_long / brief / choice_batch(方法名与 `LayaKit` 对齐) | `decima` |
119
+ | `yimo.kit.crawl.article_models` | `ArticleInfo` / `ArticleResult` / `SavedOutput` 等 | 文章抓取通用模型(三个 `*ArticleKit` 共用,含 `reason` 分类与非致命 `warnings`) | 无 |
120
+ | `yimo.kit.crawl.article_io` | `resolve_stem` / `save_article` 等 | 落盘公共层(目录命名 / 图片本地化 / YAML 头 / `meta.json`),三个 `*ArticleKit` 共用 | 无 |
121
+ | `yimo.kit.crawl.wx_article_kit` | `WxArticleKit` | 微信公众号文章 → Markdown + 图片转存 | 无 |
122
+ | `yimo.kit.crawl.web_article_kit` | `WebArticleKit` | 通用网页文章 → Markdown + 图片转存(**不含微信**,微信请用 `WxArticleKit`;明确支持头条) | `web-article` |
123
+ | `yimo.kit.crawl.deepseek_kit` | `DeepSeekKit` | DeepSeek Search / Fetch API:网页搜索 + 单页抓取转 Markdown(`save` 与另两个 Kit 同契约) | 无(需 `DEEPSEEK_API_KEY`) |
124
+
125
+ ## 安装
126
+
127
+ ```bash
128
+ pip install yimo-kit # 基础版:config/log + yimo.kit.db 核心(SQLite 常规操作零额外依赖)
129
+ # 或
130
+ uv add yimo-kit
131
+ ```
132
+
133
+ 可选能力按 extras 按需安装(均为延迟导入,不装不影响基础使用,缺依赖时报错会提示安装命令):
134
+
135
+ | extra | 能力 | 安装 |
136
+ |-------|------|------|
137
+ | `pg` | PgKit(PostgreSQL 驱动;向量方法另需服务端 pgvector) | `pip install "yimo-kit[pg]"` |
138
+ | `mysql` | MySqlKit(MySQL 驱动;向量仅存储,需 MySQL 9.x) | `pip install "yimo-kit[mysql]"` |
139
+ | `sqliteai` | SQLiteKit 向量方法(numpy / sqliteai-vector,SQLite 向量扩展) | `pip install "yimo-kit[sqliteai]"` |
140
+ | `redis` | RedisKit | `pip install "yimo-kit[redis]"` |
141
+ | `ai` | AI 服务池(openai>=3.54 + httpx + python-dotenv;安装体积约 +10MB,SDK 自带 httpx2) | `pip install "yimo-kit[ai]"` |
142
+ | `md2doc` | Md2DocKit:Markdown → Word / PDF / HTML(pimd / fpdf2,含图片) | `pip install "yimo-kit[md2doc]"` |
143
+ | `anydoc` | AnyDocKit 文档转 Markdown(firecrawl-anydoc + pikepdf) | `pip install "yimo-kit[anydoc]"` |
144
+ | `docx` | DocxKit 模板动态填充(docxtpl) | `pip install "yimo-kit[docx]"` |
145
+ | `docx-parse` | RcDocParserKit 离线 docx 解析(rc-docparser → Markdown + images/) | `pip install "yimo-kit[docx-parse]"` |
146
+ | `mineru` | MinerUKit 解析 API(精准解析 + Agent 轻量解析) | `pip install "yimo-kit[mineru]"` |
147
+ | `laya` | LayaKit 类型化决策(laya + torch,本地小模型 choice / multi_choice / score / noul;支持多字段 / 批量 / 长文本) | `pip install "yimo-kit[laya]"` |
148
+ | `decima` | DecimaKit 决策模型(decima-ai + onnxruntime,**无 torch**;选项乱序不变、置信度可门控;磁盘约 137 MB) | `pip install "yimo-kit[decima]"` |
149
+ | `web-article` | WebArticleKit 通用网页文章抓取转存(trafilatura,纯 HTTP 无浏览器) | `pip install "yimo-kit[web-article]"` |
150
+ | `agent` | Agent 能力:MCP client(fastmcp-slim)+ Skill 加载 + 工具循环(含 ai 三项依赖与 pyyaml) | `pip install "yimo-kit[agent]"` |
151
+ | `recommended` | 常用能力集合(DB / 缓存 / AI / 文档 / 抓取);不含重依赖(laya / decima) | `pip install "yimo-kit[recommended]"` |
152
+
153
+ ## Agent 快速开始(extra `agent`)
154
+
155
+ ```python
156
+ import asyncio
157
+
158
+ from yimo.kit.ai.agent import Agent, McpServerConfig, SkillRegistry
159
+
160
+
161
+ async def main() -> None:
162
+ skills = SkillRegistry()
163
+ skills.load("./skills") # 一级子目录含 SKILL.md 即注册
164
+
165
+ agent = Agent(
166
+ skills=skills,
167
+ servers=[
168
+ McpServerConfig(
169
+ name="filesystem",
170
+ transport="stdio",
171
+ command="npx",
172
+ args=["-y", "@modelcontextprotocol/server-filesystem", "./data"],
173
+ )
174
+ ],
175
+ system_prompt="你是一个谨慎的文档助手。",
176
+ )
177
+
178
+ async with agent: # 建连一次,可多次 run()
179
+ result = await agent.run("总结 data 目录里的文件")
180
+ print(result.text)
181
+
182
+
183
+ asyncio.run(main())
184
+ ```
185
+
186
+ - 模型档案沿用 `yimo.kit.ai`(`config/ai_models.json`),首轮可 failover,成功后锁定档案;
187
+ - 档案可在 `ai_models.json` 写 `supports_tools: true/false` 声明 function calling 能力;缺省时运行时检测 400 并自动换候选;
188
+ - Skill 只读工具:`read_skill` / `list_skill_files` / `read_skill_file`(路径越界拒绝);
189
+ - MCP 工具默认放行,skill 脚本默认拒绝;可用 `DenyAllApproval` 整体收紧;
190
+ - stdio 默认 `keep_alive=False`,`Agent` 退出即断开并终止直接子进程;
191
+ - `timeout` / `max_turns` / `tool_timeout` / `approval_timeout` 控制总预算、轮次与审批等待;
192
+ - 完整说明见 `docs/agents/modules/agent-kit.md`(仓库内)。
193
+
194
+ ## 配置(.env)
195
+
196
+ kit 通过 pydantic-settings 读取项目根目录 `.env`;**同名真实环境变量优先于 `.env`**。全部变量都有默认值,按需覆盖即可。
197
+
198
+ ### 最小样例 `.env`
199
+
200
+ ```dotenv
201
+ # 日志(可选)
202
+ LOG_LEVEL=INFO
203
+ LOG_TO_FILE=false
204
+
205
+ # 数据库(三选一,切换只改 DEFAULT_DB_TYPE:postgresql / mysql / sqlite)
206
+ DEFAULT_DB_TYPE=sqlite
207
+ SQLITE_DB_PATH=./data/sqlite.db
208
+ # DB_HOST=localhost
209
+ # DB_PORT=5432
210
+ # DB_DATABASE=postgres
211
+ # DB_USER=admin
212
+ # DB_PASSWORD=
213
+ # MYSQL_PORT=3306
214
+ # MYSQL_DATABASE=mydb
215
+ # MYSQL_USER=root
216
+ # MYSQL_CHARSET=utf8mb4
217
+
218
+ # 按需启用以下能力
219
+ # REDIS_HOST=localhost
220
+ # REDIS_PORT=6379
221
+ # REDIS_DB=0
222
+ # REDIS_PASSWORD=
223
+ # FILE_STORAGE_ROOT=./data
224
+
225
+ # AI:档案路径 + 你为各模型档案自定的密钥变量名(变量名在 ai_models.json 里声明)
226
+ # AI_MODELS_CONFIG_PATH=./config/ai_models.json
227
+ # SILICONFLOW_API_KEY=sk-xxxxxx
228
+
229
+ # MinerU(仅精准解析需要 Key,Agent 轻量解析免登录)
230
+ # MINERU_API_KEY=
231
+
232
+ # Laya(类型化决策,可选依赖 yimo-kit[laya])
233
+ # LAYA_MODEL=multilingual # multilingual / english / typed-decisions
234
+ # LAYA_DEVICE= # 留空由 laya 自动选择
235
+ # LAYA_HF_ENDPOINT=https://hf-mirror.com
236
+ # LAYA_HF_DISABLE_XET=true
237
+ # LAYA_PRELOAD= # true 时只预热当前 LAYA_MODEL
238
+ # LAYA_MAX_LOADED= # 同时驻留检查点上限,留空用 laya 默认 2
239
+
240
+ # Decima(决策模型,可选依赖 yimo-kit[decima])
241
+ # DECIMA_MODEL=amyrmahdy/decima-small
242
+ # DECIMA_PRECISION=int8 # int8(127 MB)/ fp32(489 MB)
243
+ # DECIMA_THREADS=1 # batch-1 单线程最快,不建议调大
244
+ # DECIMA_LANG=zh # 仅 fa/ar 有实质归一化
245
+ # DECIMA_HF_ENDPOINT=https://hf-mirror.com
246
+ # DECIMA_LOCAL_ONLY=false # true = 只用本地缓存,离线部署
247
+ ```
248
+
249
+ ### 环境变量 ↔ 能力对照表
250
+
251
+ > 表中未出现的模块(`yimo.kit.crawl.article_models`、`yimo.kit.crawl.article_io`、`yimo.kit.common_kit`、`yimo.kit.docs.docx_kit`、`yimo.kit.docs.md2doc_kit`、`yimo.kit.license_kit`)不读取任何环境变量。
252
+
253
+ **基础与日志**(影响 `yimo.kit.config` 及所有模块的日志输出)
254
+
255
+ | 环境变量 | 默认值 | 作用 |
256
+ |----------|--------|------|
257
+ | `LOG_LEVEL` | `INFO` | kit 统一日志级别 |
258
+ | `LOG_TO_CONSOLE` | `true` | 是否输出到控制台 |
259
+ | `LOG_TO_FILE` | `false` | 是否输出到文件 |
260
+ | `LOG_DIR` | `./logs` | 日志目录 |
261
+ | `LOG_FILE` | `app.log` | 日志文件名 |
262
+
263
+ **数据库** → `yimo.kit.db`、`SQLiteKit` / `PgKit` / `MySqlKit`
264
+
265
+ | 环境变量 | 默认值 | 作用 |
266
+ |----------|--------|------|
267
+ | `DEFAULT_DB_TYPE` | `postgresql` | 默认数据库类型:`postgresql` / `mysql` / `sqlite`;切换数据库只改这一项 |
268
+ | `DB_HOST` | `localhost` | PG / MySQL 共用主机 |
269
+ | `DB_PORT` | `5432` | PostgreSQL 端口 |
270
+ | `DB_DATABASE` | `postgres` | PostgreSQL 库名 |
271
+ | `DB_USER` | `admin` | PostgreSQL 用户 |
272
+ | `DB_PASSWORD` | `1qaz@WSX3edc` | PG / MySQL 共用密码 |
273
+ | `MYSQL_PORT` | `3306` | MySQL 端口(与 PG 不同时覆盖) |
274
+ | `MYSQL_DATABASE` | `mydb` | MySQL 库名 |
275
+ | `MYSQL_USER` | `root` | MySQL 用户 |
276
+ | `MYSQL_CHARSET` | `utf8mb4` | MySQL 字符集 |
277
+ | `SQLITE_DB_PATH` | `./data/sqlite.db` | SQLite 文件路径(`:memory:` 时自动共享单连接) |
278
+
279
+ **Redis** → `yimo.kit.redis_kit`
280
+
281
+ | 环境变量 | 默认值 | 作用 |
282
+ |----------|--------|------|
283
+ | `REDIS_HOST` | `localhost` | Redis 主机 |
284
+ | `REDIS_PORT` | `6379` | Redis 端口 |
285
+ | `REDIS_DB` | `0` | 数据库编号 |
286
+ | `REDIS_PASSWORD` | `None` | 密码,无密码留空 |
287
+
288
+ **文件存储** → `yimo.kit.file_kit`
289
+
290
+ | 环境变量 | 默认值 | 作用 |
291
+ |----------|--------|------|
292
+ | `FILE_STORAGE_ROOT` | `./data` | FileKit 全部相对路径的根目录。⚠ 该目录**必须已存在**,否则首次调用抛 `RuntimeError`(根路径不存在) |
293
+
294
+ **AI** → `yimo.kit.ai`
295
+
296
+ | 环境变量 | 默认值 | 作用 |
297
+ |----------|--------|------|
298
+ | `AI_MODELS_CONFIG_PATH` | `./config/ai_models.json` | 档案文件位置;文件不存在时调用抛 `AIConfigError` |
299
+ | `KIT_AI_CHAIN_TIMEOUT` | 未设置 | 全局整链预算(秒)= 门面同步等待上限。⚠ **不是 `Settings` 字段**,由代码直读 `os.environ`,无类型/范围校验,非法值仅告警后回退 |
300
+ | *(密钥,变量名由档案决定)* | 无 | 名字写在 `ai_models.json` 各档案的 `api_key` 字段(如 `SILICONFLOW_API_KEY`),值放 `.env` 或系统环境变量。未配置的档案会被剔除出候选链;该类型全部未配置则调用失败 |
301
+
302
+ **MinerU** → `yimo.kit.docs.mineru_kit`
303
+
304
+ | 环境变量 | 默认值 | 作用 |
305
+ |----------|--------|------|
306
+ | `MINERU_API_KEY` | 无 | 精准解析 Token(Agent 轻量解析免登录,不读该变量);缺失时抛 `MinerUError` |
307
+ | `MINERU_BASE_API_URL` | `https://mineru.net` | API 基础地址 |
308
+ | `MINERU_TIMEOUT` | `60`(1–600) | 单次 HTTP 请求连接超时 |
309
+ | `MINERU_TRANSFER_TIMEOUT` | `300`(1–3600) | 文件上传 / 结果下载读取超时 |
310
+ | `MINERU_POLL_INTERVAL` | `2.0`(≥0.5) | 任务轮询间隔 |
311
+ | `MINERU_MAX_WAIT` | `600`(≥10) | 轮询总超时,超时抛 `MinerUError` |
312
+
313
+ **Laya** → `yimo.kit.ai.decision.laya`
314
+
315
+ | 环境变量 | 默认值 | 作用 |
316
+ |----------|--------|------|
317
+ | `LAYA_MODEL` | `multilingual` | 检查点:`multilingual`(多语言含中文)/ `english` / `typed-decisions` |
318
+ | `LAYA_DEVICE` | 无(不写入 config) | 推理设备(`cpu` / `cuda`);不配置则由 laya 自动选择 |
319
+ | `LAYA_HF_ENDPOINT` | `https://hf-mirror.com` | 检查点权重下载入口(国内镜像);置空则用 HuggingFace 官方源 |
320
+ | `LAYA_HF_DISABLE_XET` | `true` | 禁用 HF Xet 存储后端(国内镜像不支持,开启会导致权重下载挂起) |
321
+ | `LAYA_PRELOAD` | 无(不写入 config) | `true` 时创建 Router 后预热当前 `LAYA_MODEL`(只预热这一份) |
322
+ | `LAYA_MAX_LOADED` | 无(不写入 config) | Router 同时驻留的检查点上限;不配置则用 laya 默认 2 |
323
+
324
+ > 能力边界:`decide` 的 schema 仅支持 `enum` / `boolean` / 带 `minimum`+`maximum` 的数值字段
325
+ > (数组、嵌套对象、联合类型不支持);`decide` 中的 `score` 投影为最置信档位(argmax),
326
+ > 不是序数期望值;`decide` 返回 `DecisionResult` 的 7 个键,`min_confidence` 低于阈值时字段值为 `None`;
327
+ > 长文本用 `predict_long`,批量用 `decide_batch`(上游没有 `decide_long`)。
328
+ > 多选用 `multi_choice`:每个候选标签独立做 `noul` 判断,返回 0-N 个标签;
329
+ > `threshold`(默认 0.5)由调用方给定且未标定,可能出现 0 个或全部命中,请按 `probabilities` 复核。
330
+
331
+ > `LAYA_HF_*` 同样由 kit 在**导入 laya 之前**经 `os.environ.setdefault` 应用,不覆盖显式配置;
332
+ > `LAYA_MODEL` / `LAYA_DEVICE` / `LAYA_PRELOAD` / `LAYA_MAX_LOADED` 由 `Settings` 读取(进程内缓存,改后需重启进程)。
333
+
334
+ **Decima** → `yimo.kit.ai.decision.decima`
335
+
336
+ | 环境变量 | 默认值 | 作用 |
337
+ |----------|--------|------|
338
+ | `DECIMA_MODEL` | `amyrmahdy/decima-small` | HF repo id 或本地 ONNX 导出目录 |
339
+ | `DECIMA_PRECISION` | `int8` | `int8`(127 MB,与 fp32 一致率 99.4%)/ `fp32`(489 MB) |
340
+ | `DECIMA_THREADS` | `1` | ONNX Runtime intra-op 线程数;batch-1 单线程最快 |
341
+ | `DECIMA_LANG` | `zh` | 传给 `Question.lang`;仅 fa/ar 有实质归一化 |
342
+ | `DECIMA_HF_ENDPOINT` | `https://hf-mirror.com` | 权重下载入口(国内镜像);置空则用官方源 |
343
+ | `DECIMA_LOCAL_ONLY` | `false` | `true` 时只用本地缓存、不联网 |
344
+
345
+ > `DECIMA_HF_ENDPOINT` 由 kit 在**导入 decima 之前**经 `os.environ.setdefault` 应用,不覆盖显式配置;
346
+ > `HF_HUB_DISABLE_XET=1` 由 kit 固定设置(国内镜像不支持 xet,会挂起)。
347
+ > 不占用上游环境变量 `DECIMA_MODELS`(短名→路径覆盖)与 `DECIMA_DECODE`(自动解码)。
348
+
349
+ **DeepSeek Search / Fetch** → `yimo.kit.crawl.deepseek_kit`
350
+
351
+ | 环境变量 | 默认值 | 作用 |
352
+ |----------|--------|------|
353
+ | `DEEPSEEK_API_KEY` | 无 | Search / Fetch 鉴权 Key(与模型对话共用同一套);缺失时调用抛 `DeepSeekKitError` |
354
+ | `DEEPSEEK_BASE_URL` | `https://api.deepseek.com` | API 基础地址 |
355
+ | `DEEPSEEK_TIMEOUT` | `60`(1–600) | 单次 HTTP 请求超时(秒) |
356
+ | `DEEPSEEK_MAX_RETRIES` | `2`(0–5) | 408 / 429 / 5xx 重试次数(不含首次请求);其它 4xx 不重试 |
357
+
358
+ **文章抓取长度自检** → `yimo.kit.crawl.wx_article_kit` / `web_article_kit` / `deepseek_kit`
359
+
360
+ | 环境变量 | 默认值 | 作用 |
361
+ |----------|--------|------|
362
+ | `CRAWL_MIN_CONTENT_CHARS` | `500`(≥0) | 正文短于该长度时写入 `warnings`(非致命,不改成功语义、不截断正文);`0` 关闭该判据 |
363
+
364
+ **云 OCR**(任何 `ocr="hosted"` 的转换)→ `yimo.kit.docs.anydoc_kit`
365
+
366
+ | 环境变量 | 默认值 | 作用 |
367
+ |----------|--------|------|
368
+ | `FIRECRAWL_API_KEY` | 无 | 扫描件云 OCR 密钥。kit **不读**该变量:仅在方法参数 `api_key=None` 时由 firecrawl-anydoc 自行回落读取 |
369
+ | `FIRECRAWL_API_URL` | 无 | 云 OCR 服务地址,回落规则同上 |
370
+
371
+ ### 环境变量的四类来源
372
+
373
+ | 类别 | 命名方式 | 当前变量 | 读取方与语义 |
374
+ |------|----------|----------|--------------|
375
+ | ① Settings 变量 | 固定,kit 定义 | 上表中除 `KIT_AI_CHAIN_TIMEOUT` 与密钥类之外的全部 | pydantic-settings 读 `.env` 与真实环境变量(后者优先),带类型与范围校验,缺失用默认值 |
376
+ | ② 直读变量 | 固定,kit 代码直接读 `os.environ` | `KIT_AI_CHAIN_TIMEOUT` | 无类型校验,非法值告警后回退 |
377
+ | ③ 档案声明变量 | **动态**,名字写在 JSON 里 | AI 的 `api_key` | **名字进 JSON、值进 `.env`**——所以档案文件可以安全入库,密钥留在环境里 |
378
+ | ④ 第三方库变量 | 由依赖库定义 | `FIRECRAWL_API_KEY`、`FIRECRAWL_API_URL`(anydoc) | anydoc:kit 只透传 `None`,由其自行回落 |
379
+
380
+ ### 密钥解析优先级
381
+
382
+ | 能力 | 解析顺序 | 全部缺失时 |
383
+ |------|----------|------------|
384
+ | AI | 真实环境变量 > 项目根 `.env`(首次加载档案时经 `load_dotenv(override=False)` 注入 `os.environ`) | 该档案被剔除出候选链;该类型无可用档案则调用报 `AIAggregateError` |
385
+ | MinerU | 仅 `Settings`(`.env` / 真实环境变量) | 精准解析接口抛 `MinerUError` |
386
+
387
+ > AI 的 `load_dotenv(override=False)` 表示已存在的真实环境变量不会被 `.env` 覆盖——生产用容器 / 系统环境变量注入时,可以放心保留开发用的 `.env`。
388
+
389
+ ### 改了配置何时生效
390
+
391
+ | 改动内容 | 生效时机 |
392
+ |----------|----------|
393
+ | `LOG_*`、`DB_*`、`MYSQL_*`、`REDIS_*`、`FILE_STORAGE_ROOT`、`MINERU_*` | `get_settings()` 带 `lru_cache`,进程内首次读取后固定 → **重启进程**(或调用 `AI.reload_config()`,它会顺带清空该缓存) |
394
+ | `LAYA_HF_ENDPOINT` / `LAYA_HF_DISABLE_XET` | 仅在 `import yimo.kit.ai.decision.laya` 时经 `os.environ.setdefault` 应用 → 改动需**重启进程**重新导入模块 |
395
+ | `DECIMA_HF_ENDPOINT` / `HF_HUB_DISABLE_XET` | 仅在 `import yimo.kit.ai.decision.decima` 时经 `os.environ.setdefault` 应用 → 改动需**重启进程**重新导入模块 |
396
+ | AI 密钥写在 `.env` 里 | `.env` 只在加载档案时注入一次 → 重启,或 `AI.reload_config(reload_file=True)` |
397
+ | AI 密钥由自己写入 `os.environ` | `AI.reload_config()`(默认 `reload_file=False`,只重读 `os.environ`) |
398
+ | `ai_models.json`(增删档案、换 model) | `AI.reload_config(reload_file=True)` |
399
+ | `KIT_AI_CHAIN_TIMEOUT` | 每次调用现读 `os.environ` → 改 `os.environ` 立即生效;写在 `.env` 里的新值要等下一次档案加载 |
400
+
401
+ ---
402
+
403
+ ## yimo.kit.config —— 配置与日志
404
+
405
+ ```python
406
+ from yimo.kit.config import get_settings, get_default_logger
407
+
408
+ settings = get_settings() # Settings 单例(lru_cache,读取 .env)
409
+ logger = get_default_logger(__name__) # 统一日志入口(禁止自建 logging handler)
410
+ logger.info("hello %s", settings.FILE_STORAGE_ROOT)
411
+ ```
412
+
413
+ | 入口 | 说明 |
414
+ |------|------|
415
+ | `get_settings() -> Settings` | 返回全局配置单例,字段名与环境变量同名(如 `settings.SQLITE_DB_PATH`、`settings.DEFAULT_DB_TYPE`),完整清单见上文对照表 |
416
+ | `get_default_logger(name=None, log_level=None, log_file=None) -> logging.Logger` | 获取统一格式日志器(控制台 + 轮转文件) |
417
+ | `setup_logger(name=None, log_level=None, log_file=None, log_format=..., date_format=..., max_bytes=5*1024*1024, backup_count=5) -> logging.Logger` | 完整参数版本,一般无需直接使用 |
418
+
419
+ ---
420
+
421
+ ## yimo.kit.db —— 统一数据库访问层
422
+
423
+ `yimo/kit/__init__.py` 直接重导出 `yimo.kit.db` 的全部公开符号,下列两种写法等价:
424
+
425
+ ```python
426
+ from yimo.kit.db import session_scope, transactional, DBError # 推荐
427
+ from yimo.kit import session_scope, transactional, DBError # 等价
428
+ ```
429
+
430
+ ### 1. 三个数据库 Kit(31 个共享方法 API 完全一致)
431
+
432
+ | 类 | 导入 | 数据库 | extra |
433
+ |----|------|--------|-------|
434
+ | `SQLiteKit` | `from yimo.kit.db.sqlite_kit import SQLiteKit` | SQLite | 无(常规操作) |
435
+ | `PgKit` | `from yimo.kit.db.pg_kit import PgKit` | PostgreSQL | `pg` |
436
+ | `MySqlKit` | `from yimo.kit.db.mysql_kit import MySqlKit` | MySQL | `mysql` |
437
+
438
+ **共有方法(31 个,全部为 classmethod;`raw_*` 内部自动提交,`build_raw_*` 只拼装不执行)**
439
+
440
+ | 分组 | 方法 | 说明 |
441
+ |------|------|------|
442
+ | 连接 | `connect() -> bool` | 建引擎并验证连通 |
443
+ | 连接 | `close() -> None` | 关闭引擎 |
444
+ | 连接 | `is_connected() -> bool` | 探测当前是否可连 |
445
+ | 连接 | `raw_connection()` | 取原生 DBAPI 连接(PG=psycopg2 / MySQL=pymysql / SQLite=sqlite3);调用方负责 commit 与 close,psycopg2 / pymysql 默认不自动提交 |
446
+ | ORM | `create(model, data) -> Model` | 插入单条 |
447
+ | ORM | `create_multi(model, data_list) -> list[Model]` | 批量插入 |
448
+ | ORM | `get(model, id) -> Model \| None` | 按主键查询 |
449
+ | ORM | `get_by(model, field_name, field_value) -> Model \| None` | 按字段等值查询 |
450
+ | ORM | `list(model, *, skip=0, limit=100, order_by=None, desc=False) -> list[Model]` | 分页 + 排序查询 |
451
+ | ORM | `update(model, id, data) -> Model` | 按主键更新 |
452
+ | ORM | `delete(model, id) -> bool` | 按主键删除 |
453
+ | ORM | `upsert(model, data, conflict_fields) -> Model` | 原子插入或更新(`conflict_fields` 须为唯一约束) |
454
+ | ORM | `count(model) -> int` | 记录总数 |
455
+ | 原生 SQL | `query(sql, params=None) -> list[dict]` | 原生查询,返回字典列表 |
456
+ | 原生 SQL | `execute(sql, params=None) -> int` | 原生写入,返回影响行数;`params` 传**字典列表**时批量执行(executemany,行键集须一致、行值须为标量、空列表返回 0) |
457
+ | 原生 SQL | `prepare_statement(sql, params=None) -> (语句, dict \| None)` | **模块级函数**(`from yimo.kit.db import prepare_statement`):构造可在**自有事务**内 `session.execute(stmt, bound)` 的语句,支持 `IN :ids`,调用方无须 import `sqlalchemy` |
458
+ | 原生表 | `create_raw_table(table_name, columns, if_not_exists=True) -> None` | 按「列名 → 列定义」建普通表;⚠ 列定义须按目标库方言书写,不做方言翻译 |
459
+ | 原生表 | `raw_insert(table_name, data, *, ignore_conflict=False) -> int` | 插入一行;`ignore_conflict=True` 幂等(PG/SQLite `ON CONFLICT DO NOTHING`、MySQL `INSERT IGNORE`) |
460
+ | 原生表 | `raw_update(table_name, data, where, params=None) -> int` | 按 `where`(不含 `WHERE`)更新;启用审计填充时自动补 `updated_*` |
461
+ | 原生表 | `raw_touch(table_name, where, params=None) -> int` | 只刷新 `updated_*`(需先 `enable`;表无该列抛 `DBError`) |
462
+ | 原生表 | `raw_delete(table_name, where, params=None) -> int` | 条件删除(`where` 必填) |
463
+ | 原生表 | `build_raw_insert / build_raw_update / build_raw_touch / build_raw_delete` | 只拼装不执行,返回 `(语句, 参数)`,供**自有事务**内 `session.execute(*builder(...))` |
464
+ | 原生表 | `raw_get_by(table_name, column, value) -> dict \| None` | 按单列等值取首行 |
465
+ | 事务 | `transaction()` | 事务上下文管理器,`with PgKit.transaction() as session:` |
466
+ | 表 | `list_tables() -> list[str]` | 列出全部表名 |
467
+ | 表 | `table_exists(table_name) -> bool` | 判断表是否存在 |
468
+ | 表 | `create_tables(models) -> None` | 按模型列表建表 |
469
+ | 表 | `get_table_info(table_name) -> list[dict]` | 获取列信息(按列序;公共键 4 个:`column_name`/`data_type`/`is_nullable`/`column_default`) |
470
+
471
+ > **列表参数(`IN`)**:`query` / `execute` 的 `params` 中值为 `list`/`tuple`/`set`/`frozenset`
472
+ > 时按 `IN` 展开,可直接写 `WHERE id IN :ids`(三库通用)。`IN` **不保证顺序**;参数列表过大
473
+ > 应分批(PG 单语句上限 65535 参数)。
474
+ >
475
+ > **`LIKE` 的方言差异**:SQLite 对 ASCII 不区分大小写,PostgreSQL 区分(用 `ILIKE`);
476
+ > 跨库一致写法:`LOWER(col) LIKE LOWER(:pattern)`。
477
+ >
478
+ > **导出面**:`from yimo.kit.db import PgKit, SQLiteKit, build_pg_url, to_vector_literal, …`
479
+ > (`kit` 顶层与 `yimo.kit.db` 导出同一套符号)。
480
+
481
+ ```python
482
+ from sqlalchemy import BigInteger
483
+ from sqlmodel import SQLModel, Field
484
+ from yimo.kit.common_kit import CommonKit
485
+ from yimo.kit.db import SQLiteKit # 也可 from yimo.kit.db.sqlite_kit import SQLiteKit
486
+
487
+ class User(SQLModel, table=True):
488
+ # 主键:64 位整数 + 雪花 ID(应用侧生成,不用数据库自增)
489
+ id: int = Field(default_factory=CommonKit.generate_snowflake_id,
490
+ primary_key=True, sa_type=BigInteger)
491
+ name: str
492
+
493
+ SQLiteKit.connect()
494
+ SQLiteKit.create_tables([User])
495
+
496
+ user = SQLiteKit.create(User, {"name": "张三"}) # 自动提交
497
+ SQLiteKit.update(User, user.id, {"name": "李四"})
498
+ users = SQLiteKit.list(User, skip=0, limit=10, order_by="id", desc=True)
499
+
500
+ rows = SQLiteKit.query("SELECT * FROM user WHERE name = :name", {"name": "李四"})
501
+ affected = SQLiteKit.execute("UPDATE user SET name = '王五' WHERE id = :id", {"id": user.id})
502
+ rows = SQLiteKit.query("SELECT * FROM user WHERE id IN :ids", {"ids": [1, 2, 3]}) # 列表参数
503
+
504
+ with SQLiteKit.transaction() as session: # 多操作原子提交
505
+ SQLiteKit.create(User, {"name": "批量一"})
506
+ SQLiteKit.create(User, {"name": "批量二"})
507
+ ```
508
+
509
+ > 切换数据库:把 import 的 `SQLiteKit` 换成 `PgKit` / `MySqlKit` 即可,其余代码不变。
510
+ > 注意三点例外:① `create_raw_table` 的列定义文本须按目标库方言改写;② 向量能力
511
+ > **三库同名同参但能力不同**(可由 `VECTOR_CAPABILITIES` feature-detect),尤其
512
+ > **MySQL 侧检索不可用**;③ `create_vector_table` 的 `dims` 为**必填**参数。
513
+
514
+ ### 2. 向量方法(三库同名同参,能力差异化)
515
+
516
+ > 签名在 `SQLiteKit` / `PgKit` / `MySqlKit` 上完全一致;能力按后端不同(见下表)。
517
+ > extra 前提:SQLite 需 `yimo-kit[sqliteai]`;PG 需 `yimo-kit[pg]` **且服务端已装 pgvector**
518
+ > (`create_vector_table` 会自动尝试 `CREATE EXTENSION`);MySQL 需 **9.x**(Community 即可存,
519
+ > 但检索需 HeatWave on OCI / MySQL AI)——建表前会校验服务端版本,低于 9.x 抛 `DBError`。
520
+
521
+ | 方法 | 说明 |
522
+ |------|------|
523
+ | `create_vector_table(table_name, dims, id_col="id", column="embedding", extra_cols=None) -> None` | 建含向量列的表;**`dims` 必填**(SQLite 用 `CHECK` 落实为数据库层约束;PG 硬约束并回读校验已存在表;MySQL 为上限语义)。`extra_cols` 支持 `{列名: 类型串}`(推荐,与 `create_raw_table` 同形)与 `[{"name","type"}]` 两种形态 |
524
+ | `insert_vectors(table_name, vectors, ids=None, extra_data=None, id_col="id", column="embedding") -> int` | 批量插入向量(**自成一事务并提交**);`ids=None` 时由 Kit 生成雪花 ID;接受 `list[list[float]]` 或二维 numpy 数组 |
525
+ | `build_insert_vectors(table_name, vectors, ids=None, extra_data=None, id_col="id", column="embedding") -> list[tuple[str, list[dict]]]` | **只拼装、不执行、不管事务**:返回按列集分组的 `(SQL, 参数列表)`,供调用方在**自有事务**内写向量行(见「自有事务内写向量」) |
526
+ | `search_vectors(table_name, query_vector, top_k=10, distance_type="L2", filter_sql=None, exact=True, id_col="id", column="embedding") -> list[dict]` | KNN 检索,按距离升序返回 `{"id", "distance"}`;`exact=True`(默认)禁止近似加速;**MySQL 侧抛 `VectorNotSupportedError`** |
527
+ | `vector_column_dimension(table_name, column="embedding") -> int \| None` | 查列**声明的维度**:PG 为精确维度(`vector(1024)`→1024);MySQL 为**最大上限**(未指定维度落 `2048`);SQLite 恒 `None`(无元数据)。列不存在 / 非向量列 / 无维度声明 → `None`,不抛异常。口径差异由 `VECTOR_CAPABILITIES["dimension_kind"]` 声明(`"exact"` / `"max"` / `None`) |
528
+ | `vector_version() -> str` | 向量后端版本;不可用时返回 `"unavailable"`(MySQL 侧为服务端版本号) |
529
+
530
+ **`id_col` / `column`(逃生口)**:让**自建 DDL 的向量表**也能读写/检索。需要复合主键、额外约束、
531
+ 分区或与既有业务表合表时,用 `execute()` 自建 DDL 再用这两个参数接入;SQLite 侧要求 `id_col`
532
+ 为 rowid 别名(`INTEGER PRIMARY KEY`)。
533
+
534
+ **`exact` 参数(默认 `True` = 禁止近似加速)**:
535
+
536
+ | 后端 | `exact=True`(默认) | `exact=False` | 是否提速 |
537
+ |------|---------------------|---------------|----------|
538
+ | `PgKit` | 同事务 `SET LOCAL enable_indexscan = off`(有索引也精确;**代价:该查询不使用任何索引**,含过滤列索引) | 不干预查询计划(有索引即近似召回,`distance` 仍为真值) | ✅ 仅"大表 + 已建索引"时 |
539
+ | `SQLiteKit` | `vector_full_scan`(**真值 L2**) | `vector_quantize_scan`(量化 L2 = 真值 × 255) | ❌ **不提速**(每次调用重建量化) |
540
+ | `MySqlKit` | 不适用 | 同左 | — |
541
+
542
+ **能力差异(仅 L2 可跨库比较数值;float32 vs float64,需带容差)**:
543
+
544
+ | 项 | `SQLiteKit`(sqlite-vector) | `PgKit`(pgvector) | `MySqlKit`(9.x 原生) |
545
+ |----|------------------------------|---------------------|------------------------|
546
+ | 支持的 `distance_type` | **仅 L2** | `COSINE` / `L2` / `L1` / `DOT`(负内积) / `SQUARED_L2` | **无(检索不可用)** |
547
+ | 默认 `distance_type` | `"L2"` | `"L2"`(三库统一,不按后端覆写) | `"L2"`(形参保留,调用即抛错) |
548
+ | 非法取值 | 抛 `ValueError` | 抛 `ValueError` | `search_vectors` 抛 `VectorNotSupportedError` |
549
+ | `distance` 口径 | `exact=True` 真值 L2 / `exact=False` 量化(×255) | 真实距离 | — |
550
+ | 维度约束 | `CHECK`(仅新表;旧表靠方法内校验) | 强制(不匹配即报错;建表时回读比对) | **上限**(`VECTOR(N)` 的 N 是最大维度,写入须 ≤ N,超限报 `1406 Data too long`) |
551
+ | 维度查询 | 恒 `None`(无元数据) | 精确维度(`dimension_kind="exact"`) | 最大上限(`dimension_kind="max"`) |
552
+ | `filter_sql` 与 `top_k` | **先过滤再取 top_k**(与 PG 一致) | **先过滤再取 top_k** | 不适用 |
553
+ | 索引 | 无(精确路径为全表扫描) | kit 不建索引;**自建后须 `exact=False` 才会被使用** | 无法建(B-Tree 拒绝向量列) |
554
+
555
+ > MySQL `DISTANCE()` / `VECTOR_DISTANCE()` 仅 HeatWave on OCI 与 MySQL AI 提供
556
+ > (Community 实测报 `1305 FUNCTION ... does not exist`);故 `MySqlKit` 只覆盖存储侧。
557
+ >
558
+ > 维度上限(插件侧实测 pgvector 0.8.7):`vector` ≤ **16000** 维;hnsw / ivfflat 索引
559
+ > ≤ **2000** 维;`halfvec` 表达式索引 ≤ **4000** 维。因此 **1024 维表可建 HNSW,
560
+ > 2560 / 4096 维表建不了**。
561
+
562
+ **主键与 id(三库统一)**:向量表主键均为 `BIGINT`(SQLite 用等价的 64 位 `INTEGER PRIMARY KEY`),
563
+ **不使用数据库自增**;`ids=None` 时由 Kit 用 `CommonKit.generate_snowflake_id()` 生成雪花 ID
564
+ (18~19 位,int64)。
565
+ ⚠ 雪花 ID 超过 `2^53`,经 JSON 传给 JavaScript 会丢精度,需按字符串传输;
566
+ 多实例部署需各自 `CommonKit.configure(datacenter_id, machine_id)`(默认 `(1,1)` 会重复)。
567
+
568
+ ```python
569
+ # SQLite(默认精确:distance 为真值 L2)
570
+ from yimo.kit.db.sqlite_kit import SQLiteKit
571
+ SQLiteKit.create_vector_table("images", 384) # dims 必填
572
+ SQLiteKit.insert_vectors("images", [[0.1] * 384, [0.2] * 384])
573
+ rows = SQLiteKit.search_vectors("images", [0.1] * 384, top_k=5)
574
+ rows = SQLiteKit.search_vectors("images", [0.1] * 384, top_k=5, exact=False) # 旧量化口径(不提速)
575
+
576
+ # PostgreSQL(签名相同;可选 COSINE/L2/L1/DOT/SQUARED_L2)
577
+ from yimo.kit.db.pg_kit import PgKit
578
+ PgKit.create_vector_table("images", 384)
579
+ PgKit.insert_vectors("images", [[0.1] * 384, [0.2] * 384])
580
+ rows = PgKit.search_vectors("images", [0.1] * 384, top_k=5, distance_type="COSINE")
581
+ # 大表 + 自建索引时才用 exact=False(否则索引不被使用,见上表)
582
+ PgKit.execute("CREATE INDEX ON images USING hnsw (embedding vector_cosine_ops)")
583
+ rows = PgKit.search_vectors("images", [0.1] * 384, top_k=5,
584
+ distance_type="COSINE", exact=False)
585
+
586
+ # MySQL(仅存储;search_vectors 抛 VectorNotSupportedError)
587
+ from yimo.kit.db.mysql_kit import MySqlKit
588
+ MySqlKit.create_vector_table("images", 384)
589
+ MySqlKit.insert_vectors("images", [[0.1] * 384, [0.2] * 384])
590
+
591
+ # 能力自省(无需 try/except)
592
+ PgKit.VECTOR_CAPABILITIES
593
+ # {'store': True, 'search': True, 'exact': True,
594
+ # 'distances': ('COSINE', 'L2', 'L1', 'DOT', 'SQUARED_L2'),
595
+ # 'distance_kind': 'true', 'fast_distance_kind': 'true',
596
+ # 'dimension_kind': 'exact'} # MySQL='max' / SQLite=None
597
+
598
+ # 查询库列声明的维度(守卫「配置 vs 库列」用;查不到返回 None)
599
+ PgKit.vector_column_dimension("images", "embedding") # 384
600
+
601
+ # 自建 DDL 的表:用 id_col / column 接入
602
+ PgKit.execute("CREATE TABLE my_vec (vid BIGINT PRIMARY KEY, vec vector(384))")
603
+ PgKit.insert_vectors("my_vec", [[0.1] * 384], ids=[1], id_col="vid", column="vec")
604
+ PgKit.search_vectors("my_vec", [0.1] * 384, top_k=5, id_col="vid", column="vec")
605
+ ```
606
+
607
+ > ⚠ `:name::type` 这类 PostgreSQL 风格 cast **不被 SQLAlchemy 的 `text()` 识别**,
608
+ > 请改用 `CAST(:name AS type)`。
609
+
610
+ **两段查询范式(推荐用法)**:`search_vectors` 只返回 `[{"id", "distance"}]`,载荷二次取回:
611
+
612
+ ```python
613
+ hits = SQLiteKit.search_vectors("item_vectors", query_vector, top_k=5)
614
+ rows = SQLiteKit.query("SELECT id, title FROM items WHERE id IN :ids",
615
+ {"ids": [h["id"] for h in hits]}) # IN 不保证顺序,需按 hits 重排
616
+ ```
617
+
618
+ **自有事务内写向量(推荐:`build_insert_vectors` + `transaction()`)**:
619
+
620
+ ```python
621
+ from yimo.kit.db import SQLiteKit, prepare_statement # 无须 import sqlalchemy
622
+
623
+ with SQLiteKit.transaction() as session: # 换成 PgKit / MySqlKit 写法相同
624
+ stmt, bound = prepare_statement(
625
+ "INSERT INTO docs_item (id, title) VALUES (:id, :t)", {"id": doc_id, "t": title})
626
+ session.execute(stmt, bound) # 第二个值必须一并传入
627
+ for sql, params in SQLiteKit.build_insert_vectors("docs_doc_vectors", vectors,
628
+ ids=row_ids, extra_data=metas,
629
+ id_col="rowid"):
630
+ session.execute(*prepare_statement(sql, params))
631
+ # 正常退出统一提交;异常自动回滚(多处写入保持同一事务)
632
+ ```
633
+
634
+ **SQLite 的 DBAPI 变体**(`raw_connection()` 支持 `:name` 命名参数):
635
+
636
+ ```python
637
+ conn = SQLiteKit.raw_connection() # 调用方负责 commit / close
638
+ try:
639
+ for sql, params in SQLiteKit.build_insert_vectors("item_vectors", vectors,
640
+ ids=row_ids, extra_data=metas):
641
+ conn.executemany(sql, params)
642
+ conn.commit()
643
+ finally:
644
+ conn.close()
645
+ ```
646
+
647
+ > ⚠ 两点约束:① `build_insert_vectors` 输出为 `:name` 风格,**PG / MySQL 的原生 DBAPI 不支持**
648
+ > (psycopg2 / pymysql 需 `%(name)s`),只能经 `transaction()` 的 session 执行;
649
+ > ② SQLite 上**持有未提交写事务**时再调 kit 的**自提交**方法(如 `insert_vectors`)会因另一个连接
650
+ > 拿不到写锁而失败(`OperationalError: database is locked`,约 **6.4s** 后才报错)——
651
+ > 把写入并入**同一个** `transaction()`(如上)即可避免。
652
+
653
+ > 相似度换算建议:SQLite 仅支持 L2,若向量入库前已**归一化**,则 `cos = 1 − L2²/2`;
654
+ > PG 可直接用 `distance_type="COSINE"`。
655
+
656
+ ### 3. 审计字段自动填充与软删除过滤(默认关闭)
657
+
658
+ `AuditConfig.enable(...)` 后,kit 的写入口自动补齐审计字段;`set_soft_delete_filter(True)`
659
+ 后查询自动只看未删除记录。**两项默认都关闭**,不调用时行为与旧版完全一致。
660
+
661
+ ```python
662
+ from yimo.kit.db import AuditConfig, PgKit
663
+
664
+ AuditConfig.enable(user_resolver=get_current_userid) # 启动时调用一次
665
+ AuditConfig.set_soft_delete_filter(True) # 可选:查询过滤软删除
666
+ ```
667
+
668
+ 填充字段(默认列名 + 内置别名):
669
+
670
+ | 槽位 | 默认列名 | 内置别名 | 说明 |
671
+ |------|----------|----------|------|
672
+ | `created_at` | `created_at` | `create_time` | 创建时间 |
673
+ | `created_by` | `created_by` | — | 创建人 |
674
+ | `updated_at` | `updated_at` | `update_time` | 更新时间 |
675
+ | `updated_by` | `updated_by` | — | 更新人 |
676
+ | `deleted` | `deleted` | — | `0` 正常 / `1` 删除 |
677
+
678
+ **内置别名无需配置**:表里的时间列若叫 `create_time` / `update_time`,同样会被识别;
679
+ 两套列同时存在时两列都填(同值)。
680
+
681
+ 判定只有两条(同时满足才填):**表中存在该列** + **本次写入数据中该字段为空**
682
+ (`None` / 空串 / 纯空白;`0` 与 `False` 不算空)。显式非空值一律保留,
683
+ **不存在覆盖语义**;「当前值」指本次写入的数据,不是数据库已存值。
684
+
685
+ | 动作 | `created_at` / `create_time` | `updated_at` / `update_time` | `deleted` |
686
+ |------|------------------------------|------------------------------|-----------|
687
+ | INSERT | 空才填 | 空才填(与 created 同值) | 空才填 `0`(字符串列填 `"0"`) |
688
+ | UPDATE | **不参与** | 空才填 | **不参与** |
689
+
690
+ 落点:ORM flush(`before_flush`)、`CRUDBase.update_multi` / `upsert`、
691
+ `raw_insert` / `raw_update`。**`execute()` 手写 SQL 与批量 executemany 不填充**。
692
+
693
+ ```python
694
+ PgKit.raw_insert("chat_session", {"id": 1, "title": "t"})
695
+ # → 自动补 created_at/created_by/updated_at/updated_by 与 deleted=0
696
+
697
+ PgKit.raw_update("chat_session", {"title": "t2"}, "id = :id", {"id": 1})
698
+ # → 只刷 updated_at / updated_by;where 的值全部走绑定参数
699
+
700
+ PgKit.raw_get_by("chat_session", "id", 1) # 过滤开启时自动排除已删除行
701
+
702
+ with AuditConfig.include_deleted(): # 需要读已删除记录时临时绕过
703
+ PgKit.get(Model, 1)
704
+ ```
705
+
706
+ 自定义字段名(列名与约定完全不同时):
707
+
708
+ ```python
709
+ AuditConfig.set_fields({"created_at": "create_on", "deleted": "del_flag"})
710
+ AuditConfig.fields() # 查看当前「槽位 → 实际列名」
711
+ AuditConfig.set_fields(None) # 恢复默认
712
+ ```
713
+
714
+ 约定与局限:
715
+
716
+ - `set_fields` 的列名必须是合法标识符(字母 / 数字 / 下划线,不以数字开头),
717
+ 否则立即 `ValueError`——列名会被拼进 SQL 的标识符位置。
718
+ - `deleted` 支持整数列(填 `0`)与字符串列(填 `"0"`,`VARCHAR` / `CHAR` / `TEXT`);
719
+ **boolean 列不支持**(会报类型错误)。
720
+ - 查询过滤严格等值 `deleted = 0`(字符串列 `"0"`);`NULL` **不**视为未删除,历史数据需自行回填。
721
+ - 写方法与 `query()` 手写 SQL 不追加过滤条件;`upsert` 的冲突回查跳过过滤。
722
+ - `user_resolver` 返回 `None` / 空串或抛异常时跳过 `*_by` 填充,不影响写入。
723
+
724
+ **原生写工具**:`raw_insert` / `raw_update` / `raw_touch` / `raw_delete` 自带事务;
725
+ `build_raw_*` 只拼装(返回 `(语句, 参数)`),供 `with Kit.transaction() as session:` 内使用:
726
+
727
+ ```python
728
+ with PgKit.transaction() as session:
729
+ session.execute(*PgKit.build_raw_insert("docs_tag", {"id": 1}, ignore_conflict=True))
730
+ session.execute(*PgKit.build_raw_touch("docs_item", "id = :id", {"id": 1}))
731
+ ```
732
+
733
+ - `ignore_conflict=True`:PG/SQLite `ON CONFLICT DO NOTHING`、MySQL `INSERT IGNORE`
734
+ (⚠ MySQL 忽略范围更宽,含数据截断告警);冲突被忽略时返回 `0`。
735
+ - `raw_touch`:只刷新 `updated_*`(含别名 `update_time`),需先 `enable`;表无该列抛 `DBError`。
736
+ - 写入值:`dict` 自动编码为 JSON 文本;`list` 仅在 JSON 列编码,其它列抛 `ValueError`
737
+ (避免被当作 `IN` 展开破坏 SQL;数组 / 向量请用字符串或 `execute()`)。
738
+
739
+ ### 4. CRUDBase(配合 session_scope,不自动提交)
740
+
741
+ ```python
742
+ from yimo.kit.db import CRUDBase, session_scope
743
+
744
+ user_crud = CRUDBase(User)
745
+
746
+ with session_scope() as session: # 正常退出提交、异常回滚
747
+ user_crud.create(session, {"name": "张三"})
748
+ user_crud.update(session, user_crud.get(session, 1), {"name": "李四"})
749
+ ```
750
+
751
+ | 方法 | 说明 |
752
+ |------|------|
753
+ | `CRUDBase(model)` | 构造,传入 SQLModel 模型类 |
754
+ | `get(session, id) -> Model \| None` | 按主键取单条 |
755
+ | `get_or_raise(session, id) -> Model` | 按主键取,缺失抛 `NotFoundError` |
756
+ | `get_multi(session, *, skip=0, limit=100, order_by=None, desc=False) -> list[Model]` | 分页 + 排序 |
757
+ | `get_by_field(session, field_name, field_value) -> Model \| None` | 按字段等值取单条 |
758
+ | `get_multi_by_field(session, field_name, field_value, *, skip=0, limit=100) -> list[Model]` | 按字段等值分页取多条 |
759
+ | `create(session, obj_in) -> Model` | 插入单条(add + flush) |
760
+ | `create_multi(session, objs_in) -> list[Model]` | 批量插入(add_all + flush) |
761
+ | `update(session, db_obj, obj_in) -> Model` | 更新,入参为模型实例或字典 |
762
+ | `update_multi(session, ids, obj_in) -> int` | 单条批量 UPDATE,返回影响行数 |
763
+ | `delete(session, id) -> Model \| None` | 按主键删除 |
764
+ | `delete_multi(session, ids) -> int` | 单条批量 DELETE,返回影响行数 |
765
+ | `count(session) -> int` | 记录总数 |
766
+ | `exists(session, id) -> bool` | 主键是否存在 |
767
+ | `upsert(session, obj_in, conflict_fields) -> Model` | 原生 `INSERT ... ON CONFLICT / ON DUPLICATE KEY` 原子语句 |
768
+
769
+ > 约定:`SQLiteKit / PgKit / MySqlKit` 方法自动提交;`CRUDBase` 方法**不提交**,事务边界由外层 `session_scope` 或 `@transactional` 决定。
770
+
771
+ ### 5. 引擎 / 会话 / 事务 / 异常
772
+
773
+ | 符号 | 签名 | 说明 |
774
+ |------|------|------|
775
+ | `get_engine` | `(db_type=None, **kwargs) -> Engine` | 线程安全引擎单例,`**kwargs` 首次创建时透传 `create_engine` |
776
+ | `create_tables` | `(models, db_type=None) -> None` | 按模型列表建表 |
777
+ | `list_tables` | `(db_type=None) -> list[str]` | 列出全部表 |
778
+ | `table_exists` | `(table_name, db_type=None) -> bool` | 判断表是否存在 |
779
+ | `close_engine` | `(db_type) -> None` | 关闭并移除指定类型引擎 |
780
+ | `close_all_engines` | `() -> None` | 关闭全部引擎 |
781
+ | `session_scope` | `(db_type=None, *, autocommit=True)` | 唯一会话入口:正常提交、异常回滚、最终关闭 |
782
+ | `get_session` | `(db_type=None) -> Session` | 裸 Session,调用方自管生命周期 |
783
+ | `transactional` | `(db_type=None, *, retry_count=0, retry_delay=0.5)` | 事务装饰器:自动注入 `session` 参数、失败退避重试 |
784
+ | `POSTGRESQL` / `MYSQL` / `SQLITE` | `"postgresql"` / `"mysql"` / `"sqlite"` | 数据库类型常量 |
785
+ | `DBError` | 继承 `SQLAlchemyError` | 数据库异常基类 |
786
+ | `NotFoundError` | 继承 `DBError` | 记录不存在 |
787
+
788
+ ```python
789
+ from yimo.kit.db import transactional
790
+ from sqlmodel import Session
791
+
792
+ @transactional(retry_count=3)
793
+ def transfer(session: Session, from_id: int, to_id: int, amount: float) -> None:
794
+ # 被装饰函数必须接受 session 参数;退出时自动提交,异常自动回滚并重试
795
+ ...
796
+ ```
797
+
798
+ ### 6. 模型混入类与查询构建器
799
+
800
+ ```python
801
+ from sqlalchemy import BigInteger
802
+ from sqlmodel import Field, SQLModel
803
+
804
+ from yimo.kit.common_kit import CommonKit
805
+ from yimo.kit.db.models import TimestampMixin, SoftDeleteMixin, AuditMixin
806
+
807
+ class Article(TimestampMixin, SoftDeleteMixin, SQLModel, table=True):
808
+ # 主键:64 位整数 + 雪花 ID(应用侧生成,不用数据库自增)
809
+ id: int = Field(default_factory=CommonKit.generate_snowflake_id,
810
+ primary_key=True, sa_type=BigInteger)
811
+ title: str
812
+ ```
813
+
814
+ | 混入类 | 字段 |
815
+ |--------|------|
816
+ | `TimestampMixin` | `created_at`(UTC)、`updated_at` |
817
+ | `SoftDeleteMixin` | `is_deleted`、`deleted_at` |
818
+ | `AuditMixin` | 时间戳字段 + `created_by`、`updated_by` |
819
+
820
+ 查询构建器需显式从子模块导入(未进入 `yimo.kit.db` 顶层导出):
821
+
822
+ ```python
823
+ from yimo.kit.db.query import QueryBuilder, QueryCache, QueryOptimizer, cached_query
824
+
825
+ qb = QueryBuilder(User, session)
826
+ active = qb.filter(User.name == "张三").all() # 链式不可变,每步返回新实例
827
+ page = qb.paginate(page=1, per_page=20) # {"items", "total", ...}
828
+ ```
829
+
830
+ | 类 | 方法 |
831
+ |----|------|
832
+ | `QueryBuilder(model, session)` | `filter(*conditions)`、`filter_by(**kwargs)`、`join(target, onclause=None, isouter=False)`、`order_by(*columns)`、`limit(n)`、`offset(n)`、`distinct()`、`only(*field_names)`、`all()`、`first()`、`count()`、`exists()`、`paginate(page=1, per_page=20)` |
833
+ | `QueryCache(default_ttl=300, maxsize=1000)` | `get(key)`、`set(key, value, ttl=None)`、`delete(key)`、`clear()`、`clean_expired()` |
834
+ | `QueryOptimizer(session)` | `explain(statement)`、`suggest_indexes(model, query_fields)`、`measure(statement, params=None)`、`stats`、`clear_stats()` |
835
+ | `cached_query(ttl=300, maxsize=1000)` | 查询结果缓存装饰器 |
836
+
837
+ ---
838
+
839
+ ## yimo.kit.ai —— AI 多模型服务池
840
+
841
+ 安装:`pip install "yimo-kit[ai]"`
842
+
843
+ 传输:chat / embedding / image 走 `openai` SDK(`>=3.54,<4`,
844
+ 自带 `httpx2`),rerank 走 httpx 自研传输(SDK 无 `/rerank` 资源)。
845
+ 档案里的 `endpoint` **对前三类不再生效**——SDK 固定拼 `/chat/completions`、
846
+ `/embeddings`、`/images/generations`,仅 rerank 仍使用该字段(探活走 openai SDK 的 `GET {base_url}/models`,不读本字段)。
847
+
848
+ > 安装提示:`openai` 3.x 会引入 `httpx2`,与 rerank 用的 `httpx` 并存(两个包名不同,不冲突)。
849
+
850
+ 档案:项目根 `config/ai_models.json`(见文末「AI 档案文件」)
851
+
852
+ ### 1. 同步门面 `AI`(推荐)
853
+
854
+ ```python
855
+ from yimo.kit.ai import AI, shutdown
856
+
857
+ text = AI.chat_once("用一句话介绍 Python") # 单轮对话
858
+ hits = AI.rerank("水声通信", ["文档A", "文档B"], top_n=2) # 重排序
859
+ url = AI.image("一只在写代码的猫") # 文生图
860
+ AI.use("chat", "glm") # 切换当前档案(进程内长期生效)
861
+ print(AI.available("chat")) # 查看各档案状态快照
862
+ shutdown() # 应用退出前释放资源(幂等)
863
+ ```
864
+
865
+ | 分组 | 方法 | 说明 |
866
+ |------|------|------|
867
+ | chat | `chat_once(prompt, *, max_tokens=None, thinking=None, json_mode=None, response_format=None, stats=None) -> str` | 单轮对话(仅 user 消息) |
868
+ | chat | `chat(messages, *, max_tokens=None, thinking=None, json_mode=None, response_format=None, stats=None) -> str` | 多轮对话,`messages` 为 `[{"role": "user", "content": "..."}]` |
869
+ | chat | `chat_stream(messages, *, max_tokens=None, thinking=None, json_mode=None, response_format=None) -> Iterator[str]` | 同步流式逐 token 迭代器(建议 `with` 使用);结束后可读 `reasoning_chars` / `content_chars` / `finish_reason` / `requested_max_tokens` / `truncated` / `empty_kind` / `thinking_applied` / `json_mode_applied` |
870
+ | embedding | `create(text) -> list[float]` | 单文本向量化 |
871
+ | embedding | `create_batch(texts) -> list[list[float]]` | 批量向量化 |
872
+ | rerank | `rerank(query, documents, top_n=None) -> list[RerankHit]` | 返回 `RerankHit`(`index` / `score` / `document`)降序列表;**`top_n` 是返回条数上限,由 kit 本地裁剪**(服务端返回超量也按分数截断),`top_n=None` 返回全部命中,`top_n<=0` 直接返回空列表 |
873
+ | image | `image(prompt, *, size=None, n=1, return_base64=False, ratio=None) -> ImageResult` | 文生图,返回 `ImageResult`(`url` / `b64` 至少一个非空) |
874
+ | 管理 | `use(model_type, profile) -> None` | 切换该类型当前档案(`chat` / `embedding` / `rerank` / `image`) |
875
+ | 管理 | `available(model_type) -> list[ProfileStatus]` | 各档案状态快照(含未配置密钥与被剔除者);**类型未在 `ai_models.json` 中配置时返回 `[]`**(不再抛异常),类型名非法抛 `AIModelTypeNotConfiguredError`(`AIConfigError` 子类) |
876
+ | 管理 | `reload_config(*, model_type=None, reload_file=False, probe=True, immediate=False) -> ReloadResult` | 配置热重载,改密钥 / 档案后无需重启;同时清空思考/结构化输出的告警去重表(修正档案后同一原因会重新提示) |
877
+
878
+ **可用性查询(`available`)**:`available` 返回的是**状态快照**,不是「可用档案列表」。
879
+ 判断某类型是否已配置用 `if not AI.available(t)`,不要靠捕获异常:
880
+
881
+ ```python
882
+ from yimo.kit.ai import AI
883
+
884
+ profiles = AI.available("image") # ai_models.json 无 image 段 → []
885
+ if not profiles:
886
+ raise RuntimeError("尚未配置图像生成模型")
887
+ current = next((p for p in profiles if p.current), None)
888
+ ```
889
+
890
+ > 旧写法 `try: AI.available(t) except AIConfigError: ...` 仍可用(异常分支不再触发);
891
+ > `AI.available(t)[0]` 在类型未配置时会抛 `IndexError`,请改用上面的判空写法。
892
+
893
+ ```python
894
+ from yimo.kit.ai import AI
895
+
896
+ with AI.chat_stream([{"role": "user", "content": "写一首短诗"}]) as stream:
897
+ for token in stream: # 逐 token 消费
898
+ print(token, end="", flush=True)
899
+ ```
900
+
901
+ #### 流式收尾统计(思考型模型必备)
902
+
903
+ 迭代器在流结束后可读八个字段(`reasoning_chars` / `content_chars` / `finish_reason` /
904
+ `requested_max_tokens` / `truncated` / `empty_kind` / `thinking_applied` / `json_mode_applied`),
905
+ 其中 `truncated` 与 `empty_kind` 是只读派生属性。用于区分「模型真的没返回」与「输出预算被思考吃光」——
906
+ 思考型模型的推理 token 计入 `max_tokens`,长上下文 + 小预算时常出现「返回 200 但正文为空」
907
+ (同一套字段也可用于非流式 `ask` / `complete`,见下文「结构化输出」)。
908
+
909
+ `empty_kind` 把「正文为空」分成五类,不再一律归因为预算耗尽:
910
+
911
+ | 取值 | 判定 | 建议处置 |
912
+ |---|---|---|
913
+ | `budget_exhausted` | 被长度截断且有推理 | 调大 `max_tokens`,或对该调用传 `thinking=False` |
914
+ | `truncated_empty` | 被长度截断且无推理 | 调大 `max_tokens`;若模型支持独立推理预算,确认推理是否计入输出配额 |
915
+ | `reasoning_only` | 有推理、`finish_reason=stop`、正文 0 | 提高预算或换模型 |
916
+ | `no_finish` | 结束原因缺失或非 `stop`(端点未发送 `finish_reason`) | 可原样重试;连续出现检查端点 |
917
+ | `stopped_empty` | 无推理、`finish_reason=stop`、正文 0 | 检查提示词与模型输出 |
918
+
919
+ 正文非空时 `empty_kind is None`。判定只用「是否截断 + 是否有推理 + 结束原因」,不依赖 token 数(kit 目前不采集 `usage`)。
920
+ 注意:该属性**仅在流正常结束后可读**,迭代中与异常 / 中断后为 `None`(避免把「正文还没到」误判成 `no_finish`);`requested_max_tokens` 无此限制。
921
+
922
+ ```python
923
+ with AI.chat_stream(messages, max_tokens=450) as stream:
924
+ body = "".join(stream)
925
+ if not body:
926
+ match stream.empty_kind:
927
+ case "budget_exhausted" | "truncated_empty":
928
+ ... # 调大 max_tokens(或配独立推理预算)
929
+ case "no_finish":
930
+ ... # 原样重试
931
+ ```
932
+
933
+ `requested_max_tokens` 是本次**实际下发**的输出上限(调用方传值优先,否则取档案 `max_tokens`;都没有为 `None`),
934
+ 在发请求前写入,失败/中断时也可读——业务可据此判断「预算是否真的设够了」。
935
+
936
+ - 推理字段兼容 `delta.reasoning_content`(GLM / DeepSeek / Qwen)与 `delta.reasoning`(sensenova):只计数不产出;
937
+ - 推理字段名是 kit 内部白名单(当前就是上面两种):新 provider 若用别的字段名,`reasoning_chars` 会恒为 0——此时仍可用 `truncated` / `empty_kind` 判定;
938
+ - 正文为空时 kit 按 `empty_kind` 分级打 `WARNING`(含模型、`max_tokens`、`finish_reason` 与推荐处置),不再统一归因「预算被思考耗尽」;
939
+ - `truncated` 覆盖 `finish_reason` 为 `length` 或 `max_tokens` 两种口径;
940
+ - **字符数 ≠ token 数**(实测中文约 2~2.5 字符/token,各家口径不一),不要用 `reasoning_chars` 反推还差多少预算;
941
+ - provider 不返回 `finish_reason` 时 `finish_reason is None`、`truncated is False`;正文为空则归为 `no_finish`(可原样重试);
942
+ - 流式过程中读到的是尽力而为的中间值,**结束后才是最终值**;提前 `break` 时为截至中断的累计值。
943
+
944
+ #### 逐调用思考开关
945
+
946
+ 同一档案下按调用点切换思考(入库抽取关、章节生成开),不必复制档案:
947
+
948
+ ```python
949
+ AI.chat(messages, thinking=False) # 关闭思考
950
+ AI.chat(messages, thinking=True) # 开启思考
951
+ AI.chat(messages) # None:不干预(按档案 thinking.default;未配置则请求体逐字节不变)
952
+ ```
953
+
954
+ kit 不认识任何厂商字段名,请求体字段由档案 `thinking` 声明翻译(见「ai_models.json 可选字段」)。
955
+ 三条局限:
956
+
957
+ - **未声明即忽略**:档案没有 `thinking` 声明时,逐调用 `thinking` 被忽略并打 `WARNING`(不报错、不触发冷却),调用照常成功;
958
+ - **跨候选降级**:候选链切到未声明的备胎时,本次调用退回厂商默认(通常是开),只在日志与 `thinking_applied` 中体现;
959
+ - **不提供档位**:只有开/关;`low` / `medium` / `high` 这类分级本轮不支持(可用 `on` 直接给厂商取值)。
960
+
961
+ `thinking_applied`(流式迭代器属性 / `StreamStats` 字段):`None` 未要求干预 / `True` 已按声明注入 / `False` 要求了但被忽略。
962
+
963
+ > 设计说明:曾否决「新增 thinking / reasoning_effort 具名字段、只用 `extra_body`」,
964
+ > 该否决理由(候选链跨厂商,备胎收到未知字段会 400 → 冷却)已由「档案能力声明」机制解除——
965
+ > 字段只发给声明了它的候选,未声明者不注入。思考**档位**(`low/medium/high`)仍然不做。
966
+
967
+ > 首帧等待语义:每候选 60 秒内**一帧都没有**(含推理帧)才切下一候选;思考阶段的
968
+ > 推理帧算活动并重置窗口,不会误判健康模型失败、也不会重放整段 prompt。
969
+
970
+ #### 结构化输出(JSON 模式)
971
+
972
+ 只要「合法 JSON 对象」用 `json_mode=True`;要约束字段用协议的 `response_format` 原样透传:
973
+
974
+ ```python
975
+ answer = AI.chat(messages, json_mode=True) # 要求返回 JSON 对象
976
+
977
+ fmt = {
978
+ "type": "json_schema",
979
+ "json_schema": {
980
+ "name": "extract",
981
+ "strict": True,
982
+ "schema": {
983
+ "type": "object",
984
+ "properties": {"tags": {"type": "array", "items": {"type": "string"}}},
985
+ "required": ["tags"],
986
+ "additionalProperties": False,
987
+ },
988
+ },
989
+ }
990
+ answer = AI.chat(messages, response_format=fmt) # 严格模式:schema 由你负责
991
+ ```
992
+
993
+ - **缺省即注入(开箱即用)**:档案未声明 `structured_output` 时,`json_mode=True` 按 OpenAI 兼容默认写
994
+ `{"response_format": {"type": "json_object"}}`;**实测不支持该字段的端点必须在档案写
995
+ `"structured_output": false`**,否则会 400 并触发冷却。
996
+ - **kit 不校验 JSON**:`json_mode=True` 只是「要求」,返回可能仍是散文或被截断的 JSON;schema 的生成、
997
+ 校验、修补都不在 kit(`response_format` 写错即端点 400)。
998
+ - **互斥**:`json_mode` 与 `response_format` 同时给 → `ValueError`;`json_mode=False` 与 `None` 等效(不注入)。
999
+ - **跨候选降级**:切到已写 `false` 的备胎时本次调用退回普通文本,只在日志与 `json_mode_applied` 中体现。
1000
+ - **`stream=True` 兼容性未知**:部分端点会静默忽略 `response_format`,kit 不探测;流式 JSON 只能是半成品,kit 不做增量解析。
1001
+
1002
+ `json_mode_applied`(流式迭代器属性 / `StreamStats` 字段):`None` 未要求注入 / `True` 已注入 / `False` 要求了但该档案已关闭。
1003
+
1004
+ **非流式收尾统计**:`ask` / `complete` 也接受 `stats=StreamStats()`(类名沿用历史,流式与非流式共用同一累加器),
1005
+ 可读 `finish_reason` / `truncated` / `content_chars` / `reasoning_chars` / `json_mode_applied`:
1006
+
1007
+ ```python
1008
+ from yimo.kit.ai import StreamStats
1009
+
1010
+ stats = StreamStats()
1011
+ body = AI.chat(messages, json_mode=True, stats=stats)
1012
+ if stats.truncated: # finish_reason 为 length / max_tokens
1013
+ ... # 半截 JSON:直接重试或调大 max_tokens,不要尝试修复
1014
+ ```
1015
+
1016
+ > **非流式(`ask` / `complete`)的同款诊断**:provider 在截断时可能完全不返回 `content` 键,
1017
+ > 此时 kit 抛 `AIResponseError`,消息里带 `finish_reason` 与推理字符数(不再只报「content
1018
+ > 类型异常」,可直接判断是否被思考吃光);正文为空串时返回 `""` 并打 `WARNING`。
1019
+ > 返回类型(`str`)与异常类型均未改变。
1020
+
1021
+ > 门面仅面向**同步上下文**;若调用点本身在 async 函数内,请直接 `await` 原生异步服务,避免阻塞事件循环线程。
1022
+ > 模块级另有 `yimo.kit.ai.runner.reload_config(...)`、`run_sync(coro_factory, *, timeout=120.0)`、`shutdown()`。
1023
+
1024
+ ### 2. 原生异步服务
1025
+
1026
+ ```python
1027
+ from yimo.kit.ai import (
1028
+ ChatService, EmbeddingService, RerankService, ImageService, # 服务类
1029
+ RerankHit, ImageResult, StreamStats, ModelBuilder, # 结果类型 / 构建器
1030
+ )
1031
+
1032
+ service = ModelBuilder.build_chat() # 老按类型构建:build_chat / build_embedding / build_rerank / build_image
1033
+ answer = await service.create(messages) # 或 await service.create_once(prompt)
1034
+ await service.close()
1035
+ ```
1036
+
1037
+ | 类 | 方法 |
1038
+ |----|------|
1039
+ | `ChatService` | `create(messages, *, temperature=None, max_tokens=None, thinking=None, json_mode=None, response_format=None, stats: StreamStats \| None = None, deadline=None) -> str`、`create_once(prompt, *, ...) -> str`、`create_stream(messages, *, ..., stats: StreamStats \| None = None) -> AsyncIterator[str]`(传 `StreamStats()` 即可读收尾统计);`thinking` / `json_mode` / `response_format` 语义与门面一致 |
1040
+ | `EmbeddingService` | `create(text) -> list[float]`、`create_batch(texts, *, batch_size=None, concurrency=4) -> list[list[float]]`、`dimension` 属性(**目标维度**,见下) |
1041
+ | `RerankService` | `create(query, documents, *, top_n=None) -> list[RerankHit]`(已按 score 降序) |
1042
+ | `ImageService` | `create(prompt, *, size=None, n=1, return_base64=False, ratio=None) -> ImageResult` |
1043
+ | `ModelBuilder` | `build(model_type, model=None, *, api_key=None)` 及各类型专用 `build_chat / build_embedding / build_rerank / build_image` |
1044
+ | `SdkServiceBase` | `profile` 属性、`await close()`、支持 `async with` |
1045
+
1046
+ **embedding 维度契约**:`ai_models.json` 里 embedding 档案的 `dimension` 是**目标向量维度**
1047
+ (不是模型原生维度),`EmbeddingService` 保证输出恒等于它:
1048
+
1049
+ | 模型返回维 vs `dimension` | 行为 |
1050
+ |---|---|
1051
+ | 相等 | 原样返回(不归一化,逐字节不变) |
1052
+ | 更大 | **截断到该维度并做 L2 归一化**(依赖模型的 MRL 支持;非 MRL 模型截断后质量会退化) |
1053
+ | 更小 | 抛 `AIResponseError`(降维只能变小,不能放大) |
1054
+
1055
+ 用途:让「建表维度 = 配置维度 = 输出维度」共用一个数值——
1056
+ `create_vector_table(t, dims)` 与 `vector_column_dimension(t, col)` 都取该配置值,
1057
+ 换用原生维度更大的模型时无需重构向量列(换模型后需全量重新入库)。
1058
+
1059
+ > ⚠ 启用候选链时,**链内各档案的 `dimension` 必须一致**:故障切换后输出维度跟随被选中档案的配置。
1060
+
1061
+ ### 3. 异常
1062
+
1063
+ ```python
1064
+ from yimo.kit.ai.exceptions import (
1065
+ AIError, AIConfigError, AIRequestError, AITimeoutError,
1066
+ AIAggregateError, AIResponseError,
1067
+ )
1068
+ ```
1069
+
1070
+ | 异常 | 触发场景 / 可用属性 |
1071
+ |------|---------------------|
1072
+ | `AIError` | 基类 |
1073
+ | `AIConfigError` | 档案缺失或非法、档案不存在、密钥未配置、必填字段缺失、`default_profile` 未在 `profiles` 中定义(加载期校验) |
1074
+ | `AIModelTypeNotConfiguredError` | 模型类型名非法(合法类型但未配置返回 `[]` 不抛);`AIConfigError` 子类 |
1075
+ | `AIRequestError` | 单次请求失败;`status_code`、`retry_after`(429 时解析 `Retry-After`) |
1076
+ | `AITimeoutError` | 请求超时(继承 `AIRequestError`) |
1077
+ | `AIAggregateError` | 全部候选失败或整链预算耗尽;`tried`、`statuses`、`last_error`、`budget_exhausted` |
1078
+ | `AIResponseError` | 响应结构解析失败、流式数据无法解析 |
1079
+
1080
+ ## yimo.kit.redis_kit —— Redis 工具
1081
+
1082
+ 安装:`pip install "yimo-kit[redis]"`
1083
+
1084
+ ```python
1085
+ from yimo.kit.redis_kit import RedisKit
1086
+
1087
+ RedisKit.set("user:1", "clark", expire=60)
1088
+ RedisKit.get("user:1") # -> "clark"
1089
+ RedisKit.zadd("rank", {"alice": 1.0, "bob": 2.0})
1090
+ RedisKit.zrange("rank", 0, -1, withscores=True)
1091
+ RedisKit.close()
1092
+ ```
1093
+
1094
+ | 分组 | 方法 |
1095
+ |------|------|
1096
+ | 通用 | `get_client()`(上下文管理器)、`set(key, value, expire=None) -> bool`、`get(key) -> RedisValue \| None`、`delete(key) -> bool`、`exists(key) -> bool`、`keys(pattern) -> list[str]`、`close() -> None` |
1097
+ | 批量 | `batch_set(key_value_pairs, expire=None) -> bool`、`batch_get(keys) -> dict`、`batch_delete(keys) -> bool` |
1098
+ | Hash | `hset(key, field, value) -> bool`、`hget(key, field)`、`hgetall(key) -> dict`、`hdel(key, *fields) -> bool` |
1099
+ | List | `lpush(key, *values) -> bool`、`rpush(key, *values) -> bool`、`lpop(key)`、`rpop(key)`、`lrange(key, start, stop) -> list` |
1100
+ | Set | `sadd(key, *members) -> bool`、`srem(key, *members) -> bool`、`smembers(key) -> list`、`sismember(key, member) -> bool` |
1101
+ | Sorted Set | `zadd(key, mapping) -> bool`、`zrange(key, start, stop, withscores=False)` |
1102
+
1103
+ > `RedisValue = str | int | float | bytes`;连接池 `decode_responses=True`,内置指数退避重试。
1104
+
1105
+ ---
1106
+
1107
+ ## yimo.kit.file_kit —— 文件工具
1108
+
1109
+ 相对路径均相对于 `FILE_STORAGE_ROOT`(默认 `./data`)。
1110
+
1111
+ ```python
1112
+ from yimo.kit.file_kit import FileKit
1113
+
1114
+ FileKit.write_file("docs/a.txt", "hello") # mode="overwrite"(默认)/ "append"
1115
+ text = FileKit.read_file("docs/a.txt")
1116
+ path = FileKit.get_full_path("docs/a.txt") # -> Path 绝对路径
1117
+ for root, dirs, files in FileKit.walk_dir("docs"):
1118
+ print(root, files)
1119
+ FileKit.open_with_default_app(path) # 系统默认程序打开:-> "opened" / "revealed"
1120
+ ```
1121
+
1122
+ | 分组 | 方法 |
1123
+ |------|------|
1124
+ | 配置 | `configure(root_path) -> None`、`get_root_path() -> str`、`get_full_path(relative_path) -> Path` |
1125
+ | 文件 | `read_file(relative_path, encoding="utf-8") -> str`、`write_file(relative_path, content, mode="overwrite", encoding="utf-8") -> bool`、`move_file(src, dest) -> bool`、`copy_file(src, dest) -> bool`、`delete_file(relative_path) -> bool`、`file_exists(relative_path) -> bool` |
1126
+ | 目录 | `move_dir(src, dest) -> bool`、`copy_dir(src, dest) -> bool`、`delete_dir(relative_path) -> bool`、`walk_dir(relative_path="", top_down=True, on_error=None)` |
1127
+ | 命名 | `generate_unique_id() -> str`、`generate_filename(prefix="", extension="") -> str` |
1128
+ | 系统 | `open_with_default_app(path) -> OpenResult`(`"opened"` / `"revealed"`,失败降级为文件管理器定位) |
1129
+
1130
+ ---
1131
+
1132
+ ## yimo.kit.common_kit —— 通用工具
1133
+
1134
+ ```python
1135
+ from yimo.kit.common_kit import CommonKit
1136
+
1137
+ CommonKit.configure(datacenter_id=1, machine_id=1) # 各限 1–31
1138
+ CommonKit.generate_snowflake_id() # 63 位雪花 ID(int)
1139
+ CommonKit.generate_snow_id() # 雪花 ID(str)
1140
+ CommonKit.generate_timestamp_id() # 20 位时间戳 ID
1141
+ CommonKit.format_current_time("yyyy-MM-dd")
1142
+ ```
1143
+
1144
+ | 方法 | 说明 |
1145
+ |------|------|
1146
+ | `configure(datacenter_id, machine_id) -> None` | 配置雪花算法数据中心 / 机器 ID(越界抛 `ValueError`) |
1147
+ | `generate_snowflake_id(datacenter_id=None, machine_id=None) -> int` | 生成雪花 ID |
1148
+ | `generate_snow_id(datacenter_id=None, machine_id=None) -> str` | 生成雪花 ID 字符串 |
1149
+ | `generate_timestamp_id() -> str` | `YYYYMMDDHHMMSSfff` + 3 位随机 |
1150
+ | `format_current_time(format_pattern="yyyyMMdd") -> str` | 支持 `yyyyMMdd`、`yyyyMMddhhmm`、`yyyyMMddhhmmss`、`yyyy-MM-dd`、`yyyy-MM-dd hh:mm`、`yyyy-MM-dd hh:mm:ss` |
1151
+ | `reset() -> None` | 重置 ID 生成器状态 |
1152
+
1153
+ ---
1154
+
1155
+ ## yimo.kit.license_kit —— 离线授权签发与校验
1156
+
1157
+ 零第三方依赖(`cryptography` 已在 base),按需 import。校验链:签名 → 产品 → 机器码 → 有效期。
1158
+
1159
+ ```python
1160
+ from datetime import datetime, timezone
1161
+ from pathlib import Path
1162
+
1163
+ from yimo.kit.license_kit import LicenseKit, LicensePayload, LicenseVerifier
1164
+
1165
+ # 1. 生成密钥对(一次性;私钥自行保管,不随包分发)
1166
+ private_pem, public_pem = LicenseKit.generate_keypair()
1167
+
1168
+ # 2. 取机器码(16 位十六进制;仅 Windows 支持)
1169
+ machine = LicenseKit.get_machine_code()
1170
+ LicenseKit.export_fingerprint_file(Path("fingerprint.txt")) # 或导出文件交给签发方
1171
+ machine = LicenseKit.parse_fingerprint_file(Path("fingerprint.txt"))
1172
+
1173
+ # 3. 签发(离线)
1174
+ payload = LicensePayload(
1175
+ product="thinktank",
1176
+ machine_code=machine,
1177
+ tier="pro",
1178
+ customer_id="C-0001",
1179
+ expires_at=datetime(2027, 12, 31, tzinfo=timezone.utc),
1180
+ )
1181
+ token = LicenseKit.sign(payload, private_pem)
1182
+
1183
+ # 4. 校验(应用启动 / 请求时)
1184
+ verifier = LicenseVerifier(public_pem, Path("license.json"))
1185
+ claims = verifier.verify(product="thinktank", machine_code=machine)
1186
+ print(claims.tier, claims.expires_at)
1187
+ ```
1188
+
1189
+ | 符号 | 说明 |
1190
+ |------|------|
1191
+ | `LicenseKit.generate_keypair() -> (str, str)` | 生成 Ed25519(私钥 PEM, 公钥 PEM) |
1192
+ | `LicenseKit.get_machine_code() -> str` | 本机机器码(16 位十六进制;⚠ 仅 Windows 平台) |
1193
+ | `LicenseKit.export_fingerprint_file(path) -> Path` | 导出机器指纹文件 |
1194
+ | `LicenseKit.parse_fingerprint_file(path) -> str` | 从指纹文件读回机器码 |
1195
+ | `LicenseKit.sign(payload, private_key_pem) -> str` | 签发授权 token |
1196
+ | `LicenseVerifier(public_key_pem, license_path)` | 构造验签器(绑定公钥与 license 文件) |
1197
+ | `LicenseVerifier.verify(*, product, machine_code, now=None) -> LicensePayload` | 全量校验并返回载荷;`now=None` 取 aware UTC,naive 按 UTC 解释 |
1198
+ | `LicenseVerifier.reverify() -> LicensePayload` | 用最近一次成功 `verify` 的上下文重新校验(文件被换会失败) |
1199
+ | `LicenseVerifier.file_signature` | 当前 license 文件的签名(属性) |
1200
+
1201
+ `LicensePayload` 字段:`version` / `product` / `machine_code` / `tier` / `customer_id` /
1202
+ `issued_at` / `expires_at`。
1203
+
1204
+ 异常:`LicenseError`(基类)、`LicenseFormatError`、`LicenseSignatureError`、
1205
+ `LicenseProductMismatchError`、`LicenseMachineMismatchError`、`LicenseExpiredError`、
1206
+ `LicenseUnsupportedPlatformError`(非 Windows 取机器码时抛)。
1207
+
1208
+ ---
1209
+
1210
+ ## yimo.kit.docs.anydoc_kit —— 文档转 Markdown
1211
+
1212
+ 安装:`pip install "yimo-kit[anydoc]"`(支持 `.doc .docx .ppt .pptx .xls .xlsx .csv .pdf`)
1213
+
1214
+ ```python
1215
+ from yimo.kit.docs.anydoc_kit import AnyDocKit
1216
+
1217
+ markdown = AnyDocKit.convert_to_md("report.docx") # 直接转换,失败抛异常
1218
+ result = AnyDocKit.convert("report.pdf") # 安全转换,异常封装为结果对象
1219
+ if result.success:
1220
+ print(result.markdown)
1221
+ AnyDocKit.convert_to_file("report.docx", "out/report.md")
1222
+ md = AnyDocKit.convert_bytes_to_md(file_bytes, "csv") # 字节内容直接转,无需落盘
1223
+ md = AnyDocKit.convert_to_md("scan.pdf", ocr="hosted") # 需 FIRECRAWL_API_KEY
1224
+ ```
1225
+
1226
+ | 方法 | 说明 |
1227
+ |------|------|
1228
+ | `is_supported(file_path) -> bool` | 按扩展名判断是否受支持 |
1229
+ | `detect_format(file_path) -> str \| None` | 由扩展名推断规范格式名 |
1230
+ | `convert_to_md(file_path, *, ocr="reject", api_key=None, api_url=None) -> str` | 文件 → Markdown(非标 PDF 自动修复重试) |
1231
+ | `convert_bytes_to_md(data, fmt=None, *, ocr="reject", api_key=None, api_url=None) -> str` | 字节内容 → Markdown |
1232
+ | `convert(file_path, *, ocr="reject", api_key=None, api_url=None) -> AnyDocResult` | 安全转换 |
1233
+ | `convert_to_file(src_path, dest_path=None, *, ocr="reject", ...) -> str` | 转换并写入 `.md`,返回目标路径 |
1234
+
1235
+ `AnyDocResult(success, markdown, file_path, source_format, error)`
1236
+
1237
+ > 异常:沿用上游 `anydoc.ConvertError` 体系(`MalformedError` / `NeedsOcrError` 等子类可直接捕获),
1238
+ > `AnyDocError` 是该基类的别名;安全版 `convert()` 会把它们封装为 `AnyDocResult.error`。
1239
+
1240
+ ---
1241
+
1242
+ ## yimo.kit.docs.docx_kit —— Word 模板动态填充
1243
+
1244
+ 安装:`pip install "yimo-kit[docx]"`
1245
+
1246
+ ```python
1247
+ from yimo.kit.docs.docx_kit import DocxKit, DocxReport, DocxSection, DocxParagraph, DocxTable
1248
+
1249
+ DocxKit.create_template("templates/report.docx", title="{{ title }}") # 生成模板骨架
1250
+ DocxKit.unify_font("templates/report.docx", font_name="宋体")
1251
+ DocxKit.unify_heading_color("templates/report.docx")
1252
+
1253
+ report = DocxReport(
1254
+ sections=(
1255
+ DocxSection(
1256
+ title="第一章 概述",
1257
+ level=1,
1258
+ blocks=(
1259
+ DocxParagraph("本章介绍项目背景。"),
1260
+ DocxTable(headers=("名称", "数值"), rows=(("甲", "1"),)),
1261
+ ),
1262
+ ),
1263
+ ),
1264
+ variables={"project": "Yimo"},
1265
+ )
1266
+ DocxKit.render("templates/report.docx", "out/report.docx", report)
1267
+ ```
1268
+
1269
+ | 方法 | 说明 |
1270
+ |------|------|
1271
+ | `create_template(dest_path, *, title=None, leading_paragraphs=(), anchor_style=None) -> str` | 生成标准模板骨架(含章节循环锚点) |
1272
+ | `unify_font(docx_path, *, font_name="宋体") -> str` | 统一文档默认与全部样式的字体(原地,幂等) |
1273
+ | `unify_heading_color(docx_path, *, color="000000") -> str` | 统一 `Heading 1..9` 字体颜色 |
1274
+ | `inspect_template(template_path, *, context=None) -> tuple[str, ...]` | 列出模板中未被上下文满足的变量 |
1275
+ | `render(template_path, dest_path, report, *, anchor_style=None, strict=True) -> str` | 按结构化数据渲染模板并落盘(核心方法) |
1276
+
1277
+ 数据结构:`DocxReport(sections, variables)`、`DocxSection(title, level=1, blocks=())`、`DocxParagraph(text)`、`DocxListItem(text, level=1, ordered=False)`、`DocxTable(headers, rows=(), style=None)`
1278
+
1279
+ ---
1280
+
1281
+ ## yimo.kit.docs.md2doc_kit —— Markdown 转 Word / PDF / HTML
1282
+
1283
+ 安装:`pip install "yimo-kit[md2doc]"`(PDF 需系统已安装 `mainfont` 指定字体,默认 `SimSun`)
1284
+
1285
+ ```python
1286
+ from yimo.kit.docs.md2doc_kit import Md2DocKit
1287
+
1288
+ Md2DocKit.convert_md_to_docx("report.md", "out.docx", generate_toc=True)
1289
+ Md2DocKit.convert_md_to_html("report.md", title="项目报告")
1290
+ Md2DocKit.convert_md_to_pdf("report.md", mainfont="KaiTi")
1291
+ ```
1292
+
1293
+ | 方法 | 说明 |
1294
+ |------|------|
1295
+ | `convert_md_to_docx(src_path, dest_path=None, *, generate_toc=False, mainfont="宋体") -> str` | Markdown → Word(可插目录、统一字体、图片内嵌) |
1296
+ | `convert_md_to_html(src_path, dest_path=None, *, title=None) -> str` | Markdown → 独立 HTML5 文件(图片输出 `<figure><img>`) |
1297
+ | `convert_md_to_pdf(src_path, dest_path=None, *, mainfont="SimSun") -> str` | Markdown → PDF(实验性,内部使用;图片等比限宽居中) |
1298
+
1299
+ > `dest_path=None` 时输出到源文件同目录;同一源文件不支持并发转换。
1300
+
1301
+ **图片**:`![alt](相对路径)` 以 Markdown 源文件所在目录为基准解析,宽度等比限幅
1302
+ (96dpi 还原自然尺寸、不放大),超高先分页/按版心收紧;缺图、越界路径、非图片
1303
+ 格式一律回落 `alt` 文本,不抛异常。远程地址在 PDF / Word 中不下载(回落 alt),
1304
+ 在 HTML 中直出 `<img src="https://…">` 交给浏览器。HTML 输出保留相对路径,需与
1305
+ `images/` 目录保持同层级才能在浏览器中显示。
1306
+
1307
+ ---
1308
+
1309
+ ## yimo.kit.docs.mineru_kit —— MinerU 文档解析
1310
+
1311
+ 安装:`pip install "yimo-kit[mineru]"`(精准解析需 `MINERU_API_KEY`,Agent 轻量解析免登录)
1312
+
1313
+ ```python
1314
+ from yimo.kit.docs.mineru_kit import MinerUKit
1315
+
1316
+ # 精准解析:公网 URL / 本地文件
1317
+ result = MinerUKit.parse_url("https://cdn-mineru.openxlab.org.cn/demo/example.pdf", model_version="vlm")
1318
+ if result.state == "done":
1319
+ zip_path = MinerUKit.download_zip(result.full_zip_url, "./output")
1320
+
1321
+ results = MinerUKit.parse_files(["report1.pdf", "report2.docx"])
1322
+
1323
+ # Agent 轻量解析(免登录、单文件 ≤10MB、≤20 页)
1324
+ r = MinerUKit.agent_parse_url(url, page_range="1-10")
1325
+ if r.state == "done":
1326
+ md_path = MinerUKit.download_markdown(r.markdown_url, "./output")
1327
+ ```
1328
+
1329
+ | 分组 | 方法 |
1330
+ |------|------|
1331
+ | 精准解析(高层) | `parse_url(url, **opts) -> TaskResult`、`parse_files(file_paths, **opts) -> list[BatchTaskResult]`、`wait_for_task(task_id, *, poll_interval=None, timeout=None)`、`wait_for_batch(batch_id, *, expected_count=None, ...)`、`download_zip(zip_url, dest_dir) -> str` |
1332
+ | 精准解析(低层) | `create_task(url, **opts) -> str`、`get_task_result(task_id) -> TaskResult`、`create_batch(files, **opts) -> BatchUploadInfo`、`upload_files(file_paths, upload_urls) -> list[bool]`、`get_batch_results(batch_id) -> list[BatchTaskResult]` |
1333
+ | Agent 轻量 | `agent_parse_url(url, **opts) -> AgentParseResult`、`agent_parse_file(file_path, **opts) -> AgentParseResult`、`agent_create_url_task(url, **opts) -> str`、`agent_create_file_task(file_name, **opts) -> AgentUploadInfo`、`agent_upload_file(file_path, file_url) -> None`、`agent_get_result(task_id)`、`agent_wait_for_result(task_id, *, poll_interval=None, timeout=None)`、`download_markdown(markdown_url, dest_dir, filename=None) -> str` |
1334
+ | 校验 | `is_supported(file_path) -> bool`、`is_agent_supported(file_path) -> bool` |
1335
+
1336
+ > 可选参数(`model_version` / `is_ocr` / `enable_formula` / `enable_table` / `language` / `page_ranges` / `extra_formats` / `no_cache` 等)详见各方法 docstring。
1337
+ > 结果类型:`TaskResult`、`BatchTaskResult`、`BatchFile`、`BatchUploadInfo`、`AgentParseResult`、`AgentUploadInfo`。
1338
+
1339
+ ---
1340
+
1341
+ ## yimo.kit.docs.rc_docparser_kit —— 离线 docx → Markdown + Images
1342
+
1343
+ 安装:`pip install "yimo-kit[docx-parse]"`(依赖 `rc-docparser`,纯 Python,无模型 / OCR / GTK)
1344
+
1345
+ 支持面:仅 `.docx`。产物契约:`<out>/<stem>.md` + `<out>/images/`。
1346
+
1347
+ ```python
1348
+ from yimo.kit.docs.rc_docparser_kit import RcDocParserKit
1349
+
1350
+ md_path = RcDocParserKit.convert_to_dir("report.docx") # -> report/report.md + report/images/
1351
+ md = RcDocParserKit.convert_to_md("report.docx") # 只取文本(图片不落盘)
1352
+ result = RcDocParserKit.convert("report.docx", "out/doc")
1353
+ if result.success:
1354
+ print(result.md_path, len(result.image_paths))
1355
+ ```
1356
+
1357
+ | 方法 | 说明 |
1358
+ |------|------|
1359
+ | `is_supported(file_path) -> bool` | 是否 `.docx` |
1360
+ | `convert_to_md(file_path) -> str` | 解析并返回 Markdown 文本 |
1361
+ | `convert_to_dir(src_path, output_dir=None, *, extract_images=True) -> str` | 落盘 md + `images/`,返回 md 绝对路径 |
1362
+ | `convert(src_path, output_dir=None, *, ...) -> RcDocParserResult` | 安全版:失败封装为结果对象 |
1363
+
1364
+ > 产物:`<out>/images/img-NNN-<sha1 前 10>.<ext>`(按出现顺序、内容哈希命名);无图不建空目录。
1365
+ > 前提:中文标题依赖 `w:outlineLvl` 或「标题 N」样式(都没有时退化为正文);合并单元格表格会重建为
1366
+ > 等宽 GFM(覆盖位留空,不输出 HTML `<table>`);页眉页脚/脚注不提取。纯本地,无需模型或 GPU。
1367
+
1368
+ ## yimo.kit.ai.decision.decima —— 选项乱序不变、置信度可门控的决策模型
1369
+
1370
+ 122M 参数的 late-interaction 决策模型(int8 ONNX,单 CPU 线程,**不依赖 torch**)。
1371
+ 每个选项独立编码、独立与 state 打分,因此**调换选项顺序不会改变答案**。
1372
+
1373
+ ```bash
1374
+ pip install "yimo-kit[decima]"
1375
+ ```
1376
+
1377
+ ```python
1378
+ from yimo.kit.ai.decision.decima import DecimaKit
1379
+
1380
+ state = "我们三月份被重复扣费了两次,请把重复的那笔退款。"
1381
+
1382
+ # 单选题:选项顺序不影响结果
1383
+ r = DecimaKit.choice(
1384
+ state,
1385
+ "这封来信应该由哪个部门处理?",
1386
+ {"账务": "账单、付款、退款", "技术": "故障、报错"},
1387
+ )
1388
+ r["decision"], r["answer_confidence"], r["probabilities"]
1389
+
1390
+ # 是否题 / 评分题:第一个参数是待判断文本,第二个是命题
1391
+ DecimaKit.noul(state, "客户是否明确要求退款?")
1392
+ DecimaKit.score(state, "有多紧急?", ["不紧急", "较快处理", "紧急"])
1393
+
1394
+ # 多选:原生 rank(每项独立 sigmoid),返回 0-N 个
1395
+ DecimaKit.multi_choice(state, "涉及哪些事项?", {"账务": "账单", "技术": "故障"})
1396
+
1397
+ # 批量 / 多问题 / 长文本(方法名与 LayaKit 对齐)
1398
+ DecimaKit.choice_batch(
1399
+ [state, "系统登录后一直报错。"], "哪个部门?", {"账务": "账单", "技术": "故障"}
1400
+ )
1401
+ raw = DecimaKit.predict(
1402
+ state,
1403
+ {"dept": {"type": "choice", "instructions": "哪个部门?",
1404
+ "criteria": {"账务": "账单", "技术": "故障"}}},
1405
+ )
1406
+ DecimaKit.brief(raw)
1407
+ DecimaKit.predict_long(state * 50, {"r": {"type": "noul", "instructions": "是否要求退款?"}})
1408
+ ```
1409
+
1410
+ **返回字段**(`answer_confidence` 与 `LayaKit` 同名同口径):
1411
+
1412
+ | 字段 | 含义 |
1413
+ |------|------|
1414
+ | `decision` | 选中标签 / 序数期望值 / P(true) |
1415
+ | `answer_confidence` | top-1 概率 `max(p)`;**与 laya 同名同口径,但在本 Kit 上已标定、可做门控** |
1416
+ | `confidence` | 上游归一化置信度 `(k·max(p)−1)/(k−1)`,0~1(本 Kit 特有) |
1417
+ | `top_prob` | 原始 top-1 概率 `max(p)`,与 `answer_confidence` 相同 |
1418
+ | `probabilities` | 完整分布(`score` 的键为档位文本) |
1419
+ | `abstained` | 仅当传了 `min_confidence` 才有布尔值,否则为 `None` |
1420
+
1421
+ **从 LayaKit 迁移**:`choice` / `score` / `noul` / `multi_choice` / `predict` / `predict_long` /
1422
+ `brief` / `router` / `unload` 同名同形,**只改 import 即可**;
1423
+ `decide`(schema 多字段)、`decide_batch`、`route` 是 laya 独有能力,本 Kit 不提供
1424
+ (`decide_batch` 显式抛 `NotImplementedError`,不会静默按单选跑)。
1425
+
1426
+ ### 与 `LayaKit` 的取舍(同环境实测)
1427
+
1428
+ | 维度 | `LayaKit`(0.4.21) | `DecimaKit`(small 1.1) |
1429
+ |---|---|---|
1430
+ | 选项顺序导致的决策变化 | 中文工单 15.0%、文献 17% | **0%**(构造性) |
1431
+ | 门控覆盖率(放行准确率 ≥90%) | 25.0% | **52.5%** |
1432
+ | 中文工单分诊(40 条) | 0.700 | **0.750** |
1433
+ | 其中三个实质类(剔除「其他」,**推算**) | **0.867** | 0.667 |
1434
+ | JevBench 231 题 | 0.485 | **0.563** |
1435
+ | JevBench easy 48 题 | **0.896** | 0.812 |
1436
+ | JevBench hard 111 题 | 0.333 | **0.441** |
1437
+ | 磁盘(单检查点) | 617 MB | **137.5 MB** |
1438
+ | 依赖 | laya + torch | decima-ai + onnxruntime |
1439
+
1440
+ **怎么选**:要「动态选项 + 顺序稳定 + 低置信转人工」用 `DecimaKit`;要「固定标签 + 简单明确分诊 +
1441
+ 多字段 schema / GPU / 语言自动路由」用 `LayaKit`。两者**并列存在**,不互相替代。
1442
+ (`unload()` 两边都不该当内存回收 API:laya 实测只回落 0.4%,decima 回落约 50% 但也不回基线。)
1443
+
1444
+ ### 限制
1445
+
1446
+ - **不提供默认门控阈值**:阈值随选项数与业务分布变化(4 选项约 0.80、6 选项约 0.85、二选一约 0.54),
1447
+ 必须用自有数据标定后传入 `min_confidence`。
1448
+ - **不适用于复杂推理**:JevBench 231 题 0.563,同基准 Jev 1.13.0 为 0.986;
1449
+ `multi_hop` 0.28、`trap` 0.12。多跳策略判断请用大模型。
1450
+ - **`score` 最弱**(上游自认 benchmark 0.447):只返回分布与期望值,不承诺准确性。
1451
+ - **`multi_choice` 的 0.5 阈值偏严**:`rank` 是每选项独立 sigmoid,概率普遍低于 laya 的 `noul`
1452
+ (实测「账务 0.49 / 技术 0.12」会返回空列表);先看 `probabilities` 再定 `threshold`。
1453
+ - **无 schema 多字段能力**:`decide` / `decide_batch` 留在 laya 侧。
1454
+ - **仅 CPU**;**无真实释放接口**:上游没有 `unload`,`onnxruntime` 的 `InferenceSession`
1455
+ 也没有 `close()`,`unload()` 只能丢引用 + GC。实测 WorkingSet 882.7 → 440.2 MB(约 50%),
1456
+ 不回基线,反复加载/释放以 14~29 MB/轮 累积——长驻进程建议只加载一次。
1457
+ - **窗口 512 token 且不可调**:超长文本截断,或传 `long="chunk"` / `predict_long` 分窗。
1458
+ 分窗固定「512 token 窗口 + 64 token 重叠」,`predict_long` 的 `window` / `stride` /
1459
+ `batch_size` **只是为兼容 LayaKit 签名而接受,内部丢弃**(首次传参会告警一次);
1460
+ 需要更细粒度扫描请自行切分文本后逐段调用。长文档优先只喂标题 + 摘要。
1461
+ - **倾向选兜底类**:业务有「其他 / 无法判定」类时表现正常(实测该类 10/10 全对),
1462
+ 但代价是三个实质类低于 laya(账务 0.50 vs 0.80、销售 0.60 vs 0.80)——
1463
+ **业务没有兜底类时准确率会下降**。
1464
+
1465
+ > 实测数据来自 `research/decima/`(中文工单 40 条由 AI 标注、未人工复核,只作方向参考;
1466
+ > JevBench 为本轮独立复现,231 题实测 0.563 与模型卡自报 0.571 同量级)。
1467
+
1468
+ > **许可提示**:权重为 Apache-2.0,但 `decima-small` 训练数据含 CC BY-NC 数据集
1469
+ > (ANLI / XNLI / multilingual-NLI-26lang)。商用前请自行复核许可条款;纯商用数据版本为
1470
+ > `decima-base-clean`(体积与延迟更大,改 `DECIMA_MODEL` 后需重新验证效果)。
1471
+
1472
+ ## yimo.kit.crawl.wx_article_kit —— 微信公众号文章抓取存储
1473
+
1474
+ 零第三方依赖(标准库 `urllib` + 内置 HTML→Markdown 转换器),**无需 extra**,按需 import:
1475
+
1476
+ ```python
1477
+ from yimo.kit.crawl.wx_article_kit import WxArticleKit
1478
+
1479
+ # 抓取解析(不落盘)
1480
+ result = WxArticleKit.fetch("https://mp.weixin.qq.com/s/xxxx")
1481
+ if result.ok:
1482
+ print(result.info.title, result.info.author, result.info.publish_time)
1483
+
1484
+ # 抓取并存储:<output_dir>/<stem>/ 下 <stem>.md + images/ + meta.json
1485
+ saved = WxArticleKit.save(url, output_dir="./output", file_name="12345")
1486
+ print(saved.md_path, saved.images_saved)
1487
+
1488
+ # 不传 file_name:目录按本地时间 yymmddhhmmss 自动命名
1489
+ WxArticleKit.save(url, "./output")
1490
+
1491
+ # 不需要 meta.json 时显式关闭
1492
+ WxArticleKit.save(url, "./output", "12345", write_meta=False)
1493
+ ```
1494
+
1495
+ | 方法 | 说明 |
1496
+ |------|------|
1497
+ | `fetch(url, timeout=20.0) -> ArticleResult` | 抓取并解析正文(不落盘);结果对象字段 `ok` / `error` / `info`(`ArticleInfo`)/ `markdown` |
1498
+ | `save(url, output_dir, file_name=None, write_meta=True, timeout=20.0) -> SavedOutput` | 抓取并存储到 `<output_dir>/<stem>/`;结果对象字段 `ok` / `error` / `output_dir` / `md_path` / `images_dir` / `title` / `images_saved` / `reason` / `warnings` |
1499
+
1500
+ 落盘结构(三个 `*ArticleKit` 统一由 `yimo.kit.crawl.article_io` 完成):
1501
+
1502
+ ```
1503
+ <output_dir>/<stem>/
1504
+ ├── <stem>.md # 正文 Markdown(YAML 头:title / author / publish_time / source / source_url)
1505
+ ├── images/ # 图片转存(NNN.ext,正文引用已本地化)
1506
+ └── meta.json # 结构化元信息(默认产出;write_meta=False 关闭)
1507
+ ```
1508
+
1509
+ - `stem` 不传时按本地时间 `%y%m%d%H%M%S` 自动命名,同秒碰撞追加 `-2`…`-99`;
1510
+ 显式传 `file_name` 时同名目录**覆盖写**;
1511
+ - 元信息随 Markdown 的 YAML 头落盘(头部 `publish_time` 为中文日期,如 `2026年8月4日`);
1512
+ `ArticleInfo.publish_time` 与 `meta.json` 内仍为 ISO 8601(结构化数据)。
1513
+ - 无登录态抓取:命中微信风控(环境异常 / 访问过于频繁)时返回 `ok=False` + 原因,不破解验证码;
1514
+ 抓取或图片下载失败不抛异常,单张图片失败时正文保留原远程 URL。
1515
+ - 模型与 `WebArticleKit` 共用 `yimo.kit.crawl.article_models`(`ArticleInfo` 含 `source` / `site_host`);
1516
+ 失败时 `reason` 为类型化分类(微信常用 `risk_control` / `no_content` / `fetch_failed`)。
1517
+ - 显式 `file_name` 时同名子目录**覆盖写**(不追加序号);省略时按时间自动命名,同秒追加 `-2`…;
1518
+ `file_name` 带 `.md` 后缀会自动去除,显式传空串则抛 `ValueError`。
1519
+
1520
+ ---
1521
+
1522
+ ## yimo.kit.crawl.web_article_kit —— 通用网页文章抓取存储
1523
+
1524
+ 可选依赖(`trafilatura`),需安装 `pip install "yimo-kit[web-article]"`,按需 import:
1525
+
1526
+ ```python
1527
+ from yimo.kit.crawl.web_article_kit import WebArticleKit
1528
+
1529
+ # 抓取解析(不落盘)
1530
+ result = WebArticleKit.fetch("https://blog.csdn.net/xxx/article/details/123")
1531
+ if result.ok:
1532
+ print(result.info.source, result.info.title, result.info.publish_time)
1533
+
1534
+ # 抓取并存储:<output_dir>/<stem>/ 下 <stem>.md + images/ + meta.json
1535
+ saved = WebArticleKit.save(url, output_dir="./output", file_name="12345")
1536
+ print(saved.md_path, saved.images_saved)
1537
+
1538
+ # 不传 file_name:目录按本地时间 yymmddhhmmss 自动命名
1539
+ WebArticleKit.save(url, "./output")
1540
+ ```
1541
+
1542
+ | 方法 | 说明 |
1543
+ |------|------|
1544
+ | `fetch(url, timeout=20.0) -> ArticleResult` | 抓取并解析正文(不落盘);结果对象字段 `ok` / `error` / `info`(`ArticleInfo`)/ `markdown` |
1545
+ | `save(url, output_dir, file_name=None, write_meta=True, timeout=20.0) -> SavedOutput` | 抓取并存储到 `<output_dir>/<stem>/`;字段与 `WxArticleKit.save` 一致 |
1546
+
1547
+ 落盘结构与 `WxArticleKit` 完全一致(`<stem>.md` + `images/` + `meta.json`):
1548
+ `<stem>.md` 的 YAML 头为 `title / author / publish_time / source / source_url`(`publish_time` 渲染为中文日期)。
1549
+
1550
+ **站点覆盖范围**(规则表只允许「转交」与「接口适配」两类条目,不做逐站 DOM 补丁):
1551
+
1552
+ | 站点类型 | 行为 |
1553
+ |---|---|
1554
+ | 通用静态 / 服务端渲染页面(博客、文档站、CSDN 等) | ✅ 直接抽取 |
1555
+ | 头条(文章页为 JS 空壳) | ✅ **明确支持**:走移动端 JSON 接口 |
1556
+ | 微信公众号 | ❌ **不覆盖**:返回提示,请改用 `yimo.kit.crawl.wx_article_kit.WxArticleKit`(该来源有专属解析,二者各自独立) |
1557
+ | 正文依赖 JavaScript 动态渲染或需登录态的站点 | ❌ 失败并给出**类型化说明**(不维护域名名单) |
1558
+
1559
+ `ArticleInfo` 为平台中立的通用字段集:`url` / `title` / `author` / `publish_time`(ISO 8601)/ `source`
1560
+ (来源平台名)/ `site_host` / `summary` / `images` / `links` / `code_blocks`,便于多平台抓取后写入同一张表;
1561
+ `to_dict()` 可直接 JSON 化(即 `meta.json` 的内容)。模型定义在 `yimo.kit.crawl.article_models`,与
1562
+ `WxArticleKit` **共用同一套**。
1563
+
1564
+ 质量信号(均不改变成功语义):
1565
+
1566
+ | 字段 | 取值 / 含义 |
1567
+ |---|---|
1568
+ | `reason` | 失败时的类型化分类:`unsupported_source` / `fetch_blocked` / `fetch_failed` / `no_content` / `risk_control` / `auth_failed` / `rate_limited` / `config_missing`(成功为空串) |
1569
+ | `warnings` | **非致命**抽取自检提示(`tuple[str, ...]`):正文疑似过短、页面含图片但产物无图;同时写入 warning 日志 |
1570
+
1571
+ 标题统一去除站点后缀(如 CSDN 的 `标题-CSDN博客`);刻意不做「与页面 h1 择优」(h1 可能是导航文案)。
1572
+
1573
+ ## yimo.kit.crawl.deepseek_kit —— DeepSeek Search / Fetch
1574
+
1575
+ 零第三方依赖,基础安装即可用(按请求次数计费,0.005 元/次量级)。需配置 API Key:
1576
+
1577
+ ```
1578
+ DEEPSEEK_API_KEY=sk-xxx # .env 或环境变量
1579
+ DEEPSEEK_BASE_URL=https://api.deepseek.com
1580
+ DEEPSEEK_TIMEOUT=60
1581
+ DEEPSEEK_MAX_RETRIES=2 # 仅 408/429/5xx 重试
1582
+ ```
1583
+
1584
+ ```python
1585
+ from yimo.kit.crawl.deepseek_kit import DeepSeekKit
1586
+
1587
+ # 1. 网页搜索(不落盘)
1588
+ found = DeepSeekKit.search("DeepSeek V4 发布 site:github.com", count=5, need_content=False)
1589
+ for item in found.items:
1590
+ print(item.title, item.url, item.rerank_score, item.authority)
1591
+
1592
+ # 2. 单页抓取(不落盘)
1593
+ page = DeepSeekKit.fetch("https://api-docs.deepseek.com/zh-cn/guides/search")
1594
+ print(page.info.title, page.markdown)
1595
+
1596
+ # 3. 抓取并存储:<output_dir>/<stem>/ 下 <stem>.md + images/ + meta.json
1597
+ saved = DeepSeekKit.save(url, output_dir="./output", file_name="ds-guide")
1598
+ ```
1599
+
1600
+ | 方法 | 说明 |
1601
+ |------|------|
1602
+ | `search(query, count=10, need_content=False, ori_question=None, localization=None, timeout=None, retries=None) -> SearchResult` | 返回 `ok` / `error` / `reason` / `items`(`SearchItem` 元组)/ `warnings`;`SearchItem.to_dict()` 可直接 JSON 化 |
1603
+ | `fetch(url, timeout=None, retries=None) -> ArticleResult` | 与 `WebArticleKit.fetch` 同构(`info` / `markdown` / `reason` / `warnings`) |
1604
+ | `save(url, output_dir, file_name=None, write_meta=True, timeout=None, retries=None) -> SavedOutput` | 落盘结构与两个 `*ArticleKit` 完全一致 |
1605
+
1606
+ 失败 `reason`:`auth_failed`(401/402)/ `fetch_blocked`(403)/ `no_content`(404)/
1607
+ `rate_limited`(429)/ `fetch_failed`(408/5xx 重试后仍失败、请求不合法)。
1608
+ 未配置 `DEEPSEEK_API_KEY` 抛 `DeepSeekKitError`。实现要求:
1609
+
1610
+ - 服务端返回的正文是**重度反斜杠转义的伪 Markdown**,kit 会统一反转义后再落盘;
1611
+ - 该接口**不返回代码块围栏**,代码会被压成普通段落;图片也常缺失。
1612
+ 需要高保真正文(代码块、图片)请改用 `WebArticleKit`。
1613
+
1614
+ ---
1615
+
1616
+ ## AI 档案文件
1617
+
1618
+ AI 功能需要在项目根目录提供 `config/ai_models.json`(chat / embedding / rerank / image 四类型多厂商模型档案)。
1619
+
1620
+
1621
+ 文件缺失时,首次使用相应功能会报错,**报错信息中附带可直接复制的最小模板**;
1622
+ 其中 `api_key` 字段填写环境变量名,真实密钥配置在 `.env`。
1623
+
1624
+ ### ai_models.json 可选字段
1625
+
1626
+ | 层级 | 字段 | 说明 |
1627
+ |------|------|------|
1628
+ | 档案级 | `endpoint` | 请求路径。**仅 rerank 生效**:chat / embedding / image 由 openai SDK 固定拼路径,本字段被忽略(保留仅为兼容旧配置,不报错) |
1629
+ | 档案级 | `timeout` | 请求超时秒数(默认 60);SDK 侧为单次调用总超时。**流式例外**:流式请求 `timeout=None`,由门面首帧 60s + 帧间隔 120s 兜底 |
1630
+ | 档案级 | `max_tokens` | 输出上限(chat 用);`AI.chat/chat_once/chat_stream` 也可按调用点传参,逐级回落:调用点 → 档案 → provider 默认 |
1631
+ | 档案级 | `retries` | 5xx 重试次数(默认 2;超时不重试,候选链切换才是有效重试) |
1632
+ | 档案级 | `extra_body` | 厂商专有请求体字段透传(如 GLM/Qwen 关闭思考的 `{"thinking": {"type": "disabled"}}`、`{"reasoning_effort": "low"}`);与服务构造的同名键冲突时**以服务的值为准**,故 `model` / `messages` / `stream` 等保留键不可覆盖;改名类需求(如 OpenAI o 系列的 `max_completion_tokens`)无法用它实现。逐调用 `thinking` 与之同键时**以逐调用为准**并打 `WARNING`。改文件后需 `reload_config(reload_file=True)` 生效 |
1633
+ | 档案级 | `thinking` | 思考开关的注入声明:`{"arg": "thinking", "off": {"type": "disabled"}, "on": {"type": "enabled"}, "default": false}`。`arg` 是请求体顶层键名(不得占用 `model` / `messages` / `stream` / `max_tokens` / `temperature` 等保留键,配置期与运行期双重校验);`off` / `on` 可为**任意 JSON 值**(双方都是 dict 时浅合并,否则整键替换);`on` 缺省表示不能显式开启;`default` 为档案默认三态(`null` 不干预 / `false` 默认关 / `true` 默认开)。**未声明 = 不支持按调用切换**:逐调用 `thinking` 被忽略并告警(不报错、不影响候选链冷却)。kit 只做翻译,不含任何厂商名 |
1634
+ | 档案级 | `structured_output` | 结构化输出的注入声明:`{"arg": "response_format", "json_mode": {"type": "json_object"}}`。`arg` 是请求体顶层键名(不得占用保留键);`json_mode` 是 `json_mode=True` 时写入该键的取值。**未声明 = 用内置 OpenAI 兼容默认**(`response_format: {"type":"json_object"}`,开箱即用);`"structured_output": false` 表示该档案不支持(`json_mode=True` 被忽略 + 告警,不发任何字段)。逐调用 `response_format` 原样透传优先于本声明。kit 只做翻译,不含任何厂商名 |
1635
+ | 类型级 | `chain_timeout` | 整链预算秒数(与 `default_profile` 同级);门面同步等待上限。未配置时按 `sum(候选 timeout) + 10s` 自适应,也可用环境变量 `KIT_AI_CHAIN_TIMEOUT` 全局覆盖 |
1636
+
1637
+ `thinking` 声明两种实测形态(按平台各自写入档案):
1638
+
1639
+ ```json
1640
+ "thinking": {"arg": "thinking", "off": {"type": "disabled"}}
1641
+ "thinking": {"arg": "chat_template_kwargs", "off": {"enable_thinking": false}}
1642
+ ```
1643
+
1644
+ - **未知字段的厂商反应不一致**:有的返回 400、有的**静默忽略**(仍照常思考)。所以 kit 只按声明下发,绝不猜厂商默认值;
1645
+ - **强制思考模型**(如只接受 `low/high/max` 的平台)不写 `thinking` 声明,逐调用开关会被忽略并告警;
1646
+ - 声明写错(`arg` 拼错、值形态不符)由厂商判定,可能 400 → 冷却;语义正确性由使用方的模型能力清单保证。
1647
+
1648
+ `structured_output` 声明与关闭形态:
1649
+
1650
+ ```json
1651
+ "structured_output": {"arg": "response_format", "json_mode": {"type": "json_object"}}
1652
+ "structured_output": false // 该端点实测不支持:json_mode=True 时忽略并告警
1653
+ ```
1654
+
1655
+ > **`extra_body` 的用法边界**:`extra_body` 是**档案级**的固有配置,无法按调用点切换。需要
1656
+ > 「同一模型,长文开思考、短文关思考」并存时用档案 `thinking` 声明 + 逐调用 `thinking=False/True`;
1657
+ > 仅在无法用开关表达时才考虑复制档案 + `ModelBuilder.build_chat("<档案名>")`
1658
+ > (门面侧 `AI.use("chat", "<档案名>")` 是进程级切换,非并发安全)。
1659
+ > 结构化输出同理:档案声明只给 `json_mode=True` 提供取值,按调用点变化的 schema 一律走
1660
+ > 逐调用 `response_format`。
1661
+
1662
+ ### 候选链切换语义(两类,勿混淆)
1663
+
1664
+ - **跨调用切换**:`AI.use()` 与其它请求产生的失败冷却均只影响**下一次**请求——每次调用的候选计划在开始时定格;
1665
+ - **一次调用内降级**:本次调用按开始时定格的计划串行尝试(首帧前失败 / 首帧超时切下一候选),中途的 `use` / 冷却变化不影响它。
1666
+
1667
+ 全部候选失败(或整链预算耗尽)抛 `AIAggregateError`(`AIRequestError` 子类):
1668
+ 全候选状态码一致时透传(如整链 429 可用 `exc.status_code == 429` 判定),
1669
+ 429 的 `Retry-After` 解析后挂于 `exc.retry_after`(冷却钳制 5–300s)。
1670
+
1671
+ ## License
1672
+
1673
+ Apache-2.0