@sciexpr/ai 0.1.0

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.
@@ -0,0 +1,467 @@
1
+ import { ExpressionRoot, ExpressionKind, ValidationError, ExpressionNode } from '@sciexpr/core';
2
+
3
+ /** AI 补全上下文 */
4
+ interface CompletionContext {
5
+ /** 当前已输入的文本 */
6
+ currentInput: string;
7
+ /** 光标位置(基于 0 的偏移量) */
8
+ cursorPosition: number;
9
+ /** 当前已解析的 AST(如果输入合法) */
10
+ currentAST?: ExpressionRoot;
11
+ /** 表达式类型 */
12
+ expressionType: ExpressionKind;
13
+ /** 周围文档上下文(如前后段落) */
14
+ surroundingText?: string;
15
+ /** 用户自定义上下文 */
16
+ customContext?: Record<string, unknown>;
17
+ }
18
+ /** 补全候选项 */
19
+ interface CompletionItem {
20
+ /** 补全文本(LaTeX 源码) */
21
+ text: string;
22
+ /** 显示标签 */
23
+ label: string;
24
+ /** 描述/说明 */
25
+ description?: string;
26
+ /** 预览渲染 HTML */
27
+ previewHtml?: string;
28
+ /** 分类 */
29
+ category: 'symbol' | 'command' | 'template' | 'correction' | 'formula';
30
+ /** 排序权重(越高越靠前) */
31
+ score: number;
32
+ }
33
+ /** 补全结果 */
34
+ interface CompletionResult {
35
+ /** 补全候选项列表 */
36
+ items: CompletionItem[];
37
+ /** 是否为 AI 生成(vs 本地静态匹配) */
38
+ source: 'ai' | 'local' | 'hybrid';
39
+ /** 请求耗时(ms) */
40
+ latencyMs?: number;
41
+ }
42
+ /**
43
+ * AI 补全提供者接口(SPI)
44
+ *
45
+ * 使用方实现此接口,将自己已有的 AI 模型注入引擎。
46
+ * 引擎不依赖任何特定 AI SDK。
47
+ */
48
+ interface IAICompletionProvider {
49
+ /** 提供者唯一标识 */
50
+ readonly id: string;
51
+ /** 提供者名称 */
52
+ readonly name: string;
53
+ /**
54
+ * 获取补全候选项
55
+ * @param context 补全上下文
56
+ * @returns 补全结果
57
+ */
58
+ complete(context: CompletionContext): Promise<CompletionResult>;
59
+ /**
60
+ * 流式补全(可选)
61
+ * 用于打字机效果的实时补全
62
+ */
63
+ completeStream?(context: CompletionContext): AsyncIterable<CompletionItem>;
64
+ /**
65
+ * AI 纠错建议(可选)
66
+ * 当用户输入无效时,AI 给出修正建议
67
+ */
68
+ correct?(input: string, error: ValidationError): Promise<CompletionItem[]>;
69
+ /**
70
+ * 自然语言 → 公式转换(可选)
71
+ * "水的化学式" → "H₂O"
72
+ */
73
+ naturalLanguageToFormula?(query: string): Promise<CompletionItem[]>;
74
+ }
75
+
76
+ /** 知识库查询参数 */
77
+ interface KBQueryParams {
78
+ /** 查询文本 */
79
+ query: string;
80
+ /** 查询类型限制 */
81
+ types?: ('element' | 'compound' | 'formula' | 'symbol' | 'reaction' | 'constant')[];
82
+ /** 最大返回数 */
83
+ maxResults?: number;
84
+ /** 语言偏好 */
85
+ language?: string;
86
+ }
87
+ /** 符号信息 */
88
+ interface SymbolInfo {
89
+ /** LaTeX 命令或符号 */
90
+ symbol: string;
91
+ /** 名称 */
92
+ name: string;
93
+ /** 描述 */
94
+ description: string;
95
+ /** 分类 */
96
+ category: string;
97
+ /** 使用示例 */
98
+ example?: string;
99
+ /** 关联符号 */
100
+ relatedSymbols?: string[];
101
+ }
102
+ /** 公式模板 */
103
+ interface FormulaTemplate {
104
+ /** 模板唯一标识 */
105
+ id: string;
106
+ /** 模板名称 */
107
+ name: string;
108
+ /** LaTeX 源码 */
109
+ latex: string;
110
+ /** 描述 */
111
+ description: string;
112
+ /** 分类 */
113
+ category: string;
114
+ /** 预览 HTML */
115
+ previewHtml?: string;
116
+ }
117
+ /** 化学元素详细信息 */
118
+ interface ElementInfo {
119
+ /** 元素符号 */
120
+ symbol: string;
121
+ /** 元素名称 */
122
+ name: string;
123
+ /** 原子序数 */
124
+ atomicNumber: number;
125
+ /** 相对原子质量 */
126
+ atomicMass: number;
127
+ /** 族 */
128
+ group: number;
129
+ /** 周期 */
130
+ period: number;
131
+ /** 区块 */
132
+ block: 's' | 'p' | 'd' | 'f';
133
+ /** 电负性 */
134
+ electronegativity?: number;
135
+ /** 常见氧化态 */
136
+ oxidationStates?: number[];
137
+ /** 常见化合物 */
138
+ commonCompounds?: string[];
139
+ }
140
+ /** 知识库查询结果 */
141
+ interface KBQueryResult {
142
+ /** 匹配的符号 */
143
+ symbols: SymbolInfo[];
144
+ /** 匹配的公式模板 */
145
+ formulas: FormulaTemplate[];
146
+ /** 匹配的元素 */
147
+ elements: ElementInfo[];
148
+ /** 原始 AI 响应(可选,用于调试) */
149
+ rawResponse?: string;
150
+ }
151
+ /**
152
+ * 知识库提供者接口(SPI)
153
+ *
154
+ * 使用方实现此接口,将自己的知识库/向量数据库注入引擎
155
+ */
156
+ interface IKnowledgeBaseProvider {
157
+ readonly id: string;
158
+ readonly name: string;
159
+ /**
160
+ * 通用知识查询
161
+ */
162
+ query(params: KBQueryParams): Promise<KBQueryResult>;
163
+ /**
164
+ * 按符号搜索
165
+ */
166
+ searchSymbols(query: string, limit?: number): Promise<SymbolInfo[]>;
167
+ /**
168
+ * 按公式名搜索
169
+ */
170
+ searchFormulas(query: string, limit?: number): Promise<FormulaTemplate[]>;
171
+ /**
172
+ * 获取元素详细信息
173
+ */
174
+ getElementInfo(symbol: string): Promise<ElementInfo | null>;
175
+ /**
176
+ * 语义检索(可选,基于向量相似度)
177
+ * "跟水相关的化合物" → 语义匹配
178
+ */
179
+ semanticSearch?(query: string, limit?: number): Promise<KBQueryResult>;
180
+ /**
181
+ * 批量获取元素信息(可选)
182
+ */
183
+ getElementsBatch?(symbols: string[]): Promise<Map<string, ElementInfo>>;
184
+ }
185
+
186
+ /** 规范化修改记录 */
187
+ interface NormalizationChange {
188
+ /** 修改类型 */
189
+ type: 'delimiter-fix' | 'command-fix' | 'unicode-convert' | 'format-unify' | 'chemical-fix';
190
+ /** 修改前 */
191
+ from: string;
192
+ /** 修改后 */
193
+ to: string;
194
+ /** 修改原因 */
195
+ reason: string;
196
+ }
197
+ /** 规范化结果 */
198
+ interface NormalizedResult {
199
+ /** 规范化后的表达式文本 */
200
+ normalized: string;
201
+ /** 原始输入 */
202
+ original: string;
203
+ /** 置信度 0-1 */
204
+ confidence: number;
205
+ /** 所做的修改列表 */
206
+ changes: NormalizationChange[];
207
+ /** 规范化后的 AST */
208
+ ast: ExpressionRoot;
209
+ }
210
+ /**
211
+ * AI 规范化提供者接口(SPI)
212
+ *
213
+ * 用于统一不同 LLM 输出的格式差异:
214
+ * - ChatGPT 输出: $$H_2O$$
215
+ * - Claude 输出: \(H_2O\)
216
+ * - Gemini 输出: H₂O (Unicode)
217
+ * - 某模型输出: \ce{H2O}
218
+ *
219
+ * 引擎通过此接口将以上所有格式统一为标准格式
220
+ */
221
+ interface IAINormalizerProvider {
222
+ readonly id: string;
223
+ readonly name: string;
224
+ /**
225
+ * 规范化 AI 输出
226
+ * @param input 原始 AI 输出
227
+ * @param targetFormat 目标格式
228
+ */
229
+ normalize(input: string, targetFormat: 'latex' | 'unicode' | 'chemical' | 'auto'): Promise<NormalizedResult>;
230
+ /**
231
+ * 自动检测并修复
232
+ */
233
+ detectAndFix(input: string): Promise<NormalizedResult>;
234
+ /**
235
+ * 批量规范化(可选)
236
+ */
237
+ normalizeBatch?(inputs: string[], targetFormat: 'latex' | 'unicode' | 'chemical'): Promise<NormalizedResult[]>;
238
+ }
239
+
240
+ /** 格式化风格 */
241
+ interface FormatStyle {
242
+ /** 目标输出格式 */
243
+ outputFormat: 'latex' | 'unicode' | 'mathml';
244
+ /** 领域约定 */
245
+ domain?: 'physics' | 'chemistry' | 'mathematics' | 'biology' | 'general';
246
+ /** 是否使用 ISO 标准符号 */
247
+ isoStandard?: boolean;
248
+ /** 分数显示偏好 */
249
+ fractionStyle?: 'frac' | 'tfrac' | 'dfrac' | 'inline';
250
+ /** 自定义规则 */
251
+ customRules?: FormatRule[];
252
+ }
253
+ /** 格式化规则 */
254
+ interface FormatRule {
255
+ id: string;
256
+ description: string;
257
+ /** 匹配条件 */
258
+ match: (node: ExpressionNode) => boolean;
259
+ /** 转换规则 */
260
+ apply: (node: ExpressionNode) => ExpressionNode;
261
+ }
262
+ /** 格式化建议 */
263
+ interface FormatSuggestion {
264
+ description: string;
265
+ /** 修改前的 LaTeX */
266
+ before: string;
267
+ /** 修改后的 LaTeX */
268
+ after: string;
269
+ reason: string;
270
+ confidence: number;
271
+ }
272
+ /**
273
+ * AI 格式化提供者接口(SPI)
274
+ *
275
+ * 使用 AI 将表达式优化为特定领域的规范格式
276
+ */
277
+ interface IAIFormatterProvider {
278
+ readonly id: string;
279
+ readonly name: string;
280
+ /**
281
+ * 格式化 AST
282
+ * @param ast 待格式化 AST
283
+ * @param style 目标风格
284
+ */
285
+ format(ast: ExpressionRoot, style: FormatStyle): Promise<ExpressionRoot>;
286
+ /**
287
+ * 格式建议(可选,不直接修改,返回建议列表)
288
+ */
289
+ suggest?(ast: ExpressionRoot, style: FormatStyle): Promise<FormatSuggestion[]>;
290
+ }
291
+
292
+ /** AI 缓存配置 */
293
+ interface AICacheConfig {
294
+ enabled: boolean;
295
+ ttlMs: number;
296
+ maxSize: number;
297
+ }
298
+ /** AI 管线配置 */
299
+ interface AIPipelineConfig {
300
+ completionProvider?: IAICompletionProvider;
301
+ knowledgeBaseProvider?: IKnowledgeBaseProvider;
302
+ normalizerProvider?: IAINormalizerProvider;
303
+ formatterProvider?: IAIFormatterProvider;
304
+ aiEnabled?: boolean;
305
+ completionDebounceMs?: number;
306
+ maxCompletions?: number;
307
+ cache?: AICacheConfig;
308
+ }
309
+ /**
310
+ * AI 管线
311
+ *
312
+ * 统一编排所有 AI Provider,处理回退逻辑和缓存。
313
+ * 默认使用内置回退实现(离线可用),外部 Provider 作为增强。
314
+ */
315
+ declare class AIPipeline {
316
+ private completionProvider;
317
+ private knowledgeBaseProvider;
318
+ private normalizerProvider;
319
+ private formatterProvider;
320
+ private aiEnabled;
321
+ private maxCompletions;
322
+ private cache;
323
+ private completionCache;
324
+ private kbCache;
325
+ private eventListeners;
326
+ constructor(config?: AIPipelineConfig);
327
+ /**
328
+ * 获取智能补全(本地 + AI 混合)
329
+ */
330
+ getCompletions(context: CompletionContext): Promise<CompletionResult>;
331
+ /**
332
+ * 查询知识库
333
+ */
334
+ queryKnowledge(params: KBQueryParams): Promise<KBQueryResult>;
335
+ /**
336
+ * 规范化 AI 输出
337
+ */
338
+ normalize(input: string, format?: 'latex' | 'unicode' | 'chemical' | 'auto'): Promise<NormalizedResult>;
339
+ /**
340
+ * 格式化表达式
341
+ */
342
+ format(ast: ExpressionRoot, style?: Partial<FormatStyle>): Promise<ExpressionRoot>;
343
+ /**
344
+ * 自然语言 → 公式
345
+ */
346
+ naturalLanguageToFormula(query: string): Promise<CompletionItem[]>;
347
+ /**
348
+ * AI 纠错
349
+ */
350
+ correct(input: string, error: ValidationError): Promise<CompletionItem[]>;
351
+ setEnabled(enabled: boolean): void;
352
+ isEnabled(): boolean;
353
+ getCacheStats(): {
354
+ hits: number;
355
+ misses: number;
356
+ completionSize: number;
357
+ kbSize: number;
358
+ };
359
+ clearCache(): void;
360
+ on(event: string, callback: (...args: any[]) => void): void;
361
+ off(event: string, callback: (...args: any[]) => void): void;
362
+ private emit;
363
+ private getCached;
364
+ private setCache;
365
+ }
366
+
367
+ /** Prompt 模板定义 */
368
+ interface PromptTemplate {
369
+ /** 模板名称 */
370
+ name: string;
371
+ /** System prompt 模板 */
372
+ system: string;
373
+ /** User message 模板 */
374
+ user: string;
375
+ /** 模板变量列表 */
376
+ variables: string[];
377
+ }
378
+ /** 内置 Prompt 模板 */
379
+ declare const BUILTIN_PROMPTS: Record<string, PromptTemplate>;
380
+ /**
381
+ * Prompt 注册表(支持自定义模板覆盖)
382
+ */
383
+ declare class PromptRegistry {
384
+ private templates;
385
+ constructor();
386
+ /**
387
+ * 注册自定义 Prompt 模板(可覆盖内置)
388
+ */
389
+ register(template: PromptTemplate): void;
390
+ /**
391
+ * 获取模板
392
+ */
393
+ get(name: string): PromptTemplate | undefined;
394
+ /**
395
+ * 渲染模板为 system + user 消息
396
+ */
397
+ render(name: string, variables: Record<string, string>): {
398
+ system: string;
399
+ user: string;
400
+ } | null;
401
+ /**
402
+ * 获取所有已注册模板名称
403
+ */
404
+ list(): string[];
405
+ /**
406
+ * 移除自定义模板(不能移除内置模板)
407
+ */
408
+ remove(name: string): boolean;
409
+ }
410
+
411
+ /** 流数据源类型 */
412
+ type StreamSource = {
413
+ type: 'sse';
414
+ url: string;
415
+ } | {
416
+ type: 'websocket';
417
+ url: string;
418
+ } | {
419
+ type: 'async-iterator';
420
+ iterator: AsyncIterable<string>;
421
+ } | {
422
+ type: 'callback';
423
+ onRead: (callback: (chunk: string) => void) => void;
424
+ };
425
+ /**
426
+ * 流式 AI 响应适配器
427
+ * 支持 SSE / WebSocket / AsyncIterator
428
+ */
429
+ interface IAIStreamAdapter {
430
+ /** 连接流式源 */
431
+ connect(source: StreamSource): Promise<void>;
432
+ /** 监听增量 token */
433
+ onToken(callback: (token: CompletionItem) => void): void;
434
+ /** 监听完成 */
435
+ onComplete(callback: (result: CompletionResult) => void): void;
436
+ /** 监听错误 */
437
+ onError(callback: (error: Error) => void): void;
438
+ /** 取消连接 */
439
+ abort(): void;
440
+ }
441
+
442
+ declare class BuiltinCompletionProvider implements IAICompletionProvider {
443
+ readonly id = "builtin-completion";
444
+ readonly name = "Built-in Symbol Completion";
445
+ complete(context: CompletionContext): Promise<CompletionResult>;
446
+ }
447
+ declare class BuiltinKnowledgeBase implements IKnowledgeBaseProvider {
448
+ readonly id = "builtin-kb";
449
+ readonly name = "Built-in Knowledge Base";
450
+ query(params: KBQueryParams): Promise<KBQueryResult>;
451
+ searchSymbols(query: string, limit?: number): Promise<SymbolInfo[]>;
452
+ searchFormulas(query: string, limit?: number): Promise<FormulaTemplate[]>;
453
+ getElementInfo(symbol: string): Promise<ElementInfo | null>;
454
+ }
455
+ declare class BuiltinNormalizer implements IAINormalizerProvider {
456
+ readonly id = "builtin-normalizer";
457
+ readonly name = "Built-in Regex Normalizer";
458
+ normalize(input: string, targetFormat: 'latex' | 'unicode' | 'chemical' | 'auto'): Promise<NormalizedResult>;
459
+ detectAndFix(input: string): Promise<NormalizedResult>;
460
+ }
461
+ declare class BuiltinFormatter implements IAIFormatterProvider {
462
+ readonly id = "builtin-formatter";
463
+ readonly name = "Built-in Rule Formatter";
464
+ format(ast: ExpressionRoot, _style: FormatStyle): Promise<ExpressionRoot>;
465
+ }
466
+
467
+ export { type AICacheConfig, AIPipeline, type AIPipelineConfig, BUILTIN_PROMPTS, BuiltinCompletionProvider, BuiltinFormatter, BuiltinKnowledgeBase, BuiltinNormalizer, type CompletionContext, type CompletionItem, type CompletionResult, type ElementInfo, type FormatRule, type FormatStyle, type FormatSuggestion, type FormulaTemplate, type IAICompletionProvider, type IAIFormatterProvider, type IAINormalizerProvider, type IAIStreamAdapter, type IKnowledgeBaseProvider, type KBQueryParams, type KBQueryResult, type NormalizationChange, type NormalizedResult, PromptRegistry, type PromptTemplate, type StreamSource, type SymbolInfo };