-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver_sdk.py
More file actions
296 lines (243 loc) · 10.2 KB
/
observer_sdk.py
File metadata and controls
296 lines (243 loc) · 10.2 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
"""
Observer Protocol SDK for Python / FastAPI
Provides reputation checks and middleware for agent-to-agent payments.
Works with x402, Lightning, L402, and any payment rail.
"""
import httpx
from typing import Optional, Dict, Any, Callable
from functools import wraps
import time
DEFAULT_BASE_URL = "https://api.agenticterminal.ai"
DEFAULT_FALLBACK = "review"
class ReputationData:
"""Reputation data object for dependency injection."""
def __init__(self, data: Dict[str, Any]):
self._data = data
self.agent_id = data.get("agent_id") or data.get("wallet_address")
self.verified = data.get("verified", False)
self.reputation_score = data.get("reputation_score", 0)
self.trust_tier = data.get("trust_tier", "unknown")
self.payment_history = data.get("payment_history")
self.risk_signals = data.get("risk_signals", {})
self.suggested_action = data.get("suggested_action", "review")
self._error = data.get("_error")
def __repr__(self):
return f"<ReputationData tier={self.trust_tier} score={self.reputation_score}>"
class ObserverClient:
"""
Observer Protocol client for reputation checks.
Usage:
observer = ObserverClient()
reputation = await observer.get_reputation("agent-123")
"""
def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None):
self.api_key = api_key
self.base_url = base_url or DEFAULT_BASE_URL
self._cache: Dict[str, Dict[str, Any]] = {}
def _get_cache(self, key: str) -> Optional[Dict[str, Any]]:
"""Get cached data if not expired."""
cached = self._cache.get(key)
if cached and cached["expires"] > time.time():
return cached["data"]
return None
def _set_cache(self, key: str, data: Dict[str, Any], ttl_seconds: int):
"""Cache data with TTL."""
self._cache[key] = {
"data": data,
"expires": time.time() + ttl_seconds
}
async def get_reputation(self, agent_id: str) -> Dict[str, Any]:
"""
Get reputation for an agent by ID.
Args:
agent_id: The Observer Protocol agent ID
Returns:
Reputation data dictionary
"""
cache_key = f"agent:{agent_id}"
cached = self._get_cache(cache_key)
if cached:
return cached
headers = {}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
try:
async with httpx.AsyncClient() as client:
response = await client.get(
f"{self.base_url}/observer/reputation/{agent_id}",
headers=headers,
timeout=10.0
)
if response.status_code == 404:
fallback = {
"agent_id": agent_id,
"verified": False,
"reputation_score": 0,
"trust_tier": "unknown",
"payment_history": None,
"risk_signals": {"known_bad": False},
"suggested_action": "review",
"cache_ttl_seconds": 60
}
self._set_cache(cache_key, fallback, 60)
return fallback
response.raise_for_status()
data = response.json()
self._set_cache(cache_key, data, data.get("cache_ttl_seconds", 300))
return data
except Exception as e:
# Network error - return review fallback
return {
"agent_id": agent_id,
"verified": False,
"reputation_score": 0,
"trust_tier": "unknown",
"payment_history": None,
"risk_signals": {"known_bad": False},
"suggested_action": "review",
"cache_ttl_seconds": 60,
"_error": str(e)
}
async def get_reputation_by_wallet(self, address: str) -> Dict[str, Any]:
"""
Get reputation for an agent by wallet address.
Args:
address: EVM wallet address
Returns:
Reputation data dictionary
"""
cache_key = f"wallet:{address.lower()}"
cached = self._get_cache(cache_key)
if cached:
return cached
headers = {}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
try:
async with httpx.AsyncClient() as client:
response = await client.get(
f"{self.base_url}/observer/reputation/wallet/{address}",
headers=headers,
timeout=10.0
)
if response.status_code == 404:
fallback = {
"wallet_address": address,
"verified": False,
"reputation_score": 0,
"trust_tier": "unknown",
"payment_history": None,
"risk_signals": {"known_bad": False},
"suggested_action": "review",
"cache_ttl_seconds": 60
}
self._set_cache(cache_key, fallback, 60)
return fallback
response.raise_for_status()
data = response.json()
self._set_cache(cache_key, data, data.get("cache_ttl_seconds", 300))
return data
except Exception as e:
return {
"wallet_address": address,
"verified": False,
"reputation_score": 0,
"trust_tier": "unknown",
"payment_history": None,
"risk_signals": {"known_bad": False},
"suggested_action": "review",
"cache_ttl_seconds": 60,
"_error": str(e)
}
async def reputation_middleware(self, request, call_next):
"""
ASGI middleware for reputation checking.
Usage with FastAPI:
app.middleware("http")(observer.reputation_middleware)
"""
from starlette.requests import Request
# Extract agent identity from headers
agent_id = request.headers.get("x-observer-agent-id")
wallet_address = request.headers.get("x-agent-wallet")
# For POST requests, check body for x402 payment proof
x402_from = None
if request.method == "POST":
try:
body = await request.json()
x402_from = body.get("from") or body.get("payment", {}).get("from")
except:
pass
identity = None
identity_type = None
if agent_id:
identity = agent_id
identity_type = "agent"
elif wallet_address:
identity = wallet_address
identity_type = "wallet"
elif x402_from:
identity = x402_from
identity_type = "wallet"
# Fetch reputation if identity found
reputation = None
if identity:
try:
if identity_type == "agent":
reputation = await self.get_reputation(identity)
else:
reputation = await self.get_reputation_by_wallet(identity)
except Exception:
reputation = {"suggested_action": "review", "trust_tier": "unknown"}
# Attach to request state
request.state.observer_reputation = ReputationData(reputation) if reputation else None
response = await call_next(request)
return response
def require_reputation(min_tier: str = "unknown", policy: str = "lenient"):
"""
FastAPI dependency for requiring minimum reputation tier.
Usage:
@app.get("/api/data")
async def get_data(reputation: ReputationData = Depends(require_reputation(min_tier="active"))):
return {"data": "..."}
Trust tiers (lowest to highest): unknown < new < active < established < trusted
"""
from fastapi import Request, HTTPException
TIER_ORDER = ["unknown", "new", "active", "established", "trusted"]
async def dependency(request: Request) -> ReputationData:
reputation = getattr(request.state, "observer_reputation", None)
if reputation is None:
# No reputation data - check if we need to fetch it
raise HTTPException(
status_code=400,
detail="Reputation check required. Add ObserverClient middleware."
)
# Check tier requirement
current_idx = TIER_ORDER.index(reputation.trust_tier) if reputation.trust_tier in TIER_ORDER else 0
min_idx = TIER_ORDER.index(min_tier) if min_tier in TIER_ORDER else 0
if current_idx < min_idx:
raise HTTPException(
status_code=403,
detail=f"Insufficient reputation tier. Required: {min_tier}, Got: {reputation.trust_tier}"
)
# Check suggested action
if reputation.suggested_action == "reject":
raise HTTPException(
status_code=403,
detail="Access denied: Agent reputation insufficient"
)
if reputation.suggested_action == "review" and policy == "strict":
raise HTTPException(
status_code=402,
detail={
"error": "Payment requires review",
"reason": "Agent not verified in Observer Protocol",
"registration_url": "https://agenticterminal.ai/observer/register"
}
)
return reputation
return dependency
# Convenience function for simple usage
def create_middleware(api_key: Optional[str] = None, base_url: Optional[str] = None):
"""Create a middleware function for simple usage."""
client = ObserverClient(api_key=api_key, base_url=base_url)
return client.reputation_middleware