use rho_protocol::ContentBlock;
const INSTRUCTIONS: &str = "t3_code_instructions";
const REQUEST: &str = "user_request";
const TRAILING: [&str; 2] = ["runtime_info", "pull_request_linking"];
pub(super) fn split_context(mut prompt: Vec<ContentBlock>) -> Vec<ContentBlock> {
let is_text = |block: &ContentBlock| matches!(block, ContentBlock::Text { .. });
let (Some(first), Some(last)) = (
prompt.iter().position(is_text),
prompt.iter().rposition(is_text),
) else {
return prompt;
};
let trailing = text_mut(&mut prompt[last])
.map(take_trailing)
.unwrap_or_default();
let leading = text_mut(&mut prompt[first]).and_then(take_instructions);
if leading.is_none() && trailing.is_empty() {
return prompt;
}
let emptied = |index: usize, block: &ContentBlock| {
(index == first || index == last)
&& matches!(block, ContentBlock::Text { text } if text.is_empty())
};
let person = prompt
.into_iter()
.enumerate()
.filter(|(index, block)| !emptied(*index, block))
.map(|(_, block)| block);
leading
.into_iter()
.chain(trailing)
.map(|text| ContentBlock::Context { text })
.chain(person)
.collect()
}
fn text_mut(block: &mut ContentBlock) -> Option<&mut String> {
match block {
ContentBlock::Text { text } => Some(text),
_ => None,
}
}
fn take_trailing(text: &mut String) -> Vec<String> {
let mut taken = Vec::new();
for tag in TRAILING.iter().rev() {
let end = text.trim_end().len();
if let Some(start) = trailing_block(&text[..end], tag) {
taken.push(text[start..end].to_owned());
text.truncate(start);
}
}
if !taken.is_empty() {
text.truncate(text.trim_end().len());
}
taken.reverse();
taken
}
fn trailing_block(text: &str, tag: &str) -> Option<usize> {
let (open, close) = (format!("<{tag}>"), format!("</{tag}>"));
if !text.ends_with(&close) {
return None;
}
let mut opens = 0;
let start = text
.rmatch_indices(&open)
.map(|(start, _)| start)
.find(|&start| {
opens += 1;
text[start..].matches(&close).count() == opens
})?;
(start == 0 || text[..start].ends_with('\n')).then_some(start)
}
fn take_instructions(text: &mut String) -> Option<String> {
let open = format!("<{INSTRUCTIONS}>");
let close = format!("</{INSTRUCTIONS}>");
let end = open.len() + text.strip_prefix(&open)?.find(&close)? + close.len();
let instructions = text[..end].to_owned();
let rest = text[end..].trim_start();
*text = unwrap_request(rest).unwrap_or(rest).to_owned();
Some(instructions)
}
fn unwrap_request(text: &str) -> Option<&str> {
let inner = text
.trim_end()
.strip_prefix(&format!("<{REQUEST}>"))?
.strip_suffix(&format!("</{REQUEST}>"))?;
let inner = inner.strip_prefix('\n').unwrap_or(inner);
Some(inner.strip_suffix('\n').unwrap_or(inner))
}
#[cfg(test)]
#[path = "t3_prompt_tests.rs"]
mod tests;