feat(core): pop_last_user helper on conversation history
used by llm fallback to roll back the user turn when the api call fails, so the next attempt does not leave a dangling user message in the history.
This commit is contained in:
parent
1e2c883e68
commit
176f405310
1 changed files with 23 additions and 0 deletions
|
|
@ -50,6 +50,14 @@ impl ConversationHistory {
|
|||
self.turns.clear();
|
||||
}
|
||||
|
||||
pub fn pop_last_user(&mut self) -> Option<ChatMessage> {
|
||||
if matches!(self.turns.last(), Some(m) if m.role == "user") {
|
||||
self.turns.pop()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate(&mut self) {
|
||||
if self.turns.len() > self.max_turns {
|
||||
let drop = self.turns.len() - self.max_turns;
|
||||
|
|
@ -102,6 +110,21 @@ mod tests {
|
|||
assert_eq!(snap[1].content, "b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pop_last_user_only_pops_a_trailing_user_turn() {
|
||||
let mut h = ConversationHistory::new("sys", 4);
|
||||
h.push_user("u1");
|
||||
h.push_assistant("a1");
|
||||
assert!(h.pop_last_user().is_none());
|
||||
h.push_user("u2");
|
||||
let popped = h.pop_last_user().expect("trailing user turn should pop");
|
||||
assert_eq!(popped.role, "user");
|
||||
assert_eq!(popped.content, "u2");
|
||||
let snap = h.snapshot();
|
||||
assert_eq!(snap.len(), 1 + 2);
|
||||
assert_eq!(snap[2].content, "a1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_removes_turns_but_not_system() {
|
||||
let mut h = ConversationHistory::new("sys", 4);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue