|
| 1 | +""" |
| 2 | +Cerebratech CogDx Connector |
| 3 | +Cognitive Diagnostics for Prediction Market Agents |
| 4 | +
|
| 5 | +Provides reasoning verification before trade execution. |
| 6 | +Free pilot: Use coupon code MERCURY-PILOT-2026 for $5 credit. |
| 7 | +
|
| 8 | +Docs: https://api.cerebratech.ai |
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | +import requests |
| 13 | +from typing import Dict, Any, Optional, List |
| 14 | + |
| 15 | +class CogDxClient: |
| 16 | + """ |
| 17 | + Client for Cerebratech's Cognitive Diagnostics API. |
| 18 | + |
| 19 | + Verifies agent reasoning quality before high-stakes decisions. |
| 20 | + Detects logical fallacies, calibration issues, and cognitive biases. |
| 21 | + """ |
| 22 | + |
| 23 | + BASE_URL = "https://api.cerebratech.ai" |
| 24 | + |
| 25 | + def __init__(self, coupon: Optional[str] = None, wallet: Optional[str] = None): |
| 26 | + """ |
| 27 | + Initialize CogDx client. |
| 28 | + |
| 29 | + Args: |
| 30 | + coupon: Pilot coupon code (e.g., 'MERCURY-PILOT-2026' for $5 credit) |
| 31 | + wallet: Ethereum wallet address for credit-based payments |
| 32 | + """ |
| 33 | + self.coupon = coupon or os.getenv("COGDX_COUPON") |
| 34 | + self.wallet = wallet or os.getenv("COGDX_WALLET") |
| 35 | + |
| 36 | + def _headers(self) -> Dict[str, str]: |
| 37 | + headers = {"Content-Type": "application/json"} |
| 38 | + if self.coupon: |
| 39 | + headers["X-COUPON"] = self.coupon |
| 40 | + if self.wallet: |
| 41 | + headers["X-WALLET"] = self.wallet |
| 42 | + return headers |
| 43 | + |
| 44 | + def analyze_reasoning(self, reasoning_trace: str) -> Dict[str, Any]: |
| 45 | + """ |
| 46 | + Analyze a reasoning trace for logical fallacies and validity issues. |
| 47 | + |
| 48 | + Args: |
| 49 | + reasoning_trace: The agent's reasoning text to analyze |
| 50 | + |
| 51 | + Returns: |
| 52 | + dict with: |
| 53 | + - logical_validity: float 0-1 |
| 54 | + - status: 'valid' | 'flawed' |
| 55 | + - flaws_detected: list of detected fallacies |
| 56 | + - recommendations: suggested improvements |
| 57 | + """ |
| 58 | + try: |
| 59 | + response = requests.post( |
| 60 | + f"{self.BASE_URL}/reasoning_trace_analysis", |
| 61 | + headers=self._headers(), |
| 62 | + json={"trace": reasoning_trace}, |
| 63 | + timeout=30 |
| 64 | + ) |
| 65 | + |
| 66 | + if response.status_code == 402: |
| 67 | + return { |
| 68 | + "error": "payment_required", |
| 69 | + "message": "Add COGDX_COUPON or COGDX_WALLET to env", |
| 70 | + "logical_validity": None |
| 71 | + } |
| 72 | + |
| 73 | + return response.json() |
| 74 | + |
| 75 | + except Exception as e: |
| 76 | + return {"error": str(e), "logical_validity": None} |
| 77 | + |
| 78 | + def calibration_audit( |
| 79 | + self, |
| 80 | + agent_id: str, |
| 81 | + predictions: List[Dict[str, Any]] |
| 82 | + ) -> Dict[str, Any]: |
| 83 | + """ |
| 84 | + Audit prediction calibration - do confidence levels match accuracy? |
| 85 | + |
| 86 | + Args: |
| 87 | + agent_id: Identifier for the agent |
| 88 | + predictions: List of {prompt, response, confidence} dicts |
| 89 | + |
| 90 | + Returns: |
| 91 | + dict with: |
| 92 | + - calibration_score: float 0-1 (1 = perfectly calibrated) |
| 93 | + - overconfidence_rate: float |
| 94 | + - underconfidence_rate: float |
| 95 | + - recommendations: list of strings |
| 96 | + """ |
| 97 | + try: |
| 98 | + response = requests.post( |
| 99 | + f"{self.BASE_URL}/calibration_audit", |
| 100 | + headers=self._headers(), |
| 101 | + json={ |
| 102 | + "agent_id": agent_id, |
| 103 | + "sample_outputs": predictions |
| 104 | + }, |
| 105 | + timeout=30 |
| 106 | + ) |
| 107 | + return response.json() |
| 108 | + except Exception as e: |
| 109 | + return {"error": str(e)} |
| 110 | + |
| 111 | + def bias_scan( |
| 112 | + self, |
| 113 | + agent_id: str, |
| 114 | + outputs: List[Dict[str, Any]] |
| 115 | + ) -> Dict[str, Any]: |
| 116 | + """ |
| 117 | + Scan for cognitive biases in agent outputs. |
| 118 | + |
| 119 | + Detects: anchoring, confirmation bias, availability heuristic, |
| 120 | + representativeness, sunk cost, and more. |
| 121 | + |
| 122 | + Args: |
| 123 | + agent_id: Identifier for the agent |
| 124 | + outputs: List of {prompt, response, confidence} dicts |
| 125 | + |
| 126 | + Returns: |
| 127 | + dict with: |
| 128 | + - biases_detected: list of bias findings |
| 129 | + - severity: 'low' | 'medium' | 'high' |
| 130 | + - recommendations: list of strings |
| 131 | + """ |
| 132 | + try: |
| 133 | + response = requests.post( |
| 134 | + f"{self.BASE_URL}/bias_scan", |
| 135 | + headers=self._headers(), |
| 136 | + json={ |
| 137 | + "agent_id": agent_id, |
| 138 | + "sample_outputs": outputs |
| 139 | + }, |
| 140 | + timeout=30 |
| 141 | + ) |
| 142 | + return response.json() |
| 143 | + except Exception as e: |
| 144 | + return {"error": str(e)} |
| 145 | + |
| 146 | + def verify_before_trade( |
| 147 | + self, |
| 148 | + reasoning: str, |
| 149 | + min_validity: float = 0.7 |
| 150 | + ) -> Dict[str, Any]: |
| 151 | + """ |
| 152 | + Pre-trade verification gate. |
| 153 | + |
| 154 | + Use this before executing trades to catch reasoning flaws. |
| 155 | + |
| 156 | + Args: |
| 157 | + reasoning: The reasoning trace that led to the trade decision |
| 158 | + min_validity: Minimum logical validity score to pass (default 0.7) |
| 159 | + |
| 160 | + Returns: |
| 161 | + dict with: |
| 162 | + - approved: bool |
| 163 | + - validity_score: float |
| 164 | + - issues: list of detected problems |
| 165 | + - recommendation: 'proceed' | 'review' | 'reject' |
| 166 | + """ |
| 167 | + result = self.analyze_reasoning(reasoning) |
| 168 | + |
| 169 | + if result.get("error"): |
| 170 | + # On error, default to proceed but flag for review |
| 171 | + return { |
| 172 | + "approved": True, |
| 173 | + "validity_score": None, |
| 174 | + "issues": [f"CogDx unavailable: {result.get('error')}"], |
| 175 | + "recommendation": "proceed_with_caution" |
| 176 | + } |
| 177 | + |
| 178 | + validity = result.get("logical_validity", 0) |
| 179 | + flaws = result.get("flaws_detected", []) |
| 180 | + |
| 181 | + approved = validity >= min_validity and len(flaws) == 0 |
| 182 | + |
| 183 | + if validity >= min_validity and len(flaws) == 0: |
| 184 | + recommendation = "proceed" |
| 185 | + elif validity >= 0.5: |
| 186 | + recommendation = "review" |
| 187 | + else: |
| 188 | + recommendation = "reject" |
| 189 | + |
| 190 | + return { |
| 191 | + "approved": approved, |
| 192 | + "validity_score": validity, |
| 193 | + "issues": [f.get("name", str(f)) for f in flaws], |
| 194 | + "recommendation": recommendation |
| 195 | + } |
| 196 | + |
| 197 | + |
| 198 | +def verify_trade_reasoning(reasoning: str, coupon: str = None) -> bool: |
| 199 | + """ |
| 200 | + Convenience function for quick trade verification. |
| 201 | + |
| 202 | + Usage: |
| 203 | + from agents.connectors.cogdx import verify_trade_reasoning |
| 204 | + |
| 205 | + if verify_trade_reasoning(my_reasoning, coupon="MERCURY-PILOT-2026"): |
| 206 | + execute_trade() |
| 207 | + else: |
| 208 | + print("Reasoning flagged for review") |
| 209 | + |
| 210 | + Returns True if reasoning passes verification, False otherwise. |
| 211 | + """ |
| 212 | + client = CogDxClient(coupon=coupon) |
| 213 | + result = client.verify_before_trade(reasoning) |
| 214 | + return result.get("approved", False) |
0 commit comments