Write a Custom Source in Python: Index Any API

Index an internal API with CocoIndex v1: plain async Python, deletes propagate, and a memo on updated_at skips unchanged items.

FeatureUpdated 8 min read
Index any API with a custom source in plain async Python. The v0 connector API, SourceSpec, create(spec), list(), get_value(key) and provides_ordinal(), is crossed out. In v1, for an internal ticketing API: async def list_ticket_ids() -> list[str], async def fetch_ticket(ticket_id: str) -> TicketRow, a @coco.fn process_ticket that calls table.declare_row(row=ticket), and await coco.mount_each(process_ticket, ...). The engine diffs, syncs and deletes rows of removed tickets.
Enlarge cover

Write a Custom Source in Python: Index Any API

Zoom in to see details.

Index any API with a custom source in plain async Python. The v0 connector API, SourceSpec, create(spec), list(), get_value(key) and provides_ordinal(), is crossed out. In v1, for an internal ticketing API: async def list_ticket_ids() -> list[str], async def fetch_ticket(ticket_id: str) -> TicketRow, a @coco.fn process_ticket that calls table.declare_row(row=ticket), and await coco.mount_each(process_ticket, ...). The engine diffs, syncs and deletes rows of removed tickets.

An agent answers from what you indexed for it. For most teams, the knowledge that matters lives in internal systems: a ticket tracker, a CRM, a wiki, a homegrown API. When a ticket is closed or a runbook is deleted, the index has to follow. If it does not, the agent quotes the old status, or cites a page that no longer exists.

CocoIndex can read data from any of these systems, with or without a built-in connector. Whatever you can fetch from Python, CocoIndex can ingest, track for changes, and keep in sync with your targets, including deletes.

Updated for CocoIndex v1

The original version of this post introduced a dedicated source connector API (SourceSpec, source_connector, list() / get_value()). CocoIndex v1 removed the need for that interface: a custom source is now ordinary async Python plus processing components. This post describes the v1 approach, with a mapping from the v0 API for readers of the original.

Custom sources are the complement to custom targets, giving you control over both ends of a pipeline: where data comes from and where it lands.

Why CocoIndex does not wait for a connector

Expanding the connector library is on the roadmap. But a connector only solves the read. The harder part of a pipeline comes after it: detecting what changed, reconciling the target with the source, and recovering from failures. CocoIndex puts its effort into that incremental processing engine, and keeps the source a thin layer you can write yourself.

Assemble pipelines from building blocks

CocoIndex apps are modular. Sources, transformations and targets compose, and you can replace one without rewriting the others. A custom source is the input-side block you supply yourself, alongside:

  • Custom targets: write to any system, with the same diff-and-sync treatment as built-in targets.
  • Custom transformations: domain-specific logic as ordinary decorated functions.
  • Built-in connectors and operations for the common cases.

The pipeline stays incremental and traceable whatever it reads from or writes to.

What a custom source looks like in v1

A custom source needs no connector class and no plugin registration. It is two plain async functions and one processing component:

  1. A listing function that returns what exists right now: a stable key for each item, plus a version such as updated_at if your API has one.
  2. A fetch function that returns the full content for one key.
  3. A processing component, one per item, that fetches the item, transforms it, and declares the rows that should exist downstream.

Here is a complete app for an internal ticketing API. Only the two API calls are left for you to fill in:

main.py
import os
from dataclasses import dataclass
from datetime import datetime
from typing import AsyncIterator

import asyncpg
import cocoindex as coco
from cocoindex.connectors import postgres

DATABASE_URL = os.environ["POSTGRES_URL"]
PG_DB = coco.ContextKey[asyncpg.Pool]("tickets_db")


@dataclass
class TicketRef:
    """One entry of the listing: a stable key plus a version."""
    id: str
    updated_at: datetime


@dataclass
class TicketRow:
    id: str
    title: str
    body: str
    status: str
    updated_at: datetime


async def list_tickets() -> list[TicketRef]:
    """Ask your system what exists right now."""
    ...


async def fetch_ticket(ticket_id: str) -> TicketRow:
    """Fetch the full content for one item."""
    ...


@coco.fn(memo=True)
async def process_ticket(
    ref: TicketRef, table: postgres.TableTarget[TicketRow]
) -> None:
    ticket = await fetch_ticket(ref.id)
    table.declare_row(row=ticket)


@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
    async with asyncpg.create_pool(DATABASE_URL) as pool:
        builder.provide(PG_DB, pool)
        yield


@coco.fn
async def app_main() -> None:
    table = await postgres.mount_table_target(
        PG_DB,
        table_name="tickets",
        table_schema=await postgres.TableSchema.from_class(
            TicketRow, primary_key=["id"]
        ),
    )
    refs = await list_tickets()
    await coco.mount_each(process_ticket, ((r.id, r) for r in refs), table)


app = coco.App(coco.AppConfig(name="TicketIndex"), app_main)

