tinyfish 0.10.0__tar.gz → 0.11.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.
Files changed (69) hide show
  1. {tinyfish-0.10.0 → tinyfish-0.11.0}/CHANGELOG.md +13 -0
  2. {tinyfish-0.10.0 → tinyfish-0.11.0}/PKG-INFO +40 -2
  3. {tinyfish-0.10.0 → tinyfish-0.11.0}/README.md +39 -1
  4. {tinyfish-0.10.0 → tinyfish-0.11.0}/pyproject.toml +1 -1
  5. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/__init__.py +50 -0
  6. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/_utils/sse_parser.py +11 -4
  7. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/client.py +5 -0
  8. tinyfish-0.11.0/src/tinyfish/datasets/__init__.py +358 -0
  9. tinyfish-0.11.0/src/tinyfish/datasets/types.py +199 -0
  10. tinyfish-0.11.0/tests/test_datasets.py +286 -0
  11. tinyfish-0.11.0/tests/test_datasets_events.py +355 -0
  12. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_research_events.py +1 -1
  13. tinyfish-0.11.0/tests/test_sse_parser.py +24 -0
  14. {tinyfish-0.10.0 → tinyfish-0.11.0}/uv.lock +1 -1
  15. {tinyfish-0.10.0 → tinyfish-0.11.0}/.gitignore +0 -0
  16. {tinyfish-0.10.0 → tinyfish-0.11.0}/.pre-commit-config.yaml +0 -0
  17. {tinyfish-0.10.0 → tinyfish-0.11.0}/AGENTS.md +0 -0
  18. {tinyfish-0.10.0 → tinyfish-0.11.0}/CLAUDE.md +0 -0
  19. {tinyfish-0.10.0 → tinyfish-0.11.0}/RELEASE.md +0 -0
  20. {tinyfish-0.10.0 → tinyfish-0.11.0}/docs/exceptions-and-errors-guide.md +0 -0
  21. {tinyfish-0.10.0 → tinyfish-0.11.0}/docs/internal/api-integration-header.md +0 -0
  22. {tinyfish-0.10.0 → tinyfish-0.11.0}/docs/internal/exceptions-and-errors-guide.md +0 -0
  23. {tinyfish-0.10.0 → tinyfish-0.11.0}/docs/internal/publishing-private-guide.md +0 -0
  24. {tinyfish-0.10.0 → tinyfish-0.11.0}/docs/pagination-guide.md +0 -0
  25. {tinyfish-0.10.0 → tinyfish-0.11.0}/docs/proxy-and-browser-profiles.md +0 -0
  26. {tinyfish-0.10.0 → tinyfish-0.11.0}/docs/streaming-guide.md +0 -0
  27. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/_utils/__init__.py +0 -0
  28. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/_utils/client/__init__.py +0 -0
  29. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/_utils/client/_base.py +0 -0
  30. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/_utils/client/async_.py +0 -0
  31. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/_utils/client/sync.py +0 -0
  32. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/_utils/exceptions.py +0 -0
  33. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/_utils/resource.py +0 -0
  34. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/agent/__init__.py +0 -0
  35. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/agent/types.py +0 -0
  36. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/browser/__init__.py +0 -0
  37. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/browser/types.py +0 -0
  38. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/fetch/__init__.py +0 -0
  39. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/fetch/types.py +0 -0
  40. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/monitors/__init__.py +0 -0
  41. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/monitors/types.py +0 -0
  42. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/profiles/__init__.py +0 -0
  43. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/profiles/types.py +0 -0
  44. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/py.typed +0 -0
  45. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/research/__init__.py +0 -0
  46. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/research/types.py +0 -0
  47. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/runs/__init__.py +0 -0
  48. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/runs/types.py +0 -0
  49. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/search/__init__.py +0 -0
  50. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/search/types.py +0 -0
  51. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/vault/__init__.py +0 -0
  52. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/vault/types.py +0 -0
  53. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/wallet/__init__.py +0 -0
  54. {tinyfish-0.10.0 → tinyfish-0.11.0}/src/tinyfish/wallet/types.py +0 -0
  55. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/__init__.py +0 -0
  56. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/conftest.py +0 -0
  57. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_agent.py +0 -0
  58. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_browser.py +0 -0
  59. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_client.py +0 -0
  60. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_errors.py +0 -0
  61. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_fetch.py +0 -0
  62. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_monitors.py +0 -0
  63. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_profiles.py +0 -0
  64. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_research.py +0 -0
  65. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_runs.py +0 -0
  66. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_search.py +0 -0
  67. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_vault.py +0 -0
  68. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/test_wallet.py +0 -0
  69. {tinyfish-0.10.0 → tinyfish-0.11.0}/tests/testing_guide.md +0 -0
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.11.0](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.10.0...sdk-py/v0.11.0) (2026-10-23)
4
+
5
+
6
+ ### Features
7
+
8
+ * **sdk-py:** add datasets resource ([#6579](https://github.com/tinyfish-io/ux-labs/issues/6579)) ([36b6607](https://github.com/tinyfish-io/ux-labs/commit/36b66072798b562d2ffef4c7d5376d632fd93c3a))
9
+ * **sdk-py:** carry SSE event names on frames ([#6578](https://github.com/tinyfish-io/ux-labs/issues/6578)) ([72b5896](https://github.com/tinyfish-io/ux-labs/commit/72b58966bf98548bc6cd374363c0913b98570415))
10
+
11
+
12
+ ### Documentation
13
+
14
+ * **research:** align public Research docs with code, gate CLI examples in CI ([#6584](https://github.com/tinyfish-io/ux-labs/issues/6584)) ([1d40ed7](https://github.com/tinyfish-io/ux-labs/commit/1d40ed7a20abf074ed0f7a47ee7f6e917c7bea25))
15
+
3
16
  ## [0.10.0](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.9.0...sdk-py/v0.10.0) (2026-10-21)
4
17
 
5
18
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: tinyfish
3
- Version: 0.10.0
3
+ Version: 0.11.0
4
4
  Summary: Official Python SDK for the TinyFish API
5
5
  Requires-Python: >=3.11
6
6
  Requires-Dist: httpx>=0.27.0
@@ -64,6 +64,11 @@ Every method below is available on both `TinyFish` (sync) and `AsyncTinyFish` (a
64
64
  | [`research.stream()`](#research--deep-research) | Start deep research, stream its events | `ResearchStream` | No |
65
65
  | [`research.events()`](#research--deep-research) | Attach or reconnect to a run's events | `ResearchStream` | No |
66
66
  | [`research.get()` / `list()` / `cancel()`](#research--deep-research) | Read, list, and cancel research runs | `ResearchRunDetail` and friends | — |
67
+ | [`datasets.create()`](#datasets--build-a-dataset-from-a-prompt) | Plan a dataset from a prompt (or a spec) and start filling it | `Dataset` | No |
68
+ | [`datasets.plan()`](#datasets--build-a-dataset-from-a-prompt) | Get the planner's schema for a prompt, to review first | `DatasetPlanResponse` | Yes |
69
+ | [`datasets.events()`](#datasets--build-a-dataset-from-a-prompt) | Follow a run's status, rows and log | `DatasetRunStream` | No |
70
+ | [`datasets.rows()` / `populate()` / `cancel_run()`](#datasets--build-a-dataset-from-a-prompt) | Read rows, fill again, stop a run | `DatasetRowsResponse` and friends | — |
71
+ | [`datasets.list()` / `get()` / `delete()`](#datasets--build-a-dataset-from-a-prompt) | List, read, and delete datasets | `Dataset` and friends | — |
67
72
  | [`wallet.get()`](#walletget--get-your-balance) | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
68
73
  | [`profiles.setup.start()`](#profilessetup--sign-in-once-reuse-the-session) | Open a browser to sign in to a profile | `ProfileSetupSession` | — |
69
74
  | [`profiles.setup.save()`](#profilessetup--sign-in-once-reuse-the-session) | Save the signed-in state into the profile | `ProfileSaveResult` | Yes |
@@ -396,7 +401,7 @@ client.monitors.cancel(monitor_id) # deletes the Monitor and its schedule
396
401
 
397
402
  ### `research` — deep research
398
403
 
399
- Same shape as `agent`, with keyword-only arguments: `run()` blocks, `queue()` returns at once, `stream()` yields events. Options: `output_language`, `domain_type`, `after_date` / `before_date`, `recency_minutes`, `weak_sources_enabled`, `domain_filter`, `prior_run_id` or `session_id`. `mode` is `"deep"` (default, 5–20 min) or `"max"` (5–45 min). Starts are billed and never retried, since a retry could bill a second run.
404
+ Same shape as `agent`, with keyword-only arguments: `run()` blocks, `queue()` returns at once, `stream()` yields events. Options: `output_language`, `domain_type`, `after_date` / `before_date`, `recency_minutes`, `weak_sources_enabled`, `domain_filter`, `prior_run_id` or `session_id`. `mode` is `"deep"` (default, 5–20 min) or `"max"` (5–45 min). Completed runs beyond the daily free allowance are billed. Starts are never retried, since a retry could start (and bill) a second run. See [Research limits](https://docs.tinyfish.ai/research-api/reference#limits).
400
405
 
401
406
  ```python
402
407
  run = client.research.run(query="Compare long-duration energy storage approaches", mode="deep")
@@ -427,6 +432,39 @@ with client.research.events(run_id) as stream: # `async with` / `async for` on
427
432
 
428
433
  ---
429
434
 
435
+ ### `datasets` — build a dataset from a prompt
436
+
437
+ `create()` plans a schema from a prompt (or takes a `spec` from `plan()`), creates the dataset and starts filling it to `target_rows` (default 100, at most 250). `events()` follows the run; `rows()` reads the rows. `create()` and `populate()` are billed and never retried, since a retry could start a second run.
438
+
439
+ ```python
440
+ dataset = client.datasets.create(prompt="Specialty coffee shops in Oakland with their website and rating", target_rows=50)
441
+ assert dataset.run is not None # None only when created with populate=False
442
+
443
+ with client.datasets.events(dataset.id, dataset.run.id, on_row=lambda e: print(e.data)) as stream:
444
+ for event in stream:
445
+ if isinstance(event, DatasetRunStatusEvent):
446
+ print(event.status) # running, then done, failed or cancelled
447
+
448
+ after = None
449
+ while True:
450
+ page = client.datasets.rows(dataset.id, limit=500, after=after)
451
+ for row in page.rows:
452
+ print(row.data)
453
+ if (after := page.next_cursor) is None:
454
+ break
455
+
456
+ spec = client.datasets.plan(prompt="...").spec # edit, then create(spec=spec)
457
+ client.datasets.get(dataset.id) # status: empty, populating, ready, failed or cancelled
458
+ dataset = client.datasets.populate(dataset.id, reset=True, target_rows=100) # ConflictError while a run is live
459
+ client.datasets.cancel_run(dataset.id, dataset.run.id) # the new run
460
+ client.datasets.list(limit=20)
461
+ client.datasets.delete(dataset.id) # ConflictError while a run is live
462
+ ```
463
+
464
+ `events()` has no overall time limit, a 60s idle timeout, and reconnects a dropped connection up to `max_retries` times. Run frames carry no event ids: a reconnect re-sends the current status and does not replay rows landed in the gap, so read `rows()` after the run. Leaving the `with` block detaches; only `cancel_run()` stops the run. Unknown event names are skipped, as in `agent.stream()`.
465
+
466
+ ---
467
+
430
468
  ### `wallet.get()` — get your balance
431
469
 
432
470
  Returns the caller's current balance, auto-reload configuration, per-product rates, and any in-flight top-up.
@@ -54,6 +54,11 @@ Every method below is available on both `TinyFish` (sync) and `AsyncTinyFish` (a
54
54
  | [`research.stream()`](#research--deep-research) | Start deep research, stream its events | `ResearchStream` | No |
55
55
  | [`research.events()`](#research--deep-research) | Attach or reconnect to a run's events | `ResearchStream` | No |
56
56
  | [`research.get()` / `list()` / `cancel()`](#research--deep-research) | Read, list, and cancel research runs | `ResearchRunDetail` and friends | — |
57
+ | [`datasets.create()`](#datasets--build-a-dataset-from-a-prompt) | Plan a dataset from a prompt (or a spec) and start filling it | `Dataset` | No |
58
+ | [`datasets.plan()`](#datasets--build-a-dataset-from-a-prompt) | Get the planner's schema for a prompt, to review first | `DatasetPlanResponse` | Yes |
59
+ | [`datasets.events()`](#datasets--build-a-dataset-from-a-prompt) | Follow a run's status, rows and log | `DatasetRunStream` | No |
60
+ | [`datasets.rows()` / `populate()` / `cancel_run()`](#datasets--build-a-dataset-from-a-prompt) | Read rows, fill again, stop a run | `DatasetRowsResponse` and friends | — |
61
+ | [`datasets.list()` / `get()` / `delete()`](#datasets--build-a-dataset-from-a-prompt) | List, read, and delete datasets | `Dataset` and friends | — |
57
62
  | [`wallet.get()`](#walletget--get-your-balance) | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
58
63
  | [`profiles.setup.start()`](#profilessetup--sign-in-once-reuse-the-session) | Open a browser to sign in to a profile | `ProfileSetupSession` | — |
59
64
  | [`profiles.setup.save()`](#profilessetup--sign-in-once-reuse-the-session) | Save the signed-in state into the profile | `ProfileSaveResult` | Yes |
@@ -386,7 +391,7 @@ client.monitors.cancel(monitor_id) # deletes the Monitor and its schedule
386
391
 
387
392
  ### `research` — deep research
388
393
 
389
- Same shape as `agent`, with keyword-only arguments: `run()` blocks, `queue()` returns at once, `stream()` yields events. Options: `output_language`, `domain_type`, `after_date` / `before_date`, `recency_minutes`, `weak_sources_enabled`, `domain_filter`, `prior_run_id` or `session_id`. `mode` is `"deep"` (default, 5–20 min) or `"max"` (5–45 min). Starts are billed and never retried, since a retry could bill a second run.
394
+ Same shape as `agent`, with keyword-only arguments: `run()` blocks, `queue()` returns at once, `stream()` yields events. Options: `output_language`, `domain_type`, `after_date` / `before_date`, `recency_minutes`, `weak_sources_enabled`, `domain_filter`, `prior_run_id` or `session_id`. `mode` is `"deep"` (default, 5–20 min) or `"max"` (5–45 min). Completed runs beyond the daily free allowance are billed. Starts are never retried, since a retry could start (and bill) a second run. See [Research limits](https://docs.tinyfish.ai/research-api/reference#limits).
390
395
 
391
396
  ```python
392
397
  run = client.research.run(query="Compare long-duration energy storage approaches", mode="deep")
@@ -417,6 +422,39 @@ with client.research.events(run_id) as stream: # `async with` / `async for` on
417
422
 
418
423
  ---
419
424
 
425
+ ### `datasets` — build a dataset from a prompt
426
+
427
+ `create()` plans a schema from a prompt (or takes a `spec` from `plan()`), creates the dataset and starts filling it to `target_rows` (default 100, at most 250). `events()` follows the run; `rows()` reads the rows. `create()` and `populate()` are billed and never retried, since a retry could start a second run.
428
+
429
+ ```python
430
+ dataset = client.datasets.create(prompt="Specialty coffee shops in Oakland with their website and rating", target_rows=50)
431
+ assert dataset.run is not None # None only when created with populate=False
432
+
433
+ with client.datasets.events(dataset.id, dataset.run.id, on_row=lambda e: print(e.data)) as stream:
434
+ for event in stream:
435
+ if isinstance(event, DatasetRunStatusEvent):
436
+ print(event.status) # running, then done, failed or cancelled
437
+
438
+ after = None
439
+ while True:
440
+ page = client.datasets.rows(dataset.id, limit=500, after=after)
441
+ for row in page.rows:
442
+ print(row.data)
443
+ if (after := page.next_cursor) is None:
444
+ break
445
+
446
+ spec = client.datasets.plan(prompt="...").spec # edit, then create(spec=spec)
447
+ client.datasets.get(dataset.id) # status: empty, populating, ready, failed or cancelled
448
+ dataset = client.datasets.populate(dataset.id, reset=True, target_rows=100) # ConflictError while a run is live
449
+ client.datasets.cancel_run(dataset.id, dataset.run.id) # the new run
450
+ client.datasets.list(limit=20)
451
+ client.datasets.delete(dataset.id) # ConflictError while a run is live
452
+ ```
453
+
454
+ `events()` has no overall time limit, a 60s idle timeout, and reconnects a dropped connection up to `max_retries` times. Run frames carry no event ids: a reconnect re-sends the current status and does not replay rows landed in the gap, so read `rows()` after the run. Leaving the `with` block detaches; only `cancel_run()` stops the run. Unknown event names are skipped, as in `agent.stream()`.
455
+
456
+ ---
457
+
420
458
  ### `wallet.get()` — get your balance
421
459
 
422
460
  Returns the caller's current balance, auto-reload configuration, per-product rates, and any in-flight top-up.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "tinyfish"
3
- version = "0.10.0"
3
+ version = "0.11.0"
4
4
  description = "Official Python SDK for the TinyFish API"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -49,6 +49,32 @@ from .agent.types import (
49
49
  # Browser types
50
50
  from .browser.types import BrowserProxyConfig, BrowserSession, BrowserSessionCreateParams
51
51
  from .client import AsyncTinyFish, TinyFish
52
+ from .datasets import AsyncDatasetRunStream, DatasetRunStream
53
+
54
+ # Datasets types
55
+ from .datasets.types import (
56
+ Dataset,
57
+ DatasetCancelRunResponse,
58
+ DatasetColumnType,
59
+ DatasetDeleteResponse,
60
+ DatasetKeepWhen,
61
+ DatasetListResponse,
62
+ DatasetPagination,
63
+ DatasetPlanResponse,
64
+ DatasetRow,
65
+ DatasetRowColumn,
66
+ DatasetRowsResponse,
67
+ DatasetRun,
68
+ DatasetRunDoneEvent,
69
+ DatasetRunEvent,
70
+ DatasetRunLogEvent,
71
+ DatasetRunRowEvent,
72
+ DatasetRunStatus,
73
+ DatasetRunStatusEvent,
74
+ DatasetSpec,
75
+ DatasetSpecColumn,
76
+ DatasetStatus,
77
+ )
52
78
  from .fetch.types import (
53
79
  FetchError,
54
80
  FetchFormat,
@@ -182,6 +208,8 @@ __all__ = [
182
208
  "AsyncAgentStream",
183
209
  "ResearchStream",
184
210
  "AsyncResearchStream",
211
+ "DatasetRunStream",
212
+ "AsyncDatasetRunStream",
185
213
  # Browser types
186
214
  "BrowserSession",
187
215
  "BrowserProxyConfig",
@@ -233,6 +261,28 @@ __all__ = [
233
261
  "MonitorListResponse",
234
262
  "MonitorRunResponse",
235
263
  "MonitorDeleteResponse",
264
+ # Datasets types
265
+ "Dataset",
266
+ "DatasetCancelRunResponse",
267
+ "DatasetColumnType",
268
+ "DatasetDeleteResponse",
269
+ "DatasetKeepWhen",
270
+ "DatasetListResponse",
271
+ "DatasetPagination",
272
+ "DatasetPlanResponse",
273
+ "DatasetRow",
274
+ "DatasetRowColumn",
275
+ "DatasetRowsResponse",
276
+ "DatasetRun",
277
+ "DatasetRunDoneEvent",
278
+ "DatasetRunEvent",
279
+ "DatasetRunLogEvent",
280
+ "DatasetRunRowEvent",
281
+ "DatasetRunStatus",
282
+ "DatasetRunStatusEvent",
283
+ "DatasetSpec",
284
+ "DatasetSpecColumn",
285
+ "DatasetStatus",
236
286
  # Research types
237
287
  "ResearchMode",
238
288
  "ResearchRunStatus",
@@ -63,15 +63,18 @@ async def async_parse_sse_line_stream(lines: AsyncIterator[str]) -> AsyncIterato
63
63
 
64
64
 
65
65
  class SSEFrame(NamedTuple):
66
- """One SSE event: its id, if any, and parsed JSON data."""
66
+ """One SSE event: its id, if any, parsed JSON data, and its event name."""
67
67
 
68
68
  id: str | None
69
69
  data: dict[str, Any]
70
+ # Last, with a default: positional SSEFrame(id, data) stays valid.
71
+ event: str | None = None
70
72
 
71
73
 
72
74
  class _FrameBuilder:
73
75
  def __init__(self) -> None:
74
76
  self._id: str | None = None
77
+ self._event: str | None = None
75
78
  self._data: list[str] = []
76
79
 
77
80
  def feed(self, line: str) -> SSEFrame | None:
@@ -82,17 +85,21 @@ class _FrameBuilder:
82
85
  value = value.removeprefix(" ")
83
86
  if name == "id":
84
87
  self._id = value
88
+ elif name == "event":
89
+ self._event = value
85
90
  elif name == "data":
86
91
  self._data.append(value)
87
92
  return None
88
93
 
89
94
  def flush(self) -> SSEFrame | None:
90
- frame_id, data = self._id, "\n".join(self._data)
91
- self._id, self._data = None, []
95
+ # id, event and data all reset per frame; resume across reconnects
96
+ # is the caller's job (research._EventCursor keeps the last id).
97
+ frame_id, event, data = self._id, self._event, "\n".join(self._data)
98
+ self._id, self._event, self._data = None, None, []
92
99
  if not data:
93
100
  return None
94
101
  try:
95
- return SSEFrame(frame_id, json.loads(data))
102
+ return SSEFrame(frame_id, json.loads(data), event)
96
103
  except json.JSONDecodeError as e:
97
104
  raise SSEParseError(f"Malformed JSON in SSE event: {e}", line=data) from e
98
105
 
@@ -5,6 +5,7 @@ from tinyfish._utils.client._base import _DEFAULT_TIMEOUT, DEFAULT_BASE_URL
5
5
 
6
6
  from .agent import AgentResource, AsyncAgentResource
7
7
  from .browser import AsyncBrowserResource, BrowserResource
8
+ from .datasets import AsyncDatasetsResource, DatasetsResource
8
9
  from .fetch import AsyncFetchResource, FetchResource
9
10
  from .monitors import AsyncMonitorsResource, MonitorsResource
10
11
  from .profiles import AsyncProfilesResource, ProfilesResource
@@ -30,6 +31,7 @@ class TinyFish(BaseSyncAPIClient):
30
31
  # did `pip install tinyfish`.
31
32
  agent: AgentResource
32
33
  browser: BrowserResource
34
+ datasets: DatasetsResource
33
35
  fetch: FetchResource
34
36
  monitors: MonitorsResource
35
37
  profiles: ProfilesResource
@@ -59,6 +61,7 @@ class TinyFish(BaseSyncAPIClient):
59
61
 
60
62
  self.agent = AgentResource(self)
61
63
  self.browser = BrowserResource(self)
64
+ self.datasets = DatasetsResource(self)
62
65
  self.fetch = FetchResource(self)
63
66
  self.monitors = MonitorsResource(self)
64
67
  self.profiles = ProfilesResource(self)
@@ -77,6 +80,7 @@ class AsyncTinyFish(BaseAsyncAPIClient):
77
80
  # the sync variants) when resolving types from an installed package.
78
81
  agent: AsyncAgentResource
79
82
  browser: AsyncBrowserResource
83
+ datasets: AsyncDatasetsResource
80
84
  fetch: AsyncFetchResource
81
85
  monitors: AsyncMonitorsResource
82
86
  profiles: AsyncProfilesResource
@@ -106,6 +110,7 @@ class AsyncTinyFish(BaseAsyncAPIClient):
106
110
 
107
111
  self.agent = AsyncAgentResource(self)
108
112
  self.browser = AsyncBrowserResource(self)
113
+ self.datasets = AsyncDatasetsResource(self)
109
114
  self.fetch = AsyncFetchResource(self)
110
115
  self.monitors = AsyncMonitorsResource(self)
111
116
  self.profiles = AsyncProfilesResource(self)
@@ -0,0 +1,358 @@
1
+ """Datasets resource: plan, create, read rows, and follow runs of web-filled datasets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ from collections.abc import AsyncGenerator, AsyncIterator, Callable, Generator, Iterator
8
+ from contextlib import aclosing, closing
9
+ from typing import Any
10
+ from urllib.parse import quote
11
+
12
+ import httpx
13
+ from pydantic import ValidationError
14
+
15
+ from tinyfish._utils.exceptions import APIConnectionError, APIStatusError, APITimeoutError
16
+ from tinyfish._utils.resource import BaseAsyncAPIResource, BaseSyncAPIResource
17
+ from tinyfish._utils.sse_parser import SSEFrame, async_parse_sse_frames, parse_sse_frames
18
+
19
+ from .types import (
20
+ Dataset,
21
+ DatasetCancelRunResponse,
22
+ DatasetDeleteResponse,
23
+ DatasetListResponse,
24
+ DatasetPlanResponse,
25
+ DatasetRowsResponse,
26
+ DatasetRunDoneEvent,
27
+ DatasetRunEvent,
28
+ DatasetRunLogEvent,
29
+ DatasetRunRowEvent,
30
+ DatasetRunStatusEvent,
31
+ DatasetSpec,
32
+ frame_object,
33
+ is_dataset_run_in_progress,
34
+ parse_dataset_run_event,
35
+ )
36
+
37
+ _DATASETS_PATH = "/v1/datasets"
38
+ # Idle read timeout, not total; server heartbeats every 15s.
39
+ _EVENTS_TIMEOUT = httpx.Timeout(60.0)
40
+ # Reconnects back off 1, 2, 4 s... up to the cap.
41
+ _EVENTS_RECONNECT_DELAY_S = 1.0
42
+ _EVENTS_RECONNECT_MAX_DELAY_S = 16.0
43
+ _STREAM_ERRORS = (httpx.TransportError, APIConnectionError, APIStatusError)
44
+
45
+
46
+ def _require_id(value: str, name: str) -> str:
47
+ if not value or not value.strip():
48
+ raise ValueError(f"{name} must be a non-empty string")
49
+ return value
50
+
51
+
52
+ def _dataset_path(dataset_id: str, suffix: str = "") -> str:
53
+ return f"{_DATASETS_PATH}/{quote(_require_id(dataset_id, 'dataset_id'), safe='')}{suffix}"
54
+
55
+
56
+ def _run_path(dataset_id: str, run_id: str, suffix: str = "") -> str:
57
+ return _dataset_path(dataset_id, f"/runs/{quote(_require_id(run_id, 'run_id'), safe='')}{suffix}")
58
+
59
+
60
+ def _without_none(**fields: object) -> dict[str, Any]:
61
+ return {key: value for key, value in fields.items() if value is not None}
62
+
63
+
64
+ def _build_create_body(
65
+ prompt: str | None,
66
+ spec: DatasetSpec | dict[str, Any] | None,
67
+ target_rows: int | None,
68
+ populate: bool | None,
69
+ ) -> dict[str, Any]:
70
+ if (prompt is None) == (spec is None):
71
+ raise ValueError("Send exactly one of prompt or spec")
72
+ if prompt is not None and not prompt.strip():
73
+ raise ValueError("prompt must be a non-empty string")
74
+ if spec is not None:
75
+ try:
76
+ spec = DatasetSpec.model_validate(spec).model_dump(exclude_none=True)
77
+ except ValidationError as e:
78
+ raise ValueError(f"Invalid spec: {e}") from e
79
+ return _without_none(prompt=prompt, spec=spec, target_rows=target_rows, populate=populate)
80
+
81
+
82
+ def _callbacks(
83
+ on_status: Callable[[DatasetRunStatusEvent], None] | None,
84
+ on_row: Callable[[DatasetRunRowEvent], None] | None,
85
+ on_log: Callable[[DatasetRunLogEvent], None] | None,
86
+ ) -> dict[str, Callable[[Any], None]]:
87
+ by_event: dict[str, Callable[[Any], None] | None] = {"status": on_status, "row": on_row, "log": on_log}
88
+ return {name: callback for name, callback in by_event.items() if callback}
89
+
90
+
91
+ class _RunCursor:
92
+ """Failures and terminal state across reconnects; there are no event ids to resume from."""
93
+
94
+ def __init__(self, max_retries: int, events_path: str, callbacks: dict[str, Callable[[Any], None]]) -> None:
95
+ self.events_path = events_path
96
+ self.terminal = False
97
+ self._callbacks = callbacks
98
+ self._max_retries = max_retries
99
+ self._failures = 0
100
+ self._status: str | None = None
101
+
102
+ def accept(self, frame: SSEFrame) -> DatasetRunEvent | None:
103
+ if frame.event == "error":
104
+ # The proxy's own frame: the service went away mid-stream.
105
+ raise APIConnectionError(str(frame_object(frame).get("message") or "Dataset run stream failed"))
106
+ event = parse_dataset_run_event(frame)
107
+ if event is None or isinstance(event, DatasetRunDoneEvent):
108
+ return event
109
+ # Rows, log lines and status changes are progress; a re-sent status is not.
110
+ if isinstance(event, DatasetRunStatusEvent):
111
+ if event.status != self._status:
112
+ self._failures = 0
113
+ self._status = event.status
114
+ if not is_dataset_run_in_progress(event.status):
115
+ self.terminal = True
116
+ else:
117
+ self._failures = 0
118
+ if callback := self._callbacks.get(event.event):
119
+ callback(event)
120
+ return event
121
+
122
+ def reconnect_or_raise(self, error: Exception) -> float:
123
+ """Dropped, idle, and 5xx streams reconnect after a backoff; 4xx do not."""
124
+ self._failures += 1
125
+ is_client_error = isinstance(error, APIStatusError) and error.status_code < 500
126
+ if not is_client_error and self._failures <= self._max_retries:
127
+ return min(_EVENTS_RECONNECT_DELAY_S * 2 ** (self._failures - 1), _EVENTS_RECONNECT_MAX_DELAY_S)
128
+ if isinstance(error, httpx.TransportError):
129
+ timed_out = isinstance(error, httpx.TimeoutException)
130
+ cause, error = error, (APITimeoutError if timed_out else APIConnectionError)(str(error))
131
+ error.__cause__ = cause
132
+ raise error
133
+
134
+
135
+ def _stream_closed() -> APIConnectionError:
136
+ # The server ended the stream without a terminal status, e.g. a run another process holds.
137
+ return APIConnectionError(
138
+ "Dataset run event stream closed while the run is still running; call events() again to keep following it"
139
+ )
140
+
141
+
142
+ class DatasetRunStream:
143
+ """Run events until the run ends; closing it detaches without cancelling."""
144
+
145
+ def __init__(self, events: Generator[DatasetRunEvent, None, None]) -> None:
146
+ self._events = events
147
+
148
+ def __enter__(self) -> DatasetRunStream:
149
+ return self
150
+
151
+ def __exit__(self, *args: object) -> None:
152
+ self._events.close()
153
+
154
+ def __iter__(self) -> Iterator[DatasetRunEvent]:
155
+ return self._events
156
+
157
+
158
+ class AsyncDatasetRunStream:
159
+ """Async run events until the run ends; closing it detaches without cancelling."""
160
+
161
+ def __init__(self, events: AsyncGenerator[DatasetRunEvent, None]) -> None:
162
+ self._events = events
163
+
164
+ async def __aenter__(self) -> AsyncDatasetRunStream:
165
+ return self
166
+
167
+ async def __aexit__(self, *args: object) -> None:
168
+ await self._events.aclose()
169
+
170
+ def __aiter__(self) -> AsyncIterator[DatasetRunEvent]:
171
+ return self._events
172
+
173
+
174
+ class DatasetsResource(BaseSyncAPIResource):
175
+ """Datasets filled from the web: plan, create, read rows, follow runs."""
176
+
177
+ def create(
178
+ self,
179
+ *,
180
+ prompt: str | None = None,
181
+ spec: DatasetSpec | dict[str, Any] | None = None,
182
+ target_rows: int | None = None,
183
+ populate: bool | None = None,
184
+ ) -> Dataset:
185
+ """Plan from a prompt or take a spec, then fill unless populate=False. Billed; never retried."""
186
+ body = _build_create_body(prompt, spec, target_rows, populate)
187
+ return self._post(_DATASETS_PATH, json=body, cast_to=Dataset, max_retries=0)
188
+
189
+ def plan(self, *, prompt: str) -> DatasetPlanResponse:
190
+ """The schema the planner designs for a prompt; edit it and pass to create(spec=...)."""
191
+ if not prompt or not prompt.strip():
192
+ raise ValueError("prompt must be a non-empty string")
193
+ return self._post(f"{_DATASETS_PATH}/plan", json={"prompt": prompt}, cast_to=DatasetPlanResponse)
194
+
195
+ def list(self, *, limit: int | None = None, cursor: str | None = None) -> DatasetListResponse:
196
+ """List your datasets, newest first; cursor is a previous next_cursor."""
197
+ return self._get(_DATASETS_PATH, params=_without_none(limit=limit, cursor=cursor), cast_to=DatasetListResponse)
198
+
199
+ def get(self, dataset_id: str) -> Dataset:
200
+ """Retrieve a dataset's spec, status, row count and latest run."""
201
+ return self._get(_dataset_path(dataset_id), cast_to=Dataset)
202
+
203
+ def delete(self, dataset_id: str) -> DatasetDeleteResponse:
204
+ """Delete a dataset and its rows. Refused (ConflictError) while a run is live."""
205
+ return self._delete(_dataset_path(dataset_id), cast_to=DatasetDeleteResponse)
206
+
207
+ def rows(self, dataset_id: str, *, limit: int | None = None, after: str | None = None) -> DatasetRowsResponse:
208
+ """One page of rows; pass next_cursor back as after for the next."""
209
+ params = _without_none(limit=limit, after=after)
210
+ return self._get(_dataset_path(dataset_id, "/rows"), params=params, cast_to=DatasetRowsResponse)
211
+
212
+ def populate(self, dataset_id: str, *, reset: bool | None = None, target_rows: int | None = None) -> Dataset:
213
+ """Start a run; ConflictError while one is live. Billed; never retried."""
214
+ body = _without_none(reset=reset, target_rows=target_rows)
215
+ return self._post(_dataset_path(dataset_id, "/populate"), json=body, cast_to=Dataset, max_retries=0)
216
+
217
+ def cancel_run(self, dataset_id: str, run_id: str) -> DatasetCancelRunResponse:
218
+ """Ask a run to stop; the events stream confirms with a status."""
219
+ return self._post(_run_path(dataset_id, run_id, "/cancel"), cast_to=DatasetCancelRunResponse)
220
+
221
+ def events(
222
+ self,
223
+ dataset_id: str,
224
+ run_id: str,
225
+ *,
226
+ on_status: Callable[[DatasetRunStatusEvent], None] | None = None,
227
+ on_row: Callable[[DatasetRunRowEvent], None] | None = None,
228
+ on_log: Callable[[DatasetRunLogEvent], None] | None = None,
229
+ ) -> DatasetRunStream:
230
+ """Follow a run's status, rows and log until it ends; reconnects on drops."""
231
+ path = _run_path(dataset_id, run_id, "/events")
232
+ cursor = _RunCursor(self._client._max_retries, path, _callbacks(on_status, on_row, on_log))
233
+ return DatasetRunStream(self._follow(cursor))
234
+
235
+ def _follow(self, cursor: _RunCursor) -> Generator[DatasetRunEvent, None, None]:
236
+ while True:
237
+ error: Exception = _stream_closed()
238
+ try:
239
+ lines = self._get_stream(cursor.events_path, timeout=_EVENTS_TIMEOUT)
240
+ if (yield from _read(lines, cursor)):
241
+ return
242
+ except _STREAM_ERRORS as exc:
243
+ # A cut or proxy error after the terminal status is not worth a reconnect.
244
+ if cursor.terminal:
245
+ return
246
+ error = exc
247
+ time.sleep(cursor.reconnect_or_raise(error))
248
+
249
+
250
+ def _read(lines: Generator[str, None, None], cursor: _RunCursor) -> Generator[DatasetRunEvent, None, bool]:
251
+ """Yields one connection's events; returns True once the run has ended."""
252
+ with closing(lines):
253
+ for frame in parse_sse_frames(lines):
254
+ if (event := cursor.accept(frame)) is None:
255
+ continue
256
+ if isinstance(event, DatasetRunDoneEvent):
257
+ # done after a terminal status ends the run; alone it is no progress.
258
+ if not cursor.terminal:
259
+ return False
260
+ yield event
261
+ return True
262
+ yield event
263
+ # Nothing follows a terminal status but done.
264
+ return cursor.terminal
265
+
266
+
267
+ async def _aread(lines: AsyncGenerator[str, None], cursor: _RunCursor) -> AsyncGenerator[DatasetRunEvent, None]:
268
+ """Async version of `_read()`; the caller checks `cursor.terminal` after it ends."""
269
+ async with aclosing(lines):
270
+ async for frame in async_parse_sse_frames(lines):
271
+ if (event := cursor.accept(frame)) is None:
272
+ continue
273
+ if isinstance(event, DatasetRunDoneEvent):
274
+ if cursor.terminal:
275
+ yield event
276
+ return
277
+ yield event
278
+
279
+
280
+ class AsyncDatasetsResource(BaseAsyncAPIResource):
281
+ """Async datasets filled from the web: plan, create, read rows, follow runs."""
282
+
283
+ async def create(
284
+ self,
285
+ *,
286
+ prompt: str | None = None,
287
+ spec: DatasetSpec | dict[str, Any] | None = None,
288
+ target_rows: int | None = None,
289
+ populate: bool | None = None,
290
+ ) -> Dataset:
291
+ """Async version of `DatasetsResource.create()`. Billed; never retried."""
292
+ body = _build_create_body(prompt, spec, target_rows, populate)
293
+ return await self._post(_DATASETS_PATH, json=body, cast_to=Dataset, max_retries=0)
294
+
295
+ async def plan(self, *, prompt: str) -> DatasetPlanResponse:
296
+ """Async version of `DatasetsResource.plan()`."""
297
+ if not prompt or not prompt.strip():
298
+ raise ValueError("prompt must be a non-empty string")
299
+ return await self._post(f"{_DATASETS_PATH}/plan", json={"prompt": prompt}, cast_to=DatasetPlanResponse)
300
+
301
+ async def list(self, *, limit: int | None = None, cursor: str | None = None) -> DatasetListResponse:
302
+ """Async version of `DatasetsResource.list()`."""
303
+ params = _without_none(limit=limit, cursor=cursor)
304
+ return await self._get(_DATASETS_PATH, params=params, cast_to=DatasetListResponse)
305
+
306
+ async def get(self, dataset_id: str) -> Dataset:
307
+ """Async version of `DatasetsResource.get()`."""
308
+ return await self._get(_dataset_path(dataset_id), cast_to=Dataset)
309
+
310
+ async def delete(self, dataset_id: str) -> DatasetDeleteResponse:
311
+ """Async version of `DatasetsResource.delete()`."""
312
+ return await self._delete(_dataset_path(dataset_id), cast_to=DatasetDeleteResponse)
313
+
314
+ async def rows(self, dataset_id: str, *, limit: int | None = None, after: str | None = None) -> DatasetRowsResponse:
315
+ """Async version of `DatasetsResource.rows()`."""
316
+ params = _without_none(limit=limit, after=after)
317
+ return await self._get(_dataset_path(dataset_id, "/rows"), params=params, cast_to=DatasetRowsResponse)
318
+
319
+ async def populate(self, dataset_id: str, *, reset: bool | None = None, target_rows: int | None = None) -> Dataset:
320
+ """Async version of `DatasetsResource.populate()`. Billed; never retried."""
321
+ body = _without_none(reset=reset, target_rows=target_rows)
322
+ return await self._post(_dataset_path(dataset_id, "/populate"), json=body, cast_to=Dataset, max_retries=0)
323
+
324
+ async def cancel_run(self, dataset_id: str, run_id: str) -> DatasetCancelRunResponse:
325
+ """Async version of `DatasetsResource.cancel_run()`."""
326
+ return await self._post(_run_path(dataset_id, run_id, "/cancel"), cast_to=DatasetCancelRunResponse)
327
+
328
+ def events(
329
+ self,
330
+ dataset_id: str,
331
+ run_id: str,
332
+ *,
333
+ on_status: Callable[[DatasetRunStatusEvent], None] | None = None,
334
+ on_row: Callable[[DatasetRunRowEvent], None] | None = None,
335
+ on_log: Callable[[DatasetRunLogEvent], None] | None = None,
336
+ ) -> AsyncDatasetRunStream:
337
+ """Async version of `DatasetsResource.events()`."""
338
+ path = _run_path(dataset_id, run_id, "/events")
339
+ cursor = _RunCursor(self._client._max_retries, path, _callbacks(on_status, on_row, on_log))
340
+ return AsyncDatasetRunStream(self._follow(cursor))
341
+
342
+ async def _follow(self, cursor: _RunCursor) -> AsyncGenerator[DatasetRunEvent, None]:
343
+ while True:
344
+ error: Exception = _stream_closed()
345
+ try:
346
+ lines = self._get_stream(cursor.events_path, timeout=_EVENTS_TIMEOUT)
347
+ async with aclosing(_aread(lines, cursor)) as events:
348
+ async for event in events:
349
+ yield event
350
+ if isinstance(event, DatasetRunDoneEvent):
351
+ return
352
+ if cursor.terminal:
353
+ return
354
+ except _STREAM_ERRORS as exc:
355
+ if cursor.terminal:
356
+ return
357
+ error = exc
358
+ await asyncio.sleep(cursor.reconnect_or_raise(error))