Notas / 03
1M-token context without hitting the timeout
A million-token context is not a feature you switch on; it is a budget you spend on every call. Three things break when teams first use one: the request exceeds the window and returns 400 because somebody counted characters instead of tokens, the call runs past the gateway's 280-second limit because it was not streamed, and the pre-authorisation for a huge max_tokens is refused before the request ever reaches a model. This article gives a planner that decides between "send it whole" and "map-reduce it", a streaming caller that survives long time-to-first-token, and the arithmetic that keeps a large-context workflow inside a prepaid balance.
What a large window actually buys you
A big context is a *single-shot* capability: one request carries the whole document, so the model sees everything at once with no retrieval step and no chunk-boundary artefacts. That is genuinely different from RAG, and it is the reason to pay for the tokens. What it does not buy you is memory. There is no server-side conversation state on an OpenAI-compatible API: you resend the entire history on every turn and you are billed for the entire history on every turn. A 400,000-token document plus a ten-turn conversation is 4.4 million input tokens billed, not 400,000. Plan the interaction shape before you plan the prompt.
The second thing it does not buy you is free truncation. When the history exceeds the window, the provider rejects the request with a 400 and the provider's message. Nothing is silently trimmed. That is the right behaviour — a silently truncated prompt produces answers that look correct and are wrong — but it means your client must know the size of what it is sending, before it sends it.
A planner: send it whole, or split it
#!/usr/bin/env python3
"""bigctx.py — run a large document through a 1M-context model without timing out."""
import os, sys, time
from openai import OpenAI
BASE = "https://api.tokenaimodels.com/v1"
MODEL = "deepseek-chat"
CONTEXT = 1_000_000
MAX_OUT = 384_000
RESERVE = 20_000 # headroom for the answer and the instruction
client = OpenAI(api_key=os.environ["MODELRY_API_KEY"], base_url=BASE,
timeout=600.0, max_retries=1)
def est_tokens(text: str) -> int:
"""Rough, deliberately pessimistic: English prose ~4.0 chars/token, code ~3.0."""
return int(len(text) / 3.4) + 8
def ask(prompt: str, max_tokens: int = 4000) -> tuple[str, dict]:
"""Stream, because a non-streaming large call will hit the server timeout."""
started = time.monotonic()
parts: list[str] = []
usage: dict = {}
stream = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
max_tokens=max_tokens,
stream=True,
stream_options={"include_usage": True},
)
for event in stream:
if not event.choices:
if event.usage:
usage = event.usage.model_dump()
continue
piece = event.choices[0].delta.content
if piece:
parts.append(piece)
usage["elapsed_s"] = round(time.monotonic() - started, 2)
return "".join(parts), usage
def plan(doc: str) -> str:
n = est_tokens(doc)
print(f"estimate: {n:,} prompt tokens", file=sys.stderr)
if n + RESERVE <= CONTEXT:
return "single"
if n > 12 * CONTEXT:
raise SystemExit("document too large even for map-reduce; split it upstream")
return "map-reduce"
def map_reduce(doc: str, question: str, window: int = 300_000) -> str:
step = window * 3 # chars, per the 3.4 chars/token estimate
chunks = [doc[i:i + step] for i in range(0, len(doc), step)]
notes = []
for i, chunk in enumerate(chunks, 1):
out, usage = ask(
f"Extract every fact relevant to: {question}\n"
f"Be exhaustive and terse. Part {i} of {len(chunks)}.\n\n{chunk}",
max_tokens=2000,
)
print(f" chunk {i}/{len(chunks)} in={usage.get('prompt_tokens')} "
f"out={usage.get('completion_tokens')} {usage['elapsed_s']}s", file=sys.stderr)
notes.append(out)
final, _ = ask(
f"Question: {question}\n\nUsing only these notes, answer in full.\n\n"
+ "\n\n".join(notes),
max_tokens=4000,
)
return final
if __name__ == "__main__":
text = open(sys.argv[1], encoding="utf-8").read()
question = sys.argv[2] if len(sys.argv) > 2 else "Summarise the risk register."
mode = plan(text)
answer = ask(text + "\n\n" + question)[0] if mode == "single" else map_reduce(text, question)
print(answer)
export MODELRY_API_KEY="sk-live-..."
python3 bigctx.py ./contract.txt "List every clause that mentions liability."
Failure 1: 400 "context length exceeded" on a document that should fit
Character counts are not token counts, and the ratio varies by content: English prose runs near four characters per token, source code nearer three, CJK text nearer one. A 900,000-character codebase can be 300,000 tokens or 400,000 depending on what is in it, and a naive len(text)/4 will under-count by 30%. Measure instead of guessing: send a 20,000-token slice and read usage.prompt_tokens from the response, then extrapolate from *that* ratio. Also remember the window includes the answer — reserve the max_tokens you plan to use before you decide the document fits.
Failure 2: the call dies at 280 seconds
Long non-streaming requests are the standard timeout victim. A gateway typically caps a request at a fixed wall-clock limit (280 seconds on the platform used here) and closes the connection; a model that thinks for three minutes before its first token has already spent most of that budget. Two changes: stream always, which keeps the connection alive and gives you progress, and raise the client's idle timeout because "no bytes for forty seconds" is normal during long thinking. If you must avoid streaming, keep the request small enough to finish well inside the limit rather than tuning retries to hammer it.
Failure 3: 402 before the model is ever called
Prepaid gateways pre-authorise: they estimate the cost from your prompt size and your max_tokens, add a cushion (15% in this case), and freeze that amount before contacting the provider. Ask for a 300,000-token output on a $5 balance and the request fails with 402 insufficient_balance even though the real cost would have been a few cents — the freeze is what failed, not the charge. Set max_tokens to what the answer actually needs, not to the model ceiling. Requesting 384,000 tokens "just in case" is the single most common cause of a 402 on an otherwise healthy account.
What to watch when you speak to a gateway instead of OpenAI
Three gateway-specific properties shape a large-context workflow. Prefix stability: put the big document first and the volatile instruction last, because caching works on a prefix — the same document answered twice with a different question at the top never hits the cache, while the same document followed by a new question does. Output clamping: an oversized max_tokens is clamped to the model maximum rather than rejected, so a typo of 900,000 silently becomes 384,000 and your "largest possible answer" is not what you asked for; read finish_reason: "length" as evidence, not rumour. Failover limits: where a second channel is configured, a request that fails before its first token can move to another channel for the same model, but once bytes flow the response is committed — with a multi-minute generation that means a mid-stream failure costs you the whole attempt, so checkpoint long map-reduce jobs at the chunk level instead of rerunning them.
Two habits that make large contexts survivable
First, always checkpoint. A map-reduce job over twenty chunks is twenty billable requests, and a crash on chunk nineteen should not resend eighteen. Write each chunk's note to disk under a hash of its content and skip it on restart; a file on disk costs nothing next to a resent chunk. Second, overlap your windows slightly — a 2,000-token overlap between adjacent chunks costs a fraction of one extra request and prevents the failure mode where a fact that spans a boundary is invisible to both halves. Neither habit is about the model; both change how often you pay for the same document twice.
Start at https://tokenaimodels.com, run bigctx.py against one real document, and compare the prompt_tokens it reports with your own estimate — the gap is your tokenizer, and knowing it is worth more than any prompt trick.
A Modelry opera uma plataforma que serve modelos DeepSeek atrás de um único endpoint HTTP, com créditos pré-pagos e impostos tratados pelo merchant of record no checkout, além de uma política de retenção de dados documentada. Comece com $0.50 de crédito de teste: criar uma chave.