Install cocoindex[postgres] (it brings asyncpg). Set POSTGRES_URL, and set COCOINDEX_DB to a local file path such as ./cocoindex.db, where CocoIndex keeps its own state (see App). Then run cocoindex update main.py.

Four details of this code do the incremental work:

  • coco.mount_each mounts one processing component per item, keyed by the ticket ID. That key gives each item a stable component path across runs, which is how the engine matches an item to its previous run.
  • declare_row states what should exist in the target. You never write inserts, updates or deletes. The engine compares the declared rows against the previous run and applies only the difference.
  • memo=True on process_ticket makes its arguments the memo key. The TicketRef dataclass carries the ID and updated_at, so a ticket whose updated_at did not change is skipped before fetch_ticket runs.
  • The fetch functions are plain async def. Any HTTP API, message queue, SDK or database driver works the same way. Clients and connection pools go in the app lifespan, as the Postgres pool does here, and components reach them through a context key.

The downstream half of the pipeline (chunking, embedding, LLM extraction, graph building) is written the same way as for a built-in connector. A transformation does not know whether its input came from S3, Postgres or your ticketing API.

How it stays in sync

On each run, list_tickets returns what exists now, and mount_each mounts one component per ticket:

  • A ticket with a new ID gets a new component. It fetches the ticket, and its row is inserted.
  • A ticket seen before is matched by its component path. If its TicketRef is the same as last run, the component is a memo hit: its body does not run, so there is no fetch, and the row it declared last time is kept. If updated_at changed, the body runs, and the row is updated if its content differs.
  • A ticket that is gone from the listing is no longer mounted. The engine deletes the target states that component declared, so the ticket’s row leaves the table. You write no delete logic.

Without memo=True the engine still writes only the rows that changed, but it has to run every component to learn what each row is. Every run then calls fetch_ticket once per listed ticket, which costs time and API rate limit on a large tracker. Try both settings:

Edit the tickets, then run the update

Illustrative model of a cocoindex update run
@coco.fn(memo=True)
ticket APIprocess_tickettickets row
T-101SSO login loops on Safariopenupdated_at 09:02 memo hit no write
T-102editedCSV export drops UTF-8in progressupdated_at 09:47 ran · fetched updated
T-103Refund policy for annual plansin progressupdated_at 09:14 memo hit no write
T-104deletedWebhook retries charge twiceclosedupdated_at 09:21removed from the API not mounted deleted
T-105Rate limit docs out of dateopenupdated_at 09:30 memo hit no write
T-106newAgent cites a deleted runbookopenupdated_at 09:54 ran · fetched inserted
listed
5
fetch_ticket calls
2
rows written
3
2 fetch_ticket calls for 5 listed tickets; 1 inserted, 1 updated, 1 deleted. Without memo, every listed ticket would be fetched: 5.

The memo key has three limits:

  • The memo is only as good as the version. An upstream edit that does not change updated_at is skipped until the next change that does. If your API has no version field, leave memo=True off: every run fetches everything, and the target is still diffed and cleaned up.
  • A code change invalidates the memo. Every @coco.fn fingerprints its own source code, so after you edit process_ticket (or a decorated function it calls), the next run fetches every ticket once. fetch_ticket is undecorated here, so editing it does not invalidate the memo.
  • Every field of TicketRef is part of the key. To list more fields without adding them to the key, pass memo_key= to @coco.fn or define __coco_memo_key__ on the dataclass (see memoization keys).

Expensive steps inside the component, such as embedding or LLM extraction, can carry their own memo=True. When a ticket changes only its status, its component re-runs, but the embedding of its unchanged body is reused.

In v0 this skip depended on your connector returning an ordinal (a timestamp or version number) from list(), and True from provides_ordinal(). In v1 the version is an ordinary argument of a memoized component.

Keep it fresh

cocoindex update is a catch-up run: it lists, syncs and exits. There are three ways to keep the index current.

  • A schedule. Run cocoindex update main.py from cron, a CI job or your orchestrator.

  • coco.auto_refresh. Wrap the listing in a component that re-runs on an interval, and start the app in live mode with cocoindex update -L main.py. Each cycle reconciles against the previous one, so deletes propagate as they do in a catch-up run. In catch-up mode the wrapper runs once. The wrapper adds a level to the component paths (sync_tickets/process_ticket/<id>), so the first run after you switch to it fetches every ticket once.

    python
    import datetime
    
    
    async def sync_tickets(table: postgres.TableTarget[TicketRow]) -> None:
        refs = await list_tickets()
        await coco.mount_each(process_ticket, ((r.id, r) for r in refs), table)
    
    
    @coco.fn
    async def app_main() -> None:
        table = ...  # mount_table_target, as above
        await coco.mount(
            coco.auto_refresh(sync_tickets, interval=datetime.timedelta(minutes=5)),
            table,
        )
  • A LiveMapView or LiveMapFeed. If your system pushes changes (webhooks, a change feed), write a live map and pass it to mount_each in place of the list. A LiveMapView can scan the current items and watch for changes; a LiveMapFeed only watches, so it needs live mode (-L). Each event updates or deletes one component, without re-listing everything.

