Repository navigation
Expand file tree
/
Copy pathPromptTemplate.php
More file actions
124 lines (107 loc) · 2.98 KB
/
Copy pathPromptTemplate.php
File metadata and controls
124 lines (107 loc) · 2.98 KB
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
<?php
declare(strict_types=1);
namespace ClaudeAgents\Prompts;
use ClaudeAgents\Exceptions\ValidationException;
/**
* Template for prompt generation with variable substitution.
*/
class PromptTemplate
{
/**
* @var array<string> Variable names in the template
*/
private array $variables = [];
/**
* @param string $template The template string with {variable} placeholders
*/
public function __construct(
private readonly string $template,
) {
$this->extractVariables();
}
/**
* Create a new template.
*/
public static function create(string $template): self
{
return new self($template);
}
/**
* Format the template with values.
*
* @param array<string, mixed> $values Map of variable names to values
* @return string Formatted prompt
*/
public function format(array $values): string
{
$prompt = $this->template;
foreach ($values as $key => $value) {
$placeholder = '{' . $key . '}';
$prompt = str_replace($placeholder, (string) $value, $prompt);
}
return $prompt;
}
/**
* Get required variables.
*
* @return array<string>
*/
public function getVariables(): array
{
return $this->variables;
}
/**
* Validate that all variables are provided.
*
* @param array<string, mixed> $values
* @throws ValidationException If required variables missing
*/
public function validate(array $values): void
{
$missing = [];
foreach ($this->variables as $var) {
if (! isset($values[$var])) {
$missing[] = $var;
}
}
if (! empty($missing)) {
$available = array_keys($values);
throw new ValidationException(
sprintf(
'Missing required variable(s): %s. Available variables: %s. ' .
"Please provide all required variables in the format: ['%s' => 'value']",
implode(', ', $missing),
empty($available) ? '(none)' : implode(', ', $available),
implode("' => 'value', '", $missing)
)
);
}
}
/**
* Extract variable names from template.
*/
private function extractVariables(): void
{
if (preg_match_all('/\{(\w+)\}/', $this->template, $matches)) {
$this->variables = array_unique($matches[1]);
}
}
/**
* Get the template string.
*/
public function getTemplate(): string
{
return $this->template;
}
/**
* Create a partial template with some variables filled in.
*
* @param array<string, mixed> $values Partial values
* @return PromptTemplate New template with substitutions
*/
public function partial(array $values): self
{
$newTemplate = $this->format($values);
return new self($newTemplate);
}
}