rustai-core 0.4.0

Zero-cost local research pipeline: async search routing, TLS-fingerprint-aware fetching, SIMD DOM denoising and BM25 context slimming for local LLMs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
"""Type stubs for the compiled `rustai._rustai` extension."""

from typing import Any, Literal, Sequence

__version__: str

UnitKind = Literal["heading", "paragraph", "list_item", "code", "quote", "table"]
IndexMode = Literal["auto", "never", "always"]

class RustaiError(Exception):
    """Base class for every rustai error."""

class NetworkError(RustaiError):
    """The request failed at the transport level."""

class HttpStatusError(RustaiError):
    """The server answered with a failure status."""

class RobotsError(RustaiError):
    """robots.txt disallows this URL."""

class ExtractError(RustaiError):
    """The document could not be parsed."""

class ProviderError(RustaiError):
    """A search provider failed."""

class BrowserError(RustaiError):
    """The headless fallback was unavailable."""

class Meta:
    """Document metadata read from `<head>`."""
    @property
    def title(self) -> str | None:
        """Best available title."""
        ...
    @property
    def description(self) -> str | None:
        """Meta or Open Graph description."""
        ...
    @property
    def byline(self) -> str | None:
        """Declared author."""
        ...
    @property
    def published(self) -> str | None:
        """Publication timestamp, verbatim from the page."""
        ...
    @property
    def language(self) -> str | None:
        """BCP-47 language tag."""
        ...
    @property
    def canonical(self) -> str | None:
        """Canonical URL."""
        ...
    @property
    def site_name(self) -> str | None:
        """Site name."""
        ...
    def to_dict(self) -> dict[str, Any]:
        """Everything above, as a dict."""
        ...

class Unit:
    """One block of an extracted document."""
    @property
    def kind(self) -> UnitKind:
        """`"heading"`, `"paragraph"`, `"list_item"`, `"code"`, `"quote"` or `"table"`."""
        ...
    @property
    def level(self) -> int:
        """Heading level, or list nesting depth."""
        ...
    @property
    def text(self) -> str:
        """Plain text."""
        ...
    @property
    def markdown(self) -> str:
        """Rendered Markdown."""
        ...
    @property
    def heading_path(self) -> list[str]:
        """Enclosing headings, outermost first."""
        ...
    @property
    def position(self) -> int:
        """Index in document order."""
        ...
    @property
    def tokens(self) -> int:
        """Estimated tokens."""
        ...
    def to_dict(self) -> dict[str, Any]:
        """Everything above, as a dict."""
        ...

class DenoiseStats:
    """What the denoiser removed."""
    @property
    def nodes_visited(self) -> int:
        """Nodes considered."""
        ...
    @property
    def nodes_dropped(self) -> int:
        """Nodes rejected as boilerplate."""
        ...
    @property
    def html_bytes(self) -> int:
        """Bytes of HTML in."""
        ...
    @property
    def markdown_bytes(self) -> int:
        """Bytes of Markdown out."""
        ...
    @property
    def compression(self) -> float:
        """Size reduction in `[0, 1]`."""
        ...
    def to_dict(self) -> dict[str, Any]:
        """Everything above, as a dict."""
        ...

class Link:
    """One link harvested from a listing page."""
    @property
    def text(self) -> str:
        """Anchor text."""
        ...
    @property
    def url(self) -> str:
        """Absolute URL."""
        ...
    @property
    def snippet(self) -> str:
        """Nearby descriptive text, if the page offered any."""
        ...
    @property
    def heading_path(self) -> list[str]:
        """Enclosing section headings, outermost first."""
        ...
    def to_dict(self) -> dict[str, Any]:
        """Everything above, as a dict."""
        ...

