-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patharbiter.py
More file actions
2314 lines (1999 loc) · 91.3 KB
/
Copy patharbiter.py
File metadata and controls
2314 lines (1999 loc) · 91.3 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
"""
Arbiter: Intelligent Conflict Resolver for Smart-Edit Operations
================================================================
The Arbiter is a per-layer arbitration system that:
- Detects conflicts between edits proposed by different QA evaluators
- Resolves conflicts intelligently using AI with original request context
- Maintains edit history per layer for informing subsequent rounds
- Prevents contradictory edits from degrading content quality
This module contains data models, enums, and prompt templates.
The actual Arbiter class implementation will be added in Phase 2.
"""
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Tuple
from pydantic import BaseModel, Field
from ai_service import AIService, is_content_filter_stop
from content_events import (
ContentEvent,
ContentEventSink,
ContentEventTemplate,
ContentPhase,
ContentStatus,
ContentSubphase,
)
from llm_routing import endpoint_id_call_kwargs
from local_execution_policy import LocalExecutionPolicyError
from model_aliasing import PromptPart
from model_capability_registry import resolve_model_capability_context
from request_timeouts import resolve_request_timeout
if TYPE_CHECKING:
from smart_edit import TextEditRange
# =============================================================================
# ENUMS
# =============================================================================
class ConflictType(str, Enum):
"""Types of conflicts between proposed edits."""
OPPOSITE_OPERATIONS = "opposite_operations" # DELETE vs REPLACE
OPPOSITE_DIRECTIONS = "opposite_directions" # EXPAND vs CONDENSE
SEVERITY_MISMATCH = "severity_mismatch" # critical vs minor
SEMANTIC_REDUNDANCY = "semantic_redundancy" # Same intent, different words
CYCLE_DETECTED = "cycle_detected" # Previously discarded edit
STALE_FRAGMENT = "stale_fragment" # exact_fragment no longer in content
ALREADY_APPLIED = "already_applied" # suggested_text already matches content
class ArbiterDecision(str, Enum):
"""Arbiter's decision for an edit."""
APPLY = "apply"
DISCARD = "discard"
class EditDistribution(str, Enum):
"""
Classification of how edits are distributed among QA evaluators.
This determines which model Arbiter uses for resolution:
- CONSENSUS, MAJORITY, SINGLE_QA → Economic model (arbiter_model)
- MINORITY, CONFLICT, TIE → Powerful model (gran_sabio_model)
Logic by QA model count:
- 1 QA model: SINGLE_QA (no comparison possible)
- 2 QA models: CONSENSUS (both agree) or TIE (any disagreement)
- 3+ QA models: CONSENSUS, MAJORITY, MINORITY, or CONFLICT
"""
CONSENSUS = "consensus" # ALL QA models propose same/compatible edits
MAJORITY = "majority" # >50% propose edit (only with 3+ models)
MINORITY = "minority" # <50% propose edit (only with 3+ models)
CONFLICT = "conflict" # Multiple incompatible edits for same target
TIE = "tie" # 50-50 split or disagreement (2 models)
SINGLE_QA = "single_qa" # Only 1 QA model (no comparison possible)
# =============================================================================
# DATA MODELS
# =============================================================================
@dataclass
class ProposedEdit:
"""An edit proposed by a QA evaluator."""
edit: "TextEditRange" # The actual edit
source_evaluator: str # Blind evaluator alias (e.g., "Evaluator A")
source_score: float # Score given by that evaluator
paragraph_key: str # Unique key for the paragraph
@dataclass
class ConflictInfo:
"""Information about a detected conflict."""
conflict_type: ConflictType
paragraph_key: str
involved_edits: List[ProposedEdit]
description: str
@dataclass
class ArbiterEditDecision:
"""Arbiter's decision for a single edit."""
edit: "TextEditRange"
decision: ArbiterDecision
reason: str
source_evaluator: str
conflict_resolved: Optional[ConflictInfo] = None
@dataclass
class EditRoundRecord:
"""Record of a single smart-edit round within a layer."""
round_number: int
proposed_edits: List[ProposedEdit]
conflicts_detected: List[ConflictInfo]
decisions: List[ArbiterEditDecision]
@property
def edits_applied(self) -> List[ArbiterEditDecision]:
"""Get all edits that were approved for application."""
return [d for d in self.decisions if d.decision == ArbiterDecision.APPLY]
@property
def edits_discarded(self) -> List[ArbiterEditDecision]:
"""Get all edits that were discarded."""
return [d for d in self.decisions if d.decision == ArbiterDecision.DISCARD]
def _enum_or_text_value(value: Any, default: str = "unknown") -> str:
"""Return enum .value when present, otherwise a stable string value."""
if value is None:
return default
raw_value = value.value if hasattr(value, "value") else value
text = str(raw_value).strip()
return text or default
def _edit_type_value(edit: Any, default: str = "unknown") -> str:
return _enum_or_text_value(getattr(edit, "edit_type", None), default)
def _get_paragraph_key_for_history(edit: "TextEditRange") -> str:
"""
Generate a unique key for an edit based on its location markers.
This is used by LayerEditHistory to track which paragraphs have been edited.
"""
# Use start_marker if available, otherwise use word indices
if hasattr(edit, 'start_marker') and edit.start_marker:
return f"phrase:{edit.start_marker[:50]}"
elif hasattr(edit, 'start_word_index') and edit.start_word_index is not None:
return f"word_idx:{edit.start_word_index}"
else:
# Fallback to issue description hash
desc = getattr(edit, 'issue_description', '') or ''
return f"desc:{hash(desc[:100])}"
@dataclass
class LayerEditHistory:
"""
Complete edit history for a single QA layer.
This tracks all edits (applied and discarded) across multiple rounds
within a single layer. The history is:
- Used to inform QA evaluators in subsequent rounds
- Used by Arbiter to detect edit cycles
- Cleared when moving to a new layer
"""
layer_name: str
rounds: List[EditRoundRecord] = field(default_factory=list)
def add_round(self, record: EditRoundRecord) -> None:
"""Add a new round record to the history."""
self.rounds.append(record)
def format_for_prompt(
self,
max_rounds: Optional[int] = None,
max_chars: Optional[int] = None
) -> str:
"""
Format history as concise summary for injection into QA/Arbiter prompts.
Args:
max_rounds: Maximum number of recent rounds to include.
If None, uses config.EDIT_HISTORY_MAX_ROUNDS.
max_chars: Maximum total characters for the formatted output.
If None, uses config.EDIT_HISTORY_MAX_CHARS.
Returns:
Formatted string like:
[PREVIOUS_EDITS_IN_LAYER]
Round 1:
- Applied: DELETE duplicate "and" (p3) - GPT-4o
- Discarded: REPLACE "and"->"but" (p3) - Claude
Reason: Conflicts with DELETE operation
[/PREVIOUS_EDITS_IN_LAYER]
"""
# Import config here to avoid circular imports
from config import config
if max_rounds is None:
max_rounds = config.EDIT_HISTORY_MAX_ROUNDS
if max_chars is None:
max_chars = config.EDIT_HISTORY_MAX_CHARS
if not self.rounds:
return ""
lines = ["[PREVIOUS_EDITS_IN_LAYER]"]
for record in self.rounds[-max_rounds:]:
lines.append(f"Round {record.round_number}:")
for decision in record.edits_applied:
op = _edit_type_value(decision.edit, "EDIT")
desc = ""
if hasattr(decision.edit, 'issue_description') and decision.edit.issue_description:
desc = decision.edit.issue_description[:50]
elif hasattr(decision.edit, 'edit_instruction') and decision.edit.edit_instruction:
desc = decision.edit.edit_instruction[:50]
lines.append(f"- Applied: {op.upper()} {desc} - {decision.source_evaluator}")
for decision in record.edits_discarded:
op = _edit_type_value(decision.edit, "EDIT")
desc = ""
if hasattr(decision.edit, 'issue_description') and decision.edit.issue_description:
desc = decision.edit.issue_description[:50]
elif hasattr(decision.edit, 'edit_instruction') and decision.edit.edit_instruction:
desc = decision.edit.edit_instruction[:50]
lines.append(f"- Discarded: {op.upper()} {desc} - {decision.source_evaluator}")
lines.append(f" Reason: {decision.reason[:80]}")
lines.append("[/PREVIOUS_EDITS_IN_LAYER]")
result = "\n".join(lines)
if len(result) > max_chars:
if max_rounds > 1:
# Truncate older rounds if too long
return self.format_for_prompt(max_rounds - 1, max_chars)
# Base case: even a single round exceeds the budget, so
# hard-truncate the text instead of returning it whole (ORQ-07).
truncated_marker = "\n... [truncated]"
if max_chars > len(truncated_marker):
return result[: max_chars - len(truncated_marker)] + truncated_marker
return result[:max_chars]
return result
def get_discarded_edit_keys(self) -> set:
"""Get paragraph keys of all previously discarded edits."""
keys = set()
for record in self.rounds:
for decision in record.edits_discarded:
keys.add(_get_paragraph_key_for_history(decision.edit))
return keys
def get_applied_edit_keys(self) -> set:
"""Get paragraph keys of all previously applied edits."""
keys = set()
for record in self.rounds:
for decision in record.edits_applied:
keys.add(_get_paragraph_key_for_history(decision.edit))
return keys
class ArbiterResult(BaseModel):
"""Result from Arbiter arbitration."""
edits_to_apply: List[Any] = Field(default_factory=list, description="TextEditRange objects to apply")
edits_discarded: List[Dict[str, Any]] = Field(default_factory=list, description="Discarded edits with reasons")
edit_decisions: List[Any] = Field(default_factory=list, exclude=True, description="Internal ArbiterEditDecision records")
conflicts_found: int = Field(default=0, description="Number of conflicts detected")
conflicts_resolved: int = Field(default=0, description="Number of conflicts resolved")
round_record: Optional[Dict[str, Any]] = Field(default=None, description="EditRoundRecord as dict for history")
arbiter_reasoning: str = Field(default="", description="Arbiter's overall reasoning")
# Distribution and escalation info
distribution: str = Field(default="single_qa", description="Edit distribution classification")
escalated_to_gran_sabio: bool = Field(default=False, description="Whether GranSabio model was used")
model_used: str = Field(default="", description="Actual model used for arbitration")
# =============================================================================
# ARBITER CONTEXT (for Phase 2)
# =============================================================================
@dataclass
class ArbiterContext:
"""
Context provided to Arbiter for making informed decisions.
This mirrors the context that GranSabio receives, ensuring
the Arbiter can make decisions aligned with the original request.
"""
# From original request
original_prompt: str # User's original instructions
content_type: str # "biography", "script", etc.
system_prompt: Optional[str] # System prompt if provided
# From current layer
layer_name: str # "Spelling", "Coherence", etc.
layer_criteria: str # Layer's evaluation criteria
layer_min_score: float # Minimum score required
# From content
current_content: str # Content after previous edits
content_excerpt: Optional[str] # Relevant fragment (to save tokens)
# From evaluators
proposed_edits: List[ProposedEdit] # All proposed edits
evaluator_scores: Dict[str, float] # Scores by model
# History
layer_history: LayerEditHistory # Previous edits in this layer
# Model escalation (for minority/conflict/tie cases)
gran_sabio_model: Optional[str] = None # Powerful model for difficult cases
qa_model_count: int = 1 # Total number of QA models (for distribution calc)
model_alias_registry: Optional[Any] = None
cancellation_token: Optional[Any] = None
# Tool-loop activation knob forwarded from ``ContentRequest.arbiter_tools_mode``.
# ``"auto"`` lets the Arbiter activate the shared ``call_ai_with_validation_tools``
# loop when the provider supports it; ``"never"`` forces the legacy single-shot
# path. Declared here (not on the constructor) so tests and callers can vary
# it per-arbitration without mutating Arbiter state.
arbiter_tools_mode: str = "auto"
original_request: Optional[Any] = None
# Layer name carried by every Arbiter content event, so a subscriber can tell
# arbitration chunks apart from the QA layers that produced the edits.
_ARBITER_STREAM_LAYER = "arbitration"
def _arbiter_content_filter_terminal_event(
template: ContentEventTemplate,
exc: Exception,
) -> ContentEvent:
"""Build the terminal ``filtered`` verdict of an arbitration attempt.
The chunks already streamed went out labelled ``draft``; this event says
that attempt is dead and why, so a consumer is not left following a draft
that never resolves. It carries no content - the draft is never resent - and
the terminal stop keeps propagating untouched.
"""
finish_reason = str(getattr(exc, "finish_reason", None) or "").strip()
reason = "Provider content policy stopped the arbitration."
if finish_reason:
reason = (
"Provider content policy stopped the arbitration "
f"(finish_reason={finish_reason})."
)
return ContentEvent(
phase=template.phase,
model=template.model,
layer=template.layer,
attempt=template.attempt,
content_status=ContentStatus.FILTERED,
reason=reason,
data={
"error_code": "content_filter",
"finish_reason": getattr(exc, "finish_reason", None),
"finish_reason_category": "content_filter",
"retryable": False,
},
)
# =============================================================================
# PROMPT TEMPLATES
# =============================================================================
ARBITER_SYSTEM_PROMPT = """You are Arbiter, an intelligent conflict resolver for text editing operations.
Your role is to analyze proposed edits from multiple AI evaluators and determine which edits should be applied. You MUST verify that each edit aligns with the user's original request.
CRITICAL: Edits can be WRONG even without conflicts. A QA model may propose an edit that:
- Contradicts the user's explicit instructions
- Changes content the user specifically requested to keep
- Applies criteria beyond the current layer's scope
- Is based on flawed reasoning
DECISION CRITERIA (in order of importance):
1. ALIGNMENT WITH ORIGINAL REQUEST - Does this edit honor what the user asked for?
2. Appropriateness for the current QA layer's criteria ONLY
3. Whether the edit's reasoning is sound
4. Severity of the issue being addressed
5. Avoiding changes that alter meaning when not intended
CONFLICT TYPES TO DETECT:
- OPPOSITE_OPERATIONS: DELETE vs REPLACE/MODIFY on same text
- OPPOSITE_DIRECTIONS: EXPAND vs CONDENSE on same paragraph
- SEVERITY_MISMATCH: Same issue marked with different severities
- SEMANTIC_REDUNDANCY: Multiple edits asking for the same thing differently
- CYCLE_DETECTED: Edit was previously discarded and is being re-proposed
- MISALIGNMENT: Edit contradicts user's original request (FALSE POSITIVE)
YOU CAN AND SHOULD REJECT ALL EDITS if they are poorly reasoned or contradict the user's intent.
OUTPUT FORMAT:
Return valid JSON with your decisions for each proposed edit.
"""
ARBITER_USER_PROMPT_TEMPLATE = """
## ORIGINAL REQUEST CONTEXT
Content Type: {content_type}
Original Instructions: {original_prompt}
{system_prompt_section}
## CURRENT QA LAYER
Layer: {layer_name}
Criteria: {layer_criteria}
Minimum Score: {layer_min_score}
## CONTENT EXCERPT (relevant section)
{content_excerpt}
## EDIT HISTORY FOR THIS LAYER
{layer_history}
## PROPOSED EDITS FROM EVALUATORS
{proposed_edits_formatted}
## EDIT DISTRIBUTION
{distribution_info}
## DETECTED POTENTIAL CONFLICTS
{conflicts_formatted}
## YOUR TASK
Analyze EACH proposed edit and decide:
1. APPLY - The edit should be applied (well-reasoned and aligned with request)
2. DISCARD - The edit should NOT be applied (explain why - misalignment, poor reasoning, etc.)
CRITICAL VERIFICATION (check for EACH edit):
1. Does this edit CONTRADICT the user's original instructions? If yes → DISCARD
2. Is the edit's reasoning sound, or is it based on a misunderstanding? If flawed → DISCARD
3. Does the edit apply criteria BEYOND this layer's scope? If yes → DISCARD
4. If this is a MINORITY edit (only one model proposed it), be extra skeptical
5. Even if multiple models agree, verify the edit doesn't violate user intent
You CAN discard ALL edits if none are appropriate. An empty edit list is valid.
RESPONSE FORMAT (JSON):
{{
"reasoning": "Your analysis - especially note any edits that contradict user intent...",
"decisions": [
{{
"edit_index": 0,
"decision": "APPLY|DISCARD",
"reason": "Specific reason - if discarding, explain the misalignment or flaw"
}}
],
"conflicts_resolved": [
{{
"conflict_index": 0,
"resolution": "How you resolved it"
}}
]
}}
"""
# =============================================================================
# ARBITER RESPONSE SCHEMA (JSON Structured Outputs contract)
# =============================================================================
# Schema conventions (mirroring ``qa_response_schemas.py``):
# - No numeric ``minimum``/``maximum`` — OpenAI strict structured outputs
# reject those keywords.
# - ``additionalProperties: false`` at every object level (root + items).
# - Every property listed in ``required`` (nullables are expressed via
# ``"type": [..., "null"]`` inside ``properties``, not by omission).
# - MERGE decision removed — only ``APPLY`` / ``DISCARD`` survive.
ARBITER_RESPONSE_SCHEMA: Dict[str, Any] = {
"type": "object",
"additionalProperties": False,
"required": ["decisions", "conflicts_resolved", "reasoning"],
"properties": {
"decisions": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": False,
"required": ["edit_index", "decision", "reason"],
"properties": {
"edit_index": {"type": "integer"},
"decision": {"type": "string", "enum": ["APPLY", "DISCARD"]},
"reason": {"type": "string"},
},
},
},
"conflicts_resolved": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": False,
"required": ["conflict_index", "resolution"],
"properties": {
"conflict_index": {"type": "integer"},
"resolution": {"type": "string"},
},
},
},
"reasoning": {"type": "string"},
},
}
# =============================================================================
# ARBITER PARSE ERROR (fail-closed exception for the hardened parser)
# =============================================================================
class ArbiterParseError(Exception):
"""Raised when the Arbiter response violates the decision contract.
Carries granular lists for telemetry so operators can diagnose which
criterion failed (missing index, duplicate, out-of-range, or an invalid
decision value). When raised inside the runtime arbitration flow the
caller fail-closes the batch — no edit is applied.
"""
def __init__(
self,
message: str,
*,
missing_indices: Optional[List[int]] = None,
duplicate_indices: Optional[List[int]] = None,
out_of_range: Optional[List[int]] = None,
invalid_decisions: Optional[List[Dict[str, Any]]] = None,
) -> None:
super().__init__(message)
self.missing_indices: List[int] = list(missing_indices or [])
self.duplicate_indices: List[int] = list(duplicate_indices or [])
self.out_of_range: List[int] = list(out_of_range or [])
self.invalid_decisions: List[Dict[str, Any]] = list(invalid_decisions or [])
def to_event_payload(self) -> Dict[str, Any]:
"""Shape the exception data into a debug-event payload dict."""
return {
"message": str(self),
"missing_indices": list(self.missing_indices),
"duplicate_indices": list(self.duplicate_indices),
"out_of_range": list(self.out_of_range),
"invalid_decisions": list(self.invalid_decisions),
}
# =============================================================================
# ARBITER CLASS (Phase 2 Implementation)
# =============================================================================
# Define operation compatibility groups for conflict detection
_DESTRUCTIVE_OPS = {"delete"}
_MODIFYING_OPS = {"replace", "rephrase", "improve", "fix_grammar", "fix_style"}
_EXPANDING_OPS = {"expand", "insert_before", "insert_after"}
_CONTRACTING_OPS = {"condense", "delete"}
class Arbiter:
"""
Intelligent conflict resolver for smart-edit operations.
The Arbiter acts at the per-layer level to:
1. Receive all edits proposed by QA evaluators
2. Classify edit distribution (consensus, majority, minority, conflict, tie)
3. ALWAYS verify edits with AI - checking alignment with original request
4. Detect and resolve conflicts between edits
5. Reject edits that contradict user intent (even without conflicts)
6. Generate history for informing subsequent rounds
7. Return curated list of edits to apply
Model escalation:
- CONSENSUS/MAJORITY/SINGLE_QA: Use economic arbiter model
- MINORITY/CONFLICT/TIE: Escalate to GranSabio model (more powerful)
"""
def __init__(
self,
ai_service: Any,
model: Optional[str] = None,
stream_callback: Optional[ContentEventSink] = None,
debug_event_callback: Optional[Callable[[str, Dict[str, Any]], Awaitable[None]]] = None,
tool_event_callback: Optional[Callable[[str, Dict[str, Any]], Awaitable[None]]] = None,
):
"""
Initialize Arbiter.
Args:
ai_service: AI service instance for making API calls
model: Model to use for conflict resolution (default from config)
stream_callback: Optional content-event sink invoked once per
provider chunk AS IT ARRIVES (C5). Every emission is a labelled
draft (``content_status="draft"``) carrying its model, the
``arbitration`` layer and the provider-reported ``is_thinking``
flag. Verdict validation is unchanged: the arbitration payload
is still parsed and schema-checked before it governs anything.
debug_event_callback: Optional pre-bound callback that persists arbitration
events to the debugger DB. Signature: async def cb(event_type, payload).
The caller is responsible for binding session_id at construction time.
tool_event_callback: Optional pre-bound callback for live tool-loop events
pushed to /stream/project. Signature: async def cb(event_type, payload).
Used when the Arbiter runs inside the shared tool loop.
"""
self.ai_service = ai_service
self._model = model
self.stream_callback = stream_callback
self._debug_event_callback = debug_event_callback
self._tool_event_callback = tool_event_callback
# One Arbiter serves every resolution of a QA run, so the attempt id of
# the labelled drafts is counted here: without it two consecutive
# arbitrations would publish under the same key and a consumer could
# concatenate the drafts of the second onto the first (C0.2).
self._stream_attempt = 0
self._logger = __import__('logging').getLogger(__name__)
@staticmethod
def _resolve_request_timeout(context: ArbiterContext) -> float:
from config import config
return resolve_request_timeout(
getattr(context, "original_request", None),
"arbiter_seconds",
settings=getattr(config, "REQUEST_TIMEOUTS", {}) or {},
config_path=("process_timeouts", "arbiter_seconds"),
fallback=float(getattr(config, "REQUEST_TIMEOUT", 12000) or 12000),
)
@staticmethod
def _resolve_output_max_tokens(
context: ArbiterContext,
selected_model: str,
) -> Tuple[int, Dict[str, Any]]:
"""Resolve Arbiter output budget from routing, config fallback, and model limits."""
from config import config
from llm_routing import resolve_call
route = resolve_call("arbiter.resolve", request=getattr(context, "original_request", None))
resolution = config.resolve_output_max_tokens(
selected_model,
routed_max_tokens=(route.params or {}).get("max_tokens"),
configured_default=getattr(config, "ARBITER_MAX_TOKENS", None),
call_id="arbiter.resolve",
)
resolved_max_tokens = resolution.get("max_tokens") if isinstance(resolution, dict) else None
if resolved_max_tokens is None:
resolved_max_tokens = config.ARBITER_MAX_TOKENS
return int(resolved_max_tokens), resolution
@staticmethod
def _resolve_escalation_model(context: ArbiterContext) -> Optional[str]:
"""Resolve the conditional escalation model through canonical routing."""
original_request = getattr(context, "original_request", None)
if original_request is not None:
try:
from llm_routing import resolve_call
routed_model = resolve_call(
"gransabio.escalation",
request=original_request,
).model
if routed_model:
return str(routed_model)
except Exception:
# Direct/unit callers may provide a lightweight request that has
# not gone through route attachment. Preserve their explicit
# compatibility value instead of inventing another model.
pass
return context.gran_sabio_model
def _resolve_arbiter_call_id(
self,
context: ArbiterContext,
distribution: EditDistribution,
selected_model: str,
) -> str:
"""Return the exact canonical call represented by this arbitration."""
if distribution in {
EditDistribution.MINORITY,
EditDistribution.CONFLICT,
EditDistribution.TIE,
}:
escalation_model = self._resolve_escalation_model(context)
if escalation_model and selected_model == escalation_model:
return "gransabio.escalation"
return "arbiter.resolve"
def _resolve_runtime_parameters(
self,
context: ArbiterContext,
selected_model: str,
*,
call_id: str,
) -> Tuple[int, Dict[str, Any], float, Optional[str], Optional[int]]:
"""Resolve the parameters the selected Arbiter call will actually use."""
from config import config
from llm_routing import LLMRoutingError, resolve_call, resolve_temperature
try:
route = resolve_call(
call_id,
request=getattr(context, "original_request", None),
)
except LLMRoutingError:
if call_id != "gransabio.escalation":
raise
route = resolve_call(
"gransabio.review",
request=getattr(context, "original_request", None),
)
if call_id == "arbiter.resolve":
max_tokens, budget_resolution = self._resolve_output_max_tokens(
context,
selected_model,
)
else:
budget_resolution = config.resolve_output_max_tokens(
selected_model,
routed_max_tokens=(route.params or {}).get("max_tokens"),
configured_default=getattr(config, "ARBITER_MAX_TOKENS", None),
call_id=call_id,
)
resolved_max_tokens = (
budget_resolution.get("max_tokens")
if isinstance(budget_resolution, dict)
else None
)
if resolved_max_tokens is None:
resolved_max_tokens = config.ARBITER_MAX_TOKENS
max_tokens = int(resolved_max_tokens)
params = route.params or {}
return (
max_tokens,
budget_resolution,
resolve_temperature(route, default=config.ARBITER_TEMPERATURE),
params.get("reasoning_effort"),
params.get("thinking_budget_tokens"),
)
@staticmethod
def _resolve_provider_options(context: ArbiterContext, *, call_id: str) -> Dict[str, Any]:
"""Resolve validated options without changing the legacy tuple contract."""
from llm_routing import LLMRoutingError, resolve_call
try:
route = resolve_call(
call_id,
request=getattr(context, "original_request", None),
)
except LLMRoutingError:
if call_id != "gransabio.escalation":
raise
route = resolve_call(
"gransabio.review",
request=getattr(context, "original_request", None),
)
return dict(route.provider_options)
@staticmethod
def _resolve_endpoint_id(context: ArbiterContext, *, call_id: str) -> Optional[str]:
"""Resolve the administrative endpoint together with a routed Arbiter call."""
from llm_routing import LLMRoutingError, resolve_call
try:
route = resolve_call(call_id, request=getattr(context, "original_request", None))
except LLMRoutingError:
if call_id != "gransabio.escalation":
raise
route = resolve_call("gransabio.review", request=getattr(context, "original_request", None))
return getattr(route, "endpoint_id", None)
async def _emit_debug_event(self, event_type: str, payload: Dict[str, Any]) -> None:
"""Persist an arbiter event to the debugger DB if a callback is bound."""
if self._debug_event_callback is None:
return
try:
await self._debug_event_callback(event_type, payload)
except Exception:
self._logger.exception("Arbiter debug_event_callback failed for %s", event_type)
@property
def model(self) -> str:
"""Get the default economic model for arbitration."""
if self._model:
return self._model
from llm_routing import resolve_call
return str(resolve_call("arbiter.resolve").model)
# =========================================================================
# DISTRIBUTION CLASSIFICATION METHODS
# =========================================================================
def _classify_distribution(
self,
proposed_edits: List[ProposedEdit],
qa_model_count: int,
conflicts: List[ConflictInfo]
) -> EditDistribution:
"""
Classify the distribution of edits among QA evaluators.
This determines which model to use for arbitration:
- CONSENSUS/MAJORITY/SINGLE_QA → Economic model
- MINORITY/CONFLICT/TIE → GranSabio model (escalation)
Args:
proposed_edits: All proposed edits
qa_model_count: Total number of QA models
conflicts: Detected conflicts
Returns:
EditDistribution classification
"""
if qa_model_count <= 0:
return EditDistribution.SINGLE_QA
# Count unique evaluators that proposed edits
evaluators_with_edits = set(pe.source_evaluator for pe in proposed_edits)
proposing_count = len(evaluators_with_edits)
# Check for conflicts first (always escalate)
if conflicts:
# With 2 models, any conflict is a TIE (disagreement between the pair)
if qa_model_count == 2:
return EditDistribution.TIE
return EditDistribution.CONFLICT
# Single QA model - no comparison possible
if qa_model_count == 1:
return EditDistribution.SINGLE_QA
# 2 QA models
if qa_model_count == 2:
if proposing_count == 0:
return EditDistribution.CONSENSUS # Both agree: no edits needed
if proposing_count == 2:
# Both proposed - check if for same paragraph (implicit conflict)
paragraphs = set(pe.paragraph_key for pe in proposed_edits)
if len(paragraphs) < len(proposed_edits):
return EditDistribution.TIE # Multiple edits for same paragraph
return EditDistribution.CONSENSUS # Different paragraphs, compatible
# Only 1 of 2 proposed - this is a TIE (disagreement)
return EditDistribution.TIE
# 3+ QA models
if proposing_count == 0:
return EditDistribution.CONSENSUS # No edits proposed
if proposing_count == qa_model_count:
return EditDistribution.CONSENSUS # All models proposed edits
# Calculate ratio
ratio = proposing_count / qa_model_count
if ratio > 0.5:
return EditDistribution.MAJORITY # >50% proposed
if proposing_count * 2 == qa_model_count:
return EditDistribution.TIE # Exactly 50% proposed
return EditDistribution.MINORITY # <50% proposed
def _select_model_for_distribution(
self,
distribution: EditDistribution,
gran_sabio_model: Optional[str]
) -> tuple:
"""
Select appropriate model based on edit distribution.
Args:
distribution: Classified distribution
gran_sabio_model: Model for escalation cases
Returns:
Tuple of (model_to_use, escalated_to_gran_sabio)
"""
# Escalate for difficult cases
if distribution in (EditDistribution.MINORITY, EditDistribution.CONFLICT, EditDistribution.TIE):
if gran_sabio_model:
self._logger.info(
f"Distribution={distribution.value}: Escalating to GranSabio model ({gran_sabio_model})"
)
return gran_sabio_model, True
else:
self._logger.warning(
f"Distribution={distribution.value}: Would escalate but no gran_sabio_model provided"
)
# Use economic model for consensus/majority/single_qa
return self.model, False
def _format_distribution_info(
self,
distribution: EditDistribution,
proposed_edits: List[ProposedEdit],
qa_model_count: int
) -> str:
"""
Format distribution information for the prompt.
Args:
distribution: Classified distribution
proposed_edits: All proposed edits
qa_model_count: Total number of QA models
Returns:
Formatted string for prompt injection
"""
evaluators_with_edits = set(pe.source_evaluator for pe in proposed_edits)
proposing_count = len(evaluators_with_edits)
lines = [
f"Total QA evaluators: {qa_model_count}",
f"Evaluators proposing edits: {proposing_count} ({', '.join(sorted(evaluators_with_edits)) if evaluators_with_edits else 'none'})",
f"Distribution: {distribution.value.upper()}"
]
if distribution == EditDistribution.MINORITY:
lines.append("WARNING: MINORITY of evaluators proposed these edits. Be extra skeptical.")
elif distribution == EditDistribution.TIE:
lines.append("WARNING: TIE/DISAGREEMENT between evaluators. Careful analysis required.")
elif distribution == EditDistribution.CONFLICT:
lines.append("WARNING: CONFLICTING edits detected. Must resolve incompatibilities.")
return "\n".join(lines)
# =========================================================================
# CONFLICT DETECTION METHODS
# =========================================================================
def _group_edits_by_paragraph(
self,
proposed_edits: List[ProposedEdit]
) -> Dict[str, List[ProposedEdit]]:
"""
Group proposed edits by their paragraph key.
Args:
proposed_edits: List of ProposedEdit objects
Returns:
Dict mapping paragraph_key to list of edits affecting that paragraph
"""
groups: Dict[str, List[ProposedEdit]] = {}
for pe in proposed_edits:
key = pe.paragraph_key
if key not in groups:
groups[key] = []
groups[key].append(pe)
return groups
def _filter_stale_edits(
self,
proposed_edits: List[ProposedEdit],
current_content: str
) -> Tuple[List[ProposedEdit], List[Dict[str, Any]], List[Tuple[int, ArbiterEditDecision]]]:
"""
Filter out stale edits that are no longer applicable to current content.
An edit is stale if:
- STALE_FRAGMENT: exact_fragment no longer exists in content (was already modified)
- ALREADY_APPLIED: suggested_text already matches content at the target location
This prevents wasted AI calls and potential corruption from applying edits
that reference outdated content state.
Args:
proposed_edits: List of proposed edits to filter
current_content: Current content after previous edits
Returns:
Tuple of (valid_edits, discarded_edits_info, discarded_decisions_by_original_index)
"""
valid_edits = []
discarded_info = []
discarded_decisions: List[Tuple[int, ArbiterEditDecision]] = []
for original_index, pe in enumerate(proposed_edits):
edit = pe.edit
# Get exact_fragment and suggested_text from edit
exact_fragment = getattr(edit, 'exact_fragment', None) or ""