pattern-agent-sdk 0.1.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.
pattern_agent_sdk/sdk.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
import time
|
|
4
|
+
import base64
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _parse_extra_headers(raw: Optional[str]) -> dict[str, str]:
|
|
14
|
+
if not raw:
|
|
15
|
+
return {}
|
|
16
|
+
try:
|
|
17
|
+
decoded = base64.b64decode(raw)
|
|
18
|
+
headers = json.loads(decoded)
|
|
19
|
+
if isinstance(headers, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in headers.items()):
|
|
20
|
+
return headers
|
|
21
|
+
except Exception:
|
|
22
|
+
pass
|
|
23
|
+
logger.warning("PatternSDK: __PA_AGENT_SERVICES_TOKEN_REQUEST_HEADERS is malformed, ignoring")
|
|
24
|
+
return {}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _decode_jwt_payload(token: str) -> dict:
|
|
28
|
+
parts = token.split(".")
|
|
29
|
+
if len(parts) != 3:
|
|
30
|
+
raise ValueError("Invalid JWT format")
|
|
31
|
+
payload_b64 = parts[1] + "=" * (-len(parts[1]) % 4)
|
|
32
|
+
return json.loads(base64.urlsafe_b64decode(payload_b64))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class PatternSDK:
|
|
36
|
+
def __init__(self, services_endpoint: Optional[str] = None, token_request_headers: Optional[str] = None):
|
|
37
|
+
self._services_endpoint = (services_endpoint or "").rstrip("/")
|
|
38
|
+
self._enabled = bool(self._services_endpoint)
|
|
39
|
+
if not self._enabled:
|
|
40
|
+
logger.info("PatternSDK: no services endpoint configured, SDK disabled")
|
|
41
|
+
return
|
|
42
|
+
self._mint_headers = _parse_extra_headers(token_request_headers)
|
|
43
|
+
self._token: Optional[str] = None
|
|
44
|
+
self._deployment_id: Optional[str] = None
|
|
45
|
+
self._token_exp: float = 0
|
|
46
|
+
self._renew_failed: bool = False
|
|
47
|
+
self._config_cache: Optional[dict] = None
|
|
48
|
+
self._prompts_cache: Optional[dict] = None
|
|
49
|
+
|
|
50
|
+
def _require_enabled(self):
|
|
51
|
+
if not self._enabled:
|
|
52
|
+
raise RuntimeError("PatternSDK is disabled: services endpoint not specified")
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def _endpoint(self) -> str:
|
|
56
|
+
return self._services_endpoint
|
|
57
|
+
|
|
58
|
+
async def _mint_token(self) -> str:
|
|
59
|
+
url = f"{self._endpoint}/mint-agent-token"
|
|
60
|
+
try:
|
|
61
|
+
async with httpx.AsyncClient(timeout=10) as client:
|
|
62
|
+
resp = await client.post(url, headers=self._mint_headers or None)
|
|
63
|
+
except httpx.ConnectError as e:
|
|
64
|
+
logger.error(f"PatternSDK: cannot connect to agent services at {url} — is the sidecar running? {e}")
|
|
65
|
+
raise
|
|
66
|
+
except httpx.TimeoutException:
|
|
67
|
+
logger.error(f"PatternSDK: request to {url} timed out")
|
|
68
|
+
raise
|
|
69
|
+
|
|
70
|
+
if resp.status_code != 200:
|
|
71
|
+
logger.error(f"PatternSDK: mint-agent-token returned {resp.status_code}: {resp.text}")
|
|
72
|
+
resp.raise_for_status()
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
token = resp.json()["token"]
|
|
76
|
+
except (KeyError, json.JSONDecodeError) as e:
|
|
77
|
+
logger.error(f"PatternSDK: mint-agent-token response missing 'token' field: {resp.text}")
|
|
78
|
+
raise RuntimeError("mint-agent-token response missing 'token' field") from e
|
|
79
|
+
|
|
80
|
+
payload = _decode_jwt_payload(token)
|
|
81
|
+
self._token = token
|
|
82
|
+
self._deployment_id = payload["sub"]
|
|
83
|
+
self._token_exp = payload.get("exp", 0)
|
|
84
|
+
self._renew_failed = False
|
|
85
|
+
return token
|
|
86
|
+
|
|
87
|
+
async def _ensure_token(self):
|
|
88
|
+
if not self._token or time.time() >= self._token_exp:
|
|
89
|
+
await self._mint_token()
|
|
90
|
+
|
|
91
|
+
def _token_is_expired(self) -> bool:
|
|
92
|
+
return time.time() >= self._token_exp
|
|
93
|
+
|
|
94
|
+
async def _request(self, method: str, path: str) -> dict:
|
|
95
|
+
await self._ensure_token()
|
|
96
|
+
url = f"{self._endpoint}/deployment/{self._deployment_id}{path}"
|
|
97
|
+
headers = {"Authorization": f"Bearer {self._token}"}
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
async with httpx.AsyncClient(timeout=10) as client:
|
|
101
|
+
resp = await client.request(method, url, headers=headers)
|
|
102
|
+
except httpx.ConnectError as e:
|
|
103
|
+
logger.error(f"PatternSDK: cannot connect to {url}: {e}")
|
|
104
|
+
raise
|
|
105
|
+
except httpx.TimeoutException:
|
|
106
|
+
logger.error(f"PatternSDK: request to {url} timed out")
|
|
107
|
+
raise
|
|
108
|
+
|
|
109
|
+
if resp.status_code == 403 and self._token_is_expired() and not self._renew_failed:
|
|
110
|
+
logger.info("PatternSDK: got 403 with expired token, attempting renewal")
|
|
111
|
+
try:
|
|
112
|
+
await self._mint_token()
|
|
113
|
+
except Exception:
|
|
114
|
+
self._renew_failed = True
|
|
115
|
+
logger.error("PatternSDK: token renewal failed after 403, not retrying")
|
|
116
|
+
raise
|
|
117
|
+
headers = {"Authorization": f"Bearer {self._token}"}
|
|
118
|
+
try:
|
|
119
|
+
async with httpx.AsyncClient(timeout=10) as client:
|
|
120
|
+
resp = await client.request(method, url, headers=headers)
|
|
121
|
+
except httpx.ConnectError as e:
|
|
122
|
+
logger.error(f"PatternSDK: cannot connect to {url} on retry: {e}")
|
|
123
|
+
raise
|
|
124
|
+
except httpx.TimeoutException:
|
|
125
|
+
logger.error(f"PatternSDK: retry request to {url} timed out")
|
|
126
|
+
raise
|
|
127
|
+
|
|
128
|
+
if resp.status_code == 401:
|
|
129
|
+
logger.error(f"PatternSDK: 401 from {path}: {resp.text}")
|
|
130
|
+
raise PermissionError(f"Unauthorized: {resp.text}")
|
|
131
|
+
if resp.status_code == 403:
|
|
132
|
+
logger.error(f"PatternSDK: 403 from {path}: {resp.text}")
|
|
133
|
+
raise PermissionError(f"Forbidden: {resp.text}")
|
|
134
|
+
if resp.status_code >= 400:
|
|
135
|
+
logger.error(f"PatternSDK: {resp.status_code} from {path}: {resp.text}")
|
|
136
|
+
resp.raise_for_status()
|
|
137
|
+
|
|
138
|
+
return resp.json()
|
|
139
|
+
|
|
140
|
+
async def config(self, key: Optional[str] = None):
|
|
141
|
+
self._require_enabled()
|
|
142
|
+
if self._config_cache is None:
|
|
143
|
+
self._config_cache = await self._request("GET", "/config")
|
|
144
|
+
if key is not None:
|
|
145
|
+
return self._config_cache.get(key)
|
|
146
|
+
return self._config_cache
|
|
147
|
+
|
|
148
|
+
async def prompt(self, slug: str) -> Optional[str]:
|
|
149
|
+
self._require_enabled()
|
|
150
|
+
if self._prompts_cache is None:
|
|
151
|
+
self._prompts_cache = await self._request("GET", "/prompts")
|
|
152
|
+
return self._prompts_cache.get(slug)
|
|
153
|
+
|
|
154
|
+
async def prompts(self) -> dict:
|
|
155
|
+
self._require_enabled()
|
|
156
|
+
if self._prompts_cache is None:
|
|
157
|
+
self._prompts_cache = await self._request("GET", "/prompts")
|
|
158
|
+
return self._prompts_cache
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
pa_sdk = PatternSDK(
|
|
162
|
+
os.environ.get("__PA_AGENT_SERVICES_ENDPOINT"),
|
|
163
|
+
os.environ.get("__PA_AGENT_SERVICES_TOKEN_REQUEST_HEADERS"),
|
|
164
|
+
)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pattern_agent_sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SDK for Pattern Agentic agents
|
|
5
|
+
Author-email: Amos Joshua <amos@patternagentic.ai>
|
|
6
|
+
License-File: LICENSE.md
|
|
7
|
+
Classifier: License :: Other/Proprietary License
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Requires-Dist: httpx>=0.27.0
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# pattern_agentic_sdk
|
|
15
|
+
|
|
16
|
+
SDK for Pattern Agentic agents.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install pattern_agentic_sdk
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from pattern_agentic_sdk import pa_sdk
|
|
24
|
+
|
|
25
|
+
config = await pa_sdk.config()
|
|
26
|
+
prompt = await pa_sdk.prompt("my-prompt")
|
|
27
|
+
```
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
pattern_agent_sdk/__init__.py,sha256=TqrhUN5c8qZ6SPVYlleox_-AtpIE_nL8tzSCfxFJl2g,72
|
|
2
|
+
pattern_agent_sdk/sdk.py,sha256=O53lQNYxwBHe9MzfWbzGqYBgkSiRaw2hBJBCpOeqBx8,6338
|
|
3
|
+
pattern_agent_sdk-0.1.0.dist-info/METADATA,sha256=88XM13lDXdRfx-gOpP1iHXNx-5yMmkta91PdPdfM_ZI,643
|
|
4
|
+
pattern_agent_sdk-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
5
|
+
pattern_agent_sdk-0.1.0.dist-info/licenses/LICENSE.md,sha256=DSh1W_L7SWGgHr_mFV9GoohIgDdryWg2dI8I3yI77Cw,3825
|
|
6
|
+
pattern_agent_sdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
## Elastic License 2.0 (ELv2)
|
|
2
|
+
|
|
3
|
+
### Acceptance
|
|
4
|
+
|
|
5
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
6
|
+
|
|
7
|
+
### Copyright License
|
|
8
|
+
|
|
9
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below.
|
|
10
|
+
|
|
11
|
+
### Limitations
|
|
12
|
+
|
|
13
|
+
You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
|
|
14
|
+
|
|
15
|
+
You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
|
|
16
|
+
|
|
17
|
+
You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor's trademarks is subject to applicable law.
|
|
18
|
+
|
|
19
|
+
### Patents
|
|
20
|
+
|
|
21
|
+
The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
|
|
22
|
+
|
|
23
|
+
### Notices
|
|
24
|
+
|
|
25
|
+
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
|
|
26
|
+
|
|
27
|
+
If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
|
|
28
|
+
|
|
29
|
+
### No Other Rights
|
|
30
|
+
|
|
31
|
+
These terms do not imply any licenses other than those expressly granted in these terms.
|
|
32
|
+
|
|
33
|
+
### Termination
|
|
34
|
+
|
|
35
|
+
If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
|
|
36
|
+
|
|
37
|
+
### No Liability
|
|
38
|
+
|
|
39
|
+
*As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.*
|
|
40
|
+
|
|
41
|
+
### Definitions
|
|
42
|
+
|
|
43
|
+
The **licensor** is Pattern Agentic, the entity offering these terms.
|
|
44
|
+
|
|
45
|
+
The **software** is the software the licensor makes available under these terms, including any portion of it.
|
|
46
|
+
|
|
47
|
+
**You** refers to the individual or entity agreeing to these terms.
|
|
48
|
+
|
|
49
|
+
**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
|
|
50
|
+
|
|
51
|
+
**Your licenses** are all the licenses granted to you for the software under these terms.
|
|
52
|
+
|
|
53
|
+
**Use** means anything you do with the software requiring one of your licenses.
|
|
54
|
+
|
|
55
|
+
Copyright © 2025 Pattern Agentic. All rights reserved.
|