跪拜 Guibai
← All articles
Artificial Intelligence · Frontend · AI Programming

Token Budgets, Prompt Caching, and the Three Ways to Call an LLM from TypeScript

By Setsuna_F_Seiei ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Frontend developers building agent UIs need to understand token economics and streaming mechanics at the wire level, not just the chat widget. Misjudging context-window pressure or skipping prompt caching can silently multiply API costs by 5–10× as conversations grow, while choosing invoke over stream locks the UI for seconds at a time.

Summary

LLM calls are billed by tokens, not characters, and output tokens cost roughly five times more than input. A single agent turn can burn through a context window fast—system prompts, conversation history, tool results, and reasoning all compete for space. When usage hits 75–90% of the window, context compression or summarization becomes mandatory to prevent the model from forgetting early instructions or erroring out. Anthropic's prompt caching cuts costs by 90% for stable prefixes longer than 2,000 tokens, but the cache expires after five minutes and only matches on exact prefix alignment.

LangChain's ChatPromptTemplate turns raw message lists into parameterized, composable templates. A well-structured system prompt covers five elements: role, capability boundaries, output format, style, and counter-examples. Few-shot examples embedded in the template steer the model toward specific JSON structures or tones without post-processing. The MessagesPlaceholder pattern lets you inject dynamic conversation history or RAG results into a fixed template skeleton.

Three calling modes serve different needs. Invoke blocks until the full response arrives—fine for batch extraction, terrible for user-facing UIs. Stream delivers tokens incrementally, enabling typewriter-style rendering and mid-generation cancellation. Batch reuses HTTP connections and enforces concurrency limits, making it 5–10× faster than looping invoke for bulk translation or classification. Production code wraps all three with timeout controls, AbortController signals, and exponential-backoff retry logic that only retries on transient failures like rate limits or 5xx errors.

Takeaways
Output tokens cost about 5× more than input tokens, so constraining model responses to short, structured formats saves more money than trimming prompts.
Context windows fill up from system prompts, conversation history, tool results, and reasoning tokens; trigger compression when usage exceeds 75% of the window.
Anthropic Prompt Cache bills cached prefixes at 1/10 the standard input price, but only when the first N tokens match exactly and the cache is under 5 minutes old.
A production system prompt needs five elements: role, capability boundaries, output format, style, and explicit counter-examples of what not to do.
Few-shot examples inside a ChatPromptTemplate reliably steer the model toward a specific JSON schema or tone without extra parsing.
Stream mode enables typewriter rendering and mid-generation cancellation; invoke blocks the entire response and is only suitable for background jobs.
Batch calls reuse HTTP connections and enforce concurrency limits, running 5–10× faster than looping invoke for bulk tasks like translation.
Always pull token counts from response.usage_metadata—Anthropic's input_tokens field includes cache_read tokens, so naive multiplication double-bills cache hits.
Retry logic should use exponential backoff only for transient errors (429, 5xx, timeout); business errors like invalid parameters should fail immediately.
Conclusions

Token budgeting is a frontend concern now. As agent loops grow longer, the UI layer must track context pressure and trigger summarization, or the model silently degrades mid-conversation.

Prompt caching's 5-minute expiry and prefix-match requirement make it a session-level optimization, not a global one—it rewards architectures that keep system prompts and tool definitions identical across turns.

The 5× output-token premium flips conventional API design instincts: verbose model responses are the real cost driver, not large input contexts, which pushes agent developers toward terse, machine-parseable output formats.

LangChain's batch method is underused. Most tutorials show sequential invoke calls, but any bulk classification or translation task benefits from connection reuse and built-in concurrency gating.

Concepts & terms
Token
The smallest semantic unit an LLM processes, roughly 4 English characters or 0.5 Chinese characters. Billing is per token, not per character or message.
Context Window
The maximum total tokens (input + output) a model can handle in one call. Exceeding it causes truncation or errors; typical limits range from 128K to 200K tokens.
Prompt Caching (Anthropic)
A feature that stores stable prompt prefixes server-side. Subsequent requests with the same prefix reuse the cache and are billed at 1/10 the standard input price. Cache expires after 5 minutes.
ChatPromptTemplate
A LangChain utility that parameterizes prompt construction, letting developers define message templates with variables, inject dynamic history via MessagesPlaceholder, and embed few-shot examples.
Few-shot Prompting
Including example input-output pairs in a prompt so the model mimics the format and style. Effective for enforcing structured JSON output or a specific tone without fine-tuning.
Streaming (LLM)
An invocation mode where the model returns tokens incrementally as they are generated, enabling real-time UI rendering and mid-generation cancellation, unlike blocking invoke calls.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