{% extends "base.html" %} {% block title %}API Documentation{% endblock %} {% block content %} {% raw %}

Lead Miner API

Lead Miner runs entirely on your own machine and exposes a small HTTP API on http://127.0.0.1:<PORT>. The port is picked at random between 9001 and 9999 on every launch, so read it from the terminal line Lead Miner is running at ….

There is no authentication. The server only listens on localhost and is intended for the bundled web UI and your own local scripts. All request and response bodies are JSON unless noted otherwise.

Base URL http://127.0.0.1:<PORT> Auth none Formats JSON · NDJSON · SSE

Common contract

Every response carries two diagnostic headers. Errors are returned as a small JSON envelope with a machine-readable message and the same request id.

Response headers

HeaderDescription
X-Request-ID Echoes the request's X-Request-ID header, or a generated UUID. Use it to correlate a response with the server log.
X-Response-Time-Ms Time the server spent handling the request, in milliseconds (e.g. 412.7).

Error envelope

Every handled error returns this shape (FastAPI's own 422 validation errors use a different, standard shape — see below):

{
  "error": "Unknown queries file: ghost.csv",
  "request_id": "3f1c9a2b4e7d4c1e8a0f6b2d5c9e1a37"
}
GET /api/query-files

List every selectable queries CSV: the files in the queries/ folder plus the configured default CSV. The configured default is flagged with is_default.

Parameters

None.

Response 200 OK

{
  "total": 2,
  "default": "queries_2026-09-07.csv",
  "files": [
    {
      "name": "b2b_queries_2026-09-16.csv",
      "is_default": false,
      "size": 4096,
      "modified": "2026-09-16T10:12:03+00:00"
    },
    {
      "name": "queries_2026-09-07.csv",
      "is_default": true,
      "size": 8192,
      "modified": "2026-09-07T09:00:00+00:00"
    }
  ]
}
curl
curl http://127.0.0.1:9123/api/query-files
Python
import requests

files = requests.get("http://127.0.0.1:9123/api/query-files").json()
for entry in files["files"]:
    label = " (default)" if entry["is_default"] else ""
    print(entry["name"] + label)
JavaScript
const res = await fetch("http://127.0.0.1:9123/api/query-files");
const { files, default: defaultFile } = await res.json();

console.log(files.map(f => f.name), "default:", defaultFile);
POST /api/query-files

Upload a queries CSV. The file is copied into the queries/ folder and becomes immediately selectable. The CSV must contain the columns Keyword, Purpose, and Query.

Request body (multipart/form-data)

FieldTypeRequiredDescription
file file required A .csv file with Keyword, Purpose, and Query columns.

Response 200 OK

{
  "name": "my_leads.csv",
  "is_default": false,
  "size": 128,
  "modified": "2026-09-20T15:00:00+00:00"
}

Errors

StatusWhen
400The upload is not a .csv, or its columns are missing / rows are invalid.
curl
curl -F "file=@my_leads.csv;type=text/csv" \
  http://127.0.0.1:9123/api/query-files
Python
import requests

with open("my_leads.csv", "rb") as handle:
    res = requests.post(
        "http://127.0.0.1:9123/api/query-files",
        files={"file": ("my_leads.csv", handle, "text/csv")},
    )

print(res.json()["name"])
JavaScript
const form = new FormData();
form.append("file", fileInput.files[0]);

const res = await fetch("http://127.0.0.1:9123/api/query-files", {
  method: "POST",
  body: form,
});
const uploaded = await res.json();
console.log(uploaded.name);
GET /api/queries

Return the parsed rows of a queries CSV. Omitting file reads the configured default CSV.

Query parameters

NameTypeRequiredDescription
file string optional File name from GET /api/query-files. Defaults to the configured queries CSV.

Response 200 OK

{
  "total": 1,
  "queries": [
    {
      "keyword": "meilleur logiciel email marketing",
      "purpose": "email",
      "query": "\"meilleur logiciel email marketing\" \"Maroc\" email"
    }
  ]
}

Errors

StatusWhen
400The requested file is not one of the managed files.
500The default CSV is missing, has the wrong headers, or contains no valid rows.
curl
curl "http://127.0.0.1:9123/api/queries?file=queries_2026-09-07.csv"
Python
import requests

rows = requests.get(
    "http://127.0.0.1:9123/api/queries",
    params={"file": "queries_2026-09-07.csv"},
).json()["queries"]

for row in rows:
    print(row["keyword"], "-", row["query"])
JavaScript
const params = new URLSearchParams({ file: "queries_2026-09-07.csv" });
const res = await fetch(`http://127.0.0.1:9123/api/queries?${params}`);
const { queries } = await res.json();

for (const row of queries) console.log(row.keyword, "-", row.query);
POST /api/extract

Run one search query end to end: search the web, crawl the result pages, extract and de-duplicate contact emails, and save them to a dedicated CSV in output/.

Request body (application/json)

FieldTypeRequiredDescription
query string required The search query. 1–2000 characters, must not be blank.
keyword string optional Keyword group this query belongs to. Defaults to "".
max_results integer optional Search results to crawl. 1–50. Defaults to 10.
url_keywords string[] optional Only crawl result URLs containing at least one of these keywords (case-insensitive). Defaults to [] (crawl all).
geo_locations string[] optional Keep only pages whose country domain, domain, URL, or content matches a geo term (e.g. ["ma", "Maroc"]). Applied after crawling. Defaults to [].

Response 200 OK

{
  "query": "\"meilleur logiciel email marketing\" \"Maroc\" email",
  "keyword": "email marketing",
  "requested_max_results": 10,
  "scanned_urls": 8,
  "matched_urls": 5,
  "skipped_urls": 3,
  "found_emails": 2,
  "emails": [
    {
      "email": "contact@example.ma",
      "source_url": "https://example.ma/contact",
      "url_keywords": ["contact"],
      "geo_locations": ["ma"]
    }
  ],
  "saved_file": "emails_email-marketing_2026-09-20_150000.csv",
  "url_keywords": ["contact"],
  "geo_locations": ["ma"]
}
FieldDescription
scanned_urlsURLs that passed the URL keyword filter and were crawled.
matched_urlsURLs that survived every filter.
skipped_urlsSearch results removed by the URL keyword / geo filters.
found_emailsNumber of unique emails in emails.
saved_fileFile name written under output/, or "" when nothing was found.

Errors

StatusWhen
422The body fails schema validation (blank query, max_results outside 1–50, missing required field).
429The search engine rate-limited the request.
502Search failed (proxy/network) or a page could not be fetched.
504The search engine timed out.
curl
curl -X POST http://127.0.0.1:9123/api/extract \
  -H "Content-Type: application/json" \
  -d '{
    "query": "\"meilleur logiciel email marketing\" \"Maroc\" email",
    "keyword": "email marketing",
    "max_results": 10,
    "url_keywords": ["contact"],
    "geo_locations": ["ma"]
  }'
