* Extracts the curated (valid) history from a comprehensive history. * * @remarks * The model may sometimes generate invalid or empty contents(e.g., due to safety * filters or recitation). Extracting valid turns from the history * ensures that subsequent requests could be accepted by the model.
(comprehensiveHistory: Content[])
| 77 | * ensures that subsequent requests could be accepted by the model. |
| 78 | */ |
| 79 | function extractCuratedHistory(comprehensiveHistory: Content[]): Content[] { |
| 80 | if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { |
| 81 | return []; |
| 82 | } |
| 83 | const curatedHistory: Content[] = []; |
| 84 | const length = comprehensiveHistory.length; |
| 85 | let i = 0; |
| 86 | while (i < length) { |
| 87 | if (comprehensiveHistory[i].role === 'user') { |
| 88 | curatedHistory.push(comprehensiveHistory[i]); |
| 89 | i++; |
| 90 | } else { |
| 91 | const modelOutput: Content[] = []; |
| 92 | let isValid = true; |
| 93 | while (i < length && comprehensiveHistory[i].role === 'model') { |
| 94 | modelOutput.push(comprehensiveHistory[i]); |
| 95 | if (isValid && !isValidContent(comprehensiveHistory[i])) { |
| 96 | isValid = false; |
| 97 | } |
| 98 | i++; |
| 99 | } |
| 100 | if (isValid) { |
| 101 | curatedHistory.push(...modelOutput); |
| 102 | } else { |
| 103 | // Remove the last user input when model content is invalid. |
| 104 | curatedHistory.pop(); |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | return curatedHistory; |
| 109 | } |
| 110 | |
| 111 | /** |
| 112 | * Chat session that enables sending messages to the model with previous |
no test coverage detected