Product sync parsers

Product sync parsers

Turn any product feed, API or database into your Octocom catalog with a small Python parser.

A product sync parser is a small Python script that turns a business's product data into catalog rows Octocom can search. Every business's catalog is synced by its own parser, so any source works: an XML or CSV feed, a JSON API, a database, or several of these joined together. For example, a retailer can join its main product feed with a separate reviews feed by SKU, in one parser.

The AI agent, storefront search and product recommendations all read the catalog the parser produces. See Product catalog.

  • Store platforms get a default parser when the integration is connected: Shopify, WooCommerce, BigCommerce, Shoptet Premium and PrestaShop. See Default parsers for store integrations.
  • Any other source needs a parser written for it, by a developer or an AI agent such as Copilot. Copilot can write, dry-run and publish one from this page.

The parser runs on a schedule to populate the catalog. You write two functions; Octocom calls them in a loop, validates each mapped product against a schema, and writes the valid ones to the product index.

This page is the reference for the contract. For complete parsers to start from, see the examples:

The contract

Your parser must define exactly two top-level functions. The runtime looks them up by name and calls them in a loop until the feed is exhausted.

A few rules the runtime enforces:

  • Keep each fetch_next_chunk call short. Aim for under about 150 seconds per call. The per-call limit is 200 seconds by default, and dryrun_product_sync accepts perCallTimeoutSeconds up to 220. Make one chunk one HTTP round-trip or one streamed batch from disk.
  • map_one must be pure. No I/O, no network, no global mutation. It runs once per raw item and is expected to be fast.
  • Return DONE when the feed is exhausted. DONE and WAIT are pre-injected constants. Returning [] twice in a row also ends the run.
  • Return WAIT while the source isn't ready. For a bulk export that takes minutes to prepare, poll inside the call (sleep up to ~150 seconds), then return WAIT if it still isn't ready. The runtime calls again without treating it as the end of the feed. Every call counts toward the run's step budget, so don't return WAIT without waiting.
  • An exception fails the whole run. If fetch_next_chunk raises, the sync fails and nothing is published, so a feed that breaks halfway can never replace the catalog with half of it. If the source is flaky, catch and retry inside the call. Keep in mind that a generator which raised can't be resumed.

The state dict

state is a module-level dict that the runtime owns and passes to fetch_next_chunk on every call. The same dict instance is reused across calls within a sync run, so anything you stash in it survives. The keys that matter when you're writing a parser:

KeyTypeOwnerNotes
contextdictruntimeThe same dict your map_one(raw, context) receives. See below.
cursoranybothOpaque per-run cursor. Initialised from context.get('cursor'). You may overwrite it.
empty_streakintruntimeConsecutive empty fetch results. 2 or more ends the run.

The runtime also tracks a handful of read-only counters you never set yourself:

You own anything else you put in state. The example parsers keep their own state under state['parser']:

You can also use state['cursor'] directly when a single opaque value (page number, since-id, watermark) is enough.

The context dict

context is built once per run from the business's product sync configuration and passed to map_one(raw, context) (and available as state["context"]). Treat it as read-only.

When you call dryrun_product_sync(..., parserContext={...}) the extra keys are merged into context. Scheduled runs don't get a parserContext: anything you need at runtime that isn't on the business config has to be in the parser source, or read at runtime (for example store credentials with get_store_credentials()).

Output schema (map_one return value)

The runtime validates each non-None return value against the V4ProductInput schema (the full field set is documented below). The shape is flat: no nested variants, prices or collections. You collapse the source's structure into summary values, searchable text and an opaque rawJson string that carries everything else.

Return None from map_one to skip an item without counting it as an error. This is useful for inactive items, gift cards or filtered categories.

Product images

Keep image URLs inside the JSON encoded by rawJson. The schema has no top-level imageUrl or images field; adding either to the returned row fails validation.

Use a supported field name as the primary way to declare images: imageUrl, imageUrls, image_url, image, images, image_link, or additional_image_link. These fields accept a URL string, an object with a url or src field, or an array of those values. Put the primary photo first. Field names are case-sensitive.