class Article:
    """A cleaned document."""
    @property
    def url(self) -> str | None:
        """Source URL."""
        ...
    @property
    def kind(self) -> Literal["article", "index"]:
        """`"article"` for prose, `"index"` for a listing page."""
        ...
    @property
    def links(self) -> list[Link]:
        """Links harvested from a listing page."""
        ...
    @property
    def title(self) -> str | None:
        """Title, falling back to the first heading."""
        ...
    @property
    def markdown(self) -> str:
        """The whole cleaned document as Markdown."""
        ...
    @property
    def text(self) -> str:
        """The whole cleaned document as plain text."""
        ...
    @property
    def meta(self) -> Meta:
        """Metadata from `<head>`."""
        ...
    def chunks(
        self,
        *,
        target_tokens: int = 512,
        overlap_tokens: int = 64,
        min_tokens: int = 24,
    ) -> list[dict]:
        """Group the units into pieces an embedding model will accept.

        A `Unit` is one block — a paragraph, a list item, a heading. That is
        the grain ranking wants and the wrong one for a vector store: on MDN's
        `Promise` reference the median unit is 37 tokens and a third are under
        30, so embedding units directly gives you 125 vectors that each know
        almost nothing. This walks them in order and groups them up to
        `target_tokens`, starting a new chunk at each heading so a chunk opens
        with the thing that says what it is about.

        `overlap_tokens` repeats whole units from the previous chunk's tail, so
        an answer that straddles a boundary is retrievable from either side. A
        unit longer than `target_tokens` is emitted whole rather than cut
        mid-sentence, and an article that would otherwise produce nothing gets
        one chunk anyway — a short page is still a source.

        Returns dicts, ready to hand to a vector store:

        ```text
        for c in article.chunks():
            store.add(id=f"{c['url']}#{c['index']}", text=c["text"],
                      metadata={"title": c["title"], "url": c["url"]})
        ```
        """
        ...
    @property
    def units(self) -> list[Unit]:
        """Rankable blocks."""
        ...
    @property
    def stats(self) -> DenoiseStats:
        """Denoiser statistics."""
        ...
    @property
    def tokens(self) -> int:
        """Estimated tokens for the whole article."""
        ...
    def to_dict(self) -> dict[str, Any]:
        """The article as nested dicts."""
        ...
    def __len__(self) -> int:
        """Return len(self)."""
        ...

class Page:
    """A raw HTTP response."""
    @property
    def url(self) -> str:
        """URL as requested."""
        ...
    @property
    def final_url(self) -> str:
        """URL after redirects."""
        ...
    @property
    def status(self) -> int:
        """HTTP status code."""
        ...
    @property
    def content_type(self) -> str | None:
        """`Content-Type` header."""
        ...
    @property
    def body(self) -> str:
        """Decoded response body."""
        ...
    @property
    def elapsed_ms(self) -> int:
        """Wall time in milliseconds."""
        ...
    @property
    def rendered(self) -> bool:
        """Whether headless Chrome produced this body."""
        ...
    def extract(self) -> Article:
        """Extract this page without fetching it again."""
        ...
    def to_dict(self) -> dict[str, Any]:
        """Everything above, as a dict."""
        ...

class SearchResult:
    """One search hit."""
    @property
    def title(self) -> str:
        """Result title."""
        ...
    @property
    def url(self) -> str:
        """Absolute URL."""
        ...
    @property
    def snippet(self) -> str:
        """Provider snippet."""
        ...
    @property
    def providers(self) -> list[str]:
        """Providers that returned this URL."""
        ...
    @property
    def score(self) -> float:
        """Fused rank-fusion score."""
        ...
    @property
    def rank(self) -> int:
        """Best position this URL reached at any *single* provider, zero-based.

        Not this result's position in the fused list — for that, enumerate the
        list you were handed. A result ranked first by two providers and a
        result ranked first by one both report `0`; what separates them is
        `score`, which is what the list is sorted by.
        """
        ...
    def to_dict(self) -> dict[str, Any]:
        """Everything above, as a dict."""
        ...

class Context:
    """A compressed context window."""
    @property
    def query(self) -> str:
        """The query it was built for."""
        ...
    @property
    def markdown(self) -> str:
        """Ready-to-prompt Markdown."""
        ...
    @property
    def tokens(self) -> int:
        """Estimated tokens."""
        ...
    @property
    def sources(self) -> list[dict[str, Any]]:
        """Sources that contributed, as dicts."""
        ...
    @property
    def selected(self) -> list[dict[str, Any]]:
        """Why each unit was chosen, as dicts.

        Keys: `source` and `unit`, which are indices rather than text --
        `articles[source].units[unit]` is the block itself -- plus `tokens`
        and the three scores behind the decision: `relevance` (BM25 against
        the query), `density` (nouns and numbers over filler) and the combined
        `score`. Enough to answer "why is this in my context window and that
        paragraph is not".

        These scores rank units *within one query* and are not comparable
        across queries: BM25 scales with how rare the query's terms are, so a
        common-word question produces small numbers for good matches and a
        rare-word question large ones for mediocre matches. Measured on two
        live queries, an off-topic encyclopedia article scored 0.22 on one
        while every correct source on the other scored below 0.10 -- so a fixed
        cutoff drops the good set and keeps the bad one. Sort by them, show
        them, but do not threshold on them.
        """
        ...
    @property
    def units_considered(self) -> int:
        """Units available before selection."""
        ...
    def to_dict(self) -> dict[str, Any]:
        """Everything above, as a dict."""
        ...
    def __str__(self) -> str:
        """Return str(self)."""
        ...

