Repository navigation
Expand file tree
/
Copy pathPromptComposer.php
More file actions
371 lines (324 loc) · 10.2 KB
/
Copy pathPromptComposer.php
File metadata and controls
371 lines (324 loc) · 10.2 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
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
<?php
declare(strict_types=1);
namespace ClaudeAgents\Prompts;
use ClaudeAgents\Exceptions\ValidationException;
/**
* Composer for combining and chaining multiple prompts.
*
* Allows building complex prompts by composing simpler templates together,
* with support for conditional sections and dynamic composition.
*/
class PromptComposer
{
/**
* @var array<array{type: string, content: mixed, condition: callable|null}> Prompt sections
*/
private array $sections = [];
/**
* @var string Separator between sections
*/
private string $separator = "\n\n";
/**
* @var array<string> Collected variables from all sections
*/
private array $variables = [];
private function __construct()
{
}
/**
* Create a new prompt composer.
*/
public static function create(): self
{
return new self();
}
/**
* Add a text section.
*
* @param string $text Static or template text
* @param callable|null $condition Optional condition function (receives $values, returns bool)
*/
public function addText(string $text, ?callable $condition = null): self
{
$this->sections[] = [
'type' => 'text',
'content' => $text,
'condition' => $condition,
];
$this->extractVariables($text);
return $this;
}
/**
* Add a PromptTemplate section.
*
* @param PromptTemplate $template Template to include
* @param callable|null $condition Optional condition function
*/
public function addTemplate(PromptTemplate $template, ?callable $condition = null): self
{
$this->sections[] = [
'type' => 'template',
'content' => $template,
'condition' => $condition,
];
$this->variables = array_merge($this->variables, $template->getVariables());
return $this;
}
/**
* Add a conditional section that only appears if condition is met.
*
* @param string $text Text to include
* @param callable $condition Function that returns bool
*/
public function addConditional(string $text, callable $condition): self
{
return $this->addText($text, $condition);
}
/**
* Add a section that only appears if a variable is set.
*
* @param string $variableName Variable to check
* @param string $text Text to include (can use the variable)
*/
public function addIfVariable(string $variableName, string $text): self
{
return $this->addText($text, function ($values) use ($variableName) {
return isset($values[$variableName]) && ! empty($values[$variableName]);
});
}
/**
* Add a list of items with a template for each.
*
* @param string $itemsVariable Variable name containing array of items
* @param string $itemTemplate Template for each item (use {item} for value)
* @param string $listPrefix Optional prefix before the list
*/
public function addList(
string $itemsVariable,
string $itemTemplate = '- {item}',
string $listPrefix = ''
): self {
$this->sections[] = [
'type' => 'list',
'content' => [
'variable' => $itemsVariable,
'template' => $itemTemplate,
'prefix' => $listPrefix,
],
'condition' => null,
];
$this->variables[] = $itemsVariable;
return $this;
}
/**
* Add examples section with formatting.
*
* @param string $examplesVariable Variable containing examples array
* @param string $inputPrefix Prefix for inputs (e.g., "Input: ")
* @param string $outputPrefix Prefix for outputs (e.g., "Output: ")
*/
public function addExamples(
string $examplesVariable,
string $inputPrefix = 'Input: ',
string $outputPrefix = 'Output: '
): self {
$this->sections[] = [
'type' => 'examples',
'content' => [
'variable' => $examplesVariable,
'inputPrefix' => $inputPrefix,
'outputPrefix' => $outputPrefix,
],
'condition' => null,
];
$this->variables[] = $examplesVariable;
return $this;
}
/**
* Set the separator between sections.
*/
public function withSeparator(string $separator): self
{
$this->separator = $separator;
return $this;
}
/**
* Compose all sections into a single prompt.
*
* @param array<string, mixed> $values Variable values
* @return string Complete composed prompt
*/
public function compose(array $values): string
{
$parts = [];
foreach ($this->sections as $section) {
// Check condition if present
if ($section['condition'] !== null) {
if (! ($section['condition'])($values)) {
continue;
}
}
// Process section based on type
$part = match ($section['type']) {
'text' => $this->processText($section['content'], $values),
'template' => $this->processTemplate($section['content'], $values),
'list' => $this->processList($section['content'], $values),
'examples' => $this->processExamples($section['content'], $values),
default => '',
};
if (! empty($part)) {
$parts[] = $part;
}
}
return implode($this->separator, $parts);
}
/**
* Get all required variables.
*
* @return array<string>
*/
public function getVariables(): array
{
return array_unique($this->variables);
}
/**
* Validate that all required variables are provided.
*
* @param array<string, mixed> $values
* @throws ValidationException If required variables are missing
*/
public function validate(array $values): void
{
$missing = [];
foreach ($this->getVariables() as $var) {
if (! isset($values[$var])) {
$missing[] = $var;
}
}
if (! empty($missing)) {
throw new ValidationException(
'Missing required variable(s) for composition: ' . implode(', ', $missing)
);
}
}
/**
* Create a quick composition from multiple templates.
*
* @param array<PromptTemplate|string> $items Templates or text strings
* @param string $separator Separator between items
*/
public static function fromTemplates(array $items, string $separator = "\n\n"): self
{
$composer = self::create()->withSeparator($separator);
foreach ($items as $item) {
if ($item instanceof PromptTemplate) {
$composer->addTemplate($item);
} elseif (is_string($item)) {
$composer->addText($item);
}
}
return $composer;
}
/**
* Process a text section.
*/
private function processText(string $text, array $values): string
{
foreach ($values as $key => $value) {
if (is_scalar($value)) {
$placeholder = '{' . $key . '}';
$text = str_replace($placeholder, (string) $value, $text);
}
}
return $text;
}
/**
* Process a template section.
*/
private function processTemplate(PromptTemplate $template, array $values): string
{
return $template->format($values);
}
/**
* Process a list section.
*
* @param array{variable: string, template: string, prefix: string} $config
*/
private function processList(array $config, array $values): string
{
if (! isset($values[$config['variable']])) {
return '';
}
$items = $values[$config['variable']];
if (! is_array($items)) {
return '';
}
$lines = [];
if (! empty($config['prefix'])) {
$lines[] = $config['prefix'];
}
foreach ($items as $item) {
$line = str_replace('{item}', (string) $item, $config['template']);
$lines[] = $line;
}
return implode("\n", $lines);
}
/**
* Process an examples section.
*
* @param array{variable: string, inputPrefix: string, outputPrefix: string} $config
*/
private function processExamples(array $config, array $values): string
{
if (! isset($values[$config['variable']])) {
return '';
}
$examples = $values[$config['variable']];
if (! is_array($examples)) {
return '';
}
$formatted = [];
foreach ($examples as $example) {
if (! isset($example['input']) || ! isset($example['output'])) {
continue;
}
$formatted[] = $config['inputPrefix'] . $example['input'] . "\n" .
$config['outputPrefix'] . $example['output'];
}
return implode("\n\n", $formatted);
}
/**
* Extract variables from text.
*/
private function extractVariables(string $text): void
{
if (preg_match_all('/\{(\w+)\}/', $text, $matches)) {
$this->variables = array_merge($this->variables, $matches[1]);
}
}
/**
* Create a chain-of-thought composition.
*/
public static function chainOfThought(): self
{
return self::create()
->addText('Problem: {problem}')
->addText("Let's solve this step by step:")
->addText('Step 1: Understand the problem')
->addText('Step 2: Break it down')
->addText('Step 3: Solve systematically')
->withSeparator("\n\n");
}
/**
* Create a RAG (Retrieval Augmented Generation) composition.
*/
public static function rag(): self
{
return self::create()
->addText('Context:')
->addText('{context}')
->addText('Question: {question}')
->addText('Based on the context above, provide a detailed answer:')
->withSeparator("\n\n");
}
}