Skip to content

Commit 70eb7fc

Browse files
author
balogh.adam@icloud.com
committed
rm exception
1 parent 12bd1fc commit 70eb7fc

9 files changed

Lines changed: 58 additions & 180 deletions

File tree

src/opengradient/client/_utils.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
from pathlib import Path
44
from typing import Callable
55

6-
from .exceptions import OpenGradientError
7-
86
_ABI_DIR = Path(__file__).parent.parent / "abi"
97
_BIN_DIR = Path(__file__).parent.parent / "bin"
108

@@ -58,7 +56,7 @@ def run_with_retry(
5856

5957
if any(error in error_msg for error in _NONCE_ERRORS):
6058
if attempt == effective_retries - 1:
61-
raise OpenGradientError(f"Transaction failed after {effective_retries} attempts: {e}")
59+
raise RuntimeError(f"Transaction failed after {effective_retries} attempts: {e}")
6260
time.sleep(retry_delay)
6361
continue
6462

src/opengradient/client/alpha.py

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
from ..types import HistoricalInputQuery, InferenceMode, InferenceResult, ModelOutput, SchedulerParams
2222
from ._conversions import convert_array_to_model_output, convert_to_model_input, convert_to_model_output
2323
from ._utils import get_abi, get_bin, run_with_retry
24-
from .exceptions import OpenGradientError
2524

2625
# How much time we wait for txn to be included in chain
2726
INFERENCE_TX_TIMEOUT = 120
@@ -91,7 +90,7 @@ def infer(
9190
model_output (Dict[str, np.ndarray]): Output of the ONNX model
9291
9392
Raises:
94-
OpenGradientError: If the inference fails.
93+
RuntimeError: If the inference fails.
9594
"""
9695

9796
def execute_transaction():
@@ -106,7 +105,7 @@ def execute_transaction():
106105
tx_hash, tx_receipt = self._send_tx_with_revert_handling(run_function)
107106
parsed_logs = contract.events.InferenceResult().process_receipt(tx_receipt, errors=DISCARD)
108107
if len(parsed_logs) < 1:
109-
raise OpenGradientError("InferenceResult event not found in transaction logs")
108+
raise RuntimeError("InferenceResult event not found in transaction logs")
110109

111110
# TODO: This should return a ModelOutput class object
112111
model_output = convert_to_model_output(parsed_logs[0]["args"])
@@ -184,7 +183,7 @@ def _get_inference_result_from_node(self, inference_id: str, inference_mode: Inf
184183
Dict: The inference result as returned by the node
185184
186185
Raises:
187-
OpenGradientError: If the request fails or returns an error
186+
RuntimeError: If the request fails or returns an error
188187
"""
189188
try:
190189
encoded_id = urllib.parse.quote(inference_id, safe="")
@@ -199,50 +198,50 @@ def _get_inference_result_from_node(self, inference_id: str, inference_mode: Inf
199198
decoded_string = decoded_bytes.decode("utf-8")
200199
output = json.loads(decoded_string).get("InferenceResult", {})
201200
if output is None:
202-
raise OpenGradientError("Missing InferenceResult in inference output")
201+
raise RuntimeError("Missing InferenceResult in inference output")
203202

204203
match inference_mode:
205204
case InferenceMode.VANILLA:
206205
if "VanillaResult" not in output:
207-
raise OpenGradientError("Missing VanillaResult in inference output")
206+
raise RuntimeError("Missing VanillaResult in inference output")
208207
if "model_output" not in output["VanillaResult"]:
209-
raise OpenGradientError("Missing model_output in VanillaResult")
208+
raise RuntimeError("Missing model_output in VanillaResult")
210209
return {"output": output["VanillaResult"]["model_output"]}
211210

212211
case InferenceMode.TEE:
213212
if "TeeNodeResult" not in output:
214-
raise OpenGradientError("Missing TeeNodeResult in inference output")
213+
raise RuntimeError("Missing TeeNodeResult in inference output")
215214
if "Response" not in output["TeeNodeResult"]:
216-
raise OpenGradientError("Missing Response in TeeNodeResult")
215+
raise RuntimeError("Missing Response in TeeNodeResult")
217216
if "VanillaResponse" in output["TeeNodeResult"]["Response"]:
218217
if "model_output" not in output["TeeNodeResult"]["Response"]["VanillaResponse"]:
219-
raise OpenGradientError("Missing model_output in VanillaResponse")
218+
raise RuntimeError("Missing model_output in VanillaResponse")
220219
return {"output": output["TeeNodeResult"]["Response"]["VanillaResponse"]["model_output"]}
221220

222221
else:
223-
raise OpenGradientError("Missing VanillaResponse in TeeNodeResult Response")
222+
raise RuntimeError("Missing VanillaResponse in TeeNodeResult Response")
224223

225224
case InferenceMode.ZKML:
226225
if "ZkmlResult" not in output:
227-
raise OpenGradientError("Missing ZkmlResult in inference output")
226+
raise RuntimeError("Missing ZkmlResult in inference output")
228227
if "model_output" not in output["ZkmlResult"]:
229-
raise OpenGradientError("Missing model_output in ZkmlResult")
228+
raise RuntimeError("Missing model_output in ZkmlResult")
230229
return {"output": output["ZkmlResult"]["model_output"]}
231230

232231
case _:
233-
raise OpenGradientError(f"Invalid inference mode: {inference_mode}")
232+
raise ValueError(f"Invalid inference mode: {inference_mode}")
234233
else:
235234
return None
236235

237236
else:
238-
raise OpenGradientError(f"Failed to get inference result: HTTP {response.status_code}")
237+
raise RuntimeError(f"Failed to get inference result: HTTP {response.status_code}")
239238

240239
except requests.RequestException as e:
241-
raise OpenGradientError(f"Failed to get inference result: {str(e)}")
242-
except OpenGradientError:
240+
raise RuntimeError(f"Failed to get inference result: {str(e)}")
241+
except (RuntimeError, ValueError):
243242
raise
244243
except Exception as e:
245-
raise OpenGradientError(f"Failed to get inference result: {str(e)}")
244+
raise RuntimeError(f"Failed to get inference result: {str(e)}")
246245

247246
def new_workflow(
248247
self,

src/opengradient/client/exceptions.py

Lines changed: 0 additions & 112 deletions
This file was deleted.

src/opengradient/client/llm.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from x402v2.mechanisms.evm.upto.register import register_upto_evm_client as register_upto_evm_clientv2
1515

1616
from ..types import TEE_LLM, StreamChoice, StreamChunk, StreamDelta, TextGenerationOutput, x402SettlementMode
17-
from .exceptions import OpenGradientError
1817
from .opg_token import Permit2ApprovalResult, ensure_opg_approval
1918
from .tee_registry import TEERegistry, build_ssl_context_from_der
2019

@@ -186,7 +185,7 @@ def ensure_opg_approval(self, opg_amount: float) -> Permit2ApprovalResult:
186185
187186
Raises:
188187
ValueError: If the OPG amount is less than 0.05.
189-
OpenGradientError: If the approval transaction fails.
188+
RuntimeError: If the approval transaction fails.
190189
"""
191190
if opg_amount < 0.05:
192191
raise ValueError("OPG amount must be at least 0.05.")
@@ -223,7 +222,7 @@ async def completion(
223222
- Payment hash for x402 transactions
224223
225224
Raises:
226-
OpenGradientError: If the inference fails.
225+
RuntimeError: If the inference fails.
227226
"""
228227
model_id = model.split("/")[1]
229228
headers = self._headers(x402_settlement_mode)
@@ -253,10 +252,10 @@ async def completion(
253252
tee_timestamp=result.get("tee_timestamp"),
254253
**self._tee_metadata(),
255254
)
256-
except OpenGradientError:
255+
except RuntimeError:
257256
raise
258257
except Exception as e:
259-
raise OpenGradientError(f"TEE LLM completion failed: {e}") from e
258+
raise RuntimeError(f"TEE LLM completion failed: {e}") from e
260259

261260
async def chat(
262261
self,
@@ -294,7 +293,7 @@ async def chat(
294293
- If stream=True: Async generator yielding StreamChunk objects
295294
296295
Raises:
297-
OpenGradientError: If the inference fails.
296+
RuntimeError: If the inference fails.
298297
"""
299298
params = _ChatParams(
300299
model=model.split("/")[1],
@@ -336,7 +335,7 @@ async def _chat_request(self, params: _ChatParams, messages: List[Dict]) -> Text
336335

337336
choices = result.get("choices")
338337
if not choices:
339-
raise OpenGradientError(f"Invalid response: 'choices' missing or empty in {result}")
338+
raise RuntimeError(f"Invalid response: 'choices' missing or empty in {result}")
340339

341340
message = choices[0].get("message", {})
342341
content = message.get("content")
@@ -353,10 +352,10 @@ async def _chat_request(self, params: _ChatParams, messages: List[Dict]) -> Text
353352
tee_timestamp=result.get("tee_timestamp"),
354353
**self._tee_metadata(),
355354
)
356-
except OpenGradientError:
355+
except RuntimeError:
357356
raise
358357
except Exception as e:
359-
raise OpenGradientError(f"TEE LLM chat failed: {e}") from e
358+
raise RuntimeError(f"TEE LLM chat failed: {e}") from e
360359

361360
async def _chat_tools_as_stream(self, params: _ChatParams, messages: List[Dict]) -> AsyncGenerator[StreamChunk, None]:
362361
"""Non-streaming fallback for tool-call requests wrapped as a single StreamChunk."""
@@ -403,7 +402,7 @@ async def _parse_sse_response(self, response) -> AsyncGenerator[StreamChunk, Non
403402
status_code = getattr(response, "status_code", None)
404403
if status_code is not None and status_code >= 400:
405404
body = await response.aread()
406-
raise OpenGradientError(f"TEE LLM streaming request failed with status {status_code}: {body.decode('utf-8', errors='replace')}")
405+
raise RuntimeError(f"TEE LLM streaming request failed with status {status_code}: {body.decode('utf-8', errors='replace')}")
407406

408407
buffer = b""
409408
async for raw_chunk in response.aiter_raw():

src/opengradient/client/model_hub.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from requests_toolbelt import MultipartEncoder # type: ignore[import-untyped]
99

1010
from ..types import FileUploadResult, ModelRepository
11-
from .exceptions import OpenGradientError
1211

1312
# Security Update: Credentials moved to environment variables
1413
_FIREBASE_CONFIG = {
@@ -72,7 +71,7 @@ def create_model(self, model_name: str, model_desc: str, version: str = "1.00")
7271
response.raise_for_status()
7372
except requests.HTTPError as e:
7473
error_details = f"HTTP {e.response.status_code}: {e.response.text}"
75-
raise OpenGradientError(f"Model creation failed: {error_details}") from e
74+
raise RuntimeError(f"Model creation failed: {error_details}") from e
7675

7776
json_response = response.json()
7877
model_name = json_response.get("name")
@@ -140,7 +139,7 @@ def upload(self, model_path: str, model_name: str, version: str) -> FileUploadRe
140139
dict: The processed result.
141140
142141
Raises:
143-
OpenGradientError: If the upload fails.
142+
RuntimeError: If the upload fails.
144143
"""
145144

146145
if not self._hub_user:
@@ -166,17 +165,17 @@ def upload(self, model_path: str, model_name: str, version: str) -> FileUploadRe
166165
else:
167166
raise RuntimeError("Empty or null response content received")
168167
elif response.status_code == 500:
169-
raise OpenGradientError("Internal server error occurred", status_code=500)
168+
raise RuntimeError("Internal server error occurred", status_code=500)
170169
else:
171170
error_message = response.json().get("detail", "Unknown error occurred")
172-
raise OpenGradientError(f"Upload failed: {error_message}", status_code=response.status_code)
171+
raise RuntimeError(f"Upload failed: {error_message}", status_code=response.status_code)
173172

174173
except requests.RequestException as e:
175-
raise OpenGradientError(f"Upload failed: {str(e)}")
176-
except OpenGradientError:
174+
raise RuntimeError(f"Upload failed: {str(e)}")
175+
except RuntimeError:
177176
raise
178177
except Exception as e:
179-
raise OpenGradientError(f"Unexpected error during upload: {str(e)}")
178+
raise RuntimeError(f"Unexpected error during upload: {str(e)}")
180179

181180
def list_files(self, model_name: str, version: str) -> List[Dict]:
182181
"""
@@ -190,7 +189,7 @@ def list_files(self, model_name: str, version: str) -> List[Dict]:
190189
List[Dict]: A list of dictionaries containing file information.
191190
192191
Raises:
193-
OpenGradientError: If the file listing fails.
192+
RuntimeError: If the file listing fails.
194193
"""
195194
if not self._hub_user:
196195
raise ValueError("User not authenticated")
@@ -204,6 +203,6 @@ def list_files(self, model_name: str, version: str) -> List[Dict]:
204203
return response.json()
205204

206205
except requests.RequestException as e:
207-
raise OpenGradientError(f"File listing failed: {str(e)}")
206+
raise RuntimeError(f"File listing failed: {str(e)}")
208207
except Exception as e:
209-
raise OpenGradientError(f"Unexpected error during file listing: {str(e)}")
208+
raise RuntimeError(f"Unexpected error during file listing: {str(e)}")

0 commit comments

Comments
 (0)