Python
import requests

payload = {
    "query": '"meilleur logiciel email marketing" "Maroc" email',
    "keyword": "email marketing",
    "max_results": 10,
    "url_keywords": ["contact"],
    "geo_locations": ["ma"],
}

res = requests.post("http://127.0.0.1:9123/api/extract", json=payload)
data = res.json()

print(data["found_emails"], "emails ->", data["saved_file"])
for row in data["emails"]:
    print(row["email"], row["source_url"])
JavaScript
const payload = {
  query: '"meilleur logiciel email marketing" "Maroc" email',
  keyword: "email marketing",
  max_results: 10,
  url_keywords: ["contact"],
  geo_locations: ["ma"],
};

const res = await fetch("http://127.0.0.1:9123/api/extract", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(payload),
});
const data = await res.json();

console.log(data.found_emails, "emails ->", data.saved_file);
POST /api/extract-batch

Run many queries sequentially and stream progress as it happens. Emails are de-duplicated across the whole run and saved once to a combined CSV. The response is newline-delimited JSON (application/x-ndjson): one JSON object per line. A query that fails is recorded and skipped — it never aborts the batch.

Request body (application/json)

FieldTypeRequiredDescription
mode string required One of first_n, selected, or all.
n integer first_n only How many queries to run, in CSV order. 1–number of queries.
queries string[] selected only Exact query strings to run, in CSV order. Must match queries in the file.
max_results integer optional Results to crawl per query. 1–50. Defaults to 10.
file string optional Queries CSV to run. Defaults to the configured queries CSV.
url_keywords string[] optional URL keyword filter, applied to every query. Defaults to [].
geo_locations string[] optional Geo filter, applied to every query after crawling. Defaults to [].

Streamed events

Each line is one event. The first is always start; the last is always result.

