Every authenticated shape below is the documented shape, read from api.kosmobids.com/docs on 30 November 2026 — not something I ran. The only key on this machine is stats-only and answers 403 everywhere else. The 401 is real.
- Six calls do the work; the pipeline is the state you keep between them, not the calls.
- Search and matches return ids and scores only, so every decision needs
GET /tenders/{id}— and matches need the run'srunId, not the run record'sid. - Documents are the exception: 1,262 of 97,793 open tenders had files in the store on 26 November 2026.
- Everything long is polled, three flows use three status vocabularies, and
isFinalStatusis the only portable stop signal.
tender-pipeline/
pipeline.py # search → hydrate → fetch → read → answer, one run
state.sqlite3 # created on first run; the resume point
out/<tender_id>/ # tender.json, files.json, pages-<fileId>.txt, answers.json
What this is not: the ingest. Building the crawl — 81 sources, dedupe, one normalised record — is a different job with its own traps. Here you have a provider, or you are deciding whether to become one.
Stage 1 — Define the search once
{ "criteria": { "cpvCodes": [{ "code": "72000000", "includeDescendants": true }],
"contractingCountry": ["DE", "AT"], "submissionDeadlineAtLeastDays": 14 },
"options": { "type": "mixed", "recommendedFilter": "all", "sort": "deadline" } }
POST /api/v1/search takes criteria and options. Three things a first build ignores. A value filter hides tenders that never published a value unless you set skipUnknownValue, so minContractValueEur quietly shrinks the corpus. Relative and absolute windows cannot be mixed — submissionDeadlineAtLeastDays with submissionDeadlineBefore is a 422, not a merge. And ad-hoc search is bounded without saying how far: the reference for POST /api/v1/search documents no page-size parameter and its 200 carries results and no total (read 30 November 2026), so a one-off search is a sample you cannot measure — not a census.
That is why the pipeline runs on a saved search. POST /saved-searches stores the same criteria under a name, 10 per company (the eleventh answers 409), and every later stage inherits one copy of the filter.
Stage 2 — Collect the run and read fit
POST /saved-searches/{id}/runs with {"publishMatches": false} answers 200 with {"runId": …, "status": "new"}. That default is a preview: nothing lands in the company pipeline unless you publish it. The run is asynchronous, its vocabulary is its own (new → in_progress → done | error), and isFinalStatus turns true on done or error.
Then the trap that reads like an empty result. GET /saved-searches/{id}/runs returns run records, and a record's id is not what the matches endpoint wants:
{ "id": "run-record-id", "runId": "workflow-id", "status": "done", "triggerSource": "api" }
GET /saved-searches/{id}/runs/{runId}/matches needs runId; pass the record's id and you get a 404 that looks exactly like "this run found nothing". Keep the value from the trigger response and the problem never exists.
Matches are the only place you get a judgement: evaluation.fit ∈ match | industry_match | not_match, finalScore.score is an integer 1–5, warnings[] carries the red flags. Scores are comparative, not probabilities, and not comparable across searches or rerankers — store the fit label, use the score as a tie-breaker inside one run.
Stage 3 — Hydrate the shortlist
GET /tenders/{id} holds title, description, cpv_codes, submission_date, estimated_value_eur, contracting_country_iso, language and source_tender. Read the casing before you write a client: tender and notice models are snake_case, app models (/pipeline, run and match records) are camelCase, and the match record keeps tender_id. "The API is camelCase" is wrong.
Three field rules. estimated_value_eur can be null — missing is unknown, not zero, and pricing on nulls drops the tenders whose buyer published nothing. tenderId is a lot, not a notice: sibling lots come from GET /tenders/by-source/{sourceTenderId}, buyer contact and submission mechanics sit one level up at GET /notices/{noticeId}. And auth precedes lookup, so a guessed UUID answers 401 {"error":"Unauthorized","message":"Invalid API key"}, never 404 — you cannot probe which tenders exist.
Stage 4 — Decide whether documents exist at all
This stage separates a pipeline that runs for months from one that burns its quota in a week. The trigger has exactly four documented answers:
| HTTP | scheduled |
Meaning |
|---|---|---|
202 | true | A download workflow was created. |
200 | false | Already downloading or processing — safe to re-call. |
200 | false | Nothing to download: the workflow ran, no files found. |
404 | — | Tender, source tender id or document record missing. |
POST /tenders/{id}/documents/download — and the two 200s are not distinguishable from the body, so the file list is the only way to tell "in progress" from "nothing here". GET /tenders/{id}/files returns rows carrying two identifiers — id for the stored file, fileId for the processed document — plus lifecycle (active | archived | removed) and documentStatus (new | processed | error, null when the type is outside the OCR pipeline).
Now the base rate that justifies the gate: on 26 November 2026, 1,262 of 97,793 open tenders had files in the store, and 90 days came to 4,226 downloads (3,997 completed) — our own index, research/13. Documents are fetched on demand everywhere: a portal that login-walls its attachments yields the notice and not the paperwork. So stage 4 is one trigger and one bounded poll, and a tender that yields nothing is finished, never retried. That decision is most of your quota.
Stage 5 — Fetch and read
Two ids, and swapping them is the number one cause of 404 here. The row's id is the uploaded file — GET /files/{id}/download streams bytes. The row's fileId is the processed document — GET /documents/{fileId}/pages returns text. /documents/{fileId} accepts only the processed id, and a document still building answers 200 with status: "new" and empty pages, not 404.
{ "pageNumber": 12, "content": "1. Introduction\n…", "pageWidth": 2480, "pageHeight": 3508,
"uploadedFileId": "page-image-id",
"regions": [{ "index": 0, "content": "1. Introduction", "bbox_2d": [120, 340, 1800, 410] }] }
Supply both startPage and endPage to filter a range; supply neither for every page. bbox_2d is [x1, y1, x2, y2] in page-image pixels — divide by pageWidth/pageHeight before drawing, because the API returns coordinates, not an annotated image.
Why ranges are not a nicety: the corpus averages 12.3 pages per file and the largest document is 787 pages — 19,529 files, 18,577 processed, 227,961 pages (all-time, 26 November 2026, research/13). At a rough 1,200 tokens a page, an average document is ~15k tokens before the model thinks, and forty is 600k. Over 14 days to 2026-11-26 the mix was PDF 13,476 files (69%), DOCX 5,075 (26%), plus .dwg 616, .p7s 70 and .zip 21 that no text extractor reads.
Stage 6 — Answer with citations
POST /tenders/{id}/analyze takes 1–20 questions and answers 202 with {"workflowId": …, "status": "scheduled"}. No processed document is a 409 with "Documents not ready" — stage 4's answer, one stage late. The poll has the third vocabulary you meet: pending | running | waiting | retry then completed | failed | aborted. A failed workflow is a 200 with isFinalStatus: true, isStatusSuccess: false and a generic "Analysis failed"; polling never turns it into a success, so a retry means starting a new analysis.
{ "questionId": "q1", "answer": "… [Ref:1]",
"references": [{ "idx": 1, "fileId": "processed-document-id", "pageNumber": 12,
"regionIndex": 0, "uploadedFileId": "page-image-id", "filename": "specification.pdf" }] }
Three consequences. Questions get ids in order (q1, q2…), so store the question text beside the id or the answers are unjoinable next week. References carry both ids, which is what lets a reviewer open the page image and read the sentence. And analysis reads the tender documents plus your company's own knowledge documents, so two companies asking the same questions can get different answers — never merge analyses across tenants.
Stage 7-lite — Find what looks like the one you won
POST /tenders/{id}/look-alike with {"maxResults": 25, "onlyActiveTenders": true, "excludeSameSource": true, "grade": false} returns the nearest live tenders, each with score, submissionDate, country and source urls. maxResults is 1–100 with no pagination beyond the cap; both booleans default to true, which is right for monitoring and wrong when you are mapping a framework's sibling lots. grade: true adds an LLM judgement per result — slower, and it spends tokens. The endpoint reads global data, so it works on a tender you have never tracked.
The script, end to end
Standard library only, written against the documented shape — a client skeleton to check against a real key, not a transcript of a run.
#!/usr/bin/env python3
"""pipeline.py — search, hydrate, fetch, read, answer. Standard library only."""
import json, os, sqlite3, time, urllib.error, urllib.request
BASE = os.environ.get("KOSMOBIDS_BASE", "https://api.kosmobids.com/api/v1")
KEY = os.environ["KOSMOBIDS_API_KEY"] # never hardcode a key
SEARCH_ID = os.environ["SAVED_SEARCH_ID"]
DB, OUT = os.environ.get("TENDER_DB", "state.sqlite3"), os.environ.get("TENDER_OUT", "out")
QUESTIONS = ["Which certifications are mandatory?",
"What is the bid bond and when is it due?",
"Is a site visit or mandatory clarification meeting required?"]
STAGES = ["new", "hydrated", "files", "read", "answered"]
SCHEMA = """
create table if not exists tender(tender_id text primary key, fit text, score integer,
stage text not null default 'new', updated text);
create table if not exists doc(file_id text primary key, tender_id text not null,
filename text, pages integer default 0, chars integer default 0);
create table if not exists answer(tender_id text not null, question_id text not null,
question text, answer text, references_json text, primary key(tender_id, question_id));
"""
def call(method, path, body=None, attempts=5):
"""Retry only what the docs say: 429 after Retry-After, 502/503 with backoff, 500 once."""
data = json.dumps(body).encode() if body is not None else None
delay = 2.0
for attempt in range(attempts):
req = urllib.request.Request(BASE + path, data=data, method=method,
headers={"x-api-key": KEY, "content-type": "application/json",
"accept": "application/json", "user-agent": "tender-pipeline/1.0"})
try:
with urllib.request.urlopen(req, timeout=120) as resp:
return resp.status, json.loads(resp.read() or b"{}")
except urllib.error.HTTPError as err:
if err.code == 429:
time.sleep(float(err.headers.get("Retry-After", delay)))
continue
if err.code in (502, 503) and attempt < attempts - 1:
time.sleep(delay); delay = min(delay * 2, 60)
continue
if err.code == 500 and attempt == 0:
time.sleep(delay)
continue
raise RuntimeError("%s %s -> %s %s" % (method, path, err.code, err.read()[:300]))
raise RuntimeError("%s %s -> retries exhausted" % (method, path))
def connect():
conn = sqlite3.connect(DB)
conn.executescript(SCHEMA)
return conn
def stage(conn, tender_id):
row = conn.execute("select stage from tender where tender_id=?", (tender_id,)).fetchone()
return row[0] if row else "new"
def set_stage(conn, tender_id, fit, score, value):
conn.execute("insert into tender(tender_id, fit, score, stage, updated) "
"values (?,?,?,?,datetime('now')) on conflict(tender_id) do update "
"set stage=excluded.stage, updated=excluded.updated",
(tender_id, fit, score, value))
conn.commit()
def save(tender_id, name, payload):
folder = os.path.join(OUT, tender_id)
os.makedirs(folder, exist_ok=True)
with open(os.path.join(folder, name), "w", encoding="utf-8") as handle:
handle.write(payload if isinstance(payload, str)
else json.dumps(payload, ensure_ascii=False, indent=1))
def collect_run(conn):
"""Trigger one run, poll it, page the matches. Returns the shortlist."""
_, body = call("POST", "/saved-searches/%s/runs" % SEARCH_ID, {"publishMatches": False})
run_id, rows, offset = body["data"]["runId"], [], 0 # runId, NOT the record's `id`
while True:
_, page = call("GET", "/saved-searches/%s/runs/%s/matches?limit=500&offset=%d"
% (SEARCH_ID, run_id, offset))
data = page["data"]
if not data.get("isFinalStatus"):
time.sleep(20); continue # one poll at a time, never faster than 1/s
rows.extend(data.get("matchScores") or [])
offset += data.get("count") or 0
if offset >= (data.get("total") or 0):
break
shortlist = []
for row in rows:
fit, score = row["evaluation"]["fit"], row["finalScore"]["score"]
set_stage(conn, row["tender_id"], fit, score, "new")
if fit != "not_match":
shortlist.append((row["tender_id"], fit, score))
return shortlist
def hydrate(conn, tender_id):
_, body = call("GET", "/tenders/%s" % tender_id)
save(tender_id, "tender.json", body["data"]["tender"])
def files_and_trigger(conn, tender_id, wait_s=900):
"""202 created a workflow; 200 means already running OR nothing to download —
`scheduled` is false for both, so the file list is the only way to tell."""
status, _ = call("POST", "/tenders/%s/documents/download" % tender_id)
if status == 202:
print("%s: download scheduled" % tender_id)
started = time.time()
while time.time() - started < wait_s:
_, listing = call("GET", "/tenders/%s/files" % tender_id)
files = listing["data"]["files"]
save(tender_id, "files.json", files)
for row in files:
if row.get("documentStatus") == "processed" and row.get("fileId"):
conn.execute("insert or ignore into doc(file_id, tender_id, filename) "
"values (?,?,?)", (row["fileId"], tender_id, row["filename"]))
conn.commit()
if files and not [r for r in files if r.get("documentStatus") == "new"]:
return len(files)
if not files and time.time() - started > 120:
return 0 # nothing came back; do not poll for the full hour
time.sleep(30)
return -1 # timed out: stage unchanged, resume tomorrow
def read_pages(conn, tender_id, max_pages=40):
for (file_id,) in conn.execute("select file_id from doc where tender_id=?", (tender_id,)):
_, body = call("GET", "/documents/%s/pages?startPage=1&endPage=%d" % (file_id, max_pages))
pages = body["data"]["pages"]
text = "\n".join("[p%s] %s" % (p["pageNumber"], p["content"]) for p in pages)
conn.execute("update doc set pages=?, chars=? where file_id=?",
(len(pages), len(text), file_id))
save(tender_id, "pages-%s.txt" % file_id, text)
conn.commit()
def answer(conn, tender_id, wait_s=1800):
_, body = call("POST", "/tenders/%s/analyze" % tender_id, {"questions": QUESTIONS})
workflow_id, started = body["data"]["workflowId"], time.time()
while time.time() - started < wait_s:
_, result = call("GET", "/analyses/%s" % workflow_id)
data = result["data"]
if not data.get("isFinalStatus"):
time.sleep(20); continue
if not data.get("isStatusSuccess"):
return None # failed: a new analysis is the only retry
save(tender_id, "answers.json", data.get("answers") or [])
for row in data.get("answers") or []:
conn.execute("insert or replace into answer values (?,?,?,?,?)",
(tender_id, row["questionId"], QUESTIONS[int(row["questionId"][1:]) - 1],
row["answer"], json.dumps(row["references"])))
conn.commit()
return data.get("answers")
return None
def main():
conn = connect()
for tender_id, fit, score in collect_run(conn):
current = stage(conn, tender_id)
if STAGES.index(current) < 1:
hydrate(conn, tender_id)
set_stage(conn, tender_id, fit, score, "hydrated"); current = "hydrated"
if STAGES.index(current) < 2:
found = files_and_trigger(conn, tender_id)
if found == 0:
set_stage(conn, tender_id, fit, score, "read"); continue
if found < 0:
continue # unchanged stage; tomorrow resumes here
set_stage(conn, tender_id, fit, score, "files"); current = "files"
if STAGES.index(current) < 3:
read_pages(conn, tender_id)
set_stage(conn, tender_id, fit, score, "read"); current = "read"
if STAGES.index(current) < 4 and answer(conn, tender_id):
set_stage(conn, tender_id, fit, score, "answered")
if __name__ == "__main__":
main()
The state table that makes a rerun free
| Table | Primary key | Guards |
|---|---|---|
tender | tender_id (lot uuid) | one row per lot; stage is the resume point |
doc | file_id (processed document) | page text written once per document |
answer | (tender_id, question_id) | a rerun replaces rather than appends |
insert or ignore on doc and insert or replace on answer make the run idempotent: run it twice and the second writes nothing new. The ladder is new → hydrated → files → read → answered, and a step runs only when the row is behind it. The asymmetry that matters: a tender with no files is finished and never retried, because that is a fact about the portal — while a timed-out tender keeps its stage and resumes tomorrow. A JSON manifest per tender does the same job if you would rather not carry a database; SQLite ships with Python.
Stage, endpoint, wait, limit
The waits are the docs' own statements about the asynchronous steps. No p50 is published for a synchronous call, so none is invented here.
| Stage | Endpoint | Typical wait | Limit that applies |
|---|---|---|---|
| 1. Search | POST /search | one request | bounded; no number published |
| 1. Store criteria | POST /saved-searches | one request | 10 per company, then 409 |
| 2. Trigger a run | POST …/runs | returns immediately | one workflow per trigger |
| 2. Poll a run | GET …/runs/{runId}/matches | "minutes to tens of minutes" | limit 1–500, default 25 |
| 2. List runs | GET …/runs | one request | limit 1–100, default 50 |
| 3. Hydrate | GET /tenders/{id} | one request | one lot per call |
| 4. Trigger files | POST /tenders/{id}/documents/download | returns 202 at once | one workflow per tender |
| 4. List files | GET /tenders/{id}/files | one request | 404 without a source tender id |
| 5. Read pages | GET /documents/{fileId}/pages | one request | both bounds, or every page |
| 6. Start analysis | POST /tenders/{id}/analyze | returns 202 at once | 1–20 questions |
| 6. Poll analysis | GET /analyses/{workflowId} | not published; ≥1 s apart | one workflow per request |
Under all of it: 3 requests a second, 100 a minute, 1,000 an hour per company, tighter per-minute caps on search, analysis, look-alike and run triggers, uploads at 60 an hour (reference/limits, read 2026-11-30). Every authenticated response carries x-rate-limit-second|minute|hour-limit, -remaining and -reset; a 429 carries Retry-After.
What makes it safe to leave running
Pagination can lie about finishing. Pipeline pages use an opaque cursor with hasMore, and a page may hold fewer items than limit while hasMore is true — rows whose tender is missing are omitted server-side and the request still answers 200. Never stop on a short page; stop on hasMore: false or nextCursor: null. Matches report count (this page) and total (everything matching the filter), so page while offset + count < total.
Retry by status, not by hope. 502/503 → backoff. 429 → only after Retry-After, or use the -reset headers instead of fixed sleeps. 500 → one retry, then alert: it is a bug on the far side and looping hides it. 401, 403, 404, 409, 422 → never without changing the request; a 422 is a list of field-level issues, a 409 ("Documents not ready", the 11th saved search) is state you must change first.
202 and 200 differ on the trigger. 202 scheduled a workflow; 200 means already running or nothing to fetch, and the body does not say which. Read the file list, not the status line.
Three flows, three vocabularies. Runs: new → in_progress → done | error. Analyses: pending | running | waiting | retry → completed | failed | aborted. Downloads have no status endpoint — you watch the file list fill. The portable signal is isFinalStatus, with isStatusSuccess for the outcome; never compare status == "done" across flows. There are no webhooks in v1, so every long step is a poll, and a client timeout shorter than the work is the classic bug. A wrong path answers HTML (<pre>Cannot GET /api/v1/…</pre>), not the JSON envelope — branch on status, then content type.
What this pipeline cannot fix
- Freshness. Median publish-to-indexed lag was 57 hours on a four-day sample of 48,158 notices (to 2026-11-26), and 60 of 81 sources are read weekly or slower — a batched portal cannot beat its cadence.
- Documents are on demand. 1,262 of 97,793 open tenders had files that day; login-walled portals yield the notice, not the paperwork.
- Four EU members are TED-only (CY, IE, LT, LU): below-threshold work there is in nobody's European-only build.
- No OCR accuracy figure exists — 227,961 pages processed, no published measurement, ours included.
- Fit is a judgement. The docs say scores and fit are "not a substitute for reading the tender documents". Your citations are the defence.
FAQ
Do I need an API at all, or can I build this on TED?
TED carries above-threshold EU notices with no key, and the ingest route is real work but not impossible. An API buys three things: below-threshold flow (79.5% of the 5,976 notices a day in the 28 days to 2026-11-26 came from national sources), a document fetch you do not maintain, and fit scores to rank a shortlist before you read it.
How many calls does one tender cost?
Six: tender detail, the download trigger, the file list, one /pages call per document, POST /analyze, then /analyses/{workflowId} until final. Polling adds calls; at 1,000 requests an hour you can carry roughly forty tenders an hour with a couple of polls each.
Why do my matches come back empty for a run that finished?
Almost always the id. GET /saved-searches/{id}/runs returns records whose id is a record id, while the matches endpoint wants runId — and a mismatch answers 404, which reads like "no matches". Take runId from the trigger response.
Can I analyse a tender that has no documents?
Not from the procurement source: POST /analyze answers 409 with "Documents not ready" until one document is processed. You can unblock it by uploading your own file to POST /tenders/{id}/files, which works even when the notice has no source files.
Why does /documents/{fileId} return 404 after I listed the files?
You passed the row's id, not its fileId. The list carries both: id is the uploaded file for GET /files/{id}/download, fileId is the processed document for /documents/{fileId} and /pages. A document still building answers 200 with status: "new", not 404.
How do I stop a nightly rerun from re-downloading and re-OCRing?
Keep a stage per tender and a row per processed fileId, write with insert or ignore, and trigger only when the row is behind. Mark "no files found" as finished so it is never retried; leave a timeout at its old stage so it resumes.
Is there a webhook when a download or an analysis finishes?
No. There are no webhooks in v1: work that cannot finish inside a request is scheduled and reported through a status field or a polling endpoint. Poll the file list for documents and /analyses/{workflowId} for answers, no faster than once a second, and stop on isFinalStatus.
Sources
research/05-product-facts.md— 25 operations over 21 paths, the DOCUMENTED vs EXECUTED split, the executed 401/403/404 shapes, the two-id document model (captured 2026-11-25).research/13-answers-from-prod.md— 1,262 of 97,793 open tenders with files; 4,226 downloads in 90 days; 19,529 files / 18,577 processed / 227,961 pages; 12.3 pages per file; 787-page maximum; PDF 69% / DOCX 26% over 14 days; 57 h median lag; 5,976 notices a day from 81 sources, 20.5% TED (measured 2026-11-26).research/11-coverage-methodology.md— publication lag, corrigenda, duplicates, document loss (2026-11-26);research/10-documents-and-ocr-cost.md— delivery shapes and OCR cost (2026-11-26).- docs/reference/limits · concepts/errors-and-limits — rate windows and headers, page sizes, status and retry tables, the two error envelopes (read 2026-11-30).
- concepts/documents-and-ocr · concepts/document-analysis — 202/200/404 on the trigger, the two ids, page and region shape, the
409, workflow states, reference shape (read 2026-11-30). - concepts/saved-searches-and-runs · tutorials/find-and-qualify-tenders · tutorials/look-alike-discovery —
runIdvs recordid, run vocabulary,count/total, criteria andskipUnknownValue,maxResultsandgrade(read 2026-11-30).
Sibling posts: tender APIs compared, how to get tender data, tender MCP servers. The same stages over MCP tools: /mcp/; the HTTP surface they mirror: /api/.