class Research:
    """The result of a full research run."""
    @property
    def query(self) -> str:
        """The query as asked."""
        ...
    @property
    def context(self) -> Context:
        """The compressed context."""
        ...
    @property
    def markdown(self) -> str:
        """Ready-to-prompt Markdown, straight from the context."""
        ...
    @property
    def results(self) -> list[SearchResult]:
        """Search hits, best first."""
        ...
    @property
    def articles(self) -> list[Article]:
        """Articles that were successfully read."""
        ...
    @property
    def failures(self) -> list[tuple[str, str]]:
        """`(stage, message)` pairs for non-fatal failures."""
        ...
    def to_dict(self) -> dict[str, Any]:
        """Everything above, as a dict."""
        ...
    def __str__(self) -> str:
        """Return str(self)."""
        ...

class Client:
    """A reusable pipeline: connection pool, providers, extractor and slimmer.

    Build one and keep it: the connection pool, the robots cache and the
    per-host delays all live on the client, so a second call to a host you
    have already visited is cheaper.

    `providers` accepts `"duckduckgo"`, `"wikipedia"` or `"wikipedia:ko"`,
    `"searxng:https://…"`, `"rss:https://…"` and `"sitemap:https://…"`.

    Two separate caps decide how much work a question costs, and they are
    easy to mistake for each other:

    * `max_results` (this constructor) is search breadth -- how many fused
      hits `search` returns. Fetching nothing, it is cheap to raise.
    * `max_sources` (`research`) is read depth -- how many of those hits are
      actually fetched and extracted. This is what costs time.

    So `Client(max_results=20).research(q, max_sources=5)` casts a wide net
    and reads the best five of it. `max_results` was called `limit` in 0.2.0
    and that name still works.

    `respect_crawl_delay` is why a fetch sometimes stalls for a long time with
    nothing on the network. A site may publish a `Crawl-delay` in its
    `robots.txt` and this client honours it: arXiv asks for fifteen seconds
    between requests, so a second arXiv URL through the same client waits that
    long. A *new* client has not visited anything yet and so does not wait,
    which is worth knowing before concluding that reusing a client is slow.
    Setting this to `False` ignores a published request; do that for a host you
    own. `per_host_delay` does not override it — the larger of the two wins.

    `max_tokens_per_source` caps how much any one page may contribute to the
    context. Leaving it `None` is right for most questions: measured over six
    queries at budgets of 1,000, 2,048 and 4,096 tokens, capping either
    changed nothing or bought source coverage by admitting less relevant text,
    and coverage rises on its own as the budget grows. Reach for it when a
    question needs corroboration rather than depth -- two of those six queries
    had a single long page take 86% and 90% of the window, in one case
    starving the encyclopedia article on the exact term asked about.
    """
    def __init__(
        self,
        *,
        providers: Sequence[str] | None = None,
        concurrency: int = 16,
        timeout: float = 20.0,
        impersonate: str = "chrome",
        respect_robots: bool = True,
        respect_crawl_delay: bool = True,
        per_host_delay: float = 0.25,
        retries: int = 2,
        max_body_bytes: int = 8388608,
        accept_language: str = "en-US,en;q=0.9",
        browser_fallback: bool = False,
        contact_email: str | None = None,
        proxies: Sequence[str] | None = None,
        max_retry_after: float = 60.0,
        cookie_file: str | None = None,
        allow_private_hosts: bool = False,
        max_tokens: int = 2048,
        max_tokens_per_source: int | None = None,
        diversity: float = 0.35,
        include_links: bool = True,
        include_images: bool = False,
        include_tables: bool = True,
        index_mode: IndexMode = "auto",
        max_results: int | None = None,
        limit: int | None = None,
    ) -> None:
        """Initialize self.  See help(type(self)) for accurate signature."""
        ...
    def search(self, query: str, *, strict: bool = False) -> list[SearchResult]:
        """Search every configured provider and return fused results.

        Provider failures are not raised: a partial result set is more useful
        than an exception when one of five providers is having a bad day. Pass
        `strict=True` to raise when *every* provider failed.
        """
        ...
    def fetch(
        self, urls: Sequence[str], *, raise_on_error: bool = False
    ) -> list[Page]:
        """Fetch URLs concurrently.

        **The result is not 1:1 with the input.** With `raise_on_error=False`
        (the default) a failed URL is simply absent, so one dead link cannot
        lose you the other nineteen — but neither can you tell which one went,
        and indexing the result against the input you passed will be wrong.
        Match on `Page.url` instead, or pass `raise_on_error=True` when a
        missing page is a problem rather than a nuisance.

        This differs deliberately from `extract_many`, which is 1:1 and raises:
        there, an input is a document you already hold, and losing one silently
        would be a bug in your own pipeline. Here an input is somebody else's
        server, and it is allowed to be down.
        """
        ...
    def read(
        self, urls: Sequence[str], *, raise_on_error: bool = False
    ) -> list[Article]:
        """Fetch and extract in one step.

        **The result is not 1:1 with the input** — see `fetch`. Match on
        `Article.url` rather than by position, or pass `raise_on_error=True`.
        """
        ...
    def research(self, query: str, *, max_sources: int = 5) -> Research:
        """Search, read the top results, and compress them into a context window."""
        ...
    def save_cookies(self) -> int:
        """Write the cookie jar to the `cookie_file` this client was built with.

        Returns how many cookies were saved, or 0 when no file was configured.
        Clearance cookies are the expensive part of getting through a bot wall;
        saving them means not paying for them again next run.
        """
        ...

