Przejdź do treści
Biblioteka skilli
Dane i analityka · Budowanie i kod

oms-cocoindex

/oms-cocoindex

Buduje potoki przyjmowania i przekształcania danych na cocoindex v1.0.0, czyli przyrostowe indeksowanie dla ETL, RAG i wyszukiwania wektorowego.

Repozytorium
oh-my-skills ↗
Licencja
Apache-2.0
Ostatnia zmiana repozytorium
10.11.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
10
Skrypty
0
Komentarze HTML
9
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 10.11.2026, bez odwołań do wycofanych modeli i API.

Licencja

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

Co sprawdzić przed instalacją
  • SKILL.md zawiera komentarze HTML (9). Nie widać ich w podglądzie Markdown, a model je czyta.

Co robi i kiedy

Buduje potoki przyjmowania i przekształcania danych na cocoindex v1.0.0, czyli przyrostowe indeksowanie dla ETL, RAG i wyszukiwania wektorowego.

Oryginalny opis (EN)

Build data ingestion + transformation pipelines on top of cocoindex v1.0.0 — a Python framework with a Rust engine for ultra-performant, incremental indexing (ETL, RAG, knowledge graphs, vector search). Use when authoring cocoindex v1.0.0 components — App / Environment / @lifespan / @fn / mount + TargetState reconciliation + connectors + ops. **This is a complete paradigm change from v0.3.37**; the old FlowBuilder/DataScope/DataSlice/flow_def API was wholly removed in v1.0.0 — do NOT mix vocabularies.

Jak działa

  1. Quick Start
  2. Common Workflows
  3. Key API Summary
  4. Key Types
  5. Architecture at a Glance
  6. CLI
  7. Migration from v0.3.37
  8. Gotchas
Sekcje z nagłówków SKILL.md, w oryginale · 350 linii, 3 810 słów
Podgląd SKILL.md
---
name: oms-cocoindex
description: Build data ingestion + transformation pipelines on top of cocoindex v1.0.0 — a Python framework with a Rust engine for ultra-performant, incremental indexing (ETL, RAG, knowledge graphs, vector search). Use when authoring cocoindex v1.0.0 components — App / Environment / @lifespan / @fn / mount + TargetState reconciliation + connectors + ops. **This is a complete paradigm change from v0.3.37**; the old FlowBuilder/DataScope/DataSlice/flow_def API was wholly removed in v1.0.0 — do NOT mix vocabularies.
---

# Cocoindex v1.0.0 — Component-based Pipelines

Cocoindex authors data pipelines as Python *components* mounted into an *Environment* and orchestrated by an *App*. State is reconciled into target connectors via a `TargetState` / `TargetHandler` declarative API. Functions are decorated with `@coco.fn` (optionally memoized), or with `@coco.fn.as_async` when they need batching or a runner such as the GPU. Lifespan-scoped resources (DB pools, embedders) are provided via `@coco.lifespan` and retrieved with `coco.use_context(KEY)`. Persistent state lives in a local LMDB store at `Settings.db_path`.