start
{"event": "start", "total": 3, "run_id": "9f2c…"}
progress Emitted after each query completes.
{"event": "progress", "done": 1, "total": 3, "keyword": "email marketing", "query": "…", "found": 2}
query_error Emitted instead of progress when a query fails.
{"event": "query_error", "done": 2, "total": 3, "keyword": "…", "query": "…", "error": "rate limited", "detail": {}}
result Final event. Carries the whole run's summary and emails.
{
  "event": "result",
  "mode": "first_n",
  "total_queries": 3,
  "completed_queries": 3,
  "failed_queries": 0,
  "scanned_urls": 24,
  "matched_urls": 18,
  "skipped_urls": 6,
  "found_emails": 5,
  "emails": [
    {
      "email": "contact@example.ma",
      "source_url": "https://example.ma/contact",
      "keyword": "email marketing",
      "query": "…",
      "url_keywords": ["contact"],
      "geo_locations": ["ma"]
    }
  ],
  "saved_file": "emails_combined_2026-09-20_150000.csv",
  "failures": [],
  "stopped": false,
  "url_keywords": ["contact"],
  "geo_locations": ["ma"]
}

Errors

StatusWhen
400Unknown mode, out-of-range n, empty selected list, unknown file, or no queries available.
422The body fails schema validation.
curl
curl -N -X POST http://127.0.0.1:9123/api/extract-batch \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "first_n",
    "n": 3,
    "max_results": 10,
    "file": "queries_2026-09-07.csv",
    "url_keywords": ["contact"],
    "geo_locations": ["ma"]
  }'
Python
import json
import requests

payload = {
    "mode": "first_n",
    "n": 3,
    "max_results": 10,
    "file": "queries_2026-09-07.csv",
}

with requests.post(
    "http://127.0.0.1:9123/api/extract-batch", json=payload, stream=True
) as res:
    for line in res.iter_lines():
        if not line:
            continue
        event = json.loads(line)
        if event["event"] == "progress":
            print(f"{event['done']}/{event['total']} - {event['query']}")
        elif event["event"] == "result":
            print(event["found_emails"], "unique emails ->", event["saved_file"])
JavaScript
const res = await fetch("http://127.0.0.1:9123/api/extract-batch", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ mode: "first_n", n: 3, max_results: 10 }),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";

for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });

  let newline;
  while ((newline = buffer.indexOf("\n")) >= 0) {
    const line = buffer.slice(0, newline).trim();
    buffer = buffer.slice(newline + 1);
    if (line) handleEvent(JSON.parse(line));
  }
}

function handleEvent(event) {
  if (event.event === "progress") console.log(event.done, "/", event.total);
  if (event.event === "result") console.log(event.found_emails, "unique emails");
}
POST /api/extract/stop

Stop a running batch. It ends within a second or two, abandoning the query in progress, then finishes like any batch: the emails found so far are saved to the combined CSV and the stream's last line is the usual result, with "stopped": true. The run_id is in the batch's start event.

Request body (application/json)

FieldTypeRequiredDescription
run_id string required The batch to stop, from its start event.

Response

{"stopping": true}

Errors

StatusWhen
404No batch with that run_id is running (it may have just finished).
422The body fails schema validation.
curl
curl -X POST http://127.0.0.1:9050/api/extract/stop   -H "Content-Type: application/json"   -d '{"run_id": "9f2c…"}'
GET /api/search-usage

How many searches each engine was sent per day, and how it responded. Free engines allow a limited number of searches per day from one connection; the first_refusal_after reading measures that allowance. Newest day first, up to 14 days kept. Engines reached through ddgs share one row named ddgs.

Query parameters

NameDescription
daysHow many days to return, 1–14. Default 7.

Response

{
  "days": [
    {
      "date": "2026-09-21",
      "engines": [
        {"engine": "brave", "sent": 131, "answered": 118, "empty": 8,
         "refused": 5, "failed": 0, "first_refusal_after": 96}
      ]
    }
  ]
}
FieldDescription
answeredReturned at least one result.
emptyReplied with no results.
refusedCAPTCHA, too many requests, or access denied.
failedTimed out or another error.
first_refusal_afterRequests the engine had already handled that day when it first refused. null if it has not refused.
curl
curl http://127.0.0.1:9123/api/search-usage?days=3
GET /api/logs/stream

A Server-Sent Events (text/event-stream) feed of live activity from the backend: search, crawl, filter, extract, dedupe, save, and done steps. Useful for building your own progress UI. The connection is kept open; a comment heartbeat (: keep-alive) is sent every 15 seconds when idle.

Event data

