File size: 11,822 Bytes
e706de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import {LlamaText} from "node-llama-cpp";
import path from "path";
import fs from "fs/promises";

/**

 * Output types for debugging

 */
const OutputTypes = {
    EXACT_PROMPT: 'exactPrompt',
    CONTEXT_STATE: 'contextState',
    STRUCTURED: 'structured'
};

/**

 * Helper class for debugging and logging LLM prompts

 */
export class PromptDebugger {
    constructor(options = {}) {
        this.outputDir = options.outputDir || './';
        this.filename = options.filename;
        this.includeTimestamp = options.includeTimestamp ?? false;
        this.appendMode = options.appendMode ?? false;
        // Configure which outputs to include
        this.outputTypes = options.outputTypes || [OutputTypes.EXACT_PROMPT];
        // Ensure outputTypes is always an array
        if (!Array.isArray(this.outputTypes)) {
            this.outputTypes = [this.outputTypes];
        }
    }

    /**

     * Captures only the exact prompt (user input + system + functions)

     * @param {Object} params

     * @param {Object} params.session - The chat session

     * @param {string} params.prompt - The user prompt

     * @param {string} params.systemPrompt - System prompt (optional)

     * @param {Object} params.functions - Available functions (optional)

     * @returns {Object} The exact prompt data

     */
    captureExactPrompt(params) {
        const { session, prompt, systemPrompt, functions } = params;

        const chatWrapper = session.chatWrapper;

        // Build minimal history for exact prompt
        const history = [{ type: 'user', text: prompt }];

        if (systemPrompt) {
            history.unshift({ type: 'system', text: systemPrompt });
        }

        // Generate the context state with just the current prompt
        const state = chatWrapper.generateContextState({
            chatHistory: history,
            availableFunctions: functions,
            systemPrompt: systemPrompt
        });

        const formattedPrompt = state.contextText.toString();

        return {
            exactPrompt: formattedPrompt,
            timestamp: new Date().toISOString(),
            prompt,
            systemPrompt,
            functions: functions ? Object.keys(functions) : []
        };
    }

    /**

     * Captures the full context state (includes assistant responses)

     * @param {Object} params

     * @param {Object} params.session - The chat session

     * @param {Object} params.model - The loaded model

     * @returns {Object} The context state data

     */
    captureContextState(params) {
        const { session, model } = params;

        // Get the actual context from the session after responses
        const contextState = model.detokenize(session.sequence.contextTokens, true);

        return {
            contextState,
            timestamp: new Date().toISOString(),
            tokenCount: session.sequence.contextTokens.length
        };
    }

    /**

     * Captures the structured token representation

     * @param {Object} params

     * @param {Object} params.session - The chat session

     * @param {Object} params.model - The loaded model

     * @returns {Object} The structured token data

     */
    captureStructured(params) {
        const { session, model } = params;

        const structured = LlamaText.fromTokens(model.tokenizer, session.sequence.contextTokens);

        return {
            structured,
            timestamp: new Date().toISOString(),
            tokenCount: session.sequence.contextTokens.length
        };
    }

    /**

     * Captures all configured output types

     * @param {Object} params - Contains all possible parameters

     * @returns {Object} Combined captured data based on configuration

     */
    captureAll(params) {
        const result = {
            timestamp: new Date().toISOString()
        };

        if (this.outputTypes.includes(OutputTypes.EXACT_PROMPT)) {
            const exactData = this.captureExactPrompt(params);
            result.exactPrompt = exactData.exactPrompt;
            result.prompt = exactData.prompt;
            result.systemPrompt = exactData.systemPrompt;
            result.functions = exactData.functions;
        }

        if (this.outputTypes.includes(OutputTypes.CONTEXT_STATE)) {
            const contextData = this.captureContextState(params);
            result.contextState = contextData.contextState;
            result.contextTokenCount = contextData.tokenCount;
        }

        if (this.outputTypes.includes(OutputTypes.STRUCTURED)) {
            const structuredData = this.captureStructured(params);
            result.structured = structuredData.structured;
            result.structuredTokenCount = structuredData.tokenCount;
        }

        return result;
    }

    /**

     * Formats the captured data based on configuration

     * @param {Object} capturedData - Data from capture methods

     * @returns {string} Formatted output

     */
    formatOutput(capturedData) {
        let output = `\n========== PROMPT DEBUG OUTPUT ==========\n`;
        output += `Timestamp: ${capturedData.timestamp}\n`;

        if (capturedData.prompt) {
            output += `Original Prompt: ${capturedData.prompt}\n`;
        }

        if (capturedData.systemPrompt) {
            output += `System Prompt: ${capturedData.systemPrompt.substring(0, 50)}...\n`;
        }

        if (capturedData.functions && capturedData.functions.length > 0) {
            output += `Functions: ${capturedData.functions.join(', ')}\n`;
        }

        if (capturedData.exactPrompt) {
            output += `\n=== EXACT PROMPT ===\n`;
            output += capturedData.exactPrompt;
            output += `\n`;
        }

        if (capturedData.contextState) {
            output += `Token Count: ${capturedData.contextTokenCount || 'N/A'}\n`;

            output += `\n=== CONTEXT STATE ===\n`;
            output += capturedData.contextState;
            output += `\n`;
        }

        if (capturedData.structured) {
            output += `\n=== STRUCTURED ===\n`;
            output += `Token Count: ${capturedData.structuredTokenCount || 'N/A'}\n`;
            output += JSON.stringify(capturedData.structured, null, 2);
            output += `\n`;
        }

        output += `==========================================\n`;
        return output;
    }

