iagenify 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.
- iagenify/__init__.py +113 -0
- iagenify/client.py +229 -0
- iagenify/errors.py +31 -0
- iagenify/prompt.py +103 -0
- iagenify/resources.py +1823 -0
- iagenify/service_tools.py +1057 -0
- iagenify-0.1.0.dist-info/METADATA +188 -0
- iagenify-0.1.0.dist-info/RECORD +10 -0
- iagenify-0.1.0.dist-info/WHEEL +4 -0
- iagenify-0.1.0.dist-info/licenses/LICENSE +204 -0
iagenify/__init__.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""IaGenify Python SDK.
|
|
2
|
+
|
|
3
|
+
The public resource layout mirrors the JavaScript client while using normal
|
|
4
|
+
Python keyword arguments and synchronous calls.
|
|
5
|
+
"""
|
|
6
|
+
from .client import DEFAULT_BASE_URL, SDK_VERSION, IaGenifyClient
|
|
7
|
+
from .errors import IaGenifyError, NotEnoughCredits, RequestTimeout, Unauthorized, Unreachable
|
|
8
|
+
from .prompt import PROMPT_OPTIONS, parse_prompt, parse_token_count, storage_slug
|
|
9
|
+
from .resources import (
|
|
10
|
+
AccountLibrary, Agent, AgentLibrary, AgentTools, AgentsResource, AssistantSession,
|
|
11
|
+
AuthResource, CloudResource, ComputeResource, ComputeTerminal,
|
|
12
|
+
ConnectedStorage, ConvertResource, Domain, DomainsResource, FetchResource,
|
|
13
|
+
FilesResource, Host, HostsResource, IaGenifyFile, KeysResource,
|
|
14
|
+
LocalAgent, LocalFiles, LocalLibrary, LocalTerminals, MailResource, Mailbox,
|
|
15
|
+
McpClient, McpResource, MCP_PROTOCOL_VERSION, MemoryResource, ModelsResource, SearchResource,
|
|
16
|
+
StorageResource, Terminal, Workflow, WorkflowRun, WorkflowsResource, MEDIA_OPTIONS,
|
|
17
|
+
create_mcp_tools, sanitize_schema, tool_name_for, _items, encode_attachments, ALWAYS_ASK,
|
|
18
|
+
)
|
|
19
|
+
from .service_tools import SERVICE_TOOL_NAMES, create_service_tools
|
|
20
|
+
|
|
21
|
+
# JavaScript-name aliases ease migration; snake_case is the native Python API.
|
|
22
|
+
parsePrompt = parse_prompt
|
|
23
|
+
parseTokenCount = parse_token_count
|
|
24
|
+
storageSlug = storage_slug
|
|
25
|
+
sanitizeSchema = sanitize_schema
|
|
26
|
+
toolNameFor = tool_name_for
|
|
27
|
+
createMcpTools = create_mcp_tools
|
|
28
|
+
|
|
29
|
+
__version__ = SDK_VERSION
|
|
30
|
+
AGENT_MODES = ("ask", "auto", "plan", "full")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class IaGenify:
|
|
34
|
+
"""Synchronous client for the IaGenify API and agent services.
|
|
35
|
+
|
|
36
|
+
Example::
|
|
37
|
+
|
|
38
|
+
api = IaGenify(api_key="ia_...")
|
|
39
|
+
session = api.models.create(model="gemini-3.5-flash")
|
|
40
|
+
result = session.generate(inputs=[{"type": "text", "content": "Hello"}])
|
|
41
|
+
"""
|
|
42
|
+
def __init__(self, *, api_key=None, base_url=None, storage=None,
|
|
43
|
+
session_path=None, app_name=None, timeout=60.0, transport=None):
|
|
44
|
+
self._client = IaGenifyClient(api_key, base_url=base_url, storage=storage,
|
|
45
|
+
session_path=session_path, app_name=app_name,
|
|
46
|
+
timeout=timeout, transport=transport)
|
|
47
|
+
self.base_url = self._client.base_url
|
|
48
|
+
self.env = "python"
|
|
49
|
+
self.framework = "python"
|
|
50
|
+
self.capabilities = {"runtime": "python", "shell": True, "filesystem": True,
|
|
51
|
+
"persistentStorage": True, "http": True}
|
|
52
|
+
self.auth = AuthResource(self._client)
|
|
53
|
+
self.keys = KeysResource(self._client)
|
|
54
|
+
self.models = ModelsResource(self._client)
|
|
55
|
+
self.memory = MemoryResource(self._client)
|
|
56
|
+
self.files = FilesResource(self._client)
|
|
57
|
+
self.storage = StorageResource(self._client, app_name=app_name or "")
|
|
58
|
+
self.cloud = CloudResource(self._client)
|
|
59
|
+
self.search = SearchResource(self._client)
|
|
60
|
+
self.fetch = FetchResource(self._client)
|
|
61
|
+
self.convert = ConvertResource(self._client)
|
|
62
|
+
self.workflows = WorkflowsResource(self._client)
|
|
63
|
+
self.domains = DomainsResource(self._client)
|
|
64
|
+
self.mail = MailResource(self._client)
|
|
65
|
+
self.hosts = HostsResource(self._client)
|
|
66
|
+
self.compute = ComputeResource(self._client)
|
|
67
|
+
self.mcp = McpResource(self._client)
|
|
68
|
+
self.agents = AgentsResource(self._client, self)
|
|
69
|
+
self.tools = AgentTools(self)
|
|
70
|
+
|
|
71
|
+
def get_user(self):
|
|
72
|
+
user=self._client.get("/api/auth/me").get("user")
|
|
73
|
+
if not user: return None
|
|
74
|
+
return {"id":user.get("_id"),"email":user.get("email"),"credits":user.get("credits"),"pack":user.get("pack")}
|
|
75
|
+
|
|
76
|
+
def catalogue(self): return _items(self._client.get("/api/ai/prices"),"prices")
|
|
77
|
+
|
|
78
|
+
def get_storage(self):
|
|
79
|
+
storage=self._client.get("/api/storage/default").get("storage")
|
|
80
|
+
if not storage: return None
|
|
81
|
+
return {"id":storage.get("_id"),"label":storage.get("label"),"type":storage.get("type"),"tier":storage.get("tier")}
|
|
82
|
+
|
|
83
|
+
def session(self):
|
|
84
|
+
data=self._client._read_session() or {}
|
|
85
|
+
if data.get("session_id"): return {"id":data["session_id"],"storageId":data.get("storage_id")}
|
|
86
|
+
if data.get("jwt"):
|
|
87
|
+
try:
|
|
88
|
+
sessions=self._client.get("/api/auth/sessions").get("sessions",[])
|
|
89
|
+
match=next((x for x in sessions if x.get("isActive") and str(x.get("storageId"))==str(data.get("storage_id"))),None)
|
|
90
|
+
if match: return {"id":match.get("_id"),"storageId":match.get("storageId")}
|
|
91
|
+
except IaGenifyError: pass
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
def close(self): self._client.close()
|
|
95
|
+
def __enter__(self): return self
|
|
96
|
+
def __exit__(self,*_): self.close()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
__all__ = [
|
|
100
|
+
"IaGenify", "IaGenifyClient", "IaGenifyError", "Unauthorized", "NotEnoughCredits",
|
|
101
|
+
"RequestTimeout", "Unreachable", "DEFAULT_BASE_URL", "AssistantSession", "Agent", "AgentsResource",
|
|
102
|
+
"AgentLibrary", "AccountLibrary", "ConnectedStorage", "LocalFiles", "LocalTerminals", "Terminal", "LocalLibrary",
|
|
103
|
+
"LocalAgent", "IaGenifyFile", "Host", "Domain",
|
|
104
|
+
"Mailbox", "Workflow", "WorkflowRun", "ComputeTerminal", "McpClient", "McpResource", "MCP_PROTOCOL_VERSION",
|
|
105
|
+
"AuthResource", "KeysResource", "ModelsResource", "MemoryResource", "FilesResource",
|
|
106
|
+
"StorageResource", "CloudResource", "SearchResource", "FetchResource", "ConvertResource",
|
|
107
|
+
"WorkflowsResource", "DomainsResource", "MailResource", "HostsResource", "ComputeResource",
|
|
108
|
+
"AgentTools", "MEDIA_OPTIONS", "PROMPT_OPTIONS", "parsePrompt", "parseTokenCount", "storageSlug",
|
|
109
|
+
"sanitizeSchema", "toolNameFor", "createMcpTools",
|
|
110
|
+
"parse_prompt", "parse_token_count", "storage_slug", "sanitize_schema", "tool_name_for", "create_mcp_tools",
|
|
111
|
+
"AGENT_MODES", "SDK_VERSION", "__version__",
|
|
112
|
+
"encode_attachments", "ALWAYS_ASK", "SERVICE_TOOL_NAMES", "create_service_tools",
|
|
113
|
+
]
|
iagenify/client.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""HTTP transport, authentication and session persistence."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import secrets
|
|
9
|
+
import stat
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import urljoin
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from .errors import IaGenifyError, NotEnoughCredits, RequestTimeout, Unauthorized, Unreachable
|
|
18
|
+
|
|
19
|
+
SDK_VERSION = "0.1.0"
|
|
20
|
+
DEFAULT_BASE_URL = os.getenv("IAGENIFY_API_URL", "https://api.iagenify.com").rstrip("/")
|
|
21
|
+
_DEFAULT_TIMEOUT = object()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class IaGenifyClient:
|
|
25
|
+
def __init__(self, api_key=None, *, base_url=None, storage=None, session_path=None,
|
|
26
|
+
app_name=None, timeout=60.0, transport=None):
|
|
27
|
+
if not api_key and storage is None:
|
|
28
|
+
raise ValueError("IaGenify requires api_key or a custom session storage.")
|
|
29
|
+
self.api_key = api_key
|
|
30
|
+
self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
|
31
|
+
self.app_name = app_name or ""
|
|
32
|
+
self.timeout = timeout
|
|
33
|
+
self._custom_storage = storage
|
|
34
|
+
self.session_path = Path(session_path).expanduser() if session_path else Path.home() / ".iagenify" / "session"
|
|
35
|
+
self._session = None
|
|
36
|
+
self._machine_id = self._load_machine_id()
|
|
37
|
+
self._http = httpx.Client(timeout=timeout, transport=transport, follow_redirects=True)
|
|
38
|
+
|
|
39
|
+
@staticmethod
|
|
40
|
+
def _load_machine_id():
|
|
41
|
+
try:
|
|
42
|
+
p = Path.home() / ".iagenify" / "machine-id"
|
|
43
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
if p.exists():
|
|
45
|
+
return p.read_text(encoding="utf-8").strip()
|
|
46
|
+
value = secrets.token_hex(16)
|
|
47
|
+
p.write_text(value, encoding="utf-8")
|
|
48
|
+
try: p.chmod(0o600)
|
|
49
|
+
except OSError: pass
|
|
50
|
+
return value
|
|
51
|
+
except OSError:
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
def _read_session(self):
|
|
55
|
+
if self._session is not None:
|
|
56
|
+
return self._session
|
|
57
|
+
if self._custom_storage is not None:
|
|
58
|
+
self._session = self._custom_storage.read()
|
|
59
|
+
else:
|
|
60
|
+
try: self._session = json.loads(self.session_path.read_text(encoding="utf-8"))
|
|
61
|
+
except (OSError, ValueError): self._session = None
|
|
62
|
+
return self._session
|
|
63
|
+
|
|
64
|
+
def _write_session(self, session):
|
|
65
|
+
self._session = session
|
|
66
|
+
if self._custom_storage is not None:
|
|
67
|
+
self._custom_storage.write(session)
|
|
68
|
+
return
|
|
69
|
+
self.session_path.parent.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
try: self.session_path.parent.chmod(0o700)
|
|
71
|
+
except OSError: pass
|
|
72
|
+
self.session_path.write_text(json.dumps(session), encoding="utf-8")
|
|
73
|
+
try: self.session_path.chmod(0o600)
|
|
74
|
+
except OSError: pass
|
|
75
|
+
|
|
76
|
+
def _clear_session(self):
|
|
77
|
+
self._session = None
|
|
78
|
+
if self._custom_storage is not None:
|
|
79
|
+
self._custom_storage.clear()
|
|
80
|
+
else:
|
|
81
|
+
try: self.session_path.unlink()
|
|
82
|
+
except OSError: pass
|
|
83
|
+
|
|
84
|
+
@staticmethod
|
|
85
|
+
def _jwt_valid(jwt):
|
|
86
|
+
try:
|
|
87
|
+
import base64
|
|
88
|
+
part = jwt.split(".")[1]
|
|
89
|
+
part += "=" * (-len(part) % 4)
|
|
90
|
+
return json.loads(base64.urlsafe_b64decode(part)).get("exp", 0) * 1000 > time.time() * 1000
|
|
91
|
+
except Exception:
|
|
92
|
+
return False
|
|
93
|
+
|
|
94
|
+
def _raw(self, method, path, *, json_body=None, files=None, params=None, timeout=None):
|
|
95
|
+
url = self.base_url + path
|
|
96
|
+
headers = {"X-IaGenify-Version": SDK_VERSION}
|
|
97
|
+
if self.app_name: headers["X-IaGenify-App-Name"] = self.app_name
|
|
98
|
+
try:
|
|
99
|
+
response = self._http.request(method, url, json=json_body, files=files, params=params,
|
|
100
|
+
headers=headers, timeout=self.timeout if timeout is None else timeout)
|
|
101
|
+
except httpx.TimeoutException as exc:
|
|
102
|
+
raise RequestTimeout(f"No response from {url} within the configured timeout.") from exc
|
|
103
|
+
except httpx.HTTPError as exc:
|
|
104
|
+
raise Unreachable(f"IaGenify API is unreachable ({url}): {exc}") from exc
|
|
105
|
+
try: response_data = response.json()
|
|
106
|
+
except ValueError: response_data = {"msg": response.text}
|
|
107
|
+
return response, response_data
|
|
108
|
+
|
|
109
|
+
def _auth_headers(self, auth_required=True):
|
|
110
|
+
session = self._read_session() or {}
|
|
111
|
+
fingerprint = hashlib.sha256(str(self.api_key).encode()).hexdigest()[:16] if self.api_key else None
|
|
112
|
+
if session and fingerprint and session.get("key_fingerprint") != fingerprint:
|
|
113
|
+
self._clear_session()
|
|
114
|
+
session = {}
|
|
115
|
+
jwt = session.get("jwt")
|
|
116
|
+
if jwt and self._jwt_valid(jwt):
|
|
117
|
+
return {"Authorization": f"Bearer {jwt}"}
|
|
118
|
+
refresh = session.get("refresh_token")
|
|
119
|
+
if refresh:
|
|
120
|
+
try:
|
|
121
|
+
_, result = self._raw("POST", "/api/auth/refresh", json_body={"refreshToken": refresh}, timeout=30)
|
|
122
|
+
if result.get("ok"):
|
|
123
|
+
session.update(jwt=result.get("jwt"), refresh_token=result.get("refreshToken"))
|
|
124
|
+
self._write_session(session)
|
|
125
|
+
return {"Authorization": f"Bearer {session['jwt']}"}
|
|
126
|
+
except IaGenifyError:
|
|
127
|
+
pass
|
|
128
|
+
if not self.api_key:
|
|
129
|
+
if auth_required: raise Unauthorized("No valid session and no API key provided.")
|
|
130
|
+
return {}
|
|
131
|
+
body = {
|
|
132
|
+
"apiKey": self.api_key,
|
|
133
|
+
"storageId": session.get("storage_id"),
|
|
134
|
+
"storageType": "filesystem",
|
|
135
|
+
"framework": "python",
|
|
136
|
+
"appName": self.app_name,
|
|
137
|
+
"environment": {"os": platform.system().lower(), "arch": platform.machine(), "runtime": platform.python_version()},
|
|
138
|
+
"machineId": self._machine_id,
|
|
139
|
+
}
|
|
140
|
+
body = {key: value for key, value in body.items() if value is not None}
|
|
141
|
+
_, result = self._raw("POST", "/api/auth/sessions/exchange", json_body=body, timeout=30)
|
|
142
|
+
if not result.get("ok") or not result.get("jwt"):
|
|
143
|
+
raise Unauthorized(result.get("message") or result.get("error") or "Session exchange failed")
|
|
144
|
+
self._write_session({
|
|
145
|
+
"jwt": result.get("jwt"), "refresh_token": result.get("refreshToken"),
|
|
146
|
+
"session_id": (result.get("session") or {}).get("id"),
|
|
147
|
+
"storage_id": (result.get("session") or {}).get("storageId") or session.get("storage_id"),
|
|
148
|
+
"key_fingerprint": fingerprint,
|
|
149
|
+
})
|
|
150
|
+
return {"Authorization": f"Bearer {result['jwt']}"}
|
|
151
|
+
|
|
152
|
+
def request(self, method, path, *, json=None, files=None, data=None, params=None, timeout=_DEFAULT_TIMEOUT, auth=True, retry=True):
|
|
153
|
+
headers = self._auth_headers(auth)
|
|
154
|
+
if files is None and json is not None:
|
|
155
|
+
headers["Content-Type"] = "application/json"
|
|
156
|
+
try:
|
|
157
|
+
response = self._http.request(method, self.base_url + path, json=json, files=files, data=data, params=params,
|
|
158
|
+
headers={"X-IaGenify-Version": SDK_VERSION,
|
|
159
|
+
**({"X-IaGenify-App-Name": self.app_name} if self.app_name else {}),
|
|
160
|
+
**({"X-IaGenify-Machine-Id": self._machine_id} if self._machine_id else {}),
|
|
161
|
+
**headers}, timeout=self.timeout if timeout is _DEFAULT_TIMEOUT else timeout)
|
|
162
|
+
except httpx.TimeoutException as exc:
|
|
163
|
+
raise RequestTimeout(f"Request to {path} timed out.") from exc
|
|
164
|
+
except httpx.HTTPError as exc:
|
|
165
|
+
raise Unreachable(f"IaGenify API is unreachable ({path}): {exc}") from exc
|
|
166
|
+
try: response_data = response.json()
|
|
167
|
+
except ValueError: response_data = {"msg": response.text}
|
|
168
|
+
if response.status_code == 401 and retry:
|
|
169
|
+
session = self._read_session() or {}
|
|
170
|
+
if session.get("refresh_token"):
|
|
171
|
+
session["jwt"] = None
|
|
172
|
+
self._write_session(session)
|
|
173
|
+
return self.request(method, path, json=json, files=files, data=data, params=params, timeout=timeout, auth=auth, retry=False)
|
|
174
|
+
self._clear_session()
|
|
175
|
+
return self.request(method, path, json=json, files=files, data=data, params=params, timeout=timeout, auth=auth, retry=False)
|
|
176
|
+
if not response.is_success:
|
|
177
|
+
if response_data.get("notEnough") or response_data.get("error") == "not_enough_credits":
|
|
178
|
+
raise NotEnoughCredits(response_data.get("requiredCredits", response_data.get("required", 0)), (response_data.get("user") or {}).get("credits", response_data.get("available", 0)))
|
|
179
|
+
raise IaGenifyError(response.status_code, response_data.get("error") or response_data.get("code") or "unknown",
|
|
180
|
+
response_data.get("msg") or response_data.get("message") or response.reason_phrase,
|
|
181
|
+
response_data.get("details"))
|
|
182
|
+
return response_data
|
|
183
|
+
|
|
184
|
+
def get(self, path, *, params=None, timeout=_DEFAULT_TIMEOUT):
|
|
185
|
+
return self.request("GET", path, params=params, timeout=timeout)
|
|
186
|
+
def post(self, path, body=None, *, files=None, timeout=_DEFAULT_TIMEOUT):
|
|
187
|
+
return self.request("POST", path, json=None if files else body, files=files, data=body if files else None, timeout=timeout)
|
|
188
|
+
def put(self, path, body=None, *, files=None, timeout=_DEFAULT_TIMEOUT):
|
|
189
|
+
return self.request("PUT", path, json=None if files else body, files=files, data=body if files else None, timeout=timeout)
|
|
190
|
+
def patch(self, path, body=None, *, files=None, timeout=_DEFAULT_TIMEOUT):
|
|
191
|
+
return self.request("PATCH", path, json=body, files=files, timeout=timeout)
|
|
192
|
+
def delete(self, path, *, params=None):
|
|
193
|
+
return self.request("DELETE", path, params=params)
|
|
194
|
+
|
|
195
|
+
def stream(self, path, body, *, timeout=_DEFAULT_TIMEOUT):
|
|
196
|
+
headers = self._auth_headers(True)
|
|
197
|
+
headers.update({"X-IaGenify-Version": SDK_VERSION, "Content-Type": "application/json", "Accept": "text/event-stream"})
|
|
198
|
+
if self.app_name: headers["X-IaGenify-App-Name"] = self.app_name
|
|
199
|
+
if self._machine_id: headers["X-IaGenify-Machine-Id"] = self._machine_id
|
|
200
|
+
try:
|
|
201
|
+
with self._http.stream("POST", self.base_url + path, json=body, headers=headers,
|
|
202
|
+
timeout=self.timeout if timeout is _DEFAULT_TIMEOUT else timeout) as response:
|
|
203
|
+
if not response.is_success:
|
|
204
|
+
try: data=response.json()
|
|
205
|
+
except ValueError: data={"msg":response.read().decode(errors="replace")}
|
|
206
|
+
if data.get("notEnough"): raise NotEnoughCredits(data.get("requiredCredits",0),(data.get("user") or {}).get("credits",0))
|
|
207
|
+
raise IaGenifyError(response.status_code,data.get("error") or data.get("code") or "unknown",data.get("msg") or data.get("message") or response.reason_phrase,data.get("details"))
|
|
208
|
+
event="message"; payload=[]
|
|
209
|
+
for line in response.iter_lines():
|
|
210
|
+
if isinstance(line,bytes): line=line.decode("utf-8",errors="replace")
|
|
211
|
+
if not line:
|
|
212
|
+
if payload:
|
|
213
|
+
try: data=json.loads("\n".join(payload))
|
|
214
|
+
except ValueError: data={}
|
|
215
|
+
yield event,data
|
|
216
|
+
event="message"; payload=[]
|
|
217
|
+
elif line.startswith("event:"): event=line[6:].strip()
|
|
218
|
+
elif line.startswith("data:"): payload.append(line[5:].strip())
|
|
219
|
+
except httpx.TimeoutException as exc:
|
|
220
|
+
raise RequestTimeout(f"Stream from {path} timed out.") from exc
|
|
221
|
+
except httpx.HTTPError as exc:
|
|
222
|
+
raise Unreachable(f"IaGenify API is unreachable ({path}): {exc}") from exc
|
|
223
|
+
|
|
224
|
+
def close(self):
|
|
225
|
+
self._http.close()
|
|
226
|
+
|
|
227
|
+
def __enter__(self): return self
|
|
228
|
+
def __exit__(self, *_): self.close()
|
|
229
|
+
|
iagenify/errors.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Typed errors raised by the IaGenify client."""
|
|
2
|
+
|
|
3
|
+
class IaGenifyError(Exception):
|
|
4
|
+
def __init__(self, status: int, code: str, message: str, details=None):
|
|
5
|
+
super().__init__(message)
|
|
6
|
+
self.status = status
|
|
7
|
+
self.code = code
|
|
8
|
+
self.details = details
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Unauthorized(IaGenifyError):
|
|
12
|
+
def __init__(self, message="Unauthorized"):
|
|
13
|
+
super().__init__(401, "unauthorized", message)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class NotEnoughCredits(IaGenifyError):
|
|
17
|
+
def __init__(self, required: int = 0, available: int = 0):
|
|
18
|
+
super().__init__(402, "not_enough_credits", f"Need {required} credits, have {available}")
|
|
19
|
+
self.required = required
|
|
20
|
+
self.available = available
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class RequestTimeout(IaGenifyError):
|
|
24
|
+
def __init__(self, message="The request timed out"):
|
|
25
|
+
super().__init__(408, "timeout", message)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Unreachable(IaGenifyError):
|
|
29
|
+
def __init__(self, message="IaGenify API is unreachable"):
|
|
30
|
+
super().__init__(503, "unreachable", message)
|
|
31
|
+
|
iagenify/prompt.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Python implementation of the SDK prompt syntax helpers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
import unicodedata
|
|
6
|
+
|
|
7
|
+
from .errors import IaGenifyError
|
|
8
|
+
|
|
9
|
+
PROMPT_OPTIONS = {
|
|
10
|
+
"model": "text", "mode": ["ask", "auto", "plan", "full"],
|
|
11
|
+
"budget": "credits", "context": "tokens", "agent": "text", "no-memory": "flag",
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse_token_count(value):
|
|
16
|
+
match = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([kKmM])?", str(value or "").strip().replace("_", ""))
|
|
17
|
+
if not match:
|
|
18
|
+
return None
|
|
19
|
+
amount = float(match.group(1)) * {None: 1, "k": 1_000, "m": 1_000_000}[match.group(2).lower() if match.group(2) else None]
|
|
20
|
+
return round(amount) if amount > 0 else None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def storage_slug(label):
|
|
24
|
+
value = unicodedata.normalize("NFD", str(label or "").lower())
|
|
25
|
+
value = "".join(char for char in value if unicodedata.category(char) != "Mn")
|
|
26
|
+
value = re.sub(r"['-?]", "", value)
|
|
27
|
+
return re.sub(r"^-+|-+$", "", re.sub(r"[^a-z0-9]+", "-", value))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _fail(code, message):
|
|
31
|
+
raise IaGenifyError(400, code, message)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def parse_prompt(value, library=None):
|
|
35
|
+
"""Parse leading options and skill/agent mentions plus file/storage references."""
|
|
36
|
+
library = library or {}
|
|
37
|
+
skills = {item if isinstance(item, str) else item.get("name") for item in library.get("skills", [])}
|
|
38
|
+
agents = {item if isinstance(item, str) else item.get("name") for item in library.get("agents", [])}
|
|
39
|
+
rest = str(value or "")
|
|
40
|
+
options = {}
|
|
41
|
+
while True:
|
|
42
|
+
flag = re.match(r"^\s*--([a-z][a-z-]*)(?=\s|=|$)", rest, re.I)
|
|
43
|
+
if not flag:
|
|
44
|
+
break
|
|
45
|
+
key = flag.group(1).lower()
|
|
46
|
+
kind = PROMPT_OPTIONS.get(key)
|
|
47
|
+
if kind is None:
|
|
48
|
+
_fail("unknown_option", f"Unknown option --{key}. Options: {' '.join('--'+name for name in PROMPT_OPTIONS)}.")
|
|
49
|
+
rest = rest[flag.end():]
|
|
50
|
+
if kind == "flag":
|
|
51
|
+
if key == "no-memory": options["memory"] = False
|
|
52
|
+
continue
|
|
53
|
+
found = re.match(r"^(?:=|[ \t]+)(?:\"([^\"]*)\"|'([^']*)'|(\S+))", rest)
|
|
54
|
+
if not found:
|
|
55
|
+
_fail("option_value_required", f"--{key} needs a value.")
|
|
56
|
+
val = next(group for group in found.groups() if group is not None)
|
|
57
|
+
rest = rest[found.end():]
|
|
58
|
+
if key == "mode":
|
|
59
|
+
if val not in kind: _fail("invalid_option", f"--mode must be one of {', '.join(kind)}.")
|
|
60
|
+
options[key] = val
|
|
61
|
+
elif key == "budget":
|
|
62
|
+
if val == "none": options[key] = None
|
|
63
|
+
elif val.isdigit() and int(val) > 0: options[key] = round(float(val))
|
|
64
|
+
else: _fail("invalid_option", "--budget takes a number of credits, or none.")
|
|
65
|
+
elif key == "context":
|
|
66
|
+
tokens = parse_token_count(val)
|
|
67
|
+
if not tokens: _fail("invalid_option", "--context takes a number of tokens: 200k, 400k, 1M.")
|
|
68
|
+
options["contextTokens"] = tokens
|
|
69
|
+
else:
|
|
70
|
+
options[key] = val
|
|
71
|
+
rest = rest.lstrip()
|
|
72
|
+
command = delegate = None
|
|
73
|
+
head = re.match(r"^([/@])([a-z0-9][a-z0-9-]{0,63})(?:[ \t]+([\s\S]*)|\n([\s\S]*))?$", rest)
|
|
74
|
+
if head:
|
|
75
|
+
sigil, name = head.group(1), head.group(2)
|
|
76
|
+
args = (head.group(3) or head.group(4) or "").strip()
|
|
77
|
+
if sigil == "/" and name in skills:
|
|
78
|
+
command = {"name": name, "kind": "skill", "arguments": args}; rest = args
|
|
79
|
+
elif sigil == "@" and name in agents:
|
|
80
|
+
delegate = {"agent": name, "prompt": args}; rest = args
|
|
81
|
+
files=[]
|
|
82
|
+
for match in re.finditer(r"(^|[\s(\[\"'`])@(?:\"([^\"\n]+)\"|([^\s@#,;!?()[\]\"'`]+))", rest):
|
|
83
|
+
path=(match.group(2) or re.sub(r"[.:]+$", "", match.group(3) or "")).strip()
|
|
84
|
+
if path and not (match.group(3) and path in agents) and path not in files: files.append(path)
|
|
85
|
+
index={}
|
|
86
|
+
by_provider={}
|
|
87
|
+
storages_in=library.get("storages", [])
|
|
88
|
+
for storage in storages_in:
|
|
89
|
+
if not storage: continue
|
|
90
|
+
slug=storage_slug(storage.get("label") or storage.get("name"))
|
|
91
|
+
if slug: index[slug]=storage
|
|
92
|
+
if storage.get("provider"): by_provider.setdefault(storage["provider"], []).append(storage)
|
|
93
|
+
for provider, items in by_provider.items():
|
|
94
|
+
if len(items)==1 and provider not in index: index[provider]=items[0]
|
|
95
|
+
storages=[]
|
|
96
|
+
for match in re.finditer(r"(^|[\s(\[\"'`])#([a-z0-9][a-z0-9-]*)(?:\.([\w$-][\w$.-]*))?", rest, re.I):
|
|
97
|
+
storage=index.get(match.group(2).lower())
|
|
98
|
+
if not storage: continue
|
|
99
|
+
collection=match.group(3).rstrip(".") if match.group(3) else None
|
|
100
|
+
if not any(item["id"]==storage.get("id") and item["collection"]==collection for item in storages):
|
|
101
|
+
storages.append({"id":storage.get("id"),"name":storage.get("label") or storage.get("name"),"provider":storage.get("service") or storage.get("provider"),"collection":collection})
|
|
102
|
+
text=re.sub(r"\\(@|#|--)",r"\1",rest)
|
|
103
|
+
return {"options":options,"command":command,"delegate":delegate,"files":files,"storages":storages,"text":text}
|