Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

docs(resources, ops, cli): Python and Rust pages for common resources, built-in ops and the CLI (#2749)

LJ πŸ₯₯🌴fd2c4786750b
diff --git a/docs/src/content/docs/cli.mdx b/docs/src/content/docs/cli.mdx
index 025f9a5a..7bf2ee65 100644
--- a/docs/src/content/docs/cli.mdx
+++ b/docs/src/content/docs/cli.mdx
@@ -2,13 +2,13 @@
title: The *CLI* reference
description: >
Reference for the `cocoindex` CLI β€” app target formats, environment variable
- loading, and subcommands for init, ls, show, update (catch-up or live), and
- drop.
+ loading, and subcommands for init, ls, show, update (catch-up or live), drop
+ and google-drive.
languages: [python]
---
-CocoIndex CLI is a standalone tool for managing and inspecting your apps.
+CocoIndex CLI is a standalone tool for managing and inspecting your apps. This page describes the CLI for Python projects, installed with the `cocoindex` package.
-This page describes the CLI for Python projects. A Rust project has its own `cocoindex` binary with the same subcommands; see [the Rust CLI reference](/docs/rust/cli/). Both read the same state database format, so `show --db PATH --app-name NAME` works on either tool against an app the other SDK wrote.
+Rust projects have their own `cocoindex` binary with the same subcommands; see [the Rust CLI reference](/docs/rust/cli/). Both read the same state database format, so `show --db PATH --app-name NAME` works on either tool against an app the other SDK wrote.
## Invoke the CLI
diff --git a/docs/src/content/docs/cli_commands.mdx b/docs/src/content/docs/cli_commands.mdx
index 68a1d1d1..77bc90cc 100644
--- a/docs/src/content/docs/cli_commands.mdx
+++ b/docs/src/content/docs/cli_commands.mdx
@@ -3,6 +3,8 @@ title: CLI *subcommands* reference
description: >
Reference for every `cocoindex` CLI subcommand β€” drop, init, ls, show, and
update (catch-up or live) β€” with their arguments, flags, and app-target formats.
+languages: [python]
+rust_counterpart: cli
---
## Subcommands reference
diff --git a/docs/src/content/docs/cli_rust.mdx b/docs/src/content/docs/cli_rust.mdx
index 41407ef1..2155c5be 100644
--- a/docs/src/content/docs/cli_rust.mdx
+++ b/docs/src/content/docs/cli_rust.mdx
@@ -3,12 +3,12 @@ title: The *CLI* reference
description: >
Reference for the `cocoindex` CLI for Rust projects β€” how it builds and drives
your crate, the app target format, the three attributes an app registers with,
- and the ls, show, update, drop and init subcommands.
+ and the ls, show, update, drop, init and google-drive subcommands.
languages: [rust]
# The Rust page in the CLI slot: /docs/rust/cli/.
route: cli
---
-The `cocoindex` CLI for Rust projects gives a Rust pipeline the same commands the [Python CLI](/docs/cli/) has: `ls`, `show`, `update`, `drop`, `init` and `google-drive`. The Python prose on that page describes the Python tool; this page describes the Rust tool, which is a separate binary built from the `rust/cli` crate of the repository.
+The `cocoindex` CLI for Rust projects is a standalone tool for managing and inspecting your apps: `ls`, `show`, `update`, `drop`, `init` and `google-drive`. It is a binary of its own, built from the `rust/cli` crate of the repository. Python projects use the [Python CLI](/docs/cli/), which has the same subcommands.
## How it works
@@ -71,7 +71,7 @@ async fn main() -> Result<()> {
}
```
-- `#[cocoindex::lifespan]` registers the environment setup: the state database path, the shared resources provided under context keys, and shutdown hooks. The function takes the `EnvironmentBuilder` by value and returns it. It is the Rust analogue of Python's `@coco.lifespan`. The same lifespan runs when your own code calls `Environment::from_registered()`.
+- `#[cocoindex::lifespan]` registers the environment setup: the state database path, the shared resources provided under context keys, and shutdown hooks. The function takes the `EnvironmentBuilder` by value and returns it. The same lifespan runs when your own code calls `Environment::from_registered()`.
- `#[cocoindex::app(name = "...")]` registers an app entry point. The name defaults to the function name. The function keeps its signature and stays callable. App names must be unique within one binary.
- `#[cocoindex::main]` makes your `async fn main` the entry point of a cocoindex binary. When the CLI started the binary, the CLI's request is answered before the body runs; otherwise the body runs as a normal `main`.
@@ -216,7 +216,7 @@ The scaffold is a crate with `Cargo.toml`, `src/main.rs` (a `lifespan`, an `app`
### `google-drive`
-Sign a personal Google account in to the Google Drive connector (experimental). The same two commands as the Python CLI, over the same token file, so one sign-in serves both SDKs; see [Google Drive](./connectors/google_drive#signing-in-with-a-personal-account).
+Sign a personal Google account in to the Google Drive connector (experimental). The Python CLI has the same two commands over the same token file, so one sign-in serves both SDKs; see [Google Drive](./connectors/google_drive#signing-in-with-a-personal-account).
```sh
cocoindex google-drive sign-in [CLIENT_SECRETS]
diff --git a/docs/src/content/docs/common_resources/data_types.mdx b/docs/src/content/docs/common_resources/data_types.mdx
index 3ded42a1..d1baf0f1 100644
--- a/docs/src/content/docs/common_resources/data_types.mdx
+++ b/docs/src/content/docs/common_resources/data_types.mdx
@@ -4,20 +4,32 @@ description: >
Data types shared across connectors and built-in operations β€” FileLike,
FilePath, FilePathMatcher, Chunk with text positions, and the Embedder
protocol for single-text async embedding.
+rust_description: >
+ Data types shared across connectors and built-in operations β€” FileLike,
+ FilePath, FilePathMatcher, Chunk with text positions, and the Embedder
+ trait for single-text async embedding.
---
import LangTabs from '../../../components/LangTabs.astro';
+<Lang only="python">
+
The `cocoindex.resources` package provides common data models and abstractions shared across connectors and built-in operations. Connectors provide concrete implementations β€” for example, `localfs.File` implements `FileLike`, and `localfs.FilePath` extends `FilePath`. See individual [connector docs](../connectors/localfs) for connector-specific details.
-The Rust SDK has the same modules under `cocoindex::resources` (`file`, `fs`, `chunk`, `embedder`, `id`, `live_map`, `rate_limit`, `schema`). The types this page names are re-exported from `cocoindex::prelude`. The local file system lives in `cocoindex::resources::fs`: its `FileEntry` implements `FileLike`, and `walk_dir` builds a `FilePath` for each file.
+</Lang>
+
+<Lang only="rust">
+
+The `cocoindex::resources` modules (`file`, `fs`, `chunk`, `embedder`, `id`, `live_map`, `rate_limit`, `schema`) provide common data models and abstractions shared across connectors and built-in operations. The types this page names are re-exported from `cocoindex::prelude`. Connectors provide concrete implementations β€” for example, the local file system (`cocoindex::resources::fs`) has `FileEntry`, which implements `FileLike`, and its `walk_dir` builds a `FilePath` for each file. See individual [connector docs](../connectors/localfs) for connector-specific details.
+
+</Lang>
## File
-The file module (`cocoindex.resources.file`) defines base classes and utilities for working with file-like objects.
+The file module (<Lang only="python">`cocoindex.resources.file`</Lang><Lang only="rust">`cocoindex::resources::file`</Lang>) defines <Lang only="python">base classes</Lang><Lang only="rust">types and traits</Lang> and utilities for working with file-like objects.
### FileLike
-`FileLike` is a base class for file objects with async read methods. Each connector provides its own subclass (e.g., `localfs.File`, `amazon_s3.S3Object`).
+<Lang only="python">`FileLike` is a base class for file objects with async read methods. Each connector provides its own subclass (e.g., `localfs.File`, `amazon_s3.S3Object`).</Lang><Lang only="rust">`FileLike` is a trait for file objects with async read methods. Each connector has a type that implements it: `FileEntry` for the local file system, `AzureBlobFile` for Azure Blob Storage, and so on. A function takes the concrete type, as below, or a `&dyn FileLike`.</Lang>
{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (read_file), examples/rust/azure_blob_embedding/src/main.rs */}
<LangTabs>
@@ -44,11 +56,11 @@ async fn read_file(ctx: &Ctx, file: &FileEntry) -> Result<String> {
}
```
-In Rust, `FileLike` is a trait (`cocoindex::resources::file::FileLike`). Each connector has a type that implements it: `FileEntry` for the local file system, `AzureBlobFile` for Azure Blob Storage, and so on. A function takes the concrete type, as above, or a `&dyn FileLike`.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
**Properties:**
- `file_path` β€” A `FilePath` object representing the file's path. Access the relative path via `file_path.path` (`PurePath`).
@@ -59,29 +71,37 @@ In Rust, `FileLike` is a trait (`cocoindex::resources::file::FileLike`). Each co
- `async read(size=-1)` β€” Read file content as bytes. Pass `size` to limit bytes read.
- `async read_text(encoding=None, errors="replace")` β€” Read as text. Auto-detects encoding via BOM if not specified.
-The Rust trait has the same surface with Rust names:
+</Lang>
+
+<Lang only="rust">
+
+**Methods:**
+
+- `file_path()` β€” A `FilePath` representing the file's path. Access the relative path via `file_path().path()` (`&Path`).
+- `metadata().await?` β€” A `FileMetadata`: `size` in bytes, `modified`, and an optional `content_fingerprint`.
+- `read().await?` β€” The file content as `bytes::Bytes` (the cached content, shared, not copied).
+- `read_size(size).await?` β€” At most `size` bytes of the content.
+- `read_text().await?` β€” The content as text. Detects the encoding by BOM, falls back to UTF-8, and decodes with replacement characters.
+- `read_text_with(encoding, errors).await?` β€” The content as text with an explicit decoding: `encoding` is a WHATWG label such as `Some("latin1")` or `Some("utf-16le")` (or `"utf-32le"` / `"utf-32be"`), `None` detects by BOM; `errors` is `DecodeErrors::Replace` (the default of `read_text`), `Ignore` or `Strict`.
+- `content_fingerprint().await?` β€” The `Fingerprint` the memo validation uses.
-| Python | Rust (`FileLike`) |
-|---|---|
-| `file.file_path` | `file.file_path()` returns a `FilePath` |
-| `await file.size()` | `file.metadata().await?.size`; `FileMetadata` also holds `modified` and an optional `content_fingerprint` |
-| `await file.read()` | `file.read().await?` returns `bytes::Bytes` (the cached content, shared, not copied) |
-| `await file.read(size)` | `file.read_size(size).await?` |
-| `await file.read_text()` | `file.read_text().await?` detects a BOM and decodes with replacement characters |
-| `await file.read_text(encoding="latin1", errors="strict")` | `file.read_text_with(Some("latin1"), DecodeErrors::Strict).await?` |
-| β€” | `file.content_fingerprint().await?` returns the `Fingerprint` the memo validation uses |
+`decode_bytes_with` decodes bytes you already hold the same way. `FileEntry` adds the sync helpers `content()` and `content_str()`, plus `key()`, `stem()` and `relative_path()`.
-`read_text_with(encoding, errors)` is Python's `read_text(encoding=, errors=)`: `encoding` is a WHATWG label such as `"latin1"` or `"utf-16le"` (or `"utf-32le"` / `"utf-32be"`), `None` detects by BOM and falls back to UTF-8; `DecodeErrors::Replace` (the default), `Ignore` and `Strict` are Python's `"replace"`, `"ignore"` and `"strict"`. `decode_bytes_with` does the same on bytes you already hold. `FileEntry` adds the sync helpers `content()` and `content_str()`, plus `key()`, `stem()` and `relative_path()`.
+</Lang>
**Memoization:**
`FileLike` objects provide a memoization key based on `file_path` (file identity). When used as arguments to a [memoized function](../programming_guide/function#memoization), CocoIndex uses a two-level validation: it checks the modification time first (cheap), then computes a content fingerprint only if the modification time has changed. This means touching a file or moving it won't cause unnecessary recomputation if the content is unchanged. When the backend reports a fingerprint at no cost (for example an S3 ETag), CocoIndex compares it even when the modification time is unchanged. This catches an overwrite within the resolution of the modification time (S3 reports whole seconds).
-The Rust types do the same: a `FileLike` is a `MemoInput` whose key is `file_path().memo_key()`, and whose state is the modification time, validated by the content fingerprint when the time changed. A `FileEntry` can therefore be an argument of a `#[cocoindex::function(memo)]` directly, or inside a `Vec`.
+<Lang only="rust">
+
+A `FileLike` is a `MemoInput` whose key is `file_path().memo_key()`, and whose state is the modification time, validated by the content fingerprint when the time changed. A `FileEntry` can therefore be an argument of a `#[cocoindex::function(memo)]` directly, or inside a `Vec`.
+
+</Lang>
### FilePath
-`FilePath` is a base class that combines a **base directory** (with a stable key) and a **relative path**. This enables stable memoization even when the entire directory tree is moved to a different location.
+`FilePath` <Lang only="python">is a base class that combines</Lang><Lang only="rust">combines</Lang> a **base directory** (with a stable key) and a **relative path**. This enables stable memoization even when the entire directory tree is moved to a different location.
{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (with_base_dir), rust/sdk/cocoindex/tests/fs_target.rs (under_context_dir) */}
<LangTabs>
@@ -109,11 +129,11 @@ let files = walk_dir(FilePath::with_base_dir("docs", root.to_path_buf(), PathBuf
let root = FilePath::under_context_dir(&ctx, &OUT_DIR, "out")?;
```
-In Rust there is one `FilePath` struct for every connector. `with_base_dir(base_key, base_dir, path)` is Python's `FilePath(path, base_dir=...)`; `under_context_dir(&ctx, &KEY, path)` reads the base directory from the context and uses the key's name as the base key.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
Each connector provides its own `FilePath` subclass (e.g., `localfs.FilePath`). The base class defines the common interface.
**Properties:**
@@ -125,10 +145,30 @@ Each connector provides its own `FilePath` subclass (e.g., `localfs.FilePath`).
- `resolve()` β€” Resolve to the full path (type depends on the connector, e.g., `pathlib.Path` for local filesystem).
-In Rust, `path()` returns the relative `&Path`, `base_key()` the optional base key, and `resolve()` a `PathBuf` (the base directory joined with the path).
+</Lang>
+
+<Lang only="rust">
+
+One `FilePath` struct serves every connector.
+
+**Constructors:**
+
+- `FilePath::new(path)` β€” A path with no base key.
+- `FilePath::with_base_dir(base_key, base_dir, path)` β€” A path under a base directory with a stable key.
+- `FilePath::under_context_dir(&ctx, &KEY, path)?` β€” Reads the base directory from a `ContextKey<PathBuf>` in the context and uses the key's name as the base key.
+
+**Methods:**
+
+- `path()` β€” The path relative to the base directory (`&Path`).
+- `base_key()` β€” The optional base key, used for stable memoization.
+- `resolve()` β€” The full path, a `PathBuf` (the base directory joined with the path).
+
+</Lang>
**Path Operations:**
+<Lang only="python">
+
`FilePath` supports most `pathlib.PurePath` operations:
```python
@@ -154,22 +194,30 @@ config_path.match("*.json") # True
config_path.as_posix() # "config/settings.json"
```
-The Rust `FilePath` has the same operations as methods: `join(child)`, `name()`, `stem()`, `suffix()`, `suffixes()`, `parts()`, `parent()`, `with_name(..)`, `with_stem(..)`, `with_suffix(..)`, `parents()`, `relative_to(base)`, `is_relative_to(base)`, `matches(pattern)` and `as_posix()`. `matches` follows `PurePath.match`: a relative pattern is matched from the right, one component at a time, and an absolute pattern must match the whole path.
+</Lang>
+
+<Lang only="rust">
+
+`FilePath` has the `pathlib.PurePath`-style operations as methods: `join(child)`, `name()`, `stem()`, `suffix()`, `suffixes()`, `parts()`, `parent()`, `with_name(..)`, `with_stem(..)`, `with_suffix(..)`, `parents()`, `relative_to(base)`, `is_relative_to(base)`, `matches(pattern)` and `as_posix()`. `matches` follows `PurePath.match`: a relative pattern is matched from the right, one component at a time, and an absolute pattern must match the whole path. Each method that returns a path keeps the base key.
+
+</Lang>
**Memoization:**
-`FilePath` provides a memoization key based on `(base_dir.key, path)`. This means:
+`FilePath` provides a memoization key based on <Lang only="python">`(base_dir.key, path)`</Lang><Lang only="rust">`(base_key, path)`, returned by `memo_key()`; it falls back to the path alone when the `FilePath` has no base key</Lang>. This means:
- Two `FilePath` objects with the same base directory key and relative path have the same memo key
- Moving the entire project directory doesn't invalidate memoization, as long as the same base directory key is used
-For connector-specific usage (e.g., `register_base_dir`), see the individual connector documentation like [Local File System](../connectors/localfs).
-
-In Rust, `memo_key()` returns that same `(base_key, path)` pair, and it falls back to the path alone when the `FilePath` has no base key.
+For connector-specific usage<Lang only="python"> (e.g., `register_base_dir`)</Lang>, see the individual connector documentation like [Local File System](../connectors/localfs).
### FilePathMatcher
-`FilePathMatcher` is a protocol for filtering files and directories during traversal.
+`FilePathMatcher` is a <Lang only="python">protocol</Lang><Lang only="rust">trait</Lang> for filtering files and directories during traversal.
+
+{/* Rust: rust/sdk/cocoindex/src/resources/file.rs (trait definition) */}
+<LangTabs>
+<Fragment slot="python">
```python
from cocoindex.resources.file import FilePathMatcher
@@ -184,7 +232,27 @@ class MyMatcher(FilePathMatcher):
return path.suffix in (".py", ".md")
```
-In Rust, `FilePathMatcher` is a trait with the same two methods, `is_dir_included(&self, path: &Path) -> bool` (default: `true`) and `is_file_included(&self, path: &Path) -> bool`. Pass an implementation to `walk_dir(..).path_matcher(..)`. `MatchAllFilePathMatcher` includes everything.
+</Fragment>
+<Fragment slot="rust">
+
+```rust
+pub trait FilePathMatcher: Send + Sync {
+ fn is_dir_included(&self, _path: &Path) -> bool {
+ true
+ }
+
+ fn is_file_included(&self, path: &Path) -> bool;
+}
+```
+
+</Fragment>
+</LangTabs>
+
+<Lang only="rust">
+
+`is_dir_included` returns `true` to traverse a directory (the default); `is_file_included` returns `true` to include a file. Pass an implementation to `walk_dir(..).path_matcher(..)`. `MatchAllFilePathMatcher` includes everything.
+
+</Lang>
#### PatternFilePathMatcher
@@ -219,14 +287,18 @@ let files = walk_dir(sourcedir)
)?);
```
-`PatternFilePathMatcher::new(included, excluded)` takes two iterables of patterns and returns a `Result`: an invalid glob is an error at construction. `PatternFilePathMatcher::include(patterns)` is the form with no exclusions.
-
</Fragment>
</LangTabs>
+<Lang only="rust">
+
+`PatternFilePathMatcher::new(included, excluded)` takes two iterables of patterns and returns a `Result`: an invalid glob is an error at construction. `PatternFilePathMatcher::include(patterns)` is the form with no exclusions.
+
+</Lang>
+
**Parameters:**
-- `included_patterns` β€” Glob patterns ([globset](https://docs.rs/globset) syntax) for files to include. Use `**/*.ext` to match at any depth. If `None`, all files are included.
+- `included_patterns` β€” Glob patterns ([globset](https://docs.rs/globset) syntax) for files to include. Use `**/*.ext` to match at any depth. <Lang only="python">If `None`, all files are included.</Lang><Lang only="rust">An empty list includes all files.</Lang>
- `excluded_patterns` β€” Glob patterns ([globset](https://docs.rs/globset) syntax) for files/directories to exclude. Excluded directories are not traversed. A pattern prefixed with `!` negates the exclusion for matching paths (see below).
:::note
@@ -235,6 +307,8 @@ Patterns use [globset](https://docs.rs/globset) semantics: `*.py` matches only i
**Gitignore-style negation.** Within `excluded_patterns`, a pattern beginning with `!` *un-excludes* paths that would otherwise be excluded by a preceding pattern. This lets you exclude broadly and then carve out exceptions, instead of enumerating every directory to exclude:
+<Lang only="python">
+
```python
# Exclude all dot-entries, but keep .github through
matcher = PatternFilePathMatcher(
@@ -245,15 +319,33 @@ matcher = PatternFilePathMatcher(
)
```
-Directory traversal honors negations correctly: a directory excluded by a normal pattern is still traversed when a `!` pattern could match its contents, so the kept paths inside it are reachable.
+</Lang>
-The Rust matcher reads the same `!` negations from its `excluded` patterns, and traverses directories the same way.
+<Lang only="rust">
+
+```rust
+// Exclude all dot-entries, but keep .github through
+let matcher = PatternFilePathMatcher::new(
+ std::iter::empty::<&str>(),
+ [
+ "**/.*", // exclude all dot-files and dot-directories
+ "!**/.github/**", // …except anything under .github
+ ],
+)?;
+```
+
+</Lang>
+
+Directory traversal honors negations correctly: a directory excluded by a normal pattern is still traversed when a `!` pattern could match its contents, so the kept paths inside it are reachable.
## Chunk
-The chunk module (`cocoindex.resources.chunk`) defines types for representing text chunks produced by [text splitters](../ops/text).
+The chunk module (<Lang only="python">`cocoindex.resources.chunk`</Lang><Lang only="rust">`cocoindex::resources::chunk`</Lang>) defines types for representing text chunks produced by [text splitters](../ops/text).
### Chunk
+
+<Lang only="python">
+
A `Chunk` is a frozen dataclass representing a piece of text with its position information in the original document.
```python
@@ -266,20 +358,52 @@ from cocoindex.resources.chunk import Chunk
- `start` (`TextPosition`) β€” Start position in the original text.
- `end` (`TextPosition`) β€” End position in the original text.
-The Rust `Chunk` (`cocoindex::resources::chunk::Chunk`, in the prelude) has the public fields `start` and `end`, but it does not own its text. It keeps the byte range: `chunk.range()` returns it, and `chunk.text(&source)` returns the slice of the original string. Chunking a large document therefore does not copy its contents.
+</Lang>
+
+<Lang only="rust">
+
+A `Chunk` (in the prelude) represents a piece of text with its position information in the original document.
+
+```rust
+use cocoindex::resources::chunk::Chunk;
+```
+
+**Fields and methods:**
+
+- `start` (`TextPosition`) β€” Start position in the original text.
+- `end` (`TextPosition`) β€” End position in the original text.
+- `range()` β€” The byte range of the chunk in the original text.
+- `text(&source)` β€” The text content of the chunk: the slice of the original string.
+
+</Lang>
+
+<RustNote>
+A `Chunk` does not own its text. It keeps the byte range, and `chunk.text(&source)` slices the original string, so chunking a large document does not copy its contents.
+</RustNote>
### TextPosition
-A frozen dataclass representing a position in text.
+<Lang only="python">A frozen dataclass representing a position in text.</Lang><Lang only="rust">A struct representing a position in text.</Lang>
**Fields:**
+<Lang only="python">
+
- `byte_offset` (`int`) β€” Byte offset from the start of the text.
- `char_offset` (`int`) β€” Character offset from the start of the text.
- `line` (`int`) β€” 1-based line number.
- `column` (`int`) β€” 1-based column number.
-In Rust, `TextPosition` has the same four fields: `byte_offset` and `char_offset` are `usize`, `line` and `column` are `u32`.
+</Lang>
+
+<Lang only="rust">
+
+- `byte_offset` (`usize`) β€” Byte offset from the start of the text.
+- `char_offset` (`usize`) β€” Character offset from the start of the text.
+- `line` (`u32`) β€” 1-based line number.
+- `column` (`u32`) β€” 1-based column number.
+
+</Lang>
**Example:**
@@ -324,10 +448,20 @@ for chunk in &chunks {
## Embedder
-The embedder module (`cocoindex.resources.embedder`) defines a protocol for single-text async embedding.
+The embedder module (<Lang only="python">`cocoindex.resources.embedder`</Lang><Lang only="rust">`cocoindex::resources::embedder`</Lang>) defines a <Lang only="python">protocol</Lang><Lang only="rust">trait</Lang> for single-text async embedding.
+
+<Lang only="python">
### Embedder Protocol
+</Lang>
+
+<Lang only="rust">
+
+### Embedder trait
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/resources/embedder.rs (trait definition) */}
<LangTabs>
<Fragment slot="python">
@@ -351,15 +485,25 @@ pub trait Embedder: Send + Sync {
}
```
-The Rust trait takes the `Ctx` explicitly, so an implementation can memoize each text and batch concurrent calls through the engine. The two built-in embedders, [`SentenceTransformerEmbedder`](../ops/sentence_transformers) and [`ApiEmbedder`](../ops/litellm), do both.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
This is the call-site contract that consumers like [`resolve_entities`](../ops/entity_resolution) rely on. Both [`LiteLLMEmbedder`](../ops/litellm) and [`SentenceTransformerEmbedder`](../ops/sentence_transformers) satisfy this protocol β€” `await embedder.embed("some text")` returns a single `NDArray[np.float32]`.
The protocol is deliberately narrow: it does not include `dimension()` or `__coco_vector_schema__()`, which are concerns of connectors and table-schema creation, not of embedding consumers.
+</Lang>
+
+<Lang only="rust">
+
+This is the call-site contract that consumers like [`resolve_entities`](../ops/entity_resolution) rely on. Both [`SentenceTransformerEmbedder`](../ops/sentence_transformers) and [`ApiEmbedder`](/docs/rust/ops/model_apis/) implement this trait β€” `embedder.embed(ctx, "some text").await?` returns a single `Vec<f32>`.
+
+The trait takes the `Ctx` explicitly, so an implementation can memoize each text and batch concurrent calls through the engine; the two built-in embedders do both. The trait is deliberately narrow: it does not include the vector dimension or vector schema, which are concerns of connectors and table-schema creation, not of embedding consumers.
+
+</Lang>
+
{/* Rust: examples/rust/conversation_to_knowledge/src/pipeline.rs (resolve_entities) */}
<LangTabs>
<Fragment slot="python">
@@ -394,7 +538,11 @@ let resolved = entity_resolution::resolve_entities(
.await?;
```
-`resolve_entities` takes an `EntityEmbedder`. Every `Embedder` is one through a blanket implementation, so a `SentenceTransformerEmbedder`, an `ApiEmbedder` or your own type works as is.
-
</Fragment>
</LangTabs>
+
+<Lang only="rust">
+
+`resolve_entities` takes an `EntityEmbedder`. Every `Embedder` is one through a blanket implementation, so a `SentenceTransformerEmbedder`, an `ApiEmbedder` or your own type works as is.
+
+</Lang>
diff --git a/docs/src/content/docs/common_resources/id_generation.mdx b/docs/src/content/docs/common_resources/id_generation.mdx
index 7a988331..40bda94f 100644
--- a/docs/src/content/docs/common_resources/id_generation.mdx
+++ b/docs/src/content/docs/common_resources/id_generation.mdx
@@ -7,24 +7,39 @@ description: >
---
import LangTabs from '../../../components/LangTabs.astro';
-The ID module (`cocoindex.resources.id`) provides utilities for generating stable unique IDs and UUIDs that persist across incremental updates. The Rust SDK has the same four APIs in `cocoindex::resources::id`, re-exported from `cocoindex::prelude`.
+The ID module (<Lang only="python">`cocoindex.resources.id`</Lang><Lang only="rust">`cocoindex::resources::id`, re-exported from `cocoindex::prelude`</Lang>) provides utilities for generating stable unique IDs and UUIDs that persist across incremental updates.
-In an incremental pipeline, using random IDs (like `uuid.uuid4()`) means every reprocessing run generates different IDs for the same data β€” causing unnecessary churn in your targets (deleting old rows, inserting identical ones with new IDs). CocoIndex's ID utilities produce **stable** IDs: the same inputs produce the same IDs across runs, so unchanged data keeps its identity and targets only see real changes.
+In an incremental pipeline, using random IDs (like <Lang only="python">`uuid.uuid4()`</Lang><Lang only="rust">`Uuid::new_v4()`</Lang>) means every reprocessing run generates different IDs for the same data β€” causing unnecessary churn in your targets (deleting old rows, inserting identical ones with new IDs). CocoIndex's ID utilities produce **stable** IDs: the same inputs produce the same IDs across runs, so unchanged data keeps its identity and targets only see real changes.
## Choosing the right API
+<Lang only="python">
+
| API | Same `dep` produces... | Use when... |
|-----|------------------------|-------------|
| `generate_id(dep)` | **Same** ID every time | Each unique input maps to exactly one ID |
| `IdGenerator.next_id(dep)` | **Distinct** ID each call | You need multiple IDs for potentially non-distinct inputs |
+</Lang>
+
+<Lang only="rust">
+
+| API | Same `dep` produces... | Use when... |
+|-----|------------------------|-------------|
+| `generate_id(&ctx, &dep)` | **Same** ID every time | Each unique input maps to exactly one ID |
+| `id_gen.next_id(&ctx, &dep)` | **Distinct** ID each call | You need multiple IDs for potentially non-distinct inputs |
+
+</Lang>
+
The same distinction applies to `generate_uuid` vs `UuidGenerator`.
-The Rust names are `generate_id(&ctx, &dep)` and `id_gen.next_id(&ctx, &dep)`. Every Rust ID function takes the component's `Ctx` first: the memo that keeps an ID stable belongs to the processing component, and in Rust the context is explicit.
+<RustNote>
+Every ID function takes the component's `Ctx` first: the memo that keeps an ID stable belongs to the processing component, and in Rust the context is explicit.
+</RustNote>
## generate_id / generate_uuid
-Async functions that return the **same** ID/UUID for the **same** `dep` value. These are idempotent: calling multiple times with identical `dep` yields identical results.
+<Lang only="python">`generate_id` is an async function and `generate_uuid` a sync one;</Lang><Lang only="rust">Async functions that</Lang> <Lang only="python">both</Lang> return the **same** ID/UUID for the **same** `dep` value. These are idempotent: calling multiple times with identical `dep` yields identical results.
{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (generate_id_returns_same_id_for_same_dep_across_runs, generate_uuid_...) */}
<LangTabs>
@@ -38,9 +53,9 @@ async def process_item(item: Item) -> Row:
item_id = await generate_id(item.key)
return Row(id=item_id, data=item.data)
-async def process_document(doc: Document) -> Row:
+def process_document(doc: Document) -> Row:
# Same doc.path always gets the same UUID
- doc_uuid = await generate_uuid(doc.path)
+ doc_uuid = generate_uuid(doc.path)
return Row(id=doc_uuid, content=doc.content)
```
@@ -65,25 +80,43 @@ let uuids = vec![
];
```
-`dep` is any `Serialize` value, passed by reference. `generate_id_default(&ctx)` and `generate_uuid_default(&ctx)` are the forms with no dependency value (Python's `dep=None`).
-
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `dep` β€” Dependency value that determines the ID/UUID. The same `dep` always produces the same result within a component. Defaults to `None`.
+</Lang>
+
+<Lang only="rust">
+
+- `ctx` β€” The component's `Ctx`.
+- `dep` β€” Dependency value that determines the ID/UUID: any `Serialize` value, passed by reference. The same `dep` always produces the same result within a component. `generate_id_default(&ctx)` and `generate_uuid_default(&ctx)` are the forms with no dependency value.
+
+</Lang>
+
**Returns:**
+<Lang only="python">
+
- `generate_id` returns an `int` (IDs start from 1; 0 is reserved)
- `generate_uuid` returns a `uuid.UUID`
-In Rust, `generate_id` returns a `u64` and `generate_uuid` a `uuid::Uuid`, each inside a `Result`.
+</Lang>
+
+<Lang only="rust">
+
+- `generate_id` returns a `Result<u64>` (IDs start from 1; 0 is reserved)
+- `generate_uuid` returns a `Result<uuid::Uuid>`
+
+</Lang>
## IdGenerator / UuidGenerator
-Classes that return a **distinct** ID/UUID on each call, even when called with the same `dep` value. The sequence is stable across runs.
+<Lang only="python">Classes</Lang><Lang only="rust">Generators</Lang> that return a **distinct** ID/UUID on each call, even when called with the same `dep` value. The sequence is stable across runs.
Use these when you need multiple IDs for potentially non-distinct inputs, such as splitting text into chunks where chunks may have identical content but still need unique IDs.
@@ -104,13 +137,13 @@ async def process_document(doc: Document) -> list[Row]:
rows.append(Row(id=chunk_id, content=chunk.content))
return rows
-async def process_with_uuids(doc: Document) -> list[Row]:
+def process_with_uuids(doc: Document) -> list[Row]:
# Use doc.path to distinguish generators within the same processing component
uuid_gen = UuidGenerator(deps=doc.path)
rows = []
for chunk in split_into_chunks(doc.content):
# Each call returns a distinct UUID, even if chunks are identical
- chunk_uuid = await uuid_gen.next_uuid(chunk.content)
+ chunk_uuid = uuid_gen.next_uuid(chunk.content)
rows.append(Row(id=chunk_uuid, content=chunk.content))
return rows
```
@@ -163,20 +196,43 @@ let uuid_gen = UuidGenerator::new();
let uuid = uuid_gen.next_uuid(&ctx, &"same").await?;
```
-`next_id` and `next_uuid` take `&self`: the generator counts how often it has seen each `dep` behind a mutex, and that ordinal is part of the memo key. One generator can therefore be shared by the concurrent closures of `ctx.map`, as in `examples/rust/text_embedding`. Concurrent calls take their ordinals in the order they reach the generator, so give each call a `dep` that identifies its item, as the chunk text does above. A generator is not `Clone`: a copy would replay the same ordinals and hand out the same IDs again.
-
</Fragment>
</LangTabs>
+<Lang only="rust">
+
+`next_id` and `next_uuid` take `&self`: the generator counts how often it has seen each `dep` behind a mutex, and that ordinal is part of the memo key. One generator can therefore be shared by the concurrent closures of `ctx.map`, as in `examples/rust/text_embedding`. Concurrent calls take their ordinals in the order they reach the generator, so give each call a `dep` that identifies its item, as the chunk text does above. A generator is not `Clone`: a copy would replay the same ordinals and hand out the same IDs again.
+
+</Lang>
+
**Constructor:**
+<Lang only="python">
+
- `IdGenerator(deps=None)` / `UuidGenerator(deps=None)` β€” Create a generator. The `deps` parameter distinguishes generators within the same [processing component](../programming_guide/processing_component). Use distinct `deps` values for different generator instances.
-In Rust: `IdGenerator::new()` / `UuidGenerator::new()` have no dependency; `IdGenerator::with_deps(&deps)?` / `UuidGenerator::with_deps(&deps)?` take any `Serialize` value.
+</Lang>
+
+<Lang only="rust">
+
+- `IdGenerator::new()` / `UuidGenerator::new()` β€” Create a generator with no dependency.
+- `IdGenerator::with_deps(&deps)?` / `UuidGenerator::with_deps(&deps)?` β€” Create a generator whose `deps` (any `Serialize` value) distinguishes it from other generators within the same [processing component](../programming_guide/processing_component). Use distinct `deps` values for different generator instances.
+
+</Lang>
**Methods:**
+<Lang only="python">
+
- `async IdGenerator.next_id(dep=None)` β€” Generate the next unique integer ID (distinct on each call)
-- `async UuidGenerator.next_uuid(dep=None)` β€” Generate the next unique UUID (distinct on each call)
+- `UuidGenerator.next_uuid(dep=None)` β€” Generate the next unique UUID (distinct on each call)
+
+</Lang>
+
+<Lang only="rust">
+
+- `async fn next_id(&self, ctx: &Ctx, dep: &D) -> Result<u64>` β€” Generate the next unique integer ID (distinct on each call)
+- `async fn next_uuid(&self, ctx: &Ctx, dep: &D) -> Result<Uuid>` β€” Generate the next unique UUID (distinct on each call)
+- `next_id_default(&ctx)` / `next_uuid_default(&ctx)` β€” The same with no per-call dependency.
-In Rust: `next_id(&ctx, &dep)` / `next_uuid(&ctx, &dep)`, and `next_id_default(&ctx)` / `next_uuid_default(&ctx)` with no per-call dependency.
+</Lang>
diff --git a/docs/src/content/docs/common_resources/index.mdx b/docs/src/content/docs/common_resources/index.mdx
index e1b21690..7c9fdd16 100644
--- a/docs/src/content/docs/common_resources/index.mdx
+++ b/docs/src/content/docs/common_resources/index.mdx
@@ -7,6 +7,17 @@ description: >
import DocCardGrid from '@cocoindex/brand/DocCardGrid.astro';
import { commonResourcesGroups } from '/src/data/section-grids';
+{/* The grid's hrefs point at the Python tree; the Rust page gets a copy that points at /docs/rust/. */}
+export const rustGroups = commonResourcesGroups.map((g) => ({
+ ...g,
+ cards: g.cards.map((c) => ({ ...c, href: c.href.replace(/^\/docs\//, '/docs/rust/') })),
+}));
+
The building blocks that connectors and operations share. Reach for these when you wire your own pieces together, or need the exact type a connector expects.
+<Lang only="python">
<DocCardGrid groups={commonResourcesGroups} ariaLabel="Common resources" />
+</Lang>
+<Lang only="rust">
+<DocCardGrid groups={rustGroups} ariaLabel="Common resources" />
+</Lang>
diff --git a/docs/src/content/docs/common_resources/live_map.mdx b/docs/src/content/docs/common_resources/live_map.mdx
index e65fbeab..7c8a503d 100644
--- a/docs/src/content/docs/common_resources/live_map.mdx
+++ b/docs/src/content/docs/common_resources/live_map.mdx
@@ -4,17 +4,19 @@ description: >
LiveMap is an in-memory keyed collection that bridges live producing and consuming
logic β€” declare (key, value) entries as target states on one side, consume it as a
LiveMapView with mount_each on the other.
+rust_description: >
+ LiveMap is an in-memory keyed collection that bridges live producing and consuming
+ logic β€” declare (key, value) entries as target states on one side, consume it as a
+ LiveMapView with ctx.mount_each_live on the other.
---
import LangTabs from '../../../components/LangTabs.astro';
-`LiveMap[K, V]` (`cocoindex.resources.live_map`) is an in-memory, keyed collection that sits **between** a producing part of your pipeline and a consuming part. The producing side **declares** `(key, value)` entries; the consuming side reads the map as a [`LiveMapView`](../advanced_topics/live_component#livemapfeed-and-livemapview) via `coco.mount_each`, getting one [processing component](../programming_guide/processing_component) per entry that stays in sync as entries appear, change, and disappear.
+<Lang only="python">`LiveMap[K, V]` (`cocoindex.resources.live_map`)</Lang><Lang only="rust">`LiveMap<K, V>` (`cocoindex::resources::live_map`, also `cocoindex::LiveMap`)</Lang> is an in-memory, keyed collection that sits **between** a producing part of your pipeline and a consuming part. The producing side **declares** `(key, value)` entries; the consuming side reads the map as a [`LiveMapView`](../advanced_topics/live_component#livemapfeed-and-livemapview) via <Lang only="python">`coco.mount_each`</Lang><Lang only="rust">`ctx.mount_each_live`</Lang>, getting one [processing component](../programming_guide/processing_component) per entry that stays in sync as entries appear, change, and disappear.
-Think of it as a connector whose "external system" is an in-process `dict`: entries are declared as [target states](../programming_guide/target_state) (so they participate in CocoIndex's declarative change detection and ownership) and that same `dict` is simultaneously exposed as a live source for downstream components. It lets you split a pipeline into a producer half and a consumer half that are decoupled through one shared, incrementally-maintained collection.
+Think of it as a connector whose "external system" is an in-process <Lang only="python">`dict`</Lang><Lang only="rust">map</Lang>: entries are declared as [target states](../programming_guide/target_state) (so they participate in CocoIndex's declarative change detection and ownership) and that same map is simultaneously exposed as a live source for downstream components. It lets you split a pipeline into a producer half and a consumer half that are decoupled through one shared, incrementally-maintained collection.
It is designed for [live mode](../programming_guide/live_mode): the producer and consumer run concurrently, and the consumer reacts as the producer updates the map.
-The Rust SDK has `LiveMap<K, V>` in `cocoindex::resources::live_map` (also `cocoindex::LiveMap`). `K` is any `LiveMapKey`: `String`, `i64`, `u64` or a `StableKey`, so a composite key works too.
-
## Example
{/* Rust: rust/sdk/cocoindex/tests/live_map.rs (live module: Producer, Consumer) */}
@@ -50,7 +52,10 @@ async def app_main() -> None:
<Fragment slot="rust">
```rust
+use std::sync::{Arc, Mutex};
+
use cocoindex::{Ctx, LiveComponent, LiveComponentOperator, LiveMap, Result, async_trait};
+use tokio::sync::Notify;
/// Declares every entry of `source`; re-runs its full pass on `trigger`.
struct Producer {
@@ -138,9 +143,19 @@ let lm: LiveMap<String, String> = LiveMap::create(&ctx).await?;
</Fragment>
</LangTabs>
-`create()` is an async factory and must be called from **inside the app's component tree** (it mounts a backing target). `K` must be a [stable key](../programming_guide/processing_component#component-path); `V` is any value comparable with `==` β€” no hashability, serialization, or fingerprinting is required, so arbitrary objects (lists, dataclasses, …) work.
+`create` is an async factory and must be called from **inside the app's component tree** (it mounts a backing target).
+
+<Lang only="python">
+
+`K` must be a [stable key](../programming_guide/processing_component#component-path); `V` is any value comparable with `==` β€” no hashability, serialization, or fingerprinting is required, so arbitrary objects (lists, dataclasses, …) work.
+
+</Lang>
+
+<Lang only="rust">
+
+`K` is any `LiveMapKey`: `String`, `i64`, `u64` or a [`StableKey`](../programming_guide/processing_component#component-path), so a composite key works too. `V` must be `Serialize + DeserializeOwned + Clone + PartialEq + Send + Sync + 'static` (the `LiveMapValue` bound, implemented automatically for every such type). Values are compared with `==`; the serialization bound is what makes an entry a target state. A `LiveMap` is cheap to clone, and all clones share one map.
-In Rust, the key is a `String`, and `V` must be `Serialize + DeserializeOwned + Clone + PartialEq + Send + Sync + 'static` (the `LiveMapValue` bound, implemented automatically for every such type). Values are compared with `==` as in Python; the serialization bound is what makes an entry a target state. A `LiveMap` is cheap to clone, and all clones share one map.
+</Lang>
## Producing entries
@@ -156,7 +171,7 @@ lm.declare_entry(key, value)
<Fragment slot="rust">
```rust
-lm.declare_entry(&ctx, "a", "alpha".to_string())?;
+lm.declare_entry(&ctx, "a".to_string(), "alpha".to_string())?;
```
</Fragment>
@@ -172,7 +187,7 @@ Multiple components may declare into the same map, as long as each key has a sin
## Consuming entries
-A `LiveMap` is a [`LiveMapView`](../advanced_topics/live_component#livemapfeed-and-livemapview), so pass it straight to `coco.mount_each` β€” it behaves just like a live source:
+A `LiveMap` is a [`LiveMapView`](../advanced_topics/live_component#livemapfeed-and-livemapview), so pass it straight to <Lang only="python">`coco.mount_each`</Lang><Lang only="rust">`ctx.mount_each_live`</Lang> β€” it behaves just like a live source:
{/* Rust: rust/sdk/cocoindex/tests/live_map.rs (Consumer::process) */}
<LangTabs>
@@ -196,20 +211,20 @@ ctx.mount_each_live(&"each", self.lm.clone(), move |_ctx, value: String| {
.await
```
-In Rust the consumer is `ctx.mount_each_live(&key, feed, process_fn)`: the Rust `LiveMap` implements `LiveMapView<String, V>` and `LiveMapFeed<String, V>`, so it is a live feed like a watched directory. `lm.scan().await?` returns the current entries as `Vec<(String, V)>`.
+`ctx.mount_each_live(&key, feed, process_fn)` takes the map as its feed: `LiveMap<K, V>` implements `LiveMapView<K, V>` and `LiveMapFeed<K, V>`, so it is a live feed like a watched directory. `lm.scan().await?` (from the `LiveMapView` trait) returns the current entries as `Vec<(K, V)>`.
</Fragment>
</LangTabs>
-`mount_each` mounts one processing component per entry (keyed by the entry key), scans the current entries first, then reacts to incremental changes β€” re-mounting a component when its value changes and removing it when its entry is deleted. The processor receives the entry **value**.
+<Lang only="python">`mount_each`</Lang><Lang only="rust">`mount_each_live`</Lang> mounts one processing component per entry (keyed by the entry key), scans the current entries first, then reacts to incremental changes β€” re-mounting a component when its value changes and removing it when its entry is deleted. The processor receives the entry **value**.
-A LiveMap supports **one active consumer** (`mount_each`) at a time; a second concurrent consumer raises `RuntimeError`. In Rust, the second concurrent `watch()` fails with an `Error` instead, and a consumer that finished (or was mounted again) can watch the map again.
+A LiveMap supports **one active consumer** at a time; <Lang only="python">a second concurrent consumer (`mount_each`) raises `RuntimeError`.</Lang><Lang only="rust">a second concurrent `watch` fails with an `Error`. A consumer that finished, failed or was cancelled releases the map, so it can be watched again.</Lang>
## Semantics
-- **Live-mode first.** LiveMap is built for [`app.update(live=True)`](../programming_guide/live_mode): the consumer subscribes and reacts as producers update the map. In catch-up mode (plain `app.update()`), the consumer scans whatever entries happen to exist when it runs, which can race producers running concurrently in the same session β€” so for predictable one-shot results, order the producer ahead of the consumer (await the producer's `handle.ready()` before consuming).
+- **Live-mode first.** LiveMap is built for [live mode](../programming_guide/live_mode)<Lang only="python"> (`app.update(live=True)`)</Lang>: the consumer subscribes and reacts as producers update the map. In catch-up mode (a plain update<Lang only="python">, `app.update()`</Lang>), the consumer scans whatever entries happen to exist when it runs, which can race producers running concurrently in the same session β€” so for predictable one-shot results, order the producer ahead of the consumer (<Lang only="python">await the producer's `handle.ready()`</Lang><Lang only="rust">wait for the producer's mount handle to be ready</Lang> before consuming).
- **In-memory and per-session.** The map lives in process memory and is rebuilt from its producers each time the app starts; its contents do not persist across restarts.
-- **Empty in a preview.** A preview (`app.update(preview=True)`, `cocoindex update --preview`) applies no target actions, so it does not fill the map either: its consumers see an empty map, and the preview lists no downstream actions for them. Preview the producers' own targets instead. The Rust `app.preview(..)` behaves the same way.
+- **Empty in a preview.** A preview (<Lang only="python">`app.update(preview=True)`</Lang><Lang only="rust">`app.preview(..)`</Lang>, `cocoindex update --preview`) applies no target actions, so it does not fill the map either: its consumers see an empty map, and the preview lists no downstream actions for them. Preview the producers' own targets instead.
## When to use it
diff --git a/docs/src/content/docs/common_resources/rate_limiting.mdx b/docs/src/content/docs/common_resources/rate_limiting.mdx
index 6dc95864..a331030b 100644
--- a/docs/src/content/docs/common_resources/rate_limiting.mdx
+++ b/docs/src/content/docs/common_resources/rate_limiting.mdx
@@ -6,12 +6,12 @@ description: >
---
import LangTabs from '../../../components/LangTabs.astro';
-The rate-limiting module (`cocoindex.resources.rate_limit`) provides a
+The rate-limiting module (<Lang only="python">`cocoindex.resources.rate_limit`</Lang><Lang only="rust">`cocoindex::resources::rate_limit`</Lang>) provides a
token-bucket `RateLimiter` for throttling outbound work β€” typically the API calls
a pipeline makes to an external service β€” so it stays within that service's rate
limit.
-{/* Rust: rust/sdk/cocoindex/src/resources/rate_limit.rs (signatures; no example or test calls RateLimiter yet) */}
+{/* Rust: rust/sdk/cocoindex/src/resources/rate_limit.rs (signatures checked against the source; no example or test calls RateLimiter yet, and the snippets are shaped after examples/rust/text_embedding) */}
<LangTabs>
<Fragment slot="python">
@@ -31,7 +31,7 @@ use cocoindex::resources::rate_limit::RateLimiter; // also in cocoindex::prelude
## RateLimiter
-A token-bucket limiter. Acquire tokens with `await limiter.acquire(n)`; the call
+A token-bucket limiter. Acquire tokens with <Lang only="python">`await limiter.acquire(n)`</Lang><Lang only="rust">`limiter.acquire(n).await?`</Lang>; the call
returns once `n` tokens are available, otherwise it waits.
{/* Rust: rust/sdk/cocoindex/src/resources/rate_limit.rs (signatures) */}
@@ -59,23 +59,40 @@ impl RateLimiter {
}
```
-The Rust constructor has no default arguments: pass `Duration::from_secs(1)` for Python's default burst window, and `acquire(1)` for one token. An invalid rate (zero or negative) is an error from `new`.
-
</Fragment>
</LangTabs>
+<RustNote>
+The constructor and `acquire` have no default arguments: pass `Duration::from_secs(1)` for a one-second burst window, and `acquire(1)` for one token. An invalid rate (zero or negative) is an error from `new`, not a panic.
+</RustNote>
+
**Constructor parameters:**
- `max_rows_per_second` β€” the **sustained** rate, in tokens (think: units of
work) per second. Fractional rates are supported (e.g. `2.5` β†’ one token every
0.4s). Must be positive.
+
+<Lang only="python">
+
- `burst_window_secs` β€” the **burst** allowance, in seconds. Up to
`max_rows_per_second * burst_window_secs` tokens may accumulate while the
limiter is idle, letting a sudden fan-out proceed immediately before settling
to the sustained rate. Defaults to `1.0` (a one-second burst). Set to `0.0` for
no burst (strict spacing between tokens).
-**`acquire(n=1)`** β€” wait until `n` tokens are available, then consume them. A
+</Lang>
+
+<Lang only="rust">
+
+- `burst_window` β€” the **burst** allowance, as a `Duration`. Up to
+ `max_rows_per_second` Γ— `burst_window` (in seconds) tokens may accumulate while the
+ limiter is idle, letting a sudden fan-out proceed immediately before settling
+ to the sustained rate. `Duration::from_secs(1)` gives a one-second burst;
+ `Duration::ZERO` gives no burst (strict spacing between tokens).
+
+</Lang>
+
+**<Lang only="python">`acquire(n=1)`</Lang><Lang only="rust">`acquire(n)`</Lang>** β€” wait until `n` tokens are available, then consume them. A
single `RateLimiter` is safe to share across concurrent callers; they are served
in **FIFO order**, so no caller can be starved.
@@ -112,11 +129,15 @@ of sharing is the instance: functions and components handed the *same*
`RateLimiter` draw from one shared budget, while two separately-constructed
limiters are two independent budgets β€” even with identical `max_rows_per_second`.
-The Rust `RateLimiter` is `Clone`, and every clone shares the one bucket. Cloning
+<Lang only="rust">
+
+`RateLimiter` is `Clone`, and every clone shares the one bucket. Cloning
is the way to hand a limiter to several closures; it does not create a second budget.
+</Lang>
+
The idiomatic way to share one budget is to bind a `RateLimiter` to a
-[context](../programming_guide/context) key and retrieve it with `coco.use_context`
+[context](../programming_guide/context) key and retrieve it with <Lang only="python">`coco.use_context`</Lang><Lang only="rust">`ctx.get_key`</Lang>
wherever you make outbound calls. Every component then draws from the same budget,
with no limiter to thread through each signature:
@@ -168,11 +189,13 @@ async fn fetch_one(ctx: &Ctx, item: Item) -> Result<Data> {
</Fragment>
</LangTabs>
-Because the key resolves to one shared instance, every `acquire()` across the app
+Because the key resolves to one shared instance, every `acquire` call across the app
draws from the same 50/s budget.
## Pacing a batched function
+<Lang only="python">
+
A [batched function](../programming_guide/function#batching) whose every batch is one request can take its tokens from the limiter itself: pass it as `rate_limiter`, and each batch takes one token before it runs. A token then pays for one batch rather than one call, and calls that arrive while the batcher waits for a token ride the next batch, so a scarce quota is spent on full batches. See [Pacing batches with a rate limiter](../programming_guide/function#pacing-batches-with-a-rate-limiter).
```python
@@ -184,12 +207,22 @@ async def fetch_many(ids: list[str]) -> list[Item]:
return await call_external_api(ids) # one request per batch, one token each
```
-The Rust `#[cocoindex::function(batching, ..)]` has no `rate_limiter` option. Call `acquire(1)` at the start of the batched body instead: the body runs once per batch, so one token still pays for one batch.
+</Lang>
+
+<Lang only="rust">
+
+A [batched function](../programming_guide/function#batching) whose every batch is one request can pace itself on the limiter: call `acquire(1)` at the start of the batched body. The body runs once per batch, so a token pays for one batch rather than one call, and a scarce quota is spent on batches rather than on single items.
+
+</Lang>
+
+<RustNote>
+`#[cocoindex::function(batching, ..)]` has no `rate_limiter` option, so the batcher does not wait for a token before it forms a batch. Call `acquire(1)` in the body instead.
+</RustNote>
## When to use it
Reach for a `RateLimiter` whenever a pipeline makes outbound calls to a
-rate-limited service β€” an API you query from a `@coco.fn`, an embedding or LLM
+rate-limited service β€” an API you query from a <Lang only="python">`@coco.fn`</Lang><Lang only="rust">`#[cocoindex::function]`</Lang>, an embedding or LLM
endpoint, a bucket or database with a request cap β€” and you want the whole
pipeline to stay within one budget rather than each call site guessing at its own
`sleep`. Because a fan-out (e.g. one component per source item) can otherwise
diff --git a/docs/src/content/docs/common_resources/vector_schema.mdx b/docs/src/content/docs/common_resources/vector_schema.mdx
index cda9f14b..25807f0c 100644
--- a/docs/src/content/docs/common_resources/vector_schema.mdx
+++ b/docs/src/content/docs/common_resources/vector_schema.mdx
@@ -4,16 +4,22 @@ description: >
Describe vector columns with VectorSchema and VectorSchemaProvider. Covers
the three annotation patterns (ContextKey, embedder instance, explicit
schema) and MultiVectorSchema for models like ColBERT.
+rust_description: >
+ Describe vector columns with VectorSchema and VectorSchemaProvider. Covers
+ the three ways to size a vector field (an embedder from the context, an
+ embedder instance, an explicit schema) and MultiVectorSchema for models like ColBERT.
---
import LangTabs from '../../../components/LangTabs.astro';
-The schema module (`cocoindex.resources.schema`) defines types that describe vector columns. CocoIndex connectors use these to automatically configure the correct column type (e.g., `vector(384)` in Postgres, `fixed_size_list<float32>(384)` in LanceDB).
+The schema module (<Lang only="python">`cocoindex.resources.schema`</Lang><Lang only="rust">`cocoindex::resources::schema`, re-exported from `cocoindex::prelude`</Lang>) defines types that describe vector columns. CocoIndex connectors use these to automatically configure the correct column type (e.g., `vector(384)` in Postgres, `fixed_size_list<float32>(384)` in LanceDB).
-The Rust SDK has the same types in `cocoindex::resources::schema` (re-exported from `cocoindex::prelude`): `VectorSchema`, `VectorElementType`, `VectorSchemaProvider`, `MultiVectorSchema` and `MultiVectorSchemaProvider`. Python attaches a schema to a dataclass field with `Annotated`; Rust attaches it to a row struct field with `#[coco(vector)]` and resolves it on the connector's `TableSchema`.
+<RustNote>
+A vector schema is not attached to the row type with an annotation. A row struct field is marked `#[coco(vector)]` (or `#[coco(vector = N)]`), and the connector's `TableSchema` resolves its dimension.
+</RustNote>
## VectorSchema
-A frozen dataclass that describes a vector column's dtype and dimension.
+<Lang only="python">A frozen dataclass</Lang><Lang only="rust">A struct</Lang> that describes a vector column's dtype and dimension.
{/* Rust: rust/sdk/cocoindex/src/resources/schema.rs (VectorSchema::f32, f16) */}
<LangTabs>
@@ -44,10 +50,19 @@ let schema = VectorSchema { element_type: VectorElementType::Float32, size: 768
**Fields:**
+<Lang only="python">
+
- `dtype` β€” NumPy dtype of each element (e.g., `np.float32`)
- `size` β€” Number of dimensions in the vector (e.g., `384`)
-In Rust, the element type is the `VectorElementType` enum (`Float32`, `Float16`, `Float64`) instead of a NumPy dtype. `Float16` selects a half-precision column where the store has one; `Float32` and `Float64` both select the store's standard float vector column, as the Python connectors do for every dtype other than `float16`.
+</Lang>
+
+<Lang only="rust">
+
+- `element_type` β€” A `VectorElementType`: `Float32`, `Float16` or `Float64`. `Float16` selects a half-precision column where the store has one; `Float32` and `Float64` both select the store's standard float vector column.
+- `size` β€” Number of dimensions in the vector (e.g., `384`)
+
+</Lang>
You can construct `VectorSchema` directly when using a custom embedding model that doesn't implement `VectorSchemaProvider`:
@@ -99,18 +114,42 @@ let target = qdrant::mount_collection_target(
## VectorSchemaProvider
+<Lang only="python">
+
A protocol for objects that can provide vector schema information. The primary use case is as metadata in `Annotated` type annotations β€” connectors extract vector column configuration from the annotation automatically.
Any object that implements the `__coco_vector_schema__()` method satisfies this protocol. The built-in [`SentenceTransformerEmbedder`](../ops/sentence_transformers) implements it.
-In Rust, `VectorSchemaProvider` is a trait with one method, `async fn vector_schema(&self) -> Result<VectorSchema>`. `SentenceTransformerEmbedder`, `ApiEmbedder` and `VectorSchema` itself implement it. A Rust row struct does not carry the provider: a field marked `#[coco(vector)]` has a dimension that is "unresolved" until the connector schema's `with_vector_schema(field, &provider)` (or `with_vector_dim(field, n)`) supplies it. Mounting a target with an unresolved vector column is an error that names the field and `with_vector_dim`.
-
There are three ways to specify vector schema in annotations:
+</Lang>
+
+<Lang only="rust">
+
+A trait for values that can provide vector schema information, with one method, `async fn vector_schema(&self) -> Result<VectorSchema>`. The built-in [`SentenceTransformerEmbedder`](../ops/sentence_transformers), [`ApiEmbedder`](/docs/rust/ops/model_apis/) and `VectorSchema` itself implement it.
+
+A row struct does not carry the provider: a field marked `#[coco(vector)]` has a dimension that is "unresolved" until the connector schema's `with_vector_schema(field, &provider)` (or `with_vector_dim(field, n)`) supplies it. Mounting a target with an unresolved vector column is an error that names the field and `with_vector_dim`.
+
+There are three ways to size a vector field:
+
+</Lang>
+
+<Lang only="python">
+
### Using a `ContextKey` (recommended)
Define a [`ContextKey`](../programming_guide/context) for the embedder and use it as the annotation. The connector resolves the key at schema creation time. This is the recommended approach because the embedder is configured once in the lifespan and shared across all functions via context.
+</Lang>
+
+<Lang only="rust">
+
+### Using an embedder from the context (recommended)
+
+Define a [context key](../programming_guide/context) for the embedder, resolve it with `ctx.get_key(&EMBEDDER)?` when you mount the target, and pass the embedder to `with_vector_schema`. This is the recommended approach because the embedder is configured once in the lifespan and shared across all functions via context.
+
+</Lang>
+
{/* Rust: examples/rust/text_embedding/src/main.rs */}
<LangTabs>
<Fragment slot="python">
@@ -184,14 +223,12 @@ let table = postgres::mount_table_target(
let embedding = ctx.get_key(&EMBEDDER)?.embed(ctx, text).await?;
```
-Python's connector resolves the `ContextKey` itself. In Rust the context is explicit: resolve the key with `ctx.get_key(&EMBEDDER)?` and pass the embedder to `with_vector_schema`.
-
</Fragment>
</LangTabs>
### Using a `VectorSchemaProvider` instance
-Pass an embedder instance directly as the annotation. Simpler for scripts where the embedder is a module-level constant.
+Pass an embedder instance directly <Lang only="python">as the annotation</Lang><Lang only="rust">to `with_vector_schema`</Lang>. Simpler for scripts where the embedder is a module-level constant.
{/* Rust: rust/sdk/SHOWCASE.md "Derive connector schemas from row types", verified against rust/sdk/cocoindex/src/connectors/postgres.rs (with_vector_schema) */}
<LangTabs>
@@ -220,11 +257,15 @@ let schema = postgres::TableSchema::from_row::<DocEmbedding>(["id"])?
.await?;
```
-`with_vector_schema` takes any `VectorSchemaProvider` by reference. The Postgres, SQLite, Doris and LanceDB schemas have it; Qdrant's `CollectionSchema::from_row` takes `with_vector_dim`.
-
</Fragment>
</LangTabs>
+<Lang only="rust">
+
+`with_vector_schema` takes any `VectorSchemaProvider` by reference. The Postgres, SQLite, Doris, LanceDB and SurrealDB schemas have it; Qdrant's `CollectionSchema::from_row`, Turbopuffer and zvec take `with_vector_dim`.
+
+</Lang>
+
### Using a `VectorSchema`
Specify dimension and dtype explicitly. Useful when using a custom embedding model that doesn't implement `VectorSchemaProvider`.
@@ -254,14 +295,22 @@ struct ImageEmbedding {
}
```
-`#[coco(vector = N)]` fixes an `f32` column of dimension `N` for every connector the struct is used with. `#[coco(vector = N, half)]` makes it a half-precision column. For a dimension known only at run time, keep `#[coco(vector)]` and call `with_vector_dim("embedding", n)?` on the connector schema, or pass a fixed `VectorSchema` to `with_vector_schema`, since `VectorSchema` is its own provider.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
When a connector's `TableSchema.from_class()` encounters an `Annotated[NDArray, annotation]` field, it resolves the annotation (unwrapping `ContextKey` if needed) and calls `__coco_vector_schema__()` to determine the column's dimension and dtype.
-The Rust counterpart is the connector's `TableSchema::from_row::<Row>(primary_key)`, which reads the `#[derive(SchemaFields)]` row struct. A `#[coco(vector = N)]` field is complete; a `#[coco(vector)]` field waits for `with_vector_schema` or `with_vector_dim`.
+</Lang>
+
+<Lang only="rust">
+
+`#[coco(vector = N)]` fixes an `f32` column of dimension `N` for every connector the struct is used with. `#[coco(vector = N, half)]` makes it a half-precision column. For a dimension known only at run time, keep `#[coco(vector)]` and call `with_vector_dim("embedding", n)?` on the connector schema, or pass a fixed `VectorSchema` to `with_vector_schema`, since `VectorSchema` is its own provider.
+
+A connector's `TableSchema::from_row::<Row>(primary_key)` reads the `#[derive(SchemaFields)]` row struct. A `#[coco(vector = N)]` field is complete; a `#[coco(vector)]` field waits for `with_vector_schema` or `with_vector_dim`.
+
+</Lang>
## MultiVectorSchema / MultiVectorSchemaProvider
@@ -292,7 +341,11 @@ let multi_schema = MultiVectorSchema {
let collection = CollectionSchema::from_multivector_schema(multi_schema, Distance::Cosine)?;
```
-`MultiVectorSchemaProvider` is the trait form (`async fn multi_vector_schema(&self) -> Result<MultiVectorSchema>`), implemented by `MultiVectorSchema` itself; Qdrant's `CollectionSchema::from_multivector_provider(&provider, distance)` accepts one.
-
</Fragment>
</LangTabs>
+
+<Lang only="rust">
+
+`MultiVectorSchemaProvider` is the trait form (`async fn multi_vector_schema(&self) -> Result<MultiVectorSchema>`), implemented by `MultiVectorSchema` itself; Qdrant's `CollectionSchema::from_multivector_provider(&provider, distance)` accepts one.
+
+</Lang>
diff --git a/docs/src/content/docs/ops/entity_resolution.mdx b/docs/src/content/docs/ops/entity_resolution.mdx
index 399b96c8..aefdfac1 100644
--- a/docs/src/content/docs/ops/entity_resolution.mdx
+++ b/docs/src/content/docs/ops/entity_resolution.mdx
@@ -4,11 +4,24 @@ description: >
Deduplicate entity names via FAISS embedding similarity and a pluggable LLM
pair-resolver that confirms matches and chooses canonical forms β€” with
PINNED / PREFERRED policies for existing canonicals and resolution callbacks.
+rust_description: >
+ Deduplicate entity names via embedding similarity and a pluggable LLM
+ pair-resolver that confirms matches and chooses canonical forms β€” with
+ Pinned / Preferred policies for existing canonicals and resolution callbacks.
---
-import LangTabs from '../../../components/LangTabs.astro';
+
+<Lang only="python">
The `cocoindex.ops.entity_resolution` package resolves a set of raw entity names into a deduplicated canonical map. It finds near-duplicate names via embedding similarity (FAISS), then asks a pair-resolver (typically an LLM) to confirm matches and pick the better canonical name.
+</Lang>
+
+<Lang only="rust">
+
+The `cocoindex::entity_resolution` module resolves a set of raw entity names into a deduplicated canonical map. It finds near-duplicate names via embedding similarity, then asks a pair-resolver (typically an LLM) to confirm matches and pick the better canonical name.
+
+</Lang>
+
{/* Rust: examples/rust/conversation_to_knowledge/src/pipeline.rs */}
<LangTabs>
<Fragment slot="python">
@@ -25,11 +38,23 @@ use cocoindex::entity_resolution;
use cocoindex::ops::api::LlmPairResolver;
```
-The Rust module is `cocoindex::entity_resolution`, behind no Cargo feature; its types are in `cocoindex::prelude`. The built-in `LlmPairResolver` lives in `cocoindex::ops::api` (feature `embed_api`) and calls an OpenAI-compatible chat endpoint. The candidate search is an in-process cosine scan, so Rust needs no FAISS.
-
</Fragment>
</LangTabs>
+<RustNote>
+The candidate search is an in-process cosine scan over the entities' unit vectors, not a FAISS index, so there is nothing extra to install.
+</RustNote>
+
+<Lang only="rust">
+
+:::note[Cargo features]
+`cocoindex::entity_resolution` is behind no Cargo feature, and its types are in `cocoindex::prelude`. The built-in [`LlmPairResolver`](#llmpairresolver) is in `cocoindex::ops::api`, behind the `embed_api` feature; the local [`SentenceTransformerEmbedder`](./sentence_transformers) is behind the `fastembed` feature.
+:::
+
+</Lang>
+
+<Lang only="python">
+
:::note[Dependencies]
This module requires additional dependencies. Install with:
@@ -43,6 +68,8 @@ pip install cocoindex[entity_resolution]
:::
+</Lang>
+
## Basic usage
{/* Rust: examples/rust/conversation_to_knowledge/src/pipeline.rs (resolve_entities), src/clients.rs (context keys) */}
@@ -111,7 +138,7 @@ pub async fn resolve_entities(
}
```
-The Rust `resolve_entities(&ctx, entities, &embedder, &resolve_pair, is_existing_canonical, options)` takes every argument positionally: the entities (any iterable of strings), an `EntityEmbedder`, a `PairResolver`, an optional existing-canonical predicate, and a `ResolveOptions`. The `Ctx` is passed through to the embedder and the resolver, so both memoize and batch through the engine.
+`resolve_entities(&ctx, entities, &embedder, &resolve_pair, is_existing_canonical, options)` takes every argument positionally: the entities (any iterable of strings), an `EntityEmbedder`, a `PairResolver`, an optional existing-canonical predicate, and a `ResolveOptions`. The `Ctx` is passed through to the embedder and the resolver, so both memoize and batch through the engine.
</Fragment>
</LangTabs>
@@ -147,7 +174,7 @@ result.groups()?; // -> BTreeMap<String, BTreeSet<String>
result.to_map(); // -> BTreeMap<String, Option<String>>
```
-`canonical_of` and `groups` return a `Result`: an unknown name is an error, not an exception. `to_map` is the Rust name of `to_dict`.
+`canonical_of` and `groups` return a `Result`: an unknown name is an error. `to_map` returns the whole map: each name to its canonical, or `None` for a canonical name.
</Fragment>
</LangTabs>
@@ -160,6 +187,10 @@ If some entity names are already established as canonical (e.g., they have on-di
The resolver decides which side becomes canonical on every match. No special treatment for any name.
+{/* Rust: examples/rust/conversation_to_knowledge/src/pipeline.rs (resolve_entities) */}
+<LangTabs>
+<Fragment slot="python">
+
```python
result = await resolve_entities(
entities=raw_entities,
@@ -168,12 +199,42 @@ result = await resolve_entities(
)
```
+</Fragment>
+<Fragment slot="rust">
+
+```rust
+let result = entity_resolution::resolve_entities(
+ &ctx,
+ raw_entities,
+ &embedder,
+ &resolver,
+ None,
+ ResolveOptions::default(),
+)
+.await?;
+```
+
+</Fragment>
+</LangTabs>
+
### With `is_existing_canonical`
+<Lang only="python">
+
Pass a sync predicate that returns `True` for names you consider already-established canonicals. The `existing_policy` parameter controls how strongly that status is enforced:
#### `PINNED` (default)
+</Lang>
+
+<Lang only="rust">
+
+Pass a predicate that returns `true` for names you consider already-established canonicals. The `existing_policy` field of `ResolveOptions` controls how strongly that status is enforced:
+
+#### `Pinned` (default)
+
+</Lang>
+
Existing canonicals are immutable. They are seeded directly as canonicals without consulting the resolver. Two existings never merge. Non-existing entities are resolved in a second pass; if they match an existing canonical, the existing always wins.
{/* Rust: rust/sdk/cocoindex/tests/entity_resolution.rs (resolve helper) */}
@@ -209,8 +270,18 @@ let result = entity_resolution::resolve_entities(
</Fragment>
</LangTabs>
+<Lang only="python">
+
#### `PREFERRED`
+</Lang>
+
+<Lang only="rust">
+
+#### `Preferred`
+
+</Lang>
+
A softer policy: existing-canonical status breaks ties, but the resolver is always consulted. When exactly one side of a match is existing-canonical, that side wins regardless of the resolver's verdict. When both or neither are existing, the resolver decides.
{/* Rust: rust/sdk/cocoindex/tests/entity_resolution.rs (preferred_existing_can_repoint_non_existing_candidate) */}
@@ -253,8 +324,18 @@ let result = entity_resolution::resolve_entities(
## Events
+<Lang only="python">
+
Pass `on_resolution` to receive a `ResolutionEvent` for each entity. Events are delivered once resolution finishes, in the same order the sequential implementation would have emitted them (PREFERRED: sorted by entity; PINNED: pass-1 existings first then pass-2 non-existings):
+</Lang>
+
+<Lang only="rust">
+
+Call `resolve_entities_with_events` with an `on_resolution` callback to receive a `ResolutionEvent` for each entity. Events are delivered once resolution finishes, in the same order the sequential implementation would have emitted them (`Preferred`: sorted by entity; `Pinned`: pass-1 existings first then pass-2 non-existings):
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/tests/entity_resolution.rs (on_resolution_delivers_one_event_per_entity_in_order) */}
<LangTabs>
<Fragment slot="python">
@@ -291,7 +372,7 @@ let result = entity_resolution::resolve_entities_with_events(
.await?;
```
-In Rust the callback is the last argument of `resolve_entities_with_events`; `resolve_entities` is the same call without it.
+The callback is the last argument of `resolve_entities_with_events`; `resolve_entities` is the same call without it.
</Fragment>
</LangTabs>
@@ -301,10 +382,12 @@ Each event includes:
- `candidates` β€” what was passed to the resolver (empty if no resolver call)
- `decision` β€” the resolver's raw verdict (compare with `canonical` to detect policy overrides)
- `repointed` β€” if a prior canonical was demoted, its name
-- `seeded` β€” `True` for pinned existing-canonical entities seeded without resolver
+- `seeded` β€” <Lang only="python">`True`</Lang><Lang only="rust">`true`</Lang> for pinned existing-canonical entities seeded without resolver
## `resolve_entities` parameters
+<Lang only="python">
+
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `entities` | `Iterable[str]` | *(required)* | Raw entity names. Duplicates collapsed; iterated in sorted order. |
@@ -316,7 +399,11 @@ Each event includes:
| `max_distance` | `float` | `0.3` | Cosine distance threshold (similarity >= 0.7). |
| `top_n` | `int` | `5` | Max candidates surfaced per entity. |
-The Rust parameters, in order:
+</Lang>
+
+<Lang only="rust">
+
+The parameters, in order:
| Parameter | Type | Default |
|-----------|------|---------|
@@ -328,13 +415,29 @@ The Rust parameters, in order:
| `options` | `ResolveOptions { existing_policy, max_distance, top_n }` | `ResolveOptions::default()`: `Pinned`, `0.3`, `5` |
| `on_resolution` (`resolve_entities_with_events` only) | `Option<&(dyn Fn(&ResolutionEvent) + Sync)>` | `None` |
+`max_distance` is the cosine distance threshold (similarity >= 0.7 at the default `0.3`), and `top_n` is the maximum number of candidates surfaced per entity. `existing_policy` is ignored when `is_existing_canonical` is `None`.
+
+</Lang>
+
---
## `LlmPairResolver`
+<Lang only="python">
+
`cocoindex.ops.entity_resolution.llm_resolver` provides `LlmPairResolver`, a built-in resolver that uses an LLM (via [litellm](https://docs.litellm.ai/)) to decide pair matches. It sends each `(entity, candidates)` pair to the model and returns a structured decision β€” with automatic validation and retry when the model hallucinates a name not in the candidate list.
-The Rust `LlmPairResolver` (`cocoindex::ops::api`, feature `embed_api`) does not use litellm: it calls an OpenAI-compatible `/chat/completions` endpoint through `ApiChatClient`, and asks for a JSON object response. The prompt, the validation and the retry behavior mirror the Python implementation.
+</Lang>
+
+<Lang only="rust">
+
+`cocoindex::ops::api` provides `LlmPairResolver`, a built-in resolver that uses an LLM to decide pair matches. It sends each `(entity, candidates)` pair to the model and returns a structured decision β€” with automatic validation and retry when the model hallucinates a name not in the candidate list. It calls an OpenAI-compatible `/chat/completions` endpoint through [`ApiChatClient`](/docs/rust/ops/model_apis/#chat-and-structured-extraction), in JSON mode.
+
+</Lang>
+
+<RustNote>
+The resolver does not use litellm or `instructor`: it asks the endpoint for a JSON-object response and parses it. The prompt, the validation and the retry behavior are the same as in Python.
+</RustNote>
### Usage
@@ -386,6 +489,8 @@ let result = entity_resolution::resolve_entities(
</Fragment>
</LangTabs>
+<Lang only="python">
+
### Model strings
Uses the same litellm model-string format as [`LiteLLMEmbedder`](./litellm):
@@ -399,11 +504,19 @@ Uses the same litellm model-string format as [`LiteLLMEmbedder`](./litellm):
See the [LiteLLM docs](https://docs.litellm.ai/docs/providers) for the full list of 100+ supported providers.
-The Rust resolver takes the bare model name the endpoint expects (`gpt-4o-mini`), with `with_base_url` for a provider other than OpenAI.
+</Lang>
+
+<Lang only="rust">
+
+### Model names
+
+The resolver takes the bare model name the endpoint expects (`gpt-4o-mini`), with `with_base_url` for a provider other than OpenAI. See [Model APIs](/docs/rust/ops/model_apis/).
+
+</Lang>
### Entity type hints
-Pass `entity_type` to tailor the prompt for specific entity categories:
+Pass <Lang only="python">`entity_type`</Lang><Lang only="rust">`with_entity_type`</Lang> to tailor the prompt for specific entity categories:
{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (with_entity_type) */}
<LangTabs>
@@ -429,7 +542,7 @@ This adds context to the system prompt, helping the model make better judgments
### Extra guidance
-Append domain-specific rules to the default prompt via `extra_guidance`:
+Append domain-specific rules to the default prompt via <Lang only="python">`extra_guidance`</Lang><Lang only="rust">`with_extra_guidance`</Lang>:
{/* Rust: with_extra_guidance from rust/sdk/cocoindex/src/ops/api.rs (signature) */}
<LangTabs>
@@ -461,7 +574,7 @@ let resolver = LlmPairResolver::new("gpt-4o-mini")
</Fragment>
</LangTabs>
-`extra_guidance` is for **domain rules only** β€” do not include output-format instructions.
+<Lang only="python">`extra_guidance`</Lang><Lang only="rust">The guidance</Lang> is for **domain rules only** β€” do not include output-format instructions.
### Validation and retry
@@ -494,12 +607,22 @@ let resolver = LlmPairResolver::new("gpt-4o-mini").with_retries(1); // fewer ret
### Memoization
+<Lang only="python">
+
Each unique `(entity, candidates)` pair's decision is persisted across runs via [`@coco.fn(memo=True)`](../programming_guide/function). Changing the model or prompt invalidates the cache. No additional memoization wrapper is needed.
-The Rust resolver memoizes each decision the same way, through the `ctx` it receives. Its memo key holds the model, base URL, entity type and extra guidance; `retries` is absent, since it cannot change a valid decision.
+</Lang>
+
+<Lang only="rust">
+
+Each unique `(entity, candidates)` pair's decision is [memoized](../programming_guide/function) through the `ctx` the resolver receives, and persists across runs. The memo key holds the model, base URL, entity type and extra guidance, so changing the model or prompt invalidates the cache; `retries` is absent, since it cannot change a valid decision. No additional memoization wrapper is needed.
+
+</Lang>
### Parameters
+<Lang only="python">
+
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `model` | `str` | *(required)* | Litellm model string (e.g. `"openai/gpt-4o-mini"`). |
@@ -507,13 +630,27 @@ The Rust resolver memoizes each decision the same way, through the `ctx` it rece
| `extra_guidance` | `str \| None` | `None` | Domain rules appended to the default prompt. |
| `retries` | `int` | `2` | Max retries on invalid `matched` output. |
-The Rust builders: `LlmPairResolver::new(model)` or `with_client(ApiChatClient)`, then `with_base_url`, `with_api_key`, `with_entity_type`, `with_extra_guidance` and `with_retries` (default 2).
+</Lang>
+
+<Lang only="rust">
+
+| Builder | Default | Description |
+|---------|---------|-------------|
+| `LlmPairResolver::new(model)` | *(required)* | The model name the endpoint expects (e.g. `"gpt-4o-mini"`); builds its own `ApiChatClient`. |
+| `LlmPairResolver::with_client(client)` | | Builds on a pre-configured `ApiChatClient` instead of `new`. |
+| `with_base_url(url)` | OpenAI's | The endpoint's base URL. |
+| `with_api_key(key)` | `OPENAI_API_KEY` | The bearer API key. |
+| `with_entity_type(t)` | none | Entity type hint woven into the prompt. |
+| `with_extra_guidance(text)` | none | Domain rules appended to the default prompt. |
+| `with_retries(n)` | `2` | Max retries on invalid `matched` output. |
+
+</Lang>
---
## Custom resolvers
-For cases where the built-in `LlmPairResolver` doesn't fit (rule-based matching, different LLM framework, etc.), implement the `PairResolver` protocol:
+For cases where the built-in `LlmPairResolver` doesn't fit (rule-based matching, different LLM framework, etc.), implement the `PairResolver` <Lang only="python">protocol</Lang><Lang only="rust">trait</Lang>:
{/* Rust: rust/sdk/cocoindex/tests/entity_resolution.rs (ScriptedResolver), PairDecision constructors from rust/sdk/cocoindex/src/entity_resolution.rs */}
<LangTabs>
@@ -568,9 +705,15 @@ impl PairResolver for MyResolver {
}
```
-In Rust a resolver implements the `PairResolver` trait; the method also receives the `Ctx`, so a resolver can memoize through the engine as `LlmPairResolver` does. `resolve_pair` may run concurrently across components.
+`resolve_pair` also receives the `Ctx`, so a resolver can memoize through the engine as `LlmPairResolver` does. It may run concurrently across components.
</Fragment>
</LangTabs>
-Any async callable with the signature `(entity: str, candidates: list[str]) -> PairDecision` works β€” no subclassing required. `PairDecision.canonical` is advisory: the `existing_policy` may override it (see [Existing-canonical handling](#existing-canonical-handling)).
+<Lang only="python">
+
+Any async callable with the signature `(entity: str, candidates: list[str]) -> PairDecision` works β€” no subclassing required.
+
+</Lang>
+
+`PairDecision.canonical` is advisory: the `existing_policy` may override it (see [Existing-canonical handling](#existing-canonical-handling)).
diff --git a/docs/src/content/docs/ops/index.mdx b/docs/src/content/docs/ops/index.mdx
index 4c5e4948..e34c01f9 100644
--- a/docs/src/content/docs/ops/index.mdx
+++ b/docs/src/content/docs/ops/index.mdx
@@ -5,11 +5,22 @@ description: >
local and hosted embeddings, audio transcription, and entity resolution,
with links to each operation module's reference.
---
-import LangTabs from '../../../components/LangTabs.astro';
+
+<Lang only="python">
CocoIndex ships a set of built-in operations under the `cocoindex.ops` package.
Each module is independently importable and composes with the rest of a pipeline.
+</Lang>
+
+<Lang only="rust">
+
+CocoIndex ships a set of built-in operations under the `cocoindex::ops` module,
+plus `cocoindex::entity_resolution`. Each module is independently usable and
+composes with the rest of a pipeline.
+
+</Lang>
+
{/* Rust: module paths from rust/sdk/cocoindex/src/ops/mod.rs and src/lib.rs */}
<LangTabs>
<Fragment slot="python">
@@ -26,19 +37,34 @@ use cocoindex::entity_resolution;
use cocoindex::ops::{api, sentence_transformers, text};
```
-In the Rust SDK each `cocoindex::ops` module sits behind a Cargo feature of the `cocoindex` crate, so the heavy dependencies (tree-sitter grammars, the ONNX runtime, an HTTP client) are only built when used. `cocoindex::entity_resolution` needs no feature.
+Each `cocoindex::ops` module sits behind a Cargo feature of the `cocoindex` crate, so the heavy dependencies (tree-sitter grammars, the ONNX runtime, an HTTP client) are only built when used. `cocoindex::entity_resolution` needs no feature.
</Fragment>
</LangTabs>
## Operation modules
-| Module | What it provides | Rust |
+<Lang only="python">
+
+| Module | What it provides |
+|---|---|
+| [Text operations](./text) | Code language detection, regex-based `SeparatorSplitter`, and syntax-aware `RecursiveSplitter` (tree-sitter) returning position-tracked [`Chunk`](../common_resources/data_types#chunk)s. |
+| [Sentence Transformers](./sentence_transformers) | Local text embeddings via `sentence-transformers`, with model caching, thread-safe GPU access, and optional normalization. |
+| [LiteLLM](./litellm) | Embeddings and audio transcription through LiteLLM's unified API across 100+ providers (OpenAI, Azure, Vertex AI, Bedrock, Cohere, and more). |
+| [Entity resolution](./entity_resolution) | Deduplicate entity names via FAISS embedding similarity plus a pluggable LLM pair-resolver, with PINNED / PREFERRED canonical policies. |
+
+</Lang>
+
+<Lang only="rust">
+
+| Module | What it provides | Cargo feature |
|---|---|---|
-| [Text operations](/docs/ops/text/) | Code language detection, regex-based `SeparatorSplitter`, and syntax-aware `RecursiveSplitter` (tree-sitter) returning position-tracked [`Chunk`](/docs/common_resources/data_types/#chunk)s. | `cocoindex::ops::text`, feature `text` |
-| [Sentence Transformers](/docs/ops/sentence_transformers/) | Local text embeddings via `sentence-transformers`, with model caching, thread-safe GPU access, and optional normalization. | `cocoindex::ops::sentence_transformers`, feature `fastembed` (runs the ONNX models through `fastembed`) |
-| [LiteLLM](/docs/ops/litellm/) | Embeddings and audio transcription through LiteLLM's unified API across 100+ providers (OpenAI, Azure, Vertex AI, Bedrock, Cohere, and more). | `cocoindex::ops::api`, feature `embed_api`: `ApiEmbedder` and `ApiTranscriber` over an OpenAI-compatible HTTP API, not LiteLLM |
-| [Entity resolution](/docs/ops/entity_resolution/) | Deduplicate entity names via FAISS embedding similarity plus a pluggable LLM pair-resolver, with PINNED / PREFERRED canonical policies. | `cocoindex::entity_resolution`, no feature needed; `LlmPairResolver` in `cocoindex::ops::api` |
+| [Text operations](./text) | Code language detection, regex-based `SeparatorSplitter`, and syntax-aware `RecursiveSplitter` (tree-sitter) returning position-tracked [`Chunk`](../common_resources/data_types#chunk)s. `cocoindex::ops::text`. | `text` |
+| [Sentence Transformers](./sentence_transformers) | Local text embeddings from sentence-transformers ONNX models through `fastembed`, memoized and batched, on the GPU runner. `cocoindex::ops::sentence_transformers`. | `fastembed` |
+| [Model APIs](/docs/rust/ops/model_apis/) | Embeddings, audio transcription and JSON-mode chat (with typed `extract`) over any OpenAI-compatible HTTP API: `ApiEmbedder`, `ApiTranscriber`, `ApiChatClient`, `LlmPairResolver`. `cocoindex::ops::api`. | `embed_api` |
+| [Entity resolution](./entity_resolution) | Deduplicate entity names via embedding similarity plus a pluggable LLM pair-resolver, with `Pinned` / `Preferred` canonical policies. `cocoindex::entity_resolution`. | none; `LlmPairResolver` needs `embed_api` |
+
+</Lang>
## Most common: chunking code and text
@@ -88,7 +114,7 @@ let chunks = splitter.split_with(
It tries to keep each output chunk between `min_chunk_size` and `chunk_size`, splitting
at the highest-level boundary that fits and descending to finer boundaries when a piece
-is still too large. See [Text operations](/docs/ops/text/) for the full parameter reference,
+is still too large. See [Text operations](./text) for the full parameter reference,
supported languages, and custom-language configuration.
## Embeddings
@@ -96,7 +122,18 @@ supported languages, and custom-language configuration.
Two interchangeable embedding backends are available, both providing a
`VectorSchemaProvider` so vector columns are configured automatically by connectors:
-- [Sentence Transformers](/docs/ops/sentence_transformers/) runs locally, no API key.
-- [LiteLLM](/docs/ops/litellm/) reaches hosted providers behind one API.
+<Lang only="python">
+
+- [Sentence Transformers](./sentence_transformers) runs locally, no API key.
+- [LiteLLM](./litellm) reaches hosted providers behind one API.
+
+</Lang>
+
+<Lang only="rust">
+
+- [`SentenceTransformerEmbedder`](./sentence_transformers) runs locally through `fastembed`, no API key.
+- [`ApiEmbedder`](/docs/rust/ops/model_apis/#embeddings) reaches any OpenAI-compatible endpoint.
+
+Both also implement the [`Embedder`](../common_resources/data_types#embedder) trait, so either one plugs into [entity resolution](./entity_resolution).
-The Rust SDK has the same two: `SentenceTransformerEmbedder` (local, through `fastembed`) and `ApiEmbedder` (any OpenAI-compatible endpoint). Both implement `VectorSchemaProvider` and the [`Embedder`](/docs/common_resources/data_types/#embedder) trait.
+</Lang>
diff --git a/docs/src/content/docs/ops/litellm.mdx b/docs/src/content/docs/ops/litellm.mdx
index 27b1c952..ced2979a 100644
--- a/docs/src/content/docs/ops/litellm.mdx
+++ b/docs/src/content/docs/ops/litellm.mdx
@@ -4,31 +4,16 @@ description: >
Embed text and transcribe audio through LiteLLM's unified API across 100+
providers (OpenAI, Azure, Vertex AI, Bedrock, Cohere, and more) β€” with
VectorSchemaProvider for automatic vector column configuration.
+languages: [python]
+rust_counterpart: ops/model_apis
---
-import LangTabs from '../../../components/LangTabs.astro';
The `cocoindex.ops.litellm` module provides integration with the [LiteLLM](https://docs.litellm.ai/) library for text embeddings (`LiteLLMEmbedder`) and speech-to-text transcription (`LiteLLMTranscriber`).
-The Rust SDK does not use LiteLLM. Its counterpart is `cocoindex::ops::api` (feature `embed_api`): `ApiEmbedder` and `ApiTranscriber` call an OpenAI-compatible HTTP API directly, with `reqwest`. Point them at any compatible base URL (OpenAI, Together, vLLM, Ollama, ...) with `with_base_url`. The Rust tabs on this page show that API; the LiteLLM model strings and provider tables apply to Python only.
-
-{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs */}
-<LangTabs>
-<Fragment slot="python">
-
```python
from cocoindex.ops.litellm import LiteLLMEmbedder, LiteLLMTranscriber
```
-</Fragment>
-<Fragment slot="rust">
-
-```rust
-use cocoindex::ops::api::{ApiEmbedder, ApiTranscriber};
-```
-
-</Fragment>
-</LangTabs>
-
:::note[Dependencies]
This module requires additional dependencies. Install with:
@@ -48,18 +33,12 @@ The `LiteLLMEmbedder` class is a wrapper around LiteLLM's embedding API that:
- Passes through all additional arguments to the LiteLLM embedding API, except `timeout` and `max_inflight_requests`, which CocoIndex owns
- Returns properly typed numpy arrays
-The Rust `ApiEmbedder` calls `POST {base_url}/embeddings`. It implements `VectorSchemaProvider` (it probes one embedding to discover the dimension, once) and `Embedder`, and returns `Vec<f32>`. There is no pass-through of arbitrary provider arguments: the request carries the model, the input, and the optional `dimensions` and `input_type`.
-
## Basic usage
### Creating an embedder
All extra keyword arguments are passed through to every `litellm.aembedding` call (`api_key`, `api_base`, `dimensions`, …) β€” except `timeout` and `max_inflight_requests`, which are CocoIndex's own knobs (see [Timeout](#timeout) and [Limiting concurrent requests](#limiting-concurrent-requests)). See [Supported providers](#supported-providers) for provider-specific model strings and configuration.
-{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (ApiEmbedder builders) */}
-<LangTabs>
-<Fragment slot="python">
-
```python
from datetime import timedelta
@@ -80,47 +59,10 @@ embedder = LiteLLMEmbedder("text-embedding-3-small", max_inflight_requests=8)
embedder = LiteLLMEmbedder("openai/bge-m3", api_base="http://localhost:7997", timeout=timedelta(minutes=30))
```
-</Fragment>
-<Fragment slot="rust">
-
-```rust
-use std::time::Duration;
-
-use cocoindex::ops::api::ApiEmbedder;
-
-// Defaults to the OpenAI base URL and the OPENAI_API_KEY environment variable.
-let embedder = ApiEmbedder::new("text-embedding-3-small");
-
-// With explicit API key and base URL
-let embedder = ApiEmbedder::new("text-embedding-3-small")
- .with_base_url("https://my-proxy.example.com")
- .with_api_key("sk-...");
-
-// With custom dimensions (OpenAI text-embedding-3 models)
-let embedder = ApiEmbedder::new("text-embedding-3-small").with_dimensions(512);
-
-// With a cap on concurrent requests to the backend
-let embedder = ApiEmbedder::new("text-embedding-3-small").with_max_inflight_requests(8);
-
-// With a longer timeout, for a slow self-hosted endpoint
-let embedder = ApiEmbedder::new("bge-m3")
- .with_base_url("http://localhost:7997")
- .with_timeout(Duration::from_secs(30 * 60));
-```
-
-The model is the name the endpoint expects, with no provider prefix. The embedder is cheap to clone; clones share the in-flight cap and the probed dimension.
-
-</Fragment>
-</LangTabs>
-
### Embedding text
The `embed()` method converts text into a `numpy.ndarray` of `float32`. It's an async method β€” use `await` when calling it:
-{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (embed, embed_with_input_type, embed_batch) */}
-<LangTabs>
-<Fragment slot="python">
-
```python
# In a CocoIndex function
embedding = await embedder.embed("Hello, world!")
@@ -129,30 +71,10 @@ embedding = await embedder.embed("Hello, world!")
table.declare_row(row=DocEmbedding(text="Hello, world!", embedding=embedding))
```
-</Fragment>
-<Fragment slot="rust">
-
-```rust
-// In a CocoIndex function: memoized per text, batched across concurrent calls.
-let embedding = embedder.embed(&ctx, "Hello, world!").await?;
-
-// For asymmetric models, send an input type; each input type is memoized and batched apart.
-let query_vec = embedder.embed_with_input_type(&ctx, "q", "search_query").await?;
-let doc_vec = embedder.embed_with_input_type(&ctx, "doc", "search_document").await?;
-
-// Outside an update there is no Ctx: one raw request, no memoization.
-let vectors = embedder.embed_batch(vec!["Hello, world!".to_string()]).await?;
-```
-
-</Fragment>
-</LangTabs>
-
#### Text that looks like a media reference
litellm's Gemini embedding path reads a string that starts with `data:` and contains `;base64,`, or that starts with `gs://` or `files/`, as a file to embed rather than text β€” an inline file, a Cloud Storage object, or an uploaded file. Ordinary corpus text hits all three (a glTF file's buffer, an HTML page's inline image, a list of paths beginning `files/`), and the request would then fail before it is sent or silently embed an image. `LiteLLMEmbedder` sends such a text with one leading space, for every provider, so it embeds as text β€” litellm has no way to send such a string as text ([BerriAI/litellm#46719](https://github.com/BerriAI/litellm/issues/46719)). To embed media through Gemini, call `litellm.aembedding` directly.
-This is a litellm behavior. The Rust `ApiEmbedder` sends the text as given.
-
### Limiting concurrent requests
Concurrent `embed()` calls are batched: CocoIndex groups them into requests of
@@ -161,10 +83,6 @@ work queued. `max_inflight_requests` caps how many requests this embedder keeps
open against the backend at once β€” useful for a self-hosted endpoint (Infinity,
TEI, Ollama, vLLM, …) that rejects bursts with 429s:
-{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (with_max_inflight_requests) */}
-<LangTabs>
-<Fragment slot="python">
-
```python
embedder = LiteLLMEmbedder(
"openai/bge-m3",
@@ -173,32 +91,14 @@ embedder = LiteLLMEmbedder(
)
```
-</Fragment>
-<Fragment slot="rust">
-
-```rust
-let embedder = ApiEmbedder::new("bge-m3")
- .with_base_url("http://localhost:7997")
- .with_max_inflight_requests(8);
-```
-
-</Fragment>
-</LangTabs>
-
The default is `None` (no cap). The cap is per embedder instance: two
embedders pointed at the same endpoint have independent limits, so share one
instance when you want one limit.
-The Rust embedder batches the same way (up to 64 texts per request) and is uncapped by default. Its cap is shared by all clones of one embedder.
-
### Using as a type annotation
The `LiteLLMEmbedder` implements [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), which means it can be used directly as metadata in `Annotated` type annotations. This is the recommended way to declare vector columns β€” CocoIndex connectors automatically extract the vector dimension and dtype from the annotation when creating tables.
-{/* Rust: row struct from examples/rust/text_embedding/src/main.rs; with_vector_schema from rust/sdk/SHOWCASE.md, verified against rust/sdk/cocoindex/src/connectors/postgres.rs */}
-<LangTabs>
-<Fragment slot="python">
-
```python
from dataclasses import dataclass
from typing import Annotated
@@ -214,33 +114,8 @@ class DocEmbedding:
embedding: Annotated[NDArray, embedder]
```
-</Fragment>
-<Fragment slot="rust">
-
-```rust
-use cocoindex::prelude::*;
-
-#[derive(Clone, Serialize, Deserialize, SchemaFields)]
-struct DocEmbedding {
- id: i64,
- filename: String,
- text: String,
- #[coco(vector)]
- embedding: Vec<f32>,
-}
-```
-
-A Rust row struct cannot name the embedder in a field attribute. `#[coco(vector)]` marks the column; the embedder supplies the dimension when the table is mounted, below.
-
-</Fragment>
-</LangTabs>
-
When you pass this dataclass to a connector's `TableSchema.from_class()`, the connector automatically reads the embedder annotation to determine the vector column's dimension and dtype. For example, with Postgres:
-{/* Rust: examples/rust/text_embedding/src/main.rs (index), with an ApiEmbedder in the context key */}
-<LangTabs>
-<Fragment slot="python">
-
```python
from cocoindex.connectors import postgres
@@ -256,48 +131,16 @@ target_table = await postgres.mount_table_target(
)
```
-</Fragment>
-<Fragment slot="rust">
-
-```rust
-use cocoindex::connectors::postgres;
-
-cocoindex::context_key!(static EMBEDDER: ApiEmbedder, detect_change);
-
-// The embedder probes its dimension once and reports it for the `embedding` column.
-let table = postgres::mount_table_target(
- &ctx,
- &DB,
- "doc_embeddings",
- postgres::TableSchema::from_row::<DocEmbedding>(["id"])?
- .with_vector_schema("embedding", ctx.get_key(&EMBEDDER)?)
- .await?,
- Some("my_schema"),
-)
-.await?;
-```
-
-See [Vector schema annotations](../common_resources/vector_schema) for `with_vector_schema` and `with_vector_dim`.
-
-</Fragment>
-</LangTabs>
-
The connector automatically creates the appropriate `vector(N)` column. See the [Connectors](../connectors/postgres) docs for other supported backends (LanceDB, Qdrant, SQLite).
## Speech-to-text
The `LiteLLMTranscriber` class is a wrapper around LiteLLM's transcription API that turns audio into text through any LiteLLM-supported speech-to-text provider (OpenAI Whisper, ElevenLabs, Groq, and more) using a unified interface.
-The Rust `ApiTranscriber` calls `POST {base_url}/audio/transcriptions` with the audio as a multipart upload, read from any `FileLike`.
-
### Creating a transcriber
All extra keyword arguments are passed through to every `litellm.atranscription` call (`api_key`, `api_base`, `language`, `extra_body`, …) β€” except `timeout`, which is CocoIndex's own bound on the whole request (see [Timeout](#timeout)).
-{/* Rust: examples/rust/audio_to_text/src/main.rs, rust/sdk/cocoindex/tests/ops_api.rs (ApiTranscriber builders) */}
-<LangTabs>
-<Fragment slot="python">
-
```python
from datetime import timedelta
@@ -315,40 +158,10 @@ transcriber = LiteLLMTranscriber("whisper-1", language="en")
transcriber = LiteLLMTranscriber("whisper-1", timeout=timedelta(minutes=30))
```
-</Fragment>
-<Fragment slot="rust">
-
-```rust
-use std::time::Duration;
-
-use cocoindex::ops::api::ApiTranscriber;
-
-// Defaults to the OpenAI base URL and the OPENAI_API_KEY environment variable.
-let transcriber = ApiTranscriber::new("whisper-1");
-
-// With an explicit API key and a language hint applied to every call
-let transcriber = ApiTranscriber::new("whisper-1")
- .with_api_key("sk-...")
- .with_language("en");
-
-// With a longer timeout, for long audio or a slow endpoint
-let transcriber = ApiTranscriber::new("whisper-1").with_timeout(Duration::from_secs(30 * 60));
-
-// An OpenAI-compatible endpoint
-let transcriber = ApiTranscriber::new("whisper-1").with_base_url(base_url);
-```
-
-</Fragment>
-</LangTabs>
-
### Transcribing audio
The `transcribe()` method takes a `FileLike` object (such as a `localfs.File`) containing audio data and returns the transcribed text as a `str`. It's an async method β€” use `await` when calling it. Per-call keyword arguments override the defaults provided at construction time β€” except `timeout`, which is settable only on the constructor (see [Timeout](#timeout)):
-{/* Rust: examples/rust/audio_to_text/src/main.rs (process_audio) */}
-<LangTabs>
-<Fragment slot="python">
-
```python
# In a CocoIndex function, `file` is a FileLike (e.g. localfs.File)
transcript = await transcriber.transcribe(file)
@@ -357,23 +170,7 @@ transcript = await transcriber.transcribe(file)
transcript = await transcriber.transcribe(file, response_format="verbose_json")
```
-</Fragment>
-<Fragment slot="rust">
-
-```rust
-// In a CocoIndex function, `file` is a FileLike (here a FileEntry); memoized by the file's content.
-let text = ctx.get_key(&TRANSCRIBER)?.transcribe(ctx, &file).await?;
-
-// Raw bytes, outside an update: no memoization. The filename's extension tells the server the format.
-let text = transcriber.transcribe_bytes(bytes, "clip.mp3".to_string()).await?;
-```
-
-The Rust `transcribe` has no per-call options: the language hint is set once with `with_language`. `transcribe_bytes` is from the `ApiTranscriber` docs in `rust/sdk/cocoindex/src/ops/api.rs`.
-
-</Fragment>
-</LangTabs>
-
-A complete pipeline that walks local audio files, transcribes each one, and stores the transcripts in Postgres is available in the [`audio_to_text` example](https://github.com/cocoindex-io/cocoindex/tree/main/examples/audio_to_text). The Rust port is [`examples/rust/audio_to_text`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/rust/audio_to_text).
+A complete pipeline that walks local audio files, transcribes each one, and stores the transcripts in Postgres is available in the [`audio_to_text` example](https://github.com/cocoindex-io/cocoindex/tree/main/examples/audio_to_text).
### Supported transcription providers
@@ -387,38 +184,19 @@ A complete pipeline that walks local audio files, transcribes each one, and stor
See the [LiteLLM audio transcription docs](https://docs.litellm.ai/docs/audio_transcription) for the full list of providers and model strings.
-The Rust `ApiTranscriber` takes the model name the endpoint expects (`whisper-1` at OpenAI) and reaches other providers through `with_base_url`, when they offer an OpenAI-compatible transcription endpoint.
-
## Shared behavior
`LiteLLMEmbedder` and `LiteLLMTranscriber` reach their providers the same way: one retry loop, one clock, one memoization contract. Everything in this section applies to both.
-The Rust `ApiEmbedder` and `ApiTranscriber` follow the same contract: the same default timeout, the same retry rules, and the same memoization.
-
### Timeout
`timeout` bounds each request end to end; the default is 10 minutes. Transient failures (HTTP 429, 5xx, a dropped connection, and [others below](#retries)) are retried with backoff inside that window; a request that times out fails with `DeadlineExceededError` and is not retried. It takes a `timedelta`, or seconds as a number.
-{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (with_timeout) */}
-<LangTabs>
-<Fragment slot="python">
-
```python
embedder = LiteLLMEmbedder("text-embedding-3-small", timeout=timedelta(minutes=30))
transcriber = LiteLLMTranscriber("whisper-1", timeout=timedelta(minutes=30))
```
-</Fragment>
-<Fragment slot="rust">
-
-```rust
-let embedder = ApiEmbedder::new("text-embedding-3-small").with_timeout(Duration::from_secs(30 * 60));
-let transcriber = ApiTranscriber::new("whisper-1").with_timeout(Duration::from_secs(30 * 60));
-```
-
-</Fragment>
-</LangTabs>
-
`timeout` is CocoIndex's own clock and the only one on the request β€” litellm's per-request `timeout` is not forwarded. What to size it against is where the two differ:
- **Embedding** β€” one request carries up to 64 texts, so raise it for an endpoint that needs longer than the default to embed a full batch.
@@ -440,14 +218,10 @@ The 408 row and the timeout row look contradictory and aren't: an HTTP 408 *resp
A surrounding [`coco.timeout()`](../advanced_topics/timeouts) merges with this one by taking whichever is shorter, so it can only cut retries short β€” raising `timeout` is the only way to give a request longer.
-In Rust, an active `Ctx` deadline plays that role: it can only shorten the bound, never extend it.
-
### Memoization
`embed()` and `transcribe()` are both memoized (`memo=True`): inside a processing component, each distinct input's result is cached across that component's runs, so a caller that re-executes doesn't re-pay the API call for unchanged input. `timeout` and `max_inflight_requests` are deliberately absent from the memo key β€” they bound and pace requests but cannot change a result, so retuning them invalidates nothing.
-The Rust memo keys are the same: `ApiEmbedder` keys on the model, base URL and `dimensions`; `ApiTranscriber` on the model, base URL and language, plus the file's identity and content. The API key, timeout and in-flight cap are absent from both.
-
Mind the [memoization placement rule](../programming_guide/function#when-to-memoize); it lands differently on the two:
- **Embedding** β€” the memo holds one full vector per distinct text. That is what makes the common per-file-component pattern incremental, but it is redundant when your components are already keyed by the embedded content.
@@ -459,8 +233,6 @@ Callsite control over an op's memoization is tracked in [#2275](https://github.c
Below are common providers with their model strings and configuration. The `litellm` module is re-exported from `cocoindex.ops.litellm` for setting provider-specific variables. See the [LiteLLM embedding docs](https://docs.litellm.ai/docs/embedding/supported_embedding) for the full list.
-This section is Python only. The Rust `ApiEmbedder` has no provider router: it reaches a provider through its OpenAI-compatible `/embeddings` endpoint, with `with_base_url` and `with_api_key`, and the bare model name.
-
### Ollama
| Model | Model string |
diff --git a/docs/src/content/docs/ops/model_apis.mdx b/docs/src/content/docs/ops/model_apis.mdx
new file mode 100644
index 00000000..f4af5eae
--- /dev/null
+++ b/docs/src/content/docs/ops/model_apis.mdx
@@ -0,0 +1,338 @@
+---
+title: "*Model APIs*: embeddings, speech-to-text and chat"
+description: >
+ Embed text, transcribe audio and run JSON-mode chat completions over any
+ OpenAI-compatible HTTP API with ApiEmbedder, ApiTranscriber and
+ ApiChatClient, memoized and batched by the engine, plus the LlmPairResolver
+ for entity resolution.
+languages: [rust]
+python_counterpart: ops/litellm
+---
+
+The `cocoindex::ops::api` module calls hosted models over an OpenAI-compatible HTTP API:
+
+- `ApiEmbedder` embeds text (`POST {base_url}/embeddings`).
+- `ApiTranscriber` turns audio into text (`POST {base_url}/audio/transcriptions`).
+- `ApiChatClient` runs chat completions in JSON mode (`POST {base_url}/chat/completions`) and extracts typed values with `extract`.
+- `LlmPairResolver` asks an LLM whether two entity names are the same thing, for [entity resolution](./entity_resolution).
+
+Each client defaults to the OpenAI base URL (`https://api.openai.com/v1`) and reads the API key from the `OPENAI_API_KEY` environment variable. Point a client at any compatible endpoint (OpenAI, Together, vLLM, Ollama, ...) with `with_base_url`, and give the model name that endpoint expects, with no provider prefix.
+
+{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs */}
+```rust
+use cocoindex::ops::api::{ApiChatClient, ApiEmbedder, ApiTranscriber, ChatMessage, LlmPairResolver};
+```
+
+<RustNote>
+The Rust SDK does not use LiteLLM. It has no provider router: it sends requests to one OpenAI-compatible endpoint with `reqwest`, and there is no pass-through of arbitrary provider arguments. A provider without an OpenAI-compatible endpoint is out of reach of this module.
+</RustNote>
+
+:::note[Cargo feature]
+The module is behind the `embed_api` feature of the `cocoindex` crate:
+
+```toml
+cocoindex = { version = "...", features = ["embed_api"] }
+```
+
+:::
+
+## Embeddings
+
+`ApiEmbedder` implements [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider) and the [`Embedder`](../common_resources/data_types#embedder) trait, and returns each embedding as a `Vec<f32>`. The request carries the model, the input, and the optional `dimensions` and `input_type`.
+
+### Creating an embedder
+
+{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (ApiEmbedder builders) */}
+```rust
+use std::time::Duration;
+
+use cocoindex::ops::api::ApiEmbedder;
+
+// Defaults to the OpenAI base URL and the OPENAI_API_KEY environment variable.
+let embedder = ApiEmbedder::new("text-embedding-3-small");
+
+// With explicit API key and base URL
+let embedder = ApiEmbedder::new("text-embedding-3-small")
+ .with_base_url("https://my-proxy.example.com")
+ .with_api_key("sk-...");
+
+// With custom dimensions (OpenAI text-embedding-3 models)
+let embedder = ApiEmbedder::new("text-embedding-3-small").with_dimensions(512);
+
+// With a cap on concurrent requests to the backend
+let embedder = ApiEmbedder::new("text-embedding-3-small").with_max_inflight_requests(8);
+
+// With a longer timeout, for a slow self-hosted endpoint
+let embedder = ApiEmbedder::new("bge-m3")
+ .with_base_url("http://localhost:7997")
+ .with_timeout(Duration::from_secs(30 * 60));
+```
+
+The embedder is cheap to clone. Clones share the in-flight cap and the probed dimension.
+
+### Embedding text
+
+{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (embed, embed_with_input_type, embed_batch) */}
+```rust
+// In a CocoIndex function: memoized per text, batched across concurrent calls.
+let embedding = embedder.embed(&ctx, "Hello, world!").await?;
+
+// For asymmetric models, send an input type; each input type is memoized and batched apart.
+let query_vec = embedder.embed_with_input_type(&ctx, "q", "search_query").await?;
+let doc_vec = embedder.embed_with_input_type(&ctx, "doc", "search_document").await?;
+
+// Outside an update there is no Ctx: one raw request, no memoization.
+let vectors = embedder.embed_batch(vec!["Hello, world!".to_string()]).await?;
+```
+
+`embed` memoizes each text and coalesces the concurrent cache misses of an update into requests of up to 64 texts. Fan the calls out with `ctx.map` to let them batch:
+
+{/* Rust: rust/sdk/SHOWCASE.md (Embed, transcribe and resolve entities with the built-in ops) */}
+```rust
+cocoindex::context_key!(static EMBEDDER: ApiEmbedder, detect_change);
+
+#[cocoindex::function]
+async fn embed_chunks(ctx: &Ctx, chunks: Vec<String>) -> Result<Vec<Vec<f32>>> {
+ let embedder = ctx.get_key(&EMBEDDER)?;
+ ctx.map(chunks, {
+ let ctx = ctx.clone();
+ let embedder = embedder.clone();
+ move |chunk| {
+ let ctx = ctx.clone();
+ let embedder = embedder.clone();
+ async move { embedder.embed(&ctx, chunk).await }
+ }
+ })
+ .await
+}
+```
+
+`embed_batch` is for code outside a CocoIndex update, such as embedding a search query: it sends one request and memoizes nothing.
+
+### Limiting concurrent requests
+
+Concurrent `embed` calls are batched into requests of up to 64 texts, and the embedder sends as many such requests in parallel as there is work queued. `with_max_inflight_requests` caps how many requests the embedder keeps open against the backend at once. Use it for a self-hosted endpoint (Infinity, TEI, Ollama, vLLM, ...) that rejects bursts with 429s:
+
+{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (with_max_inflight_requests) */}
+```rust
+let embedder = ApiEmbedder::new("bge-m3")
+ .with_base_url("http://localhost:7997")
+ .with_max_inflight_requests(8);
+```
+
+The default is no cap. The cap belongs to one embedder and all its clones: two embedders built separately against the same endpoint have independent limits, so share one embedder (or its clones) when you want one limit.
+
+### Vector columns
+
+A row struct marks its vector column with `#[coco(vector)]`. It cannot name the embedder in a field attribute: the embedder supplies the dimension when the table is mounted.
+
+{/* Rust: row struct from examples/rust/text_embedding/src/main.rs */}
+```rust
+use cocoindex::prelude::*;
+
+#[derive(Clone, Serialize, Deserialize, SchemaFields)]
+struct DocEmbedding {
+ id: i64,
+ filename: String,
+ text: String,
+ #[coco(vector)]
+ embedding: Vec<f32>,
+}
+```
+
+{/* Rust: examples/rust/text_embedding/src/main.rs (index), with an ApiEmbedder in the context key */}
+```rust
+use cocoindex::connectors::postgres;
+
+cocoindex::context_key!(static EMBEDDER: ApiEmbedder, detect_change);
+
+// The embedder probes its dimension once and reports it for the `embedding` column.
+let table = postgres::mount_table_target(
+ &ctx,
+ &DB,
+ "doc_embeddings",
+ postgres::TableSchema::from_row::<DocEmbedding>(["id"])?
+ .with_vector_schema("embedding", ctx.get_key(&EMBEDDER)?)
+ .await?,
+ Some("my_schema"),
+)
+.await?;
+```
+
+The embedder finds its dimension by embedding a probe text (`"hello"`) once, and caches it; `dimension()` returns it. The connector then creates the `vector(N)` column. See [Vector schema](../common_resources/vector_schema) for `with_vector_schema` and `with_vector_dim`, and the [Connectors](../connectors/postgres) docs for other backends.
+
+## Speech-to-text
+
+`ApiTranscriber` sends the audio as a multipart upload, read from any `FileLike`, and returns the transcript as a `String`.
+
+### Creating a transcriber
+
+{/* Rust: examples/rust/audio_to_text/src/main.rs, rust/sdk/cocoindex/tests/ops_api.rs (ApiTranscriber builders) */}
+```rust
+use std::time::Duration;
+
+use cocoindex::ops::api::ApiTranscriber;
+
+// Defaults to the OpenAI base URL and the OPENAI_API_KEY environment variable.
+let transcriber = ApiTranscriber::new("whisper-1");
+
+// With an explicit API key and a language hint applied to every call
+let transcriber = ApiTranscriber::new("whisper-1")
+ .with_api_key("sk-...")
+ .with_language("en");
+
+// With a longer timeout, for long audio or a slow endpoint
+let transcriber = ApiTranscriber::new("whisper-1").with_timeout(Duration::from_secs(30 * 60));
+
+// An OpenAI-compatible endpoint
+let transcriber = ApiTranscriber::new("whisper-1").with_base_url(base_url);
+```
+
+The language hint is an ISO-639-1 code. Another provider is reachable through `with_base_url` when it offers an OpenAI-compatible transcription endpoint.
+
+### Transcribing audio
+
+{/* Rust: examples/rust/audio_to_text/src/main.rs (process_audio); transcribe_bytes from rust/sdk/cocoindex/src/ops/api.rs */}
+```rust
+// In a CocoIndex function, `file` is a FileLike (here a FileEntry); memoized by the file's content.
+let text = ctx.get_key(&TRANSCRIBER)?.transcribe(ctx, &file).await?;
+
+// Raw bytes, outside an update: no memoization. The filename's extension tells the server the format.
+let text = transcriber.transcribe_bytes(bytes, "clip.mp3".to_string()).await?;
+```
+
+`transcribe` has no per-call options: set the language hint once with `with_language`.
+
+A complete pipeline that walks local audio files, transcribes each one, and stores the transcripts in Postgres is in [`examples/rust/audio_to_text`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/rust/audio_to_text).
+
+## Chat and structured extraction
+
+`ApiChatClient` runs a chat completion with the JSON-object response format. Build the conversation from `ChatMessage::system`, `ChatMessage::user` and `ChatMessage::assistant`.
+
+{/* Rust: examples/rust/product_recommendation/src/main.rs (chat_client) */}
+```rust
+use cocoindex::ops::api::{ApiChatClient, ChatMessage};
+
+/// The chat client for the configured model: an OpenAI-compatible endpoint
+/// (`OPENAI_API_KEY`; `LLM_BASE_URL` for another provider, e.g. Ollama).
+fn chat_client(ctx: &Ctx) -> Result<ApiChatClient> {
+ let client = ApiChatClient::new(ctx.get_key(&LLM_MODEL)?);
+ Ok(match std::env::var("LLM_BASE_URL") {
+ Ok(url) => client.with_base_url(url),
+ Err(_) => client,
+ })
+}
+```
+
+The client has `new(model)`, `with_base_url` and `with_api_key`. Two methods send a request:
+
+- `extract::<T>(&ctx, &messages)` deserializes the answer into `T` and memoizes it through the engine, keyed by the model, the endpoint and the messages. This is the way to extract structured data with an LLM inside an update.
+- `chat_json(&messages)` returns the raw JSON string of the answer, with no memoization.
+
+{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (chat_client_extract_deserializes_and_memoizes) */}
+```rust
+#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
+struct Person {
+ name: String,
+ age: u32,
+}
+
+let messages = [
+ ChatMessage::system("Reply with JSON {name, age}."),
+ ChatMessage::user(text),
+];
+let person = client.extract::<Person>(&ctx, &messages).await?;
+```
+
+The endpoint's JSON mode guarantees JSON, not a shape: the prompt has to describe the JSON shape that `T` deserializes from. An answer that does not deserialize into `T` is an error.
+
+The client's memo key is the model and the endpoint (the base URL). So a `detect_change` context key that holds a client invalidates memoized work when the model or the endpoint changes:
+
+{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs */}
+```rust
+cocoindex::context_key!(static CHAT: ApiChatClient, detect_change);
+```
+
+Complete pipelines that extract with `ApiChatClient` are in [`examples/rust/product_recommendation`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/rust/product_recommendation) and [`examples/rust/docs_to_knowledge_graph`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/rust/docs_to_knowledge_graph).
+
+## Entity-pair resolution with an LLM
+
+`LlmPairResolver` implements the `PairResolver` trait of [entity resolution](./entity_resolution). Given a new entity name and a list of canonical candidates, it asks the LLM whether the new name refers to one of them, and which name stays canonical.
+
+{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (LlmPairResolver builders); with_client from examples/rust/conversation_to_knowledge/src/pipeline.rs */}
+```rust
+use cocoindex::ops::api::LlmPairResolver;
+
+// Builds its own ApiChatClient for the model.
+let resolver = LlmPairResolver::new("gpt-4o-mini")
+ .with_base_url(base_url)
+ .with_api_key("sk-...")
+ .with_entity_type("organization")
+ .with_retries(3);
+
+// Or reuse a configured chat client.
+let resolver = LlmPairResolver::with_client(ctx.get_key(&RESOLVER_LLM)?.clone())
+ .with_entity_type(kind.as_str());
+```
+
+| Builder | Effect |
+|---|---|
+| `with_entity_type(t)` | Weaves an entity-type hint into the prompt, for example `"person"`. |
+| `with_extra_guidance(text)` | Appends domain guidance to the prompt. Do not put output-format instructions in it. |
+| `with_retries(n)` | The number of retries when the LLM answers with a name that is not in the candidate list. Default 2. When the retries run out, the decision is "no match". |
+
+Each `(entity, candidates)` decision is memoized through the engine and persists across runs. The memo key is the model, the endpoint, the entity type and the extra guidance; the retry count is absent, because it cannot change a valid decision.
+
+Pass the resolver to `resolve_entities`; see [Entity resolution](./entity_resolution).
+
+## Shared behavior
+
+All four clients reach their endpoint the same way.
+
+### Timeout
+
+A request is bounded end to end, retries included. The default bound is 10 minutes. `ApiEmbedder` and `ApiTranscriber` take `with_timeout(Duration)`; `ApiChatClient` and `LlmPairResolver` use the default.
+
+{/* Rust: rust/sdk/cocoindex/tests/ops_api.rs (with_timeout) */}
+```rust
+let embedder = ApiEmbedder::new("text-embedding-3-small").with_timeout(Duration::from_secs(30 * 60));
+let transcriber = ApiTranscriber::new("whisper-1").with_timeout(Duration::from_secs(30 * 60));
+```
+
+Size the bound against one request:
+
+- **Embedding**: one request carries up to 64 texts, so raise it for an endpoint that needs longer than the default to embed a full batch.
+- **Transcription**: one request carries one whole audio file, so size it against the longest file you expect.
+
+An active [`Ctx` deadline](../advanced_topics/timeouts) can only shorten the bound, never extend it.
+
+### Retries
+
+Within the bound, a failed request is retried with exponential backoff: 1s, doubling, capped at 30s. A `Retry-After` header in seconds replaces the backoff delay, under the same 30s cap. There is no attempt cap; time is the only brake.
+
+| Failure | Retried? |
+| --- | --- |
+| HTTP 408, 409, 425, 429, or any 5xx | Yes |
+| A refused or reset connection | Yes |
+| A request that times out | No: terminal |
+| Any other HTTP error (bad credentials, unknown model, permission denied) | No: terminal |
+
+A request that times out is not retried, because it has already spent its duration. Against an overloaded backend, another try only adds load. The remedy for a genuine timeout is a longer timeout. When the bound expires, the call fails with an error.
+
+### Memoization
+
+`ApiEmbedder::embed`, `ApiTranscriber::transcribe`, `ApiChatClient::extract` and the `LlmPairResolver` decisions are memoized: inside a processing component, the result for each distinct input is cached across runs, so a component that re-runs does not pay the API call again for unchanged input. The memo keys:
+
+| Client | Memo key |
+|---|---|
+| `ApiEmbedder` | model, base URL, `dimensions`, and the text (and input type) |
+| `ApiTranscriber` | model, base URL, language, and the file's identity and content |
+| `ApiChatClient::extract` | model, base URL, and the messages |
+| `LlmPairResolver` | model, base URL, entity type, extra guidance, and the entity and candidates |
+
+The API key, the timeout and the in-flight cap are absent from every key: they authenticate, bound and pace requests but cannot change a result, so changing them invalidates nothing. `embed_batch`, `transcribe_bytes` and `chat_json` memoize nothing.
+
+Mind the [memoization placement rule](../programming_guide/function#when-to-memoize); it lands differently on embedding and transcription:
+
+- **Embedding**: the memo holds one full vector per distinct text. That makes the common per-file-component pattern incremental, but it is redundant when your components are already keyed by the embedded content.
+- **Transcription**: the memo holds one transcript per file: small entries standing in for an expensive call. It hits whenever the enclosing component re-runs for a reason other than the audio changing (its code edited, its version bumped, another of its inputs changed), so it is usually worth keeping.
diff --git a/docs/src/content/docs/ops/sentence_transformers.mdx b/docs/src/content/docs/ops/sentence_transformers.mdx
index 604de19d..24adb05b 100644
--- a/docs/src/content/docs/ops/sentence_transformers.mdx
+++ b/docs/src/content/docs/ops/sentence_transformers.mdx
@@ -4,11 +4,24 @@ description: >
Run sentence-transformers models locally for text embeddings with automatic
model caching, thread-safe GPU access, and optional normalization β€” plus
VectorSchemaProvider integration for connectors.
+rust_description: >
+ Run sentence-transformers ONNX models locally for text embeddings through
+ fastembed, memoized and batched by the engine, with GPU execution providers
+ and VectorSchemaProvider integration for connectors.
---
-import LangTabs from '../../../components/LangTabs.astro';
+
+<Lang only="python">
The `cocoindex.ops.sentence_transformers` module provides integration with the [sentence-transformers](https://www.sbert.net/) library for text embeddings.
+</Lang>
+
+<Lang only="rust">
+
+The `cocoindex::ops::sentence_transformers` module runs [sentence-transformers](https://www.sbert.net/) models locally for text embeddings. It runs their ONNX exports through [`fastembed`](https://github.com/Anush008/fastembed-rs), with no Python runtime.
+
+</Lang>
+
{/* Rust: examples/rust/text_embedding/src/main.rs */}
<LangTabs>
<Fragment slot="python">
@@ -23,12 +36,11 @@ from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder
```rust
use cocoindex::ops::sentence_transformers::SentenceTransformerEmbedder;
```
-
-The Rust module is `cocoindex::ops::sentence_transformers`, behind the `fastembed` feature of the `cocoindex` crate. It runs the same ONNX models locally through [`fastembed`](https://github.com/Anush008/fastembed-rs), with no Python runtime.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Dependencies]
This module requires additional dependencies. Install with:
@@ -38,8 +50,25 @@ pip install cocoindex[sentence_transformers]
:::
+</Lang>
+
+<Lang only="rust">
+
+:::note[Cargo feature]
+The module is behind the `fastembed` feature of the `cocoindex` crate:
+
+```toml
+cocoindex = { version = "...", features = ["fastembed"] }
+```
+
+:::
+
+</Lang>
+
## Overview
+<Lang only="python">
+
The `SentenceTransformerEmbedder` class is a wrapper around SentenceTransformer models that:
- Implements `VectorSchemaProvider` to supply vector schema information to CocoIndex connectors
@@ -47,7 +76,24 @@ The `SentenceTransformerEmbedder` class is a wrapper around SentenceTransformer
- Provides an `embed()` method
- Returns typed NumPy arrays
-The Rust `SentenceTransformerEmbedder` implements `VectorSchemaProvider` and `Embedder` too, and returns `Vec<f32>`. It runs the model on the ONNX Runtime execution providers compiled into the binary (CPU by default), on a blocking thread.
+</Lang>
+
+<Lang only="rust">
+
+The `SentenceTransformerEmbedder` struct wraps a locally loaded `fastembed` model. It:
+
+- Implements `VectorSchemaProvider` to supply vector schema information to CocoIndex connectors
+- Implements the [`Embedder`](../common_resources/data_types#embedder) trait, so it plugs into [entity resolution](./entity_resolution) directly
+- Provides an `embed(&ctx, text)` method, memoized and batched by the engine
+- Returns each embedding as a `Vec<f32>`
+
+It runs the model on the ONNX Runtime execution providers compiled into the binary (CPU by default), on a blocking thread.
+
+</Lang>
+
+<RustNote>
+The Rust embedder is built on `fastembed`, not on the `sentence-transformers` library, so its options differ. It has no `prompt_name` and no `normalize_embeddings`: `fastembed` has no prompt registry and always L2-normalizes its output. It has no `device` either: [`load_with`](#execution-providers) takes ONNX Runtime execution providers instead.
+</RustNote>
## Basic usage
@@ -81,7 +127,17 @@ let embedder = SentenceTransformerEmbedder::load("sentence-transformers/all-Mini
### Embedding text
-The `embed()` method converts text into a `numpy.ndarray` of `float32`. It supports both sync and async usage:
+<Lang only="python">
+
+The `embed()` method converts text into a `numpy.ndarray` of `float32`. It's an async method β€” use `await` when calling it:
+
+</Lang>
+
+<Lang only="rust">
+
+The `embed(&ctx, text)` method converts text into a `Vec<f32>`:
+
+</Lang>
{/* Rust: examples/rust/text_embedding/src/main.rs (process_file, query_once) */}
<LangTabs>
@@ -106,21 +162,43 @@ let embedding = embedder.embed(&ctx, "Hello, world!").await?;
let query_vec = embedder.embed_batch(vec![query.to_string()]).await?.remove(0);
```
-`embed(&ctx, text)` returns `Vec<f32>`. Outside an update there is no `Ctx`: use `embed_batch(texts)`, which embeds one batch directly.
+Outside an update there is no `Ctx`: use `embed_batch(texts)`, which embeds one batch directly.
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Built-in memoization]
`embed()` is memoized (`memo=True`): inside a processing component, each distinct text's vector is cached across that component's runs, so a caller that re-executes doesn't recompute unchanged text β€” the tradeoff is model compute vs. cache storage (one full vector per distinct text). This composes well with the per-file component in the example below; mind the [memoization placement rule](../programming_guide/function#when-to-memoize) if your components are instead keyed by the embedded content. Callsite control over an op's memoization is tracked in [#2275](https://github.com/cocoindex-io/cocoindex/issues/2275).
:::
-The Rust `embed(&ctx, text)` is memoized the same way, and it batches: concurrent cache misses in one update are coalesced into batches of up to 64 texts. The memo key holds the model name and dimension, so a different model invalidates the cached vectors.
+</Lang>
+
+<Lang only="rust">
+
+:::note[Built-in memoization]
+`embed(&ctx, text)` is memoized: inside a processing component, each distinct text's vector is cached across that component's runs, so a caller that re-executes doesn't recompute unchanged text. The tradeoff is model compute vs. cache storage (one full vector per distinct text). It also batches: concurrent cache misses in one update are coalesced into batches of up to 64 texts. The memo key holds the model name and dimension, so a different model invalidates the cached vectors. Mind the [memoization placement rule](../programming_guide/function#when-to-memoize) if your components are keyed by the embedded content.
+:::
+
+</Lang>
+
+<Lang only="python">
### Using as a type annotation
The `SentenceTransformerEmbedder` implements [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), which means it can be used directly as metadata in `Annotated` type annotations. This is the recommended way to declare vector columns β€” CocoIndex connectors automatically extract the vector dimension and dtype from the annotation when creating tables.
+</Lang>
+
+<Lang only="rust">
+
+### Declaring the vector column
+
+The `SentenceTransformerEmbedder` implements [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), so a connector reads the vector dimension and element type from it when it creates a table. The row struct marks the column with `#[coco(vector)]`:
+
+</Lang>
+
{/* Rust: examples/rust/text_embedding/src/main.rs (DocEmbedding, index) */}
<LangTabs>
<Fragment slot="python">
@@ -160,13 +238,23 @@ struct DocEmbedding {
}
```
-A Rust row struct cannot name the embedder in a field attribute. `#[coco(vector)]` marks the column; the embedder supplies the dimension when the table is mounted, below.
+A row struct cannot name the embedder in a field attribute: the embedder supplies the dimension when the table is mounted, below.
</Fragment>
</LangTabs>
+<Lang only="python">
+
When you pass this dataclass to a connector's `TableSchema.from_class()`, the connector automatically reads the embedder annotation to determine the vector column's dimension and dtype. For example, with Postgres:
+</Lang>
+
+<Lang only="rust">
+
+When you mount the table, pass the embedder to `with_vector_schema`, and the connector takes the vector column's dimension and element type from it. For example, with Postgres:
+
+</Lang>
+
{/* Rust: examples/rust/text_embedding/src/main.rs (index) */}
<LangTabs>
<Fragment slot="python">
@@ -205,7 +293,7 @@ let table = postgres::mount_table_target(
.await?;
```
-`TableSchema::from_row::<Row>(primary_key)` is the Rust `from_class`; `with_vector_schema(field, &embedder)` resolves the `#[coco(vector)]` column from any `VectorSchemaProvider`. See [Vector schema annotations](../common_resources/vector_schema).
+`TableSchema::from_row::<Row>(primary_key)` builds the schema from the row struct; `with_vector_schema(field, &embedder)` resolves the `#[coco(vector)]` column from any `VectorSchemaProvider`. See [Vector schema annotations](../common_resources/vector_schema).
</Fragment>
</LangTabs>
@@ -214,7 +302,7 @@ The connector automatically creates the appropriate `vector(384)` column. See th
## Example: text embedding pipeline
-Here's a complete example of a text embedding pipeline (based on the [text_embedding example](https://github.com/cocoindex-io/cocoindex/tree/main/examples/text_embedding)):
+Here's a complete example of a text embedding pipeline (based on the <Lang only="python">[text_embedding example](https://github.com/cocoindex-io/cocoindex/tree/main/examples/text_embedding)</Lang><Lang only="rust">[text_embedding example](https://github.com/cocoindex-io/cocoindex/tree/main/examples/rust/text_embedding)</Lang>):
{/* Rust: examples/rust/text_embedding/src/main.rs (trimmed: the query command and the main body are left out) */}
<LangTabs>
@@ -439,7 +527,7 @@ async fn index(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
}
```
-The full program, with the `database_url()` and `source_dir()` helpers, a `query` command and the `#[cocoindex::main]` entry point, is `examples/rust/text_embedding`. Run it with the [CLI for Rust projects](../cli_rust): `cocoindex update`, or `cocoindex update -L` to keep watching the directory.
+The full program, with the `database_url()` and `source_dir()` helpers, a `query` command and the `#[cocoindex::main]` entry point, is `examples/rust/text_embedding`. Run it with the [CLI](/docs/rust/cli/): `cocoindex update`, or `cocoindex update -L` to keep watching the directory.
</Fragment>
</LangTabs>
@@ -448,6 +536,8 @@ The full program, with the `database_url()` and `source_dir()` helpers, a `query
### Model selection
+<Lang only="python">
+
You can use any model from the [sentence-transformers library](https://www.sbert.net/docs/sentence_transformer/pretrained_models.html):
```python
@@ -464,24 +554,59 @@ embedder = SentenceTransformerEmbedder("sentence-transformers/paraphrase-multili
embedder = SentenceTransformerEmbedder("/path/to/local/model")
```
-The Rust `SentenceTransformerEmbedder::load(name_or_path)` accepts a name from the `fastembed` model registry (matched case-insensitively, and by the trailing model name, so `sentence-transformers/all-MiniLM-L6-v2` and `Xenova/all-MiniLM-L6-v2` resolve to the same model), a local directory holding a sentence-transformers ONNX export (`onnx/model.onnx` or `model.onnx` plus the tokenizer files), or the Hugging Face Hub repository of such an export. `HF_HOME` and `HF_ENDPOINT` apply to the download. A model with a pooling mode other than CLS or mean is rejected.
+</Lang>
+
+<Lang only="rust">
+
+`SentenceTransformerEmbedder::load(name_or_path)` accepts a name from the `fastembed` model registry (matched case-insensitively, and by the trailing model name, so `sentence-transformers/all-MiniLM-L6-v2` and `Xenova/all-MiniLM-L6-v2` resolve to the same model), a local directory holding a sentence-transformers ONNX export (`onnx/model.onnx` or `model.onnx` plus the tokenizer files), or the Hugging Face Hub repository of such an export. `HF_HOME` and `HF_ENDPOINT` apply to the download. A model with a pooling mode other than CLS or mean is rejected. Pooling follows the export's `1_Pooling/config.json` when it has one.
+
+{/* Rust: examples/rust/text_embedding/src/main.rs (load_embedder) */}
+```rust
+let embedder = SentenceTransformerEmbedder::load("sentence-transformers/all-MiniLM-L6-v2").await?;
+```
+
+</Lang>
+
+<Lang only="python">
### Normalization
-By default, embeddings are normalized to unit length (suitable for cosine similarity):
+By default, embeddings are normalized to unit length (suitable for cosine similarity). Pass `normalize_embeddings=False` to `embed()` to disable it:
```python
# Default: normalized embeddings
-embedder = SentenceTransformerEmbedder(
- "sentence-transformers/all-MiniLM-L6-v2",
- normalize_embeddings=True # Default
-)
+embedding = await embedder.embed("Hello, world!")
# Disable normalization if needed
-embedder = SentenceTransformerEmbedder(
+embedding = await embedder.embed("Hello, world!", normalize_embeddings=False)
+```
+
+Concurrent `embed()` calls are batched only with calls that pass the same `normalize_embeddings` (and `prompt_name`).
+
+</Lang>
+
+<Lang only="rust">
+
+### Normalization and prompts
+
+`fastembed` always L2-normalizes its output, so every embedding has unit length (suitable for cosine similarity). It has no prompt registry: for a model that expects a query or document prefix, prepend the prefix to the text yourself.
+
+### Execution providers
+
+`SentenceTransformerEmbedder::load_with(name_or_path, execution_providers)` runs the model on the first of `execution_providers` that ONNX Runtime can start. A provider is registered when its `ort` feature is compiled into the binary, such as `cuda` for `CUDAExecutionProvider`; otherwise ONNX Runtime falls back to the CPU. `load(name_or_path)` is `load_with` with no providers.
+
+{/* Rust: rust/sdk/cocoindex/src/ops/sentence_transformers.rs (load_with doc comment); needs the `ort` crate with its `cuda` feature */}
+```rust
+use cocoindex::ops::sentence_transformers::SentenceTransformerEmbedder;
+use ort::execution_providers::CUDAExecutionProvider;
+
+let embedder = SentenceTransformerEmbedder::load_with(
"sentence-transformers/all-MiniLM-L6-v2",
- normalize_embeddings=False
+ vec![CUDAExecutionProvider::default().build()],
)
+.await?;
```
-The Rust embedder always normalizes: `fastembed` L2-normalizes its output, so `normalize_embeddings` has no Rust counterpart. Python's `prompt_name` has none either: `fastembed` has no prompt registry, so prepend the model's query or document prefix to the text yourself. Python's `device` is `SentenceTransformerEmbedder::load_with(name_or_path, execution_providers)`: the ONNX Runtime execution providers to try, such as `CUDAExecutionProvider::default().build()` from the `ort` crate, which the binary must enable through `ort`'s `cuda` feature; without any, the model runs on the CPU. As in Python (`runner=coco.GPU`), each batch runs under the GPU runner, so one inference runs at a time per GPU in the pool.
+Each batch runs under the GPU runner, so one inference runs at a time per GPU in the pool.
+
+</Lang>
diff --git a/docs/src/content/docs/ops/text.mdx b/docs/src/content/docs/ops/text.mdx
index d1822b99..adb9613e 100644
--- a/docs/src/content/docs/ops/text.mdx
+++ b/docs/src/content/docs/ops/text.mdx
@@ -5,9 +5,8 @@ description: >
and syntax-aware RecursiveSplitter that returns position-tracked Chunks with
optional custom domain-specific splitting rules.
---
-import LangTabs from '../../../components/LangTabs.astro';
-The `cocoindex.ops.text` module provides operations for text processing.
+The <Lang only="python">`cocoindex.ops.text`</Lang><Lang only="rust">`cocoindex::ops::text`</Lang> module provides operations for text processing.
{/* Rust: rust/sdk/cocoindex/tests/ops_text.rs */}
<LangTabs>
@@ -24,11 +23,22 @@ from cocoindex.ops.text import RecursiveSplitter, SeparatorSplitter
use cocoindex::ops::text::{RecursiveChunkConfig, RecursiveSplitter, SeparatorSplitter};
```
-The Rust module is `cocoindex::ops::text`, behind the `text` feature of the `cocoindex` crate. It wraps the same splitting engine the Python module uses, so the languages and the chunk boundaries are the same.
-
</Fragment>
</LangTabs>
+<Lang only="rust">
+
+:::note[Cargo feature]
+The module is behind the `text` feature of the `cocoindex` crate:
+
+```toml
+cocoindex = { version = "...", features = ["text"] }
+```
+
+:::
+
+</Lang>
+
Features include:
- Code language detection
@@ -71,7 +81,7 @@ assert_eq!(detect_code_language("app.rs").as_deref(), Some("rust"));
assert_eq!(detect_code_language("file.xyz"), None);
```
-The Rust function returns `Option<String>`.
+It returns `Option<String>`: `None` when the extension is not recognized.
</Fragment>
</LangTabs>
@@ -112,7 +122,7 @@ for chunk in &chunks {
println!("{}", chunk.text(text));
}
-// Keep the separator on the left of the split, as `keep_separator="left"`.
+// Keep the separator on the left of the split.
let splitter = SeparatorSplitter::with_config(SeparatorSplitConfig {
separators_regex: vec![r"\.".to_string()],
keep_separator: Some(KeepSeparator::Left),
@@ -120,7 +130,7 @@ let splitter = SeparatorSplitter::with_config(SeparatorSplitConfig {
})?;
```
-`SeparatorSplitter::new(separators)` takes the regex list; the other options (`keep_separator`, `trim`) go through `SeparatorSplitConfig` and `with_config`. A Rust `Chunk` does not hold its text: call `chunk.text(text)` with the string you split.
+`SeparatorSplitter::new(separators)` takes the regex list; the other options (`keep_separator`, `trim`) go through `SeparatorSplitConfig` and `with_config`. A `Chunk` does not hold its text: call `chunk.text(text)` with the string you split.
</Fragment>
</LangTabs>
@@ -248,7 +258,7 @@ let chunks = splitter.split_with(
When the same code is passed to several parse-consuming APIs (e.g. splitting *and*
structural pattern matching), wrap it in a `CodeSource` so it is parsed at most once.
-The `CodeSource` carries its own language, so the `language=` argument must be omitted:
+The `CodeSource` carries its own language, so <Lang only="python">the `language=` argument must be omitted</Lang><Lang only="rust">`config.language` is ignored</Lang>:
{/* Rust: CodeSource::with_language and RecursiveSplitter::split_source from rust/sdk/cocoindex/src/ops/text.rs (signatures); CodePattern::compile from rust/sdk/cocoindex/tests/code.rs */}
<LangTabs>
@@ -287,11 +297,11 @@ let chunks = splitter.split_source(
**Supported languages:**
-`language=` accepts a language name, an alternate name, or a file extension β€” `"python"`, `"py"` and `".py"` all select Python. Matching is case-insensitive. Use [`detect_code_language()`](#detect_code_language) to infer the value from a filename.
+<Lang only="python">`language=`</Lang><Lang only="rust">`language`</Lang> accepts a language name, an alternate name, or a file extension β€” `"python"`, `"py"` and `".py"` all select Python. Matching is case-insensitive. Use [`detect_code_language()`](#detect_code_language) to infer the value from a filename.
Languages with syntax-aware (tree-sitter) splitting β€” splits at logical boundaries like functions, classes, and blocks:
-| Language | `language=` value | Extensions |
+| Language | `language` value | Extensions |
|---|---|---|
| Astro | `"astro"` | `.astro` |
| Bash | `"bash"` | `.sh`, `.bash` |
@@ -333,9 +343,9 @@ Languages with syntax-aware (tree-sitter) splitting β€” splits at logical bounda
| XML | `"xml"` | `.xml` |
| YAML | `"yaml"` | `.yaml`, `.yml` |
-Note that `.h` maps to C++, not C β€” the C++ grammar also parses C headers. Pass `language="c"` explicitly to force the C grammar.
+Note that `.h` maps to C++, not C β€” the C++ grammar also parses C headers. Pass <Lang only="python">`language="c"`</Lang><Lang only="rust">`language: Some("c".to_string())`</Lang> explicitly to force the C grammar.
-110 additional languages use separator-based splitting (e.g. `"elixir"`, `"erlang"`, `"haskell"`, `"nix"`, `"perl"`, `"powershell"`, `"proto"`, `"zig"`, and more). A `language=` value that matches no known language also falls back to separator-based splitting rather than raising.
+110 additional languages use separator-based splitting (e.g. `"elixir"`, `"erlang"`, `"haskell"`, `"nix"`, `"perl"`, `"powershell"`, `"proto"`, `"zig"`, and more). A <Lang only="python">`language=`</Lang><Lang only="rust">`language`</Lang> value that matches no known language also falls back to separator-based splitting rather than <Lang only="python">raising</Lang><Lang only="rust">failing</Lang>.
### `CustomLanguageConfig`
@@ -403,6 +413,8 @@ let chunks = splitter.split_with(
## API reference
+<Lang only="python">
+
For detailed API documentation, refer to the module docstrings:
```python
@@ -414,4 +426,10 @@ help(text.detect_code_language)
help(text.CustomLanguageConfig)
```
-For Rust, build the crate documentation with `cargo doc --features text --open` and open the `cocoindex::ops::text` module.
+</Lang>
+
+<Lang only="rust">
+
+For detailed API documentation, build the crate documentation with `cargo doc --features text --open` and open the `cocoindex::ops::text` module.
+
+</Lang>
diff --git a/docs/src/data/section-grids.ts b/docs/src/data/section-grids.ts
index 9a9cbcd4..b646d9ee 100644
--- a/docs/src/data/section-grids.ts
+++ b/docs/src/data/section-grids.ts
@@ -160,7 +160,7 @@ export const commonResourcesGroups: SectionGridGroup[] = [
href: '/docs/common_resources/data_types/',
title: 'Data types',
glyph: 'types',
- body: 'Shared models across connectors and ops: FileLike, FilePath, FilePathMatcher, Chunk, and the Embedder protocol.',
+ body: 'Shared models across connectors and ops: FileLike, FilePath, FilePathMatcher, Chunk, and the Embedder interface.',
},
{
href: '/docs/common_resources/vector_schema/',