    /**

     * Saves data to file

     * @param {Object} capturedData - Data to save

     * @param {null} customFilename - Optional custom filename

     */
    async saveToFile(capturedData, customFilename = null) {
        const content = this.formatOutput(capturedData);

        let filename = customFilename || this.filename;

        if (this.includeTimestamp) {
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const ext = path.extname(filename);
            const base = path.basename(filename, ext);
            filename = `${base}_${timestamp}${ext}`;
        }

        const filepath = path.join(this.outputDir, filename);

        if (this.appendMode) {
            await fs.appendFile(filepath, content, 'utf8');
        } else {
            await fs.writeFile(filepath, content, 'utf8');
        }

        console.log(`Prompt debug output written to ${filepath}`);
        return filepath;
    }

    /**

     * Debug exact prompt only - minimal params needed

     * @param {Object} params - session, prompt, systemPrompt (optional), functions (optional)

     * @param customFilename

     */
    async debugExactPrompt(params, customFilename = null) {
        const oldOutputTypes = this.outputTypes;
        this.outputTypes = [OutputTypes.EXACT_PROMPT];
        const capturedData = this.captureAll(params);
        const filepath = await this.saveToFile(capturedData, customFilename);
        this.outputTypes = oldOutputTypes;
        return { capturedData, filepath };
    }

    /**

     * Debug context state only - needs session and model

     * @param {Object} params - session, model

     * @param customFilename

     */
    async debugContextState(params, customFilename = null) {
        const oldOutputTypes = this.outputTypes;
        this.outputTypes = [OutputTypes.CONTEXT_STATE];
        const capturedData = this.captureAll(params);
        const filepath = await this.saveToFile(capturedData, customFilename);
        this.outputTypes = oldOutputTypes;
        return { capturedData, filepath };
    }

    /**

     * Debug structured only - needs session and model

     * @param {Object} params - session, model

     * @param customFilename

     */
    async debugStructured(params, customFilename = null) {
        const oldOutputTypes = this.outputTypes;
        this.outputTypes = [OutputTypes.STRUCTURED];
        const capturedData = this.captureAll(params);
        const filepath = await this.saveToFile(capturedData, customFilename);
        this.outputTypes = oldOutputTypes;
        return { capturedData, filepath };
    }

    /**

     * Debug with configured output types

     * @param {Object} params - All parameters (session, model, prompt, etc.)

     * @param customFilename

     */
    async debug(params, customFilename = null) {
        const capturedData = this.captureAll(params);
        //const filepath = await this.saveToFile(capturedData, customFilename);
        return { capturedData };
    }

    /**

     * Log to console only

     * @param {Object} params - Parameters based on configured output types

     */
    logToConsole(params) {
        const capturedData = this.captureAll(params);
        console.log(this.formatOutput(capturedData));
        return capturedData;
    }

    /**

     * Log exact prompt to console

     */
    logExactPrompt(params) {
        const capturedData = this.captureExactPrompt(params);
        console.log(this.formatOutput(capturedData));
        return capturedData;
    }

    /**

     * Log context state to console

     */
    logContextState(params) {
        const capturedData = this.captureContextState(params);
        console.log(this.formatOutput(capturedData));
        return capturedData;
    }

    /**

     * Log structured to console

     */
    logStructured(params) {
        const capturedData = this.captureStructured(params);
        console.log(this.formatOutput(capturedData));
        return capturedData;
    }
}

/**

 * Quick function to debug exact prompt only

 */
async function debugExactPrompt(params, options = {}) {
    const promptDebugger = new PromptDebugger({
        ...options,
        outputTypes: [OutputTypes.EXACT_PROMPT]
    });
    return await promptDebugger.debug(params);
}

/**

 * Quick function to debug context state only

 */
async function debugContextState(params, options = {}) {
    const promptDebugger = new PromptDebugger({
        ...options,
        outputTypes: [OutputTypes.CONTEXT_STATE]
    });
    return await promptDebugger.debug(params);
}

/**

 * Quick function to debug structured only

 */
async function debugStructured(params, options = {}) {
    const promptDebugger = new PromptDebugger({
        ...options,
        outputTypes: [OutputTypes.STRUCTURED]
    });
    return await promptDebugger.debug(params);
}

/**

 * Quick function to debug all outputs

 */
async function debugAll(params, options = {}) {
    const promptDebugger = new PromptDebugger({
        ...options,
        outputTypes: [OutputTypes.EXACT_PROMPT, OutputTypes.CONTEXT_STATE, OutputTypes.STRUCTURED]
    });
    return await promptDebugger.debug(params);
}