system-prompt-builder 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
spb/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """System Prompt Builder."""
spb/cli.py ADDED
@@ -0,0 +1,622 @@
1
+ """Click commands for System Prompt Builder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import tempfile
7
+ from dataclasses import replace
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import click
12
+ import yaml
13
+
14
+ from spb.compression import CompressionResult, compress_prompt
15
+ from spb.evaluation import (
16
+ compare_evaluation_runs,
17
+ group_mean_scores,
18
+ load_evaluation_suite,
19
+ run_evaluation,
20
+ write_evaluation_comparison,
21
+ write_evaluation_run,
22
+ )
23
+ from spb.rendering import RenderedPrompt, ResolvedSkill, render_prompt, validate_project
24
+
25
+
26
+ @click.group()
27
+ def cli() -> None:
28
+ """Compose reproducible system prompts."""
29
+
30
+
31
+ @cli.command()
32
+ @click.option(
33
+ "--project-root",
34
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
35
+ default=Path("."),
36
+ show_default=True,
37
+ help="Directory containing .spb/config.yaml.",
38
+ )
39
+ def validate(project_root: Path) -> None:
40
+ """Validate project configuration and every prompt."""
41
+ try:
42
+ prompt_paths = validate_project(project_root)
43
+ except (OSError, ValueError) as error:
44
+ raise click.ClickException(str(error)) from error
45
+ click.echo(f"Validated {len(prompt_paths)} prompt(s).")
46
+
47
+
48
+ @cli.command()
49
+ @click.argument("prompt", type=click.Path(exists=True, dir_okay=False, path_type=Path))
50
+ @click.option("--harness", required=True, help="Harness to render for.")
51
+ @click.option(
52
+ "--var",
53
+ "variable_pairs",
54
+ multiple=True,
55
+ metavar="NAME=VALUE",
56
+ help="Template variable value; may be provided more than once.",
57
+ )
58
+ @click.option(
59
+ "--replace-release", is_flag=True, help="Replace a changed prompt release."
60
+ )
61
+ @click.option("--compress", is_flag=True, help="Write a compressed prompt artifact.")
62
+ @click.option(
63
+ "--compressor",
64
+ type=click.Choice(["none", "llmlingua"]),
65
+ default="llmlingua",
66
+ show_default=True,
67
+ help="Compressor to use with --compress.",
68
+ )
69
+ @click.option(
70
+ "--project-root",
71
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
72
+ default=Path("."),
73
+ show_default=True,
74
+ help="Directory containing .spb/config.yaml.",
75
+ )
76
+ def render(
77
+ prompt: Path,
78
+ harness: str,
79
+ variable_pairs: tuple[str, ...],
80
+ replace_release: bool,
81
+ compress: bool,
82
+ compressor: str,
83
+ project_root: Path,
84
+ ) -> None:
85
+ """Render PROMPT into a harness-specific build artifact."""
86
+ try:
87
+ result = render_prompt(
88
+ project_root,
89
+ prompt,
90
+ harness=harness,
91
+ variables=_parse_variables(variable_pairs),
92
+ )
93
+ except (OSError, ValueError) as error:
94
+ raise click.ClickException(str(error)) from error
95
+
96
+ try:
97
+ compression = compress_prompt(result.content, compressor) if compress else None
98
+ except ValueError as error:
99
+ raise click.ClickException(str(error)) from error
100
+
101
+ output_path = project_root / "build" / harness / f"{prompt.stem}.md"
102
+ manifest_path = output_path.with_suffix(".manifest.yaml")
103
+ manifest = _manifest(prompt, harness, result, compression)
104
+ try:
105
+ replacing = _check_release_collision(
106
+ output_path, manifest_path, manifest, replace_release
107
+ )
108
+ except (OSError, ValueError, yaml.YAMLError) as error:
109
+ raise click.ClickException(str(error)) from error
110
+
111
+ output_path.parent.mkdir(parents=True, exist_ok=True)
112
+ _atomic_write(output_path, result.content)
113
+ compressed_path = output_path.with_suffix(".compressed.md")
114
+ if compression is None:
115
+ compressed_path.unlink(missing_ok=True)
116
+ else:
117
+ _atomic_write(compressed_path, compression.content)
118
+ _atomic_write(manifest_path, yaml.safe_dump(manifest, sort_keys=False))
119
+ _write_skills_lock(project_root, result.skills)
120
+ if replacing:
121
+ click.echo(f"Replacing release {result.name}@{result.version}", err=True)
122
+ click.echo(output_path)
123
+
124
+
125
+ @cli.group()
126
+ def eval() -> None:
127
+ """Run DeepEval suites against rendered system prompts."""
128
+
129
+
130
+ @eval.command("validate")
131
+ @click.argument("suite", type=click.Path(exists=True, path_type=Path))
132
+ def eval_validate(suite: Path) -> None:
133
+ """Validate an evaluation SUITE without calling a model."""
134
+ try:
135
+ loaded = load_evaluation_suite(suite)
136
+ except (OSError, ValueError) as error:
137
+ raise click.ClickException(str(error)) from error
138
+ click.echo(f"Validated {len(loaded.cases)} evaluation test(s).")
139
+
140
+
141
+ @eval.command("run")
142
+ @click.argument("prompt", type=click.Path(exists=True, dir_okay=False, path_type=Path))
143
+ @click.option("--suite", required=True, type=click.Path(exists=True, path_type=Path))
144
+ @click.option("--harness", required=True)
145
+ @click.option("--var", "variable_pairs", multiple=True, metavar="NAME=VALUE")
146
+ @click.option(
147
+ "--dry-run", is_flag=True, help="Validate inputs without calling a model."
148
+ )
149
+ @click.option("--output", type=click.Path(path_type=Path))
150
+ @click.option("--fail-under", type=click.FloatRange(0, 1))
151
+ @click.option(
152
+ "--project-root",
153
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
154
+ default=Path("."),
155
+ )
156
+ def eval_run(
157
+ prompt: Path,
158
+ suite: Path,
159
+ harness: str,
160
+ variable_pairs: tuple[str, ...],
161
+ dry_run: bool,
162
+ output: Path | None,
163
+ fail_under: float | None,
164
+ project_root: Path,
165
+ ) -> None:
166
+ """Run SUITE against direct model responses using PROMPT as the system prompt."""
167
+ try:
168
+ rendered = render_prompt(
169
+ project_root,
170
+ prompt,
171
+ harness=harness,
172
+ variables=_parse_variables(variable_pairs),
173
+ )
174
+ loaded_suite = load_evaluation_suite(suite)
175
+ if not dry_run:
176
+ evaluation_run = run_evaluation(
177
+ rendered,
178
+ loaded_suite,
179
+ suite_sha256=_sha256(suite.read_text(encoding="utf-8")),
180
+ harness=harness,
181
+ )
182
+ result_path = write_evaluation_run(
183
+ evaluation_run,
184
+ output
185
+ or project_root
186
+ / "build"
187
+ / "evals"
188
+ / rendered.name
189
+ / rendered.version
190
+ / "result.yaml",
191
+ )
192
+ if any(
193
+ not metric["passed"]
194
+ for case in evaluation_run.results
195
+ for metric in case["metrics"]
196
+ ):
197
+ raise click.ClickException("One or more required metrics failed")
198
+ if fail_under is not None and evaluation_run.mean_score < fail_under:
199
+ raise click.ClickException(
200
+ f"Mean score {evaluation_run.mean_score:.3f} is below "
201
+ f"{fail_under:.3f}"
202
+ )
203
+ click.echo(result_path)
204
+ except (OSError, ValueError) as error:
205
+ raise click.ClickException(str(error)) from error
206
+ if dry_run:
207
+ click.echo(f"Validated {len(loaded_suite.cases)} evaluation test(s).")
208
+
209
+
210
+ @eval.command("compare")
211
+ @click.argument("prompt", type=click.Path(exists=True, dir_okay=False, path_type=Path))
212
+ @click.option("--suite", required=True, type=click.Path(exists=True, path_type=Path))
213
+ @click.option("--harness", required=True)
214
+ @click.option("--var", "variable_pairs", multiple=True, metavar="NAME=VALUE")
215
+ @click.option(
216
+ "--compressor", type=click.Choice(["none", "llmlingua"]), default="llmlingua"
217
+ )
218
+ @click.option(
219
+ "--max-score-drop", default=0.0, type=click.FloatRange(0, 1), show_default=True
220
+ )
221
+ @click.option("--output", type=click.Path(path_type=Path))
222
+ @click.option(
223
+ "--project-root",
224
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
225
+ default=Path("."),
226
+ )
227
+ def eval_compare(
228
+ prompt: Path,
229
+ suite: Path,
230
+ harness: str,
231
+ variable_pairs: tuple[str, ...],
232
+ compressor: str,
233
+ max_score_drop: float,
234
+ output: Path | None,
235
+ project_root: Path,
236
+ ) -> None:
237
+ """Compare normal and compressed PROMPT evaluation scores."""
238
+ try:
239
+ rendered = render_prompt(
240
+ project_root,
241
+ prompt,
242
+ harness=harness,
243
+ variables=_parse_variables(variable_pairs),
244
+ )
245
+ compressed = compress_prompt(rendered.content, compressor)
246
+ loaded_suite = load_evaluation_suite(suite)
247
+ suite_sha256 = _sha256(suite.read_text(encoding="utf-8"))
248
+ baseline = run_evaluation(
249
+ rendered, loaded_suite, suite_sha256=suite_sha256, harness=harness
250
+ )
251
+ candidate = run_evaluation(
252
+ replace(rendered, content=compressed.content),
253
+ loaded_suite,
254
+ suite_sha256=suite_sha256,
255
+ harness=harness,
256
+ )
257
+ comparison = compare_evaluation_runs(
258
+ baseline, candidate, max_score_drop=max_score_drop
259
+ )
260
+ result_path = write_evaluation_comparison(
261
+ comparison,
262
+ output
263
+ or project_root
264
+ / "build"
265
+ / "evals"
266
+ / rendered.name
267
+ / rendered.version
268
+ / "comparison.yaml",
269
+ )
270
+ except (OSError, ValueError) as error:
271
+ raise click.ClickException(str(error)) from error
272
+ click.echo(result_path)
273
+ if not comparison.passed:
274
+ raise click.ClickException(
275
+ f"Compressed prompt score dropped by {comparison.score_drop:.3f}"
276
+ )
277
+
278
+
279
+ @cli.group()
280
+ def benchmark() -> None:
281
+ """Run versioned prompt benchmarks with DeepEval."""
282
+
283
+
284
+ @benchmark.command("run")
285
+ @click.argument("prompt", type=click.Path(exists=True, dir_okay=False, path_type=Path))
286
+ @click.option("--suite", required=True, type=click.Path(exists=True, path_type=Path))
287
+ @click.option("--harness", required=True)
288
+ @click.option("--var", "variable_pairs", multiple=True, metavar="NAME=VALUE")
289
+ @click.option("--output", type=click.Path(path_type=Path))
290
+ @click.option("--fail-under", type=click.FloatRange(0, 1))
291
+ @click.option(
292
+ "--min-group-score", "minimum_groups", multiple=True, metavar="GROUP=SCORE"
293
+ )
294
+ @click.option(
295
+ "--project-root",
296
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
297
+ default=Path("."),
298
+ )
299
+ def benchmark_run(
300
+ prompt: Path,
301
+ suite: Path,
302
+ harness: str,
303
+ variable_pairs: tuple[str, ...],
304
+ output: Path | None,
305
+ fail_under: float | None,
306
+ minimum_groups: tuple[str, ...],
307
+ project_root: Path,
308
+ ) -> None:
309
+ """Benchmark PROMPT and persist per-scenario-group scores."""
310
+ try:
311
+ rendered = render_prompt(
312
+ project_root,
313
+ prompt,
314
+ harness=harness,
315
+ variables=_parse_variables(variable_pairs),
316
+ )
317
+ loaded_suite = load_evaluation_suite(suite)
318
+ evaluation_run = run_evaluation(
319
+ rendered,
320
+ loaded_suite,
321
+ suite_sha256=_sha256(suite.read_text(encoding="utf-8")),
322
+ harness=harness,
323
+ )
324
+ minimums = _parse_score_limits(minimum_groups, "--min-group-score")
325
+ groups = group_mean_scores(evaluation_run)
326
+ _check_minimum_scores(groups, minimums, "benchmark group")
327
+ if fail_under is not None and evaluation_run.mean_score < fail_under:
328
+ raise ValueError(
329
+ f"Mean score {evaluation_run.mean_score:.3f} is below {fail_under:.3f}"
330
+ )
331
+ result_path = write_evaluation_run(
332
+ evaluation_run,
333
+ output
334
+ or project_root
335
+ / "build"
336
+ / "benchmarks"
337
+ / rendered.name
338
+ / rendered.version
339
+ / "result.yaml",
340
+ )
341
+ except (OSError, ValueError) as error:
342
+ raise click.ClickException(str(error)) from error
343
+ click.echo(result_path)
344
+
345
+
346
+ @benchmark.command("compare")
347
+ @click.argument(
348
+ "baseline", type=click.Path(exists=True, dir_okay=False, path_type=Path)
349
+ )
350
+ @click.argument(
351
+ "candidate", type=click.Path(exists=True, dir_okay=False, path_type=Path)
352
+ )
353
+ @click.option("--suite", required=True, type=click.Path(exists=True, path_type=Path))
354
+ @click.option("--harness", required=True)
355
+ @click.option("--var", "variable_pairs", multiple=True, metavar="NAME=VALUE")
356
+ @click.option("--max-score-drop", default=0.0, type=click.FloatRange(0, 1))
357
+ @click.option(
358
+ "--max-group-score-drop",
359
+ "maximum_group_drops",
360
+ multiple=True,
361
+ metavar="GROUP=SCORE",
362
+ )
363
+ @click.option("--output", type=click.Path(path_type=Path))
364
+ @click.option(
365
+ "--project-root",
366
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
367
+ default=Path("."),
368
+ )
369
+ def benchmark_compare(
370
+ baseline: Path,
371
+ candidate: Path,
372
+ suite: Path,
373
+ harness: str,
374
+ variable_pairs: tuple[str, ...],
375
+ max_score_drop: float,
376
+ maximum_group_drops: tuple[str, ...],
377
+ output: Path | None,
378
+ project_root: Path,
379
+ ) -> None:
380
+ """Compare BASELINE and CANDIDATE prompt source versions."""
381
+ try:
382
+ variables = _parse_variables(variable_pairs)
383
+ baseline_prompt = render_prompt(
384
+ project_root, baseline, harness=harness, variables=variables
385
+ )
386
+ candidate_prompt = render_prompt(
387
+ project_root, candidate, harness=harness, variables=variables
388
+ )
389
+ loaded_suite = load_evaluation_suite(suite)
390
+ suite_sha256 = _sha256(suite.read_text(encoding="utf-8"))
391
+ baseline_run = run_evaluation(
392
+ baseline_prompt, loaded_suite, suite_sha256=suite_sha256, harness=harness
393
+ )
394
+ candidate_run = run_evaluation(
395
+ candidate_prompt, loaded_suite, suite_sha256=suite_sha256, harness=harness
396
+ )
397
+ comparison = compare_evaluation_runs(
398
+ baseline_run, candidate_run, max_score_drop=max_score_drop
399
+ )
400
+ maximums = _parse_score_limits(maximum_group_drops, "--max-group-score-drop")
401
+ _check_maximum_drops(comparison.group_score_drops, maximums)
402
+ result_path = write_evaluation_comparison(
403
+ comparison,
404
+ output
405
+ or project_root
406
+ / "build"
407
+ / "benchmarks"
408
+ / candidate_prompt.name
409
+ / candidate_prompt.version
410
+ / "comparison.yaml",
411
+ )
412
+ except (OSError, ValueError) as error:
413
+ raise click.ClickException(str(error)) from error
414
+ click.echo(result_path)
415
+ if not comparison.passed:
416
+ raise click.ClickException(
417
+ f"Prompt score dropped by {comparison.score_drop:.3f}"
418
+ )
419
+
420
+
421
+ @cli.command()
422
+ @click.argument("source", type=click.Path(exists=True, dir_okay=False, path_type=Path))
423
+ @click.argument("destination", type=click.Path(path_type=Path))
424
+ @click.option("--replace", is_flag=True, help="Replace an existing destination.")
425
+ def link(source: Path, destination: Path, replace: bool) -> None:
426
+ """Create a symlink from DESTINATION to compiled SOURCE."""
427
+ if destination.exists() or destination.is_symlink():
428
+ if not replace:
429
+ raise click.ClickException(
430
+ "Destination already exists; use --replace to replace it"
431
+ )
432
+ destination.unlink()
433
+ try:
434
+ destination.parent.mkdir(parents=True, exist_ok=True)
435
+ destination.symlink_to(source.resolve())
436
+ except OSError as error:
437
+ raise click.ClickException(f"Unable to create symlink: {error}") from error
438
+ click.echo(destination)
439
+
440
+
441
+ def _parse_score_limits(values: tuple[str, ...], option: str) -> dict[str, float]:
442
+ limits: dict[str, float] = {}
443
+ for value in values:
444
+ group, separator, score_text = value.partition("=")
445
+ if not separator or not group:
446
+ raise ValueError(f"{option} must use GROUP=SCORE")
447
+ try:
448
+ score = float(score_text)
449
+ except ValueError as error:
450
+ raise ValueError(f"{option} score must be a number") from error
451
+ if not 0 <= score <= 1:
452
+ raise ValueError(f"{option} score must be between 0 and 1")
453
+ if group in limits:
454
+ raise ValueError(f"Duplicate {option} group: {group}")
455
+ limits[group] = score
456
+ return limits
457
+
458
+
459
+ def _check_minimum_scores(
460
+ actual_scores: dict[str, float], minimums: dict[str, float], label: str
461
+ ) -> None:
462
+ for group, minimum in minimums.items():
463
+ if group not in actual_scores:
464
+ raise ValueError(f"Unknown {label}: {group}")
465
+ if actual_scores[group] < minimum:
466
+ raise ValueError(
467
+ f"{label.capitalize()} {group} score {actual_scores[group]:.3f} "
468
+ f"is below {minimum:.3f}"
469
+ )
470
+
471
+
472
+ def _check_maximum_drops(drops: dict[str, float], maximums: dict[str, float]) -> None:
473
+ for group, maximum in maximums.items():
474
+ if group not in drops:
475
+ raise ValueError(f"Unknown benchmark group: {group}")
476
+ if drops[group] > maximum:
477
+ raise ValueError(
478
+ f"Benchmark group {group} score dropped by {drops[group]:.3f}"
479
+ )
480
+
481
+
482
+ def _parse_variables(variable_pairs: tuple[str, ...]) -> dict[str, str]:
483
+ variables: dict[str, str] = {}
484
+ for pair in variable_pairs:
485
+ name, separator, value = pair.partition("=")
486
+ if not separator or not name:
487
+ raise ValueError("--var must use NAME=VALUE")
488
+ if not name.isidentifier():
489
+ raise ValueError(f"Invalid --var name: {name}")
490
+ if name in {"harness", "tools"}:
491
+ raise ValueError(f"Reserved --var name: {name}")
492
+ if name in variables:
493
+ raise ValueError(f"Duplicate --var name: {name}")
494
+ variables[name] = value
495
+ return variables
496
+
497
+
498
+ def _write_skills_lock(project_root: Path, skills: tuple[ResolvedSkill, ...]) -> None:
499
+ lock_path = project_root / ".spb" / "skills.lock.yaml"
500
+ existing = (
501
+ yaml.safe_load(lock_path.read_text(encoding="utf-8"))
502
+ if lock_path.exists()
503
+ else {}
504
+ )
505
+ if not isinstance(existing, dict):
506
+ raise ValueError("Existing skills lockfile must be a YAML mapping")
507
+ providers = existing.setdefault("providers", {})
508
+ if not isinstance(providers, dict):
509
+ raise ValueError("Existing skills lockfile providers must be a mapping")
510
+
511
+ for provider_name in {skill.provider for skill in skills if skill.gitrepo}:
512
+ provider_skills = [skill for skill in skills if skill.provider == provider_name]
513
+ first = provider_skills[0]
514
+ providers[provider_name] = {
515
+ "gitrepo": first.gitrepo,
516
+ "revision": first.revision,
517
+ "skills": [
518
+ {
519
+ "reference": skill.reference,
520
+ "path": str(skill.path),
521
+ "sha256": skill.sha256,
522
+ }
523
+ for skill in provider_skills
524
+ ],
525
+ }
526
+ _atomic_write(lock_path, yaml.safe_dump(existing, sort_keys=False))
527
+
528
+
529
+ def _check_release_collision(
530
+ output_path: Path,
531
+ manifest_path: Path,
532
+ manifest: dict[str, Any],
533
+ replace_release: bool,
534
+ ) -> bool:
535
+ if not output_path.exists() and not manifest_path.exists():
536
+ return False
537
+ if not manifest_path.exists():
538
+ if replace_release:
539
+ return True
540
+ raise ValueError(
541
+ "Existing artifact has no readable manifest; use --replace-release"
542
+ )
543
+
544
+ existing = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))
545
+ if not isinstance(existing, dict):
546
+ raise ValueError(
547
+ "Existing artifact has no readable manifest; use --replace-release"
548
+ )
549
+ same_identity = all(
550
+ existing.get(key) == manifest[key] for key in ("name", "version", "harness")
551
+ )
552
+ changed = bool(existing.get("rendered_sha256") != manifest["rendered_sha256"])
553
+ if same_identity and changed:
554
+ if replace_release:
555
+ return True
556
+ raise ValueError(
557
+ "Prompt release collision; use --replace-release to replace it"
558
+ )
559
+ if changed and not replace_release:
560
+ raise ValueError(
561
+ "Existing artifact differs; use --replace-release to replace it"
562
+ )
563
+ return changed
564
+
565
+
566
+ def _atomic_write(path: Path, content: str) -> None:
567
+ with tempfile.NamedTemporaryFile(
568
+ mode="w", encoding="utf-8", dir=path.parent, delete=False
569
+ ) as temporary:
570
+ temporary.write(content)
571
+ temporary_path = Path(temporary.name)
572
+ temporary_path.replace(path)
573
+
574
+
575
+ def _manifest(
576
+ prompt: Path,
577
+ harness: str,
578
+ result: RenderedPrompt,
579
+ compression: CompressionResult | None,
580
+ ) -> dict[str, Any]:
581
+ visible_variables, redacted_variables = _redact_variables(result.variables)
582
+ manifest: dict[str, Any] = {
583
+ "name": result.name,
584
+ "version": result.version,
585
+ "source": str(prompt),
586
+ "source_sha256": _sha256(prompt.read_text(encoding="utf-8")),
587
+ "harness": harness,
588
+ "rendered_sha256": _sha256(result.content),
589
+ "variables": visible_variables,
590
+ "redacted_variables": redacted_variables,
591
+ "skills": [
592
+ {
593
+ "reference": skill.reference,
594
+ "path": str(skill.path),
595
+ "sha256": skill.sha256,
596
+ }
597
+ for skill in result.skills
598
+ ],
599
+ }
600
+ if compression is not None:
601
+ manifest["compression"] = {
602
+ "compressor": compression.compressor,
603
+ "settings": compression.settings,
604
+ "sha256": _sha256(compression.content),
605
+ }
606
+ return manifest
607
+
608
+
609
+ def _redact_variables(variables: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
610
+ secret_words = ("password", "secret", "token", "key")
611
+ visible: dict[str, Any] = {}
612
+ redacted: list[str] = []
613
+ for name, value in variables.items():
614
+ if any(word in name.lower() for word in secret_words):
615
+ redacted.append(name)
616
+ else:
617
+ visible[name] = value
618
+ return visible, redacted
619
+
620
+
621
+ def _sha256(value: str) -> str:
622
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
spb/compression.py ADDED
@@ -0,0 +1,46 @@
1
+ """Optional prompt-compression adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class CompressionResult:
11
+ """The output and provenance of one compression operation."""
12
+
13
+ content: str
14
+ compressor: str
15
+ settings: dict[str, Any]
16
+
17
+
18
+ def compress_prompt(content: str, compressor: str) -> CompressionResult:
19
+ """Compress content with a named optional compressor."""
20
+ if compressor == "none":
21
+ return CompressionResult(content=content, compressor="none", settings={})
22
+ if compressor == "llmlingua":
23
+ return _compress_with_llmlingua(content)
24
+ raise ValueError(f"Unsupported compressor: {compressor}")
25
+
26
+
27
+ def _compress_with_llmlingua(content: str) -> CompressionResult:
28
+ try:
29
+ from llmlingua import PromptCompressor # type: ignore[import-not-found]
30
+ except ImportError as error:
31
+ raise ValueError(
32
+ "LLMLingua is not installed; install the llmlingua optional dependency"
33
+ ) from error
34
+
35
+ target_token = 200
36
+ output = PromptCompressor().compress_prompt(
37
+ content, instruction="", question="", target_token=target_token
38
+ )
39
+ compressed = output.get("compressed_prompt")
40
+ if not isinstance(compressed, str):
41
+ raise ValueError("LLMLingua did not return a compressed prompt")
42
+ return CompressionResult(
43
+ content=compressed,
44
+ compressor="llmlingua",
45
+ settings={"target_token": target_token},
46
+ )