assistant-runtime-sdk 1.12.1__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.12.1
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.12.1"
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}")
@@ -385,11 +385,18 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
385
385
  web_search: Optional[bool] = None,
386
386
  thinking_enabled: Optional[bool] = None,
387
387
  reasoning_effort: Optional[str] = None,
388
+ confirm_low_balance: Optional[bool] = None,
389
+ low_balance_preview: bool = True,
388
390
  ) -> AsyncGenerator[Dict[str, Any], None]:
389
391
  """Async version of AssistantRuntimeClient.stream_chat.
390
392
 
391
393
  On ``stream_complete``, ``event['session_state']`` is the updated signed
392
394
  blob — store it and pass it as ``session_state`` on the next turn.
395
+
396
+ ``confirm_low_balance`` proceeds after the user acknowledged a low-balance
397
+ warning (sent as ``1``; omitted otherwise). ``low_balance_preview`` declares
398
+ that this client can show the low-balance "Send anyway" preview (sent as
399
+ ``1`` by default); pass False only for a client that cannot.
393
400
  """
394
401
  session = self._ensure_session()
395
402
  payload = self._prepare_stream_payload(
@@ -402,6 +409,8 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
402
409
  web_search=web_search,
403
410
  thinking_enabled=thinking_enabled,
404
411
  reasoning_effort=reasoning_effort,
412
+ confirm_low_balance=confirm_low_balance,
413
+ low_balance_preview=low_balance_preview,
405
414
  )
406
415
  url = self._build_endpoint_url("streaming.stream_chat")
407
416
  payload = self._with_site_url(payload)
@@ -413,6 +422,9 @@ class AsyncAssistantRuntimeClient(BaseAssistantRuntimeClient):
413
422
  total=self.STREAM_READ_TIMEOUT,
414
423
  )
415
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
416
428
  response.raise_for_status()
417
429
 
418
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
@@ -317,6 +371,8 @@ class BaseAssistantRuntimeClient:
317
371
  web_search: Optional[bool] = None,
318
372
  thinking_enabled: Optional[bool] = None,
319
373
  reasoning_effort: Optional[str] = None,
374
+ confirm_low_balance: Optional[bool] = None,
375
+ low_balance_preview: bool = True,
320
376
  ) -> Dict[str, Any]:
321
377
  """
322
378
  Prepare JSON payload for stream_chat POST request.
@@ -350,6 +406,11 @@ class BaseAssistantRuntimeClient:
350
406
  thinking_enabled: Optional explicit extended-thinking toggle for this turn
351
407
  reasoning_effort: Optional thinking level for this turn — "off", "low", "medium",
352
408
  "high", "xhigh" or "max"
409
+ confirm_low_balance: Set True to proceed with this turn after the user
410
+ acknowledged a low-balance warning (sent as ``1``; omitted otherwise)
411
+ low_balance_preview: Declares that this client can show the low-balance
412
+ "Send anyway" preview (sent as ``1`` by default). Pass False only for
413
+ a client that cannot, so the server does not refuse the turn.
353
414
 
354
415
  Returns:
355
416
  Payload dict ready for JSON body
@@ -406,6 +467,12 @@ class BaseAssistantRuntimeClient:
406
467
  if reasoning_effort is not None:
407
468
  payload["reasoning_effort"] = str(reasoning_effort).strip().lower()
408
469
 
470
+ if confirm_low_balance:
471
+ payload["confirm_low_balance"] = 1
472
+
473
+ if low_balance_preview:
474
+ payload["low_balance_preview"] = 1
475
+
409
476
  return payload
410
477
 
411
478
  def _prepare_resource_params(
@@ -439,6 +506,13 @@ class BaseAssistantRuntimeClient:
439
506
  """Log an error message."""
440
507
  self.logger.error(message, extra={"category": category})
441
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
+
442
516
  def _log_warning(self, message: str, category: str = "AR") -> None:
443
517
  """Log a warning message."""
444
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
@@ -330,6 +324,8 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
330
324
  web_search: Optional[bool] = None,
331
325
  thinking_enabled: Optional[bool] = None,
332
326
  reasoning_effort: Optional[str] = None,
327
+ confirm_low_balance: Optional[bool] = None,
328
+ low_balance_preview: bool = True,
333
329
  ) -> Generator[Dict[str, Any], None, None]:
334
330
  """
335
331
  Stream chat response from Assistant Runtime.
@@ -365,6 +361,11 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
365
361
  reasoning_effort: Optional thinking level for this turn — "off", "low", "medium",
366
362
  "high", "xhigh" or "max". Servers that predate it ignore it, so callers
367
363
  should also send thinking_enabled.
364
+ confirm_low_balance: Set True to proceed after the user acknowledged a
365
+ low-balance warning (sent as ``1``; omitted otherwise)
366
+ low_balance_preview: Declares that this client can show the low-balance
367
+ "Send anyway" preview (sent as ``1`` by default). Pass False only for
368
+ a client that cannot, so the server does not refuse the turn.
368
369
 
369
370
  Yields:
370
371
  Parsed SSE events with structure:
@@ -395,6 +396,8 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
395
396
  web_search=web_search,
396
397
  thinking_enabled=thinking_enabled,
397
398
  reasoning_effort=reasoning_effort,
399
+ confirm_low_balance=confirm_low_balance,
400
+ low_balance_preview=low_balance_preview,
398
401
  )
399
402
  url = self._build_endpoint_url("streaming.stream_chat")
400
403
  payload = self._with_site_url(payload)
@@ -408,6 +411,9 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
408
411
  stream=True,
409
412
  timeout=(self.STREAM_CONNECT_TIMEOUT, self.STREAM_READ_TIMEOUT),
410
413
  ) as response:
414
+ if response.status_code == 503:
415
+ yield _busy_stream_error(_retry_after_from(response.headers))
416
+ return
411
417
  response.raise_for_status()
412
418
 
413
419
  current_event = None
@@ -2762,7 +2768,8 @@ class AssistantRuntimeClient(BaseAssistantRuntimeClient):
2762
2768
  msg, body = (
2763
2769
  self._extract_error_payload(e.response) if e.response is not None else (None, None)
2764
2770
  )
2765
- 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
2766
2773
  except requests.exceptions.RequestException as e:
2767
2774
  raise ARAPIError(str(e)) from e
2768
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.12.1"
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"}