-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreward.py
More file actions
1984 lines (1603 loc) · 62.7 KB
/
reward.py
File metadata and controls
1984 lines (1603 loc) · 62.7 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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""
SkyPlan Reward System - "The Paycheck"
A comprehensive reward system that evaluates agent work across multiple dimensions:
- Quality Bonus: Document quality assessment
- Teamwork Bonus: Collaboration and reference detection
- Completion Bonus: All-or-nothing completion reward
- Constraint Penalty: Penalties for violations
- Final Score: Normalized score in [0.0, 1.0]
"""
import hashlib
import json
import logging
from abc import ABC, abstractmethod
from collections import OrderedDict
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from enum import Enum
from os import environ
from typing import Protocol, runtime_checkable
from openai import OpenAI
try:
from .content_utils import (
count_paragraph_blocks,
has_markdown_headers,
has_markdown_lists,
keyword_coverage_ratio,
)
from .models import (
Document,
DocumentStatus,
DocumentStatusConfig,
SkyPlanAction,
)
from .workflow import (
get_all_agent_ids,
get_all_document_types,
get_required_documents,
get_workflow_entry,
)
except ImportError:
from content_utils import (
count_paragraph_blocks,
has_markdown_headers,
has_markdown_lists,
keyword_coverage_ratio,
)
from models import (
Document,
DocumentStatus,
DocumentStatusConfig,
SkyPlanAction,
)
from workflow import (
get_all_agent_ids,
get_all_document_types,
get_required_documents,
get_workflow_entry,
)
# ============================================================================
# Constants
# ============================================================================
# Default number of steps in a workflow (6 agents)
DEFAULT_WORKFLOW_STEPS = 6
# Score thresholds
SCORE_THRESHOLD_EXCELLENT = 0.8
SCORE_THRESHOLD_GOOD = 0.5
SCORE_THRESHOLD_POOR = 0.3
# Feedback thresholds
FEEDBACK_THRESHOLD = 0.5
HANDOFF_QUALITY_THRESHOLD = 0.8
# Deduction values
UNPROFESSIONAL_PATTERN_DEDUCTION = 0.1
SENTENCE_STRUCTURE_BONUS = 0.1
HANDOFF_ACKNOWLEDGMENT_BONUS = 0.1
HANDOFF_SETUP_BONUS = 0.1
CONTRADICTION_PENALTY_MULTIPLIER = 0.5
# ============================================================================
# Enums
# ============================================================================
class DifficultyLevel(str, Enum):
"""Task difficulty levels."""
EASY = "easy"
MEDIUM = "medium"
HARD = "hard"
class ReferenceLevel(str, Enum):
"""Reference quality levels."""
NONE = "none"
GENERIC = "generic"
SPECIFIC = "specific"
INTEGRATED = "integrated"
class PenaltyType(str, Enum):
"""Types of penalties."""
LENGTH = "length"
STRUCTURE = "structure"
CONTENT = "content"
ROLE = "role"
# ============================================================================
# Configuration
# ============================================================================
@dataclass
class RewardConfig:
"""Configuration for reward calculation weights and thresholds.
All values are configurable via environment variables or constructor arguments.
"""
# Quality Bonus (0.0-0.3 per document)
QUALITY_BONUS_MAX: float = 0.3
QUALITY_CONTENT_DEPTH_WEIGHT: float = 0.4
QUALITY_STRUCTURE_WEIGHT: float = 0.3
QUALITY_RELEVANCE_WEIGHT: float = 0.2
QUALITY_PROFESSIONALISM_WEIGHT: float = 0.1
# Content Depth Thresholds per Difficulty
CONTENT_DEPTH_THRESHOLDS: dict[str, tuple[int, int]] = field(
default_factory=lambda: {
DifficultyLevel.EASY: (100, 300),
DifficultyLevel.MEDIUM: (300, 800),
DifficultyLevel.HARD: (800, 2000),
}
)
# Structure Scoring Weights
STRUCTURE_HAS_HEADERS_WEIGHT: float = 0.3
STRUCTURE_HAS_LISTS_WEIGHT: float = 0.3
STRUCTURE_HAS_PARAGRAPHS_WEIGHT: float = 0.2
STRUCTURE_HAS_KEYWORDS_WEIGHT: float = 0.2
STRUCTURE_MIN_PARAGRAPHS: int = 2
# Structural Keywords
STRUCTURAL_KEYWORDS: list[str] = field(
default_factory=lambda: [
"overview", "summary", "introduction", "conclusion",
"goal", "objective", "requirement", "feature",
]
)
# Unprofessional Patterns
UNPROFESSIONAL_PATTERNS: list[str] = field(
default_factory=lambda: [
"lol", "haha", "omg", "btw", "idk", "tbh",
"!!!", "???", "??", "!!",
]
)
# Teamwork Bonus (0.0-0.2 per step)
TEAMWORK_BONUS_MAX: float = 0.2
TEAMWORK_REFERENCE_LEVELS: dict[str, float] = field(
default_factory=lambda: {
ReferenceLevel.NONE: 0.0,
ReferenceLevel.GENERIC: 0.05,
ReferenceLevel.SPECIFIC: 0.1,
ReferenceLevel.INTEGRATED: 0.2,
}
)
TEAMWORK_REFERENCE_THRESHOLD_LOW: float = 0.3
TEAMWORK_REFERENCE_THRESHOLD_HIGH: float = 0.7
# Entity Extraction
ENTITY_MIN_WORD_LENGTH: int = 3
# Handoff Phrases
ACKNOWLEDGMENT_PHRASES: list[str] = field(
default_factory=lambda: [
"based on", "building on", "following", "as discussed",
"as outlined", "per the", "according to",
]
)
SETUP_PHRASES: list[str] = field(
default_factory=lambda: [
"next step", "for the", "will be", "should",
"recommend", "suggest",
]
)
# Completion Bonus (all-or-nothing)
COMPLETION_BONUS: float = 0.3
# Penalties
PENALTY_TOO_SHORT: float = -0.1
PENALTY_EMPTY: float = -0.2
PENALTY_COPY_PASTE: float = -0.15
PENALTY_NO_HEADERS: float = -0.05
PENALTY_NO_LISTS: float = -0.05
PENALTY_POOR_FORMATTING: float = -0.05
PENALTY_MISSING_SECTION: float = -0.1
PENALTY_MISSING_KEYWORD: float = -0.05
PENALTY_CONTRADICTION: float = -0.1
PENALTY_UNREALISTIC: float = -0.1
PENALTY_WRONG_ROLE: float = -0.15
PENALTY_IGNORE_ROLE: float = -0.1
PENALTY_MAX_PER_STEP: float = -0.3
# Approval rewards for status transition actions
APPROVAL_BONUS_MAX: float = 0.2 # Maximum bonus per approval action
APPROVAL_MARK_REVIEW_BONUS: float = 0.05 # Bonus for marking documents for review
APPROVAL_APPROVE_BONUS: float = 0.15 # Bonus for approving documents
APPROVAL_REJECT_BONUS: float = 0.02 # Small bonus for rejecting (providing feedback)
APPROVAL_ALL_BONUS: float = 0.2 # Bonus for Sam approving all documents
APPROVAL_FINAL_BONUS: float = 0.2 # Bonus for final CEO approval
# Contradiction Patterns
CONTRADICTION_PHRASES: list[str] = field(
default_factory=lambda: [
"however", "but", "although", "despite",
"contrary to", "opposite of", "not consistent",
]
)
# Unrealistic Timeline Patterns
UNREALISTIC_PATTERNS: list[str] = field(
default_factory=lambda: [
"in 1 day", "in one day", "tomorrow",
"in 1 hour", "in one hour",
"instant", "immediately", "right now",
]
)
# Minimum thresholds
MIN_CONTENT_LENGTH: int = 50
MIN_REASONING_LENGTH: int = 20
MIN_HEADERS: int = 1
# LLM Configuration
LLM_BASE_URL: str = "https://integrate.api.nvidia.com/v1"
LLM_MODEL: str = "meta/llama-3.1-405b-instruct"
LLM_TEMPERATURE: float = 0.0
LLM_TIMEOUT: int = 10
LLM_CONTENT_PREVIEW_LENGTH: int = 2000
# Caching
CACHE_TTL_HOURS: int = 24
CACHE_MAX_ENTRIES: int = 1024
# Workflow configuration
WORKFLOW_STEPS: int = DEFAULT_WORKFLOW_STEPS
# Feedback Generation Rewards
FEEDBACK_GENERATION_BONUS: bool = True
COLLABORATIVE_FEEDBACK_BONUS: float = 0.02
VALIDATOR_FEEDBACK_BONUS: float = 0.08
STRATEGIC_FEEDBACK_BONUS: float = 0.10
# Feedback Resolution Rewards
FEEDBACK_RESOLUTION_BONUS: bool = True
PRIMARY_FEEDBACK_RESOLUTION_BONUS: float = 0.15
PEER_FEEDBACK_RESOLUTION_BONUS: float = 0.05
# Document Approval Rewards
DOCUMENT_APPROVAL_BONUS: bool = True
TAYLOR_APPROVAL_BONUS: float = 0.15
SAM_APPROVAL_BONUS: float = 0.15
FINAL_APPROVAL_BONUS: float = 0.50
# Normalizer bounds (calculated from config)
NORMALIZER_MIN_POSSIBLE: float = field(init=False)
NORMALIZER_MAX_POSSIBLE: float = field(init=False)
def __post_init__(self):
"""Calculate derived values after initialization."""
validator_required_docs = len(get_required_documents("taylor"))
max_task_required_approvals = max(
(len(required_docs) for required_docs in DocumentStatusConfig.APPROVAL_REQUIREMENTS.values()),
default=0,
)
authoring_steps = max(self.WORKFLOW_STEPS - 2, 0)
# Calculate normalizer bounds based on config and workflow steps
# Worst case: all penalties, no bonuses
self.NORMALIZER_MIN_POSSIBLE = (
self.PENALTY_MAX_PER_STEP * self.WORKFLOW_STEPS
)
# Best case: conservative workflow-aware ceiling for positive rewards.
self.NORMALIZER_MAX_POSSIBLE = (
authoring_steps
* (
self.QUALITY_BONUS_MAX
+ self.TEAMWORK_BONUS_MAX
+ self.COLLABORATIVE_FEEDBACK_BONUS
)
+ (
self.QUALITY_BONUS_MAX
+ self.TEAMWORK_BONUS_MAX
+ validator_required_docs * self.VALIDATOR_FEEDBACK_BONUS
+ (validator_required_docs + 1) * self.TAYLOR_APPROVAL_BONUS
+ self.APPROVAL_BONUS_MAX
)
+ (
self.QUALITY_BONUS_MAX
+ self.TEAMWORK_BONUS_MAX
+ 3 * self.STRATEGIC_FEEDBACK_BONUS
+ (max_task_required_approvals + 2) * self.SAM_APPROVAL_BONUS
+ self.FINAL_APPROVAL_BONUS
+ self.APPROVAL_BONUS_MAX
)
+ 2 * self.PRIMARY_FEEDBACK_RESOLUTION_BONUS
+ self.COMPLETION_BONUS
)
@classmethod
def from_env(cls) -> "RewardConfig":
"""Create configuration from environment variables.
Environment variables:
SKYPLAN_QUALITY_BONUS_MAX: Maximum quality bonus
SKYPLAN_TEAMWORK_BONUS_MAX: Maximum teamwork bonus
SKYPLAN_COMPLETION_BONUS: Completion bonus
API_BASE_URL: LLM base URL override
MODEL_NAME: LLM model name override
SKYPLAN_CACHE_TTL_HOURS: Cache TTL in hours
SKYPLAN_WORKFLOW_STEPS: Number of workflow steps
"""
config = cls()
# Override with environment variables if set
if "SKYPLAN_QUALITY_BONUS_MAX" in environ:
config.QUALITY_BONUS_MAX = float(environ["SKYPLAN_QUALITY_BONUS_MAX"])
if "SKYPLAN_TEAMWORK_BONUS_MAX" in environ:
config.TEAMWORK_BONUS_MAX = float(environ["SKYPLAN_TEAMWORK_BONUS_MAX"])
if "SKYPLAN_COMPLETION_BONUS" in environ:
config.COMPLETION_BONUS = float(environ["SKYPLAN_COMPLETION_BONUS"])
if "API_BASE_URL" in environ:
config.LLM_BASE_URL = environ["API_BASE_URL"]
if "MODEL_NAME" in environ:
config.LLM_MODEL = environ["MODEL_NAME"]
if "SKYPLAN_LLM_TIMEOUT" in environ:
config.LLM_TIMEOUT = int(environ["SKYPLAN_LLM_TIMEOUT"])
if "SKYPLAN_CACHE_TTL_HOURS" in environ:
config.CACHE_TTL_HOURS = int(environ["SKYPLAN_CACHE_TTL_HOURS"])
if "SKYPLAN_WORKFLOW_STEPS" in environ:
config.WORKFLOW_STEPS = int(environ["SKYPLAN_WORKFLOW_STEPS"])
# Re-calculate derived values
config.__post_init__()
return config
# Global configuration instance
reward_config = RewardConfig.from_env()
# Configure logger (module-level, not global)
logger = logging.getLogger(__name__)
# ============================================================================
# Data Models
# ============================================================================
@dataclass
class QualityScore:
"""Result of quality assessment."""
overall: float
content_depth: float
structure: float
relevance: float
professionalism: float
feedback: list[str] = field(default_factory=list)
llm_used: bool = False
@dataclass
class TeamworkScore:
"""Result of teamwork assessment."""
overall: float
references: dict[str, float] = field(default_factory=dict)
handoff_quality: float = 0.0
feedback: list[str] = field(default_factory=list)
@dataclass
class PenaltyScore:
"""Result of penalty assessment."""
total: float
penalties: dict[str, float] = field(default_factory=dict)
reasons: list[str] = field(default_factory=list)
@dataclass
class StepReward:
"""Reward for a single step."""
quality_bonus: float
teamwork_bonus: float
penalty: float
total: float
raw_total: float = 0.0
feedback_generation_reward: float = 0.0
feedback_resolution_reward: float = 0.0
document_approval_reward: float = 0.0
quality_score: QualityScore | None = None
teamwork_score: TeamworkScore | None = None
penalty_score: PenaltyScore | None = None
llm_error_penalty: float = 0.0
@dataclass
class EpisodeReward:
"""Final reward for an episode."""
step_rewards: list[StepReward] = field(default_factory=list)
completion_bonus: float = 0.0
total_raw: float = 0.0
final_score: float = 0.0
breakdown: dict[str, float] = field(default_factory=dict)
# ============================================================================
# Protocols
# ============================================================================
@runtime_checkable
class ScoreCalculator(Protocol):
"""Protocol for score calculators."""
def calculate(self, *args, **kwargs) -> float:
"""Calculate a score."""
...
# ============================================================================
# Shared Utilities
# ============================================================================
class ContentAnalyzer:
"""Shared utilities for content analysis."""
@staticmethod
def has_headers(content: str) -> bool:
"""Check if content has markdown headers.
Args:
content: Document content
Returns:
True if headers present
"""
return has_markdown_headers(content)
@staticmethod
def has_lists(content: str) -> bool:
"""Check if content has markdown lists.
Args:
content: Document content
Returns:
True if lists present
"""
return has_markdown_lists(content)
@staticmethod
def count_paragraphs(content: str) -> int:
"""Count number of paragraphs in content.
Args:
content: Document content
Returns:
Number of paragraphs
"""
return count_paragraph_blocks(content)
@staticmethod
def has_keyword(content: str, keyword: str, case_sensitive: bool = False) -> bool:
"""Check if content contains a keyword.
Args:
content: Document content
keyword: Keyword to search for
case_sensitive: Whether search is case-sensitive
Returns:
True if keyword found
"""
if case_sensitive:
return keyword in content
return keyword.lower() in content.lower()
@staticmethod
def extract_words(content: str, min_length: int = 1) -> list[str]:
"""Extract words from content.
Args:
content: Document content
min_length: Minimum word length
Returns:
List of words
"""
words = []
for line in content.split("\n"):
line = line.strip()
if not line or line.startswith("#"):
continue
for word in line.split():
word = word.strip(".,;:!?()[]{}\"'").strip()
if len(word) >= min_length:
words.append(word)
return words
# ============================================================================
# Cache
# ============================================================================
class RewardCache:
"""Cache for reward calculations to avoid redundant LLM calls."""
def __init__(self, ttl_hours: int = 24, max_entries: int = 1024):
self._cache: OrderedDict[str, tuple[QualityScore, datetime]] = OrderedDict()
self._ttl = timedelta(hours=ttl_hours)
self._max_entries = max_entries
def _hash_scope(self, content: str, scope: str) -> str:
"""Create a stable cache key from content plus evaluation scope.
Args:
content: Content to hash
scope: Context that materially affects the quality score
Returns:
SHA256 hash
"""
payload = json.dumps(
{"content": content, "scope": scope},
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(payload.encode()).hexdigest()
def get(self, content: str, scope: str) -> QualityScore | None:
"""Get cached score if available and not expired.
Args:
content: Document content to look up
scope: Evaluation context used to produce the score
Returns:
Cached QualityScore or None
"""
key = self._hash_scope(content, scope)
if key in self._cache:
score, timestamp = self._cache[key]
if datetime.now(UTC) - timestamp < self._ttl:
self._cache.move_to_end(key)
return score
# Expired, remove
del self._cache[key]
return None
def set(self, content: str, scope: str, score: QualityScore) -> None:
"""Cache a quality score.
Args:
content: Document content
scope: Evaluation context used to produce the score
score: QualityScore to cache
"""
key = self._hash_scope(content, scope)
self._cache[key] = (score, datetime.now(UTC))
self._cache.move_to_end(key)
while len(self._cache) > self._max_entries:
self._cache.popitem(last=False)
def clear(self) -> None:
"""Clear all cached entries."""
self._cache.clear()
def size(self) -> int:
"""Get number of cached entries.
Returns:
Number of cached entries
"""
return len(self._cache)
# Global cache instance
_reward_cache = RewardCache(
ttl_hours=reward_config.CACHE_TTL_HOURS,
max_entries=reward_config.CACHE_MAX_ENTRIES,
)
SCORE_EPSILON = 0.01
# ============================================================================
# Base Calculator
# ============================================================================
class BaseCalculator(ABC):
"""Base class for reward calculators."""
def __init__(self, config: RewardConfig | None = None):
self.config = config or reward_config
@abstractmethod
def calculate(self, *args, **kwargs) -> float:
"""Calculate the reward component.
Returns:
Calculated score
"""
...
# ============================================================================
# Quality Bonus Calculator
# ============================================================================
class QualityBonusCalculator(BaseCalculator):
"""Calculates quality bonus for document assessment."""
def __init__(
self,
config: RewardConfig | None = None,
use_llm: bool = True,
api_key: str | None = None,
):
super().__init__(config)
self.use_llm = use_llm
self.api_key = api_key
self._llm_client: OpenAI | None = None
self._analyzer = ContentAnalyzer()
@property
def llm_client(self) -> OpenAI | None:
"""Lazy initialization of LLM client.
Returns:
OpenAI client or None
"""
if self._llm_client is None and self.api_key and self.use_llm:
self._llm_client = OpenAI(
api_key=self.api_key,
base_url=self.config.LLM_BASE_URL,
timeout=self.config.LLM_TIMEOUT,
)
return self._llm_client
def calculate(
self,
action: SkyPlanAction,
documents: dict[str, Document],
task_keywords: list[str] | None = None,
task_difficulty: str = "medium",
) -> QualityScore:
"""Calculate quality score for a document.
Args:
action: The action taken
documents: All documents produced so far
task_keywords: Required keywords for the task
task_difficulty: Task difficulty level
Returns:
QualityScore with detailed breakdown
"""
cache_scope = self._build_cache_scope(
action=action,
task_keywords=task_keywords,
task_difficulty=task_difficulty,
)
# Check cache first
cached_score = _reward_cache.get(action.content, cache_scope)
if cached_score is not None:
return cached_score
# Try LLM-based scoring if available
if self.use_llm and self.llm_client:
llm_score = self._llm_quality_score(
action, documents, task_keywords, task_difficulty
)
if llm_score is not None:
# Cache the result
_reward_cache.set(action.content, cache_scope, llm_score)
return llm_score
# Fall back to rule-based scoring
return self._rule_based_quality_score(
action, documents, task_keywords, task_difficulty
)
def _rule_based_quality_score(
self,
action: SkyPlanAction,
documents: dict[str, Document],
task_keywords: list[str] | None = None,
task_difficulty: str = "medium",
) -> QualityScore:
"""Calculate quality score using rule-based methods.
Args:
action: The action taken
documents: All documents produced so far
task_keywords: Required keywords for the task
task_difficulty: Task difficulty level
Returns:
QualityScore with detailed breakdown
"""
content = action.content.lower()
keywords = task_keywords or []
# Calculate individual scores
content_depth = self._score_content_depth(action.content, task_difficulty)
structure = self._score_structure(action.content)
relevance = self._score_relevance(content, keywords)
professionalism = self._score_professionalism(action.content)
# Calculate weighted overall
overall = (
content_depth * self.config.QUALITY_CONTENT_DEPTH_WEIGHT
+ structure * self.config.QUALITY_STRUCTURE_WEIGHT
+ relevance * self.config.QUALITY_RELEVANCE_WEIGHT
+ professionalism * self.config.QUALITY_PROFESSIONALISM_WEIGHT
)
# Generate feedback
feedback = self._generate_quality_feedback(
content_depth, structure, relevance, professionalism
)
return QualityScore(
overall=overall,
content_depth=content_depth,
structure=structure,
relevance=relevance,
professionalism=professionalism,
feedback=feedback,
llm_used=False,
)
def _build_cache_scope(
self,
action: SkyPlanAction,
task_keywords: list[str] | None,
task_difficulty: str,
) -> str:
"""Create a cache scope that captures all scoring inputs besides content."""
return json.dumps(
{
"agent_id": action.agent_id,
"action_type": action.action_type,
"task_keywords": sorted(task_keywords or []),
"task_difficulty": task_difficulty,
"use_llm": self.use_llm,
"llm_model": self.config.LLM_MODEL,
},
sort_keys=True,
separators=(",", ":"),
)
def _score_content_depth(self, content: str, difficulty: str) -> float:
"""Score content depth based on length and substance.
Args:
content: Document content
difficulty: Task difficulty level
Returns:
Score in [0.0, 1.0]
"""
length = len(content)
# Get difficulty-based thresholds from config
thresholds = self.config.CONTENT_DEPTH_THRESHOLDS
min_len, target_len = thresholds.get(difficulty, thresholds[DifficultyLevel.MEDIUM])
if length < min_len:
return 0.0
if length >= target_len:
return 1.0
# Linear interpolation
return (length - min_len) / (target_len - min_len)
def _score_structure(self, content: str) -> float:
"""Score document structure.
Args:
content: Document content
Returns:
Score in [0.0, 1.0]
"""
score = 0.0
content_lower = content.lower()
# Has headers
if self._analyzer.has_headers(content):
score += self.config.STRUCTURE_HAS_HEADERS_WEIGHT
# Has lists
if self._analyzer.has_lists(content):
score += self.config.STRUCTURE_HAS_LISTS_WEIGHT
# Has multiple paragraphs
if self._analyzer.count_paragraphs(content) >= self.config.STRUCTURE_MIN_PARAGRAPHS:
score += self.config.STRUCTURE_HAS_PARAGRAPHS_WEIGHT
# Has structural keywords
if any(kw in content_lower for kw in self.config.STRUCTURAL_KEYWORDS):
score += self.config.STRUCTURE_HAS_KEYWORDS_WEIGHT
return min(score, 1.0)
def _score_relevance(self, content: str, keywords: list[str]) -> float:
"""Score relevance based on keyword presence.
Args:
content: Document content (lowercase)
keywords: Required keywords
Returns:
Score in [0.0, 1.0]
"""
if not keywords:
return 1.0
return keyword_coverage_ratio(content, keywords)
def _score_professionalism(self, content: str) -> float:
"""Score professionalism of writing.
Args:
content: Document content
Returns:
Score in [0.0, 1.0]
"""
score = 1.0
content_lower = content.lower()
# Deductions for unprofessional elements
for pattern in self.config.UNPROFESSIONAL_PATTERNS:
if pattern in content_lower:
score -= UNPROFESSIONAL_PATTERN_DEDUCTION
# Check for proper sentence structure
sentences = content.split(".")
if len(sentences) > 1:
# Has multiple sentences
score += SENTENCE_STRUCTURE_BONUS
return max(0.0, min(score, 1.0))
def _generate_quality_feedback(
self,
content_depth: float,
structure: float,
relevance: float,
professionalism: float,
) -> list[str]:
"""Generate feedback based on scores.
Args:
content_depth: Content depth score
structure: Structure score
relevance: Relevance score
professionalism: Professionalism score
Returns:
List of feedback strings
"""
feedback = []
if content_depth < FEEDBACK_THRESHOLD:
feedback.append("Content could be more detailed and substantive.")
if structure < FEEDBACK_THRESHOLD:
feedback.append("Document structure could be improved with more headers and sections.")
if relevance < FEEDBACK_THRESHOLD:
feedback.append("Content could be more relevant to the task requirements.")
if professionalism < FEEDBACK_THRESHOLD:
feedback.append("Writing could be more professional and clear.")
if not feedback:
feedback.append("Good quality work.")
return feedback
def _llm_quality_score(
self,
action: SkyPlanAction,
documents: dict[str, Document],
task_keywords: list[str] | None = None,
task_difficulty: str = "medium",
) -> QualityScore | None:
"""Calculate quality score using LLM.
Args:
action: The action taken
documents: All documents produced so far
task_keywords: Required keywords for the task
task_difficulty: Task difficulty level
Returns:
QualityScore with detailed breakdown, or None if LLM fails
"""
if not self.llm_client:
return None
try:
# Get agent info
agent_entry = get_workflow_entry(action.agent_id)
agent_role = agent_entry["role"] if agent_entry else "Unknown"
agent_name = agent_entry["name"] if agent_entry else action.agent_id
# Build prompt
prompt = self._build_quality_prompt(
action,
agent_name,
agent_role,
documents,
task_keywords,
task_difficulty,
)
# Call LLM
response = self.llm_client.chat.completions.create(
model=self.config.LLM_MODEL,
messages=[
{
"role": "system",
"content": "You are an expert evaluator of technical planning documents. Grade objectively and consistently.",
},
{"role": "user", "content": prompt},
],
temperature=self.config.LLM_TEMPERATURE,
response_format={"type": "json_object"},
)
# Parse response
result = json.loads(response.choices[0].message.content)
return QualityScore(
overall=float(result.get("overall_score", 0.0)),
content_depth=float(result.get("content_depth", 0.0)),
structure=float(result.get("structure", 0.0)),
relevance=float(result.get("relevance", 0.0)),
professionalism=float(result.get("professionalism", 0.0)),
feedback=result.get("feedback", []),
llm_used=True,
)
except Exception as e:
# Log error and fall back to rule-based
logger.warning(f"LLM quality scoring failed: {e}")
return None
def _build_quality_prompt(
self,
action: SkyPlanAction,
agent_name: str,
agent_role: str,
documents: dict[str, Document],