assistant-runtime-sdk 1.13.0__tar.gz → 1.14.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: assistant_runtime_sdk
3
- Version: 1.13.0
3
+ Version: 1.14.0
4
4
  Summary: Python SDK for FAC Cloud - the Assistant Runtime AI assistant backend
5
5
  Keywords: frappe,ai,assistant,llm,mcp,anthropic,openai,streaming
6
6
  Author: Paul Clinton
@@ -53,7 +53,7 @@ Standalone Functions:
53
53
 
54
54
  """
55
55
 
56
- __version__ = "1.13.0"
56
+ __version__ = "1.14.0"
57
57
  __author__ = "Paul Clinton"
58
58
  __license__ = "AGPL-3.0"
59
59
 
@@ -16,13 +16,14 @@ try:
16
16
  except ImportError:
17
17
  aiohttp = None # type: ignore
18
18
 
19
- from .base import BaseAssistantRuntimeClient
19
+ from .base import BaseAssistantRuntimeClient, _busy_stream_error, _http_error, _retry_after_from
20
20
  from .exceptions import (
21
21
  ARAPIError,
22
22
  ARAuthenticationError,
23
23
  ARTimeoutError,
24
24
  ARConnectionError,
25
25
  ARConfigurationError,
26
+ ARRateLimitError,
26
27
  )
27
28
 
28
29
 
@@ -134,13 +135,12 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
134
135
  except Exception:
135
136
  pass
136
137
 
137
- if response.status == 401:
138
- raise ARAuthenticationError(msg or "Authentication failed")
139
-
140
- raise ARAPIError(
138
+ raise _http_error(
139
+ response.status,
140
+ response.headers,
141
141
  msg or f"{method} {endpoint} failed with status {response.status}",
142
- status_code=response.status,
143
- response_data=data,
142
+ data,
143
+ ARAPIError(f"{method} {endpoint} failed with status {response.status}"),
144
144
  )
145
145
 
146
146
  async def _request_get(
@@ -162,7 +162,7 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
162
162
  await self._handle_error_response(response, endpoint, "GET")
163
163
  data = await response.json()
164
164
  return data.get("message", data)
165
- except (ARAuthenticationError, ARAPIError):
165
+ except (ARAuthenticationError, ARRateLimitError, ARAPIError):
166
166
  raise
167
167
  except aiohttp.ServerTimeoutError as e:
168
168
  self._log_error(f"GET {endpoint} timeout: {e}")
@@ -206,7 +206,7 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
206
206
  filename = parts[1].strip().strip('"')
207
207
 
208
208
  return content, content_type, filename
209
- except (ARAuthenticationError, ARAPIError):
209
+ except (ARAuthenticationError, ARRateLimitError, ARAPIError):
210
210
  raise
211
211
  except aiohttp.ServerTimeoutError as e:
212
212
  self._log_error(f"GET raw {endpoint} timeout: {e}")
@@ -240,7 +240,7 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
240
240
  await self._handle_error_response(response, endpoint, "POST")
241
241
  data = await response.json()
242
242
  return data.get("message", data)
243
- except (ARAuthenticationError, ARAPIError):
243
+ except (ARAuthenticationError, ARRateLimitError, ARAPIError):
244
244
  raise
245
245
  except aiohttp.ServerTimeoutError as e:
246
246
  self._log_error(f"POST {endpoint} timeout: {e}")
@@ -274,7 +274,7 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
274
274
  await self._handle_error_response(response, endpoint, "POST form")
275
275
  data = await response.json()
276
276
  return data.get("message", data)
277
- except (ARAuthenticationError, ARAPIError):
277
+ except (ARAuthenticationError, ARRateLimitError, ARAPIError):
278
278
  raise
279
279
  except aiohttp.ServerTimeoutError as e:
280
280
  self._log_error(f"POST form {endpoint} timeout: {e}")
@@ -320,7 +320,7 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
320
320
  await self._handle_error_response(response, endpoint, "POST multipart")
321
321
  data = await response.json()
322
322
  return data.get("message", data)
323
- except (ARAuthenticationError, ARAPIError):
323
+ except (ARAuthenticationError, ARRateLimitError, ARAPIError):
324
324
  raise
325
325
  except aiohttp.ServerTimeoutError as e:
326
326
  self._log_error(f"POST multipart {endpoint} timeout: {e}")
@@ -351,7 +351,7 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
351
351
  await self._handle_error_response(response, endpoint, "DELETE")
352
352
  data = await response.json()
353
353
  return data.get("message", data)
354
- except (ARAuthenticationError, ARAPIError):
354
+ except (ARAuthenticationError, ARRateLimitError, ARAPIError):
355
355
  raise
356
356
  except aiohttp.ServerTimeoutError as e:
357
357
  self._log_error(f"DELETE {endpoint} timeout: {e}")
@@ -422,6 +422,9 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
422
422
  total=self.STREAM_READ_TIMEOUT,
423
423
  )
424
424
  async with session.post(url, json=payload, headers=headers, timeout=timeout) as response:
425
+ if response.status == 503:
426
+ yield _busy_stream_error(_retry_after_from(response.headers))
427
+ return
425
428
  response.raise_for_status()
426
429
 
427
430
  current_event = None
@@ -10,11 +10,65 @@ Both AssistantRuntimeClient (sync) and AsyncAssistantRuntimeClient (async) inher
10
10
 
11
11
  import json
12
12
  import logging
13
- from typing import Dict, Any, List, Optional, Protocol, runtime_checkable
13
+ import math
14
+ from typing import Dict, Any, List, Mapping, Optional, Protocol, runtime_checkable
14
15
 
15
16
  from .auth import generate_signature
16
17
  from .streaming import parse_sse_line
17
- from .exceptions import ARConfigurationError, ARBillingUnavailableError, ARAuthenticationError
18
+ from .exceptions import (
19
+ ARAPIError,
20
+ ARAuthenticationError,
21
+ ARBillingUnavailableError,
22
+ ARConfigurationError,
23
+ ARError,
24
+ ARRateLimitError,
25
+ )
26
+
27
+ BUSY_ERROR_CODE = "AR_BUSY"
28
+ DEFAULT_BUSY_RETRY_AFTER = 5.0
29
+
30
+
31
+ def _retry_after_from(headers: Mapping[str, str]) -> float:
32
+ """Return the ``Retry-After`` header as seconds, or the default when absent, non-finite or negative."""
33
+ try:
34
+ value = float(headers.get("Retry-After"))
35
+ except (TypeError, ValueError):
36
+ return DEFAULT_BUSY_RETRY_AFTER
37
+ if not math.isfinite(value) or value < 0:
38
+ return DEFAULT_BUSY_RETRY_AFTER
39
+ return value
40
+
41
+
42
+ def _busy_stream_error(retry_after: float) -> Dict[str, Any]:
43
+ """The ``stream_error`` event emitted when AR refuses a stream with HTTP 503."""
44
+ return {
45
+ "event": "stream_error",
46
+ "data": {
47
+ "error": "The assistant is busy right now. Retrying shortly.",
48
+ "error_code": BUSY_ERROR_CODE,
49
+ "retryable": True,
50
+ "retry_after": retry_after,
51
+ },
52
+ }
53
+
54
+
55
+ def _http_error(
56
+ status_code: Optional[int],
57
+ headers: Mapping[str, str],
58
+ msg: Optional[str],
59
+ body: Optional[Dict[str, Any]],
60
+ cause: Exception,
61
+ ) -> ARError:
62
+ """Map a failed HTTP response to the SDK exception callers should see."""
63
+ if status_code == 401:
64
+ return ARAuthenticationError(msg or "Authentication failed")
65
+ if status_code == 503:
66
+ return ARRateLimitError(
67
+ msg or "Service busy",
68
+ retry_after=_retry_after_from(headers),
69
+ error_code=BUSY_ERROR_CODE,
70
+ )
71
+ return ARAPIError(msg or str(cause), status_code=status_code, response_data=body)
18
72
 
19
73
 
20
74
  @runtime_checkable
@@ -452,6 +506,13 @@ class BaseAssistantRuntimeClient:
452
506
  """Log an error message."""
453
507
  self.logger.error(message, extra={"category": category})
454
508
 
509
+ def _log_http_error(self, message: str, response: Any = None, category: str = "AR") -> None:
510
+ """Log an HTTP error; a 404 is an expected answer for several calls, so it is a warning."""
511
+ if response is not None and getattr(response, "status_code", None) == 404:
512
+ self._log_warning(message, category)
513
+ else:
514
+ self._log_error(message, category)
515
+
455
516
  def _log_warning(self, message: str, category: str = "AR") -> None:
456
517
  """Log a warning message."""
457
518
  self.logger.warning(message, extra={"category": category})
@@ -14,7 +14,7 @@ from typing import Generator, List, Optional, Dict, Any
14
14
 
15
15
  import requests
16
16
 
17
- from .base import BaseAssistantRuntimeClient
17
+ from .base import BaseAssistantRuntimeClient, _busy_stream_error, _http_error, _retry_after_from
18
18
  from .exceptions import (
19
19
  ARAPIError,
20
20
  ARAuthenticationError,
@@ -84,14 +84,13 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
84
84
  self._log_error(f"GET {endpoint} connection error: {e}")
85
85
  raise ARConnectionError(f"Failed to connect to {endpoint}") from e
86
86
  except requests.exceptions.HTTPError as e:
87
- self._log_error(f"GET {endpoint} HTTP error: {e}")
87
+ self._log_http_error(f"GET {endpoint} HTTP error: {e}", e.response)
88
88
  status_code = e.response.status_code if e.response is not None else None
89
89
  msg, body = (
90
90
  self._extract_error_payload(e.response) if e.response is not None else (None, None)
91
91
  )
92
- if status_code == 401:
93
- raise ARAuthenticationError(msg or "Authentication failed") from e
94
- raise ARAPIError(msg or str(e), status_code=status_code, response_data=body) from e
92
+ headers = e.response.headers if e.response is not None else {}
93
+ raise _http_error(status_code, headers, msg, body, e) from e
95
94
  except requests.exceptions.RequestException as e:
96
95
  self._log_error(f"GET {endpoint} error: {e}")
97
96
  raise ARAPIError(str(e)) from e
@@ -134,14 +133,13 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
134
133
  self._log_error(f"GET raw {endpoint} connection error: {e}")
135
134
  raise ARConnectionError(f"Failed to connect to {endpoint}") from e
136
135
  except requests.exceptions.HTTPError as e:
137
- self._log_error(f"GET raw {endpoint} HTTP error: {e}")
136
+ self._log_http_error(f"GET raw {endpoint} HTTP error: {e}", e.response)
138
137
  status_code = e.response.status_code if e.response is not None else None
139
138
  msg, body = (
140
139
  self._extract_error_payload(e.response) if e.response is not None else (None, None)
141
140
  )
142
- if status_code == 401:
143
- raise ARAuthenticationError(msg or "Authentication failed") from e
144
- raise ARAPIError(msg or str(e), status_code=status_code, response_data=body) from e
141
+ headers = e.response.headers if e.response is not None else {}
142
+ raise _http_error(status_code, headers, msg, body, e) from e
145
143
  except requests.exceptions.RequestException as e:
146
144
  self._log_error(f"GET raw {endpoint} error: {e}")
147
145
  raise ARAPIError(str(e)) from e
@@ -173,14 +171,13 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
173
171
  self._log_error(f"POST {endpoint} connection error: {e}")
174
172
  raise ARConnectionError(f"Failed to connect to {endpoint}") from e
175
173
  except requests.exceptions.HTTPError as e:
176
- self._log_error(f"POST {endpoint} HTTP error: {e}")
174
+ self._log_http_error(f"POST {endpoint} HTTP error: {e}", e.response)
177
175
  status_code = e.response.status_code if e.response is not None else None
178
176
  msg, body = (
179
177
  self._extract_error_payload(e.response) if e.response is not None else (None, None)
180
178
  )
181
- if status_code == 401:
182
- raise ARAuthenticationError(msg or "Authentication failed") from e
183
- raise ARAPIError(msg or str(e), status_code=status_code, response_data=body) from e
179
+ headers = e.response.headers if e.response is not None else {}
180
+ raise _http_error(status_code, headers, msg, body, e) from e
184
181
  except requests.exceptions.RequestException as e:
185
182
  self._log_error(f"POST {endpoint} error: {e}")
186
183
  raise ARAPIError(str(e)) from e
@@ -212,14 +209,13 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
212
209
  self._log_error(f"POST form {endpoint} connection error: {e}")
213
210
  raise ARConnectionError(f"Failed to connect to {endpoint}") from e
214
211
  except requests.exceptions.HTTPError as e:
215
- self._log_error(f"POST form {endpoint} HTTP error: {e}")
212
+ self._log_http_error(f"POST form {endpoint} HTTP error: {e}", e.response)
216
213
  status_code = e.response.status_code if e.response is not None else None
217
214
  msg, body = (
218
215
  self._extract_error_payload(e.response) if e.response is not None else (None, None)
219
216
  )
220
- if status_code == 401:
221
- raise ARAuthenticationError(msg or "Authentication failed") from e
222
- raise ARAPIError(msg or str(e), status_code=status_code, response_data=body) from e
217
+ headers = e.response.headers if e.response is not None else {}
218
+ raise _http_error(status_code, headers, msg, body, e) from e
223
219
  except requests.exceptions.RequestException as e:
224
220
  self._log_error(f"POST form {endpoint} error: {e}")
225
221
  raise ARAPIError(str(e)) from e
@@ -260,14 +256,13 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
260
256
  self._log_error(f"POST multipart {endpoint} connection error: {e}")
261
257
  raise ARConnectionError(f"Failed to connect to {endpoint}") from e
262
258
  except requests.exceptions.HTTPError as e:
263
- self._log_error(f"POST multipart {endpoint} HTTP error: {e}")
259
+ self._log_http_error(f"POST multipart {endpoint} HTTP error: {e}", e.response)
264
260
  status_code = e.response.status_code if e.response is not None else None
265
261
  msg, body = (
266
262
  self._extract_error_payload(e.response) if e.response is not None else (None, None)
267
263
  )
268
- if status_code == 401:
269
- raise ARAuthenticationError(msg or "Authentication failed") from e
270
- raise ARAPIError(msg or str(e), status_code=status_code, response_data=body) from e
264
+ headers = e.response.headers if e.response is not None else {}
265
+ raise _http_error(status_code, headers, msg, body, e) from e
271
266
  except requests.exceptions.RequestException as e:
272
267
  self._log_error(f"POST multipart {endpoint} error: {e}")
273
268
  raise ARAPIError(str(e)) from e
@@ -296,14 +291,13 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
296
291
  self._log_error(f"DELETE {endpoint} connection error: {e}")
297
292
  raise ARConnectionError(f"Failed to connect to {endpoint}") from e
298
293
  except requests.exceptions.HTTPError as e:
299
- self._log_error(f"DELETE {endpoint} HTTP error: {e}")
294
+ self._log_http_error(f"DELETE {endpoint} HTTP error: {e}", e.response)
300
295
  status_code = e.response.status_code if e.response is not None else None
301
296
  msg, body = (
302
297
  self._extract_error_payload(e.response) if e.response is not None else (None, None)
303
298
  )
304
- if status_code == 401:
305
- raise ARAuthenticationError(msg or "Authentication failed") from e
306
- raise ARAPIError(msg or str(e), status_code=status_code, response_data=body) from e
299
+ headers = e.response.headers if e.response is not None else {}
300
+ raise _http_error(status_code, headers, msg, body, e) from e
307
301
  except requests.exceptions.RequestException as e:
308
302
  self._log_error(f"DELETE {endpoint} error: {e}")
309
303
  raise ARAPIError(str(e)) from e
@@ -417,6 +411,9 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
417
411
  stream=True,
418
412
  timeout=(self.STREAM_CONNECT_TIMEOUT, self.STREAM_READ_TIMEOUT),
419
413
  ) as response:
414
+ if response.status_code == 503:
415
+ yield _busy_stream_error(_retry_after_from(response.headers))
416
+ return
420
417
  response.raise_for_status()
421
418
 
422
419
  current_event = None
@@ -2771,7 +2768,8 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
2771
2768
  msg, body = (
2772
2769
  self._extract_error_payload(e.response) if e.response is not None else (None, None)
2773
2770
  )
2774
- raise ARAPIError(msg or str(e), status_code=status_code, response_data=body) from e
2771
+ headers = e.response.headers if e.response is not None else {}
2772
+ raise _http_error(status_code, headers, msg, body, e) from e
2775
2773
  except requests.exceptions.RequestException as e:
2776
2774
  raise ARAPIError(str(e)) from e
2777
2775
 
@@ -52,8 +52,9 @@ class ARRateLimitError(ARError):
52
52
  message: str = "Rate limit exceeded",
53
53
  retry_after: Optional[float] = None,
54
54
  models_checked: Optional[List[str]] = None,
55
+ error_code: str = "RATE_LIMITED",
55
56
  ):
56
- super().__init__(message, error_code="RATE_LIMITED")
57
+ super().__init__(message, error_code=error_code)
57
58
  self.retry_after = retry_after
58
59
  self.models_checked = models_checked or []
59
60
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "assistant_runtime_sdk"
3
- version = "1.13.0"
3
+ version = "1.14.0"
4
4
  description = "Python SDK for FAC Cloud - the Assistant Runtime AI assistant backend"
5
5
  readme = "README.md"
6
6
  license = {text = "AGPL-3.0"}