ragit_pdl/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
use lazy_static::lazy_static;
use ragit_fs::{extension, join, parent, read_bytes, read_string};
use regex::bytes::Regex;
mod error;
mod image;
mod message;
mod role;
mod schema;
mod util;
pub use error::Error;
pub use image::ImageType;
pub use message::{Message, MessageContent};
pub use role::{PdlRole, Role};
pub use schema::Schema;
use schema::parse_schema;
pub use util::{decode_base64, encode_base64};
lazy_static! {
static ref MEDIA_RE: Regex = Regex::new(r"^media\((.+)\)$").unwrap();
static ref RAW_MEDIA_RE: Regex = Regex::new(r"^raw_media\(([a-zA-Z0-9]+):([^:]+)\)$").unwrap();
}
#[derive(Clone, Debug)]
pub struct Pdl {
pub schema: Option<Schema>,
pub messages: Vec<Message>,
}
impl Pdl {
pub fn validate(&self) -> Result<(), Error> {
if self.messages.is_empty() {
return Err(Error::InvalidPdl(String::from("A pdl file is empty.")));
}
let mut after_user = false;
let mut after_assistant = false;
for (index, Message { role, .. }) in self.messages.iter().enumerate() {
match role {
Role::User => {
if after_user {
return Err(Error::InvalidPdl(String::from("<|user|> appeared twice in a row.")));
}
after_user = true;
after_assistant = false;
},
Role::Assistant => {
if after_assistant {
return Err(Error::InvalidPdl(String::from("<|assistant|> appeared twice in a row.")));
}
after_user = false;
after_assistant = true;
},
Role::System => {
if index != 0 {
return Err(Error::InvalidPdl(String::from("<|system|> must appear at top.")));
}
},
}
}
match self.messages.last() {
Some(Message { role: Role::Assistant, .. }) => {
return Err(Error::InvalidPdl(String::from("A pdl file ends with <|assistant|>.")));
},
_ => {},
}
Ok(())
}
}
pub fn parse_pdl_from_file(
path: &str,
context: &tera::Context,
// If it's not set, it would never return `Err`.
strict_mode: bool,
// If it's set, it unescapes characters in `s`.
is_escaped: bool,
) -> Result<Pdl, Error> {
parse_pdl(
&read_string(path)?,
context,
&parent(path)?,
strict_mode,
is_escaped,
)
}
pub fn parse_pdl(
s: &str,
context: &tera::Context,
curr_dir: &str,
// If it's not set, it would never return `Err`.
strict_mode: bool,
// If it's set, it unescapes characters in `s`.
is_escaped: bool,
) -> Result<Pdl, Error> {
let tera_rendered = match tera::Tera::one_off(s, context, true) {
Ok(t) => t,
Err(e) => if strict_mode {
return Err(Error::TeraError(e));
} else {
s.to_string()
},
};
let mut messages = vec![];
let mut schema = None;
let mut curr_role = None;
let mut line_buffer = vec![];
// simple hack: Adding this line to the content makes the code
// handle the last turn correctly. Since this fake turn is empty,
// it will be removed later.
let last_line = "<|assistant|>";
for line in tera_rendered.lines().chain(std::iter::once(last_line)) {
let trimmed = line.trim();
// maybe a turn-separator
if trimmed.starts_with("<|") && trimmed.ends_with("|>") && trimmed.len() > 4 {
match trimmed.to_ascii_lowercase().get(2..(trimmed.len() - 2)).unwrap() {
t @ ("user" | "system" | "assistant" | "schema") => {
if !line_buffer.is_empty() || curr_role.is_some() {
match curr_role {
Some(PdlRole::Schema) => match parse_schema(line_buffer.join("\n").as_bytes()) {
Ok(s) => {
if schema.is_some() && strict_mode {
return Err(Error::InvalidPdl(String::from("<|schema|> appeared multiple times.")));
}
schema = Some(s);
},
Err(e) => {
if strict_mode {
return Err(e.into());
}
},
},
_ => {
// there must be lots of unnecessary newlines due to the nature of the format
// let's just trim them away
let raw_contents = line_buffer.join("\n");
let raw_contents = raw_contents.trim();
let role = match curr_role {
Some(role) => role,
None => {
if raw_contents.is_empty() {
curr_role = Some(PdlRole::from(t));
line_buffer = vec![];
continue;
}
if strict_mode {
return Err(Error::RoleMissing);
}
PdlRole::System
},
};
match into_message_contents(&raw_contents, is_escaped, curr_dir) {
Ok(t) => {
messages.push(Message {
role: role.into(),
content: t,
});
},
Err(e) => {
if strict_mode {
return Err(e);
}
else {
messages.push(Message {
role: role.into(),
content: vec![MessageContent::String(raw_contents.to_string())],
});
}
},
}
},
}
}
curr_role = Some(PdlRole::from(t));
line_buffer = vec![];
continue;
},
t => {
if strict_mode && t.chars().all(|c| c.is_ascii_alphabetic()) {
return Err(Error::InvalidTurnSeparator(t.to_string()));
}
line_buffer.push(line.to_string());
},
}
}
else {
line_buffer.push(line.to_string());
}
}
if let Some(Message { content, .. }) = messages.last() {
if content.is_empty() {
messages.pop().unwrap();
}
}
let result = Pdl {
schema,
messages,
};
if strict_mode {
result.validate()?;
}
Ok(result)
}
pub fn escape_pdl_tokens(s: &str) -> String { // TODO: use `Cow` type
s.replace("&", "&").replace("<|", "<|")
}
pub fn unescape_pdl_tokens(s: &str) -> String { // TODO: use `Cow` type
s.replace("<", "<").replace("&", "&")
}
fn into_message_contents(s: &str, is_escaped: bool, curr_dir: &str) -> Result<Vec<MessageContent>, Error> {
let bytes = s.as_bytes().iter().map(|b| *b).collect::<Vec<_>>();
let mut index = 0;
let mut result = vec![];
let mut string_buffer = vec![];
loop {
match bytes.get(index) {
Some(b'<') => match try_parse_inline_block(&bytes, index, curr_dir) {
Ok(Some((image_type, bytes, new_index))) => {
if !string_buffer.is_empty() {
match String::from_utf8(string_buffer.clone()) {
Ok(s) => {
if is_escaped {
result.push(MessageContent::String(unescape_pdl_tokens(&s)));
}
else {
result.push(MessageContent::String(s));
}
},
Err(e) => {
return Err(e.into());
},
}
}
result.push(MessageContent::Image { image_type, bytes });
index = new_index;
string_buffer = vec![];
continue;
},
Ok(None) => {
string_buffer.push(b'<');
},
Err(e) => {
return Err(e);
},
},
Some(b) => {
string_buffer.push(*b);
},
None => {
if !string_buffer.is_empty() {
match String::from_utf8(string_buffer) {
Ok(s) => {
if is_escaped {
result.push(MessageContent::String(unescape_pdl_tokens(&s)));
}
else {
result.push(MessageContent::String(s));
}
},
Err(e) => {
return Err(e.into());
},
}
}
break;
},
}
index += 1;
}
Ok(result)
}
// 1. It returns `Ok(Some(_))` if it's a valid inline block.
// 2. It returns `Ok(None)` if it's not an inline block.
// 3. It returns `Err(_)` if it's an inline block, but there's an error (syntax error, image type error, file error, ...).
fn try_parse_inline_block(bytes: &[u8], index: usize, curr_dir: &str) -> Result<Option<(ImageType, Vec<u8>, usize)>, Error> {
match try_get_pdl_token(bytes, index) {
Some((token, new_index)) => {
let media_re = &MEDIA_RE;
let raw_media_re = &RAW_MEDIA_RE;
if let Some(cap) = raw_media_re.captures(token) {
let image_type = String::from_utf8_lossy(&cap[1]).to_string();
let image_bytes = String::from_utf8_lossy(&cap[2]).to_string();
Ok(Some((ImageType::from_extension(&image_type)?, decode_base64(&image_bytes)?, new_index)))
}
else if let Some(cap) = media_re.captures(token) {
let path = &cap[1];
let file = join(curr_dir, &String::from_utf8_lossy(path).to_string())?;
// TODO: handle pdf files
Ok(Some((ImageType::from_extension(&extension(&file)?.unwrap_or(String::new()))?, read_bytes(&file)?, new_index)))
}
else {
Err(Error::InvalidInlineBlock)
}
},
// not an inline block at all
None => Ok(None),
}
}
fn try_get_pdl_token(bytes: &[u8], mut index: usize) -> Option<(&[u8], usize)> {
let old_index = index;
match (bytes.get(index), bytes.get(index + 1)) {
(Some(b'<'), Some(b'|')) => {
index += 2;
loop {
match (bytes.get(index), bytes.get(index + 1)) {
(Some(b'|'), Some(b'>')) => {
return Some((&bytes[(old_index + 2)..index], index + 2));
},
(_, Some(b'|')) => {
index += 1;
},
(_, None) => {
return None;
},
_ => {
index += 2;
},
}
}
},
_ => None,
}
}
#[cfg(test)]
mod tests {
use crate::{
ImageType,
Message,
MessageContent,
Pdl,
Role,
decode_base64,
parse_pdl,
parse_pdl_from_file,
};
use ragit_fs::{WriteMode, write_string};
// more thorough test suites are in `tests/`
#[test]
fn messages_from_file_test() {
write_string(
"/tmp/test_messages.tera",
"
<|system|>
You're a code helper.
<|user|>
Write me a sudoku-solver.
",
WriteMode::CreateOrTruncate,
).unwrap();
let Pdl { messages, schema } = parse_pdl_from_file(
"/tmp/test_messages.tera",
&tera::Context::new(),
true,
true,
).unwrap();
assert_eq!(
messages,
vec![
Message {
role: Role::System,
content: vec![
MessageContent::String(String::from("You're a code helper.")),
],
},
Message {
role: Role::User,
content: vec![
MessageContent::String(String::from("Write me a sudoku-solver.")),
],
},
],
);
assert_eq!(
schema,
None,
);
}
#[test]
fn media_content_test() {
let Pdl { messages, schema } = parse_pdl(
"
<|user|>
<|raw_media(png:HiMyNameIsBaehyunsol)|>
",
&tera::Context::new(),
".", // there's no `<|media|>`
true,
true,
).unwrap();
assert_eq!(
messages,
vec![
Message {
role: Role::User,
content: vec![
MessageContent::Image {
image_type: ImageType::Png,
bytes: decode_base64("HiMyNameIsBaehyunsol").unwrap(),
},
],
},
],
);
assert_eq!(
schema,
None,
);
}
}