-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodels.py
More file actions
2210 lines (1966 loc) · 97.2 KB
/
Copy pathmodels.py
File metadata and controls
2210 lines (1966 loc) · 97.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Data Models for Gran Sabio LLM Engine
======================================
Pydantic models for request/response handling and internal data structures.
"""
import os
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Literal, Optional, Union
from pydantic import AliasChoices, BaseModel, Field, field_validator, model_validator
from config import config
from model_capability_registry import (
model_qualifies_for_inline_accent_guard,
resolve_model_capability_context,
)
from phrase_frequency_config import normalize_phrase_frequency_config
from request_timeouts import clamp_client_timeout
from schema_utils import validate_json_schema_complexity
from smart_edit import TextEditRange
class GenerationStatus(str, Enum):
"""Status enumeration for content generation"""
INITIALIZING = "initializing"
GENERATING = "generating"
QA_EVALUATION = "qa_evaluation"
GRAN_SABIO_REVIEW = "gran_sabio_review"
COMPLETED = "completed"
REJECTED = "rejected"
FAILED = "failed"
CANCELLED = "cancelled"
# Valid content types (public documentation)
# Note: "other" is also supported but intentionally not listed for internal use only
VALID_CONTENT_TYPES = frozenset([
"biography",
"script",
"novel",
"article",
"essay",
"technical",
"creative",
"json",
# Opinion/evaluation types (for smart_editing_mode='never')
"opinion",
"analysis",
"review",
"selection",
"comparison",
"evaluation",
"vote",
"preference",
# Additional factual types
"report",
"story"
])
# Free-text and list payload ceilings (audit API-02). Sized so a fully packed
# request stays well within the ~10-25 MB body budget enforced at the HTTP
# layer, while covering every legitimate long-form workflow. The prompt
# ceiling matches MAX_ANALYSIS_TEXT_CHARACTERS in analysis_router.py.
MAX_PROMPT_CHARS = 250_000
MAX_SYSTEM_PROMPT_CHARS = 100_000
MAX_SOURCE_TEXT_CHARS = 1_000_000
MAX_CUMULATIVE_TEXT_CHARS = 1_000_000
MAX_CONTEXT_DOCUMENT_REFS = 50
MAX_IMAGE_REFS = 20
MAX_QA_LAYERS = 25
# Productive ceiling for user-supplied max_iterations (audit GEN-10). Higher
# values are accepted for API compatibility but clamped, so session memory
# retention (full content + QA results per iteration) stays bounded.
MAX_ITERATIONS_EFFECTIVE_CAP = 25
def is_json_output_requested(request: Any) -> bool:
"""Return True when a request effectively asks for JSON output.
``content_type="json"`` is a legacy alias and remains equivalent to
``json_output=True`` until product explicitly deprecates it.
"""
return bool(
getattr(request, "json_output", False)
or getattr(request, "content_type", None) == "json"
)
class QALayer(BaseModel):
"""Configuration for a QA evaluation layer"""
name: str = Field(..., description="Name of the QA layer")
description: str = Field(..., description="What this layer evaluates")
criteria: str = Field(..., description="Specific criteria for evaluation")
min_score: float = Field(default=7.0, ge=0.0, le=10.0, description="Minimum score for this layer")
is_mandatory: bool = Field(default=False, description="Whether this layer must pass after max iterations or trigger rejection")
deal_breaker_criteria: Optional[str] = Field(default=None, description="Specific deal-breaker facts to detect (e.g., 'invents facts', 'uses offensive language')")
concise_on_pass: bool = Field(default=True, description="If True, provide concise 'Passed' feedback when score >= min_score (saves tokens). If False, always provide detailed feedback.")
order: int = Field(default=1, description="Evaluation order for this layer")
# Vision support for QA evaluation
include_input_images: bool = Field(
default=False,
description="When true and images are available, include input images in QA evaluation context. Useful for layers that validate image descriptions or visual accuracy."
)
# Deprecated field for backward compatibility
is_deal_breaker: bool = Field(default=False, description="DEPRECATED: Use deal_breaker_criteria instead")
class Config:
json_schema_extra = {
"example": {
"name": "Accuracy",
"description": "Factual accuracy and truth verification",
"criteria": "Check for factual errors, invented information, or contradictions with known facts",
"min_score": 8.0,
"is_mandatory": True,
"deal_breaker_criteria": "invents facts or presents false information as true",
"order": 1
}
}
class QAModelConfig(BaseModel):
"""Configuration for a specific QA evaluation model"""
model: str = Field(..., description="Model identifier (e.g., 'gpt-5-mini', 'claude-opus-4')")
endpoint_id: Optional[str] = Field(
default=None,
min_length=1,
description="Administrator-configured inference endpoint identity for this evaluator.",
)
max_tokens: Optional[int] = Field(
default=None,
gt=0,
description=(
"Maximum tokens for QA evaluation. If omitted, resolved from "
"QA_DEFAULT_MAX_TOKENS or the model's safe output limit."
)
)
reasoning_effort: Optional[str] = Field(
default=None,
description="Reasoning effort for GPT-5/O1/O3 models (none, low, medium, high)"
)
thinking_budget_tokens: Optional[int] = Field(
default=None,
ge=1024,
description="Thinking budget for Claude models (min 1024)"
)
temperature: Optional[float] = Field(
default=None,
ge=0.0,
le=2.0,
description="Custom temperature for this QA model (default: 0.3 if not specified)"
)
timeout_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Maximum seconds allowed for this QA model evaluation attempt"
)
provider_options: Optional[Dict[str, Any]] = Field(
default=None,
description=(
"Per-evaluator provider routing options. Routing supplies this for "
"OpenRouter evaluators so duplicate model slots retain their own "
"provider policy."
),
)
@field_validator("endpoint_id")
@classmethod
def validate_endpoint_id(cls, value: Optional[str]) -> Optional[str]:
"""Reject blank endpoint identifiers before they reach routing."""
if value is None:
return None
normalized = value.strip()
if not normalized:
raise ValueError("endpoint_id must be a non-empty string")
return normalized
@field_validator("timeout_seconds")
@classmethod
def validate_timeout_ceiling(cls, v: Optional[float]) -> Optional[float]:
"""Clamp client-supplied QA timeouts to the central ceiling (audit API-09)."""
return clamp_client_timeout(v)
class Config:
json_schema_extra = {
"example": {
"model": "gpt-5-mini",
"max_tokens": 10000,
"reasoning_effort": "medium",
"temperature": 0.3,
"timeout_seconds": 12000
}
}
class WordCountEnforcement(BaseModel):
"""Configuration for word count enforcement in content generation."""
enabled: bool = Field(default=False, description="Enable word count enforcement")
flexibility_percent: float = Field(default=15.0, ge=0.0, le=100.0, description="Allowed flexibility percentage (0-100)")
direction: Literal["both", "more", "less"] = Field(default="both", description="Direction of flexibility: both (±), more (+), or less (-)")
severity: Literal["important", "deal_breaker"] = Field(default="important", description="Severity level when word count is violated")
class Config:
json_schema_extra = {
"example": {
"enabled": True,
"flexibility_percent": 15.0,
"direction": "both",
"severity": "deal_breaker"
}
}
class PhraseFrequencyRule(BaseModel):
"""Rule definition for phrase repetition checks."""
name: str = Field(..., min_length=1, description="Identifier for the rule")
min_length: int = Field(default=2, ge=1, description="Minimum n-gram length to inspect")
max_length: Optional[int] = Field(default=None, ge=1, description="Maximum n-gram length to inspect")
max_repetitions: Optional[int] = Field(default=None, ge=1, description="Maximum allowed occurrences before flagging (deprecated: use max_ratio_tokens)")
max_ratio_tokens: Optional[float] = Field(default=None, ge=0.0, le=0.5, description="Maximum ratio of text (0.0-0.5 = 0%-50%) - scales with text length")
max_count_absolute: Optional[int] = Field(default=None, ge=1, description="Absolute maximum count as safety limit (used with max_ratio_tokens)")
phrase: Optional[str] = Field(default=None, description="Exact phrase to monitor; leave empty for generic rule")
severity: Literal["warn", "deal_breaker"] = Field(default="warn", description="Severity when the rule is violated")
guidance: Optional[str] = Field(default=None, description="Optional guidance for generator iterations")
@model_validator(mode="after")
def _validate_limits(self):
"""Enforce a coherent n-gram range and an effective repetition limit.
Runs on the fully resolved model, so it also applies when the fields
fall back to their defaults (audit PER-03).
"""
if self.max_length is not None and self.max_length < self.min_length:
raise ValueError("max_length must be greater than or equal to min_length")
if self.max_ratio_tokens is None and self.max_repetitions is None:
raise ValueError("Either max_ratio_tokens or max_repetitions must be specified")
return self
class PhraseFrequencyConfig(BaseModel):
"""Configuration envelope for phrase repetition QA."""
enabled: bool = Field(default=False, description="Enable phrase repetition QA layer")
language: Optional[str] = Field(default=None, description="Language hint for repetition analysis (e.g., 'es', 'en')")
filter_stop_words: bool = Field(default=True, description="Ignore stop-word-only phrases when language stop words are available")
min_score: float = Field(default=8.0, ge=0.0, le=10.0, description="Minimum QA score threshold for this layer")
min_n: Optional[int] = Field(default=None, ge=1, description="Override minimum n-gram length")
max_n: Optional[int] = Field(default=None, ge=1, description="Override maximum n-gram length")
min_count: int = Field(default=2, ge=1, description="Minimum occurrences to include in analysis")
mp_threshold_tokens: int = Field(default=50000, ge=1, description="Token threshold for switching to multiprocess counting")
workers: int = Field(default=0, ge=0, description="Explicit worker count for multiprocess mode (0 = auto)")
summary_top_k: int = Field(default=25, ge=1, description="Top phrases per n to include in summaries")
diagnostics_mode: Literal["off", "basic", "full"] = Field(default="off", description="Diagnostics mode for repetition analyzer")
diag_len_bins: Optional[str] = Field(default=None, description="Length-bin rule string, e.g., '3-5:5,6-10:3'")
diag_max_repeat_ratio: Optional[float] = Field(default=None, ge=0.0, le=1.0, description="Max repeat ratio for diagnostics")
diag_min_distance_tokens: Optional[int] = Field(default=None, ge=0, description="Minimum token distance for diagnostics")
diag_cluster_gap_tokens: Optional[int] = Field(default=None, ge=0, description="Cluster gap tokens for diagnostics")
diag_cluster_min_count: Optional[int] = Field(default=None, ge=1, description="Minimum cluster count for diagnostics")
diag_cluster_max_span_tokens: Optional[int] = Field(default=None, ge=1, description="Maximum cluster span for diagnostics")
diag_top_k: Optional[int] = Field(default=None, ge=0, description="Maximum diagnostics violations to include")
diag_digest_k: Optional[int] = Field(default=None, ge=0, description="Maximum digest entries to include")
rules: List[PhraseFrequencyRule] = Field(default_factory=list, description="Phrase repetition rules to evaluate")
@field_validator("max_n")
@classmethod
def validate_ngram_range(cls, v: Optional[int], info):
min_n = info.data.get("min_n")
if v is not None and min_n is not None and v < min_n:
raise ValueError("max_n must be greater than or equal to min_n")
return v
@model_validator(mode="after")
def disable_when_enabled_without_rules(self):
normalize_phrase_frequency_config(self, context="PhraseFrequencyConfig validation")
return self
def derive_min_n(self) -> int:
candidate = [rule.min_length for rule in self.rules if rule.min_length]
for rule in self.rules:
if rule.phrase:
phrase_tokens = [tok for tok in rule.phrase.strip().split() if tok]
if phrase_tokens:
candidate.append(len(phrase_tokens))
min_rule = min(candidate) if candidate else 2
return max(1, self.min_n or min_rule)
def derive_max_n(self) -> int:
candidate = []
for rule in self.rules:
if rule.max_length is not None:
candidate.append(rule.max_length)
else:
if rule.phrase:
phrase_tokens = [tok for tok in rule.phrase.strip().split() if tok]
if phrase_tokens:
candidate.append(len(phrase_tokens))
continue
candidate.append(rule.min_length)
max_rule = max(candidate) if candidate else max(self.min_n or 2, 6)
configured = self.max_n or max_rule
return max(configured, self.derive_min_n())
def to_settings(self) -> "PhraseFrequencySettings":
from tools.phrase_frequency_utils import (
PhraseFrequencyRuleSpec,
PhraseFrequencySettings,
)
rules = [
PhraseFrequencyRuleSpec(
min_length=rule.min_length,
max_length=rule.max_length,
max_repetitions=rule.max_repetitions,
max_ratio_tokens=rule.max_ratio_tokens,
max_count_absolute=rule.max_count_absolute,
severity=rule.severity,
phrase=rule.phrase,
label=rule.name,
guidance=rule.guidance,
)
for rule in self.rules
]
settings = PhraseFrequencySettings(
enabled=self.enabled,
language=self.language,
filter_stop_words=self.filter_stop_words,
min_n=self.derive_min_n(),
max_n=self.derive_max_n(),
min_count=self.min_count,
mp_threshold_tokens=self.mp_threshold_tokens,
workers=self.workers,
summary_top_k=self.summary_top_k,
diagnostics_mode=self.diagnostics_mode,
diag_len_bins=self.diag_len_bins or "",
diag_max_repeat_ratio=(self.diag_max_repeat_ratio if self.diag_max_repeat_ratio is not None else 0.0),
diag_min_distance_tokens=(self.diag_min_distance_tokens if self.diag_min_distance_tokens is not None else 0),
diag_cluster_gap_tokens=(self.diag_cluster_gap_tokens if self.diag_cluster_gap_tokens is not None else 80),
diag_cluster_min_count=(self.diag_cluster_min_count if self.diag_cluster_min_count is not None else 3),
diag_cluster_max_span_tokens=(self.diag_cluster_max_span_tokens if self.diag_cluster_max_span_tokens is not None else 250),
diag_top_k=(self.diag_top_k if self.diag_top_k is not None else 50),
diag_digest_k=(self.diag_digest_k if self.diag_digest_k is not None else 20),
rules=rules,
)
return settings
def build_layer(self, order: int = 1) -> QALayer:
if not self.enabled or not self.rules:
raise ValueError("Cannot build phrase frequency layer without enabled rules")
description = "Evaluates the configured phrase repetition rules"
criteria_lines = [
"Analyze the text with a word_punct tokenizer, respecting sentence boundaries.",
"Check these repetition rules:",
]
deal_breaker_rules: List[str] = []
for rule in self.rules:
length_desc = (
f"{rule.min_length}-{rule.max_length} words"
if rule.max_length is not None and rule.max_length != rule.min_length
else (f"{rule.min_length} words" if rule.max_length == rule.min_length else f"at least {rule.min_length} words")
)
phrase_desc = f"exact phrase '{rule.phrase}'" if rule.phrase else f"phrases of {length_desc}"
severity_desc = "deal-breaker" if rule.severity == "deal_breaker" else "warning"
criteria_lines.append(
f"- {rule.name}: {phrase_desc}, at most {rule.max_repetitions} repetitions ({severity_desc})."
)
if rule.severity == "deal_breaker":
deal_breaker_rules.append(rule.name)
deal_breaker_text = None
if deal_breaker_rules:
deal_breaker_text = (
"Exceeding the configured limit on any rule marked as deal-breaker"
)
return QALayer(
name="Phrase Frequency Guard",
description=description,
criteria="\n".join(criteria_lines),
min_score=self.min_score,
is_mandatory=True,
deal_breaker_criteria=deal_breaker_text,
concise_on_pass=True,
order=order,
)
class LexicalDiversityThresholdsConfig(BaseModel):
"""Optional overrides for lexical diversity thresholds."""
herdan_green_min: Optional[float] = Field(default=None, description="Override Herdan's C GREEN minimum")
herdan_amber_min: Optional[float] = Field(default=None, description="Override Herdan's C AMBER minimum")
yulek_green_max: Optional[float] = Field(default=None, description="Override Yule's K GREEN maximum")
yulek_amber_max: Optional[float] = Field(default=None, description="Override Yule's K AMBER maximum")
mtld_green_min: Optional[float] = Field(default=None, description="Override MTLD GREEN minimum")
mtld_amber_min: Optional[float] = Field(default=None, description="Override MTLD AMBER minimum")
hdd_green_min: Optional[float] = Field(default=None, description="Override HD-D GREEN minimum")
hdd_amber_min: Optional[float] = Field(default=None, description="Override HD-D AMBER minimum")
brunet_green_max: Optional[float] = Field(default=None, description="Override Brunet's W GREEN maximum")
brunet_amber_max: Optional[float] = Field(default=None, description="Override Brunet's W AMBER maximum")
class LexicalDiversityDecisionConfig(BaseModel):
"""Decision policy for lexical diversity QA layer."""
require_majority: int = Field(default=2, ge=1, description="Number of GREEN/RED metrics required for decisive label")
deal_breaker_on_red: bool = Field(default=True, description="Mark layer as deal-breaker whenever decision is RED")
deal_breaker_on_amber: bool = Field(default=False, description="Mark layer as deal-breaker when decision is AMBER")
red_metrics_threshold: Optional[int] = Field(default=None, ge=1, description="Deal-breaker when this many metrics are RED")
amber_metrics_threshold: Optional[int] = Field(default=None, ge=1, description="Deal-breaker when this many metrics are AMBER")
custom_metric_thresholds: Dict[str, Dict[str, float]] = Field(
default_factory=dict,
description="Per-metric threshold overrides. Keys: metric name, values: threshold dictionary.",
)
class LexicalDiversityWindowConfig(BaseModel):
"""Window analysis settings for lexical diversity layer."""
analyze_windows: bool = Field(default=False, description="Force window/paragraph analysis on every run")
window_mode: Literal["tokens", "paragraphs"] = Field(default="tokens", description="Window analysis mode")
window_size: int = Field(default=200, ge=1, description="Token count per window when window_mode=tokens")
window_step: int = Field(default=100, ge=1, description="Step size between windows when window_mode=tokens")
window_top_k: int = Field(default=10, ge=0, description="Top words per window")
include_window_metrics: bool = Field(default=False, description="Include metrics for each window")
window_include_positions: bool = Field(default=False, description="Include token indices for top window words")
window_preview_chars: int = Field(default=160, ge=1, description="Preview characters per window in metadata")
auto_window_on_large_text: bool = Field(default=True, description="Enable window analysis automatically on large texts")
auto_window_token_threshold: int = Field(default=1200, ge=1, description="Token threshold for automatic window analysis")
auto_window_on_decision: List[str] = Field(
default_factory=lambda: ["RED"],
description="Decision labels that should trigger window analysis automatically",
)
def build_policy(self) -> "LexicalDiversityWindowPolicy":
from tools.lexical_diversity_utils import LexicalDiversityWindowPolicy
return LexicalDiversityWindowPolicy(
analyze_windows=self.analyze_windows,
window_mode=self.window_mode,
window_size=self.window_size,
window_step=self.window_step,
window_top_k=self.window_top_k,
include_window_metrics=self.include_window_metrics,
window_include_positions=self.window_include_positions,
window_preview_chars=self.window_preview_chars,
auto_window_on_large_text=self.auto_window_on_large_text,
auto_window_token_threshold=self.auto_window_token_threshold,
auto_window_on_decision=tuple(label.upper() for label in self.auto_window_on_decision),
)
class LexicalDiversityScoringConfig(BaseModel):
"""Scoring policy for lexical diversity evaluations."""
green_score: float = Field(default=9.0, ge=8.0, le=10.0, description="Score applied when decision=GREEN")
amber_score: float = Field(default=7.0, ge=0.0, le=9.5, description="Score applied when decision=AMBER")
red_score: float = Field(default=3.0, ge=0.0, le=8.0, description="Score applied when decision=RED")
green_floor: float = Field(default=8.0, ge=0.0, le=10.0, description="Lower bound enforced on GREEN scores")
def build_policy(self) -> "LexicalDiversityScorePolicy":
from tools.lexical_diversity_utils import LexicalDiversityScorePolicy
return LexicalDiversityScorePolicy(
green_score=self.green_score,
amber_score=self.amber_score,
red_score=self.red_score,
green_floor=self.green_floor,
)
class LexicalDiversityConfig(BaseModel):
"""Configuration envelope for lexical diversity QA."""
enabled: bool = Field(default=False, description="Enable lexical diversity QA layer")
metrics: str = Field(
default="auto",
description='Metrics to compute: "auto", "all", or comma-separated list (e.g., "mtld,hdd,yulek,c")',
)
include_ttr: bool = Field(default=False, description="Include type-token ratio when metrics=auto")
distinct_max_n: int = Field(default=0, ge=0, description="Compute distinct-n metrics up to this n (0 disables)")
mtld_threshold: float = Field(default=0.72, gt=0.0, description="MTLD factor threshold")
mtld_min_factor_len: int = Field(default=10, ge=1, description="Minimum factor length for MTLD calculation")
hdd_sample_size: int = Field(default=42, ge=1, description="Sample size for HD-D metric")
brunet_alpha: float = Field(default=0.165, gt=0.0, description="Brunet's W alpha parameter")
tokenizer: Literal["word_punct", "alnum"] = Field(default="word_punct", description="Tokenizer mode")
lowercase: bool = Field(default=True, description="Lowercase tokens before analysis")
strip_accents: bool = Field(default=False, description="Strip accents before analysis")
language: Optional[str] = Field(default=None, description="Language hint for stop-word filtering (e.g., 'es', 'en')")
filter_stop_words: bool = Field(default=True, description="Filter language stop words from top-word summaries when available")
top_words_k: int = Field(default=50, ge=0, description="Top repeated words to expose in metadata")
include_positions: bool = Field(default=False, description="Include token positions for top words")
thresholds: Optional[LexicalDiversityThresholdsConfig] = Field(
default=None, description="Threshold overrides for grading"
)
decision: LexicalDiversityDecisionConfig = Field(
default_factory=LexicalDiversityDecisionConfig, description="Decision policy tuning"
)
windows: LexicalDiversityWindowConfig = Field(
default_factory=LexicalDiversityWindowConfig, description="Window analysis configuration"
)
scoring: LexicalDiversityScoringConfig = Field(
default_factory=LexicalDiversityScoringConfig, description="Score mapping configuration"
)
def to_settings(self) -> "LexicalDiversitySettings":
from tools.lexical_diversity_utils import (
LexicalDiversityDecisionPolicy,
LexicalDiversitySettings,
)
decision_policy = LexicalDiversityDecisionPolicy(
require_majority=self.decision.require_majority,
deal_breaker_on_red=self.decision.deal_breaker_on_red,
deal_breaker_on_amber=self.decision.deal_breaker_on_amber,
red_metrics_threshold=self.decision.red_metrics_threshold,
amber_metrics_threshold=self.decision.amber_metrics_threshold,
custom_metric_thresholds={
key.lower(): value for key, value in self.decision.custom_metric_thresholds.items()
},
)
thresholds_overrides: Dict[str, float] = {}
if self.thresholds:
for field_name, value in self.thresholds.model_dump(exclude_none=True).items():
thresholds_overrides[field_name] = value
return LexicalDiversitySettings(
enabled=self.enabled,
language=self.language,
filter_stop_words=self.filter_stop_words,
metrics=self.metrics,
include_ttr=self.include_ttr,
distinct_max_n=self.distinct_max_n,
mtld_threshold=self.mtld_threshold,
mtld_min_factor_len=self.mtld_min_factor_len,
hdd_sample_size=self.hdd_sample_size,
brunet_alpha=self.brunet_alpha,
tokenizer=self.tokenizer,
lowercase=self.lowercase,
strip_accents=self.strip_accents,
thresholds_overrides=thresholds_overrides,
top_words_k=self.top_words_k,
include_positions=self.include_positions,
decision_policy=decision_policy,
score_policy=self.scoring.build_policy(),
window_policy=self.windows.build_policy(),
)
def build_layer(self, order: int = 1) -> QALayer:
if not self.enabled:
raise ValueError("Cannot build lexical diversity layer when disabled")
description = "Evaluates lexical variety across the draft"
criteria_lines = [
"Measure vocabulary richness with MTLD, HD-D, Herdan's C, Yule's K, and optional distinct-n metrics.",
"Flag drafts with overly repetitive wording or narrow vocabulary.",
"Promote varied phrasing before repetition analysis triggers additional guardrails.",
]
deal_breaker_text = (
"Lexical diversity scores below configured thresholds (decision RED) or repeated AMBER/RED metrics."
if self.decision.deal_breaker_on_red or self.decision.red_metrics_threshold
else None
)
return QALayer(
name="Lexical Diversity Guard",
description=description,
criteria="\n".join(criteria_lines),
min_score=8.0,
is_mandatory=False,
deal_breaker_criteria=deal_breaker_text,
concise_on_pass=True,
order=order,
)
# =============================================================================
# EVIDENCE GROUNDING MODELS
# Based on Strawberry/Pythea project (MIT License)
# https://github.com/leochlon/pythea
# =============================================================================
class EvidenceGroundingConfig(BaseModel):
"""Configuration for evidence grounding verification using logprobs.
This feature detects procedural hallucination (confabulation) by measuring
whether the model actually relied on cited evidence. If removing evidence
doesn't reduce model confidence, the model likely confabulated.
"""
enabled: bool = Field(default=False, description="Enable evidence grounding verification")
model: Optional[str] = Field(
default=None,
description="[DEPRECATED] Override model for BOTH extraction and scoring. "
"If None, uses evidence.extract_claims, evidence.classify_spans, and "
"evidence.score_logprobs from llm_routing. "
"Only set this to force a single model for both phases."
)
# Claim extraction settings
max_claims: int = Field(default=15, ge=1, le=50, description="Maximum claims to extract")
filter_trivial: bool = Field(default=True, description="Filter non-substantive claims")
min_claim_importance: float = Field(
default=0.6, ge=0.0, le=1.0,
description="Minimum importance score (0-1) to keep a claim"
)
# Budget thresholds
target_confidence: float = Field(
default=0.95, ge=0.5, le=0.99,
description="Expected reliability of claims for budget calculation"
)
budget_gap_threshold: float = Field(
default=0.5, ge=0.0,
description="Flag claims with budget gap above this (in bits)"
)
# Behavior on failure
on_flag: Literal["warn", "deal_breaker", "regenerate"] = Field(
default="warn",
description="Action when flagged claims exceed threshold"
)
max_flagged_claims: int = Field(
default=2, ge=1,
description="Trigger action when this many claims are flagged"
)
# Layer ordering (Phase 5)
order: Optional[int] = Field(
default=None,
description="Execution order relative to QA layers. "
"If None, auto-calculated based on on_flag: "
"deal_breaker/regenerate -> 0 (fail-fast first), "
"warn -> 999 (verification-only at end)"
)
# Advanced settings
top_logprobs: int = Field(default=10, ge=1, le=20, description="Top logprobs to request")
placeholder_text: str = Field(
default="[EVIDENCE REMOVED]",
description="Text to replace cited evidence with for pseudo-prior calculation"
)
class Config:
json_schema_extra = {
"example": {
"enabled": True,
"model": None, # Uses the evidence.* routes from llm_routing
"filter_trivial": True,
"budget_gap_threshold": 0.5,
"on_flag": "deal_breaker",
"max_flagged_claims": 2,
"order": None # Auto: deal_breaker/regenerate -> 0, warn -> 999
}
}
class SpanType(str, Enum):
"""Classification of evidence span content type.
Used by EvidenceMatcher to categorize spans for verification:
- Only ASSERTION spans can entail facts
- QUESTION/INSTRUCTION spans are masked during verification
- EMPTY spans are ignored
"""
ASSERTION = "assertion" # Declarative statements that can entail facts
QUESTION = "question" # Interrogative content (cannot entail)
INSTRUCTION = "instruction" # Prompts/commands (cannot entail)
EMPTY = "empty" # No meaningful content
class EvidenceSpan(BaseModel):
"""A labeled span of evidence text for grounding verification.
Spans are chunks of the original context, labeled with IDs (S0, S1, etc.)
for citation tracking. Used by EvidenceMatcher and BudgetScorer.
"""
id: str = Field(..., description="Span identifier (e.g., 'S0', 'S1')")
text: str = Field(..., description="The actual text content of the span")
span_type: SpanType = Field(
default=SpanType.ASSERTION,
description="Classification of the span content type"
)
start_char: int = Field(..., ge=0, description="Start character offset in original context")
end_char: int = Field(..., ge=0, description="End character offset in original context")
class Config:
json_schema_extra = {
"example": {
"id": "S0",
"text": "Marie Curie was born in Warsaw in 1867.",
"span_type": "assertion",
"start_char": 0,
"end_char": 41
}
}
class ExtractedClaim(BaseModel):
"""A single verifiable claim extracted from generated content."""
idx: int = Field(..., ge=0, description="Claim index")
claim: str = Field(..., max_length=300, description="The claim text")
kind: Literal["factual", "inference", "opinion", "trivial"] = Field(
..., description="Classification of the claim type"
)
importance: float = Field(..., ge=0.0, le=1.0, description="Importance score (0-1)")
cited_spans: List[str] = Field(
default_factory=list,
description="Span IDs this claim references (e.g., ['S0', 'S2'])"
)
source_text: str = Field(default="", description="Original text segment containing claim")
class ClaimBudgetResult(BaseModel):
"""Budget analysis result for a single claim."""
idx: int = Field(..., description="Claim index")
claim: str = Field(..., description="The claim text")
cited_spans: List[str] = Field(default_factory=list, description="Referenced span IDs")
# Probabilities
posterior_yes: float = Field(
..., ge=0.0, le=1.0,
description="P(YES | full_context) - confidence with evidence"
)
prior_yes: float = Field(
..., ge=0.0, le=1.0,
description="P(YES | context_without_evidence) - confidence without evidence"
)
# Budget metrics (in bits/nats)
required_bits: float = Field(..., description="KL(target || prior) - information needed")
observed_bits: float = Field(..., description="KL(posterior || prior) - information provided")
budget_gap: float = Field(..., description="required - observed; positive = deficit")
# Verdict
flagged: bool = Field(..., description="Whether this claim is flagged for insufficient grounding")
confidence_delta: float = Field(
...,
description="posterior - prior; intuitive measure of evidence impact"
)
class EvidenceGroundingResult(BaseModel):
"""Complete result of evidence grounding verification."""
enabled: bool = Field(..., description="Whether grounding was enabled")
model_used: str = Field(..., description="Model used for verification")
# Claim analysis counts
total_claims_extracted: int = Field(..., ge=0, description="Total claims found in content")
claims_after_filter: int = Field(..., ge=0, description="Claims remaining after trivial filter")
claims_verified: int = Field(..., ge=0, description="Claims actually verified with logprobs")
# Results
claims: List[ClaimBudgetResult] = Field(
default_factory=list,
description="Detailed results per claim"
)
flagged_claims: int = Field(..., ge=0, description="Number of claims flagged")
max_budget_gap: float = Field(..., description="Maximum budget gap across all claims")
# Verdict
passed: bool = Field(..., description="Whether verification passed overall")
triggered_action: Optional[str] = Field(
default=None,
description="Action triggered if failed: 'warn', 'deal_breaker', or 'regenerate'"
)
# Degradation (verification could not run)
degraded: bool = Field(
default=False,
description="True when verification could not run (claim extraction, span classification "
"or scoring error); passed/triggered_action then follow the on_flag error "
"policy instead of real verification evidence"
)
verification_error: Optional[str] = Field(
default=None,
description="Human-readable description of the error that degraded verification, if any"
)
# Diagnostics
verification_time_ms: float = Field(..., ge=0.0, description="Verification time in milliseconds")
tokens_used: int = Field(..., ge=0, description="Total tokens consumed for verification")
class ContextDocumentRef(BaseModel):
"""Reference to a previously uploaded attachment for context injection."""
upload_id: str = Field(..., min_length=8, description="Identifier returned by the attachment router")
username: str = Field(..., min_length=1, description="User identifier that owns the attachment")
intended_usage: Optional[str] = Field(default="context", description="Usage hint stored alongside the attachment")
class ImageRef(BaseModel):
"""Reference to an image attachment for vision-enabled generation."""
upload_id: str = Field(..., min_length=8, description="Attachment upload_id containing the image")
username: str = Field(..., min_length=1, description="Owner of the attachment")
detail: Optional[str] = Field(
default=None,
description="Detail level for OpenAI: 'low', 'high', 'auto'. None = provider default"
)
class Config:
json_schema_extra = {
"example": {
"upload_id": "abc123def456",
"username": "user1",
"detail": "auto"
}
}
class ImageData(BaseModel):
"""Resolved image data ready for API calls."""
base64_data: str = Field(..., description="Base64-encoded image content")
mime_type: str = Field(..., description="Image MIME type (e.g., image/jpeg, image/png)")
original_filename: str = Field(..., description="Original filename of the uploaded image")
size_bytes: int = Field(..., ge=0, description="File size in bytes")
width: Optional[int] = Field(default=None, ge=1, description="Image width in pixels")
height: Optional[int] = Field(default=None, ge=1, description="Image height in pixels")
estimated_tokens: Optional[int] = Field(default=None, ge=0, description="Estimated token cost for this image")
detail: Optional[str] = Field(default=None, description="Detail level applied for OpenAI")
class LlmAccentGuard(BaseModel):
"""Configuration for LLM-accent guard."""
mode: Literal["off", "inline", "post", "inline_post"] = Field(
default="off",
description="off = disabled; inline = generator self-audits via tool; post = synthetic QA layer; inline_post = both."
)
criteria: Optional[str] = Field(
default=None,
max_length=2000,
description="Optional user-supplied evaluation criteria appended to the default accent rubric."
)
min_score: Optional[float] = Field(
default=None,
ge=0.0,
le=10.0,
description="Minimum accent score. When None, resolved at dispatch time to max(7.0, request.min_global_score - 0.5)."
)
deal_breaker: bool = Field(
default=False,
description="If True, the synthetic accent layer is marked as deal-breaker (immediate rejection on failure)."
)
on_error: Literal["fail_closed", "fail_open"] = Field(
default="fail_closed",
description="Behavior when accent audit fails (timeout, error, parse failure): fail_closed raises AccentGuardError; fail_open accepts with warning."
)
max_inline_calls: int = Field(
default=3,
ge=1,
le=8,
description="Maximum audit_accent tool calls per tool loop."
)
force_accent_with_empty_layers: bool = Field(
default=False,
description="Allow accent post/inline_post mode on an otherwise-empty QA pipeline. Requires non-empty qa_models."
)
class AutoQAConfig(BaseModel):
"""Configuration for AI-assisted QA layer planning."""
enabled: bool = Field(
default=False,
description="When true, GranSabio plans semantic QA layers before preflight.",
)
rigor: Literal["light", "strict", "max"] = Field(
default="strict",
description="Controls Auto-QA scope and strictness: light, strict, or max.",
)
allow_request_overrides: bool = Field(
default=True,
description="Allow Auto-QA to tune approved request-level QA controls when the user did not explicitly set them.",
)
max_semantic_layers: Optional[int] = Field(
default=None,
ge=1,
le=6,
description="Optional cap for generated semantic QA layers; cannot exceed the rigor cap.",
)
manual_layer_policy: Literal["reject", "replace", "merge"] = Field(
default="reject",
description="Policy when Auto-QA is enabled and manual qa_layers are also supplied.",
)
class RequestTimeouts(BaseModel):
"""Per-request process timeout overrides in seconds."""
default_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Fallback process timeout for this request when a phase-specific value is not set.",
)
generation_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Timeout for primary generation model calls.",
)
stream_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Timeout for server-side streaming model calls.",
)
qa_model_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Timeout for one QA model evaluation attempt.",
)
qa_comprehensive_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Timeout for the outer comprehensive QA wrapper.",
)
gran_sabio_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Timeout for Gran Sabio review/regeneration model calls.",
)
long_text_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Fallback timeout for Long Text controller phases.",
)
preflight_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Timeout for preflight validation model calls.",
)
auto_qa_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Timeout for Auto-QA planning model calls.",
)
arbiter_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Timeout for Arbiter model calls.",
)
accent_audit_seconds: Optional[float] = Field(
default=None,
gt=0,
description="Timeout for LLM accent audit model calls.",
)
class ProjectInitRequest(BaseModel):
"""Optional payload used when allocating or reserving a project identifier."""
project_id: Optional[str] = Field(
default=None,
description="Client-supplied project identifier to validate and reserve; leave empty to let the API generate one.",
)
@field_validator("project_id")
@classmethod
def validate_project_id(cls, value: Optional[str]) -> Optional[str]:
if value is None:
return value
normalized = value.strip()
if not normalized:
raise ValueError("project_id cannot be blank or whitespace only")
if len(normalized) > 128:
raise ValueError("project_id must be 128 characters or fewer")
return normalized
class ExecutionPolicy(BaseModel):
"""Execution boundary requested for one generation."""
scope: Literal["default", "local_only"] = Field(
default="default",
description=(
"Execution policy scope. local_only admits and dispatches only "
"administrator-configured local endpoints."
),
)
class ContentRequest(BaseModel):