Keep an AI agent’s context in sync with live mode walks through live mode end to end.

From the v0 connector API

If you read the original version of this post, or wrote a v0 custom source, here is where each piece went:

v0 connector APIv1 equivalent
SourceSpecPlain function arguments and app config
create(spec)Your own client setup, typically in the app lifespan
list()A listing function plus the keys passed to mount_each
get_value(key)A fetch call inside the per-item component
Key and value typesThe component key, plus dataclasses for rows
provides_ordinal() and the ordinal from list()A version such as updated_at in the arguments of a memoized component

In v0 you fit your system into a connector contract so the engine could read through it. In v1 you read your system with whatever code fits it, and the engine tracks the results with the same components, memo and target states as the rest of the framework.

When to build a custom source

Reach for a custom source when there is no built-in connector for where your data lives: an internal or proprietary API, a legacy database with an unusual access path, or a SaaS product CocoIndex doesn’t ship a connector for yet. If a built-in connector already covers your system, use it. Custom sources cover the long tail of systems without a connector, and you add them without forking or patching the engine.

Common shapes we see:

  • Knowledge aggregation for LLM context: wikis, ticket systems, and internal APIs each become a fetch function and a component, and the index stays current as they change.
  • Data stitching: one component fetches from several services (auth, billing, usage) and declares a single composite row, so the join happens before the data hits your index.
  • Legacy wrappers: wrap a hard-to-use read path (SOAP, XML, mainframe exports) in a fetch function, and the data lands in a queryable table.

The HackerNews example is a complete custom source built this way: it fetches recent stories and their nested comments from the Algolia HN API, extracts topics from every message with an LLM, and keeps two Postgres tables in sync for search and analytics. Its LLM step is memoized; its per-thread component is not, so each run fetches every listed thread again.

The custom-source walkthrough builds it step by step, and the example gallery has more pipelines to start from.

If you build a source for a system others use too, we’d like to hear about it: CocoIndex on GitHub.

Frequently asked questions

What is a custom source in CocoIndex?

A custom source is how CocoIndex reads data from a system with no built-in connector. In CocoIndex v1 it is ordinary async Python: a listing function that returns what exists right now as stable keys, a fetch function that returns the full content for one key, and a processing component per item that declares the rows that should exist downstream. There is no connector interface to implement.

See What a custom source looks like in v1.

Do I need to implement a connector API to add a custom source?

No. The v0 connector interface (SourceSpec, source_connector, list() / get_value()) was removed in CocoIndex v1. You fetch data with plain async def functions, fan out one processing component per item with coco.mount_each, and declare target rows with declare_row. The engine handles change detection, syncing, and cleanup.

See From the v0 connector API.

Why doesn't CocoIndex just build more prebuilt connectors?

Expanding the connector library is on the roadmap, but a connector only solves the read. The harder part of a pipeline comes after it: detecting what changed, reconciling the target with the source, and recovering from failures. CocoIndex focuses on that engine and lets you write the source layer yourself when there is no connector.

See Why CocoIndex does not wait for a connector.

How does a custom source support incremental updates?

Each item runs as a processing component keyed by its ID, so the engine matches it to its previous run. Changed declared rows are updated, new ones inserted, and items that disappear from the listing have their target rows deleted. Mark the component @coco.fn(memo=True) and pass a version such as updated_at from the listing as an argument: an item whose version did not change is skipped without a fetch. Without the memo, every run fetches every listed item, and the target is still diffed.

See How it stays in sync.

How do I keep a custom source fresh?

Run cocoindex update on a schedule, or wrap the listing in coco.auto_refresh and run the app in live mode so it re-lists on an interval. If your system pushes changes, implement a LiveMapView (scan and watch) or a LiveMapFeed (watch only, live mode) and pass it to mount_each.

See Keep it fresh.

What happened to SourceSpec, source_connector, and provides_ordinal from v0?

They no longer exist in CocoIndex v1. SourceSpec becomes plain function arguments and app config, create() becomes your own client setup in the app lifespan, list() becomes a listing function plus the keys passed to mount_each, and get_value() becomes a fetch call inside the per-item component. The ordinal becomes a version such as updated_at that you pass from the listing into a memoized component, so unchanged items are skipped without a fetch.

See From the v0 connector API.

When should I build a custom source?

When no built-in connector covers where your data lives: an internal or proprietary API, a legacy database with an unusual access path, or a SaaS product without a shipped connector. Common shapes include aggregating wikis and ticket systems into LLM context, stitching several services into one composite row, and wrapping legacy read paths so the data lands in a queryable table. If a built-in connector already covers your system, use it. For Jira, Confluence, or connectors to internal systems built on request, see CocoIndex Plus.

See When to build a custom source.

Build fresh context for your agents.

CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.