@git.zone/tsdoc 1.11.0 → 1.11.2

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 (62) hide show
  1. package/dist_ts/aidocs_classes/commit.js +27 -34
  2. package/dist_ts/aidocs_classes/description.js +68 -29
  3. package/dist_ts/aidocs_classes/projectcontext.d.ts +5 -5
  4. package/dist_ts/aidocs_classes/projectcontext.js +8 -16
  5. package/dist_ts/aidocs_classes/readme.js +156 -88
  6. package/dist_ts/classes.aidoc.d.ts +10 -6
  7. package/dist_ts/classes.aidoc.js +17 -11
  8. package/dist_ts/classes.diffprocessor.js +284 -0
  9. package/dist_ts/cli.js +21 -92
  10. package/dist_ts/plugins.d.ts +1 -2
  11. package/dist_ts/plugins.js +2 -3
  12. package/package.json +11 -13
  13. package/ts/aidocs_classes/commit.ts +26 -41
  14. package/ts/aidocs_classes/description.ts +72 -34
  15. package/ts/aidocs_classes/projectcontext.ts +7 -14
  16. package/ts/aidocs_classes/readme.ts +168 -93
  17. package/ts/classes.aidoc.ts +18 -11
  18. package/ts/cli.ts +20 -100
  19. package/ts/plugins.ts +1 -2
  20. package/dist_ts/context/config-manager.d.ts +0 -83
  21. package/dist_ts/context/config-manager.js +0 -318
  22. package/dist_ts/context/context-analyzer.d.ts +0 -73
  23. package/dist_ts/context/context-analyzer.js +0 -311
  24. package/dist_ts/context/context-cache.d.ts +0 -73
  25. package/dist_ts/context/context-cache.js +0 -239
  26. package/dist_ts/context/context-trimmer.d.ts +0 -60
  27. package/dist_ts/context/context-trimmer.js +0 -258
  28. package/dist_ts/context/diff-processor.js +0 -284
  29. package/dist_ts/context/enhanced-context.d.ts +0 -73
  30. package/dist_ts/context/enhanced-context.js +0 -275
  31. package/dist_ts/context/index.d.ts +0 -11
  32. package/dist_ts/context/index.js +0 -12
  33. package/dist_ts/context/iterative-context-builder.d.ts +0 -62
  34. package/dist_ts/context/iterative-context-builder.js +0 -395
  35. package/dist_ts/context/lazy-file-loader.d.ts +0 -60
  36. package/dist_ts/context/lazy-file-loader.js +0 -182
  37. package/dist_ts/context/task-context-factory.d.ts +0 -48
  38. package/dist_ts/context/task-context-factory.js +0 -86
  39. package/dist_ts/context/types.d.ts +0 -301
  40. package/dist_ts/context/types.js +0 -2
  41. package/dist_ts/tsdoc.classes.typedoc.d.ts +0 -10
  42. package/dist_ts/tsdoc.classes.typedoc.js +0 -48
  43. package/dist_ts/tsdoc.cli.d.ts +0 -1
  44. package/dist_ts/tsdoc.cli.js +0 -32
  45. package/dist_ts/tsdoc.logging.d.ts +0 -2
  46. package/dist_ts/tsdoc.logging.js +0 -14
  47. package/dist_ts/tsdoc.paths.d.ts +0 -8
  48. package/dist_ts/tsdoc.paths.js +0 -12
  49. package/dist_ts/tsdoc.plugins.d.ts +0 -11
  50. package/dist_ts/tsdoc.plugins.js +0 -15
  51. package/ts/context/config-manager.ts +0 -369
  52. package/ts/context/context-analyzer.ts +0 -391
  53. package/ts/context/context-cache.ts +0 -286
  54. package/ts/context/context-trimmer.ts +0 -310
  55. package/ts/context/enhanced-context.ts +0 -332
  56. package/ts/context/index.ts +0 -70
  57. package/ts/context/iterative-context-builder.ts +0 -512
  58. package/ts/context/lazy-file-loader.ts +0 -207
  59. package/ts/context/task-context-factory.ts +0 -120
  60. package/ts/context/types.ts +0 -324
  61. /package/dist_ts/{context/diff-processor.d.ts → classes.diffprocessor.d.ts} +0 -0
  62. /package/ts/{context/diff-processor.ts → classes.diffprocessor.ts} +0 -0
