Four Pillars of Next-Gen LLMs: A Selection and Implementation Guide
This article explores four key areas of next-generation large models: multimodal capabilities, long context versus RAG, persistent memory, and cost control. It provides practical selection criteria, a runnable Python code example for RAG, and a comprehensive implementation checklist to help developers navigate model selection and deployment in real-world applications.
Discussions around next-generation large models often focus on making them bigger, faster, and cheaper. For developers, however, the questions are more concrete: Can the model read an entire code repository? Can it simultaneously understand requirement docs, UI sketches, and demo videos? Can it remember prior conventions during multi-turn collaborations? Is the cost of a single API call sustainable for the business? This article addresses these four questions, providing selection criteria, runnable code, and checklists for each section.
1. Multimodal Capabilities: Native Unified vs. Modular Stitching
Most systems currently use a stitching approach: a text model handles the conversation, calls an image recognition API for images, and another service for video generation. This approach is quick to deploy but prone to information loss across modules. For example, if a button’s position in an image is passed to the front-end code generation step only as text, spatial relationships and hierarchies are often distorted during translation.
Native multimodal models process text, images, video, and code within the same representation space, theoretically preserving more detail. The differences are as follows:
| Dimension | Modular Stitching | Native Unified Model |
|---|---|---|
| Deployment Speed | Fast, can reuse existing services | Depends on available models and provider conditions |
| Cross-modal Details | Easily lost at API boundaries | Information passes within the same representation |
| Debugging & Troubleshooting | Each module can be debugged individually | Internal processes are opaque, relies on evaluation sets |
| Cost Structure | Multiple calls, billed per module | Single call may have a higher unit price, but the call chain is shorter |
| Typical Failure Modes | Position/sequence info lost between modules | Errors on small text/complex charts, difficult to trace |
If the business only requires image-text Q&A (e.g., answering operational steps based on a screenshot), stitching is usually sufficient and cheaper to maintain. If you need to generate a UI-consistent page directly from a design draft, the value of native multimodal capabilities is more pronounced.
Do not choose native multimodal if: data processing locations or compliance requirements cannot be met, or the team lacks the capacity to maintain a proprietary evaluation set. Do not insist on stitching if: page layout relies on precise spatial relationships, and intermediate outputs cannot be verified.
Regardless of the choice, prepare a set of proprietary evaluation samples using real business screenshots, requirement docs, and historical bug reports. Public leaderboards measure general capabilities; alignment with specific business needs requires internal testing.
Long video generation has an unresolved issue: character appearance, lighting, and camera direction tend to drift across multiple clips. In projects, use short clips of a few seconds first to verify temporal consistency, track the frequency of drift, and then decide whether to invest in long video generation. Verification itself incurs costs and should be budgeted.
2. Choosing Between Long Context and RAG
Long context refers to the input length a model can receive in a single request. With larger windows, models can read more code and docs at once, but face two practical constraints. First, computation scales with input length, increasing cost and latency. Second, the middle part of long inputs is easily ignored—a phenomenon often called “lost in the middle.”
To mitigate “lost in the middle”:
- Place the most critical constraints and problem descriptions at the beginning or end of the prompt.
- Generate summaries for long documents in segments first, then input the summaries alongside key original paragraphs.
- Rerank search results to include only the top most relevant chunks in the prompt, ordered by relevance.
In engineering practice, long context and RAG are often used together. Refer to the table below for selection:
| Scenario | Better Solution | Reason |
|---|---|---|
| Total material fits in window, requires full read | Long context direct input | Complete structure, simple to implement |
| Large volume, question only concerns local parts | RAG | Only retrieves relevant chunks, lower cost |
| Requires cross-file reasoning, e.g., call chain analysis | Long context + retrieval | Locate files first, then read comprehensively |
| Frequent material updates | RAG | Just update the index, prompt structure remains unchanged |
| Latency-sensitive, hard limit on response time | RAG, control number of retrieved chunks | Shorter input usually means lower time-to-first-token |
The following example implements chunking, retrieval, and prompt assembly. It only uses the Python standard library, requires Python 3.9 or higher. Save it as rag_demo.py and run python rag_demo.py. The tokenizer and retriever are for demonstration only. In production, replace them with the model’s native tokenizer and a vector database.
import mathimport refrom collections import Counterfrom dataclasses import dataclassfrom typing import List, Protocolclass Tokenizer(Protocol):def encode(self, text: str) -> List[int]: ...def decode(self, tokens: List[int]) -> str: ...class CharTokenizer:"""Demo tokenizer where each character is a token. Replace with model native tokenizer in production."""def __init__(self) -> None:self._id_of: dict = {}self._char_of: List[str] = []def encode(self, text: str) -> List[int]:ids = []for ch in text:if ch not in self._id_of:self._id_of[ch] = len(self._char_of)self._char_of.append(ch)ids.append(self._id_of[ch])return idsdef decode(self, tokens: List[int]) -> str:return "".join(self._char_of[i] for i in tokens)def split_by_tokens(text: str, tokenizer: Tokenizer,chunk_tokens: int = 512, overlap: int = 64) -> List[str]:"""Splits text by token count, retaining 'overlap' tokens between adjacent chunks."""if chunk_tokens <= 0:raise ValueError("chunk_tokens must be greater than 0")if not 0 <= overlap < chunk_tokens:raise ValueError("overlap must satisfy 0 <= overlap < chunk_tokens")ids = tokenizer.encode(text)step = chunk_tokens - overlapchunks: List[str] = []for start in range(0, len(ids), step):piece = ids[start:start + chunk_tokens]chunks.append(tokenizer.decode(piece))if start + chunk_tokens >= len(ids):breakreturn chunks@dataclassclass ScoredChunk:text: strscore: floatsource_id: strdef _terms(text: str) -> Counter:"""Splits English by word and Chinese by character, for demonstration only."""return Counter(re.findall(r"[a-z0-9]+|[\u4e00-\u9fff]", text.lower()))def _cosine(a: Counter, b: Counter) -> float:dot = sum(a[t] * b[t] for t in set(a) & set(b))norm = math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values()))return dot / norm if norm else 0.0class KeywordStore:"""Demo retriever based on term-count cosine similarity. Replace with a vector database in production."""def __init__(self, chunks: List[str]) -> None:self._items = [(str(i), c, _terms(c)) for i, c in enumerate(chunks)]def search(self, query: str, top_k: int = 3) -> List[ScoredChunk]:q = _terms(query)scored = [ScoredChunk(text=c, score=_cosine(q, v), source_id=sid)for sid, c, v in self._items]scored.sort(key=lambda x: x.score, reverse=True)return scored[:top_k]def build_prompt(question: str, chunks: List[ScoredChunk]) -> str:"""Assembles retrieved results into a prompt, sorted by relevance descending."""context = "\n\n".join(f"[Chunk {i + 1}]\n{c.text}" for i, c in enumerate(chunks))return ("Please answer the question based ONLY on the following materials. If there is no answer in the materials, state so directly.\n\n"f"Materials:\n{context}\n\n"f"Question: {question}")if __name__ == "__main__":doc = ("Long context windows allow the model to read more content at once. As input length grows, computation and latency increase. ""The middle part of long inputs is easily ignored, a phenomenon often called 'lost in the middle'. ""Therefore, in engineering practice, long context is often combined with Retrieval-Augmented Generation (RAG). ""When materials are frequently updated, only the index needs updating while the prompt structure remains unchanged.")tok = CharTokenizer()chunks = split_by_tokens(doc, tok, chunk_tokens=40, overlap=8)assert len(chunks) > 1assert chunks[1][:8] == chunks[0][-8:] # Adjacent chunks overlap correctlystore = KeywordStore(chunks)hits = store.search("lost in the middle", top_k=2)assert any("lost in the middle" in h.text for h in hits)print(build_prompt("What problem occurs with long inputs?", hits))
Running this will print a prompt containing the two chunks most relevant to the question. The two assertions check whether the overlap between adjacent chunks is correct, and whether the retrieval hits a chunk containing the target term. Once you replace CharTokenizer with the model’s native tokenizer, the chunk size should be measured in tokens, not characters.
3. The Difference Between Persistent Memory and Context Window
Many people treat the context window as memory. Their lifecycles, storage locations, and management methods differ entirely. Mixing them leads to two types of problems: either costs spiral out of control, or privacy risks become unmanageable.
| Dimension | Context Window | Persistent Memory |
|---|---|---|
| Lifecycle | Single request or single session | Saved long-term across sessions |
| Storage Location | Sent with request, not stored inside the model | Saved by the application’s own database or file |
| Read Method | Entire content billed every time | Retrieved on demand, only relevant entries fetched |
| Deletion Method | Disappears when session ends | Requires explicit deletion API |
| Main Risk | Long inputs cause cost/latency spikes | Sensitive info stored long-term or misused |
Designing persistent memory requires answering several specific questions. First, what to write: Only save user-confirmed preferences and project conventions, not all conversation content. Second, how long to retain: Set expiration times for each memory and clean them up periodically. Third, who can view and delete: Users should be able to view their memories and delete individual entries. Fourth, what is forbidden to write: Sensitive data like ID numbers, passwords, API keys, and health info should not enter the memory bank; filter them before writing.
Memory reading should also go through the retrieval path. For each request, retrieve relevant memories based on the current question, then place the results into the context window. This allows the memory bank to grow continuously while keeping the input length per request controllable.
4. Cost Control
The cost of a single API call can be roughly divided into three parts: input token fees, output token fees, and extra fees generated by retries and multi-turn calls. Prices vary significantly among providers; projects should rely on actual billing rather than estimates.
Specific cost control measures:
- Set an input token limit for each task type. Truncate or summarize if exceeded, rather than sending directly.
- Limit the number of chunks returned by retrieval and deduplicate them.
- Cache vectors and summaries for identical questions or documents to avoid redundant computation.
- Route simple questions to smaller models; only escalate complex issues to large models.
- Record the “cost per task” for each business feature, not just the total bill, to identify expensive features.
- Set cost alert thresholds; trigger notifications or rate limiting if daily or per-user costs exceed limits.
- Limit retry attempts and log failure reasons to prevent repeated costs from the same error.
The premise of cost optimization is maintaining quality. Every parameter adjustment (e.g., chunk size, retrieval count, model choice) must be re-validated using your proprietary evaluation set.
5. Implementation Checklist
Before moving the project to a production environment, verify the following items one by one:
- Proprietary evaluation samples prepared, covering real screenshots, requirement docs, and historical bugs.
- Temporal consistency of long videos verified with short clips, with drift frequency recorded.
- Long context or RAG selected based on material volume, update frequency, and latency requirements.
- Chunk size calculated in tokens using the model’s native tokenizer.
- Retrieval results deduplicated, sorted by relevance, with a cap on chunk count.
- Persistent memory only writes user-confirmed content, with expiration times set.
- Sensitive information filtered before writing to memory.
- Users can view and delete their own memories.
- Cost per task tracked for every business feature.
- Cost alert thresholds configured, retry limits set.
- Quality re-validated with the evaluation set after every parameter adjustment.
