nagent 1.0.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.
- nagent/__init__.py +13 -0
- nagent/client.py +175 -0
- nagent/py.typed +0 -0
- nagent/webhooks.py +38 -0
- nagent-1.0.0.dist-info/METADATA +60 -0
- nagent-1.0.0.dist-info/RECORD +8 -0
- nagent-1.0.0.dist-info/WHEEL +4 -0
- nagent-1.0.0.dist-info/licenses/LICENSE +21 -0
nagent/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Run your Nagent agents from Python.
|
|
2
|
+
|
|
3
|
+
A thin client over the Nagent REST API (/api/v1). Standard library only.
|
|
4
|
+
Each method is one operation in /api/v1/openapi.json, named by its
|
|
5
|
+
operationId in a comment; a test in the main repository fails when they
|
|
6
|
+
drift.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .client import Nagent, NagentError
|
|
10
|
+
from .webhooks import verify_webhook
|
|
11
|
+
|
|
12
|
+
__all__ = ["Nagent", "NagentError", "verify_webhook"]
|
|
13
|
+
__version__ = "1.0.0"
|
nagent/client.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.parse
|
|
7
|
+
import urllib.request
|
|
8
|
+
from typing import Any, Callable, Dict, Iterator, Optional
|
|
9
|
+
|
|
10
|
+
Json = Dict[str, Any]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class NagentError(Exception):
|
|
14
|
+
"""A call the API refused, with its RFC 9457 problem document."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, problem: Json, request_id: Optional[str]):
|
|
17
|
+
title = problem.get("title") or "Request failed"
|
|
18
|
+
detail = problem.get("detail")
|
|
19
|
+
super().__init__(f"{title}: {detail}" if detail else title)
|
|
20
|
+
self.problem = problem
|
|
21
|
+
self.status: int = int(problem.get("status") or 0)
|
|
22
|
+
self.code: str = str(problem.get("type", "")).rsplit("#", 1)[-1]
|
|
23
|
+
self.request_id = request_id
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], "tuple[int, Dict[str, str], bytes]"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _urllib_transport(method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float):
|
|
30
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
31
|
+
try:
|
|
32
|
+
with urllib.request.urlopen(req, timeout=timeout) as res:
|
|
33
|
+
return res.status, {k.lower(): v for k, v in res.headers.items()}, res.read()
|
|
34
|
+
except urllib.error.HTTPError as e:
|
|
35
|
+
return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Nagent:
|
|
39
|
+
"""A client for one API key.
|
|
40
|
+
|
|
41
|
+
>>> nagent = Nagent(api_key=os.environ["NAGENT_API_KEY"])
|
|
42
|
+
>>> run = nagent.runs.create("nora", input="Research retail-1.example")
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(self, api_key: str, base_url: str = "https://nagent.ai", timeout: float = 310.0, transport: Optional[Transport] = None):
|
|
46
|
+
self._key = api_key
|
|
47
|
+
self._base = base_url.rstrip("/") + "/api/v1"
|
|
48
|
+
self._timeout = timeout
|
|
49
|
+
self._transport = transport or _urllib_transport
|
|
50
|
+
self.agents = _Agents(self)
|
|
51
|
+
self.runs = _Runs(self)
|
|
52
|
+
self.approvals = _Approvals(self)
|
|
53
|
+
self.webhooks = _Webhooks(self)
|
|
54
|
+
|
|
55
|
+
def _call(self, method: str, path: str, body: Any = None, headers: Optional[Dict[str, str]] = None, raw: bool = False) -> Any:
|
|
56
|
+
h = {"Authorization": f"Bearer {self._key}", "Accept": "application/json", "User-Agent": "nagent-python/1.0.0"}
|
|
57
|
+
data = None
|
|
58
|
+
if body is not None:
|
|
59
|
+
h["Content-Type"] = "application/json"
|
|
60
|
+
data = json.dumps(body).encode()
|
|
61
|
+
h.update(headers or {})
|
|
62
|
+
status, res_headers, payload = self._transport(method, self._base + path, h, data, self._timeout)
|
|
63
|
+
if status >= 400:
|
|
64
|
+
try:
|
|
65
|
+
problem = json.loads(payload.decode() or "{}")
|
|
66
|
+
except ValueError:
|
|
67
|
+
problem = {"title": "HTTP error", "status": status}
|
|
68
|
+
problem.setdefault("status", status)
|
|
69
|
+
raise NagentError(problem, res_headers.get("x-request-id"))
|
|
70
|
+
text = payload.decode()
|
|
71
|
+
return text if raw else (json.loads(text) if text else None)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _q(value: str) -> str:
|
|
75
|
+
return urllib.parse.quote(value, safe="")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class _Agents:
|
|
79
|
+
def __init__(self, c: Nagent):
|
|
80
|
+
self._c = c
|
|
81
|
+
|
|
82
|
+
def list(self) -> list:
|
|
83
|
+
"""listAgents"""
|
|
84
|
+
return self._c._call("GET", "/agents")["data"]
|
|
85
|
+
|
|
86
|
+
def get(self, key: str) -> Json:
|
|
87
|
+
"""getAgent"""
|
|
88
|
+
return self._c._call("GET", f"/agents/{_q(key)}")
|
|
89
|
+
|
|
90
|
+
def markdown(self, key: str) -> str:
|
|
91
|
+
"""getAgentMarkdown"""
|
|
92
|
+
return self._c._call("GET", f"/agents/{_q(key)}/agent.md", raw=True)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class _Runs:
|
|
96
|
+
def __init__(self, c: Nagent):
|
|
97
|
+
self._c = c
|
|
98
|
+
|
|
99
|
+
def create(self, agent: str, input: str, session_id: Optional[str] = None, metadata: Optional[Dict[str, str]] = None,
|
|
100
|
+
idempotency_key: Optional[str] = None, wait: bool = True) -> Json:
|
|
101
|
+
"""createRun. With wait=False the run comes back running (Prefer: respond-async)."""
|
|
102
|
+
body: Json = {"input": input}
|
|
103
|
+
if session_id is not None:
|
|
104
|
+
body["sessionId"] = session_id
|
|
105
|
+
if metadata is not None:
|
|
106
|
+
body["metadata"] = metadata
|
|
107
|
+
headers: Dict[str, str] = {}
|
|
108
|
+
if idempotency_key:
|
|
109
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
110
|
+
if not wait:
|
|
111
|
+
headers["Prefer"] = "respond-async"
|
|
112
|
+
return self._c._call("POST", f"/agents/{_q(agent)}/runs", body, headers)
|
|
113
|
+
|
|
114
|
+
def get(self, run_id: str) -> Json:
|
|
115
|
+
"""getRun"""
|
|
116
|
+
return self._c._call("GET", f"/runs/{_q(run_id)}")
|
|
117
|
+
|
|
118
|
+
def events(self, run_id: str) -> str:
|
|
119
|
+
"""getRunEvents"""
|
|
120
|
+
return self._c._call("GET", f"/runs/{_q(run_id)}/events", raw=True)
|
|
121
|
+
|
|
122
|
+
def wait(self, run_id: str, timeout: float = 600.0, interval: float = 3.0, sleep: Callable[[float], None] = time.sleep) -> Json:
|
|
123
|
+
"""Read a run until it is no longer running."""
|
|
124
|
+
deadline = time.monotonic() + timeout
|
|
125
|
+
while True:
|
|
126
|
+
run = self.get(run_id)
|
|
127
|
+
if run.get("status") != "running" or time.monotonic() >= deadline:
|
|
128
|
+
return run
|
|
129
|
+
sleep(interval)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class _Approvals:
|
|
133
|
+
def __init__(self, c: Nagent):
|
|
134
|
+
self._c = c
|
|
135
|
+
|
|
136
|
+
def list(self, status: str = "pending", limit: int = 25, cursor: Optional[str] = None) -> Json:
|
|
137
|
+
"""listApprovals: one page, newest first, with hasMore and nextCursor."""
|
|
138
|
+
q = {"status": status, "limit": str(limit)}
|
|
139
|
+
if cursor:
|
|
140
|
+
q["cursor"] = cursor
|
|
141
|
+
return self._c._call("GET", "/approvals?" + urllib.parse.urlencode(q))
|
|
142
|
+
|
|
143
|
+
def iter(self, status: str = "pending", page_size: int = 100) -> Iterator[Json]:
|
|
144
|
+
"""Every approval, page after page."""
|
|
145
|
+
cursor: Optional[str] = None
|
|
146
|
+
while True:
|
|
147
|
+
page = self.list(status=status, limit=page_size, cursor=cursor)
|
|
148
|
+
yield from page["data"]
|
|
149
|
+
if not page.get("hasMore") or not page.get("nextCursor"):
|
|
150
|
+
return
|
|
151
|
+
cursor = page["nextCursor"]
|
|
152
|
+
|
|
153
|
+
def decide(self, approval_id: str, decision: str, note: Optional[str] = None) -> Any:
|
|
154
|
+
"""decideApproval: decision is "approve" or "reject"."""
|
|
155
|
+
body: Json = {"decision": decision}
|
|
156
|
+
if note is not None:
|
|
157
|
+
body["note"] = note
|
|
158
|
+
return self._c._call("POST", f"/approvals/{_q(approval_id)}/decide", body)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class _Webhooks:
|
|
162
|
+
def __init__(self, c: Nagent):
|
|
163
|
+
self._c = c
|
|
164
|
+
|
|
165
|
+
def list(self) -> list:
|
|
166
|
+
"""listWebhooks"""
|
|
167
|
+
return self._c._call("GET", "/webhooks")["data"]
|
|
168
|
+
|
|
169
|
+
def create(self, url: str, events: list) -> Json:
|
|
170
|
+
"""createWebhook: the response carries the signing secret, once."""
|
|
171
|
+
return self._c._call("POST", "/webhooks", {"url": url, "events": events})
|
|
172
|
+
|
|
173
|
+
def delete(self, endpoint_id: str) -> Json:
|
|
174
|
+
"""deleteWebhook"""
|
|
175
|
+
return self._c._call("DELETE", f"/webhooks/{_q(endpoint_id)}")
|
nagent/py.typed
ADDED
|
File without changes
|
nagent/webhooks.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import time
|
|
7
|
+
from typing import Mapping, Optional, Union
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def verify_webhook(secret: str, headers: Mapping[str, str], body: Union[bytes, str], now: Optional[float] = None, tolerance: int = 300) -> bool:
|
|
11
|
+
"""Whether a delivery is Nagent's.
|
|
12
|
+
|
|
13
|
+
Standard Webhooks: HMAC-SHA256 over "id.timestamp.body" with the
|
|
14
|
+
endpoint's whsec_ secret, within five minutes. Pass the raw body, before
|
|
15
|
+
any JSON parsing.
|
|
16
|
+
"""
|
|
17
|
+
h = {k.lower(): v for k, v in headers.items()}
|
|
18
|
+
msg_id = h.get("webhook-id", "")
|
|
19
|
+
try:
|
|
20
|
+
ts = int(h.get("webhook-timestamp", ""))
|
|
21
|
+
except ValueError:
|
|
22
|
+
return False
|
|
23
|
+
if not msg_id or abs((time.time() if now is None else now) - ts) > tolerance:
|
|
24
|
+
return False
|
|
25
|
+
raw = body.encode() if isinstance(body, str) else body
|
|
26
|
+
key = base64.b64decode(secret[6:] if secret.startswith("whsec_") else secret)
|
|
27
|
+
expected = hmac.new(key, f"{msg_id}.{ts}.".encode() + raw, hashlib.sha256).digest()
|
|
28
|
+
for entry in h.get("webhook-signature", "").split():
|
|
29
|
+
version, _, sig = entry.partition(",")
|
|
30
|
+
if version != "v1" or not sig:
|
|
31
|
+
continue
|
|
32
|
+
try:
|
|
33
|
+
got = base64.b64decode(sig)
|
|
34
|
+
except ValueError:
|
|
35
|
+
continue
|
|
36
|
+
if hmac.compare_digest(got, expected):
|
|
37
|
+
return True
|
|
38
|
+
return False
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: nagent
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Run your Nagent agents from Python: a thin client over the Nagent REST API.
|
|
5
|
+
Project-URL: Homepage, https://nagent.ai/developers
|
|
6
|
+
Project-URL: Source, https://github.com/PWIN-Technologies-Pvt-Ltd/nagent-website/tree/staging/packages/nagent-python
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: agents,ai,api,mcp,nagent,sdk
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# nagent
|
|
17
|
+
|
|
18
|
+
Run your Nagent agents from Python. A thin client over the Nagent REST API
|
|
19
|
+
(`/api/v1`), standard library only, Python 3.9 and later.
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install nagent
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Create an API key in Nagent at Settings, API & MCP
|
|
26
|
+
(https://nagent.ai/admin/settings/api) and set it as `NAGENT_API_KEY`.
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import os
|
|
30
|
+
from nagent import Nagent
|
|
31
|
+
|
|
32
|
+
nagent = Nagent(api_key=os.environ["NAGENT_API_KEY"])
|
|
33
|
+
|
|
34
|
+
# A finished run
|
|
35
|
+
run = nagent.runs.create("nora", input="Research retail-1.example")
|
|
36
|
+
print(run["status"], run["output"])
|
|
37
|
+
|
|
38
|
+
# A long run: accepted at once, then waited on
|
|
39
|
+
accepted = nagent.runs.create("nora", input="Audit retail-1.example", wait=False)
|
|
40
|
+
run = nagent.runs.wait(accepted["id"])
|
|
41
|
+
|
|
42
|
+
# A conversation: the same session_id carries the earlier turns
|
|
43
|
+
nagent.runs.create("nora", input="And their competitors?", session_id="crm-4711")
|
|
44
|
+
|
|
45
|
+
# Approvals, every page
|
|
46
|
+
for approval in nagent.approvals.iter():
|
|
47
|
+
print(approval["id"], approval["action"])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Verify a webhook delivery with the raw body:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from nagent import verify_webhook
|
|
54
|
+
|
|
55
|
+
ok = verify_webhook(os.environ["NAGENT_WEBHOOK_SECRET"], request.headers, request.get_data())
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Every method maps to one operation in `/api/v1/openapi.json`. Errors raise
|
|
59
|
+
`NagentError` with `status`, `code`, the problem document and the request
|
|
60
|
+
id. Full reference: https://nagent.ai/developers
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
nagent/__init__.py,sha256=5hFCke6bJgPmIcpbiFVujC1X1e91i8f9iCgyZo_PCyU,418
|
|
2
|
+
nagent/client.py,sha256=RrmkZIrNAJEt-6BHH81Ibcw72-C4KkvruyQ_DYH14TQ,6757
|
|
3
|
+
nagent/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
nagent/webhooks.py,sha256=5ij-2Vm8Xp7hFSgvcJC0KXP4iVAFlgjWfw_o-5JpO1E,1371
|
|
5
|
+
nagent-1.0.0.dist-info/METADATA,sha256=YUDshMkJQlYuxjQIS50-fFV9MDUadhIHS_pqTQch55Q,1919
|
|
6
|
+
nagent-1.0.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
7
|
+
nagent-1.0.0.dist-info/licenses/LICENSE,sha256=uNvELyY1D8ghc1ug_iXE0vkquE9DJmi5kCSNRqiLHuQ,1082
|
|
8
|
+
nagent-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PWIN Technologies Pvt Ltd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|