entrove-sdk 0.2.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.
entrove/__init__.py ADDED
@@ -0,0 +1,117 @@
1
+ """Python client for the Entrove Agent API."""
2
+
3
+ from ._async_client import AsyncEntrove, AsyncEntroveClient
4
+ from ._base_client import DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, WORKFLOW_TIMEOUT
5
+ from ._client import Entrove, EntroveClient
6
+ from ._exceptions import (
7
+ APIConnectionError,
8
+ APIStatusError,
9
+ APITimeoutError,
10
+ AuthenticationError,
11
+ BadRequestError,
12
+ ConflictError,
13
+ EntroveError,
14
+ InternalServerError,
15
+ NotFoundError,
16
+ PayloadTooLargeError,
17
+ PermissionDeniedError,
18
+ PostAllError,
19
+ RateLimitError,
20
+ UnsupportedMediaTypeError,
21
+ )
22
+ from .types import (
23
+ MAX_BATCH,
24
+ MAX_INTENT_RESULTS,
25
+ MAX_TOOLS,
26
+ Activity,
27
+ ActivityBatchResult,
28
+ ActivityMode,
29
+ ActivityRequest,
30
+ ActivityResult,
31
+ ActivityStatus,
32
+ AgentRule,
33
+ BatchCounts,
34
+ DroppedActivity,
35
+ Intent,
36
+ IntentRef,
37
+ IntentSearchResult,
38
+ IntentWorkflow,
39
+ ItemError,
40
+ ItemWarning,
41
+ Me,
42
+ ModelUsage,
43
+ PostAllResult,
44
+ Reference,
45
+ ResolvedLinks,
46
+ StepRef,
47
+ StepRule,
48
+ ToolCall,
49
+ ToolDefinition,
50
+ WorkflowEdge,
51
+ WorkflowGraph,
52
+ WorkflowPrompt,
53
+ WorkflowRef,
54
+ WorkflowSlot,
55
+ WorkflowStep,
56
+ WorkflowSystem,
57
+ WorkflowVersion,
58
+ )
59
+
60
+ __all__ = [
61
+ "DEFAULT_MAX_RETRIES",
62
+ "DEFAULT_TIMEOUT",
63
+ "MAX_BATCH",
64
+ "MAX_INTENT_RESULTS",
65
+ "MAX_TOOLS",
66
+ "WORKFLOW_TIMEOUT",
67
+ "APIConnectionError",
68
+ "APIStatusError",
69
+ "APITimeoutError",
70
+ "Activity",
71
+ "ActivityBatchResult",
72
+ "ActivityMode",
73
+ "ActivityRequest",
74
+ "ActivityResult",
75
+ "ActivityStatus",
76
+ "AgentRule",
77
+ "AsyncEntrove",
78
+ "AsyncEntroveClient",
79
+ "AuthenticationError",
80
+ "BadRequestError",
81
+ "BatchCounts",
82
+ "ConflictError",
83
+ "DroppedActivity",
84
+ "Entrove",
85
+ "EntroveClient",
86
+ "EntroveError",
87
+ "Intent",
88
+ "IntentRef",
89
+ "IntentSearchResult",
90
+ "IntentWorkflow",
91
+ "InternalServerError",
92
+ "ItemError",
93
+ "ItemWarning",
94
+ "Me",
95
+ "ModelUsage",
96
+ "NotFoundError",
97
+ "PayloadTooLargeError",
98
+ "PermissionDeniedError",
99
+ "PostAllError",
100
+ "PostAllResult",
101
+ "RateLimitError",
102
+ "Reference",
103
+ "ResolvedLinks",
104
+ "StepRef",
105
+ "StepRule",
106
+ "ToolCall",
107
+ "ToolDefinition",
108
+ "UnsupportedMediaTypeError",
109
+ "WorkflowEdge",
110
+ "WorkflowGraph",
111
+ "WorkflowPrompt",
112
+ "WorkflowRef",
113
+ "WorkflowSlot",
114
+ "WorkflowStep",
115
+ "WorkflowSystem",
116
+ "WorkflowVersion",
117
+ ]
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections.abc import Awaitable, Callable, Iterable
5
+ from typing import Any, Protocol
6
+
7
+ import httpx2
8
+
9
+ from ._base_client import (
10
+ DEFAULT_MAX_RETRIES,
11
+ DEFAULT_TIMEOUT,
12
+ WORKFLOW_TIMEOUT,
13
+ ActivityInput,
14
+ BaseClient,
15
+ ToolInput,
16
+ activity_payloads,
17
+ intent_search_body,
18
+ json_body,
19
+ only_result,
20
+ parse_body,
21
+ status_error,
22
+ transport_error,
23
+ workflow_request,
24
+ )
25
+ from ._post_all import apost_all
26
+ from .types import (
27
+ MAX_BATCH,
28
+ ActivityBatchResult,
29
+ ActivityResult,
30
+ IntentSearchResult,
31
+ Me,
32
+ PostAllResult,
33
+ WorkflowPrompt,
34
+ )
35
+
36
+
37
+ class AsyncEntroveClient(Protocol):
38
+ """What `AsyncEntrove` and `entrove.testing.AsyncFakeEntrove` both provide; annotate with this to accept either."""
39
+
40
+ async def me(self) -> Me: ...
41
+
42
+ async def post_activities(self, activities: Iterable[ActivityInput]) -> ActivityBatchResult: ...
43
+
44
+ async def post_activity(self, activity: ActivityInput) -> ActivityResult: ...
45
+
46
+ async def post_all(self, activities: Iterable[ActivityInput], *, max_items: int = MAX_BATCH) -> PostAllResult: ...
47
+
48
+ async def search_intents(self, summary: str, *, limit: int | None = None) -> IntentSearchResult: ...
49
+
50
+ async def get_workflow(
51
+ self,
52
+ intent_id: str,
53
+ *,
54
+ tools: Iterable[ToolInput] = (),
55
+ version: int | None = None,
56
+ timeout: float = WORKFLOW_TIMEOUT,
57
+ ) -> WorkflowPrompt: ...
58
+
59
+
60
+ class AsyncEntrove(BaseClient):
61
+ """Async client for the Entrove Agent API (`GET /me`, `POST /activities`, intents and workflows)."""
62
+
63
+ def __init__(
64
+ self,
65
+ *,
66
+ api_key: str | None = None,
67
+ base_url: str | None = None,
68
+ timeout: float = DEFAULT_TIMEOUT,
69
+ max_retries: int = DEFAULT_MAX_RETRIES,
70
+ http_client: httpx2.AsyncClient | None = None,
71
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
72
+ ) -> None:
73
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)
74
+ self._owns_http = http_client is None
75
+ self._http = http_client or httpx2.AsyncClient()
76
+ self._sleep = sleep
77
+
78
+ async def __aenter__(self) -> AsyncEntrove:
79
+ return self
80
+
81
+ async def __aexit__(self, *exc: object) -> None:
82
+ await self.aclose()
83
+
84
+ async def aclose(self) -> None:
85
+ """Close the HTTP client, unless it was passed in."""
86
+ if self._owns_http:
87
+ await self._http.aclose()
88
+
89
+ async def me(self) -> Me:
90
+ """Describe the calling key, its limits and today's usage; a good smoke test for a new key."""
91
+ return parse_body(Me, await self._request("GET", "/me"), "GET", "/me")
92
+
93
+ async def post_activities(self, activities: Iterable[ActivityInput]) -> ActivityBatchResult:
94
+ """Upsert 1–100 activities. Rejected items come back in the result, not as an exception."""
95
+ body = {"activities": activity_payloads(activities)}
96
+ return parse_body(ActivityBatchResult, await self._request("POST", "/activities", body), "POST", "/activities")
97
+
98
+ async def post_activity(self, activity: ActivityInput) -> ActivityResult:
99
+ """Upsert one activity and return its item result."""
100
+ return only_result(await self.post_activities([activity]))
101
+
102
+ async def post_all(self, activities: Iterable[ActivityInput], *, max_items: int = MAX_BATCH) -> PostAllResult:
103
+ """Post any number of activities, `max_items` per request; see `PostAllResult` and `PostAllError`.
104
+
105
+ A batch the API refuses as too large (413) or invalid (400) is split in half and retried; an activity it still
106
+ refuses on its own is skipped and returned in `dropped`. Any other error raises `PostAllError`.
107
+ """
108
+ return await apost_all(self.post_activities, activities, max_items)
109
+
110
+ async def search_intents(self, summary: str, *, limit: int | None = None) -> IntentSearchResult:
111
+ """The intents to choose from for a request summary (`workflows:read`).
112
+
113
+ Write the summary in the language of the agent's documents and workflows (English for now): it is searched as
114
+ given, never translated. Leave out personal details.
115
+ """
116
+ body = intent_search_body(summary, limit)
117
+ data = await self._request("POST", "/intents/search", body)
118
+ return parse_body(IntentSearchResult, data, "POST", "/intents/search")
119
+
120
+ async def get_workflow(
121
+ self,
122
+ intent_id: str,
123
+ *,
124
+ tools: Iterable[ToolInput] = (),
125
+ version: int | None = None,
126
+ timeout: float = WORKFLOW_TIMEOUT,
127
+ ) -> WorkflowPrompt:
128
+ """The workflow prompt, graph and tools (`workflows:read`); the first call per version and tool list is slow."""
129
+ path, body = workflow_request(intent_id, tools, version)
130
+ return parse_body(WorkflowPrompt, await self._request("POST", path, body, timeout=timeout), "POST", path)
131
+
132
+ async def _request(self, method: str, path: str, body: Any = None, *, timeout: float | None = None) -> Any:
133
+ timeout = self.timeout if timeout is None else timeout
134
+ attempt = 0
135
+ while True:
136
+ try:
137
+ resp = await self._http.request(
138
+ method, f"{self.base_url}{path}", json=body, headers=self._headers, timeout=timeout
139
+ )
140
+ except httpx2.RequestError as e:
141
+ err = transport_error(method, path, e)
142
+ else:
143
+ if resp.is_success:
144
+ return json_body(method, path, resp)
145
+ err = status_error(resp)
146
+
147
+ delay = self._retry_delay(err, attempt)
148
+ if delay is None:
149
+ raise err
150
+ self._log_retry(method, path, delay, attempt, err)
151
+ await self._sleep(delay)
152
+ attempt += 1
@@ -0,0 +1,246 @@
1
+ """Configuration, payloads, retry policy and error mapping shared by `Entrove` and `AsyncEntrove`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import math
7
+ import os
8
+ import random
9
+ import warnings
10
+ from collections import Counter
11
+ from collections.abc import Iterable, Mapping
12
+ from importlib.metadata import PackageNotFoundError, version
13
+ from typing import Any
14
+ from urllib.parse import quote, urlparse
15
+
16
+ import httpx2
17
+ from pydantic import BaseModel, ValidationError
18
+
19
+ from ._exceptions import (
20
+ APIConnectionError,
21
+ APIStatusError,
22
+ APITimeoutError,
23
+ EntroveError,
24
+ RateLimitError,
25
+ status_error_class,
26
+ )
27
+ from .types import (
28
+ MAX_BATCH,
29
+ MAX_INTENT_RESULTS,
30
+ MAX_SUMMARY_LENGTH,
31
+ MAX_TOOLS,
32
+ Activity,
33
+ ActivityBatchResult,
34
+ ActivityResult,
35
+ ItemError,
36
+ ToolDefinition,
37
+ )
38
+
39
+ logger = logging.getLogger("entrove")
40
+
41
+ DEFAULT_TIMEOUT = 10.0
42
+ # On a cache miss the server maps the tools onto the workflow with an LLM call, which can take about a minute.
43
+ WORKFLOW_TIMEOUT = 90.0
44
+ DEFAULT_MAX_RETRIES = 2
45
+ # Longer waits are surfaced to the caller instead of blocking (a `quota_exceeded` waits until 00:00 UTC).
46
+ MAX_RETRY_WAIT = 60.0
47
+
48
+ ActivityInput = Activity | Mapping[str, Any]
49
+ ToolInput = ToolDefinition | Mapping[str, Any]
50
+
51
+ try:
52
+ _VERSION = version("entrove-sdk")
53
+ except PackageNotFoundError: # pragma: no cover - running from a source tree
54
+ _VERSION = "0+unknown"
55
+
56
+
57
+ def activity_payload(activity: ActivityInput) -> dict[str, Any]:
58
+ """The JSON body for one activity; mappings are sent as given, in API (camelCase) field names."""
59
+ return activity.to_api() if isinstance(activity, Activity) else dict(activity)
60
+
61
+
62
+ def activity_payloads(activities: Iterable[ActivityInput]) -> list[dict[str, Any]]:
63
+ """The JSON items for one `POST /activities`, checking the 1–100 item bound.
64
+
65
+ Builds a list, so a generator is read once and every retry resends the same items.
66
+ """
67
+ items = [activity_payload(a) for a in activities]
68
+ if not 1 <= len(items) <= MAX_BATCH:
69
+ raise ValueError(f"post_activities takes 1 to {MAX_BATCH} activities, got {len(items)}")
70
+ return items
71
+
72
+
73
+ def intent_search_body(summary: str, limit: int | None) -> dict[str, Any]:
74
+ """The JSON body for `POST /intents/search`, stripping the summary and checking it and `limit`.
75
+
76
+ The summary is request content, so an error gives its length, never its text.
77
+ """
78
+ summary = summary.strip()
79
+ if not 1 <= len(summary) <= MAX_SUMMARY_LENGTH:
80
+ raise ValueError(f"summary must be 1 to {MAX_SUMMARY_LENGTH} characters once stripped, got {len(summary)}")
81
+ body: dict[str, Any] = {"summary": summary}
82
+ if limit is not None:
83
+ if not 1 <= limit <= MAX_INTENT_RESULTS:
84
+ raise ValueError(f"limit must be 1 to {MAX_INTENT_RESULTS}, got {limit}")
85
+ body["limit"] = limit
86
+ return body
87
+
88
+
89
+ def tool_payloads(tools: Iterable[ToolInput]) -> list[dict[str, Any]]:
90
+ """The JSON tools for `get_workflow`, checking the 0–128 bound and unique names; mappings are sent as given.
91
+
92
+ Builds a list, so a generator is read once and every retry resends the same tools.
93
+ """
94
+ items = [t.to_api() if isinstance(t, ToolDefinition) else dict(t) for t in tools]
95
+ if len(items) > MAX_TOOLS:
96
+ raise ValueError(f"get_workflow takes 0 to {MAX_TOOLS} tools, got {len(items)}")
97
+ repeated = sorted(str(name) for name, n in Counter(t.get("name") for t in items).items() if n > 1)
98
+ if repeated:
99
+ raise ValueError(f"tool names must be unique; repeated: {', '.join(repeated)}")
100
+ return items
101
+
102
+
103
+ def workflow_request(intent_id: str, tools: Iterable[ToolInput], version: int | None) -> tuple[str, dict[str, Any]]:
104
+ """The path and JSON body for `POST /intents/{intentId}/workflow`, checking the id, tools and version."""
105
+ if not intent_id:
106
+ raise ValueError("intent_id must not be empty")
107
+ body: dict[str, Any] = {"tools": tool_payloads(tools)}
108
+ if version is not None:
109
+ if version < 1:
110
+ raise ValueError(f"version must be at least 1, got {version}")
111
+ body["version"] = version
112
+ return f"/intents/{quote(intent_id, safe='')}/workflow", body
113
+
114
+
115
+ def _env(name: str) -> str:
116
+ """`ENTROVE_<name>`, else the pre-rename `RHYME_<name>` with a `DeprecationWarning`, else empty."""
117
+ value = os.environ.get(f"ENTROVE_{name}", "")
118
+ if value.strip():
119
+ return value
120
+ legacy = os.environ.get(f"RHYME_{name}", "")
121
+ if legacy.strip():
122
+ warnings.warn(f"RHYME_{name} is deprecated; set ENTROVE_{name} instead", DeprecationWarning, stacklevel=4)
123
+ return legacy
124
+
125
+
126
+ def _is_local(host: str | None) -> bool:
127
+ return host in {"localhost", "127.0.0.1", "::1"}
128
+
129
+
130
+ class BaseClient:
131
+ """Configuration, headers and retry policy shared by the sync and async clients."""
132
+
133
+ def __init__(self, *, api_key: str | None, base_url: str | None, timeout: float, max_retries: int) -> None:
134
+ api_key = (api_key or _env("API_KEY")).strip()
135
+ if not api_key:
136
+ raise EntroveError("No API key: pass api_key= or set ENTROVE_API_KEY")
137
+ # No default on purpose: where activity data is sent (and its region) is the caller's decision.
138
+ base_url = (base_url or _env("BASE_URL")).strip()
139
+ if not base_url:
140
+ raise EntroveError("No base URL: pass base_url= or set ENTROVE_BASE_URL, e.g. https://<host>/api/agent/v1")
141
+ parsed = urlparse(base_url)
142
+ if parsed.scheme != "https" and not (parsed.scheme == "http" and _is_local(parsed.hostname)):
143
+ raise EntroveError("base_url must use https (http is allowed only for localhost)")
144
+
145
+ self.base_url = base_url.rstrip("/")
146
+ self.timeout = timeout
147
+ self.max_retries = max_retries
148
+ self._headers = {
149
+ "Authorization": f"Bearer {api_key}",
150
+ "Accept": "application/json",
151
+ "User-Agent": f"entrove-python/{_VERSION}",
152
+ }
153
+
154
+ def __repr__(self) -> str:
155
+ return f"{type(self).__name__}(base_url={self.base_url!r})"
156
+
157
+ def _retry_delay(self, err: EntroveError, attempt: int) -> float | None:
158
+ if attempt >= self.max_retries:
159
+ return None
160
+ if isinstance(err, APIStatusError):
161
+ if isinstance(err, RateLimitError) and err.code == "quota_exceeded":
162
+ return None
163
+ if err.status_code != 429 and err.status_code < 500:
164
+ return None
165
+ if err.retry_after is not None:
166
+ return float(err.retry_after) if err.retry_after <= MAX_RETRY_WAIT else None
167
+ return min(0.5 * 2**attempt, 8.0) * (0.5 + random.random() / 2)
168
+
169
+ def _log_retry(self, method: str, path: str, delay: float, attempt: int, err: EntroveError) -> None:
170
+ logger.info(
171
+ "Retrying %s %s in %.1fs (retry %d of %d): %s", method, path, delay, attempt + 1, self.max_retries, err
172
+ )
173
+
174
+
175
+ def transport_error(method: str, path: str, e: httpx2.RequestError) -> EntroveError:
176
+ if isinstance(e, httpx2.TimeoutException):
177
+ err: EntroveError = APITimeoutError(f"{method} {path} timed out")
178
+ else:
179
+ err = APIConnectionError(f"{method} {path} failed: {e}")
180
+ err.__cause__ = e
181
+ return err
182
+
183
+
184
+ def json_body(method: str, path: str, resp: httpx2.Response) -> Any:
185
+ try:
186
+ return resp.json()
187
+ except ValueError as e:
188
+ raise EntroveError(f"{method} {path} returned a non-JSON body") from e
189
+
190
+
191
+ def parse_body[M: BaseModel](model: type[M], data: Any, method: str, path: str) -> M:
192
+ """Validate a 2xx body, raising `EntroveError` (not pydantic's error) if it isn't the expected shape."""
193
+ try:
194
+ return model.model_validate(data)
195
+ except ValidationError as e:
196
+ raise EntroveError(f"{method} {path} returned an unexpected body") from e
197
+
198
+
199
+ def only_result(batch: ActivityBatchResult) -> ActivityResult:
200
+ """The item result of a one-activity post."""
201
+ if len(batch.results) != 1:
202
+ raise EntroveError(f"POST /activities returned {len(batch.results)} results for 1 activity")
203
+ return batch.results[0]
204
+
205
+
206
+ def _retry_after(value: Any) -> int | None:
207
+ """Seconds from a `retryAfter` field or `Retry-After` header; None if missing or not a non-negative number."""
208
+ if isinstance(value, bool):
209
+ return None
210
+ if isinstance(value, str):
211
+ value = value.strip()
212
+ return int(value) if value.isdigit() else None
213
+ if isinstance(value, int | float) and value >= 0 and value != float("inf"):
214
+ return math.ceil(value)
215
+ return None
216
+
217
+
218
+ def _item_errors(raw: Any) -> list[ItemError]:
219
+ errors = []
220
+ for d in raw if isinstance(raw, list) else []:
221
+ try:
222
+ errors.append(ItemError.model_validate(d))
223
+ except ValidationError:
224
+ continue # a malformed detail must not hide the error it belongs to
225
+ return errors
226
+
227
+
228
+ def status_error(resp: httpx2.Response) -> APIStatusError:
229
+ try:
230
+ body = resp.json()
231
+ except ValueError:
232
+ body = None
233
+ data = body if isinstance(body, dict) else {}
234
+ retry_after = _retry_after(data.get("retryAfter"))
235
+ if retry_after is None:
236
+ retry_after = _retry_after(resp.headers.get("Retry-After"))
237
+ details = _item_errors(data.get("details"))
238
+ return status_error_class(resp.status_code)(
239
+ data.get("error") or resp.reason_phrase or "request failed",
240
+ status_code=resp.status_code,
241
+ code=data.get("code"),
242
+ request_id=data.get("requestId") or resp.headers.get("X-Request-Id"),
243
+ retry_after=retry_after,
244
+ details=details,
245
+ body=body,
246
+ )
entrove/_client.py ADDED
@@ -0,0 +1,151 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from collections.abc import Callable, Iterable
5
+ from typing import Any, Protocol
6
+
7
+ import httpx2
8
+
9
+ from ._base_client import (
10
+ DEFAULT_MAX_RETRIES,
11
+ DEFAULT_TIMEOUT,
12
+ WORKFLOW_TIMEOUT,
13
+ ActivityInput,
14
+ BaseClient,
15
+ ToolInput,
16
+ activity_payloads,
17
+ intent_search_body,
18
+ json_body,
19
+ only_result,
20
+ parse_body,
21
+ status_error,
22
+ transport_error,
23
+ workflow_request,
24
+ )
25
+ from ._post_all import post_all
26
+ from .types import (
27
+ MAX_BATCH,
28
+ ActivityBatchResult,
29
+ ActivityResult,
30
+ IntentSearchResult,
31
+ Me,
32
+ PostAllResult,
33
+ WorkflowPrompt,
34
+ )
35
+
36
+
37
+ class EntroveClient(Protocol):
38
+ """What `Entrove` and `entrove.testing.FakeEntrove` both provide; annotate with this to accept either."""
39
+
40
+ def me(self) -> Me: ...
41
+
42
+ def post_activities(self, activities: Iterable[ActivityInput]) -> ActivityBatchResult: ...
43
+
44
+ def post_activity(self, activity: ActivityInput) -> ActivityResult: ...
45
+
46
+ def post_all(self, activities: Iterable[ActivityInput], *, max_items: int = MAX_BATCH) -> PostAllResult: ...
47
+
48
+ def search_intents(self, summary: str, *, limit: int | None = None) -> IntentSearchResult: ...
49
+
50
+ def get_workflow(
51
+ self,
52
+ intent_id: str,
53
+ *,
54
+ tools: Iterable[ToolInput] = (),
55
+ version: int | None = None,
56
+ timeout: float = WORKFLOW_TIMEOUT,
57
+ ) -> WorkflowPrompt: ...
58
+
59
+
60
+ class Entrove(BaseClient):
61
+ """Client for the Entrove Agent API (`GET /me`, `POST /activities`, intents and workflows)."""
62
+
63
+ def __init__(
64
+ self,
65
+ *,
66
+ api_key: str | None = None,
67
+ base_url: str | None = None,
68
+ timeout: float = DEFAULT_TIMEOUT,
69
+ max_retries: int = DEFAULT_MAX_RETRIES,
70
+ http_client: httpx2.Client | None = None,
71
+ sleep: Callable[[float], None] = time.sleep,
72
+ ) -> None:
73
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)
74
+ self._owns_http = http_client is None
75
+ self._http = http_client or httpx2.Client()
76
+ self._sleep = sleep
77
+
78
+ def __enter__(self) -> Entrove:
79
+ return self
80
+
81
+ def __exit__(self, *exc: object) -> None:
82
+ self.close()
83
+
84
+ def close(self) -> None:
85
+ """Close the HTTP client, unless it was passed in."""
86
+ if self._owns_http:
87
+ self._http.close()
88
+
89
+ def me(self) -> Me:
90
+ """Describe the calling key, its limits and today's usage; a good smoke test for a new key."""
91
+ return parse_body(Me, self._request("GET", "/me"), "GET", "/me")
92
+
93
+ def post_activities(self, activities: Iterable[ActivityInput]) -> ActivityBatchResult:
94
+ """Upsert 1–100 activities. Rejected items come back in the result, not as an exception."""
95
+ body = {"activities": activity_payloads(activities)}
96
+ return parse_body(ActivityBatchResult, self._request("POST", "/activities", body), "POST", "/activities")
97
+
98
+ def post_activity(self, activity: ActivityInput) -> ActivityResult:
99
+ """Upsert one activity and return its item result."""
100
+ return only_result(self.post_activities([activity]))
101
+
102
+ def post_all(self, activities: Iterable[ActivityInput], *, max_items: int = MAX_BATCH) -> PostAllResult:
103
+ """Post any number of activities, `max_items` per request; see `PostAllResult` and `PostAllError`.
104
+
105
+ A batch the API refuses as too large (413) or invalid (400) is split in half and retried; an activity it still
106
+ refuses on its own is skipped and returned in `dropped`. Any other error raises `PostAllError`.
107
+ """
108
+ return post_all(self.post_activities, activities, max_items)
109
+
110
+ def search_intents(self, summary: str, *, limit: int | None = None) -> IntentSearchResult:
111
+ """The intents to choose from for a request summary (`workflows:read`).
112
+
113
+ Write the summary in the language of the agent's documents and workflows (English for now): it is searched as
114
+ given, never translated. Leave out personal details.
115
+ """
116
+ body = intent_search_body(summary, limit)
117
+ return parse_body(IntentSearchResult, self._request("POST", "/intents/search", body), "POST", "/intents/search")
118
+
119
+ def get_workflow(
120
+ self,
121
+ intent_id: str,
122
+ *,
123
+ tools: Iterable[ToolInput] = (),
124
+ version: int | None = None,
125
+ timeout: float = WORKFLOW_TIMEOUT,
126
+ ) -> WorkflowPrompt:
127
+ """The workflow prompt, graph and tools (`workflows:read`); the first call per version and tool list is slow."""
128
+ path, body = workflow_request(intent_id, tools, version)
129
+ return parse_body(WorkflowPrompt, self._request("POST", path, body, timeout=timeout), "POST", path)
130
+
131
+ def _request(self, method: str, path: str, body: Any = None, *, timeout: float | None = None) -> Any:
132
+ timeout = self.timeout if timeout is None else timeout
133
+ attempt = 0
134
+ while True:
135
+ try:
136
+ resp = self._http.request(
137
+ method, f"{self.base_url}{path}", json=body, headers=self._headers, timeout=timeout
138
+ )
139
+ except httpx2.RequestError as e:
140
+ err = transport_error(method, path, e)
141
+ else:
142
+ if resp.is_success:
143
+ return json_body(method, path, resp)
144
+ err = status_error(resp)
145
+
146
+ delay = self._retry_delay(err, attempt)
147
+ if delay is None:
148
+ raise err
149
+ self._log_retry(method, path, delay, attempt, err)
150
+ self._sleep(delay)
151
+ attempt += 1