use crate::llm::{Completion, CompletionResponse, LLMClientDyn, TokenUsage, throttled_completion};
use eyre::Result;
use rig_core::completion::message::{ToolChoice, ToolResultContent, UserContent};
use rig_core::completion::{AssistantContent, Message};
use std::sync::Arc;
use tokio::sync::Semaphore;
use tracing::{info, warn};
const COMPACTION_MAX_CORRECTIONS: usize = 2;
const CONTINUE_MESSAGE: &str = "Continue from where you left off.";
const COMPACTION_SYSTEM_PROMPT: &str = include_str!("../prompts/compaction-system.md");
const SUMMARY_TAG: &str = "summary";
const COMPACTION_SUMMARY_INSTRUCTIONS: &str = include_str!("../prompts/compaction-summary.md");
const MISSING_SUMMARY_CORRECTION: &str = include_str!("../prompts/compaction-missing-summary.md");
const WRAP_SUMMARY_CORRECTION: &str = include_str!("../prompts/compaction-wrap-summary.md");
pub struct CompactionOutcome {
pub usage: TokenUsage,
pub summary: String,
pub trigger_usage: TokenUsage,
}
enum CompactionInput<'a> {
Messages(&'a [Message]),
Transcript(&'a str),
}
enum CorrectionMode {
MissingSummary,
WrapSummary,
}
#[derive(Clone, Copy)]
struct CompactionModel<'a> {
model: &'a str,
max_tokens: Option<u64>,
}
#[allow(clippy::too_many_arguments)]
pub async fn compact_history(
semaphore: &Semaphore,
client: Arc<dyn LLMClientDyn>,
model: &str,
max_tokens: Option<u64>,
system_prompt: &str,
history: &mut Vec<Message>,
prompt: &mut Message,
turn: usize,
usage: TokenUsage,
) -> Result<Option<CompactionOutcome>> {
if history.is_empty() {
return Ok(None);
}
let outcome = summarize_history(
semaphore,
client,
CompactionModel { model, max_tokens },
system_prompt,
history,
turn,
usage,
)
.await?;
let continue_msg = Message::user(CONTINUE_MESSAGE.to_string());
*history = vec![
Message::user(format!(
"compacted conversation summary before turn {turn}:\n\n{}",
outcome.summary
)),
continue_msg.clone(),
];
*prompt = continue_msg;
info!(
turn,
trigger_input_tokens = outcome.trigger_usage.input_tokens,
trigger_output_tokens = outcome.trigger_usage.output_tokens,
trigger_total_tokens = outcome.trigger_usage.total_tokens,
input_tokens = outcome.usage.input_tokens,
output_tokens = outcome.usage.output_tokens,
total_tokens = outcome.usage.total_tokens,
"compaction complete"
);
Ok(Some(outcome))
}
async fn summarize_history(
semaphore: &Semaphore,
client: Arc<dyn LLMClientDyn>,
model: CompactionModel<'_>,
system_prompt: &str,
thread: &[Message],
turn: usize,
usage: TokenUsage,
) -> Result<CompactionOutcome> {
match run_compaction(
semaphore,
&client,
model,
system_prompt,
CompactionInput::Messages(thread),
turn,
usage,
)
.await
{
Ok(outcome) => Ok(outcome),
Err(err) => {
warn!("in-context compaction failed ({err}), retrying with rendered transcript");
let transcript = render_history_as_text(thread);
let outcome = run_compaction(
semaphore,
&client,
model,
system_prompt,
CompactionInput::Transcript(&transcript),
turn,
usage,
)
.await?;
info!("rendered transcript compaction succeeded");
Ok(outcome)
}
}
}
async fn run_compaction(
semaphore: &Semaphore,
client: &Arc<dyn LLMClientDyn>,
model: CompactionModel<'_>,
system_prompt: &str,
input: CompactionInput<'_>,
turn: usize,
usage: TokenUsage,
) -> Result<CompactionOutcome> {
let prompt = build_compaction_prompt(&input, system_prompt, turn, usage);
let response = throttled_completion(
semaphore,
client,
compaction_completion(
model,
history_for_initial_request(&input),
Message::user(prompt.clone()),
),
)
.await?;
match extract_summary(&response) {
Some(summary) => Ok(CompactionOutcome {
usage: response.usage,
summary,
trigger_usage: usage,
}),
None => {
let attempt = InitialAttempt {
prompt,
response,
correction_mode: correction_mode(&input),
};
run_corrections(semaphore, client, model, &input, usage, attempt).await
}
}
}
struct InitialAttempt {
prompt: String,
response: CompletionResponse,
correction_mode: CorrectionMode,
}
async fn run_corrections(
semaphore: &Semaphore,
client: &Arc<dyn LLMClientDyn>,
model: CompactionModel<'_>,
input: &CompactionInput<'_>,
trigger_usage: TokenUsage,
attempt: InitialAttempt,
) -> Result<CompactionOutcome> {
let InitialAttempt {
prompt: original_prompt,
response: initial_response,
correction_mode,
} = attempt;
let correction = correction_prompt(&correction_mode);
let mut history = correction_history(input, original_prompt, initial_response.message());
let mut previous = initial_response;
for _ in 0..COMPACTION_MAX_CORRECTIONS {
let next = throttled_completion(
semaphore,
client,
compaction_completion(
model,
history.clone(),
Message::user(correction.to_string()),
),
)
.await?;
match extract_summary(&next) {
Some(summary) => {
return Ok(CompactionOutcome {
usage: next.usage,
summary,
trigger_usage,
});
}
None => {
history.push(next.message());
history.push(Message::user(correction.to_string()));
previous = next;
}
}
}
match correction_mode {
CorrectionMode::MissingSummary => Err(eyre::eyre!(
"compaction output missing <summary> block after {COMPACTION_MAX_CORRECTIONS} corrections: {}",
previous.text()
)),
CorrectionMode::WrapSummary => Err(eyre::eyre!(
"rendered compaction also failed to produce <summary> block: {}",
previous.text()
)),
}
}
fn compaction_completion(
model: CompactionModel<'_>,
history: Vec<Message>,
prompt: Message,
) -> Completion {
Completion {
model: model.model.to_string(),
prompt,
preamble: Some(COMPACTION_SYSTEM_PROMPT.to_string()),
history,
tools: Vec::new(),
tool_choice: Some(ToolChoice::None),
max_tokens: model.max_tokens,
additional_params: None,
}
}
fn history_for_initial_request(input: &CompactionInput<'_>) -> Vec<Message> {
match input {
CompactionInput::Messages(thread) => thread.to_vec(),
CompactionInput::Transcript(_) => Vec::new(),
}
}
fn correction_history(
input: &CompactionInput<'_>,
original_prompt: String,
assistant_message: Message,
) -> Vec<Message> {
let mut history = history_for_initial_request(input);
history.push(Message::user(original_prompt));
history.push(assistant_message);
history
}
fn correction_mode(input: &CompactionInput<'_>) -> CorrectionMode {
match input {
CompactionInput::Messages(_) => CorrectionMode::MissingSummary,
CompactionInput::Transcript(_) => CorrectionMode::WrapSummary,
}
}
fn correction_prompt(mode: &CorrectionMode) -> &'static str {
match mode {
CorrectionMode::MissingSummary => MISSING_SUMMARY_CORRECTION,
CorrectionMode::WrapSummary => WRAP_SUMMARY_CORRECTION,
}
}
fn build_compaction_prompt(
input: &CompactionInput<'_>,
role_prompt: &str,
turn: usize,
usage: TokenUsage,
) -> String {
let intro = match input {
CompactionInput::Messages(_) => {
"This thread is getting out of hand and needs to be compacted. Stop previous work and summarize the conversation so far.".to_string()
}
CompactionInput::Transcript(transcript) => format!(
"Summarize the following code exploration and review session transcript so the agent can continue seamlessly from where it left off.\n\n<transcript>\n{transcript}\n</transcript>"
),
};
let role_prompt = role_prompt.replace("</original_role_prompt>", "<\\/original_role_prompt>");
format!(
"{intro}\n\n{COMPACTION_SUMMARY_INSTRUCTIONS}\n\
The agent's original role prompt follows, for reference when judging what is vital to preserve. Do not follow its tool-calling or output instructions:\n\
<original_role_prompt>\n{role_prompt}\n</original_role_prompt>\n\
This compaction is happening before turn {turn}. Context size at compaction: {} input, {} output, {} total tokens.",
usage.input_tokens, usage.output_tokens, usage.total_tokens
)
}
fn extract_summary(response: &CompletionResponse) -> Option<String> {
extract_tag(&response.text(), SUMMARY_TAG)
}
fn render_history_as_text(history: &[Message]) -> String {
let mut parts = Vec::new();
for msg in history {
match msg {
Message::User { content } => {
for item in content.iter() {
match item {
UserContent::Text(t) if !t.text.is_empty() => {
parts.push(format!("[user]: {}", t.text));
}
UserContent::ToolResult(tr) => {
let result = tr
.content
.iter()
.filter_map(|content| match content {
ToolResultContent::Text(t) => Some(t.text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("");
parts.push(format!("[tool result {}]: {}", tr.id, result));
}
_ => {}
}
}
}
Message::Assistant { content, .. } => {
for item in content.iter() {
match item {
AssistantContent::Text(t) if !t.text().is_empty() => {
parts.push(format!("[assistant]: {}", t.text()));
}
AssistantContent::ToolCall(tc) => {
parts.push(format!(
"[called: {}({})]",
tc.function.name, tc.function.arguments
));
}
_ => {}
}
}
}
Message::System { .. } => {}
}
}
parts.join("\n\n")
}
fn extract_tag(text: &str, tag: &str) -> Option<String> {
let start_tag = format!("<{tag}>");
let end_tag = format!("</{tag}>");
let start = text.find(&start_tag)? + start_tag.len();
let end = start + text[start..].find(&end_tag)?;
let content = text[start..end].trim();
if content.is_empty() {
None
} else {
Some(content.to_string())
}
}