{
  "ts": "2026-09-20T15:00:00+00:00",
  "level": "info",
  "step": "search",
  "message": "Searching the web…",
  "run_id": "…",
  "query_id": "…",
  "data": {}
}
FieldDescription
tsUTC ISO-8601 timestamp.
levelinfo, warning, or error.
stepPhase name, e.g. start, query, search, fetch, filter, extract, dedupe, save, done, error.
messageHuman-readable description.
run_idGroups events from one extraction run.
query_idGroups events from one query within a run.
dataVerbose technical detail (URLs, counts, failures). May be empty.

Raw frames

: connected

data: {"ts":"2026-09-20T15:00:00+00:00","level":"info","step":"search","message":"Searching the web…","run_id":"…","query_id":"…","data":{}}

: keep-alive
curl
curl -N http://127.0.0.1:9123/api/logs/stream
Python
import json
import requests

with requests.get("http://127.0.0.1:9123/api/logs/stream", stream=True) as res:
    for raw in res.iter_lines(decode_unicode=True):
        if raw and raw.startswith("data: "):
            event = json.loads(raw[len("data: "):])
            print(event["step"], event["message"])
JavaScript
const source = new EventSource("http://127.0.0.1:9123/api/logs/stream");

source.onmessage = (event) => {
  const log = JSON.parse(event.data);
  console.log(log.level, log.step, log.message);
};

source.onerror = () => console.warn("stream interrupted, reconnecting…");
POST /api/generate

Generate a keyword report from a single seed keyword. The seed is sanitized, a prompt is built from the saved templates, the active AI provider is called, and the response is parsed, validated, de-duplicated, and filtered to the selected intents.

Request body (application/json)

FieldTypeRequiredDescription
seed string required The starting keyword. 1–100 characters, must not be blank.
mode string optional lead_mining, the only mode (and the default): entity footprints, the kinds of organisation and person that exist in a niche and have an inbox. Lead mining pins its own intents and adds an entity_type to every row. (The former KeyGold SEO mode was removed; "seo" is rejected.)
location string optional Target market, e.g. Casablanca, Morocco. Max 100 characters.
count integer optional Keywords to generate. 10–50. Defaults to 30.
language string optional Output language. Defaults to English. See Enumerations.
intents string[] optional Search intents to keep. Defaults to all four. Values are case-insensitive and normalized; results are post-filtered to the selected intents.

Response 200 OK

{
  "seed": "running shoes",
  "requested_count": 30,
  "generated_count": 1,
  "keywords": [
    {
      "keyword": "best running shoes",
      "intent": "Commercial",
      "pain_point": "Need comfortable shoes",
      "buyer_intent": true,
      "related_terms": ["running shoes review", "top running shoes"],
      "popularity": 78
    }
  ]
}
FieldDescription
requested_countThe count you asked for.
generated_countNumber of keywords actually returned after dedupe + intent filtering.
popularityAI-estimated score 1–100, or null when not provided.

Errors

StatusWhen
422Schema validation failed (blank/oversized seed, count outside 10–50, unknown language or intent).
400The seed contains disallowed characters or injection tokens.
500AI provider auth error (bad/missing API key, or no credit) or the AI response could not be parsed.
502AI provider upstream error, including rate limiting.
504The AI provider timed out.
curl
curl -X POST http://127.0.0.1:9123/api/generate \
  -H "Content-Type: application/json" \
  -d '{
    "seed": "running shoes",
    "count": 30,
    "language": "English",
    "intents": ["Commercial", "Transactional"]
  }'
Python
import requests

payload = {
    "seed": "running shoes",
    "count": 30,
    "language": "English",
    "intents": ["Commercial", "Transactional"],
}

res = requests.post("http://127.0.0.1:9123/api/generate", json=payload, timeout=120)
data = res.json()

print(data["generated_count"], "keywords for", data["seed"])
for row in data["keywords"]:
    print(row["intent"], "-", row["keyword"])
JavaScript
const res = await fetch("http://127.0.0.1:9123/api/generate", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    seed: "running shoes",
    count: 30,
    intents: ["Commercial", "Transactional"],
  }),
});
const data = await res.json();

console.log(data.generated_count, "keywords");
for (const row of data.keywords) console.log(row.intent, "-", row.keyword);
POST /api/generate-queries

Build advanced search queries for a list of keywords. Optionally geo-target a location, restrict to specific websites, and steer email queries toward business (B2B) or personal (B2C) inboxes.

Request body (application/json)

