iicp-client 0.2.0__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.
- iicp_client/__init__.py +35 -0
- iicp_client/_http.py +112 -0
- iicp_client/client.py +248 -0
- iicp_client/errors.py +44 -0
- iicp_client/node.py +404 -0
- iicp_client/types.py +118 -0
- iicp_client-0.2.0.dist-info/METADATA +179 -0
- iicp_client-0.2.0.dist-info/RECORD +10 -0
- iicp_client-0.2.0.dist-info/WHEEL +4 -0
- iicp_client-0.2.0.dist-info/licenses/LICENSE +180 -0
iicp_client/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""iicp-client — Official Python client SDK for the IICP protocol."""
|
|
2
|
+
|
|
3
|
+
from iicp_client.client import IicpClient
|
|
4
|
+
from iicp_client.errors import IicpError
|
|
5
|
+
from iicp_client.node import IicpNode, NodeConfig
|
|
6
|
+
from iicp_client.types import (
|
|
7
|
+
ChatMessage,
|
|
8
|
+
ChatOptions,
|
|
9
|
+
ChatResponse,
|
|
10
|
+
ClientConfig,
|
|
11
|
+
DiscoverOptions,
|
|
12
|
+
NodeList,
|
|
13
|
+
TaskAuth,
|
|
14
|
+
TaskConstraints,
|
|
15
|
+
TaskRequest,
|
|
16
|
+
TaskResponse,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__version__ = "0.2.0"
|
|
20
|
+
__all__ = [
|
|
21
|
+
"IicpClient",
|
|
22
|
+
"IicpError",
|
|
23
|
+
"IicpNode",
|
|
24
|
+
"NodeConfig",
|
|
25
|
+
"ClientConfig",
|
|
26
|
+
"TaskAuth",
|
|
27
|
+
"TaskConstraints",
|
|
28
|
+
"TaskRequest",
|
|
29
|
+
"TaskResponse",
|
|
30
|
+
"ChatMessage",
|
|
31
|
+
"ChatOptions",
|
|
32
|
+
"ChatResponse",
|
|
33
|
+
"DiscoverOptions",
|
|
34
|
+
"NodeList",
|
|
35
|
+
]
|
iicp_client/_http.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Internal HTTP helpers — TLS context, timeout normalization."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import secrets
|
|
5
|
+
import ssl
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from iicp_client.errors import IicpError, from_http
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _traceparent() -> str:
|
|
15
|
+
"""Generate a W3C traceparent header value (SDK-06).
|
|
16
|
+
|
|
17
|
+
Format: 00-<trace-id>-<parent-id>-01
|
|
18
|
+
trace-id = 16 random bytes as 32 hex chars
|
|
19
|
+
parent-id = 8 random bytes as 16 hex chars
|
|
20
|
+
flags = 01 (sampled)
|
|
21
|
+
"""
|
|
22
|
+
return f"00-{secrets.token_hex(16)}-{secrets.token_hex(8)}-01"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _tls_context(verify: bool) -> ssl.SSLContext | bool:
|
|
26
|
+
if not verify:
|
|
27
|
+
# SDK-05: tls_verify=False only permitted in debug; prod builds must verify
|
|
28
|
+
return False
|
|
29
|
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
30
|
+
ctx.minimum_version = ssl.TLSVersion.TLSv1_3
|
|
31
|
+
ctx.load_default_certs()
|
|
32
|
+
return ctx
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
async def get_json(
|
|
36
|
+
url: str,
|
|
37
|
+
*,
|
|
38
|
+
params: dict[str, Any] | None = None,
|
|
39
|
+
timeout_ms: int = 5_000,
|
|
40
|
+
component: str = "directory",
|
|
41
|
+
tls_verify: bool = True,
|
|
42
|
+
traceparent: str | None = None,
|
|
43
|
+
) -> dict[str, Any]:
|
|
44
|
+
timeout = timeout_ms / 1000.0
|
|
45
|
+
headers = {"traceparent": traceparent or _traceparent()}
|
|
46
|
+
try:
|
|
47
|
+
async with httpx.AsyncClient(
|
|
48
|
+
timeout=timeout, verify=_tls_context(tls_verify)
|
|
49
|
+
) as client:
|
|
50
|
+
resp = await client.get(url, params=params, headers=headers)
|
|
51
|
+
except httpx.TimeoutException:
|
|
52
|
+
raise IicpError(
|
|
53
|
+
code="IICP-E003",
|
|
54
|
+
message=f"Request to {url} timed out after {timeout_ms}ms",
|
|
55
|
+
component=component,
|
|
56
|
+
retryable=True,
|
|
57
|
+
) from None
|
|
58
|
+
except httpx.RequestError as exc:
|
|
59
|
+
raise IicpError(
|
|
60
|
+
code="IICP-E004",
|
|
61
|
+
message=f"Network error reaching {url}: {exc}",
|
|
62
|
+
component=component,
|
|
63
|
+
retryable=True,
|
|
64
|
+
) from exc
|
|
65
|
+
if not resp.is_success:
|
|
66
|
+
raise from_http(resp.status_code, _safe_json(resp), component)
|
|
67
|
+
return resp.json()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def post_json(
|
|
71
|
+
url: str,
|
|
72
|
+
body: dict[str, Any],
|
|
73
|
+
*,
|
|
74
|
+
timeout_ms: int = 30_000,
|
|
75
|
+
component: str = "adapter",
|
|
76
|
+
tls_verify: bool = True,
|
|
77
|
+
traceparent: str | None = None,
|
|
78
|
+
) -> tuple[dict[str, Any], int]:
|
|
79
|
+
"""Returns (response_body, elapsed_ms)."""
|
|
80
|
+
timeout = (timeout_ms / 1000.0) + 2.0
|
|
81
|
+
headers = {"traceparent": traceparent or _traceparent()}
|
|
82
|
+
t0 = time.monotonic()
|
|
83
|
+
try:
|
|
84
|
+
async with httpx.AsyncClient(
|
|
85
|
+
timeout=timeout, verify=_tls_context(tls_verify)
|
|
86
|
+
) as client:
|
|
87
|
+
resp = await client.post(url, json=body, headers=headers)
|
|
88
|
+
except httpx.TimeoutException:
|
|
89
|
+
raise IicpError(
|
|
90
|
+
code="IICP-E003",
|
|
91
|
+
message=f"Request to {url} timed out after {timeout_ms}ms",
|
|
92
|
+
component=component,
|
|
93
|
+
retryable=True,
|
|
94
|
+
) from None
|
|
95
|
+
except httpx.RequestError as exc:
|
|
96
|
+
raise IicpError(
|
|
97
|
+
code="IICP-E004",
|
|
98
|
+
message=f"Network error reaching {url}: {exc}",
|
|
99
|
+
component=component,
|
|
100
|
+
retryable=True,
|
|
101
|
+
) from exc
|
|
102
|
+
elapsed = int((time.monotonic() - t0) * 1000)
|
|
103
|
+
if not resp.is_success:
|
|
104
|
+
raise from_http(resp.status_code, _safe_json(resp), component)
|
|
105
|
+
return resp.json(), elapsed
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _safe_json(resp: httpx.Response) -> dict:
|
|
109
|
+
try:
|
|
110
|
+
return resp.json()
|
|
111
|
+
except Exception:
|
|
112
|
+
return {"message": resp.text[:200]}
|
iicp_client/client.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""IicpClient — primary entrypoint for the IICP Python SDK (ADR-016 §1)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import re
|
|
6
|
+
import uuid
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from iicp_client._http import _traceparent, get_json, post_json
|
|
10
|
+
from iicp_client.errors import IicpError
|
|
11
|
+
from iicp_client.types import (
|
|
12
|
+
ChatChoice,
|
|
13
|
+
ChatMessage,
|
|
14
|
+
ChatOptions,
|
|
15
|
+
ChatResponse,
|
|
16
|
+
ChatUsage,
|
|
17
|
+
ClientConfig,
|
|
18
|
+
DiscoverOptions,
|
|
19
|
+
Node,
|
|
20
|
+
NodeList,
|
|
21
|
+
TaskAuth,
|
|
22
|
+
TaskConstraints,
|
|
23
|
+
TaskMetrics,
|
|
24
|
+
TaskRequest,
|
|
25
|
+
TaskResponse,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
_INTENT_RE = re.compile(r"^urn:iicp:intent:[a-z0-9_:/-]+$")
|
|
29
|
+
_MAX_TIMEOUT_MS = 120_000
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class IicpClient:
|
|
33
|
+
"""Discover → select → submit client for the IICP protocol.
|
|
34
|
+
|
|
35
|
+
Implements ADR-016 §1 (SDK-01..SDK-06 conformance rules).
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, config: ClientConfig | None = None) -> None:
|
|
39
|
+
self._cfg = config or ClientConfig()
|
|
40
|
+
if self._cfg.timeout_ms > _MAX_TIMEOUT_MS:
|
|
41
|
+
# SDK-04: reject oversized timeouts at construction time
|
|
42
|
+
raise ValueError(
|
|
43
|
+
f"timeout_ms must be ≤ {_MAX_TIMEOUT_MS}; got {self._cfg.timeout_ms}"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# ------------------------------------------------------------------
|
|
47
|
+
# Public async API
|
|
48
|
+
# ------------------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
async def discover_async(
|
|
51
|
+
self,
|
|
52
|
+
intent: str,
|
|
53
|
+
options: DiscoverOptions | None = None,
|
|
54
|
+
*,
|
|
55
|
+
traceparent: str | None = None,
|
|
56
|
+
) -> NodeList:
|
|
57
|
+
"""Discover nodes capable of handling *intent*."""
|
|
58
|
+
opts = options or DiscoverOptions()
|
|
59
|
+
params: dict[str, Any] = {"limit": min(opts.limit, 50)}
|
|
60
|
+
params["intent"] = intent
|
|
61
|
+
if opts.region or self._cfg.region:
|
|
62
|
+
params["region"] = opts.region or self._cfg.region
|
|
63
|
+
if opts.qos:
|
|
64
|
+
params["qos"] = opts.qos
|
|
65
|
+
if opts.min_reputation is not None:
|
|
66
|
+
params["min_reputation"] = opts.min_reputation
|
|
67
|
+
if opts.model:
|
|
68
|
+
params["model"] = opts.model
|
|
69
|
+
|
|
70
|
+
import time
|
|
71
|
+
t0 = time.monotonic()
|
|
72
|
+
data = await get_json(
|
|
73
|
+
f"{self._cfg.directory_url}/v1/discover",
|
|
74
|
+
params=params,
|
|
75
|
+
timeout_ms=5_000,
|
|
76
|
+
component="directory",
|
|
77
|
+
tls_verify=self._cfg.tls_verify,
|
|
78
|
+
traceparent=traceparent,
|
|
79
|
+
)
|
|
80
|
+
elapsed = int((time.monotonic() - t0) * 1000)
|
|
81
|
+
|
|
82
|
+
raw_nodes = data.get("nodes", [])
|
|
83
|
+
nodes = [
|
|
84
|
+
Node(
|
|
85
|
+
node_id=n["node_id"],
|
|
86
|
+
endpoint=n["endpoint"],
|
|
87
|
+
score=float(n.get("score", 0.0)),
|
|
88
|
+
available=bool(n.get("available", True)),
|
|
89
|
+
region=n.get("region", ""),
|
|
90
|
+
latency_estimate_ms=n.get("latency_estimate_ms"),
|
|
91
|
+
reputation_score=n.get("reputation_score"),
|
|
92
|
+
)
|
|
93
|
+
for n in raw_nodes
|
|
94
|
+
]
|
|
95
|
+
return NodeList(nodes=nodes, query_ms=elapsed)
|
|
96
|
+
|
|
97
|
+
async def submit_async(self, request: TaskRequest) -> TaskResponse:
|
|
98
|
+
"""Discover → select best node → submit task.
|
|
99
|
+
|
|
100
|
+
Retries up to max_retries on transient errors (SDK-01).
|
|
101
|
+
A single W3C traceparent is generated per submit call and propagated
|
|
102
|
+
to both the discover request and the node POST (SDK-06).
|
|
103
|
+
"""
|
|
104
|
+
self._validate_intent(request.intent)
|
|
105
|
+
tp = _traceparent() # SDK-06: one trace per operation, shared across calls
|
|
106
|
+
node_list = await self.discover_async(
|
|
107
|
+
request.intent,
|
|
108
|
+
DiscoverOptions(
|
|
109
|
+
region=request.constraints.region or self._cfg.region,
|
|
110
|
+
qos=request.constraints.qos,
|
|
111
|
+
),
|
|
112
|
+
traceparent=tp,
|
|
113
|
+
)
|
|
114
|
+
if not node_list.nodes:
|
|
115
|
+
raise IicpError(
|
|
116
|
+
code="IICP-E006",
|
|
117
|
+
message=f"No nodes available for intent {request.intent!r}",
|
|
118
|
+
component="directory",
|
|
119
|
+
retryable=True,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
node = node_list.nodes[0] # highest score first (directory sorts by score)
|
|
123
|
+
task_id = str(uuid.uuid4())
|
|
124
|
+
body: dict[str, Any] = {
|
|
125
|
+
"task_id": task_id,
|
|
126
|
+
"intent": request.intent,
|
|
127
|
+
"payload": request.payload,
|
|
128
|
+
"constraints": {
|
|
129
|
+
"timeout_ms": request.constraints.timeout_ms,
|
|
130
|
+
"qos": request.constraints.qos,
|
|
131
|
+
},
|
|
132
|
+
}
|
|
133
|
+
if request.auth.node_token:
|
|
134
|
+
body["auth"] = {"node_token": request.auth.node_token}
|
|
135
|
+
|
|
136
|
+
last_exc: IicpError | None = None
|
|
137
|
+
for attempt in range(self._cfg.max_retries):
|
|
138
|
+
try:
|
|
139
|
+
raw, elapsed = await post_json(
|
|
140
|
+
f"{node.endpoint}/v1/task",
|
|
141
|
+
body,
|
|
142
|
+
timeout_ms=request.constraints.timeout_ms,
|
|
143
|
+
component="adapter",
|
|
144
|
+
tls_verify=self._cfg.tls_verify,
|
|
145
|
+
traceparent=tp,
|
|
146
|
+
)
|
|
147
|
+
return TaskResponse(
|
|
148
|
+
task_id=raw.get("task_id", task_id),
|
|
149
|
+
status=raw.get("status", "success"),
|
|
150
|
+
result=raw.get("result"),
|
|
151
|
+
metrics=TaskMetrics(
|
|
152
|
+
latency_ms=elapsed,
|
|
153
|
+
tokens_used=raw.get("usage", {}).get("total_tokens"),
|
|
154
|
+
node_id=node.node_id,
|
|
155
|
+
),
|
|
156
|
+
)
|
|
157
|
+
except IicpError as exc:
|
|
158
|
+
last_exc = exc
|
|
159
|
+
if not exc.retryable or attempt == self._cfg.max_retries - 1:
|
|
160
|
+
raise
|
|
161
|
+
await asyncio.sleep(0.5 * (attempt + 1))
|
|
162
|
+
|
|
163
|
+
raise last_exc # type: ignore[misc]
|
|
164
|
+
|
|
165
|
+
async def chat_async(
|
|
166
|
+
self,
|
|
167
|
+
messages: list[ChatMessage],
|
|
168
|
+
options: ChatOptions | None = None,
|
|
169
|
+
) -> ChatResponse:
|
|
170
|
+
"""OpenAI-compatible chat over urn:iicp:intent:llm:chat:v1 (SDK-02)."""
|
|
171
|
+
opts = options or ChatOptions()
|
|
172
|
+
payload: dict[str, Any] = {
|
|
173
|
+
"messages": [{"role": m.role, "content": m.content} for m in messages],
|
|
174
|
+
}
|
|
175
|
+
if opts.model:
|
|
176
|
+
payload["model"] = opts.model
|
|
177
|
+
if opts.max_tokens is not None:
|
|
178
|
+
payload["max_tokens"] = opts.max_tokens
|
|
179
|
+
if opts.temperature is not None:
|
|
180
|
+
payload["temperature"] = opts.temperature
|
|
181
|
+
|
|
182
|
+
response = await self.submit_async(
|
|
183
|
+
TaskRequest(
|
|
184
|
+
intent="urn:iicp:intent:llm:chat:v1",
|
|
185
|
+
payload=payload,
|
|
186
|
+
constraints=TaskConstraints(
|
|
187
|
+
timeout_ms=opts.timeout_ms or self._cfg.timeout_ms,
|
|
188
|
+
qos=opts.qos,
|
|
189
|
+
),
|
|
190
|
+
auth=TaskAuth(node_token=opts.node_token),
|
|
191
|
+
)
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
result = response.result or {}
|
|
195
|
+
raw_choices = result.get("choices", [])
|
|
196
|
+
choices = [
|
|
197
|
+
ChatChoice(
|
|
198
|
+
message=ChatMessage(
|
|
199
|
+
role=c.get("message", {}).get("role", "assistant"),
|
|
200
|
+
content=c.get("message", {}).get("content", ""),
|
|
201
|
+
),
|
|
202
|
+
finish_reason=c.get("finish_reason", "stop"),
|
|
203
|
+
)
|
|
204
|
+
for c in raw_choices
|
|
205
|
+
]
|
|
206
|
+
raw_usage = result.get("usage", {})
|
|
207
|
+
return ChatResponse(
|
|
208
|
+
id=response.task_id,
|
|
209
|
+
choices=choices,
|
|
210
|
+
usage=ChatUsage(
|
|
211
|
+
prompt_tokens=raw_usage.get("prompt_tokens", 0),
|
|
212
|
+
completion_tokens=raw_usage.get("completion_tokens", 0),
|
|
213
|
+
total_tokens=raw_usage.get("total_tokens", 0),
|
|
214
|
+
),
|
|
215
|
+
model=result.get("model", opts.model or ""),
|
|
216
|
+
iicp_node_id=response.metrics.node_id,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
# ------------------------------------------------------------------
|
|
220
|
+
# Sync wrappers (runs asyncio.run internally)
|
|
221
|
+
# ------------------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
def discover(self, intent: str, options: DiscoverOptions | None = None) -> NodeList:
|
|
224
|
+
return asyncio.run(self.discover_async(intent, options))
|
|
225
|
+
|
|
226
|
+
def submit(self, request: TaskRequest) -> TaskResponse:
|
|
227
|
+
return asyncio.run(self.submit_async(request))
|
|
228
|
+
|
|
229
|
+
def chat(
|
|
230
|
+
self,
|
|
231
|
+
messages: list[ChatMessage],
|
|
232
|
+
options: ChatOptions | None = None,
|
|
233
|
+
) -> ChatResponse:
|
|
234
|
+
return asyncio.run(self.chat_async(messages, options))
|
|
235
|
+
|
|
236
|
+
# ------------------------------------------------------------------
|
|
237
|
+
# Internal helpers
|
|
238
|
+
# ------------------------------------------------------------------
|
|
239
|
+
|
|
240
|
+
def _validate_intent(self, intent: str) -> None:
|
|
241
|
+
# SDK-03: validate URN format before sending
|
|
242
|
+
if not _INTENT_RE.match(intent):
|
|
243
|
+
raise IicpError(
|
|
244
|
+
code="IICP-E001",
|
|
245
|
+
message=f"Invalid intent URN: {intent!r}. Must match urn:iicp:intent:*",
|
|
246
|
+
component="proxy",
|
|
247
|
+
retryable=False,
|
|
248
|
+
)
|
iicp_client/errors.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""IICP structured error type (ADR-016 §3)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class IicpError(Exception):
|
|
6
|
+
"""Typed error surface — never exposes raw HTTP details to callers."""
|
|
7
|
+
|
|
8
|
+
def __init__(
|
|
9
|
+
self,
|
|
10
|
+
code: str,
|
|
11
|
+
message: str,
|
|
12
|
+
component: str,
|
|
13
|
+
retryable: bool = False,
|
|
14
|
+
http_status: int | None = None,
|
|
15
|
+
) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.code = code
|
|
18
|
+
self.message = message
|
|
19
|
+
self.component = component
|
|
20
|
+
self.retryable = retryable
|
|
21
|
+
self.http_status = http_status
|
|
22
|
+
|
|
23
|
+
def __repr__(self) -> str:
|
|
24
|
+
return (
|
|
25
|
+
f"IicpError(code={self.code!r}, component={self.component!r}, "
|
|
26
|
+
f"retryable={self.retryable}, http_status={self.http_status})"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# Well-known error codes (Phase 1 range, IICP-E001..E010)
|
|
31
|
+
_RETRYABLE_CODES = {"IICP-E003", "IICP-E004", "IICP-E005"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def from_http(status: int, body: dict, component: str) -> IicpError:
|
|
35
|
+
"""Build a typed IicpError from an HTTP response body."""
|
|
36
|
+
code = body.get("code", f"IICP-E{status:03d}")
|
|
37
|
+
message = body.get("message", body.get("error", "Unexpected error"))
|
|
38
|
+
return IicpError(
|
|
39
|
+
code=code,
|
|
40
|
+
message=message,
|
|
41
|
+
component=component,
|
|
42
|
+
retryable=code in _RETRYABLE_CODES or status in (429, 503),
|
|
43
|
+
http_status=status,
|
|
44
|
+
)
|
iicp_client/node.py
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
"""IICP provider node — registration, heartbeats, and task serving.
|
|
2
|
+
|
|
3
|
+
Endpoints served by ``IicpNode.serve()``:
|
|
4
|
+
|
|
5
|
+
+---------+----------------+----------------------------------------------+
|
|
6
|
+
| Method | Path | Description |
|
|
7
|
+
+=========+================+==============================================+
|
|
8
|
+
| POST | /v1/task | Handle an inference task (IICP-E021 gate, |
|
|
9
|
+
| | | IICP-E011 nonce replay, W3C traceparent) |
|
|
10
|
+
+---------+----------------+----------------------------------------------+
|
|
11
|
+
| GET | /iicp/health | Liveness / capacity (always 200) |
|
|
12
|
+
+---------+----------------+----------------------------------------------+
|
|
13
|
+
| GET | /metrics | Prometheus text (503 if client absent) |
|
|
14
|
+
+---------+----------------+----------------------------------------------+
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
import threading
|
|
22
|
+
import time
|
|
23
|
+
from collections.abc import Callable, Coroutine
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import httpx
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
_DEFAULT_TIMEOUT = 5.0
|
|
33
|
+
_HEARTBEAT_INTERVAL = 30
|
|
34
|
+
_NONCE_TTL = 300
|
|
35
|
+
_REGISTER_PATH = "/v1/register"
|
|
36
|
+
_HEARTBEAT_PATH = "/api/v1/heartbeat"
|
|
37
|
+
|
|
38
|
+
# Lazy Prometheus import — None until first call, False when unavailable.
|
|
39
|
+
_prom_mod: Any = None
|
|
40
|
+
# Singleton: avoids duplicate metric registration across IicpNode instances.
|
|
41
|
+
_global_metrics: _Metrics | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _get_prom() -> Any:
|
|
45
|
+
global _prom_mod
|
|
46
|
+
if _prom_mod is None:
|
|
47
|
+
try:
|
|
48
|
+
import prometheus_client as _p
|
|
49
|
+
|
|
50
|
+
_prom_mod = _p
|
|
51
|
+
except ImportError:
|
|
52
|
+
_prom_mod = False
|
|
53
|
+
return _prom_mod if _prom_mod is not False else None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class NodeConfig:
|
|
58
|
+
node_id: str
|
|
59
|
+
endpoint: str
|
|
60
|
+
intent: str
|
|
61
|
+
model: str | None = None
|
|
62
|
+
region: str | None = None
|
|
63
|
+
capabilities: list[str] = field(default_factory=list)
|
|
64
|
+
directory_url: str = "https://iicp.network/api"
|
|
65
|
+
timeout: float = _DEFAULT_TIMEOUT
|
|
66
|
+
max_concurrent: int = 4
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
TaskHandler = Callable[[dict[str, Any]], Coroutine[Any, Any, dict[str, Any]]]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class _Metrics:
|
|
73
|
+
"""Prometheus metrics wrapper — no-ops when prometheus_client is absent."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, prom: Any) -> None:
|
|
76
|
+
self._enabled = prom is not None
|
|
77
|
+
if not self._enabled:
|
|
78
|
+
return
|
|
79
|
+
self.tasks_total = prom.Counter(
|
|
80
|
+
"iicp_tasks_total",
|
|
81
|
+
"Total IICP tasks handled",
|
|
82
|
+
["status", "intent", "qos"],
|
|
83
|
+
)
|
|
84
|
+
self.task_latency_ms = prom.Histogram(
|
|
85
|
+
"iicp_task_latency_ms",
|
|
86
|
+
"IICP task processing latency (ms)",
|
|
87
|
+
["intent", "qos"],
|
|
88
|
+
buckets=[50, 100, 250, 500, 1_000, 2_500, 5_000, 10_000, 30_000],
|
|
89
|
+
)
|
|
90
|
+
self.tokens_used_total = prom.Counter(
|
|
91
|
+
"iicp_tokens_used_total",
|
|
92
|
+
"Total tokens consumed",
|
|
93
|
+
["intent"],
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
def observe(
|
|
97
|
+
self,
|
|
98
|
+
status: str,
|
|
99
|
+
intent: str,
|
|
100
|
+
qos: str,
|
|
101
|
+
latency_ms: float,
|
|
102
|
+
tokens: int = 0,
|
|
103
|
+
) -> None:
|
|
104
|
+
if not self._enabled:
|
|
105
|
+
return
|
|
106
|
+
self.tasks_total.labels(status=status, intent=intent, qos=qos).inc()
|
|
107
|
+
self.task_latency_ms.labels(intent=intent, qos=qos).observe(latency_ms)
|
|
108
|
+
if tokens:
|
|
109
|
+
self.tokens_used_total.labels(intent=intent).inc(tokens)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _get_metrics() -> _Metrics:
|
|
113
|
+
global _global_metrics
|
|
114
|
+
if _global_metrics is None:
|
|
115
|
+
_global_metrics = _Metrics(_get_prom())
|
|
116
|
+
return _global_metrics
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class IicpNode:
|
|
120
|
+
"""IICP provider node — registration, heartbeats, and task serving.
|
|
121
|
+
|
|
122
|
+
Example::
|
|
123
|
+
|
|
124
|
+
async def my_handler(task: dict) -> dict:
|
|
125
|
+
prompt = task["payload"]["messages"][-1]["content"]
|
|
126
|
+
return {"result": {"content": f"Echo: {prompt}"}}
|
|
127
|
+
|
|
128
|
+
node = IicpNode(NodeConfig(
|
|
129
|
+
node_id="my-node-001",
|
|
130
|
+
endpoint="https://my-host.example.com",
|
|
131
|
+
intent="urn:iicp:intent:llm:chat:v1",
|
|
132
|
+
max_concurrent=4,
|
|
133
|
+
))
|
|
134
|
+
token = await node.register()
|
|
135
|
+
await node.serve(my_handler, port=8020, node_token=token)
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
def __init__(self, config: NodeConfig) -> None:
|
|
139
|
+
self._cfg = config
|
|
140
|
+
self._http = httpx.AsyncClient(timeout=config.timeout)
|
|
141
|
+
self._sem = threading.Semaphore(config.max_concurrent)
|
|
142
|
+
self._active_jobs = 0
|
|
143
|
+
self._jobs_lock = threading.Lock()
|
|
144
|
+
self._nonces: dict[str, float] = {}
|
|
145
|
+
self._nonces_lock = threading.Lock()
|
|
146
|
+
self._metrics = _get_metrics()
|
|
147
|
+
|
|
148
|
+
# ── Directory operations ──────────────────────────────────────────────
|
|
149
|
+
|
|
150
|
+
async def register(self) -> str:
|
|
151
|
+
"""Register this node with the directory and return the node_token."""
|
|
152
|
+
payload: dict[str, Any] = {
|
|
153
|
+
"node_id": self._cfg.node_id,
|
|
154
|
+
"endpoint": self._cfg.endpoint,
|
|
155
|
+
"intent": self._cfg.intent,
|
|
156
|
+
}
|
|
157
|
+
if self._cfg.model:
|
|
158
|
+
payload["model"] = self._cfg.model
|
|
159
|
+
if self._cfg.region:
|
|
160
|
+
payload["region"] = self._cfg.region
|
|
161
|
+
if self._cfg.capabilities:
|
|
162
|
+
payload["capabilities"] = self._cfg.capabilities
|
|
163
|
+
|
|
164
|
+
resp = await self._http.post(
|
|
165
|
+
f"{self._cfg.directory_url.rstrip('/')}{_REGISTER_PATH}",
|
|
166
|
+
json=payload,
|
|
167
|
+
)
|
|
168
|
+
resp.raise_for_status()
|
|
169
|
+
data = resp.json()
|
|
170
|
+
token = data.get("node_token") or data.get("token")
|
|
171
|
+
if not token:
|
|
172
|
+
raise RuntimeError(f"Directory did not return node_token: {data}")
|
|
173
|
+
logger.info("Registered node %s, token acquired", self._cfg.node_id)
|
|
174
|
+
return str(token)
|
|
175
|
+
|
|
176
|
+
async def heartbeat(self, node_token: str) -> None:
|
|
177
|
+
"""Send a single heartbeat to the directory."""
|
|
178
|
+
resp = await self._http.post(
|
|
179
|
+
f"{self._cfg.directory_url.rstrip('/')}{_HEARTBEAT_PATH}",
|
|
180
|
+
json={
|
|
181
|
+
"node_id": self._cfg.node_id,
|
|
182
|
+
"node_token": node_token,
|
|
183
|
+
"status": "available",
|
|
184
|
+
},
|
|
185
|
+
)
|
|
186
|
+
resp.raise_for_status()
|
|
187
|
+
|
|
188
|
+
async def _heartbeat_loop(self, node_token: str) -> None:
|
|
189
|
+
while True:
|
|
190
|
+
await asyncio.sleep(_HEARTBEAT_INTERVAL)
|
|
191
|
+
try:
|
|
192
|
+
await self.heartbeat(node_token)
|
|
193
|
+
logger.debug("Heartbeat sent for %s", self._cfg.node_id)
|
|
194
|
+
except Exception as exc:
|
|
195
|
+
logger.warning("Heartbeat failed: %s", exc)
|
|
196
|
+
|
|
197
|
+
# ── Nonce replay protection ───────────────────────────────────────────
|
|
198
|
+
|
|
199
|
+
def _check_nonce(self, nonce: str | None) -> bool:
|
|
200
|
+
"""Return True if nonce is fresh (first use within TTL window)."""
|
|
201
|
+
if not nonce:
|
|
202
|
+
return True
|
|
203
|
+
now = time.monotonic()
|
|
204
|
+
with self._nonces_lock:
|
|
205
|
+
expired = [k for k, v in self._nonces.items() if v < now]
|
|
206
|
+
for k in expired:
|
|
207
|
+
del self._nonces[k]
|
|
208
|
+
if nonce in self._nonces:
|
|
209
|
+
return False
|
|
210
|
+
self._nonces[nonce] = now + _NONCE_TTL
|
|
211
|
+
return True
|
|
212
|
+
|
|
213
|
+
# ── HTTP server ───────────────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
async def serve(
|
|
216
|
+
self,
|
|
217
|
+
handler: TaskHandler,
|
|
218
|
+
host: str = "0.0.0.0",
|
|
219
|
+
port: int = 8020,
|
|
220
|
+
node_token: str | None = None,
|
|
221
|
+
) -> None:
|
|
222
|
+
"""Start the task server (blocks until interrupted).
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
handler: ``async def handler(task: dict) -> dict``
|
|
226
|
+
host: Bind address (default ``0.0.0.0``).
|
|
227
|
+
port: Bind port (default 8020).
|
|
228
|
+
node_token: If provided, starts a background heartbeat loop.
|
|
229
|
+
"""
|
|
230
|
+
loop = asyncio.get_event_loop()
|
|
231
|
+
node = self
|
|
232
|
+
|
|
233
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
234
|
+
def log_message(self, fmt: str, *args: Any) -> None: # noqa: N802
|
|
235
|
+
logger.debug(fmt, *args)
|
|
236
|
+
|
|
237
|
+
def do_GET(self) -> None: # noqa: N802
|
|
238
|
+
if self.path == "/iicp/health":
|
|
239
|
+
self._health()
|
|
240
|
+
elif self.path == "/metrics":
|
|
241
|
+
self._prometheus()
|
|
242
|
+
else:
|
|
243
|
+
self.send_error(404)
|
|
244
|
+
|
|
245
|
+
def do_POST(self) -> None: # noqa: N802
|
|
246
|
+
if self.path == "/v1/task":
|
|
247
|
+
self._task()
|
|
248
|
+
else:
|
|
249
|
+
self.send_error(404)
|
|
250
|
+
|
|
251
|
+
# ── GET /iicp/health ──────────────────────────────────────────
|
|
252
|
+
|
|
253
|
+
def _health(self) -> None:
|
|
254
|
+
with node._jobs_lock:
|
|
255
|
+
active = node._active_jobs
|
|
256
|
+
denom = node._cfg.max_concurrent or 1
|
|
257
|
+
body = json.dumps(
|
|
258
|
+
{
|
|
259
|
+
"status": "ok",
|
|
260
|
+
"node_id": node._cfg.node_id,
|
|
261
|
+
"region": node._cfg.region or "unknown",
|
|
262
|
+
"load": round(active / denom, 3),
|
|
263
|
+
"active_jobs": active,
|
|
264
|
+
"max_concurrent": node._cfg.max_concurrent,
|
|
265
|
+
"available": active < node._cfg.max_concurrent,
|
|
266
|
+
"model": node._cfg.model or "",
|
|
267
|
+
"intent": node._cfg.intent,
|
|
268
|
+
}
|
|
269
|
+
).encode()
|
|
270
|
+
self._json_response(200, body)
|
|
271
|
+
|
|
272
|
+
# ── GET /metrics ──────────────────────────────────────────────
|
|
273
|
+
|
|
274
|
+
def _prometheus(self) -> None:
|
|
275
|
+
prom = _get_prom()
|
|
276
|
+
if prom is None:
|
|
277
|
+
body = b"prometheus_client not installed"
|
|
278
|
+
self.send_response(503)
|
|
279
|
+
self.send_header("Content-Type", "text/plain; charset=utf-8")
|
|
280
|
+
self.send_header("Content-Length", str(len(body)))
|
|
281
|
+
self.end_headers()
|
|
282
|
+
self.wfile.write(body)
|
|
283
|
+
return
|
|
284
|
+
body = prom.generate_latest()
|
|
285
|
+
self.send_response(200)
|
|
286
|
+
self.send_header("Content-Type", prom.CONTENT_TYPE_LATEST)
|
|
287
|
+
self.send_header("Content-Length", str(len(body)))
|
|
288
|
+
self.end_headers()
|
|
289
|
+
self.wfile.write(body)
|
|
290
|
+
|
|
291
|
+
# ── POST /v1/task ─────────────────────────────────────────────
|
|
292
|
+
|
|
293
|
+
def _task(self) -> None:
|
|
294
|
+
# Concurrency gate — IICP-E021
|
|
295
|
+
if not node._sem.acquire(blocking=False):
|
|
296
|
+
err = json.dumps(
|
|
297
|
+
{
|
|
298
|
+
"error": {
|
|
299
|
+
"code": "IICP-E021",
|
|
300
|
+
"message": "capacity_exceeded",
|
|
301
|
+
"qos_class": None,
|
|
302
|
+
"retry_after_ms": 2000,
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
).encode()
|
|
306
|
+
self.send_response(429)
|
|
307
|
+
self.send_header("Content-Type", "application/json")
|
|
308
|
+
self.send_header("Retry-After", "2")
|
|
309
|
+
self.send_header("Content-Length", str(len(err)))
|
|
310
|
+
self.end_headers()
|
|
311
|
+
self.wfile.write(err)
|
|
312
|
+
return
|
|
313
|
+
|
|
314
|
+
with node._jobs_lock:
|
|
315
|
+
node._active_jobs += 1
|
|
316
|
+
t0 = time.monotonic()
|
|
317
|
+
try:
|
|
318
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
319
|
+
body: dict[str, Any] = (
|
|
320
|
+
json.loads(self.rfile.read(length)) if length else {}
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
# Nonce replay — IICP-E011
|
|
324
|
+
if not node._check_nonce(body.get("nonce")):
|
|
325
|
+
err = json.dumps(
|
|
326
|
+
{"error": {"code": "IICP-E011", "message": "replay_detected"}}
|
|
327
|
+
).encode()
|
|
328
|
+
self.send_response(409)
|
|
329
|
+
self.send_header("Content-Type", "application/json")
|
|
330
|
+
self.send_header("Content-Length", str(len(err)))
|
|
331
|
+
self.end_headers()
|
|
332
|
+
self.wfile.write(err)
|
|
333
|
+
return
|
|
334
|
+
|
|
335
|
+
# W3C traceparent propagation
|
|
336
|
+
traceparent = self.headers.get("traceparent")
|
|
337
|
+
if traceparent:
|
|
338
|
+
body.setdefault("_trace", {})["traceparent"] = traceparent
|
|
339
|
+
|
|
340
|
+
intent = body.get("intent") or node._cfg.intent
|
|
341
|
+
constraints = body.get("constraints") or {}
|
|
342
|
+
qos = (
|
|
343
|
+
constraints.get("qos_class", "best_effort")
|
|
344
|
+
if isinstance(constraints, dict)
|
|
345
|
+
else "best_effort"
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
try:
|
|
349
|
+
result = asyncio.run_coroutine_threadsafe(
|
|
350
|
+
handler(body), loop
|
|
351
|
+
).result(timeout=60)
|
|
352
|
+
latency_ms = (time.monotonic() - t0) * 1000
|
|
353
|
+
usage = result.get("usage") or {}
|
|
354
|
+
tokens = (
|
|
355
|
+
usage.get("total_tokens", 0) if isinstance(usage, dict) else 0
|
|
356
|
+
)
|
|
357
|
+
node._metrics.observe("completed", intent, qos, latency_ms, tokens)
|
|
358
|
+
resp_body = json.dumps(
|
|
359
|
+
{
|
|
360
|
+
"task_id": body.get("task_id", ""),
|
|
361
|
+
"status": "completed",
|
|
362
|
+
**result,
|
|
363
|
+
}
|
|
364
|
+
).encode()
|
|
365
|
+
self._json_response(200, resp_body)
|
|
366
|
+
except Exception as exc:
|
|
367
|
+
latency_ms = (time.monotonic() - t0) * 1000
|
|
368
|
+
node._metrics.observe("error", intent, qos, latency_ms)
|
|
369
|
+
logger.error("Handler error: %s", exc)
|
|
370
|
+
self.send_error(500, str(exc))
|
|
371
|
+
finally:
|
|
372
|
+
node._sem.release()
|
|
373
|
+
with node._jobs_lock:
|
|
374
|
+
node._active_jobs -= 1
|
|
375
|
+
|
|
376
|
+
# ── helpers ───────────────────────────────────────────────────
|
|
377
|
+
|
|
378
|
+
def _json_response(self, status: int, body: bytes) -> None:
|
|
379
|
+
self.send_response(status)
|
|
380
|
+
self.send_header("Content-Type", "application/json")
|
|
381
|
+
self.send_header("Content-Length", str(len(body)))
|
|
382
|
+
self.end_headers()
|
|
383
|
+
self.wfile.write(body)
|
|
384
|
+
|
|
385
|
+
server = ThreadingHTTPServer((host, port), _Handler)
|
|
386
|
+
logger.info("IICP node %s listening on %s:%d", self._cfg.node_id, host, port)
|
|
387
|
+
|
|
388
|
+
bg_tasks: list[asyncio.Task] = []
|
|
389
|
+
if node_token:
|
|
390
|
+
bg_tasks.append(asyncio.create_task(self._heartbeat_loop(node_token)))
|
|
391
|
+
|
|
392
|
+
try:
|
|
393
|
+
await loop.run_in_executor(None, server.serve_forever)
|
|
394
|
+
finally:
|
|
395
|
+
server.shutdown()
|
|
396
|
+
for t in bg_tasks:
|
|
397
|
+
t.cancel()
|
|
398
|
+
await self._http.aclose()
|
|
399
|
+
|
|
400
|
+
async def __aenter__(self) -> IicpNode:
|
|
401
|
+
return self
|
|
402
|
+
|
|
403
|
+
async def __aexit__(self, *_: Any) -> None:
|
|
404
|
+
await self._http.aclose()
|
iicp_client/types.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Public types for iicp-client (ADR-016 §1)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from iicp_client.errors import IicpError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class ClientConfig:
|
|
13
|
+
directory_url: str = "https://iicp.network"
|
|
14
|
+
region: str | None = None
|
|
15
|
+
timeout_ms: int = 30_000
|
|
16
|
+
max_retries: int = 3
|
|
17
|
+
tls_verify: bool = True
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class TaskConstraints:
|
|
22
|
+
timeout_ms: int = 30_000
|
|
23
|
+
qos: str = "interactive"
|
|
24
|
+
region: str | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class TaskAuth:
|
|
29
|
+
node_token: str | None = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class TaskRequest:
|
|
34
|
+
intent: str
|
|
35
|
+
payload: dict[str, Any]
|
|
36
|
+
constraints: TaskConstraints = field(default_factory=TaskConstraints)
|
|
37
|
+
auth: TaskAuth = field(default_factory=TaskAuth)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class TaskMetrics:
|
|
42
|
+
latency_ms: int
|
|
43
|
+
tokens_used: int | None
|
|
44
|
+
node_id: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class TaskResponse:
|
|
49
|
+
task_id: str
|
|
50
|
+
status: str
|
|
51
|
+
result: dict[str, Any] | None
|
|
52
|
+
metrics: TaskMetrics
|
|
53
|
+
error: IicpError | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class ChatMessage:
|
|
58
|
+
role: str
|
|
59
|
+
content: str
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class ChatOptions:
|
|
64
|
+
model: str | None = None
|
|
65
|
+
max_tokens: int | None = None
|
|
66
|
+
temperature: float | None = None
|
|
67
|
+
timeout_ms: int | None = None
|
|
68
|
+
qos: str = "interactive"
|
|
69
|
+
node_token: str | None = None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class ChatChoice:
|
|
74
|
+
message: ChatMessage
|
|
75
|
+
finish_reason: str
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class ChatUsage:
|
|
80
|
+
prompt_tokens: int
|
|
81
|
+
completion_tokens: int
|
|
82
|
+
total_tokens: int
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class ChatResponse:
|
|
87
|
+
id: str
|
|
88
|
+
choices: list[ChatChoice]
|
|
89
|
+
usage: ChatUsage
|
|
90
|
+
model: str
|
|
91
|
+
iicp_node_id: str
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass
|
|
95
|
+
class DiscoverOptions:
|
|
96
|
+
region: str | None = None
|
|
97
|
+
qos: str | None = None
|
|
98
|
+
min_reputation: float | None = None
|
|
99
|
+
model: str | None = None
|
|
100
|
+
limit: int = 10
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass
|
|
104
|
+
class Node:
|
|
105
|
+
node_id: str
|
|
106
|
+
endpoint: str
|
|
107
|
+
score: float
|
|
108
|
+
available: bool
|
|
109
|
+
region: str
|
|
110
|
+
latency_estimate_ms: int | None = None
|
|
111
|
+
reputation_score: float | None = None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass
|
|
115
|
+
class NodeList:
|
|
116
|
+
nodes: list[Node]
|
|
117
|
+
query_ms: int
|
|
118
|
+
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: iicp-client
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Official Python client SDK for the IICP protocol
|
|
5
|
+
Project-URL: Homepage, https://iicp.network
|
|
6
|
+
Project-URL: Repository, https://github.com/RobLe3/iicp-client-python
|
|
7
|
+
Project-URL: Documentation, https://iicp.network/docs
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/RobLe3/iicp-client-python/issues
|
|
9
|
+
Author-email: IICP Contributors <claude@roblemumin.com>
|
|
10
|
+
License: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai-agents,iicp,llm,protocol,sdk
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: httpx>=0.27
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: prometheus-client>=0.20; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8.3; extra == 'dev'
|
|
27
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
28
|
+
Requires-Dist: ruff>=0.8; extra == 'dev'
|
|
29
|
+
Provides-Extra: metrics
|
|
30
|
+
Requires-Dist: prometheus-client>=0.20; extra == 'metrics'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# iicp-client · Python SDK
|
|
34
|
+
|
|
35
|
+
[](https://github.com/RobLe3/iicp-client-python/actions/workflows/ci.yml)
|
|
36
|
+
[](LICENSE)
|
|
37
|
+
[](https://iicp.network/spec)
|
|
38
|
+
[](https://pypi.org/project/iicp-client/)
|
|
39
|
+
|
|
40
|
+
Official Python client library for the [IICP protocol](https://iicp.network) — route AI agent tasks by intent across a self-organising mesh of provider nodes. No central broker. No hardcoded endpoints.
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
urn:iicp:intent:llm:chat:v1 → discover → select → submit
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install iicp-client
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Requires **Python ≥ 3.11** and [`httpx`](https://www.python-httpx.org/).
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## Quickstart
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
import asyncio
|
|
62
|
+
from iicp_client import IicpClient, ChatMessage
|
|
63
|
+
|
|
64
|
+
async def main():
|
|
65
|
+
client = IicpClient()
|
|
66
|
+
|
|
67
|
+
# chat_async discovers, selects best node, and submits in one call
|
|
68
|
+
response = await client.chat_async(
|
|
69
|
+
messages=[ChatMessage(role="user", content="Hello from IICP!")],
|
|
70
|
+
)
|
|
71
|
+
print(response.choices[0].message.content)
|
|
72
|
+
|
|
73
|
+
asyncio.run(main())
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Synchronous wrapper for scripts and notebooks:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from iicp_client import IicpClient, ChatMessage
|
|
80
|
+
|
|
81
|
+
client = IicpClient()
|
|
82
|
+
response = client.chat([ChatMessage(role="user", content="Hello from IICP!")])
|
|
83
|
+
print(response.choices[0].message.content)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Configuration
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from iicp_client import ClientConfig
|
|
92
|
+
|
|
93
|
+
config = ClientConfig(
|
|
94
|
+
directory_url = "https://iicp.network", # IICP directory
|
|
95
|
+
timeout_ms = 30_000, # max 120 000 (SDK-04)
|
|
96
|
+
region = "eu-central", # prefer nodes in region
|
|
97
|
+
)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
| Field | Default | Description |
|
|
101
|
+
|-------|---------|-------------|
|
|
102
|
+
| `directory_url` | `"https://iicp.network"` | IICP directory endpoint |
|
|
103
|
+
| `timeout_ms` | `30000` | Request timeout — max 120 000 ms |
|
|
104
|
+
| `region` | `None` | Preferred node region |
|
|
105
|
+
| `max_retries` | `3` | Retry count for transient errors |
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## Discover options
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from iicp_client import DiscoverOptions
|
|
113
|
+
|
|
114
|
+
node_list = await client.discover_async(
|
|
115
|
+
"urn:iicp:intent:llm:chat:v1",
|
|
116
|
+
DiscoverOptions(
|
|
117
|
+
region = "eu-central",
|
|
118
|
+
model = "phi3:mini",
|
|
119
|
+
min_reputation = 0.7,
|
|
120
|
+
limit = 5,
|
|
121
|
+
)
|
|
122
|
+
)
|
|
123
|
+
nodes = node_list.nodes # list of Node objects
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Error handling
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from iicp_client import IicpClient, IicpError, ChatMessage
|
|
132
|
+
|
|
133
|
+
client = IicpClient()
|
|
134
|
+
try:
|
|
135
|
+
response = client.chat([ChatMessage(role="user", content="hi")])
|
|
136
|
+
except IicpError as e:
|
|
137
|
+
print(f"[{e.code}] {e.message} (HTTP {e.http_status})")
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Error codes match the [IICP error reference](https://iicp.network/docs/error-reference) — e.g. `task_timeout`, `capacity_exceeded`, `no_nodes_available`.
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## SDK conformance
|
|
145
|
+
|
|
146
|
+
| Rule | Description | Status |
|
|
147
|
+
|------|-------------|--------|
|
|
148
|
+
| SDK-01 | discover → select → submit pipeline with node retry | ✓ |
|
|
149
|
+
| SDK-02 | `task_id` auto-generated (UUID v4) | ✓ |
|
|
150
|
+
| SDK-03 | Intent URN pattern validation | ✓ |
|
|
151
|
+
| SDK-04 | `timeout_ms` capped at 120 000 ms | ✓ |
|
|
152
|
+
| SDK-05 | Retry on 429 / 503 with exponential back-off | ✓ |
|
|
153
|
+
| SDK-06 | W3C `traceparent` propagation | ✓ |
|
|
154
|
+
|
|
155
|
+
Conformance tier: `iicp:sdk:v1` (spec S.14) · [Request a badge](https://iicp.network/conformance)
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## Development
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
pip install -e ".[dev]" # install with dev deps
|
|
163
|
+
pytest tests/ -v # run 28 unit tests
|
|
164
|
+
ruff check src tests # lint
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## Links
|
|
170
|
+
|
|
171
|
+
- [Protocol spec](https://iicp.network/spec) — full IICP specification
|
|
172
|
+
- [Node setup guide](https://iicp.network/docs/node-setup) — run your own node
|
|
173
|
+
- [Error reference](https://iicp.network/docs/error-reference) — all error codes
|
|
174
|
+
- [iicp-client-typescript](https://github.com/RobLe3/iicp-client-typescript) — TypeScript SDK
|
|
175
|
+
- [iicp-client-rust](https://github.com/RobLe3/iicp-client-rust) — Rust SDK
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
Apache 2.0 · [iicp.network](https://iicp.network)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
iicp_client/__init__.py,sha256=vBqdMu0m6HiqD5NlFbCJ4NWx8IWRopPrDLZqBvJIQdM,716
|
|
2
|
+
iicp_client/_http.py,sha256=X4Pve4RWHcZH3qAT3lBMSig4Uq4MBWdTgDJOxQ7yUCs,3427
|
|
3
|
+
iicp_client/client.py,sha256=UFfLsxiFq203yue-wSnKkhxZsBiwbRJtC9HbFPxX3oY,8895
|
|
4
|
+
iicp_client/errors.py,sha256=XKZSp5uxkamoGhPIxcZsqsgd1Iv2P6osh5VhFhgRrI8,1358
|
|
5
|
+
iicp_client/node.py,sha256=tTCk-iDs3UfBIi2cU9HTRujpoDRcXmoTQ3VYeeH69xU,15918
|
|
6
|
+
iicp_client/types.py,sha256=X48Te4zqLv67QwwGh-TW-BpNzuOjsy4-RC1hJ5mXFGM,2125
|
|
7
|
+
iicp_client-0.2.0.dist-info/METADATA,sha256=wuNvz0WBD1u_qIbl92tXXA3ZPJs_p4mIMvfUWIlZojc,5507
|
|
8
|
+
iicp_client-0.2.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
9
|
+
iicp_client-0.2.0.dist-info/licenses/LICENSE,sha256=Iv_IDx2imte4neNvnlDK54ml35T8KSW30XdWoB7bFsw,10016
|
|
10
|
+
iicp_client-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship made available under
|
|
36
|
+
the License, as indicated by a copyright notice that is included in
|
|
37
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other transformations
|
|
42
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
43
|
+
of this License, Derivative Works shall not include works that remain
|
|
44
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
+
the Work and its Derivative Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
|
48
|
+
in the Work by the copyright owner or by an individual or Legal Entity
|
|
49
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
50
|
+
of this definition, "submitted" means any form of electronic, verbal,
|
|
51
|
+
or written communication sent to the Licensor or its representatives,
|
|
52
|
+
including but not limited to communication on electronic mailing lists,
|
|
53
|
+
source code control systems, and issue tracking systems that are managed
|
|
54
|
+
by, or on behalf of, the Licensor for the purpose of discussing and
|
|
55
|
+
improving the Work, but excluding communication that is conspicuously
|
|
56
|
+
marked or otherwise designated in writing by the copyright owner as
|
|
57
|
+
"Not a Contribution."
|
|
58
|
+
|
|
59
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
60
|
+
whom a Contribution has been received by the Licensor and incorporated
|
|
61
|
+
within the Work.
|
|
62
|
+
|
|
63
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
64
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
65
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
66
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
67
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
68
|
+
Work and such Derivative Works in Source or Object form.
|
|
69
|
+
|
|
70
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
71
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
72
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
73
|
+
(except as stated in this section) patent license to make, have made,
|
|
74
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
75
|
+
where such license applies only to those patent claims licensable
|
|
76
|
+
by such Contributor that are necessarily infringed by their
|
|
77
|
+
Contribution(s) alone or in combination with the Work to which such
|
|
78
|
+
Contribution(s) was submitted. If You institute patent litigation
|
|
79
|
+
against any entity (including a cross-claim or counterclaim in a
|
|
80
|
+
lawsuit) alleging that the Work or a Contribution incorporated within
|
|
81
|
+
the Work constitutes direct or contributory patent infringement, then
|
|
82
|
+
any patent licenses granted to You under this License for that Work
|
|
83
|
+
shall terminate as of the date such litigation is filed.
|
|
84
|
+
|
|
85
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
86
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
87
|
+
modifications, and in Source or Object form, provided that You
|
|
88
|
+
meet the following conditions:
|
|
89
|
+
|
|
90
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
91
|
+
Works a copy of this License; and
|
|
92
|
+
|
|
93
|
+
(b) You must cause any modified files to carry prominent notices
|
|
94
|
+
stating that You changed the files; and
|
|
95
|
+
|
|
96
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
97
|
+
that You distribute, all copyright, patent, trademark, and
|
|
98
|
+
attribution notices from the Source form of the Work,
|
|
99
|
+
excluding those notices that do not pertain to any part of
|
|
100
|
+
the Derivative Works; and
|
|
101
|
+
|
|
102
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
103
|
+
distribution, You must include a readable copy of the
|
|
104
|
+
attribution notices contained within such NOTICE file, in
|
|
105
|
+
at least one of the following places: within a NOTICE text
|
|
106
|
+
file distributed as part of the Derivative Works; within
|
|
107
|
+
the Source form or documentation, if provided along with the
|
|
108
|
+
Derivative Works; or, within a display generated by the
|
|
109
|
+
Derivative Works, if and wherever such third-party notices
|
|
110
|
+
normally appear. The contents of the NOTICE file are for
|
|
111
|
+
informational purposes only and do not modify the License.
|
|
112
|
+
You may add Your own attribution notices within Derivative
|
|
113
|
+
Works that You distribute, alongside or as an addendum to
|
|
114
|
+
the NOTICE text from the Work, provided that such additional
|
|
115
|
+
attribution notices cannot be construed as modifying the License.
|
|
116
|
+
|
|
117
|
+
You may add Your own license statement for Your modifications and
|
|
118
|
+
may provide additional grant of rights to use, copy, modify, merge,
|
|
119
|
+
publish, distribute, sublicense, and/or sell copies of the Work,
|
|
120
|
+
and to permit persons to whom the Work is furnished to do so, subject
|
|
121
|
+
to Your separate additional terms and conditions.
|
|
122
|
+
|
|
123
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
124
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
125
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
126
|
+
this License, without any additional terms or conditions.
|
|
127
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
128
|
+
the terms of any separate license agreement you may have executed
|
|
129
|
+
with Licensor regarding such Contributions.
|
|
130
|
+
|
|
131
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
132
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
133
|
+
except as required for reasonable and customary use in describing the
|
|
134
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
135
|
+
|
|
136
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
137
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
138
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
139
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
140
|
+
implied, including, without limitation, any conditions of title,
|
|
141
|
+
non-infringement, merchantability, or fitness for a particular
|
|
142
|
+
purpose. You are solely responsible for determining the
|
|
143
|
+
appropriateness of using or reproducing the Work and assume any
|
|
144
|
+
risks associated with Your exercise of permissions under this License.
|
|
145
|
+
|
|
146
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
147
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
148
|
+
unless required by applicable law (such as deliberate and grossly
|
|
149
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
150
|
+
liable to You for damages, including any direct, indirect, special,
|
|
151
|
+
incidental, or exemplary damages of any character arising as a
|
|
152
|
+
result of this License or out of the use or inability to use the
|
|
153
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
154
|
+
work stoppage, computer failure or malfunction, or all other
|
|
155
|
+
commercial damages or losses), even if such Contributor has been
|
|
156
|
+
advised of the possibility of such damages.
|
|
157
|
+
|
|
158
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
159
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
160
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
161
|
+
or other liability obligations and/or rights consistent with this
|
|
162
|
+
License. However, in accepting such obligations, You may offer only
|
|
163
|
+
conditions fully consistent with this License to any recipient of
|
|
164
|
+
the Work.
|
|
165
|
+
|
|
166
|
+
END OF TERMS AND CONDITIONS
|
|
167
|
+
|
|
168
|
+
Copyright 2026 Rob Lemumin
|
|
169
|
+
|
|
170
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
171
|
+
you may not use this file except in compliance with the License.
|
|
172
|
+
You may obtain a copy of the License at
|
|
173
|
+
|
|
174
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
175
|
+
|
|
176
|
+
Unless required by applicable law or agreed to in writing, software
|
|
177
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
178
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
179
|
+
See the License for the specific language governing permissions and
|
|
180
|
+
limitations under the License.
|