web3-systemic-agent 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
src/engine.py ADDED
@@ -0,0 +1,281 @@
1
+ """
2
+ Condition Agent Engine orchestrating the two-stage execution pipeline:
3
+ Stage 1: Deterministic Web3 check (zero LLM token consumption)
4
+ Stage 2: Semantic LLM evaluation (triggered only when deterministic conditions match)
5
+ """
6
+
7
+ import asyncio
8
+ import inspect
9
+ import logging
10
+ import os
11
+ import sys
12
+ import time
13
+ from typing import Optional, Any, List, Dict, Union
14
+
15
+ # Ensure module search paths support running directly or as a package
16
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
17
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
18
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
19
+ for _p in (_ROOT_DIR, _SRC_DIR):
20
+ if _p not in sys.path:
21
+ sys.path.insert(0, _p)
22
+
23
+ # Guarded dotenv loading: skipped during pytest execution or if python-dotenv not installed
24
+ if "pytest" not in sys.modules:
25
+ try:
26
+ import dotenv
27
+ _env_file = os.path.join(_ROOT_DIR, ".env")
28
+ if os.path.exists(_env_file):
29
+ dotenv.load_dotenv(_env_file, override=False)
30
+ dotenv.load_dotenv(override=False)
31
+ except ImportError:
32
+ pass
33
+
34
+ try:
35
+ from src.schemas import ConditionRulePayload, FinalAgentResponse, DeterministicResult
36
+ from src.chain_inspector import ChainInspector
37
+ from src.semantic_evaluator import (
38
+ MockSemanticEvaluator,
39
+ OpenAISemanticEvaluator,
40
+ GeminiSemanticEvaluator,
41
+ get_semantic_evaluator,
42
+ enforce_decision_policy,
43
+ SemanticEvaluatorProtocol,
44
+ )
45
+ from src.storage import AgentStorage
46
+ except ImportError:
47
+ from schemas import ConditionRulePayload, FinalAgentResponse, DeterministicResult
48
+ from chain_inspector import ChainInspector
49
+ from semantic_evaluator import (
50
+ MockSemanticEvaluator,
51
+ OpenAISemanticEvaluator,
52
+ GeminiSemanticEvaluator,
53
+ get_semantic_evaluator,
54
+ enforce_decision_policy,
55
+ SemanticEvaluatorProtocol,
56
+ )
57
+ from storage import AgentStorage
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ class ConditionAgentEngine:
63
+ """
64
+ Orchestrates the two-stage pipeline:
65
+ Stage 1: Deterministic Web3 check (Zero LLM cost)
66
+ Stage 2: Semantic LLM evaluation (Triggered only if Stage 1 passes)
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ rpc_url: Optional[str] = None,
72
+ semantic_evaluator: Optional[Any] = None,
73
+ rpc_urls: Optional[Dict[int, Union[str, List[str]]]] = None,
74
+ storage: Optional[AgentStorage] = None,
75
+ ):
76
+ self.rpc_url = rpc_url
77
+ self.rpc_urls = rpc_urls or {}
78
+ self.semantic_evaluator = (
79
+ semantic_evaluator if semantic_evaluator is not None else get_semantic_evaluator()
80
+ )
81
+ self.storage = storage if storage is not None else AgentStorage()
82
+
83
+ async def process_rule(
84
+ self,
85
+ payload: ConditionRulePayload,
86
+ source: str = "engine",
87
+ job_id: Optional[str] = None,
88
+ ) -> FinalAgentResponse:
89
+ start_time = time.perf_counter()
90
+ logger.info(f"Processing rule '{payload.rule_id}' on chain {payload.chain_id.value}")
91
+
92
+ chain_id_val = (
93
+ payload.chain_id.value
94
+ if hasattr(payload.chain_id, "value")
95
+ else int(payload.chain_id)
96
+ )
97
+ resolved_rpc = None
98
+ if self.rpc_urls and chain_id_val in self.rpc_urls:
99
+ resolved_rpc = self.rpc_urls[chain_id_val]
100
+ elif self.rpc_url is not None:
101
+ resolved_rpc = self.rpc_url
102
+
103
+ inspector = ChainInspector(chain_id=chain_id_val, rpc_url=resolved_rpc)
104
+
105
+ # Stage 1: Deterministic Gatekeeper
106
+ det_result = await inspector.evaluate_deterministic(
107
+ condition=payload.deterministic,
108
+ context=payload.context_metadata,
109
+ )
110
+
111
+ if det_result.error is not None:
112
+ try:
113
+ await self.storage.log_error(
114
+ stage="stage1_rpc",
115
+ error_type="RPCError",
116
+ message=det_result.error,
117
+ rule_id=payload.rule_id,
118
+ job_id=job_id,
119
+ context=det_result.observed_data,
120
+ )
121
+ except Exception:
122
+ pass
123
+
124
+ if not det_result.passed or not payload.semantic.enabled:
125
+ logger.info(
126
+ f"Rule '{payload.rule_id}' halted at Stage 1 (Passed={det_result.passed}). LLM not invoked."
127
+ )
128
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000.0, 2)
129
+ final_response = FinalAgentResponse(
130
+ rule_id=payload.rule_id,
131
+ chain_id=chain_id_val,
132
+ deterministic_check=det_result,
133
+ llm_invoked=False,
134
+ semantic_Evaluation=None,
135
+ )
136
+ try:
137
+ await self.storage.record_evaluation(
138
+ payload,
139
+ final_response,
140
+ source=source,
141
+ job_id=job_id,
142
+ latency_ms=elapsed_ms,
143
+ )
144
+ except Exception:
145
+ pass
146
+ return final_response
147
+
148
+ # Stage 2: Semantic Evaluation (Only reached when deterministic conditions match)
149
+ logger.info(f"Stage 1 passed for '{payload.rule_id}'. Invoking Stage 2 Semantic Evaluator...")
150
+ sem_result = await self.semantic_evaluator.evaluate(
151
+ condition=payload.semantic,
152
+ observed_onchain=det_result.observed_data,
153
+ metadata=payload.context_metadata,
154
+ )
155
+
156
+ sem_result = enforce_decision_policy(
157
+ sem_result, payload.semantic.risk_threshold
158
+ )
159
+
160
+ if sem_result.flagged_issues and any(
161
+ "LLM provider failure" in issue for issue in sem_result.flagged_issues
162
+ ):
163
+ try:
164
+ await self.storage.log_error(
165
+ stage="stage2_llm",
166
+ error_type="LLMFallbackError",
167
+ message="; ".join(sem_result.flagged_issues),
168
+ rule_id=payload.rule_id,
169
+ job_id=job_id,
170
+ )
171
+ except Exception:
172
+ pass
173
+
174
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000.0, 2)
175
+ final_response = FinalAgentResponse(
176
+ rule_id=payload.rule_id,
177
+ chain_id=chain_id_val,
178
+ deterministic_check=det_result,
179
+ llm_invoked=True,
180
+ semantic_Evaluation=sem_result,
181
+ )
182
+ try:
183
+ await self.storage.record_evaluation(
184
+ payload,
185
+ final_response,
186
+ source=source,
187
+ job_id=job_id,
188
+ latency_ms=elapsed_ms,
189
+ )
190
+ except Exception:
191
+ pass
192
+ return final_response
193
+
194
+ async def process_rules_batch(
195
+ self,
196
+ payloads: List[ConditionRulePayload],
197
+ max_concurrency: int = 10,
198
+ ) -> List[FinalAgentResponse]:
199
+ """
200
+ Concurrently processes a list of ConditionRulePayload with max concurrency bounded
201
+ by an asyncio.Semaphore. Preserves original list order and isolates execution failures.
202
+ """
203
+ if not payloads:
204
+ return []
205
+
206
+ semaphore = asyncio.Semaphore(max_concurrency)
207
+
208
+ async def _process_with_semaphore(payload: ConditionRulePayload) -> FinalAgentResponse:
209
+ async with semaphore:
210
+ try:
211
+ try:
212
+ sig = inspect.signature(self.process_rule)
213
+ accepts_source = "source" in sig.parameters or any(
214
+ p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()
215
+ )
216
+ except Exception:
217
+ accepts_source = True
218
+
219
+ if accepts_source:
220
+ try:
221
+ return await self.process_rule(payload, source="batch")
222
+ except TypeError:
223
+ return await self.process_rule(payload)
224
+ else:
225
+ return await self.process_rule(payload)
226
+ except Exception as exc:
227
+ logger.exception(f"Exception while processing rule '{payload.rule_id}' in batch: {exc}")
228
+ chain_id_val = (
229
+ payload.chain_id.value
230
+ if hasattr(payload.chain_id, "value")
231
+ else int(payload.chain_id)
232
+ )
233
+ return FinalAgentResponse(
234
+ rule_id=payload.rule_id,
235
+ chain_id=chain_id_val,
236
+ deterministic_check=DeterministicResult(
237
+ passed=False,
238
+ reason=f"Execution error: {exc}",
239
+ observed_data={},
240
+ error=str(exc),
241
+ ),
242
+ llm_invoked=False,
243
+ semantic_Evaluation=None,
244
+ )
245
+
246
+ tasks = [_process_with_semaphore(p) for p in payloads]
247
+ return list(await asyncio.gather(*tasks))
248
+
249
+
250
+ async def main():
251
+ # Example JSON payload representing a DAO proposal check on Base Sepolia
252
+ sample_json_payload = {
253
+ "rule_id": "dao-gov-guard-001",
254
+ "chain_id": 84532,
255
+ "deterministic": {
256
+ "target_address": "0x4200000000000000000000000000000000000006", # WETH on Base
257
+ "min_value_wei": 1000000000000000000, # 1 ETH in Wei
258
+ "required_function_selectors": ["0xf2fde38b", "0xa9059cbb"],
259
+ "check_native_balance": False,
260
+ },
261
+ "semantic": {
262
+ "enabled": True,
263
+ "policy_prompt": "Flag any ownership transfer or treasury movement above 1 ETH lacking an external security audit.",
264
+ "risk_threshold": 7.0,
265
+ },
266
+ "context_metadata": {
267
+ "tx_value_wei": 2500000000000000000, # 2.5 ETH
268
+ "calldata": "0xf2fde38b000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
269
+ "proposal_description": "Routine parameter update to optimize treasury yield farming strategies.",
270
+ },
271
+ }
272
+
273
+ payload = ConditionRulePayload(**sample_json_payload)
274
+ engine = ConditionAgentEngine()
275
+ result = await engine.process_rule(payload)
276
+ print(result.model_dump_json(indent=2))
277
+
278
+
279
+ if __name__ == "__main__":
280
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
281
+ asyncio.run(main())