FieldTypeRequiredDescription
keywords string[] required Keywords to build queries for. At least one non-empty value; max 500.
mode string optional lead_mining (the only mode, and the default).
purposes string[] required Contact targets, e.g. email, phone, linkedin. At least one.
language string optional Output language. Defaults to English.
location string optional City, region, or country to geo-target. Max 100 characters; empty means global.
niche string optional The niche in your own words (Riads, wedding planners). With a country in location, the run is learned in that niche + country scope, registered on first use: shape scores, skipped sites, known leads and verdicts all stay there, and shapes the niche has not tried yet borrow the best-trained ranking. Empty, or a country this build does not know: learned for the whole country, as before. Max 100 characters.
sites string[] optional Restrict queries to these domains. Max 50. Entries are normalized (scheme/www/path stripped, lowercased).
email_type string optional b2b or b2c (case-insensitive). Only affects email queries. Defaults to null.

Response 200 OK

{
  "keyword_count": 1,
  "total_queries": 2,
  "purposes": ["email"],
  "results": [
    {
      "keyword": "running shoes",
      "queries": [
        {"query": "\"running shoes\" email contact", "purpose": "email"},
        {"query": "\"running shoes\" @gmail.com", "purpose": "email"}
      ]
    }
  ],
  "scope": "ma-riads-lead_mining"
}

scope: where the run is learned, its niche + country (ma-riads-lead_mining) or its country (ma-lead_mining).

Errors

StatusWhen
422Schema validation failed (empty keywords/purposes, unknown email_type, oversized input).
400A site entry is not a valid domain, or input contains disallowed characters.
curl
curl -X POST http://127.0.0.1:9123/api/generate-queries \
  -H "Content-Type: application/json" \
  -d '{
    "keywords": ["running shoes"],
    "purposes": ["email", "linkedin"],
    "language": "English",
    "location": "Casablanca",
    "sites": ["example.com"],
    "email_type": "b2b"
  }'
Python
import requests

payload = {
    "keywords": ["running shoes"],
    "purposes": ["email", "linkedin"],
    "location": "Casablanca",
    "email_type": "b2b",
}

res = requests.post(
    "http://127.0.0.1:9123/api/generate-queries", json=payload, timeout=120
)
data = res.json()

print(data["total_queries"], "queries across", data["keyword_count"], "keywords")
for group in data["results"]:
    for item in group["queries"]:
        print(group["keyword"], "|", item["purpose"], "|", item["query"])
JavaScript
const res = await fetch("http://127.0.0.1:9123/api/generate-queries", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    keywords: ["running shoes"],
    purposes: ["email", "linkedin"],
    location: "Casablanca",
    email_type: "b2b",
  }),
});
const data = await res.json();

for (const group of data.results) {
  for (const item of group.queries) console.log(item.purpose, "|", item.query);
}
GET /api/prompts

Read the currently saved prompt templates (the values used by keyword generation). Falls back to built-in defaults if prompts_config.json is missing or invalid.

Parameters

None.

Response 200 OK

{
  "keywords_leadmining_system_prompt": "You are a precise data-generation assistant. …",
  "keywords_leadmining_user_template": "Generate exactly {count} keywords … in {language}. {intents} …"
}
curl
curl http://127.0.0.1:9123/api/prompts
Python
import requests

prompts = requests.get("http://127.0.0.1:9123/api/prompts").json()
print(prompts["keywords_leadmining_user_template"][:120])
JavaScript
const prompts = await fetch("http://127.0.0.1:9123/api/prompts").then((r) => r.json());
console.log(Object.keys(prompts));
GET /api/prompts/defaults

Read the factory-default prompt templates. Use this to offer a "Reset to defaults" action without having to ship the defaults client-side.

Parameters

None.

Response 200 OK

Same two fields as GET /api/prompts, with factory values.

curl
curl http://127.0.0.1:9123/api/prompts/defaults
Python
import requests

defaults = requests.get("http://127.0.0.1:9123/api/prompts/defaults").json()
          
JavaScript
const defaults = await fetch(
  "http://127.0.0.1:9123/api/prompts/defaults"
).then((r) => r.json());
console.log(defaults.keywords_leadmining_system_prompt);
PUT /api/prompts

Save prompt templates to prompts_config.json. Unknown keys are ignored and values are coerced to strings. Placeholders available to the templates: {seed}, {count}, {language}, {intents}, {keywords}, {purposes}, {location}, {sites}, {email_type}, {query_targets}.

Request body (application/json)

FieldTypeRequiredDescription
keywords_leadmining_system_promptstringoptionalSystem prompt for keyword generation.
keywords_leadmining_user_templatestringoptionalUser template for keyword generation.

Response 200 OK