@@ -1,512 +0,0 @@
1
- import * as plugins from '../plugins.js';
2
- import * as fs from 'fs';
3
- import { logger } from '../logging.js';
4
- import type {
5
- TaskType,
6
- IFileMetadata,
7
- IFileInfo,
8
- IIterativeContextResult,
9
- IIterationState,
10
- IFileSelectionDecision,
11
- IContextSufficiencyDecision,
12
- IIterativeConfig,
13
- } from './types.js';
14
- import { LazyFileLoader } from './lazy-file-loader.js';
15
- import { ContextCache } from './context-cache.js';
16
- import { ContextAnalyzer } from './context-analyzer.js';
17
- import { ConfigManager } from './config-manager.js';
18
-
19
- /**
20
- * Iterative context builder that uses AI to intelligently select files
21
- * across multiple iterations until sufficient context is gathered
22
- */
23
- export class IterativeContextBuilder {
24
- private projectRoot: string;
25
- private lazyLoader: LazyFileLoader;
26
- private cache: ContextCache;
27
- private analyzer: ContextAnalyzer;
28
- private config: Required<IIterativeConfig>;
29
- private tokenBudget: number = 190000;
30
- private openaiInstance: plugins.smartai.OpenAiProvider;
31
- private externalOpenaiInstance?: plugins.smartai.OpenAiProvider;
32
-
33
- /**
34
- * Creates a new IterativeContextBuilder
35
- * @param projectRoot - Root directory of the project
36
- * @param config - Iterative configuration
37
- * @param openaiInstance - Optional pre-configured OpenAI provider instance
38
- */
39
- constructor(
40
- projectRoot: string,
41
- config?: Partial<IIterativeConfig>,
42
- openaiInstance?: plugins.smartai.OpenAiProvider
43
- ) {
44
- this.projectRoot = projectRoot;
45
- this.lazyLoader = new LazyFileLoader(projectRoot);
46
- this.cache = new ContextCache(projectRoot);
47
- this.analyzer = new ContextAnalyzer(projectRoot);
48
- this.externalOpenaiInstance = openaiInstance;
49
-
50
- // Default configuration
51
- this.config = {
52
- maxIterations: config?.maxIterations ?? 5,
53
- firstPassFileLimit: config?.firstPassFileLimit ?? 10,
54
- subsequentPassFileLimit: config?.subsequentPassFileLimit ?? 5,
55
- temperature: config?.temperature ?? 0.3,
56
- model: config?.model ?? 'gpt-4-turbo-preview',
57
- };
58
-
59
- }
60
-
61
- /**
62
- * Initialize the builder
63
- */
64
- public async initialize(): Promise<void> {
65
- await this.cache.init();
66
- const configManager = ConfigManager.getInstance();
67
- await configManager.initialize(this.projectRoot);
68
- this.tokenBudget = configManager.getMaxTokens();
69
-
70
- // Use external OpenAI instance if provided, otherwise create a new one
71
- if (this.externalOpenaiInstance) {
72
- this.openaiInstance = this.externalOpenaiInstance;
73
- } else {
74
- // Initialize OpenAI instance from environment
75
- const qenvInstance = new plugins.qenv.Qenv();
76
- const openaiToken = await qenvInstance.getEnvVarOnDemand('OPENAI_TOKEN');
77
- if (!openaiToken) {
78
- throw new Error('OPENAI_TOKEN environment variable is required for iterative context building');
79
- }
80
- this.openaiInstance = new plugins.smartai.OpenAiProvider({
81
- openaiToken,
82
- });
83
- await this.openaiInstance.start();
84
- }
85
- }
86
-
87
- /**
88
- * Build context iteratively using AI decision making
89
- * @param taskType - Type of task being performed
90
- * @param additionalContext - Optional additional context (e.g., git diff for commit tasks)
91
- * @returns Complete iterative context result
92
- */
93
- public async buildContextIteratively(taskType: TaskType, additionalContext?: string): Promise<IIterativeContextResult> {
94
- const startTime = Date.now();
95
- logger.log('info', '🤖 Starting iterative context building...');
96
- logger.log('info', ` Task: ${taskType}, Budget: ${this.tokenBudget} tokens, Max iterations: ${this.config.maxIterations}`);
97
-
98
- // Phase 1: Scan project files for metadata
99
- logger.log('info', '📋 Scanning project files...');
100
- const metadata = await this.scanProjectFiles(taskType);
101
- const totalEstimatedTokens = metadata.reduce((sum, m) => sum + m.estimatedTokens, 0);
102
- logger.log('info', ` Found ${metadata.length} files (~${totalEstimatedTokens} estimated tokens)`);
103
-
104
- // Phase 2: Analyze files for initial prioritization
105
- logger.log('info', '🔍 Analyzing file dependencies and importance...');
106
- const analysis = await this.analyzer.analyze(metadata, taskType, []);
107
- logger.log('info', ` Analysis complete in ${analysis.analysisDuration}ms`);
108
-
109
- // Track state across iterations
110
- const iterations: IIterationState[] = [];
111
- let totalTokensUsed = 0;
112
- let apiCallCount = 0;
113
- let loadedContent = '';
114
- const includedFiles: IFileInfo[] = [];
115
-
116
- // If additional context (e.g., git diff) is provided, prepend it
117
- if (additionalContext) {
118
- // NOTE: additionalContext is expected to be pre-processed by DiffProcessor
119
- // which intelligently samples large diffs to stay within token budget (100k default)
120
- const MAX_DIFF_TOKENS = 200000; // Safety net for edge cases (DiffProcessor uses 100k budget)
121
-
122
- const diffSection = `
123
- ====== GIT DIFF ======
124
-
125
- ${additionalContext}
126
-
127
- ====== END OF GIT DIFF ======
128
- `;
129
-
130
- // Validate token count (should already be under budget from DiffProcessor)
131
- const diffTokens = this.countTokens(diffSection);
132
-
133
- if (diffTokens > MAX_DIFF_TOKENS) {
134
- logger.log('error', `❌ Pre-processed git diff exceeds safety limit (${diffTokens.toLocaleString()} tokens > ${MAX_DIFF_TOKENS.toLocaleString()} limit)`);
135
- logger.log('error', ` This should not happen - DiffProcessor should have limited to ~100k tokens.`);
136
- logger.log('error', ` Please check DiffProcessor configuration and output.`);
137
- throw new Error(
138
- `Pre-processed git diff size (${diffTokens.toLocaleString()} tokens) exceeds safety limit (${MAX_DIFF_TOKENS.toLocaleString()} tokens). ` +
139
- `This indicates a bug in DiffProcessor or misconfiguration.`
140
- );
141
- }
142
-
143
- loadedContent = diffSection;
144
- totalTokensUsed += diffTokens;
145
- logger.log('info', `📝 Added pre-processed git diff to context (${diffTokens.toLocaleString()} tokens)`);
146
- }
147
-
148
- // Phase 3: Iterative file selection and loading
149
- for (let iteration = 1; iteration <= this.config.maxIterations; iteration++) {
150
- const iterationStart = Date.now();
151
- logger.log('info', `\n🤔 Iteration ${iteration}/${this.config.maxIterations}: Asking AI which files to examine...`);
152
-
153
- const remainingBudget = this.tokenBudget - totalTokensUsed;
154
- logger.log('info', ` Token budget remaining: ${remainingBudget}/${this.tokenBudget} (${Math.round((remainingBudget / this.tokenBudget) * 100)}%)`);
155
-
156
- // Get AI decision on which files to load
157
- const decision = await this.getFileSelectionDecision(
158
- metadata,
159
- analysis.files.slice(0, 30), // Top 30 files by importance
160
- taskType,
161
- iteration,
162
- totalTokensUsed,
163
- remainingBudget,
164
- loadedContent
165
- );
166
- apiCallCount++;
167
-
168
- logger.log('info', ` AI reasoning: ${decision.reasoning}`);
169
- logger.log('info', ` AI requested ${decision.filesToLoad.length} files`);
170
-
171
- // Load requested files
172
- const iterationFiles: IFileInfo[] = [];
173
- let iterationTokens = 0;
174
-
175
- if (decision.filesToLoad.length > 0) {
176
- logger.log('info', '📥 Loading requested files...');
177
-
178
- for (const filePath of decision.filesToLoad) {
179
- try {
180
- const fileInfo = await this.loadFile(filePath);
181
- if (totalTokensUsed + fileInfo.tokenCount! <= this.tokenBudget) {
182
- const formattedFile = this.formatFileForContext(fileInfo);
183
- loadedContent += formattedFile;
184
- includedFiles.push(fileInfo);
185
- iterationFiles.push(fileInfo);
186
- iterationTokens += fileInfo.tokenCount!;
187
- totalTokensUsed += fileInfo.tokenCount!;
188
-
189
- logger.log('info', ` ✓ ${fileInfo.relativePath} (${fileInfo.tokenCount} tokens)`);
190
- } else {
191
- logger.log('warn', ` ✗ ${fileInfo.relativePath} - would exceed budget, skipping`);
192
- }
193
- } catch (error) {
194
- logger.log('warn', ` ✗ Failed to load ${filePath}: ${error.message}`);
195
- }
196
- }
197
- }
198
-
199
- // Record iteration state
200
- const iterationDuration = Date.now() - iterationStart;
201
- iterations.push({
202
- iteration,
203
- filesLoaded: iterationFiles,
204
- tokensUsed: iterationTokens,
205
- totalTokensUsed,
206
- decision,
207
- duration: iterationDuration,
208
- });
209
-
210
- logger.log('info', ` Iteration ${iteration} complete: ${iterationFiles.length} files loaded, ${iterationTokens} tokens used`);
211
-
212
- // Check if we should continue
213
- if (totalTokensUsed >= this.tokenBudget * 0.95) {
214
- logger.log('warn', '⚠️ Approaching token budget limit, stopping iterations');
215
- break;
216
- }
217
-
218
- // Ask AI if context is sufficient
219
- if (iteration < this.config.maxIterations) {
220
- logger.log('info', '🤔 Asking AI if context is sufficient...');
221
- const sufficiencyDecision = await this.evaluateContextSufficiency(
222
- loadedContent,
223
- taskType,
224
- iteration,
225
- totalTokensUsed,
226
- remainingBudget - iterationTokens
227
- );
228
- apiCallCount++;
229
-
230
- logger.log('info', ` AI decision: ${sufficiencyDecision.sufficient ? '✅ SUFFICIENT' : '⏭️ NEEDS MORE'}`);
231
- logger.log('info', ` Reasoning: ${sufficiencyDecision.reasoning}`);
232
-
233
- if (sufficiencyDecision.sufficient) {
234
- logger.log('ok', '✅ Context building complete - AI determined context is sufficient');
235
- break;
236
- }
237
- }
238
- }
239
-
240
- const totalDuration = Date.now() - startTime;
241
- logger.log('ok', `\n✅ Iterative context building complete!`);
242
- logger.log('info', ` Files included: ${includedFiles.length}`);
243
- logger.log('info', ` Token usage: ${totalTokensUsed}/${this.tokenBudget} (${Math.round((totalTokensUsed / this.tokenBudget) * 100)}%)`);
244
- logger.log('info', ` Iterations: ${iterations.length}, API calls: ${apiCallCount}`);
245
- logger.log('info', ` Total duration: ${(totalDuration / 1000).toFixed(2)}s`);
246
-
247
- return {
248
- context: loadedContent,
249
- tokenCount: totalTokensUsed,
250
- includedFiles,
251
- trimmedFiles: [],
252
- excludedFiles: [],
253
- tokenSavings: 0,
254
- iterationCount: iterations.length,
255
- iterations,
256
- apiCallCount,
257
- totalDuration,
258
- };
259
- }
260
-
261
- /**
262
- * Scan project files based on task type
263
- */
264
- private async scanProjectFiles(taskType: TaskType): Promise<IFileMetadata[]> {
265
- const configManager = ConfigManager.getInstance();
266
- const taskConfig = configManager.getTaskConfig(taskType);
267
-
268
- const includeGlobs = taskConfig?.includePaths?.map(p => `${p}/**/*.ts`) || [
269
- 'ts/**/*.ts',
270
- 'ts*/**/*.ts'
271
- ];
272
-
273
- const configGlobs = [
274
- 'package.json',
275
- 'readme.md',
276
- 'readme.hints.md',
277
- 'npmextra.json'
278
- ];
279
-
280
- return await this.lazyLoader.scanFiles([...configGlobs, ...includeGlobs]);
281
- }
282
-
283
- /**
284
- * Get AI decision on which files to load
285
- */
286
- private async getFileSelectionDecision(
287
- allMetadata: IFileMetadata[],
288
- analyzedFiles: any[],
289
- taskType: TaskType,
290
- iteration: number,
291
- tokensUsed: number,
292
- remainingBudget: number,
293
- loadedContent: string
294
- ): Promise<IFileSelectionDecision> {
295
- const isFirstIteration = iteration === 1;
296
- const fileLimit = isFirstIteration
297
- ? this.config.firstPassFileLimit
298
- : this.config.subsequentPassFileLimit;
299
-
300
- const systemPrompt = this.buildFileSelectionPrompt(
301
- allMetadata,
302
- analyzedFiles,
303
- taskType,
304
- iteration,
305
- tokensUsed,
306
- remainingBudget,
307
- loadedContent,
308
- fileLimit
309
- );
310
-
311
- const response = await this.openaiInstance.chat({
312
- systemMessage: `You are an AI assistant that helps select the most relevant files for code analysis.
313
- You must respond ONLY with valid JSON that can be parsed with JSON.parse().
314
- Do not wrap the JSON in markdown code blocks or add any other text.`,
315
- userMessage: systemPrompt,
316
- messageHistory: [],
317
- });
318
-
319
- // Parse JSON response, handling potential markdown formatting
320
- const content = response.message.replace('```json', '').replace('```', '').trim();
321
- const parsed = JSON.parse(content);
322
-
323
- return {
324
- reasoning: parsed.reasoning || 'No reasoning provided',
325
- filesToLoad: parsed.files_to_load || [],
326
- estimatedTokensNeeded: parsed.estimated_tokens_needed,
327
- };
328
- }
329
-
330
- /**
331
- * Build prompt for file selection
332
- */
333
- private buildFileSelectionPrompt(
334
- metadata: IFileMetadata[],
335
- analyzedFiles: any[],
336
- taskType: TaskType,
337
- iteration: number,
338
- tokensUsed: number,
339
- remainingBudget: number,
340
- loadedContent: string,
341
- fileLimit: number
342
- ): string {
343
- const taskDescriptions = {
344
- readme: 'generating a comprehensive README that explains the project\'s purpose, features, and API',
345
- commit: 'analyzing code changes to generate an intelligent commit message',
346
- description: 'generating a concise project description for package.json',
347
- };
348
-
349
- const alreadyLoadedFiles = loadedContent
350
- ? loadedContent.split('\n======').slice(1).map(section => {
351
- const match = section.match(/START OF FILE (.+?) ======/);
352
- return match ? match[1] : '';
353
- }).filter(Boolean)
354
- : [];
355
-
356
- const availableFiles = metadata
357
- .filter(m => !alreadyLoadedFiles.includes(m.relativePath))
358
- .map(m => {
359
- const analysis = analyzedFiles.find(a => a.path === m.path);
360
- return `- ${m.relativePath} (${m.size} bytes, ~${m.estimatedTokens} tokens${analysis ? `, importance: ${analysis.importanceScore.toFixed(2)}` : ''})`;
361
- })
362
- .join('\n');
363
-
364
- return `You are building context for ${taskDescriptions[taskType]} in a TypeScript project.
365
-
366
- ITERATION: ${iteration}
367
- TOKENS USED: ${tokensUsed}/${tokensUsed + remainingBudget} (${Math.round((tokensUsed / (tokensUsed + remainingBudget)) * 100)}%)
368
- REMAINING BUDGET: ${remainingBudget} tokens
369
-
370
- ${alreadyLoadedFiles.length > 0 ? `FILES ALREADY LOADED:\n${alreadyLoadedFiles.map(f => `- ${f}`).join('\n')}\n\n` : ''}AVAILABLE FILES (not yet loaded):
371
- ${availableFiles}
372
-
373
- Your task: Select up to ${fileLimit} files that will give you the MOST understanding for this ${taskType} task.
374
-
375
- ${iteration === 1 ? `This is the FIRST iteration. Focus on:
376
- - Main entry points (index.ts, main exports)
377
- - Core classes and interfaces
378
- - Package configuration
379
- ` : `This is iteration ${iteration}. You've already seen some files. Now focus on:
380
- - Files that complement what you've already loaded
381
- - Dependencies of already-loaded files
382
- - Missing pieces for complete understanding
383
- `}
384
-
385
- Consider:
386
- 1. File importance scores (if provided)
387
- 2. File paths (ts/index.ts is likely more important than ts/internal/utils.ts)
388
- 3. Token efficiency (prefer smaller files if they provide good information)
389
- 4. Remaining budget (${remainingBudget} tokens)
390
-
391
- Respond in JSON format:
392
- {
393
- "reasoning": "Brief explanation of why you're selecting these files",
394
- "files_to_load": ["path/to/file1.ts", "path/to/file2.ts"],
395
- "estimated_tokens_needed": 15000
396
- }`;
397
- }
398
-
399
- /**
400
- * Evaluate if current context is sufficient
401
- */
402
- private async evaluateContextSufficiency(
403
- loadedContent: string,
404
- taskType: TaskType,
405
- iteration: number,
406
- tokensUsed: number,
407
- remainingBudget: number
408
- ): Promise<IContextSufficiencyDecision> {
409
- const prompt = `You have been building context for a ${taskType} task across ${iteration} iterations.
410
-
411
- CURRENT STATE:
412
- - Tokens used: ${tokensUsed}
413
- - Remaining budget: ${remainingBudget}
414
- - Files loaded: ${loadedContent.split('\n======').length - 1}
415
-
416
- CONTEXT SO FAR:
417
- ${loadedContent.substring(0, 3000)}... (truncated for brevity)
418
-
419
- Question: Do you have SUFFICIENT context to successfully complete the ${taskType} task?
420
-
421
- Consider:
422
- - For README: Do you understand the project's purpose, main features, API surface, and usage patterns?
423
- - For commit: Do you understand what changed and why?
424
- - For description: Do you understand the project's core value proposition?
425
-
426
- Respond in JSON format:
427
- {
428
- "sufficient": true or false,
429
- "reasoning": "Detailed explanation of your decision"
430
- }`;
431
-
432
- const response = await this.openaiInstance.chat({
433
- systemMessage: `You are an AI assistant that evaluates whether gathered context is sufficient for a task.
434
- You must respond ONLY with valid JSON that can be parsed with JSON.parse().
435
- Do not wrap the JSON in markdown code blocks or add any other text.`,
436
- userMessage: prompt,
437
- messageHistory: [],
438
- });
439
-
440
- // Parse JSON response, handling potential markdown formatting
441
- const content = response.message.replace('```json', '').replace('```', '').trim();
442
- const parsed = JSON.parse(content);
443
-
444
- return {
445
- sufficient: parsed.sufficient || false,
446
- reasoning: parsed.reasoning || 'No reasoning provided',
447
- };
448
- }
449
-
450
- /**
451
- * Load a single file with caching
452
- */
453
- private async loadFile(filePath: string): Promise<IFileInfo> {
454
- // Try cache first
455
- const cached = await this.cache.get(filePath);
456
- if (cached) {
457
- return {
458
- path: filePath,
459
- relativePath: plugins.path.relative(this.projectRoot, filePath),
460
- contents: cached.contents,
461
- tokenCount: cached.tokenCount,
462
- };
463
- }
464
-
465
- // Load from disk
466
- const contents = await plugins.fsInstance.file(filePath).encoding('utf8').read() as string;
467
- const tokenCount = this.countTokens(contents);
468
- const relativePath = plugins.path.relative(this.projectRoot, filePath);
469
-
470
- // Cache it
471
- const stats = await fs.promises.stat(filePath);
472
- await this.cache.set({
473
- path: filePath,
474
- contents,
475
- tokenCount,
476
- mtime: Math.floor(stats.mtimeMs),
477
- cachedAt: Date.now(),
478
- });
479
-
480
- return {
481
- path: filePath,
482
- relativePath,
483
- contents,
484
- tokenCount,
485
- };
486
- }
487
-
488
- /**
489
- * Format a file for inclusion in context
490
- */
491
- private formatFileForContext(file: IFileInfo): string {
492
- return `
493
- ====== START OF FILE ${file.relativePath} ======
494
-
495
- ${file.contents}
496
-
497
- ====== END OF FILE ${file.relativePath} ======
498
- `;
499
- }
500
-
501
- /**
502
- * Count tokens in text
503
- */
504
- private countTokens(text: string): number {
505
- try {
506
- const tokens = plugins.gptTokenizer.encode(text);
507
- return tokens.length;
508
- } catch (error) {
509
- return Math.ceil(text.length / 4);
510
- }
511
- }
512
- }