examples = $examples; $this->examplePrompt = $example_prompt; $this->getTextLength = $getTextLength ?? [$this, 'getLengthBased']; $this->maxLength = $max_length; $this->exampleTextLengths = $this->calculateExampleTextLengths(); } public function addExample(array $example): void { $this->examples[] = $example; $string_example = $this->examplePrompt->format($example); $this->exampleTextLengths[] = call_user_func($this->getTextLength, $string_example); } private function calculateExampleTextLengths(): array { $string_examples = array_map(function ($eg) { return $this->examplePrompt->format($eg); }, $this->examples); return array_map($this->getTextLength, $string_examples); } public function selectExamples(array $input_variables): array { $inputs = implode(' ', array_values($input_variables)); $remaining_length = $this->maxLength - call_user_func($this->getTextLength, $inputs); $i = 0; $examples = []; while ($remaining_length > 0 && $i < count($this->examples)) { $new_length = $remaining_length - $this->exampleTextLengths[$i]; if ($new_length < 0) { break; } else { $examples[] = $this->examples[$i]; $remaining_length = $new_length; } $i++; } return $examples; } private function getLengthBased(string $text): int { return count(preg_split('/\n|\s/', $text)); } }