{
  "ok": true,
  "message": "Prompts saved successfully."
}
curl
curl -X PUT http://127.0.0.1:9123/api/prompts \
  -H "Content-Type: application/json" \
  -d '{
    "keywords_leadmining_system_prompt": "Return only JSON.",
    "keywords_leadmining_user_template": "Generate {count} keywords for {seed} in {language}. {intents}"
  }'
Python
import requests

prompts = {
    "keywords_leadmining_system_prompt": "Return only JSON.",
    "keywords_leadmining_user_template": "Generate {count} keywords for {seed} in {language}. {intents}"
}

res = requests.put("http://127.0.0.1:9123/api/prompts", json=prompts)
print(res.json()["message"])
JavaScript
const res = await fetch("http://127.0.0.1:9123/api/prompts", {
  method: "PUT",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    keywords_leadmining_system_prompt: "Return only JSON.",
    keywords_leadmining_user_template: "Generate {count} keywords for {seed} in {language}.",
  }),
});
const result = await res.json();
console.log(result.ok, result.message);

Enumerations

Languages (language)

English Arabic French Spanish German Italian Portuguese Dutch Russian Turkish Hindi Chinese (Simplified) Japanese Korean

Intents (intents)

Informational Navigational Commercial Transactional

Email types (email_type)

b2b b2c

ANY /api/improve/*

The Self-improvement tab's API. Everything it reports is read from data/ (scores per market, runs, learning, loop state) and from the extractor's usage counter and learned skip-list.

Method & pathWhat it does
GET /api/improve/summary?scope=ma-lead_miningRounds, trials, query shapes (weight and status) for one market, blocked sites, today's engine usage, everyday learning, switches and the round status. Learns from new extractions first.
POST /api/improve/learnLearn from new query-log lines now.
POST /api/improve/roundsStart a round in the background (about 90 searches, ~25 minutes). 400 if one is already running.
GET /api/improve/rounds/statusProgress and log tail of the current or last round.
POST /api/improve/unblock{"host": "zoho.com", "scope": "ma-riads-lead_mining"}: unblock a learned site for good in that scope (empty: the everyday list).
POST /api/improve/patterns/restore{"pattern_id": "email.mailto", "scope": "ma-lead_mining"}: try a retired shape again.
POST /api/improve/verdicts{"email": "a@shop.ma", "accepted": false, "reason": "list_page", "query": "…", "source": "https://…", "mailbox": "lead", "on_geo": true, "on_niche": true, "keyword": "…", "features": {"found_on": "page", …}}: your verdict on a lead. The tags, keyword and features (what the extractor saw, as returned with each extracted email) are kept with it for a future ranking model. It corrects the query shape that found it and beats the targeting rule from then on. Reasons: wrong_country, wrong_niche, list_page, department, not_a_business; none on an accepted lead (400). A reason also corrects the rule: a list, not-a-business, wrong-niche or wrong-country verdict skips the lead's site; a department verdict tags that inbox at every domain. Accepting a lead undoes both. The response's changes lists what changed. The summary's verdicts shows how often the rule agrees with you, and verdict_changes every rule change made from a verdict.
POST /api/improve/verdicts/batch{"verdicts": [ … ]}: several verdicts at once (the Extract page's "Mark the other leads"). One bad verdict keeps none (400).
POST /api/improve/mailboxes/forget{"mailbox": "compta"}: stop tagging an inbox as a department's, learned from a verdict. 400 if it was not learned.
POST /api/improve/verdicts/lookup{"emails": ["a@shop.ma"]}: the verdicts already given on these addresses.
PUT /api/improve/options{"weighted_cap": true, "deepseek_inventor": false, "auto_rounds": true}: the tab's switches. auto_rounds lets rounds start by themselves, at most one a day, for a market that learned from everyday runs since its last round.

Errors & status codes

StatusMeaningTypical cause
200OKRequest handled successfully.
400Validation errorBad mode, unknown file, invalid upload, out-of-range n, empty selection.
422Schema validation failedFastAPI/Pydantic rejected the JSON body (blank query, max_results > 50, missing field).
429Rate limitedThe free search backend is asking you to slow down.
500Server errorMissing/invalid configuration or an unexpected exception.
502Upstream failureSearch proxy/network error, or a page could not be fetched.
504Upstream timeoutThe search engine timed out.
Retrying. For 429 and 502/504, wait and retry — the free search backends are rate-limited. Lead Miner already pauses between queries in a batch and retries an empty query once.
{% endraw %} {% endblock %}