Spaces:
Sleeping
Sleeping
Download debatemind/engine/argument_tracker.py from Smzu890/DebateMind: direct link, hf CLI and curl.
- Browser
- Download file 8.92 kB
-
https://huggingface.co/spaces/Smzu890/DebateMind/resolve/main/debatemind/engine/argument_tracker.py
- Command line
-
hf download hf://spaces/Smzu890/DebateMind/debatemind/engine/argument_tracker.py
-
curl -L -o argument_tracker.py https://huggingface.co/spaces/Smzu890/DebateMind/resolve/main/debatemind/engine/argument_tracker.py
8.92 kB
| """Argument tracker for recording agent positions, promises, and coalitions. | |
| Tracks all agent actions across an episode so that argument consistency | |
| can be evaluated by the reward rubric. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| class Position: | |
| """A position stated by the agent on a topic during a turn.""" | |
| turn: int | |
| statement: str | |
| topic: str | |
| class Promise: | |
| """A promise made by the agent to a faction.""" | |
| turn: int | |
| target_faction: str | |
| content: str | |
| fulfilled: bool | None = None # None = not yet evaluated | |
| class CoalitionAgreement: | |
| """A coalition agreement formed between the agent and factions.""" | |
| turn: int | |
| factions: list[str] | |
| terms: str | |
| class ArgumentTracker: | |
| """Records and retrieves all agent positions, promises, and coalition agreements.""" | |
| def __init__(self) -> None: | |
| self.positions: list[Position] = [] | |
| self.promises: list[Promise] = [] | |
| self.coalition_agreements: list[CoalitionAgreement] = [] | |
| def record_position(self, turn: int, statement: str, topic: str) -> None: | |
| """Record a position stated by the agent.""" | |
| self.positions.append(Position(turn=turn, statement=statement, topic=topic)) | |
| def record_promise(self, turn: int, target_faction: str, content: str) -> None: | |
| """Record a promise made by the agent to a faction.""" | |
| self.promises.append( | |
| Promise(turn=turn, target_faction=target_faction, content=content) | |
| ) | |
| def record_coalition(self, turn: int, factions: list[str], terms: str) -> None: | |
| """Record a coalition agreement formed by the agent.""" | |
| self.coalition_agreements.append( | |
| CoalitionAgreement(turn=turn, factions=factions, terms=terms) | |
| ) | |
| def get_all_records(self) -> dict: | |
| """Return all tracked records as a dictionary. | |
| Returns a dict with keys 'positions', 'promises', and | |
| 'coalition_agreements', each containing the respective list. | |
| """ | |
| return { | |
| "positions": list(self.positions), | |
| "promises": list(self.promises), | |
| "coalition_agreements": list(self.coalition_agreements), | |
| } | |
| # ------------------------------------------------------------------ | |
| # Deterministic consistency scoring | |
| # ------------------------------------------------------------------ | |
| def _extract_keywords(self, text: str) -> set[str]: | |
| """Extract meaningful lowercase keywords from text. | |
| Strips common stop words and returns a set of tokens that can be | |
| used for overlap-based matching. | |
| """ | |
| _STOP_WORDS = frozenset({ | |
| "i", "we", "the", "a", "an", "is", "are", "was", "were", "be", | |
| "been", "being", "have", "has", "had", "do", "does", "did", | |
| "will", "would", "shall", "should", "may", "might", "can", | |
| "could", "to", "of", "in", "for", "on", "with", "at", "by", | |
| "from", "as", "into", "through", "during", "before", "after", | |
| "and", "but", "or", "nor", "not", "so", "yet", "both", "either", | |
| "neither", "each", "every", "all", "any", "few", "more", "most", | |
| "other", "some", "such", "no", "only", "own", "same", "than", | |
| "too", "very", "just", "because", "if", "when", "where", "how", | |
| "what", "which", "who", "whom", "this", "that", "these", "those", | |
| "it", "its", "my", "our", "your", "his", "her", "their", "them", | |
| "about", "up", "out", "then", "also", | |
| }) | |
| tokens = text.lower().split() | |
| return {t.strip(".,;:!?\"'()[]{}") for t in tokens if len(t) > 1} - _STOP_WORDS | |
| def promise_kept_score(self, bill_clauses: list[str], amendments: list) -> float: | |
| """Score whether promises were followed through in amendments/clauses. | |
| +1 for each promise whose keywords overlap with any amendment's | |
| new_text or current bill clause text. Returns ratio of kept | |
| promises, or 1.0 if no promises were made. | |
| Contributes up to +0.4 of the total consistency score. | |
| """ | |
| if not self.promises: | |
| return 1.0 | |
| clause_text = " ".join(bill_clauses).lower() | |
| amendment_texts = " ".join( | |
| getattr(a, "new_text", a.get("new_text", "")) if isinstance(a, dict) else a.new_text | |
| for a in amendments | |
| ).lower() | |
| combined = clause_text + " " + amendment_texts | |
| kept = 0 | |
| for promise in self.promises: | |
| keywords = self._extract_keywords(promise.content) | |
| if not keywords: | |
| kept += 1 | |
| continue | |
| if any(kw in combined for kw in keywords): | |
| kept += 1 | |
| promise.fulfilled = True | |
| else: | |
| promise.fulfilled = False | |
| return kept / len(self.promises) | |
| def no_contradiction_score(self) -> float: | |
| """Score whether the agent avoided contradicting itself on the same topic. | |
| Groups positions by topic, then checks for contradictory signals | |
| within each group using simple negation/opposition detection. | |
| Returns 1.0 if no contradictions found, decreasing toward 0.0 | |
| as contradictions accumulate. | |
| Contributes up to +0.4 of the total consistency score. | |
| """ | |
| if len(self.positions) < 2: | |
| return 1.0 | |
| _NEGATION_PAIRS = [ | |
| ({"support", "favor", "pro", "yes", "agree", "endorse", "back", "promote"}, | |
| {"oppose", "against", "anti", "no", "disagree", "reject", "remove", "eliminate", "cut"}), | |
| ({"increase", "expand", "raise", "strengthen", "add", "more", "mandate"}, | |
| {"decrease", "reduce", "lower", "weaken", "remove", "less", "eliminate", "cut"}), | |
| ] | |
| # Group positions by topic | |
| by_topic: dict[str, list[Position]] = {} | |
| for pos in self.positions: | |
| topic_key = pos.topic.lower().strip() | |
| by_topic.setdefault(topic_key, []).append(pos) | |
| contradictions = 0 | |
| total_pairs = 0 | |
| for topic, positions in by_topic.items(): | |
| if len(positions) < 2: | |
| continue | |
| for i in range(len(positions)): | |
| for j in range(i + 1, len(positions)): | |
| total_pairs += 1 | |
| kw_a = self._extract_keywords(positions[i].statement) | |
| kw_b = self._extract_keywords(positions[j].statement) | |
| for pos_set, neg_set in _NEGATION_PAIRS: | |
| a_positive = bool(kw_a & pos_set) | |
| a_negative = bool(kw_a & neg_set) | |
| b_positive = bool(kw_b & pos_set) | |
| b_negative = bool(kw_b & neg_set) | |
| if (a_positive and b_negative) or (a_negative and b_positive): | |
| contradictions += 1 | |
| break | |
| if total_pairs == 0: | |
| return 1.0 | |
| return max(0.0, 1.0 - (contradictions / total_pairs)) | |
| def position_repetition_score(self) -> float: | |
| """Score whether the agent restated core positions across readings. | |
| Checks if the same topic appears in positions recorded at | |
| different reading stages (approximated by turn ranges: turns 1-25 | |
| = reading 1, 26-50 = reading 2, 51+ = reading 3). Returns the | |
| ratio of topics that span multiple reading phases. | |
| Contributes up to +0.2 of the total consistency score. | |
| """ | |
| if not self.positions: | |
| return 0.0 | |
| def _reading_phase(turn: int) -> int: | |
| if turn <= 25: | |
| return 1 | |
| elif turn <= 50: | |
| return 2 | |
| else: | |
| return 3 | |
| # Map topic -> set of reading phases | |
| topic_phases: dict[str, set[int]] = {} | |
| for pos in self.positions: | |
| topic_key = pos.topic.lower().strip() | |
| topic_phases.setdefault(topic_key, set()).add(_reading_phase(pos.turn)) | |
| if not topic_phases: | |
| return 0.0 | |
| multi_phase_topics = sum( | |
| 1 for phases in topic_phases.values() if len(phases) >= 2 | |
| ) | |
| return multi_phase_topics / len(topic_phases) | |
| def compute_consistency_score( | |
| self, bill_clauses: list[str], amendments: list | |
| ) -> float: | |
| """Compute the full deterministic argument consistency score. | |
| Three sub-components weighted as: | |
| - promise_kept: 0.4 | |
| - no_contradiction: 0.4 | |
| - position_repetition: 0.2 | |
| Returns a float in [0.0, 1.0]. | |
| """ | |
| pk = self.promise_kept_score(bill_clauses, amendments) | |
| nc = self.no_contradiction_score() | |
| pr = self.position_repetition_score() | |
| return 0.4 * pk + 0.4 * nc + 0.2 * pr | |