**v0.3.37 → v1.0.0 paradigm shift:** the old API (`FlowBuilder`, `DataScope`, `DataSlice`, `flow_def`, `open_flow`, `transform_flow`, `cocoindex.sources.*`, `cocoindex.targets.*`, `cocoindex.functions.*`, `LlmSpec`, `LlmApiType`, `VectorSimilarityMetric`, `DatabaseConnectionSpec`, `Postgres`-backed state) is **entirely removed**. There is no `flow.py`, no `op.py`, no `index.py`, no `llm.py`, no `lib.py`, no `auth_registry.py`. Migration is a full rewrite, not a rename pass — see the [migration section](#migration-from-v0337) for the new vocabulary.

## Quick Start

```python
# pip install cocoindex
import asyncio, pathlib
from typing import AsyncIterator, Annotated
from dataclasses import dataclass

import asyncpg
import cocoindex as coco
from cocoindex.connectors import localfs, postgres
from cocoindex.ops.text import RecursiveSplitter
from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder
from cocoindex.resources.chunk import Chunk
from cocoindex.resources.file import FileLike, PatternFilePathMatcher
from cocoindex.resources.id import IdGenerator
from numpy.typing import NDArray

# Lifespan-scoped resources (created once per environment, reused across components)
PG_DB    = coco.ContextKey[asyncpg.Pool]("pg_db")
EMBEDDER = coco.ContextKey[SentenceTransformerEmbedder]("embedder", detect_change=True)

@coco.lifespan
async def env_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
    async with await asyncpg.create_pool("postgres://localhost/mydb") as pool:
        builder.provide(PG_DB, pool)
        builder.provide(EMBEDDER, SentenceTransformerEmbedder("sentence-transformers/all-MiniLM-L6-v2"))
        yield

@dataclass
class DocEmbedding:
    id: int; filename: str; chunk_start: int; chunk_end: int
    text: str
    embedding: Annotated[NDArray, EMBEDDER]   # vector schema resolved from the ContextKey

# Per-chunk component (memoization implicit via memo=True on the parent)
@coco.fn
async def process_chunk(chunk: Chunk, filename: pathlib.PurePath, id_gen: IdGenerator,
                        table: postgres.TableTarget[DocEmbedding]) -> None:
    table.declare_row(row=DocEmbedding(
        id=await id_gen.next_id(chunk.text),
        filename=str(filename),
        chunk_start=chunk.start.char_offset,
        chunk_end=chunk.end.char_offset,
        text=chunk.text,
        embedding=await coco.use_context(EMBEDDER).embed(chunk.text),
    ))

@coco.fn(memo=True)
async def process_file(file: FileLike, table: postgres.TableTarget[DocEmbedding]) -> None:
    text = await file.read_text()
    chunks = RecursiveSplitter().split(text, chunk_size=2000, chunk_overlap=500, language="markdown")
    id_gen = IdGenerator()
    await coco.map(process_chunk, chunks, file.file_path.path, id_gen, table)

@coco.fn
async def app_main(sourcedir: pathlib.Path) -> None:
    target = await postgres.mount_table_target(
        PG_DB,
        table_name="doc_embeddings",
        table_schema=await postgres.TableSchema.from_class(DocEmbedding, primary_key=["id"]),
    )
    target.declare_vector_index(column="embedding")
    files = localfs.walk_dir(sourcedir, live=True, recursive=True,
                             path_matcher=PatternFilePathMatcher(included_patterns=["**/*.md"]))
    await coco.mount_each(process_file, files.items(), target)

app = coco.App(coco.AppConfig(name="MyApp"), app_main, sourcedir=pathlib.Path("./docs"))
```

Run with: `cocoindex update main.py` (one-shot) or `cocoindex update main.py -L` (live: `walk_dir(..., live=True)` makes `files.items()` a `LiveMapView`, which is what lets `-L` watch the files for changes; without it each file is mounted once). Set `COCOINDEX_DB=/path/to/state.lmdb` for the local state store. Source: [SRC:python/cocoindex/__init__.py:L13] · [SRC:examples/text_embedding/main.py:L1] · `live=True` [SRC:examples/files_transform/main.py:L23]

<!-- [MANUAL:quick-start-notes] -->
<!-- Add custom notes here. This section is preserved during skill updates. -->
<!-- [/MANUAL:quick-start-notes] -->

## Common Workflows

**Define and mount a top-level `App`:**
`coco.App(coco.AppConfig(name="..."), app_main, *args, **kwargs)` — `app_main` is a `@coco.fn`-decorated function. Run via `app.update()` (returns `UpdateHandle`) or `app.update_blocking()`. [AST:python/cocoindex/_internal/app.py:L208]

**Lifespan-scoped resources:**
`@coco.lifespan` decorates a function `(EnvironmentBuilder) -> Iterator[None] | AsyncIterator[None]`. Use `builder.provide(KEY, value)` (or `builder.provide_with(KEY, cm)`, or `await builder.provide_async_with(KEY, cm)` for an async context manager) to register resources. Retrieve with `coco.use_context(KEY)` from inside any `@coco.fn`. [AST:python/cocoindex/_internal/environment.py:L449] · [AST:python/cocoindex/_internal/component_ctx.py:L273]

**Mount a sub-component:**
`await coco.mount([subpath,] processor_fn, *args, **kwargs)` — runs in background, returns `ComponentMountHandle`.
`await coco.mount_each([subpath,] fn, items, *args, **kwargs)` — one component per item; `items` is `Iterable[(key, value)]`, `AsyncIterable`, `LiveMapFeed`, or `LiveMapView`.
`result = await coco.use_mount([subpath,] processor_fn, *args, **kwargs)` — mount and wait for the result; the child cannot refresh independently of the parent.
The optional leading `subpath` is a `ComponentSubpath`; when omitted it is derived from `coco.Symbol(fn.__name__)`.
[AST:python/cocoindex/_internal/api.py:L333] · [:L427] · [:L194]

**Mount a target (declarative state reconciliation):**
`provider = await coco.mount_target(target_state)` — sugar over `use_mount` + `declare_target_state_with_child`. Connector-specific helpers (`postgres.mount_table_target`, `qdrant.mount_collection_target`, `lancedb.mount_table_target`, …) wrap this. [AST:python/cocoindex/_internal/api.py:L566]

**Concurrent map (no component, no checkpoint):**
`await coco.map(fn, items, *args, **kwargs)` — pure async TaskGroup over an iterable; results returned as a list. Use when you need parallelism but not memoization or sub-component lifecycle. [AST:python/cocoindex/_internal/api.py:L532]

**LLM embeddings (LiteLLM-based):**
`from cocoindex.ops.litellm import LiteLLMEmbedder; embedder = LiteLLMEmbedder("text-embedding-ada-002")`. An embedding provider only. Replaces v0.3.37's `cocoindex.functions.EmbedText(api_type=LlmApiType..., model=...)`. [AST:python/cocoindex/ops/litellm.py:L22]
v0.3.37's `cocoindex.functions.ExtractByLlm` has **no built-in replacement** — `cocoindex.ops` has no LLM-extraction op. Call LiteLLM's completion API yourself inside a `@coco.fn` (the `litellm` module is re-exported as `cocoindex.ops.litellm.litellm`); `examples/hn_trending_topics` does this with `await acompletion(model=..., messages=[...], response_format=...)`. [SRC:python/cocoindex/ops/litellm.py:L9] · [SRC:examples/hn_trending_topics/main.py:L99]

**Sentence-transformers embedding:**
`from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder; SentenceTransformerEmbedder("model-name")`. Replaces v0.3.37's `cocoindex.functions.SentenceTransformerEmbed`. [AST:python/cocoindex/ops/sentence_transformers.py:L25]

**Text chunking:**
`from cocoindex.ops.text import RecursiveSplitter, SeparatorSplitter, CustomLanguageConfig, detect_code_language`. Replaces v0.3.37's `cocoindex.functions.SplitRecursively` / `SplitBySeparators`. [AST:python/cocoindex/ops/text.py:L19]

**Lifecycle & utilities:**
```python
# Dual-mode runtime context manager — same call works for sync and async drivers
with coco.runtime():
    app.update_blocking()
# or:
async with coco.runtime():
    await app.update()

# Sync entry points for non-async callers
coco.start_blocking()
try:
    app.update_blocking()
finally:
    coco.stop_blocking()

# Async equivalents and direct env access
await coco.start()                # start default environment + enter lifespan
env = await coco.default_env()    # the default environment (starting it if needed)
await coco.stop()                 # exit lifespan + stop default environment

# Stream progress for a long-running update (consumes the handle)
handle = app.update()
result = await coco.show_progress(handle)

# Import submodules explicitly: `import cocoindex as coco` loads neither
# cocoindex.resources nor cocoindex.ops, so `coco.resources.*` / `coco.ops.*` raise AttributeError
from cocoindex.resources.id import generate_id, generate_uuid
from cocoindex.ops.text import detect_code_language

# Deterministic identifiers from content dependencies (memoized; idempotent)
chunk_id   = await generate_id(_dep=chunk.text)
chunk_uuid = generate_uuid(_dep=chunk.text)  # sync def: no await

# Detect a source file's language (for splitter pipelines)
lang = detect_code_language(filename="foo.py")
```
Provenance: [AST:python/cocoindex/_internal/api.py:L603] [:L608] [:L613] [:L618] [:L623] [:L655] · [AST:python/cocoindex/_internal/app.py:L194] · [AST:python/cocoindex/resources/id.py:L31] [:L61] · [AST:python/cocoindex/ops/text.py:L19]

**Component-context helpers (inside `@coco.fn`):**
`ctx = coco.get_component_context()` returns the current `ComponentContext`; raises `RuntimeError` outside a component. Build scoped keys with `subpath = coco.component_subpath(*key_parts)` — pass as the first positional argument to `mount` / `mount_each` / `use_mount`, or use it as a context manager. Push a scoped error handler with `async with coco.exception_handler(handler): ...` to catch exceptions raised by background-mounted children within the block. [AST:python/cocoindex/_internal/component_ctx.py:L305] [:L198] [:L331]

**Advanced extension hooks** (most callers don't need these — they exist for connector / runtime authors):

- `coco.register_root_target_states_provider(name, handler)` — register a new root `TargetStateProvider` (used by connector authors building target backends). [AST:python/cocoindex/_internal/target_state.py:L305]
- `coco.is_non_existence(obj)` — `TypeIs` guard for the `NON_EXISTENCE` sentinel when implementing memo-state branches. [AST:python/cocoindex/_internal/typing.py:L63]
- `coco.memo_fingerprint(obj)` and `coco.register_memo_key_function(typ, key_fn, *, state_fn=None)` — customize which fields participate in memoization keys for a custom type. [AST:python/cocoindex/_internal/memo_fingerprint.py:L361] [:L155]
- `coco.unpickle_safe(cls)` and `coco.serialize_by_pickle(cls)` — class decorators for pickle-safe round-trips of component state. [AST:python/cocoindex/_internal/serde.py:L128] [:L151]
- `is_live_component_class(cls) -> bool` — **internal**, not exported on `coco` (`coco.is_live_component_class` raises `AttributeError`): `from cocoindex._internal.live_component import is_live_component_class`. Runtime test for `LiveComponent`-shaped classes. [SRC:python/cocoindex/_internal/live_component.py:L35]
- `await get_vector_schema(obj)` and `await get_multi_vector_schema(obj)` (both async; `from cocoindex.resources.schema import get_vector_schema, get_multi_vector_schema`) — introspect a vector-schema provider attached to an `Annotated[...]` type (used when wiring a custom `Embedder` to a target column). [AST:python/cocoindex/resources/schema.py:L33] [:L58]

## Key API Summary

| Export | Kind | Purpose | Provenance |
|---|---|---|---|
| `App[P, R]` | class | Top-level pipeline runner. `App(name_or_config, main_fn, /, *args, **kwargs)`. Methods: `update(*, full_reprocess=False, live=False) -> UpdateHandle[R]`, `update_blocking(*, report_to_stdout=False, full_reprocess=False, live=False) -> R`, `drop() -> None` (async), `drop_blocking(*, report_to_stdout=False) -> None`. | [AST:python/cocoindex/_internal/app.py:L208] [SRC:python/cocoindex/_internal/app.py:L299] [:L335] [:L368] [:L380] |
| `AppConfig` | dataclass | `AppConfig(name, environment=_default_env, max_inflight_components=None)`. `environment` is typed `Environment \| LazyEnvironment`; the default `_default_env` is the private default `LazyEnvironment` instance — not the public `coco.default_env()` coroutine function. | [AST:python/cocoindex/_internal/app.py:L202] |
| `Environment` | class | CocoIndex runtime environment. Owns settings, context provider, event loop, and exception handler. `__init__(settings, *, name=None, context_provider=None, event_loop=None, exception_handler=None, info=None)`. | [AST:python/cocoindex/_internal/environment.py:L183] |
| `EnvironmentBuilder` | class | Lifespan builder. `provide(key, value)`, `provide_with(key, cm)`, `provide_async_with(key, cm)` (async), `set_exception_handler(handler)`. | [AST:python/cocoindex/_internal/environment.py:L87] |
| `LifespanFn` | type alias | `Callable[[EnvironmentBuilder], Iterator[None]] \| Callable[[EnvironmentBuilder], AsyncIterator[None]]`. | [SRC:python/cocoindex/_internal/environment.py:L118] |
| `lifespan` | decorator | `@coco.lifespan` registers an environment lifespan. Optional parens. | [AST:python/cocoindex/_internal/environment.py:L449] |
| `fn` | decorator namespace | `@coco.fn` (preserves sync/async), `@coco.fn(memo=True)`, `@coco.fn(memo=True, version=2, logic_tracking="self", deps=SYSTEM_PROMPT)`, where `version`, when set to an int, replaces the AST-derived logic fingerprint, `logic_tracking` takes a `LogicTracking` value (next row: `"full"`, the default, `"self"` or `None`) and `deps` is an external value the logic depends on but the body does not show, such as a module-level prompt string, or a tuple or dict of several. Batching and runners go through `@coco.fn.as_async(batching=True, max_batch_size=N, runner=GPU)`, which always yields async and takes sync or async functions. `@coco.fn(...)` with `batching=True` or a `runner` raises `ValueError` when it decorates any function. | [SRC:python/cocoindex/_internal/function.py:L1578] [SRC:python/cocoindex/_internal/function.py:L1811] [SRC:python/cocoindex/_internal/function.py:L1700] |
| `LogicTracking` | type alias | `Literal["full", "self"] \| None` — value type of the `logic_tracking=` kwarg on `@coco.fn`. `"full"` (default) tracks own code + transitive children, `"self"` tracks own code only, `None` disables tracking (incompatible with `deps`). | [SRC:python/cocoindex/_internal/function.py:L65] |
| `mount` | async fn | `await coco.mount([subpath,] processor_fn, *args, **kwargs) -> ComponentMountHandle`. Optional leading `subpath: ComponentSubpath`. | [AST:python/cocoindex/_internal/api.py:L333] |
| `mount_each` | async fn | `await coco.mount_each([subpath,] fn, items, *args, **kwargs) -> ComponentMountHandle`. Optional leading `subpath: ComponentSubpath`. | [AST:python/cocoindex/_internal/api.py:L427] |
| `mount_target` | async fn | `await coco.mount_target(target_state) -> TargetStateProvider[_ValueT, _ChildHandlerT]`. | [AST:python/cocoindex/_internal/api.py:L566] |
| `use_mount` | async fn | `result = await coco.use_mount([subpath,] processor_fn, *args, **kwargs) -> ReturnT`. Optional leading `subpath: ComponentSubpath`. Result-bearing mount. | [AST:python/cocoindex/_internal/api.py:L194] |
| `map` | async fn | `await coco.map(fn, items, *args, **kwargs) -> list[ReturnT]`. Concurrent fan-out, no component. | [AST:python/cocoindex/_internal/api.py:L532] |
| `start` / `stop` | async fns | Start/stop the default environment. | [AST:python/cocoindex/_internal/api.py:L603] [:L608] |
| `start_blocking` / `stop_blocking` | fns | Sync variants. | [AST:python/cocoindex/_internal/api.py:L613] [:L618] |
| `runtime()` | dual-mode ctxmgr | `with coco.runtime(): ...` or `async with coco.runtime(): ...`. | [AST:python/cocoindex/_internal/api.py:L655] |
| `Runner` / `GPU` | class / singleton | Abstract base for execution runners. `GPU` is a `GPURunner()` singleton — pass `runner=GPU` to `@coco.fn.as_async` (`@coco.fn(runner=GPU)` raises `ValueError`). Enable subprocess isolation with `COCOINDEX_RUN_GPU_IN_SUBPROCESS=1`. | [AST:python/cocoindex/_internal/runner.py:L34] [SRC:python/cocoindex/_internal/runner.py:L282] |
| `TargetState[OptChildHandlerT]` | class | Bundled (provider, key, value) triple. Built via `TargetStateProvider.target_state(key, value)`. | [AST:python/cocoindex/_internal/target_state.py:L248] |
| `TargetStateProvider[ValueT, OptChildHandlerT, MaybePendingS]` | class | Provider for target states. `target_state(key, value)`, `attachment(att_type)`, `memo_key`. | [AST:python/cocoindex/_internal/target_state.py:L208] |
| `TargetHandler[ValueT_contra, TrackingRecordT, OptChildHandlerT_co]` | Protocol | `reconcile(key, desired_target_state, prev_possible_records, prev_may_be_missing) -> TargetReconcileOutput \| None`. | [AST:python/cocoindex/_internal/target_state.py:L197] |
| `TargetActionSink[ActionT, OptChildHandlerT]` | class | Wraps a sink fn. `from_fn(fn)` / `from_async_fn(fn)` static constructors. | [AST:python/cocoindex/_internal/target_state.py:L143] |
| `TargetReconcileOutput[ActionT, TrackingRecordT, OptChildHandlerT]` | NamedTuple | `(action, sink, tracking_record, child_invalidation: Literal["destructive", "lossy"] \| None = None)`. | [AST:python/cocoindex/_internal/target_state.py:L188] |
| `declare_target_state(target_state)` | fn | Declare a state in the current component context. | [AST:python/cocoindex/_internal/target_state.py:L265] |
| `declare_target_state_with_child(target_state)` | fn | Declare with a child handler; returns `PendingTargetStateProvider[ValueT, OptChildHandlerT]`. | [AST:python/cocoindex/_internal/target_state.py:L282] |
| `register_root_target_states_provider(name, handler)` | fn | Register a root provider; returns `TargetStateProvider`. | [AST:python/cocoindex/_internal/target_state.py:L305] |
| `LiveComponent` | runtime Protocol | `process()` and `process_live(operator)` methods. | [AST:python/cocoindex/_internal/live_component.py:L28] |
| `LiveComponentOperator` | class | `update_full()`, `update(subpath, processor_fn, *args, **kwargs)`, `delete(subpath)`, `mark_ready()`. | [AST:python/cocoindex/_internal/live_component.py:L46] |
| `LiveMapFeed[K, V]` / `LiveMapView[K, V]` | runtime Protocols | `watch(subscriber)`; `LiveMapView` adds `__aiter__`. | [AST:python/cocoindex/_internal/live_component.py:L108] [:L119] |
| `LiveMapSubscriber[K, V]` | class | `update_all`, `mark_ready`, `update(key, value)`, `delete(key)`. | [AST:python/cocoindex/_internal/live_component.py:L130] |
| `ComponentContext` | dataclass | Internal context (frozen, slots). Use `coco.get_component_context()` to obtain; `with ctx.attach(): ...` re-binds it on another thread (`attach()` is a context manager). | [AST:python/cocoindex/_internal/component_ctx.py:L55] |
| `ComponentSubpath` | class | `coco.component_subpath(*key_parts)`. Pass as first arg to `mount`/`mount_each`/`use_mount`, or use as a context manager. Supports `/` chaining. | [AST:python/cocoindex/_internal/component_ctx.py:L142] |
| `component_subpath(*key_parts)` | fn | Convenience wrapper around `ComponentSubpath(...)`. | [AST:python/cocoindex/_internal/component_ctx.py:L198] |
| `use_context(key)` | fn | Retrieve a value provided in lifespan via `ContextKey`. Tracks change if `key.detect_change=True`. | [AST:python/cocoindex/_internal/component_ctx.py:L273] |
| `get_component_context()` | fn | Get current `ComponentContext`. Raises `RuntimeError` outside a component. | [AST:python/cocoindex/_internal/component_ctx.py:L305] |
| `exception_handler(handler)` | async ctxmgr | Push an exception handler for background-mounted components within scope. | [AST:python/cocoindex/_internal/component_ctx.py:L331] |
| `ContextKey[T]` | class | Generic `ContextKey` parametrized by `T`; constructor takes `(key: str, *, detect_change: bool = False)`. Keys are globally unique per process. | [AST:python/cocoindex/_internal/context_keys.py:L99] |
| `ContextProvider` | class | Internal — owned by `Environment`. `provide(key, value)`, `get(key, t=None)`, `provide_with(key, cm)`, `provide_async_with(key, cm)` (async), `aclose()` (async). | [AST:python/cocoindex/_internal/context_keys.py:L124] |
| `Settings` | dataclass | `Settings(db_path=None, global_execution_options=None, lmdb_max_dbs=1024, lmdb_map_size=4 GiB)`. `Settings.from_env(db_path=None)` reads the `COCOINDEX_SOURCE_MAX_INFLIGHT_*` and `COCOINDEX_LMDB_*` env vars, not `COCOINDEX_DB` (the default environment applies `COCOINDEX_DB` when `db_path` is unset). `coco.Settings` is `cocoindex._internal.setting.Settings`; `cocoindex.setting.Settings` is a separate class object with the same fields. | [AST:python/cocoindex/_internal/setting.py:L56] |
| `ServerSettings` | dataclass | `ServerSettings(address="127.0.0.1:49344", cors_origins=None)`. `from_env()` and static `parse_cors_origins(s)`. | [AST:python/cocoindex/setting.py:L93] |
| `GlobalExecutionOptions` | dataclass | `(source_max_inflight_rows=1024, source_max_inflight_bytes=None)`. | [AST:python/cocoindex/setting.py:L12] |
| `QueryHandlerInfo` | dataclass | `(result_fields: QueryHandlerResultFields \| None = None)`. **NEW in v1.0.0.** | [AST:python/cocoindex/query_handler.py:L21] |
| `QueryHandlerResultFields` | dataclass | `(embedding: list[str] = [], score: str \| None = None)`. | [AST:python/cocoindex/query_handler.py:L10] |
| `QueryInfo` | dataclass | `(embedding: list[float] \| NDArray[np.float32] \| None = None)`. v0.3.37's `similarity_metric` field is **removed**. | [AST:python/cocoindex/query_handler.py:L30] |
| `QueryOutput[R]` | dataclass | `(results: list[R], query_info: QueryInfo = QueryInfo())`. | [AST:python/cocoindex/query_handler.py:L43] |
| `cli` | click.Group | The `cocoindex` CLI entry point. Subcommands: `ls`, `show`, `update`, `drop`, `init`. | [AST:python/cocoindex/cli.py:L505] |

See:
- [Component API reference](references/component-api.md) — App, Environment, mount, fn, lifespan, runtime
- [Target state reconciliation](references/target-state.md) — TargetState, TargetHandler, declare_target_state
- [Live components](references/live-components.md) — LiveComponent, LiveMapFeed, LiveMapView
- [Connectors](references/connectors.md) — postgres, qdrant, lancedb, surrealdb, sqlite, doris, kafka, localfs, amazon_s3, google_drive
- [Ops](references/ops.md) — litellm, sentence_transformers, text, entity_resolution
- [Resources](references/resources.md) — Chunk, FileLike, IdGenerator, schema providers
- [Settings & CLI](references/settings-cli.md) — Settings, ServerSettings, query_handler, cocoindex CLI

<!-- [MANUAL:api-notes] -->
<!-- Add custom notes here. This section is preserved during skill updates. -->
<!-- [/MANUAL:api-notes] -->

## Key Types

```python
# Component-context plumbing
StableKey = None | bool | int | str | bytes | uuid.UUID | Symbol | tuple[StableKey, ...]
StablePath              # core.StablePath wrapper; supports / chaining
ROOT_PATH               # singleton StablePath()
Symbol                  # core.Symbol — opaque marker (used in subpaths)

# Update lifecycle
UpdateStatus            # StrEnum: "running" | "ready"
ComponentStats          # NamedTuple(num_execution_starts, num_unchanged, num_adds, num_deletes, num_reprocesses, num_errors). Properties: num_processed, num_finished, num_in_progress
UpdateStats             # NamedTuple(by_component: dict[str, ComponentStats]). Property: total
UpdateSnapshot[R]       # NamedTuple(stats, status, result)
UpdateHandle[R]         # Awaitable[R]; .stats(), .watch() (AsyncIterator[UpdateSnapshot])
DropHandle              # Awaitable[None]; .stats(), .watch() (AsyncIterator[UpdateSnapshot[None]]). App.drop() itself returns None

# Typestate (static-only — phantom types)
PendingS                # marker for "pending" target state providers
ResolvedS               # marker for "resolved"
MaybePendingS           # TypeVar(PendingS, ResolvedS, default=ResolvedS)
ResolvesTo[ResolvedT]   # generic mixin used in use_mount() return-type bridge

# Non-existence sentinel
NonExistenceType        # singleton type
NON_EXISTENCE           # the singleton instance
is_non_existence(obj)   # TypeIs[NonExistenceType]
MemoStateOutcome        # NamedTuple(state, memo_valid=False)

# Memoization
NotMemoKeyable          # base for types that must not be used as memo keys
memo_fingerprint(obj)   # core.Fingerprint
register_memo_key_function(typ, key_fn, *, state_fn=None)
```

Provenance: [SRC:python/cocoindex/_internal/stable_path.py:L9] [AST:python/cocoindex/_internal/stable_path.py:L16] [SRC:python/cocoindex/_internal/stable_path.py:L59] · [AST:python/cocoindex/_internal/typing.py:L47] [:L67] · [AST:python/cocoindex/_internal/update_stats.py:L9] · [AST:python/cocoindex/_internal/pending_marker.py:L74] [:L89] [:L118] [SRC:python/cocoindex/_internal/pending_marker.py:L115] · [AST:python/cocoindex/_internal/memo_fingerprint.py:L136] [:L155] [:L361]

## Architecture at a Glance

- **Public API entry point:** `python/cocoindex/__init__.py` does `from ._internal.api import *` and re-exports `_internal.api.__all__` (72 names). Always import as `import cocoindex as coco`. [SRC:python/cocoindex/__init__.py:L13]
- **API hub:** `python/cocoindex/_internal/api.py` is the canonical re-export module. It defines `mount`, `mount_each`, `mount_target`, `use_mount`, `map`, `start`, `stop`, `start_blocking`, `stop_blocking`, `default_env`, `runtime`, `ComponentMountHandle`, and re-exports the rest. [SRC:python/cocoindex/_internal/api.py:L669]
- **Component runtime:** `_internal/app.py` (App, AppConfig, UpdateHandle, DropHandle, show_progress), `_internal/environment.py` (Environment, EnvironmentBuilder, lifespan, start/stop), `_internal/runner.py` (Runner, GPU singleton).
- **Component model:** `_internal/function.py` (the `@coco.fn` decorator, a `_FunctionDecorator` instance; the `Function` Protocol; `SyncFunction` / `AsyncFunction`, the concrete classes with `__slots__` that subclass it and that `@coco.fn` returns) [SRC:python/cocoindex/_internal/function.py:L138] [SRC:python/cocoindex/_internal/function.py:L491] [SRC:python/cocoindex/_internal/function.py:L903], `_internal/component_ctx.py` (ComponentContext, ComponentSubpath, exception_handler, use_context).
- **Target reconciliation:** `_internal/target_state.py` — TargetState/TargetStateProvider/TargetHandler/TargetActionSink + declare_target_state / declare_target_state_with_child / register_root_target_states_provider.
- **Live components:** `_internal/live_component.py` — LiveComponent, LiveComponentOperator, LiveMapFeed/View, LiveMapSubscriber.
- **Plumbing:** `_internal/context_keys.py` (ContextKey, ContextProvider), `_internal/stable_path.py` (StablePath/StableKey/Symbol), `_internal/memo_fingerprint.py` (memo_fingerprint, NotMemoKeyable), `_internal/serde.py` (unpickle_safe, serialize_by_pickle).
- **Connectors:** `python/cocoindex/connectors/{amazon_s3,doris,google_drive,kafka,lancedb,localfs,postgres,qdrant,sqlite,surrealdb}` — each package re-exports its `_source.py` and/or `_target.py` `__all__`. Replaces v0.3.37 `sources.*` + `targets.*`.
- **Ops:** `python/cocoindex/ops/{litellm,sentence_transformers,text}` + `ops/entity_resolution/`. Replaces v0.3.37 `functions.*`.
- **Resources:** `python/cocoindex/resources/{chunk,embedder,file,id,schema}.py` — first-class data types referenced from connectors and `@coco.fn` signatures.
- **Storage:** state lives in **LMDB** at `Settings.db_path` (`COCOINDEX_DB` env var). v0.3.37's Postgres-backed state via `DatabaseConnectionSpec` is gone.
- **Rust engine:** `rust/` — out of scope; users author components in Python via pyo3 bindings exposed as `cocoindex._internal.core`.

## CLI

The `cocoindex` CLI is a click group ([AST:python/cocoindex/cli.py:L505]) with five subcommands ([AST:python/cocoindex/cli.py:L530] [:L581] [:L692] [:L761] [:L819]):

```sh
cocoindex [-V] [-e ENV_FILE] [-d APP_DIR] <subcommand> ...

cocoindex ls   [APP_TARGET] [--db PATH]                 # List apps (from the module, or from the LMDB store)
cocoindex show [APP_TARGET] [--db PATH --app-name NAME] [--tree]  # Show the app's stable paths
cocoindex update APP_TARGET [-L|--live] [--full-reprocess] [--reset] [-f|--force] [-q|--quiet]  # Run an update (one-shot or live)
cocoindex drop APP_TARGET [-f|--force] [-q|--quiet]     # Drop an app's target states + state DB
cocoindex init [PROJECT_NAME] [--dir PATH]              # Scaffold a new project
```

`show` takes either `APP_TARGET` or both `--db` and `--app-name`. `update --reset` drops the existing state first (asks for confirmation unless `-f`). `-e` loads a `.env` file; without it the CLI loads the nearest `.env` from the current directory upward. `-d APP_DIR` only prepends `APP_DIR` to `sys.path` and does not change the working directory: it lets a module-name `APP_TARGET` be imported from `APP_DIR`, while a `.py` path is still resolved against the current directory. [SRC:python/cocoindex/cli.py:L507] [SRC:python/cocoindex/cli.py:L513] [SRC:python/cocoindex/user_app_loader.py:L54]

`APP_TARGET` is a path to a `.py` file or a module name, optionally followed by `:app_name` or `:app_name@env_name` to pick one app by its `App` name (the `AppConfig.name`) when the module registers several. The CLI resolves it via `_load_app()` ([SRC:python/cocoindex/cli.py:L274]), which loads the module and selects among the `App` instances it registered. v0.3.37's `main.py:flow_name` meaning (selecting a flow) is gone: the suffix names an app, not a flow.

## Migration from v0.3.37

The 0.3.37 → 1.0.0 transition is **not a rename** — every public module from v0.3.37 was deleted and replaced with a different paradigm. There is no automatic migration tool. The mapping is conceptual, not mechanical:

| v0.3.37 (gone) | v1.0.0 (replacement) |
|---|---|
| `@cocoindex.flow_def(name="...")` over `(FlowBuilder, DataScope) -> None` | `coco.App(coco.AppConfig(name="..."), main_fn, *args)` where `main_fn` is `@coco.fn`-decorated |
| `cocoindex.open_flow(name, fl_def)` | `coco.App(coco.AppConfig(name=name), main_fn, ...)` |
| `cocoindex.transform_flow()` | `@coco.fn` decorator (component-level transform) |
| `FlowBuilder.add_source(spec)` | `coco.mount_each(process_fn, walker.items())` for a `walker = localfs.walk_dir(...)`; `coco.mount_each(process_fn, pg_source.fetch_rows().items(key_fn))` for a `postgres.PgTableSource` (`PgTableSource` has no `items`, and `key_fn`, which maps a row to its `StableKey`, is required); `coco.mount_each(process_fn, kafka.topic_as_map(consumer, topics))` for Kafka, which passes the feed itself (it has no `items`; live mode only). [SRC:python/cocoindex/connectors/localfs/_source.py:L147] · [SRC:python/cocoindex/connectors/postgres/_source.py:L215] [:L118] · [SRC:python/cocoindex/connectors/kafka/_source.py:L228] [:L361] |
| `DataSlice.transform(fn_spec)` / `DataSlice.row()` | `await coco.map(fn, items)` for fan-out, or `await coco.mount(child_fn, *args)` for sub-components |
| `DataCollector.collect(...)` / `.export(target_name, target_spec, ...)` | `target = await postgres.mount_table_target(...)`, then `target.declare_row(row=row)` (`row` is keyword-only) from the components that produce rows (or the per-connector equivalent) |
| `Flow.update()` / `Flow.update_async()` | `app.update_blocking()` / `await app.update()` |
| `Flow.setup()` / `Flow.drop()` | `app.update_blocking()` (setup is implicit on first run); `app.drop()` / `app.drop_blocking()` |
| `FlowLiveUpdater(fl)` with `start()`/`wait()` | `app.update(live=True)` returns an `UpdateHandle`; iterate `handle.watch()` for `UpdateSnapshot`s |
| `cocoindex.functions.SplitRecursively` / `SplitBySeparators` | `cocoindex.ops.text.RecursiveSplitter` / `SeparatorSplitter` |
| `cocoindex.functions.SentenceTransformerEmbed(model=...)` | `cocoindex.ops.sentence_transformers.SentenceTransformerEmbedder("model")` |
| `cocoindex.functions.EmbedText(api_type=LlmApiType.OPENAI, model=..., api_key=...)` | `cocoindex.ops.litellm.LiteLLMEmbedder("text-embedding-ada-002", api_key=...)` (LiteLLM-based dispatch; provider config is per-model string) |
| `cocoindex.functions.ExtractByLlm(llm_spec=LlmSpec(...), output_type=..., instruction=...)` | no built-in replacement — call LiteLLM's completion API (the `litellm` module, also re-exported as `cocoindex.ops.litellm.litellm`) inside a `@coco.fn` and parse the response yourself |
| `cocoindex.functions.ParseJson` / `DetectProgrammingLanguage` | regular Python (`json.loads`); `cocoindex.ops.text.detect_code_language(filename="main.py")` |
| `cocoindex.sources.LocalFile` / `GoogleDrive` / `AmazonS3` / `AzureBlob` / `Postgres` | `cocoindex.connectors.{localfs,google_drive,amazon_s3,…,postgres}.*` (no built-in AzureBlob; use `localfs` patterns or write a connector) |
| `cocoindex.targets.Postgres` / `Qdrant` / `Pinecone` / `Neo4j` / `FalkorDB` / `Ladybug` / `LanceDB` / `ChromaDB` / `DorisTarget` / `Turbopuffer` | `cocoindex.connectors.{postgres,qdrant,lancedb,doris,sqlite,surrealdb,kafka}` (no built-in Pinecone, Neo4j, FalkorDB, ChromaDB, Turbopuffer in v1.0.0 — write a connector or upstream a request) |
| `LlmSpec` / `LlmApiType` / `VertexAiConfig` / `OpenAiConfig` / `AzureOpenAiConfig` | LiteLLM model strings (`"vertex_ai/textembedding-gecko"`, `"azure/<deployment>"`, etc.) passed to `LiteLLMEmbedder` for embeddings (or to your own LiteLLM completion calls). Provider config flows through `**kwargs` (e.g., `api_key`, `api_base`). |
| `VectorSimilarityMetric` / `VectorIndexDef` / `FtsIndexDef` / `IndexOptions` | per-connector. E.g., `postgres.TableTarget.declare_vector_index(column="embedding")` lives on the target itself, not as a top-level type. |
| `Settings` backed by Postgres (`DatabaseConnectionSpec(url=...)`) | `coco.Settings(db_path=pathlib.Path("state.lmdb"))` — state moved from Postgres to local LMDB. `COCOINDEX_DB` env var. |
| `cocoindex.auth_registry.add_auth_entry / ref_auth_entry` | gone; pass credentials directly via `EnvironmentBuilder.provide(KEY, …)` and `coco.use_context(KEY)` |
| `cocoindex.utils.get_target_default_name` / `get_target_storage_default_name` | gone; connectors expose names via their target-spec helpers |
| `add_flow_def(name, fl_def)` (deprecated in v0.3.37) | gone; no replacement needed |
| `remove_flow(fl)` (deprecated in v0.3.37) / `Flow.close()` | gone; `app.drop()` handles teardown |
| `cocoindex.storages` (deprecated alias for `cocoindex.targets`) | gone; both `targets` and `storages` are removed |
| `cocoindex.cli` subcommand semantics (`ls`, `show`, `setup`, `drop`, `update`, `evaluate`, `server`) | reduced to `ls`, `show`, `update`, `drop`, `init`. `setup`/`evaluate`/`server` are gone; `update` does setup implicitly. |

**Storage migration:** v0.3.37 stored flow state in Postgres tables. v1.0.0 stores everything in a local LMDB file at `Settings.db_path` (`COCOINDEX_DB` env var). Existing v0.3.37 state cannot be read by v1.0.0 — plan a re-index, not an in-place upgrade.

## Gotchas

- **Cocoindex v1.0.0 does NOT preserve API stability across minor versions** despite the 1.0 tag. The 0.3 → 1.0 jump itself was a wholesale rewrite; treat future minor versions cautiously and pin in your `requirements.txt` / `pyproject.toml`.
- **All `mount*`, `App.update`, `App.drop`, `start`/`stop`, `coco.map` are async** — wrap in `asyncio.run()` or use `app.update_blocking()` / `app.drop_blocking()` / `start_blocking()` / `stop_blocking()` for sync entry points.
- **`@coco.fn` preserves sync/async** — sync function → `SyncFunction`, async function → `AsyncFunction`. For batching or a runner use `@coco.fn.as_async(batching=True, runner=GPU)`, which always yields an `AsyncFunction` and takes sync or async functions. `@coco.fn(batching=True)` and `@coco.fn(runner=GPU)` raise `ValueError` when they decorate any function, sync or async, although `@coco.fn`'s docstring says async functions are accepted: with `batching`, `runner` or `max_batch_size` set, `@coco.fn` uses a builder that rejects async functions and then rejects batching and runners. [SRC:python/cocoindex/_internal/function.py:L1700] [SRC:python/cocoindex/_internal/function.py:L1519] [SRC:python/cocoindex/_internal/function.py:L1479]
- **`logic_tracking` controls memoization invalidation:** `"full"` (default) tracks own code + transitive children; `"self"` tracks own code only; `None` disables tracking (incompatible with `deps`).
- **`deps` is snapshotted at decoration time**, not per-call. For per-call values pass them as regular function arguments; reserve `deps` for module-level constants like prompts or model identifiers.
- **`ContextKey` keys must be globally unique per process** — re-using a key string raises `ValueError`. Use module-qualified names (`"my_module.PG_DB"`) or namespaced strings.
- **`use_mount` returns whatever the child returns** — half of its overloads take a plain `ReturnT`. `ResolvesTo[T]` is only an optional static-typing bridge: when the child returns a `ResolvesTo[T]` (a pending provider), the type checker sees the resolved `T`. If you build custom pending wrappers, inherit from `ResolvesTo` and parameterize over `MaybePendingS`.
- **`LiveMapFeed` requires live mode** — passing a feed (no scannable snapshot, like `kafka.topic_as_map`) to `mount_each` without `app.update(live=True)` raises `TypeError`. A `LiveMapView` supports both modes. `localfs.walk_dir` returns a `DirWalker`, not a view: its `items()` is a `LiveMapView` only when `walk_dir` gets `live=True`, and a plain `AsyncIterable` of `(relative_path, File)` pairs otherwise. [SRC:python/cocoindex/connectors/localfs/_source.py:L147] [SRC:python/cocoindex/_internal/live_component.py:L189]
- **`COCOINDEX_RUN_GPU_IN_SUBPROCESS=1`** opts the `GPU` runner into subprocess isolation; default is in-process: sync functions run on a dedicated single-worker thread, async functions are awaited directly on the event loop. [SRC:python/cocoindex/_internal/runner.py:L252] [:L265]
- **`cocoindex.resources.*` is first-class public API** — `Chunk`, `TextPosition`, `FileLike`, `FilePath`, `FileMetadata`, `PatternFilePathMatcher`, `IdGenerator`, `UuidGenerator`, `Embedder` Protocol, `VectorSchemaProvider`, `VectorSchema`. Always import from there, not from `connectors/*` internals.
- **`cocoindex.connectorkits.*` and `cocoindex.inspect`** also exist and are referenced from connector implementations — these are not yet documented in this skill (added scope candidates for a follow-up).

<!-- [MANUAL:integration-notes] -->
<!-- Add custom notes here. This section is preserved during skill updates. -->
<!-- [/MANUAL:integration-notes] -->
Pliki w paczce (10)
  • SKILL.md 39 KB
  • context-snippet.md 1 KB
  • metadata.json 5 KB
  • references/component-api.md 19 KB
  • references/connectors.md 10 KB
  • references/live-components.md 5 KB
  • references/ops.md 9 KB
  • references/resources.md 10 KB
  • references/settings-cli.md 13 KB
  • references/target-state.md 8 KB

Wersje

W bazie nie ma innych skilli o nazwie oms-cocoindex.

Migawka bazy z 13.11.2026 · wersja paczki 89ec8e58e800 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 95cocoindex
    Pomaga budować i diagnozować przyrostowe przepływy danych w Pythonie z CocoIndex, na przykład do indeksowania pod RAG.
  • 95cocoindex
    Wspiera tworzenie potoków transformacji danych w bibliotece CocoIndex (flows), własnych funkcji i operowanie nimi przez CLI lub API, na przykład embeddingi do baz wektorowych, grafy wiedzy i indeksy wyszukiwania.
  • 100fai-build-etl-pipeline
    Projektuje potoki ETL i ELT dla zasilania systemów AI: ekstrakcja, transformacja, kontrole jakości, harmonogramy i idempotentne ładowanie, także dla dokumentów trafiających do RAG.
  • 95data-pipelines
    Buduje i naprawia potoki danych w Airflow, Prefect i dbt: modele, testy, przyrostowe ładowania i idempotentny ETL.
  • 100preprocessing-data-with-automated-pipelines
    Automatyzuje czyszczenie, transformację i walidację danych dla zadań ML, w tym potoki ETL.
  • 100preprocessing-data-with-automated-pipelines
    Automatyzuje czyszczenie, transformację i walidację danych dla zadań ML, w tym potoki ETL.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.