Why scraped text breaks naive summarization
Scraping gives you volume, not signal. A single crawl of a few thousand URLs produces navigation menus, cookie banners, comment threads, and duplicated boilerplate glued to the two paragraphs you actually wanted. If you point one model at that raw dump and hope, you get three problems at once: summaries of the wrong text, wildly uneven output shapes, and a bill that scales with how badly your extraction step performed.
The fix is boring and effective: clean before you summarize, run the bulk of the work on a cheap tier, and reserve the stronger model for the small slice of pages that genuinely need it. That is the whole architecture. The rest of this post is the working version of it.
Everything below uses the OpenAI SDK pointed at AiCredits, so the code runs as written. Sign-up takes a card or PayPal and does not require a Chinese phone number or bank account, which is the usual friction point for developers outside China trying to reach Chinese-hosted models.
The pipeline shape that holds up
Fetch and extract first — strip scripts, nav, footers, forms; prefer
, then , then . Normalize whitespace and hash the cleaned text so you can skip re-summarizing pages you have already seen.
Chunk long pages with a small overlap, then summarize each chunk on the cheap tier.
Merge chunk summaries into one record with the cheap tier again — merging is compression, not reasoning.
Run a quality gate on the result and escalate only failing records to the stronger model.
Write JSONL, validate the schema, and log the tier used for every row so you can audit later.
Step 1: Extract, chunk, and call the cheap tier
# pip install openai requests beautifulsoup4
import hashlib, json, os, re, time
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
from bs4 import BeautifulSoup
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
UA = {"User-Agent": "Mozilla/5.0 (compatible; SummarizerBot/1.0)"}
STRIP = ["script", "style", "nav", "footer", "header", "form", "noscript", "aside", "iframe"]
def fetch_text(url, timeout=20):
resp = requests.get(url, headers=UA, timeout=timeout)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html.parser")
for tag in soup(STRIP):
tag.decompose()
node = soup.find("article") or soup.find("main") or soup.body or soup
return re.sub(r"\n{2,}", "\n", node.get_text("\n", strip=True))
def chunk(text, size=6000, overlap=400):
if len(text) <= size:
return [text]
out, start = [], 0
while start < len(text):
out.append(text[start:start + size])
start += size - overlap
return out
def content_hash(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
SYSTEM = """You summarize scraped web pages for a research database.
Reply with JSON only. No markdown, no code fences.
Schema: {"title": string, "summary": string, "key_points": [string], "category": string}
Rules:
- Ignore navigation, cookie notices, ads, related links and boilerplate.
- summary: at most 3 sentences, factual, no marketing language.
- key_points: 2 to 5 concrete facts or claims actually present in the text.
- category: one lowercase label such as news, docs, blog, pricing, forum, empty.
- If the page has no usable content, set summary to "NO_CONTENT" and category to "empty"."""
def call_json(model, user_text, max_tokens=700, retries=3):
last_err = None
for attempt in range(retries):
try:
r = client.chat.completions.create(
model=model,
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": user_text}],
temperature=0.2,
max_tokens=max_tokens,
response_format={"type": "json_object"},
)
return json.loads(r.choices[0].message.content)
except Exception as exc:
last_err = exc
time.sleep(2 ** attempt)
raise RuntimeError(f"model call failed: {last_err}")
def summarize_text(text, url, model="deepseek-v4-flash"):
parts = chunk(text)
if len(parts) == 1:
rec = call_json(model, f"URL: {url}\n\n{parts[0]}")
else:
notes = []
for i, part in enumerate(parts):
piece = call_json(model, f"URL: {url}\n\nSECTION {i + 1}/{len(parts)}\n\n{part}")
if piece.get("summary") and piece["summary"] != "NO_CONTENT":
notes.append(piece["summary"])
merged = "\n".join(f"- {n}" for n in notes) or "- (no usable content)"
rec = call_json(
model,
f"URL: {url}\n\nMerge these section summaries of one page into a single record.\n\n{merged}",
)
rec["url"] = url
rec["model"] = model
rec["source_chars"] = len(text)
rec["content_hash"] = content_hash(text)
return rec
def run_pipeline(urls, out_path="summaries.jsonl", workers=6):
def work(u):
try:
text = fetch_text(u)
if len(text) < 200:
return {"url": u, "summary": "NO_CONTENT", "category": "empty", "model": "none"}
return summarize_text(text, u)
except Exception as exc:
return {"url": u, "summary": "ERROR", "category": "error",
"error": str(exc), "model": "none"}
with open(out_path, "w", encoding="utf-8") as fh, ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(work, u): u for u in urls}
for fut in as_completed(futures):
fh.write(json.dumps(fut.result(), ensure_ascii=False) + "\n")
fh.flush()
if __name__ == "__main__":
run_pipeline(["https://example.com"])
Two details matter more than they look. First, the extraction step removes the majority of wasted input; a page that drops from a messy DOM to clean prose is cheaper and more accurate to summarize, and that saving compounds across the whole crawl. Second, the content hash lets you skip work entirely — re-crawls mostly return pages you already processed, and a hash comparison costs nothing compared to a model call.
Step 2: A quality gate, not a model ladder
The common mistake is a fixed rule like "short pages use flash, long pages use pro." Page length is a weak proxy for difficulty. What you actually care about is whether the cheap tier produced something usable, so gate on the output, not the input.
def needs_escalation(rec, text):
summary = (rec.get("summary") or "").strip()
if summary in {"", "NO_CONTENT", "ERROR"}:
return True
points = rec.get("key_points") or []
if len(text) > 4000 and len(summary) < 120:
return True
if len(text) > 4000 and len(points) < 2:
return True
return False
def summarize_with_escalation(text, url):
rec = summarize_text(text, url, model="deepseek-v4-flash")
if not needs_escalation(rec, text):
rec["tier"] = "flash"
return rec
try:
strong = summarize_text(text, url, model="deepseek-v4-pro")
except RuntimeError:
rec["tier"] = "flash-fallback"
return rec
if (strong.get("summary") or "").strip() not in {"", "NO_CONTENT", "ERROR"}:
strong["tier"] = "pro"
return strong
rec["tier"] = "flash-kept"
return rec
Swap summarize_text for summarize_with_escalation inside work() and you get escalation on every page. Keep the tier field in your output — the escalation rate is the single most useful number you can track, because it tells you whether the cheap tier is actually carrying the workload or whether you are quietly paying for the strong model on everything.
If your scraped pages contain code samples and you re-emit them downstream, lint the output before storing it; AiCredits ships code linting tools that slot in at that step, and catching a broken snippet early is cheaper than debugging it after it lands in your database.
Where the cheap tier wins and where it does not
| Stage | Tier | Why |
|---|---|---|
| Boilerplate stripping, per-chunk summaries across thousands of URLs | deepseek-v4-flash | High volume, short outputs, and mistakes are visibly cheap to catch in a spot check |
| Category tagging, dedupe keys, language detection | deepseek-v4-flash | Short-text classification with a low temperature is stable and fast enough |
| Merging chunk summaries into one record | deepseek-v4-flash | Mostly compression of text you already generated — little reasoning required |
| Ambiguous long-form pages, regulated or financial content, cross-source synthesis | deepseek-v4-pro | Better instruction-following on messy input; costs more per call, so gate it behind the quality check |
Prompt layout is a cost decision
Put the stable system prompt first and the volatile scraped text last. That ordering is what makes prompt caching effective; a system prompt with a timestamp or request ID in the middle breaks it every time.
Keep the JSON schema in the system message rather than repeating it per call — shorter user messages and a cacheable prefix.
Set
temperature=0.2for extraction tasks. You want replication, not creativity, and consistent output reduces retries.Use
response_format={"type": "json_object"}so you never parse prose with a regex.Cap
max_tokens. A runaway field is a silent cost leak, and summaries have no reason to be long.
Pricing, qualitatively
Flash is the workhorse tier. Pro costs more per call and should appear as an exception path, not the default.
Cache hits are cheaper than fresh input, which is why the stable-prefix ordering above is worth the effort.
Off-peak requests cost less than peak ones — if your crawl does not need to finish immediately, schedule it off-peak.
Current rates live at aicreditsapi.com/pricing; check them rather than relying on a number from a blog post, including this one.
Evaluation you can run in an afternoon
Build a gold set of around 50 URLs spanning news, docs, blogs, forums, pricing pages, and a couple of intentionally empty pages.
Write a short rubric: does the summary reflect the main content, are key points traceable to the source, is the category right.
Run the pipeline, record the escalation rate, and eyeball every escalated record. A high escalation rate usually means your extraction is weak, not that the cheap model is.
Check NO_CONTENT false positives separately — an aggressive extractor that throws away real content looks identical to a model failure in the logs.
Re-run the gold set whenever you change the prompt. Small wording changes move output shape more than most people expect.
FAQ
Often yes, for short articles. For long pages, chunking with a small overlap and merging the section summaries on the cheap tier gives more complete coverage than truncating the input, and it keeps every individual call small.
After stripping scripts, navigation, and boilerplate, it handles most pages well. The quality gate exists for the rest: ambiguous long-form writing, regulated content, and pages where the extraction itself was imperfect.
Track three things instead: records produced per URL, the escalation rate, and how many calls hit a cache. Those move costs more than prompt-level tuning, and they are visible in your JSONL output.
No. AiCredits sign-up accepts a card or PayPal, so the OpenAI-compatible endpoint above works without any Chinese payment or phone verification.
Cheap tiers do not save money by being worse — they save money by handling the 90% of scraped pages that never needed a reasoning model in the first place. Measure the escalation rate, and let that number tell you where the line belongs.