*/ public function extractVariables(string $body): array { if (preg_match_all(self::VARIABLE_PATTERN, $body, $matches) === false) { return []; } return array_values(array_unique($matches[1])); } /** * Render the template with the given values. * * @param array $values * * @throws PromptRenderException when any variable has no string value * @throws RuntimeException when the template cannot be processed */ public function render(string $body, array $values): string { $missing = []; foreach ($this->extractVariables($body) as $variable) { if (! array_key_exists($variable, $values) || ! is_string($values[$variable])) { $missing[] = $variable; } } if ($missing !== []) { throw PromptRenderException::missing($missing); } $rendered = preg_replace_callback( self::VARIABLE_PATTERN, static fn (array $matches): string => (string) ($values[$matches[1]] ?? $matches[0]), $body ); if ($rendered === null) { throw new RuntimeException('Prompt template could not be rendered.'); } return $rendered; } }