Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: auto limit string if truncate is set #428

Merged
merged 1 commit into from
Oct 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions core/src/tokenization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ fn prepare_pre_prompt(

#[allow(clippy::too_many_arguments)]
fn tokenize_input(
inputs: EncodingInput,
mut inputs: EncodingInput,
add_special_tokens: bool,
max_input_length: usize,
truncate_params: Option<TruncationParams>,
Expand All @@ -288,9 +288,12 @@ fn tokenize_input(
let input_chars = inputs.count_chars();
let limit = max_input_length * MAX_CHAR_MULTIPLIER;
if input_chars > limit {
return Err(TextEmbeddingsError::Validation(format!(
"`inputs` must have less than {limit} characters. Given: {input_chars}"
)));
if truncate_params.is_none() {
return Err(TextEmbeddingsError::Validation(format!(
"`inputs` must have less than {limit} characters. Given: {input_chars}"
)));
}
inputs.apply_limit(limit);
}

let encoding = match inputs {
Expand Down Expand Up @@ -426,6 +429,25 @@ impl EncodingInput {
EncodingInput::Ids(v) => v.len(),
}
}

fn apply_limit(&mut self, limit: usize) {
let truncate_string = |s: &mut String, limit: usize| {
if s.is_char_boundary(limit) {
s.truncate(limit)
}
};

match self {
EncodingInput::Single(s) => {
truncate_string(s, limit);
}
EncodingInput::Dual(s1, s2) => {
truncate_string(s1, limit / 2);
truncate_string(s2, limit / 2);
}
EncodingInput::Ids(_) => {}
}
}
}

impl From<String> for EncodingInput {
Expand Down
Loading