def extract(
    html: str,
    url: str | None = None,
    *,
    include_links: bool = True,
    include_images: bool = False,
    include_tables: bool = True,
    index_mode: IndexMode = "auto",
) -> Article:
    """Denoise a raw HTML string into Markdown. No network access."""
    ...
def extract_many(
    documents: Sequence[str],
    urls: Sequence[str | None] | None = None,
    *,
    include_links: bool = True,
    include_images: bool = False,
    include_tables: bool = True,
    index_mode: IndexMode = "auto",
) -> list[Article]:
    """Denoise many HTML strings at once, in parallel across the rayon pool.

    This is the batch form of [`extract`]. Parsing is CPU-bound and per-document
    independent, so a list of 20 documents costs roughly one document's wall
    time on a multi-core machine — and because the GIL is released for the whole
    call, it parallelises whether or not the caller uses threads.

    `urls` is optional; when given it must be the same length as `documents`.
    Output is 1:1 with the input, so a failed document raises rather than
    silently shifting every later index.
    """
    ...
def slim(
    query: str,
    articles: Sequence[Article],
    *,
    max_tokens: int = 2048,
    diversity: float = 0.35,
    max_tokens_per_source: int | None = None,
    include_breadcrumbs: bool = True,
    query_vector: Sequence[float] | None = None,
    unit_vectors: Sequence[Sequence[float]] | None = None,
    semantic_weight: float = 0.5,
) -> Context:
    """Rank and compress already-extracted articles into a context window.

    Pass `query_vector` and `unit_vectors` to blend an embedding model's
    judgement into the ranking. BM25 cannot see that "딥러닝" and "deep
    learning" name the same subject, or that a paragraph explains a term
    without using it; a model you already run can, and the arithmetic then
    happens across every core with the GIL released:

    ```text
    units = [u.text for a in articles for u in a.units]
    ctx = rustai.slim(
        query, articles,
        query_vector=model.encode(query).tolist(),
        unit_vectors=model.encode(units).tolist(),
        semantic_weight=0.5,          # 0 is pure BM25, 1 is pure vector
    )
    ```

    One vector per unit, flattened in that exact order — short units are
    dropped before scoring, so the alignment is against every unit rather than
    the surviving ones, and a wrong-sized list is refused rather than quietly
    mis-ranked. Vectors need not be normalised.

    Diversity still uses word overlap rather than vector distance. The
    duplicate threshold is calibrated against overlap, and two paragraphs of
    one article routinely exceed 0.8 cosine under a sentence transformer, so
    swapping the measure without recalibrating would start discarding the
    second half of every source.
    """
    ...
def research(
    query: str,
    *,
    max_sources: int = 5,
    max_tokens: int = 2048,
    max_tokens_per_source: int | None = None,
    providers: Sequence[str] | None = None,
    impersonate: str = "chrome",
    respect_robots: bool = True,
    contact_email: str | None = None,
) -> Research:
    """Search, read and compress in one call, using a throwaway client.

    `max_tokens_per_source` caps how much any one page may contribute; see
    `Client` for when that is worth doing.
    """
    ...
def chunk_many(
    articles: Sequence[Article],
    *,
    target_tokens: int = 512,
    overlap_tokens: int = 64,
    min_tokens: int = 24,
) -> list[dict]:
    """Chunk many articles at once, in parallel across the rayon pool.

    The batch form of `Article.chunks`. Chunking is cheap per article but a
    crawl produces thousands, and the GIL is released for the whole call, so a
    list costs roughly one article's wall time on a multi-core machine.

    Returns one flat list: chunks carry their own `url`, so which article a
    chunk came from survives the flattening, which is the shape a vector store
    wants anyway.
    """
    ...
def count_tokens(text: str) -> int:
    """Estimate how many LLM tokens a string costs."""
    ...
def tokenize(text: str) -> list[str]:
    """Split text into the tokens the ranker uses."""
    ...
def density(text: str) -> float:
    """Score a block of text for information density, `0.0`–`1.0`."""
    ...
def canonical_url(url: str) -> str | None:
    """Normalise a URL to the identity used for deduplication."""
    ...
def parse_feed(xml: str) -> list[dict[str, Any]]:
    """Parse an RSS or Atom feed into a list of dicts."""
    ...
def parse_sitemap(xml: str) -> dict[str, list[str]]:
    """Parse a sitemap into `{"urls": [...], "sitemaps": [...]}`."""
    ...