headless_lms_chatbot/
content_cleaner.rs

1use crate::azure_chatbot::{LLMRequest, LLMRequestParams, NonThinkingParams};
2use crate::llm_utils::{
3    APIMessage, APIMessageKind, APIMessageText, estimate_tokens, make_blocking_llm_request,
4};
5use crate::prelude::*;
6use anyhow::Error;
7use headless_lms_models::chatbot_conversation_messages::MessageRole;
8use headless_lms_utils::document_schema_processor::GutenbergBlock;
9use serde_json::Value;
10use tracing::{debug, error, info, instrument, warn};
11
12/// Maximum context window size for LLM in tokens
13pub const MAX_CONTEXT_WINDOW: i32 = 16000;
14/// Maximum percentage of context window to use in a single request
15pub const MAX_CONTEXT_UTILIZATION: f32 = 0.75;
16/// Temperature for requests, low for deterministic results
17pub const REQUEST_TEMPERATURE: f32 = 0.1;
18
19/// JSON markers for LLM prompt
20const JSON_BEGIN_MARKER: &str = "---BEGIN COURSE MATERIAL JSON---";
21const JSON_END_MARKER: &str = "---END COURSE MATERIAL JSON---";
22
23/// System prompt for converting course material to markdown
24const SYSTEM_PROMPT: &str = r#"You are given course material in an abstract JSON format from a headless CMS. Convert this into clean, semantic Markdown that includes all user-visible content to support full-text search.
25
26* Extract and include all meaningful text content: paragraphs, headings, list items, image captions, and similar.
27* Retain any inline formatting (like bold or italic text), converting HTML tags (`<strong>`, `<em>`, etc.) into equivalent Markdown formatting.
28* For images, use the standard Markdown format: `![caption](url)`, including a caption if available.
29* Preserve heading levels (e.g., level 2 → `##`, level 3 → `###`).
30* Include text content from any block type, even non-standard ones, if it appears user-visible.
31* For exercise blocks, include the exercise name, and assignment instructions. You may also include text from the exercise specification (public spec), if it can be formatted into markdown.
32* If you encounter blocks that don't have any visible text in the JSON but are likely still user-visible (placeholder blocks) — e.g. `glossary`, `exercises-in-this-chapter`, `course-progress` — generate a fake heading representing the expected content (e.g. `## Glossary`).
33* Do not generate headings for placeholder blocks that are not user-visible — e.g. `conditionally-visible-content`, `spacer`, `divider`.
34* Exclude all purely stylistic attributes (e.g. colors, alignment, font sizes).
35* Do not include any metadata, HTML tags (other than for formatting), or non-visible fields.
36* Output **only the Markdown content**, and nothing else.
37"#;
38
39/// User prompt for converting course material to markdown
40const USER_PROMPT_START: &str =
41    "Convert this JSON content to clean markdown. Output only the markdown, nothing else.";
42
43/// Cleans content by converting the material blocks to clean markdown using an LLM
44#[instrument(skip(blocks, app_config), fields(num_blocks = blocks.len()))]
45pub async fn convert_material_blocks_to_markdown_with_llm(
46    blocks: &[GutenbergBlock],
47    app_config: &ApplicationConfiguration,
48) -> anyhow::Result<String> {
49    debug!("Starting content conversion with {} blocks", blocks.len());
50    let system_message = APIMessage {
51        role: MessageRole::System,
52        fields: APIMessageKind::Text(APIMessageText {
53            content: SYSTEM_PROMPT.to_string(),
54        }),
55    };
56
57    let system_message_tokens = estimate_tokens(SYSTEM_PROMPT);
58    let safe_token_limit = calculate_safe_token_limit(MAX_CONTEXT_WINDOW, MAX_CONTEXT_UTILIZATION);
59    let max_content_tokens = (safe_token_limit - system_message_tokens).max(1);
60
61    debug!(
62        "Token limits - system: {}, safe: {}, max content: {}",
63        system_message_tokens, safe_token_limit, max_content_tokens
64    );
65
66    let chunks = split_blocks_into_chunks(blocks, max_content_tokens)?;
67    debug!("Split content into {} chunks", chunks.len());
68    process_chunks(&chunks, &system_message, app_config).await
69}
70
71/// Calculate the safe token limit based on context window and utilization
72pub fn calculate_safe_token_limit(context_window: i32, utilization: f32) -> i32 {
73    (context_window as f32 * utilization) as i32
74}
75
76/// Recursively removes all fields named "private_spec" from a JSON value
77fn remove_private_spec_recursive(value: &mut Value) {
78    match value {
79        Value::Object(map) => {
80            map.remove("private_spec");
81            for (_, v) in map.iter_mut() {
82                remove_private_spec_recursive(v);
83            }
84        }
85        Value::Array(arr) => {
86            for item in arr.iter_mut() {
87                remove_private_spec_recursive(item);
88            }
89        }
90        _ => {}
91    }
92}
93
94/// Converts a block to JSON string, removing any private_spec fields recursively
95fn block_to_json_string(block: &GutenbergBlock) -> anyhow::Result<String> {
96    let mut json_value = serde_json::to_value(block)?;
97    remove_private_spec_recursive(&mut json_value);
98    Ok(serde_json::to_string(&json_value)?)
99}
100
101/// Converts a vector of blocks to JSON string, removing any private_spec fields recursively
102fn blocks_to_json_string(blocks: &[GutenbergBlock]) -> anyhow::Result<String> {
103    let mut json_value = serde_json::to_value(blocks)?;
104    remove_private_spec_recursive(&mut json_value);
105    Ok(serde_json::to_string(&json_value)?)
106}
107
108/// Split blocks into chunks that fit within token limits
109#[instrument(skip(blocks), fields(max_content_tokens))]
110pub fn split_blocks_into_chunks(
111    blocks: &[GutenbergBlock],
112    max_content_tokens: i32,
113) -> anyhow::Result<Vec<String>> {
114    debug!("Starting to split {} blocks into chunks", blocks.len());
115    let mut chunks: Vec<String> = Vec::new();
116    let mut current_chunk: Vec<GutenbergBlock> = Vec::new();
117    let mut current_chunk_tokens = 0;
118
119    for block in blocks {
120        let block_json = block_to_json_string(block)?;
121        let block_tokens = estimate_tokens(&block_json);
122        debug!(
123            "Processing block {} with {} tokens",
124            block.client_id, block_tokens
125        );
126
127        // If this block alone exceeds the limit, split it into smaller chunks
128        if block_tokens > max_content_tokens {
129            warn!(
130                "Block {} exceeds max token limit ({} > {})",
131                block.client_id, block_tokens, max_content_tokens
132            );
133            // Add any accumulated blocks as a chunk
134            if !current_chunk.is_empty() {
135                chunks.push(blocks_to_json_string(&current_chunk)?);
136                current_chunk = Vec::new();
137                current_chunk_tokens = 0;
138            }
139
140            // Then we do some crude splitting for the oversized block
141            split_oversized_block(&block_json, max_content_tokens, &mut chunks)?;
142            continue;
143        }
144
145        if current_chunk_tokens + block_tokens > max_content_tokens {
146            debug!(
147                "Creating new chunk after {} blocks ({} tokens)",
148                current_chunk.len(),
149                current_chunk_tokens
150            );
151            chunks.push(blocks_to_json_string(&current_chunk)?);
152            current_chunk = Vec::new();
153            current_chunk_tokens = 0;
154        }
155
156        current_chunk.push(block.clone());
157        current_chunk_tokens += block_tokens;
158    }
159
160    if !current_chunk.is_empty() {
161        debug!(
162            "Adding final chunk with {} blocks ({} tokens)",
163            current_chunk.len(),
164            current_chunk_tokens
165        );
166        chunks.push(blocks_to_json_string(&current_chunk)?);
167    }
168
169    Ok(chunks)
170}
171
172/// Splits an oversized block into smaller string chunks
173#[instrument(skip(block_json, chunks), fields(max_tokens))]
174fn split_oversized_block(
175    block_json: &str,
176    max_tokens: i32,
177    chunks: &mut Vec<String>,
178) -> anyhow::Result<()> {
179    let total_tokens = estimate_tokens(block_json);
180    debug!(
181        "Splitting oversized block with {} tokens into chunks of max {} tokens",
182        total_tokens, max_tokens
183    );
184
185    // Make a very conservative estimate of the number of chunks we need
186    // Ensure max_tokens is at least 1 to avoid division by zero
187    let max_tokens_safe = max_tokens.max(1);
188    let num_chunks = (total_tokens as f32 / (max_tokens_safe as f32 * 0.5)).ceil() as usize;
189
190    if num_chunks <= 1 || num_chunks == 0 {
191        chunks.push(block_json.to_string());
192        return Ok(());
193    }
194
195    // Split by byte length (not character count) for efficiency,
196    // but ensure we only slice at UTF-8 character boundaries
197    let bytes_per_chunk = (block_json.len() / num_chunks).max(1);
198    debug!(
199        "Splitting into {} chunks of approximately {} bytes each",
200        num_chunks, bytes_per_chunk
201    );
202
203    let mut start = 0;
204    let mut iterations = 0;
205    const MAX_ITERATIONS: usize = 100;
206    while start < block_json.len() {
207        iterations += 1;
208        if iterations > MAX_ITERATIONS {
209            return Err(anyhow::anyhow!(
210                "Infinite loop protection: exceeded {} iterations in split_oversized_block",
211                MAX_ITERATIONS
212            ));
213        }
214
215        // Use checked arithmetic to prevent overflow
216        let end_candidate = start
217            .checked_add(bytes_per_chunk)
218            .unwrap_or(block_json.len())
219            .min(block_json.len());
220
221        let mut end = if end_candidate >= block_json.len() {
222            block_json.len()
223        } else {
224            end_candidate
225        };
226
227        // Adjust end backwards to the nearest UTF-8 character boundary
228        while !block_json.is_char_boundary(end) && end > start {
229            end -= 1;
230        }
231
232        // If backtracking resulted in end == start, advance forward to next boundary
233        if end == start {
234            // Find the next character boundary after start
235            let mut next_boundary = start
236                .checked_add(1)
237                .unwrap_or(block_json.len())
238                .min(block_json.len());
239
240            let mut boundary_iterations = 0;
241            const MAX_BOUNDARY_ITERATIONS: usize = 100;
242            while next_boundary < block_json.len() && !block_json.is_char_boundary(next_boundary) {
243                boundary_iterations += 1;
244                if boundary_iterations > MAX_BOUNDARY_ITERATIONS {
245                    return Err(anyhow::anyhow!(
246                        "Infinite loop protection: exceeded {} iterations finding character boundary",
247                        MAX_BOUNDARY_ITERATIONS
248                    ));
249                }
250                next_boundary = next_boundary
251                    .checked_add(1)
252                    .unwrap_or(block_json.len())
253                    .min(block_json.len());
254            }
255            end = next_boundary.min(block_json.len());
256        }
257
258        // Ensure we have a non-empty slice and valid bounds
259        if end > start && end <= block_json.len() && start < block_json.len() {
260            // Double-check bounds before slicing
261            let chunk = block_json.get(start..end).ok_or_else(|| {
262                anyhow::anyhow!("Invalid string slice bounds: {}..{}", start, end)
263            })?;
264            chunks.push(chunk.to_string());
265            let new_start = end;
266            // Safety check: ensure start always advances
267            if new_start <= start {
268                return Err(anyhow::anyhow!(
269                    "Infinite loop protection: start did not advance ({} -> {})",
270                    start,
271                    new_start
272                ));
273            }
274            start = new_start;
275        } else {
276            // Safety: if we can't make progress, break to avoid infinite loop
277            // Push remaining content if any
278            if start < block_json.len()
279                && let Some(remaining) = block_json.get(start..)
280                && !remaining.is_empty()
281            {
282                chunks.push(remaining.to_string());
283            }
284            break;
285        }
286    }
287
288    Ok(())
289}
290
291/// Appends markdown content to a result string with proper newline separators
292pub fn append_markdown_with_separator(result: &mut String, new_content: &str) {
293    if !result.is_empty() && !result.ends_with("\n\n") {
294        if result.ends_with('\n') {
295            result.push('\n');
296        } else {
297            result.push_str("\n\n");
298        }
299    }
300
301    result.push_str(new_content);
302}
303
304/// Process all chunks and combine the results
305#[instrument(skip(chunks, system_message, app_config), fields(num_chunks = chunks.len()))]
306async fn process_chunks(
307    chunks: &[String],
308    system_message: &APIMessage,
309    app_config: &ApplicationConfiguration,
310) -> anyhow::Result<String> {
311    debug!("Processing {} chunks", chunks.len());
312    let mut result = String::new();
313
314    for (i, chunk) in chunks.iter().enumerate() {
315        debug!("Processing chunk {}/{}", i + 1, chunks.len());
316        let chunk_markdown = process_block_chunk(chunk, system_message, app_config).await?;
317        append_markdown_with_separator(&mut result, &chunk_markdown);
318    }
319
320    info!("Successfully cleaned content with LLM");
321    Ok(result)
322}
323
324/// Process a subset of blocks in a single LLM request
325#[instrument(skip(chunk, system_message, app_config), fields(chunk_tokens = estimate_tokens(chunk)))]
326async fn process_block_chunk(
327    chunk: &str,
328    system_message: &APIMessage,
329    app_config: &ApplicationConfiguration,
330) -> anyhow::Result<String> {
331    let messages = prepare_llm_messages(chunk, system_message)?;
332    let llm_base_request: LLMRequest = LLMRequest {
333        messages,
334        data_sources: vec![],
335        params: LLMRequestParams::NonThinking(NonThinkingParams {
336            temperature: Some(REQUEST_TEMPERATURE),
337            top_p: None,
338            frequency_penalty: None,
339            presence_penalty: None,
340            max_tokens: None,
341        }),
342        stop: None,
343    };
344    info!(
345        "Processing chunk of approximately {} tokens",
346        estimate_tokens(chunk)
347    );
348
349    let completion = match make_blocking_llm_request(llm_base_request, app_config).await {
350        Ok(completion) => completion,
351        Err(e) => {
352            error!("Failed to process chunk: {}", e);
353            return Err(e);
354        }
355    };
356
357    match &completion
358        .choices
359        .first()
360        .ok_or_else(|| {
361            error!("No content returned from LLM");
362            anyhow::anyhow!("No content returned from LLM")
363        })?
364        .message
365        .fields
366    {
367        APIMessageKind::Text(msg) => Ok(msg.content.clone()),
368        _ => Err(Error::msg(
369            "Didn't receive a text LLM response in content cleaner, this shouldn't happen!",
370        )),
371    }
372}
373
374/// Prepare messages for the LLM request
375pub fn prepare_llm_messages(
376    chunk: &str,
377    system_message: &APIMessage,
378) -> anyhow::Result<Vec<APIMessage>> {
379    let messages = vec![
380        system_message.clone(),
381        APIMessage {
382            role: MessageRole::User,
383            fields: APIMessageKind::Text(APIMessageText {
384                content: format!(
385                    "{}\n\n{}{}\n{}",
386                    USER_PROMPT_START, JSON_BEGIN_MARKER, chunk, JSON_END_MARKER
387                ),
388            }),
389        },
390    ];
391
392    Ok(messages)
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use crate::llm_utils::{APIMessageKind, APIMessageText};
399    use serde_json::json;
400
401    const TEST_BLOCK_NAME: &str = "test/block";
402
403    #[test]
404    fn test_calculate_safe_token_limit() {
405        assert_eq!(calculate_safe_token_limit(1000, 0.75), 750);
406        assert_eq!(calculate_safe_token_limit(16000, 0.75), 12000);
407        assert_eq!(calculate_safe_token_limit(8000, 0.5), 4000);
408    }
409
410    #[test]
411    fn test_append_markdown_with_separator() {
412        let mut result = String::new();
413        append_markdown_with_separator(&mut result, "New content");
414        assert_eq!(result, "New content");
415
416        let mut result = String::from("Existing content");
417        append_markdown_with_separator(&mut result, "New content");
418        assert_eq!(result, "Existing content\n\nNew content");
419
420        let mut result = String::from("Existing content\n");
421        append_markdown_with_separator(&mut result, "New content");
422        assert_eq!(result, "Existing content\n\nNew content");
423
424        let mut result = String::from("Existing content\n\n");
425        append_markdown_with_separator(&mut result, "New content");
426        assert_eq!(result, "Existing content\n\nNew content");
427    }
428
429    #[test]
430    fn test_split_blocks_into_chunks() -> anyhow::Result<()> {
431        // Use content strings of different lengths to influence token estimation
432        let block1 = create_test_block("a "); // short
433        let block2 = create_test_block("b b b b b b b b b b b b b b b b b b b b "); // longer
434        let block3 = create_test_block("c c c c c c c c c c c c c c c "); // medium
435
436        let blocks = vec![block1.clone(), block2.clone(), block3.clone()];
437
438        // Estimate tokens for each block
439        let t1 = estimate_tokens(&block_to_json_string(&block1)?);
440        let t2 = estimate_tokens(&block_to_json_string(&block2)?);
441        let t3 = estimate_tokens(&block_to_json_string(&block3)?);
442
443        // Test with a limit that fits all blocks
444        let chunks = split_blocks_into_chunks(&blocks, t1 + t2 + t3 + 10)?;
445        assert_eq!(chunks.len(), 1);
446
447        let deserialized_chunk: Vec<GutenbergBlock> = serde_json::from_str(&chunks[0])?;
448        assert_eq!(deserialized_chunk.len(), 3);
449
450        // Test with a limit that requires splitting after the first block
451        let chunks = split_blocks_into_chunks(&blocks, t1 + 1)?;
452
453        // First chunk should be a valid JSON array with one block
454        let first_chunk: Vec<GutenbergBlock> = serde_json::from_str(&chunks[0])?;
455        assert_eq!(first_chunk.len(), 1);
456        assert_eq!(first_chunk[0].client_id, block1.client_id);
457
458        // Remaining chunks might be split JSON strings, so we can't deserialize them
459        // Just verify they're not empty
460        for chunk in &chunks[1..] {
461            assert!(!chunk.is_empty());
462        }
463
464        Ok(())
465    }
466
467    #[test]
468    fn test_prepare_llm_messages() -> anyhow::Result<()> {
469        let blocks = vec![create_test_block("Test content")];
470        let blocks_json = blocks_to_json_string(&blocks)?;
471        let system_message = APIMessage {
472            role: MessageRole::System,
473            fields: APIMessageKind::Text(APIMessageText {
474                content: "System prompt".to_string(),
475            }),
476        };
477
478        let messages = prepare_llm_messages(&blocks_json, &system_message)?;
479
480        assert_eq!(messages.len(), 2);
481        let msg1_content = match &messages[0].fields {
482            APIMessageKind::Text(msg) => &msg.content,
483            _ => "",
484        };
485        let msg2_content = match &messages[1].fields {
486            APIMessageKind::Text(msg) => &msg.content,
487            _ => "",
488        };
489        assert_eq!(messages[0].role, MessageRole::System);
490        assert_eq!(msg1_content, "System prompt");
491        assert_eq!(messages[1].role, MessageRole::User);
492        assert!(msg2_content.contains(JSON_BEGIN_MARKER));
493        assert!(msg2_content.contains("Test content"));
494
495        Ok(())
496    }
497
498    fn create_test_block(content: &str) -> GutenbergBlock {
499        let client_id = uuid::Uuid::new_v4();
500        GutenbergBlock {
501            client_id,
502            name: TEST_BLOCK_NAME.to_string(),
503            is_valid: true,
504            attributes: {
505                let mut map = serde_json::Map::new();
506                map.insert("content".to_string(), json!(content));
507                map
508            },
509            inner_blocks: vec![],
510        }
511    }
512}