URLs in these fields need no image extension, hostname prefix, or special path. The parser is responsible for supplying real image URLs. Use absolute HTTP(S) URLs; protocol-relative URLs (//host/path) are also supported. For example:

raw_out = dict(raw)
raw_out["imageUrls"] = [raw["photo_url"]]
# Set this field on the V4 row alongside its other required fields:
row["rawJson"] = json.dumps(raw_out, ensure_ascii=False)

The same supported fields work inside variants arrays, scoped to that variant. Supported-field URLs come first within each product or variant's gallery, regardless of the source JSON's key order.

Other image URLs are also detected: image-file suffixes such as .jpg or .webp, or image-related keys combined with asset-looking hosts or paths. These supply secondary gallery images, or the whole gallery when no supported field supplies a usable URL. If an image URL is missed, map it into a supported field and sync again.

Stock semantics: the three has*Variants booleans

These three booleans together describe what the customer can do with the product, and product search reads them to filter results. Get them wrong and the AI agent will either tell customers an unavailable item is in stock, or silently skip an item the store is happy to sell.

hasInStockVariantshasPreorderableVariantshasOnSaleVariantsMeaning
trueanyanyAt least one variant physically has inventory. Search returns it for in-stock queries.
falsetrueanyNo inventory, but at least one variant is orderable (backorder / pre-order / made-to-order).
falsefalseanyNothing is sellable. The AI agent will not surface this product for purchase intent.
anyanytrueAt least one variant is on sale. Used for "what's on sale" queries.

Be literal. hasInStockVariants is true only when the source says inventory exists. Don't bend it to make products show up: hasPreorderableVariants exists exactly so back-orderable items are still discoverable.

Include the actual availability state in rawJson (for example an availability field like "in stock", "backorder" or "out of stock") so the AI agent can quote a concrete label instead of guessing from the boolean.

Worked example for a feed with an explicit availability field per variant:

Product tags

tags is the one field in the schema whose values are yours to invent. Everything else describes the product the way the feed already does; a tag is a label the business puts on a product so the AI agent can filter on it: "vegan", "clearance", "made in italy", "b2b only", "prescription required".

A tag earns its place when both of these are true:

  1. A customer can ask for it by name. "Do you have anything vegan?" is a tag. "Show me the 45cm ones" is not: measurements are extracted from the product data automatically.
  2. Search can't answer it reliably from the text. If the word already appears in the title and description of every matching product, ordinary search finds them and a tag adds nothing.

Everything else (the category tree, the brand, the supplier code) belongs in embeddableContent and rawJson, which search already reads.

How the AI agent uses them

Tags are the only filter the AI agent can't guess at, so it is given the catalog's vocabulary explicitly: after each sync, Octocom collects the distinct tags in the catalog and lists them in the description of the product search tool's tags parameter. Any tag it filters with comes from that list, and it is told when it asks for anything else.

Being shown the vocabulary is not the same as knowing when to use it. The AI agent sees the tag names and one generic instruction; whether it reaches for a tag is its own judgment. In practice it uses tags whose meaning is obvious from the name and the customer's wording (vegan, clearance), and ignores ones whose meaning it would have to infer. A catalog whose tags encode markets, membership tiers or fulfillment routes needs a rule that explains them. See Teaching the AI agent when to use them.

That has two consequences worth designing around:

  • A tag the AI agent isn't shown is a tag it can't use. The vocabulary is capped at the 150 most-used tags. Below that cut, a tag exists on the row and filters correctly if something asks for it, but the AI agent is never told about it.
  • Tag names are prompt text. "gift-suitable" tells the AI agent what it means; "flag_7" doesn't. Name them the way a customer would say them.

Multiple tags combine either way: the AI agent can ask for products carrying any of a set (the default) or all of them.

Teaching the AI agent when to use them

For anything beyond a self-evident label, add a bot rule (in the dashboard, or with create_bot_rule) explaining what the tags mean and when to apply them. The rule doesn't need to list the tags, because the product search tool already does; it only needs their meaning and the conditions for using them.

A worked example. A parts retailer sells the same parts in seven markets and tags each product market:<xx> (sold there) and in-stock:<xx> (on the shelf there). With the vocabulary alone, the AI agent answered a customer who opened with "I'm in Germany" using an unfiltered search: the answer was correct, but it read the German price out of the product data afterwards rather than searching German-available stock. One rule that said what the two prefixes mean, when to apply them, and never to infer a market from the customer's language changed the next identical question into:

{
  "query": "torsion arm bush for front axle beam on 1963 Volkswagen Beetle",
  "tags": ["market:de", "in-stock:de"],
  "tagsMatch": "all"
}

Points worth covering in such a rule:

  • What each tag means, in one line each.
  • When to apply it, and just as important, when not to. "Only once the customer has told you where they are; never infer it from the language they write in."
  • What absence means. A product without in-stock:de may still be on backorder. Left unsaid, the AI agent reads a missing tag as "we don't sell it".

Spelling and folding

Tags are matched exactly, not searched. Before storage each value is lowercased, its whitespace collapsed, and the list deduplicated and sorted, so "Gluten Free", "gluten free" and " GLUTEN FREE " are one tag. Nothing else is normalized: "gluten-free" and "gluten free" stay two separate tags, and so do a singular and a plural. Pick a spelling and keep the parser emitting it.

Limits: 32 tags per product, 64 characters per tag, 150 tags in the vocabulary the AI agent is shown. Anything past those is dropped.

When tags take effect

Tags reach the product index on the next full sync after the parser starts emitting them; there is no separate backfill. Until then the AI agent isn't offered a tag filter at all, because the vocabulary it picks from is published by the same sync that writes the tags.

If a tag filter reaches a catalog with no tags in it (for example right after a parser is replaced), the search fails visibly rather than returning an empty list. An empty list would read as "this store sells nothing like that", and the AI agent would tell the customer so; instead it's told the filter couldn't run and searches again without it.

Because the vocabulary is republished on every successful sync, dropping a tag from the parser removes it from the AI agent's options on the next run.

Checking your work

  • Dry-run and search the output for "tags" (the download is gzip-compressed: curl -s "$URL" | gunzip | grep ...). The distinct set across the file is what the vocabulary will be built from. A run that produces hundreds of distinct values means something per-product (a SKU, a date, a full category path) is leaking into the field.
  • Then search with one. search_products (MCP) takes a tags argument that uses the same filter as the AI agent.

Runtime helpers

The runtime pre-injects a few things into the parser's globals. You don't need to import them.

fetch_via_proxy(url, *, headers=None, timeout=60, method='GET', data=None) -> bytes

Fetch a URL through Octocom's HTTP proxy, from a stable IP address, instead of the parser's default outbound IP. Use it when the origin blocks direct requests: symptoms include HTTPError 403, HTTPError 429, or unexplained urlopen timeouts on URLs that work fine in a browser.

See the full fetch_via_proxy helper docs for the standard try-direct-then-fallback pattern.

open_via_proxy(url, *, headers=None, timeout=60, method='GET', data=None)

Stream large feeds without buffering the entire response. Use with open_via_proxy(url) as response: and read bounded chunks with response.read(size). The response exposes .headers; preserve any existing truncation checks and retry policy. See the streaming example.

proxy_tcp_relay(host, port)

Provide a loopback TCP endpoint for drivers such as SQL Server clients. Keep the returned object alive in parser state, connect the driver to 127.0.0.1 and relay.port, and call relay.close() when finished. The helper handles proxy TLS and refreshed execution credentials. Database transport encryption remains the driver's responsibility. See TCP driver guidance.

get_store_credentials() -> dict

Credentials of the store integrations installed on the business being synced, keyed by integration name, for example {"shopify": {"domain": "acme.myshopify.com", "stores": [...]}, "prestaShop": {"storeUrl": ..., "apiKey": ...}}. Only catalog providers are included: shopify, woocommerce, bigCommerce, magento2, prestaShop and shoptetPremium. Help desk, payment and marketing integrations are never returned to a parser. Integrations without stored credentials are absent. Shopify has no token here: query it with shopify_graphql below.

Use it instead of putting API keys in the parser source, which anyone who can read the parser can see. Call it once at the start of a run and keep the result in state["parser"]. Never return credentials from map_one or print them. It only works inside a product sync: the run's access token is scoped to this business and revoked when the run ends.

A parser's access token (OCTOCOM_ORG_API_KEY) is scoped to the sync. It can read this business's store credentials, query its Shopify store with shopify_graphql, and read an organization secret by name, for example a database password: send POST {OCTOCOM_API_BASE_URL}/rest/private/secrets/resolve with the token in the X-API-Key header and a JSON body of {"name": "..."}. Other Octocom API calls from a parser return 403. Move work that needs them, such as reading articles or another business's data, to a Python action or recurring job.

shopify_graphql(query, variables=None, *, api_version, shop=None) -> dict

Run a Shopify Admin GraphQL query on the synced business's store. Octocom sends it from its own servers with the store's token, so the parser never holds one. api_version is required (for example "2026-10"); only versions Shopify still supports are accepted. shop names one of the business's stores by its myshopify.com domain; omit it for the first. Returns Shopify's response body (data, errors, extensions); throttling and network failures are retried. Raises urllib.error.HTTPError when Shopify or Octocom refuses the request. See shopify_graphql.

V4ProductInput

The schema class used to validate map_one's return. You usually don't reference it directly: the runtime builds it for you and reports validation failures in errors_sample.

Default parsers for store integrations

Connecting a Shopify, WooCommerce, BigCommerce, Shoptet Premium or PrestaShop store installs Octocom's default parser for that platform: the business gets its own copy. The copy reads the store's credentials with get_store_credentials() at sync time, so it contains no secrets. install_default_product_sync_parser installs it on demand, for example to reset an edited copy (force: true) or to pick up a newer default.

The Shopify default uses each product's Online Store URL. A product that is active but not published to the Online Store sales channel gets no URL and is marked hiddenFromStorefront, so storefront search leaves it out while the AI agent can still answer about it.

The copy is yours to edit like any parser. The parser records which default it came from, so a later reinstall or install_default_product_sync_parser call never overwrites your changes unless you pass force: true.

Version history

Every save of a parser is a version. list_product_sync_parser_versions shows who changed it and when, and restore_product_sync_parser_version puts an earlier version back. A restore changes only the code; the next scheduled sync runs it, or start one with fullrun_product_sync.

Iterating on a parser

  1. Sketch the parser by hand or with an AI agent. The static XML feed, multiple XML feeds and paginated JSON API examples cover the common shapes: adapt one to your source.
  2. Dry-run with the dryrun_product_sync MCP tool. It runs the parser end to end and produces a gzip-compressed JSONL file (output.jsonl.gz) without touching the live catalog. It returns an executionId; poll get_product_sync_execution for the result, download the file from the returned URL and decompress it (gunzip).
  3. Inspect the output. Spot-check products you know. Does hasInStockVariants match the source? Are prices sane? Does embeddableContent read like a description a human would search for? If you emit tags, check the distinct set across the whole file, not just one row.
  4. Save and go live with upsert_product_sync_parser. This saves the source and, if the business's product sync is off, turns it on: automatic sync is enabled and the first real sync starts within about a minute. Later updates leave the schedule alone, so you can iterate without immediately re-running the live sync.

Common pitfalls

  • Non-deterministic id. Hashing volatile data (timestamps, prices, computed flags) means every sync writes a fresh row and the catalog grows unboundedly. Hash the source's stable id only.
  • Setting hasInStockVariants=true for backorder items. Tempting (you want the AI agent to recommend them) but wrong: the AI agent will claim they're in stock. Use hasInStockVariants=false with hasPreorderableVariants=true. See Stock semantics.
  • Using tags as a category dump. Mapping the feed's whole category tree into tags buries the two or three labels a customer would actually ask for among hundreds the AI agent has to read past, and past 150 distinct values, the ones it's shown are simply whichever are most common. Categories already reach search through embeddableContent and rawJson.
  • Unstable tag spelling. Tags match exactly. A parser that emits the feed's raw label one run and a tidied version the next silently splits one tag into two, and half the catalog stops matching the filter the AI agent was told about.
  • Forgetting rawJson. The AI agent reads it when it decides to mention a product; without it, the AI agent has only name and shortDescription to work with. Always include "rawJson": json.dumps(raw, ensure_ascii=False).
  • Dumping JSON into embeddableContent. The embedding model is trained on natural language. JSON tokens dilute the signal. Build a plain-text description instead.
  • Empty embeddableContent. The row still uploads, but there is nothing to build the semantic search vector from, so the product won't surface in semantic search. At minimum: the name and one of the descriptions.
  • Mutating the chunk's raw items in map_one. map_one should be pure; if you need to derive lookup tables, build them once in fetch_next_chunk's initialization block.
  • Not clearing iter-parsed elements. When using xml.etree.ElementTree.iterparse, call elem.clear() after consuming each element or memory grows unboundedly on large feeds.

On this page