smooth-py 0.3.5.dev20251107__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.

Potentially problematic release.


This version of smooth-py might be problematic. Click here for more details.

smooth/__init__.py ADDED
@@ -0,0 +1,1418 @@
1
+ # pyright: reportPrivateUsage=false
2
+ """Smooth python SDK."""
3
+
4
+ import asyncio
5
+ import base64
6
+ import io
7
+ import logging
8
+ import os
9
+ import time
10
+ import urllib.parse
11
+ import warnings
12
+ from pathlib import Path
13
+ from typing import Any, Literal, NotRequired, Type, TypedDict
14
+
15
+ import httpx
16
+ import requests
17
+ from deprecated import deprecated
18
+ from pydantic import BaseModel, ConfigDict, Field, computed_field, model_validator
19
+
20
+ # Configure logging
21
+ logger = logging.getLogger("smooth")
22
+
23
+
24
+ BASE_URL = "https://api.smooth.sh/api/"
25
+
26
+
27
+ # --- Utils ---
28
+
29
+
30
+ def _encode_url(url: str, interactive: bool = True, embed: bool = False) -> str:
31
+ parsed_url = urllib.parse.urlparse(url)
32
+ params = urllib.parse.parse_qs(parsed_url.query)
33
+ params.update(
34
+ {
35
+ "interactive": "true" if interactive else "false",
36
+ "embed": "true" if embed else "false",
37
+ }
38
+ )
39
+ return urllib.parse.urlunparse(
40
+ parsed_url._replace(query=urllib.parse.urlencode(params))
41
+ )
42
+
43
+
44
+ # --- Models ---
45
+
46
+
47
+ class Certificate(TypedDict):
48
+ """Client certificate for accessing secure websites.
49
+
50
+ Attributes:
51
+ file: p12 file object to be uploaded (e.g., open("cert.p12", "rb")).
52
+ password: Password to decrypt the certificate file. Optional.
53
+ """
54
+
55
+ file: str | io.IOBase # Required - base64 string or binary IO
56
+ password: NotRequired[str] # Optional
57
+ filters: NotRequired[
58
+ list[str]
59
+ ] # Optional - TODO: Reserved for future use to specify URL patterns where the certificate should be applied.
60
+
61
+
62
+ def _process_certificates(
63
+ certificates: list[Certificate] | None,
64
+ ) -> list[dict[str, Any]] | None:
65
+ """Process certificates, converting binary IO to base64-encoded strings.
66
+
67
+ Args:
68
+ certificates: List of certificates with file field as string or binary IO.
69
+
70
+ Returns:
71
+ List of certificates with file field as base64-encoded string, or None if input is None.
72
+ """
73
+ if certificates is None:
74
+ return None
75
+
76
+ processed_certs: list[dict[str, Any]] = []
77
+ for cert in certificates:
78
+ processed_cert = dict(cert) # Create a copy
79
+
80
+ file_content = processed_cert["file"]
81
+ if isinstance(file_content, io.IOBase):
82
+ # Read the binary content and encode to base64
83
+ binary_data = file_content.read()
84
+ processed_cert["file"] = base64.b64encode(binary_data).decode("utf-8")
85
+ elif not isinstance(file_content, str):
86
+ raise TypeError(
87
+ f"Certificate file must be a string or binary IO, got {type(file_content)}"
88
+ )
89
+
90
+ processed_certs.append(processed_cert)
91
+
92
+ return processed_certs
93
+
94
+
95
+ class TaskResponse(BaseModel):
96
+ """Task response model."""
97
+
98
+ model_config = ConfigDict(extra="allow")
99
+
100
+ id: str = Field(description="The ID of the task.")
101
+ status: Literal["waiting", "running", "done", "failed", "cancelled"] = Field(
102
+ description="The status of the task."
103
+ )
104
+ output: Any | None = Field(default=None, description="The output of the task.")
105
+ credits_used: int | None = Field(
106
+ default=None, description="The amount of credits used to perform the task."
107
+ )
108
+ device: Literal["desktop", "mobile"] | None = Field(
109
+ default=None, description="The device type used for the task."
110
+ )
111
+ live_url: str | None = Field(
112
+ default=None,
113
+ description="The URL to view and interact with the task execution.",
114
+ )
115
+ recording_url: str | None = Field(
116
+ default=None, description="The URL to view the task recording."
117
+ )
118
+ downloads_url: str | None = Field(
119
+ default=None,
120
+ description="The URL of the archive containing the downloaded files.",
121
+ )
122
+ created_at: int | None = Field(
123
+ default=None, description="The timestamp when the task was created."
124
+ )
125
+
126
+
127
+ class TaskRequest(BaseModel):
128
+ """Run task request model."""
129
+
130
+ model_config = ConfigDict(extra="allow")
131
+
132
+ task: str = Field(description="The task to run.")
133
+ response_model: dict[str, Any] | None = Field(
134
+ default=None,
135
+ description="If provided, the JSON schema describing the desired output structure. Default is None",
136
+ )
137
+ url: str | None = Field(
138
+ default=None,
139
+ description="The starting URL for the task. If not provided, the agent will infer it from the task.",
140
+ )
141
+ metadata: dict[str, str | int | float | bool] | None = Field(
142
+ default=None,
143
+ description="A dictionary containing variables or parameters that will be passed to the agent.",
144
+ )
145
+ files: list[str] | None = Field(
146
+ default=None, description="A list of file ids to pass to the agent."
147
+ )
148
+ agent: Literal["smooth", "smooth-lite"] = Field(
149
+ default="smooth", description="The agent to use for the task."
150
+ )
151
+ max_steps: int = Field(
152
+ default=32,
153
+ ge=2,
154
+ le=128,
155
+ description="Maximum number of steps the agent can take (min 2, max 128).",
156
+ )
157
+ device: Literal["desktop", "mobile"] = Field(
158
+ default="desktop", description="Device type for the task. Default is desktop."
159
+ )
160
+ allowed_urls: list[str] | None = Field(
161
+ default=None,
162
+ description=(
163
+ "List of allowed URL patterns using wildcard syntax (e.g., https://*example.com/*). If None, all URLs are allowed."
164
+ ),
165
+ )
166
+ enable_recording: bool = Field(
167
+ default=True,
168
+ description="Enable video recording of the task execution. Default is True",
169
+ )
170
+ profile_id: str | None = Field(
171
+ default=None,
172
+ description=(
173
+ "Browser profile ID to use. Each profile maintains its own state, such as cookies and login credentials."
174
+ ),
175
+ )
176
+ profile_read_only: bool = Field(
177
+ default=False,
178
+ description=(
179
+ "If true, the profile specified by `profile_id` will be loaded in read-only mode. "
180
+ "Changes made during the task will not be saved back to the profile."
181
+ ),
182
+ )
183
+ stealth_mode: bool = Field(
184
+ default=False, description="Run the browser in stealth mode."
185
+ )
186
+ proxy_server: str | None = Field(
187
+ default=None,
188
+ description=(
189
+ "Proxy server url to route browser traffic through."
190
+ ),
191
+ )
192
+ proxy_username: str | None = Field(
193
+ default=None, description="Proxy server username."
194
+ )
195
+ proxy_password: str | None = Field(
196
+ default=None, description="Proxy server password."
197
+ )
198
+ certificates: list[dict[str, Any]] | None = Field(
199
+ default=None,
200
+ description=(
201
+ "List of client certificates to use when accessing secure websites. "
202
+ "Each certificate is a dictionary with the following fields:\n"
203
+ " - `file`: p12 file object to be uploaded (e.g., open('cert.p12', 'rb')).\n"
204
+ " - `password` (optional): Password to decrypt the certificate file."
205
+ ),
206
+ )
207
+ use_adblock: bool | None = Field(
208
+ default=True,
209
+ description="Enable adblock for the browser session. Default is True.",
210
+ )
211
+ additional_tools: dict[str, dict[str, Any] | None] | None = Field(
212
+ default=None, description="Additional tools to enable for the task."
213
+ )
214
+ experimental_features: dict[str, Any] | None = Field(
215
+ default=None, description="Experimental features to enable for the task."
216
+ )
217
+
218
+ @model_validator(mode="before")
219
+ @classmethod
220
+ def _handle_deprecated_session_id(cls, data: Any) -> Any:
221
+ if isinstance(data, dict) and "session_id" in data and "profile_id" not in data:
222
+ warnings.warn(
223
+ "'session_id' is deprecated, use 'profile_id' instead",
224
+ DeprecationWarning,
225
+ stacklevel=2,
226
+ )
227
+ data["profile_id"] = data.pop("session_id")
228
+ return data
229
+
230
+ @computed_field(return_type=str | None)
231
+ @property
232
+ def session_id(self):
233
+ """(Deprecated) Returns the session ID."""
234
+ warnings.warn(
235
+ "'session_id' is deprecated, use 'profile_id' instead",
236
+ DeprecationWarning,
237
+ stacklevel=2,
238
+ )
239
+ return self.profile_id
240
+
241
+ @session_id.setter
242
+ def session_id(self, value: str | None):
243
+ """(Deprecated) Sets the session ID."""
244
+ warnings.warn(
245
+ "'session_id' is deprecated, use 'profile_id' instead",
246
+ DeprecationWarning,
247
+ stacklevel=2,
248
+ )
249
+ self.profile_id = value
250
+
251
+ def model_dump(self, **kwargs: Any) -> dict[str, Any]:
252
+ """Dump model to dict, including deprecated session_id for retrocompatibility."""
253
+ data = super().model_dump(**kwargs)
254
+ # Add deprecated session_id field for retrocompatibility
255
+ if "profile_id" in data:
256
+ data["session_id"] = data["profile_id"]
257
+ return data
258
+
259
+
260
+ class BrowserSessionRequest(BaseModel):
261
+ """Request model for creating a browser session."""
262
+
263
+ model_config = ConfigDict(extra="allow")
264
+
265
+ profile_id: str | None = Field(
266
+ default=None,
267
+ description=(
268
+ "The profile ID to use for the browser session. If None, a new profile will be created."
269
+ ),
270
+ )
271
+ live_view: bool | None = Field(
272
+ default=True,
273
+ description="Request a live URL to interact with the browser session.",
274
+ )
275
+ device: Literal["desktop", "mobile"] | None = Field(
276
+ default="desktop", description="The device type to use."
277
+ )
278
+ url: str | None = Field(
279
+ default=None, description="The URL to open in the browser session."
280
+ )
281
+ proxy_server: str | None = Field(
282
+ default=None,
283
+ description=(
284
+ "Proxy server address to route browser traffic through."
285
+ ),
286
+ )
287
+ proxy_username: str | None = Field(
288
+ default=None, description="Proxy server username."
289
+ )
290
+ proxy_password: str | None = Field(
291
+ default=None, description="Proxy server password."
292
+ )
293
+
294
+ @model_validator(mode="before")
295
+ @classmethod
296
+ def _handle_deprecated_session_id(cls, data: Any) -> Any:
297
+ if isinstance(data, dict) and "session_id" in data and "profile_id" not in data:
298
+ warnings.warn(
299
+ "'session_id' is deprecated, use 'profile_id' instead",
300
+ DeprecationWarning,
301
+ stacklevel=2,
302
+ )
303
+ data["profile_id"] = data.pop("session_id")
304
+ return data
305
+
306
+ @computed_field(return_type=str | None)
307
+ @property
308
+ def session_id(self):
309
+ """(Deprecated) Returns the session ID."""
310
+ warnings.warn(
311
+ "'session_id' is deprecated, use 'profile_id' instead",
312
+ DeprecationWarning,
313
+ stacklevel=2,
314
+ )
315
+ return self.profile_id
316
+
317
+ @session_id.setter
318
+ def session_id(self, value: str | None):
319
+ """(Deprecated) Sets the session ID."""
320
+ warnings.warn(
321
+ "'session_id' is deprecated, use 'profile_id' instead",
322
+ DeprecationWarning,
323
+ stacklevel=2,
324
+ )
325
+ self.profile_id = value
326
+
327
+ def model_dump(self, **kwargs: Any) -> dict[str, Any]:
328
+ """Dump model to dict, including deprecated session_id for retrocompatibility."""
329
+ data = super().model_dump(**kwargs)
330
+ # Add deprecated session_id field for retrocompatibility
331
+ if "profile_id" in data:
332
+ data["session_id"] = data["profile_id"]
333
+ return data
334
+
335
+
336
+ class BrowserSessionResponse(BaseModel):
337
+ """Browser session response model."""
338
+
339
+ model_config = ConfigDict(extra="allow")
340
+
341
+ profile_id: str = Field(
342
+ description="The ID of the browser profile associated with the opened browser instance."
343
+ )
344
+ live_id: str | None = Field(default=None, description="The ID of the live browser session.")
345
+ live_url: str | None = Field(
346
+ default=None, description="The live URL to interact with the browser session."
347
+ )
348
+
349
+ @model_validator(mode="before")
350
+ @classmethod
351
+ def _handle_deprecated_session_id(cls, data: Any) -> Any:
352
+ if isinstance(data, dict) and "session_id" in data and "profile_id" not in data:
353
+ warnings.warn(
354
+ "'session_id' is deprecated, use 'profile_id' instead",
355
+ DeprecationWarning,
356
+ stacklevel=2,
357
+ )
358
+ data["profile_id"] = data.pop("session_id")
359
+ return data
360
+
361
+ @computed_field(return_type=str | None)
362
+ @property
363
+ def session_id(self):
364
+ """(Deprecated) Returns the session ID."""
365
+ warnings.warn(
366
+ "'session_id' is deprecated, use 'profile_id' instead",
367
+ DeprecationWarning,
368
+ stacklevel=2,
369
+ )
370
+ return self.profile_id
371
+
372
+ @session_id.setter
373
+ def session_id(self, value: str):
374
+ """(Deprecated) Sets the session ID."""
375
+ warnings.warn(
376
+ "'session_id' is deprecated, use 'profile_id' instead",
377
+ DeprecationWarning,
378
+ stacklevel=2,
379
+ )
380
+ self.profile_id = value
381
+
382
+
383
+ class BrowserProfilesResponse(BaseModel):
384
+ """Response model for listing browser profiles."""
385
+
386
+ model_config = ConfigDict(extra="allow")
387
+
388
+ profile_ids: list[str] = Field(description="The IDs of the browser profiles.")
389
+
390
+ @model_validator(mode="before")
391
+ @classmethod
392
+ def _handle_deprecated_session_ids(cls, data: Any) -> Any:
393
+ if (
394
+ isinstance(data, dict)
395
+ and "session_ids" in data
396
+ and "profile_ids" not in data
397
+ ):
398
+ warnings.warn(
399
+ "'session_ids' is deprecated, use 'profile_ids' instead",
400
+ DeprecationWarning,
401
+ stacklevel=2,
402
+ )
403
+ data["profile_ids"] = data.pop("session_ids")
404
+ return data
405
+
406
+ @computed_field(return_type=list[str])
407
+ @property
408
+ def session_ids(self):
409
+ """(Deprecated) Returns the session IDs."""
410
+ warnings.warn(
411
+ "'session_ids' is deprecated, use 'profile_ids' instead",
412
+ DeprecationWarning,
413
+ stacklevel=2,
414
+ )
415
+ return self.profile_ids
416
+
417
+ @session_ids.setter
418
+ def session_ids(self, value: list[str]):
419
+ """(Deprecated) Sets the session IDs."""
420
+ warnings.warn(
421
+ "'session_ids' is deprecated, use 'profile_ids' instead",
422
+ DeprecationWarning,
423
+ stacklevel=2,
424
+ )
425
+ self.profile_ids = value
426
+
427
+ def model_dump(self, **kwargs: Any) -> dict[str, Any]:
428
+ """Dump model to dict, including deprecated session_ids for retrocompatibility."""
429
+ data = super().model_dump(**kwargs)
430
+ # Add deprecated session_ids field for retrocompatibility
431
+ if "profile_ids" in data:
432
+ data["session_ids"] = data["profile_ids"]
433
+ return data
434
+
435
+
436
+ class BrowserSessionsResponse(BrowserProfilesResponse):
437
+ """Response model for listing browser profiles."""
438
+
439
+ pass
440
+
441
+
442
+ class UploadFileResponse(BaseModel):
443
+ """Response model for uploading a file."""
444
+
445
+ model_config = ConfigDict(extra="allow")
446
+
447
+ id: str = Field(description="The ID assigned to the uploaded file.")
448
+
449
+
450
+ # --- Exception Handling ---
451
+
452
+
453
+ class ApiError(Exception):
454
+ """Custom exception for API errors."""
455
+
456
+ def __init__(
457
+ self, status_code: int, detail: str, response_data: dict[str, Any] | None = None
458
+ ):
459
+ """Initializes the API error."""
460
+ self.status_code = status_code
461
+ self.detail = detail
462
+ self.response_data = response_data
463
+ super().__init__(f"API Error {status_code}: {detail}")
464
+
465
+
466
+ class TimeoutError(Exception):
467
+ """Custom exception for task timeouts."""
468
+
469
+ pass
470
+
471
+
472
+ # --- Base Client ---
473
+
474
+
475
+ class BaseClient:
476
+ """Base client for handling common API interactions."""
477
+
478
+ def __init__(
479
+ self,
480
+ api_key: str | None = None,
481
+ base_url: str = BASE_URL,
482
+ api_version: str = "v1",
483
+ ):
484
+ """Initializes the base client."""
485
+ # Try to get API key from environment if not provided
486
+ if not api_key:
487
+ api_key = os.getenv("CIRCLEMIND_API_KEY")
488
+
489
+ if not api_key:
490
+ raise ValueError(
491
+ "API key is required. Provide it directly or set CIRCLEMIND_API_KEY environment variable."
492
+ )
493
+
494
+ if not base_url:
495
+ raise ValueError("Base URL cannot be empty.")
496
+
497
+ self.api_key = api_key
498
+ self.base_url = f"{base_url.rstrip('/')}/{api_version}"
499
+ self.headers = {
500
+ "apikey": self.api_key,
501
+ "User-Agent": "smooth-python-sdk/0.2.5",
502
+ }
503
+
504
+ def _handle_response(
505
+ self, response: requests.Response | httpx.Response
506
+ ) -> dict[str, Any]:
507
+ """Handles HTTP responses and raises exceptions for errors."""
508
+ if 200 <= response.status_code < 300:
509
+ try:
510
+ return response.json()
511
+ except ValueError as e:
512
+ logger.error(f"Failed to parse JSON response: {e}")
513
+ raise ApiError(
514
+ status_code=response.status_code,
515
+ detail="Invalid JSON response from server",
516
+ ) from None
517
+
518
+ # Handle error responses
519
+ error_data = None
520
+ try:
521
+ error_data = response.json()
522
+ detail = error_data.get("detail", response.text)
523
+ except ValueError:
524
+ detail = response.text or f"HTTP {response.status_code} error"
525
+
526
+ logger.error(f"API error: {response.status_code} - {detail}")
527
+ raise ApiError(
528
+ status_code=response.status_code, detail=detail, response_data=error_data
529
+ )
530
+
531
+
532
+ # --- Synchronous Client ---
533
+
534
+
535
+ class BrowserSessionHandle(BaseModel):
536
+ """Browser session handle model."""
537
+
538
+ browser_session: BrowserSessionResponse = Field(
539
+ description="The browser session associated with this handle."
540
+ )
541
+
542
+ @deprecated("session_id is deprecated, use profile_id instead")
543
+ def session_id(self):
544
+ """Returns the session ID for the browser session."""
545
+ return self.profile_id()
546
+
547
+ def profile_id(self):
548
+ """Returns the profile ID for the browser session."""
549
+ return self.browser_session.profile_id
550
+
551
+ def live_url(self, interactive: bool = True, embed: bool = False):
552
+ """Returns the live URL for the browser session."""
553
+ if self.browser_session.live_url:
554
+ return _encode_url(
555
+ self.browser_session.live_url, interactive=interactive, embed=embed
556
+ )
557
+ return None
558
+
559
+ def live_id(self):
560
+ """Returns the live ID for the browser session."""
561
+ return self.browser_session.live_id
562
+
563
+
564
+ class TaskHandle:
565
+ """A handle to a running task."""
566
+
567
+ def __init__(self, task_id: str, client: "SmoothClient"):
568
+ """Initializes the task handle."""
569
+ self._client = client
570
+ self._task_response: TaskResponse | None = None
571
+
572
+ self._id = task_id
573
+
574
+ def id(self):
575
+ """Returns the task ID."""
576
+ return self._id
577
+
578
+ def stop(self):
579
+ """Stops the task."""
580
+ self._client._delete_task(self._id)
581
+
582
+ def result(
583
+ self, timeout: int | None = None, poll_interval: float = 1
584
+ ) -> TaskResponse:
585
+ """Waits for the task to complete and returns the result."""
586
+ if self._task_response and self._task_response.status not in [
587
+ "running",
588
+ "waiting",
589
+ ]:
590
+ return self._task_response
591
+
592
+ if timeout is not None and timeout < 1:
593
+ raise ValueError("Timeout must be at least 1 second.")
594
+ if poll_interval < 0.1:
595
+ raise ValueError("Poll interval must be at least 100 milliseconds.")
596
+
597
+ start_time = time.time()
598
+ while timeout is None or (time.time() - start_time) < timeout:
599
+ task_response = self._client._get_task(self.id())
600
+ self._task_response = task_response
601
+ if task_response.status not in ["running", "waiting"]:
602
+ return task_response
603
+ time.sleep(poll_interval)
604
+ raise TimeoutError(
605
+ f"Task {self.id()} did not complete within {timeout} seconds."
606
+ )
607
+
608
+ def live_url(
609
+ self, interactive: bool = False, embed: bool = False, timeout: int | None = None
610
+ ):
611
+ """Returns the live URL for the task."""
612
+ if self._task_response and self._task_response.live_url:
613
+ return _encode_url(
614
+ self._task_response.live_url, interactive=interactive, embed=embed
615
+ )
616
+
617
+ start_time = time.time()
618
+ while timeout is None or (time.time() - start_time) < timeout:
619
+ task_response = self._client._get_task(self.id())
620
+ self._task_response = task_response
621
+ if self._task_response.live_url:
622
+ return _encode_url(
623
+ self._task_response.live_url, interactive=interactive, embed=embed
624
+ )
625
+ time.sleep(1)
626
+
627
+ raise TimeoutError(f"Live URL not available for task {self.id()}.")
628
+
629
+ def recording_url(self, timeout: int | None = None) -> str:
630
+ """Returns the recording URL for the task."""
631
+ if self._task_response and self._task_response.recording_url is not None:
632
+ return self._task_response.recording_url
633
+
634
+ start_time = time.time()
635
+ while timeout is None or (time.time() - start_time) < timeout:
636
+ task_response = self._client._get_task(self.id())
637
+ self._task_response = task_response
638
+ if task_response.recording_url is not None:
639
+ if not task_response.recording_url:
640
+ raise ApiError(
641
+ status_code=404,
642
+ detail=(
643
+ f"Recording URL not available for task {self.id()}."
644
+ " Set `enable_recording=True` when creating the task to enable it."
645
+ ),
646
+ )
647
+ return task_response.recording_url
648
+ time.sleep(1)
649
+ raise TimeoutError(f"Recording URL not available for task {self.id()}.")
650
+
651
+ def downloads_url(self, timeout: int | None = None) -> str:
652
+ """Returns the downloads URL for the task."""
653
+ if self._task_response and self._task_response.downloads_url is not None:
654
+ return self._task_response.downloads_url
655
+
656
+ start_time = time.time()
657
+ while timeout is None or (time.time() - start_time) < timeout:
658
+ task_response = self._client._get_task(
659
+ self.id(), query_params={"downloads": "true"}
660
+ )
661
+ self._task_response = task_response
662
+ if task_response.downloads_url is not None:
663
+ if not task_response.downloads_url:
664
+ raise ApiError(
665
+ status_code=404,
666
+ detail=(
667
+ f"Downloads URL not available for task {self.id()}."
668
+ " Make sure the task downloaded files during its execution."
669
+ ),
670
+ )
671
+ return task_response.downloads_url
672
+ time.sleep(1)
673
+ raise TimeoutError(f"Downloads URL not available for task {self.id()}.")
674
+
675
+
676
+ class SmoothClient(BaseClient):
677
+ """A synchronous client for the API."""
678
+
679
+ def __init__(
680
+ self,
681
+ api_key: str | None = None,
682
+ base_url: str = BASE_URL,
683
+ api_version: str = "v1",
684
+ ):
685
+ """Initializes the synchronous client."""
686
+ super().__init__(api_key, base_url, api_version)
687
+ self._session = requests.Session()
688
+ self._session.headers.update(self.headers)
689
+
690
+ def __enter__(self):
691
+ """Enters the synchronous context manager."""
692
+ return self
693
+
694
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any):
695
+ """Exits the synchronous context manager."""
696
+ self.close()
697
+
698
+ def close(self):
699
+ """Close the session."""
700
+ if hasattr(self, "_session"):
701
+ self._session.close()
702
+
703
+ def _submit_task(self, payload: TaskRequest) -> TaskResponse:
704
+ """Submits a task to be run."""
705
+ try:
706
+ response = self._session.post(
707
+ f"{self.base_url}/task", json=payload.model_dump()
708
+ )
709
+ data = self._handle_response(response)
710
+ return TaskResponse(**data["r"])
711
+ except requests.exceptions.RequestException as e:
712
+ logger.error(f"Request failed: {e}")
713
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
714
+
715
+ def _get_task(
716
+ self, task_id: str, query_params: dict[str, Any] | None = None
717
+ ) -> TaskResponse:
718
+ """Retrieves the status and result of a task."""
719
+ if not task_id:
720
+ raise ValueError("Task ID cannot be empty.")
721
+
722
+ try:
723
+ url = f"{self.base_url}/task/{task_id}"
724
+ response = self._session.get(url, params=query_params)
725
+ data = self._handle_response(response)
726
+ return TaskResponse(**data["r"])
727
+ except requests.exceptions.RequestException as e:
728
+ logger.error(f"Request failed: {e}")
729
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
730
+
731
+ def _delete_task(self, task_id: str):
732
+ """Deletes a task."""
733
+ if not task_id:
734
+ raise ValueError("Task ID cannot be empty.")
735
+
736
+ try:
737
+ response = self._session.delete(f"{self.base_url}/task/{task_id}")
738
+ self._handle_response(response)
739
+ except requests.exceptions.RequestException as e:
740
+ logger.error(f"Request failed: {e}")
741
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
742
+
743
+ def run(
744
+ self,
745
+ task: str,
746
+ response_model: dict[str, Any] | Type[BaseModel] | None = None,
747
+ url: str | None = None,
748
+ metadata: dict[str, str | int | float | bool] | None = None,
749
+ files: list[str] | None = None,
750
+ agent: Literal["smooth"] = "smooth",
751
+ max_steps: int = 32,
752
+ device: Literal["desktop", "mobile"] = "mobile",
753
+ allowed_urls: list[str] | None = None,
754
+ enable_recording: bool = True,
755
+ session_id: str | None = None,
756
+ profile_id: str | None = None,
757
+ profile_read_only: bool = False,
758
+ stealth_mode: bool = False,
759
+ proxy_server: str | None = None,
760
+ proxy_username: str | None = None,
761
+ proxy_password: str | None = None,
762
+ certificates: list[Certificate] | None = None,
763
+ use_adblock: bool | None = True,
764
+ additional_tools: dict[str, dict[str, Any] | None] | None = None,
765
+ experimental_features: dict[str, Any] | None = None,
766
+ ) -> TaskHandle:
767
+ """Runs a task and returns a handle to the task.
768
+
769
+ This method submits a task and returns a `TaskHandle` object
770
+ that can be used to get the result of the task.
771
+
772
+ Args:
773
+ task: The task to run.
774
+ response_model: If provided, the schema describing the desired output structure.
775
+ url: The starting URL for the task. If not provided, the agent will infer it from the task.
776
+ metadata: A dictionary containing variables or parameters that will be passed to the agent.
777
+ files: A list of file ids to pass to the agent.
778
+ agent: The agent to use for the task.
779
+ max_steps: Maximum number of steps the agent can take (max 64).
780
+ device: Device type for the task. Default is mobile.
781
+ allowed_urls: List of allowed URL patterns using wildcard syntax (e.g., https://*example.com/*).
782
+ If None, all URLs are allowed.
783
+ enable_recording: Enable video recording of the task execution.
784
+ session_id: (Deprecated, now `profile_id`) Browser session ID to use.
785
+ profile_id: Browser profile ID to use. Each profile maintains its own state, such as cookies and login credentials.
786
+ profile_read_only: If true, the profile specified by `profile_id` will be loaded in read-only mode.
787
+ stealth_mode: Run the browser in stealth mode.
788
+ proxy_server: Proxy server address to route browser traffic through.
789
+ proxy_username: Proxy server username.
790
+ proxy_password: Proxy server password.
791
+ certificates: List of client certificates to use when accessing secure websites.
792
+ Each certificate is a dictionary with the following fields:
793
+ - `file` (required): p12 file object to be uploaded (e.g., open("cert.p12", "rb")).
794
+ - `password` (optional): Password to decrypt the certificate file, if password-protected.
795
+ use_adblock: Enable adblock for the browser session. Default is True.
796
+ additional_tools: Additional tools to enable for the task.
797
+ experimental_features: Experimental features to enable for the task.
798
+
799
+ Returns:
800
+ A handle to the running task.
801
+
802
+ Raises:
803
+ ApiException: If the API request fails.
804
+ """
805
+ payload = TaskRequest(
806
+ task=task,
807
+ response_model=response_model
808
+ if isinstance(response_model, dict | None)
809
+ else response_model.model_json_schema(),
810
+ url=url,
811
+ metadata=metadata,
812
+ files=files,
813
+ agent=agent,
814
+ max_steps=max_steps,
815
+ device=device,
816
+ allowed_urls=allowed_urls,
817
+ enable_recording=enable_recording,
818
+ profile_id=profile_id or session_id,
819
+ profile_read_only=profile_read_only,
820
+ stealth_mode=stealth_mode,
821
+ proxy_server=proxy_server,
822
+ proxy_username=proxy_username,
823
+ proxy_password=proxy_password,
824
+ certificates=_process_certificates(certificates),
825
+ use_adblock=use_adblock,
826
+ additional_tools=additional_tools,
827
+ experimental_features=experimental_features,
828
+ )
829
+ initial_response = self._submit_task(payload)
830
+
831
+ return TaskHandle(initial_response.id, self)
832
+
833
+ def open_session(
834
+ self,
835
+ profile_id: str | None = None,
836
+ session_id: str | None = None,
837
+ live_view: bool = True,
838
+ device: Literal["desktop", "mobile"] = "desktop",
839
+ url: str | None = None,
840
+ proxy_server: str | None = None,
841
+ proxy_username: str | None = None,
842
+ proxy_password: str | None = None,
843
+ ) -> BrowserSessionHandle:
844
+ """Opens an interactive browser instance to interact with a specific browser profile.
845
+
846
+ Args:
847
+ profile_id: The profile ID to use for the session. If None, a new profile will be created.
848
+ session_id: (Deprecated, now `profile_id`) The session ID to associate with the browser.
849
+ live_view: Whether to enable live view for the session.
850
+ device: The device type to use for the browser session.
851
+ url: The URL to open in the browser session.
852
+ proxy_server: Proxy server address to route browser traffic through.
853
+ proxy_username: Proxy server username.
854
+ proxy_password: Proxy server password.
855
+
856
+ Returns:
857
+ The browser session details, including the live URL.
858
+
859
+ Raises:
860
+ ApiException: If the API request fails.
861
+ """
862
+ try:
863
+ response = self._session.post(
864
+ f"{self.base_url}/browser/session",
865
+ json=BrowserSessionRequest(
866
+ profile_id=profile_id or session_id,
867
+ live_view=live_view,
868
+ device=device,
869
+ url=url,
870
+ proxy_server=proxy_server,
871
+ proxy_username=proxy_username,
872
+ proxy_password=proxy_password,
873
+ ).model_dump(),
874
+ )
875
+ data = self._handle_response(response)
876
+ return BrowserSessionHandle(
877
+ browser_session=BrowserSessionResponse(**data["r"])
878
+ )
879
+ except requests.exceptions.RequestException as e:
880
+ logger.error(f"Request failed: {e}")
881
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
882
+
883
+ def close_session(self, live_id: str):
884
+ """Closes a browser session."""
885
+ try:
886
+ response = self._session.delete(
887
+ f"{self.base_url}/browser/session/{live_id}"
888
+ )
889
+ self._handle_response(response)
890
+ except requests.exceptions.RequestException as e:
891
+ logger.error(f"Request failed: {e}")
892
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
893
+
894
+ def list_profiles(self):
895
+ """Lists all browser profiles for the user.
896
+
897
+ Returns:
898
+ A list of existing browser profiles.
899
+
900
+ Raises:
901
+ ApiException: If the API request fails.
902
+ """
903
+ try:
904
+ response = self._session.get(f"{self.base_url}/browser/profile")
905
+ data = self._handle_response(response)
906
+ return BrowserProfilesResponse(**data["r"])
907
+ except requests.exceptions.RequestException as e:
908
+ logger.error(f"Request failed: {e}")
909
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
910
+
911
+ @deprecated("list_sessions is deprecated, use list_profiles instead")
912
+ def list_sessions(self):
913
+ """Lists all browser profiles for the user."""
914
+ return self.list_profiles()
915
+
916
+ def delete_profile(self, profile_id: str):
917
+ """Delete a browser profile."""
918
+ try:
919
+ response = self._session.delete(
920
+ f"{self.base_url}/browser/profile/{profile_id}"
921
+ )
922
+ self._handle_response(response)
923
+ except requests.exceptions.RequestException as e:
924
+ logger.error(f"Request failed: {e}")
925
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
926
+
927
+ @deprecated("delete_session is deprecated, use delete_profile instead")
928
+ def delete_session(self, session_id: str):
929
+ """Delete a browser profile."""
930
+ self.delete_profile(session_id)
931
+
932
+ def upload_file(
933
+ self, file: io.IOBase, name: str | None = None, purpose: str | None = None
934
+ ) -> UploadFileResponse:
935
+ """Upload a file and return the file ID.
936
+
937
+ Args:
938
+ file: File object to be uploaded.
939
+ name: Optional custom name for the file. If not provided, the original file name will be used.
940
+ purpose: Optional short description of the file to describe its purpose (i.e., 'the bank statement pdf').
941
+
942
+ Returns:
943
+ The file ID assigned to the uploaded file.
944
+
945
+ Raises:
946
+ ValueError: If the file doesn't exist or can't be read.
947
+ ApiError: If the API request fails.
948
+ """
949
+ try:
950
+ name = name or getattr(file, "name", None)
951
+ if name is None:
952
+ raise ValueError(
953
+ "File name must be provided or the file object must have a 'name' attribute."
954
+ )
955
+
956
+ if purpose:
957
+ data = {"file_purpose": purpose}
958
+ else:
959
+ data = None
960
+
961
+ files = {"file": (Path(name).name, file)}
962
+ response = self._session.post(
963
+ f"{self.base_url}/file", files=files, data=data
964
+ )
965
+ data = self._handle_response(response)
966
+ return UploadFileResponse(**data["r"])
967
+ except requests.exceptions.RequestException as e:
968
+ logger.error(f"Request failed: {e}")
969
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
970
+
971
+ def delete_file(self, file_id: str):
972
+ """Delete a file by its ID."""
973
+ try:
974
+ response = self._session.delete(f"{self.base_url}/file/{file_id}")
975
+ self._handle_response(response)
976
+ except requests.exceptions.RequestException as e:
977
+ logger.error(f"Request failed: {e}")
978
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
979
+
980
+
981
+ # --- Asynchronous Client ---
982
+
983
+
984
+ class AsyncTaskHandle:
985
+ """An asynchronous handle to a running task."""
986
+
987
+ def __init__(self, task_id: str, client: "SmoothAsyncClient"):
988
+ """Initializes the asynchronous task handle."""
989
+ self._client = client
990
+ self._task_response: TaskResponse | None = None
991
+
992
+ self._id = task_id
993
+
994
+ def id(self):
995
+ """Returns the task ID."""
996
+ return self._id
997
+
998
+ async def stop(self):
999
+ """Stops the task."""
1000
+ await self._client._delete_task(self._id)
1001
+
1002
+ async def result(
1003
+ self, timeout: int | None = None, poll_interval: float = 1
1004
+ ) -> TaskResponse:
1005
+ """Waits for the task to complete and returns the result."""
1006
+ if self._task_response and self._task_response.status not in [
1007
+ "running",
1008
+ "waiting",
1009
+ ]:
1010
+ return self._task_response
1011
+
1012
+ if timeout is not None and timeout < 1:
1013
+ raise ValueError("Timeout must be at least 1 second.")
1014
+ if poll_interval < 0.1:
1015
+ raise ValueError("Poll interval must be at least 100 milliseconds.")
1016
+
1017
+ start_time = time.time()
1018
+ while timeout is None or (time.time() - start_time) < timeout:
1019
+ task_response = await self._client._get_task(self.id())
1020
+ self._task_response = task_response
1021
+ if task_response.status not in ["running", "waiting"]:
1022
+ return task_response
1023
+ await asyncio.sleep(poll_interval)
1024
+ raise TimeoutError(
1025
+ f"Task {self.id()} did not complete within {timeout} seconds."
1026
+ )
1027
+
1028
+ async def live_url(
1029
+ self, interactive: bool = False, embed: bool = False, timeout: int | None = None
1030
+ ):
1031
+ """Returns the live URL for the task."""
1032
+ if self._task_response and self._task_response.live_url:
1033
+ return _encode_url(
1034
+ self._task_response.live_url, interactive=interactive, embed=embed
1035
+ )
1036
+
1037
+ start_time = time.time()
1038
+ while timeout is None or (time.time() - start_time) < timeout:
1039
+ task_response = await self._client._get_task(self.id())
1040
+ self._task_response = task_response
1041
+ if self._task_response.live_url:
1042
+ return _encode_url(
1043
+ self._task_response.live_url, interactive=interactive, embed=embed
1044
+ )
1045
+ await asyncio.sleep(1)
1046
+
1047
+ raise TimeoutError(f"Live URL not available for task {self.id()}.")
1048
+
1049
+ async def recording_url(self, timeout: int | None = None) -> str:
1050
+ """Returns the recording URL for the task."""
1051
+ if self._task_response and self._task_response.recording_url is not None:
1052
+ return self._task_response.recording_url
1053
+
1054
+ start_time = time.time()
1055
+ while timeout is None or (time.time() - start_time) < timeout:
1056
+ task_response = await self._client._get_task(self.id())
1057
+ self._task_response = task_response
1058
+ if task_response.recording_url is not None:
1059
+ if not task_response.recording_url:
1060
+ raise ApiError(
1061
+ status_code=404,
1062
+ detail=(
1063
+ f"Recording URL not available for task {self.id()}."
1064
+ " Set `enable_recording=True` when creating the task to enable it."
1065
+ ),
1066
+ )
1067
+ return task_response.recording_url
1068
+ await asyncio.sleep(1)
1069
+
1070
+ raise TimeoutError(f"Recording URL not available for task {self.id()}.")
1071
+
1072
+ async def downloads_url(self, timeout: int | None = None) -> str:
1073
+ """Returns the downloads URL for the task."""
1074
+ if self._task_response and self._task_response.downloads_url is not None:
1075
+ return self._task_response.downloads_url
1076
+
1077
+ start_time = time.time()
1078
+ while timeout is None or (time.time() - start_time) < timeout:
1079
+ task_response = await self._client._get_task(
1080
+ self.id(), query_params={"downloads": "true"}
1081
+ )
1082
+ self._task_response = task_response
1083
+ if task_response.downloads_url is not None:
1084
+ if not task_response.downloads_url:
1085
+ raise ApiError(
1086
+ status_code=404,
1087
+ detail=(
1088
+ f"Downloads URL not available for task {self.id()}."
1089
+ " Make sure the task downloaded files during its execution."
1090
+ ),
1091
+ )
1092
+ return task_response.downloads_url
1093
+ await asyncio.sleep(1)
1094
+
1095
+ raise TimeoutError(f"Downloads URL not available for task {self.id()}.")
1096
+
1097
+
1098
+ class SmoothAsyncClient(BaseClient):
1099
+ """An asynchronous client for the API."""
1100
+
1101
+ def __init__(
1102
+ self,
1103
+ api_key: str | None = None,
1104
+ base_url: str = BASE_URL,
1105
+ api_version: str = "v1",
1106
+ timeout: int = 30,
1107
+ ):
1108
+ """Initializes the asynchronous client."""
1109
+ super().__init__(api_key, base_url, api_version)
1110
+ self._client = httpx.AsyncClient(headers=self.headers, timeout=timeout)
1111
+
1112
+ async def __aenter__(self):
1113
+ """Enters the asynchronous context manager."""
1114
+ return self
1115
+
1116
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any):
1117
+ """Exits the asynchronous context manager."""
1118
+ await self.close()
1119
+
1120
+ async def _submit_task(self, payload: TaskRequest) -> TaskResponse:
1121
+ """Submits a task to be run asynchronously."""
1122
+ try:
1123
+ response = await self._client.post(
1124
+ f"{self.base_url}/task", json=payload.model_dump()
1125
+ )
1126
+ data = self._handle_response(response)
1127
+ return TaskResponse(**data["r"])
1128
+ except httpx.RequestError as e:
1129
+ logger.error(f"Request failed: {e}")
1130
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
1131
+
1132
+ async def _get_task(
1133
+ self, task_id: str, query_params: dict[str, Any] | None = None
1134
+ ) -> TaskResponse:
1135
+ """Retrieves the status and result of a task asynchronously."""
1136
+ if not task_id:
1137
+ raise ValueError("Task ID cannot be empty.")
1138
+
1139
+ try:
1140
+ url = f"{self.base_url}/task/{task_id}"
1141
+ response = await self._client.get(url, params=query_params)
1142
+ data = self._handle_response(response)
1143
+ return TaskResponse(**data["r"])
1144
+ except httpx.RequestError as e:
1145
+ logger.error(f"Request failed: {e}")
1146
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
1147
+
1148
+ async def _delete_task(self, task_id: str):
1149
+ """Deletes a task asynchronously."""
1150
+ if not task_id:
1151
+ raise ValueError("Task ID cannot be empty.")
1152
+
1153
+ try:
1154
+ response = await self._client.delete(f"{self.base_url}/task/{task_id}")
1155
+ self._handle_response(response)
1156
+ except httpx.RequestError as e:
1157
+ logger.error(f"Request failed: {e}")
1158
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
1159
+
1160
+ async def run(
1161
+ self,
1162
+ task: str,
1163
+ response_model: dict[str, Any] | Type[BaseModel] | None = None,
1164
+ url: str | None = None,
1165
+ metadata: dict[str, str | int | float | bool] | None = None,
1166
+ files: list[str] | None = None,
1167
+ agent: Literal["smooth"] = "smooth",
1168
+ max_steps: int = 32,
1169
+ device: Literal["desktop", "mobile"] = "mobile",
1170
+ allowed_urls: list[str] | None = None,
1171
+ enable_recording: bool = True,
1172
+ session_id: str | None = None,
1173
+ profile_id: str | None = None,
1174
+ profile_read_only: bool = False,
1175
+ stealth_mode: bool = False,
1176
+ proxy_server: str | None = None,
1177
+ proxy_username: str | None = None,
1178
+ proxy_password: str | None = None,
1179
+ certificates: list[Certificate] | None = None,
1180
+ use_adblock: bool | None = True,
1181
+ additional_tools: dict[str, dict[str, Any] | None] | None = None,
1182
+ experimental_features: dict[str, Any] | None = None,
1183
+ ) -> AsyncTaskHandle:
1184
+ """Runs a task and returns a handle to the task asynchronously.
1185
+
1186
+ This method submits a task and returns an `AsyncTaskHandle` object
1187
+ that can be used to get the result of the task.
1188
+
1189
+ Args:
1190
+ task: The task to run.
1191
+ response_model: If provided, the schema describing the desired output structure.
1192
+ url: The starting URL for the task. If not provided, the agent will infer it from the task.
1193
+ metadata: A dictionary containing variables or parameters that will be passed to the agent.
1194
+ files: A list of file ids to pass to the agent.
1195
+ agent: The agent to use for the task.
1196
+ max_steps: Maximum number of steps the agent can take (max 64).
1197
+ device: Device type for the task. Default is mobile.
1198
+ allowed_urls: List of allowed URL patterns using wildcard syntax (e.g., https://*example.com/*).
1199
+ If None, all URLs are allowed.
1200
+ enable_recording: Enable video recording of the task execution.
1201
+ session_id: (Deprecated, now `profile_id`) Browser session ID to use.
1202
+ profile_id: Browser profile ID to use. Each profile maintains its own state, such as cookies and login credentials.
1203
+ profile_read_only: If true, the profile specified by `profile_id` will be loaded in read-only mode.
1204
+ stealth_mode: Run the browser in stealth mode.
1205
+ proxy_server: Proxy server address to route browser traffic through.
1206
+ proxy_username: Proxy server username.
1207
+ proxy_password: Proxy server password.
1208
+ certificates: List of client certificates to use when accessing secure websites.
1209
+ Each certificate is a dictionary with the following fields:
1210
+ - `file` (required): p12 file object to be uploaded (e.g., open("cert.p12", "rb")).
1211
+ - `password` (optional): Password to decrypt the certificate file.
1212
+ use_adblock: Enable adblock for the browser session. Default is True.
1213
+ additional_tools: Additional tools to enable for the task.
1214
+ experimental_features: Experimental features to enable for the task.
1215
+
1216
+ Returns:
1217
+ A handle to the running task.
1218
+
1219
+ Raises:
1220
+ ApiException: If the API request fails.
1221
+ """
1222
+ payload = TaskRequest(
1223
+ task=task,
1224
+ response_model=response_model
1225
+ if isinstance(response_model, dict | None)
1226
+ else response_model.model_json_schema(),
1227
+ url=url,
1228
+ metadata=metadata,
1229
+ files=files,
1230
+ agent=agent,
1231
+ max_steps=max_steps,
1232
+ device=device,
1233
+ allowed_urls=allowed_urls,
1234
+ enable_recording=enable_recording,
1235
+ profile_id=profile_id or session_id,
1236
+ profile_read_only=profile_read_only,
1237
+ stealth_mode=stealth_mode,
1238
+ proxy_server=proxy_server,
1239
+ proxy_username=proxy_username,
1240
+ proxy_password=proxy_password,
1241
+ certificates=_process_certificates(certificates),
1242
+ use_adblock=use_adblock,
1243
+ additional_tools=additional_tools,
1244
+ experimental_features=experimental_features,
1245
+ )
1246
+
1247
+ initial_response = await self._submit_task(payload)
1248
+ return AsyncTaskHandle(initial_response.id, self)
1249
+
1250
+ async def open_session(
1251
+ self,
1252
+ profile_id: str | None = None,
1253
+ session_id: str | None = None,
1254
+ live_view: bool = True,
1255
+ device: Literal["desktop", "mobile"] = "desktop",
1256
+ url: str | None = None,
1257
+ proxy_server: str | None = None,
1258
+ proxy_username: str | None = None,
1259
+ proxy_password: str | None = None,
1260
+ ) -> BrowserSessionHandle:
1261
+ """Opens an interactive browser instance asynchronously.
1262
+
1263
+ Args:
1264
+ profile_id: The profile ID to use for the session. If None, a new profile will be created.
1265
+ session_id: (Deprecated, now `profile_id`) The session ID to associate with the browser.
1266
+ live_view: Whether to enable live view for the session.
1267
+ device: The device type to use for the session. Defaults to "desktop".
1268
+ url: The URL to open in the browser session.
1269
+ proxy_server: Proxy server address to route browser traffic through.
1270
+ proxy_username: Proxy server username.
1271
+ proxy_password: Proxy server password.
1272
+
1273
+ Returns:
1274
+ The browser session details, including the live URL.
1275
+
1276
+ Raises:
1277
+ ApiException: If the API request fails.
1278
+ """
1279
+ try:
1280
+ response = await self._client.post(
1281
+ f"{self.base_url}/browser/session",
1282
+ json=BrowserSessionRequest(
1283
+ profile_id=profile_id or session_id,
1284
+ live_view=live_view,
1285
+ device=device,
1286
+ url=url,
1287
+ proxy_server=proxy_server,
1288
+ proxy_username=proxy_username,
1289
+ proxy_password=proxy_password,
1290
+ ).model_dump(),
1291
+ )
1292
+ data = self._handle_response(response)
1293
+ return BrowserSessionHandle(
1294
+ browser_session=BrowserSessionResponse(**data["r"])
1295
+ )
1296
+ except httpx.RequestError as e:
1297
+ logger.error(f"Request failed: {e}")
1298
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
1299
+
1300
+ async def close_session(self, live_id: str):
1301
+ """Closes a browser session."""
1302
+ try:
1303
+ response = await self._client.delete(
1304
+ f"{self.base_url}/browser/session/{live_id}"
1305
+ )
1306
+ self._handle_response(response)
1307
+ except httpx.RequestError as e:
1308
+ logger.error(f"Request failed: {e}")
1309
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
1310
+
1311
+ async def list_profiles(self):
1312
+ """Lists all browser profiles for the user.
1313
+
1314
+ Returns:
1315
+ A list of existing browser profiles.
1316
+
1317
+ Raises:
1318
+ ApiException: If the API request fails.
1319
+ """
1320
+ try:
1321
+ response = await self._client.get(f"{self.base_url}/browser/profile")
1322
+ data = self._handle_response(response)
1323
+ return BrowserProfilesResponse(**data["r"])
1324
+ except httpx.RequestError as e:
1325
+ logger.error(f"Request failed: {e}")
1326
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
1327
+
1328
+ @deprecated("list_sessions is deprecated, use list_profiles instead")
1329
+ async def list_sessions(self):
1330
+ """Lists all browser profiles for the user."""
1331
+ return await self.list_profiles()
1332
+
1333
+ async def delete_profile(self, profile_id: str):
1334
+ """Delete a browser profile."""
1335
+ try:
1336
+ response = await self._client.delete(
1337
+ f"{self.base_url}/browser/profile/{profile_id}"
1338
+ )
1339
+ self._handle_response(response)
1340
+ except httpx.RequestError as e:
1341
+ logger.error(f"Request failed: {e}")
1342
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
1343
+
1344
+ @deprecated("delete_session is deprecated, use delete_profile instead")
1345
+ async def delete_session(self, session_id: str):
1346
+ """Delete a browser profile."""
1347
+ await self.delete_profile(session_id)
1348
+
1349
+ async def upload_file(
1350
+ self, file: io.IOBase, name: str | None = None, purpose: str | None = None
1351
+ ) -> UploadFileResponse:
1352
+ """Upload a file and return the file ID.
1353
+
1354
+ Args:
1355
+ file: File object to be uploaded.
1356
+ name: Optional custom name for the file. If not provided, the original file name will be used.
1357
+ purpose: Optional short description of the file to describe its purpose (i.e., 'the bank statement pdf').
1358
+
1359
+ Returns:
1360
+ The file ID assigned to the uploaded file.
1361
+
1362
+ Raises:
1363
+ ValueError: If the file doesn't exist or can't be read.
1364
+ ApiError: If the API request fails.
1365
+ """
1366
+ try:
1367
+ name = name or getattr(file, "name", None)
1368
+ if name is None:
1369
+ raise ValueError(
1370
+ "File name must be provided or the file object must have a 'name' attribute."
1371
+ )
1372
+
1373
+ if purpose:
1374
+ data = {"file_purpose": purpose}
1375
+ else:
1376
+ data = None
1377
+
1378
+ files = {"file": (Path(name).name, file)}
1379
+ response = await self._client.post(
1380
+ f"{self.base_url}/file", files=files, data=data
1381
+ )
1382
+ data = self._handle_response(response)
1383
+ return UploadFileResponse(**data["r"])
1384
+ except httpx.RequestError as e:
1385
+ logger.error(f"Request failed: {e}")
1386
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
1387
+
1388
+ async def delete_file(self, file_id: str):
1389
+ """Delete a file by its ID."""
1390
+ try:
1391
+ response = await self._client.delete(f"{self.base_url}/file/{file_id}")
1392
+ self._handle_response(response)
1393
+ except httpx.RequestError as e:
1394
+ logger.error(f"Request failed: {e}")
1395
+ raise ApiError(status_code=0, detail=f"Request failed: {str(e)}") from None
1396
+
1397
+ async def close(self):
1398
+ """Closes the async client session."""
1399
+ await self._client.aclose()
1400
+
1401
+
1402
+ # Export public API
1403
+ __all__ = [
1404
+ "SmoothClient",
1405
+ "SmoothAsyncClient",
1406
+ "TaskHandle",
1407
+ "AsyncTaskHandle",
1408
+ "BrowserSessionHandle",
1409
+ "TaskRequest",
1410
+ "TaskResponse",
1411
+ "BrowserSessionRequest",
1412
+ "BrowserSessionResponse",
1413
+ "BrowserSessionsResponse",
1414
+ "UploadFileResponse",
1415
+ "Certificate",
1416
+ "ApiError",
1417
+ "TimeoutError",
1418
+ ]