Technical Foundations for LLM Companies: What to Build Before Going Public

    This article looks at the technical capabilities LLM companies need before turning capital momentum into sustainable revenue. It explains how to evaluate commercialization readiness, control inference costs, combine long-context models with retrieval-augmented generation, route and fall back across models, build reliable agentic workflows, add observability and FinOps, and address security, compliance, and deployment requirements. It also outlines a phased roadmap and common pitfalls for scaling LLM products.

    Over the past two years, every funding round and IPO update from LLM startups has attracted attention. One AI company founded only three years ago saw its valuation grow more than tenfold in less than a year. Its annualized revenue rose from zero to hundreds of millions of dollars, and it began restructuring its equity architecture ahead of an IPO.

    This capital narrative is often interpreted as a victory of fundraising capability and capital operations. For the enterprise, however, the real pivot is this: in a competitive environment where large technology companies enter the market and open-source models iterate quickly, can the company continuously earn real payments from enterprise customers and maintain a healthy unit cost for every inference call?

    Capital only amplifies expectations; revenue delivers them. This article does not retell financing and restructuring details. Instead, it answers one question from a technical perspective: what technical capabilities does an LLM company need to support scalable revenue?

    1. Four Signals of Commercialization Capability

    An LLM company’s commercialization capability is usually reflected in the following four signals. Each signal corresponds to concrete technical work.

    • Revenue growth comes from real usage. Sustainable revenue comes from high-frequency calls embedded in business workflows, such as customer-service Q&A, document processing, coding assistance, and data analysis. These directly consume compute and token costs.
    • Gross margin is determined by inference efficiency. Moving from losses to healthy margins depends on whether unit inference cost declines with scale. Methods include batch scheduling, cache reuse, model tiering, and quantization/compression.
    • Renewal rates depend on whether performance is stable. Enterprise customers renew by use case, and performance is determined by model capability, data quality, tool integration, and evaluation systems.
    • Delivery capability determines deal size. Whether a company can enter high-value industries such as finance, healthcare, and government depends on whether private deployment, permission isolation, and compliance auditing are complete.

    In other words, valuation stories tell possibilities; the technical foundation determines certainty.

    2. Inference Cost: The First Constraint of Commercialization

    For LLM services, the most essential difference from traditional web services is that inference cost grows linearly with usage. Therefore, the assumption that “higher call volume automatically means more profit” does not hold without optimization.

    2.1 Where Costs Come From

    Inference can be divided into two stages, and their resource bottlenecks are fundamentally different:

    Stage Compute profile Main bottleneck Optimization direction
    Prefill Parallel processing of all input tokens Compute-intensive Prefix cache reuse
    Decode Token-by-token autoregressive generation Memory bandwidth and capacity Continuous batching, paged KV cache, quantization

    The decode stage’s bottleneck is more subtle. GPU utilization may be high, but much of it may be consumed moving the KV cache, leaving actual throughput low. Memory capacity also limits the maximum concurrency batch size. Therefore, inference services should not be evaluated only by peak QPS. Time to first token (TTFT), tokens per second (TPS), and cost per thousand tokens should also be considered.

    In addition, the price tag often does not match the bill. In long-context requests, system prompts and historical conversations that are repeatedly passed in can be charged repeatedly and can squeeze the KV cache.

    2.2 Calculate Costs First, Then Optimize

    Cost optimization should start with quantification. Code 1 shows a simplified cost calculation function. Model inference APIs usually return token usage, and cost is composed of input tokens, output tokens, and cache-hit tokens.

    1. # Code 1: Calculate the cost of a single request from token usage
    2. def request_cost(usage: dict, pricing: dict) -> dict:
    3. """Calculate request cost from the usage field returned by an inference API and extract cache-benefit metrics.
    4. usage usually contains: prompt_tokens (input tokens), completion_tokens (output tokens),
    5. cached_tokens (input tokens served from the prefix cache)"""
    6. cached = usage.get("cached_tokens", 0)
    7. billed_input = usage["prompt_tokens"] - cached
    8. cost = (billed_input * pricing["input"] + usage["completion_tokens"] * pricing["output"]
    9. + cached * pricing.get("cached_input", 0))
    10. return {
    11. "cost": cost,
    12. "cache_hit_rate": cached / max(usage["prompt_tokens"], 1),
    13. "output_per_input": usage["completion_tokens"] / max(billed_input, 1),
    14. }

    When calculation results are aggregated by scenario, tenant, and feature module, it becomes clear which calls consume cost and which create value.

    Code 2 is a request-level budget guard. It intercepts contexts that would exceed the limit before the call is made.

    1. # Code 2: Request-level budget guard
    2. MAX_PROMPT_TOKENS = 32_000
    3. class BudgetError(Exception):
    4. pass
    5. def build_prompt(system: str, history: list, query: str, count_tokens) -> list:
    6. messages = [{"role": "system", "content": system}]
    7. # Keep history backward from the most recent turn so the total input stays within budget
    8. for item in reversed(history):
    9. candidate = [{"role": item["role"], "content": item["content"]}] + messages[1:]
    10. if count_tokens(candidate) > MAX_PROMPT_TOKENS:
    11. break
    12. messages.insert(1, candidate[0])
    13. if count_tokens(messages + [{"role": "user", "content": query}]) > MAX_PROMPT_TOKENS:
    14. raise BudgetError("Input exceeds the context budget")
    15. messages.append({"role": "user", "content": query})
    16. return messages

    2.3 Tiered Composition and Elastic Scheduling

    Optimization measures are not substitutes for one another. They work from different dimensions:

    • Batching and caching. Continuous batching improves GPU utilization; paged KV-cache management reduces memory fragmentation; prefix caching lets identical system prompts, tool definitions, and knowledge snippets be computed only once.
    • Model compression. Quantization, such as INT8 and INT4, distillation, pruning, and low-rank adaptation (LoRA) fine-tuning can reduce per-request inference cost within acceptable quality loss.
    • Model composition. Models can be grouped into large, medium, and small tiers. With semantic caching, simple requests go to cache hits or small models, and only complex requests invoke large models.
    • Compute scheduling. Self-built GPU clusters and elastic cloud compute each have suitable scenarios. Regardless of the form, elastic scaling, resource quotas, and priority queues are needed.

    Inference optimization is essentially a tradeoff between benefit and cost. Every step should be based on measured data rather than assumptions.

    3. Long Context and Retrieval-Augmented Generation: Helping LLMs Understand Enterprise Knowledge

    Long-context capability was once the most visible differentiator of LLM products. It can hold long documents such as contracts, reports, and code repositories at once, significantly reducing information discontinuity caused by “chunking and stitching.” As base models now commonly support long context, product differentiation is shifting from “how long can it read” to “can it read accurately and use resources efficiently.”

    3.1 Three Constraints of Long Context

    • Cost constraint. Input tokens grow linearly with document length. Long context also easily triggers the “middle information is ignored” problem, where answer quality declines when key information is in the middle of the context.
    • Freshness constraint. Writing the full text of a document into the prompt means the content must be rewritten after updates, making real-time updates impossible.
    • Permission constraint. Enterprise knowledge is often divided into visibility scopes by department or role. Stuffing all content at once can easily cause unauthorized leakage.

    Therefore, engineering practice usually combines “long context for understanding, retrieval augmentation for supply”: long context first understands a single document at once, then retrieval sends the most relevant fragments to the generation stage.

    3.2 Key Steps in Retrieval Augmentation

    A reliable retrieval-augmented pipeline contains six steps:

    1. Document parsing: Handle formats such as PDF, Word, tables, and scanned documents, preserve heading hierarchy, tables, and page numbers to support citation tracing.
    2. Chunking: Split by semantic structure and keep a certain overlap between adjacent chunks to avoid cutting answers at boundaries.
    3. Indexing: Build both vector indexes and keyword inverted indexes.
    4. Retrieval and fusion: Vector retrieval is good at semantic matching; keyword retrieval is good at exact matching of proper nouns, model numbers, and IDs. After two-way recall, merge using weighted sum or reciprocal rank fusion (RRF).
    5. Reranking and compression: Use a cross-encoder to rerank candidate fragments and keep only a small amount of content most relevant to the question.
    6. Citation tracing: Attach source documents and locations to generated answers so users can verify them.

    Code 3 uses a schematic implementation to show the core flow of “chunking—hybrid retrieval—fusion.”

    1. # Code 3: Chunking, hybrid retrieval, and reciprocal rank fusion
    2. def split_chunks(text: str, size: int = 500, overlap: int = 80) -> list[str]:
    3. chunks, start = [], 0
    4. while start < len(text):
    5. end = min(start + size, len(text))
    6. chunks.append(text[start:end])
    7. if end == len(text):
    8. break
    9. start = end - overlap # Overlap adjacent chunks to reduce boundary truncation risk
    10. return chunks
    11. def hybrid_search(query: str, keyword_index, vector_index, top_k: int = 20):
    12. """Retrieve keyword hits and vector hits in parallel, then fuse rankings with RRF."""
    13. from concurrent.futures import ThreadPoolExecutor
    14. with ThreadPoolExecutor(max_workers=2) as pool:
    15. kw_future = pool.submit(keyword_index.search, query, top_k)
    16. vec_future = pool.submit(vector_index.search, query, top_k)
    17. kw_hits = [doc_id for doc_id, _ in kw_future.result()]
    18. vec_hits = [doc_id for doc_id, _ in vec_future.result()]
    19. scores: dict[str, float] = {}
    20. k = 60 # RRF smoothing constant that suppresses the absolute advantage of a single retriever
    21. for rank, doc_id in enumerate(kw_hits):
    22. scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank + 1)
    23. for rank, doc_id in enumerate(vec_hits):
    24. scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank + 1)
    25. return sorted(scores, key=scores.get, reverse=True) # type: ignore[arg-type]

    3.3 Incremental Updates and Performance Evaluation

    Enterprise knowledge changes continuously, so indexes must support incremental writes, version management, and canary switching. Evaluation must cover both retrieval and generation:

    • Retrieval layer: Recall rate, hit rate, and mean reciprocal rank (MRR).
    • Generation layer: Answer correctness, citation accuracy, and reasonableness of refusal.

    Only when retrieval-layer metrics are consistently stable does generation-layer tuning become meaningful. Otherwise, it is difficult to determine whether the performance problem comes from the model or the data.

    4. Multi-Model Routing and Fallback: Balancing Quality and Cost

    Base models iterate quickly and prices change frequently. Binding business logic to a single model is neither economical nor prudent. The goal of multi-model routing is to let each type of request obtain sufficiently good performance at an appropriate cost.

    Routing usually makes decisions across five dimensions:

    • Task type: Intent recognition, extraction, summarization, reasoning, and generation.
    • Context length: Short requests can use small models or cache; long documents require models that support long context.
    • Real-time requirements: Conversational requests prefer low-latency small models; offline batch processing can use larger models for quality.
    • Quality requirements: High-risk scenarios such as monetary calculation and compliance judgment should be routed to stronger pipelines with validation steps.
    • Cost budget: Set quotas by tenant and scenario; switch models or degrade when nearing the threshold.

    Supporting mechanisms are equally necessary:

    • After a call times out, automatically retry or switch to a backup model.
    • Route high-frequency similar questions through semantic cache.
    • Use an asynchronous message queue to handle offline batch processing and avoid blocking online requests during peak periods.

    Code 4 gives a schematic implementation of routing and fallback.

    1. # Code 4: Task-feature-based routing and automatic fallback
    2. import logging
    3. import time
    4. log = logging.getLogger("llm_router")
    5. class ModelClient:
    6. def __init__(self, name: str, max_tokens: int, avg_cost: float):
    7. self.name, self.max_tokens, self.avg_cost = name, max_tokens, avg_cost
    8. def chat(self, messages: list, max_tokens: int) -> str:
    9. raise NotImplementedError # Integrate with a concrete model inference service
    10. def select_model(models: list, need_tokens: int, intent: str) -> ModelClient:
    11. """Select candidate models by context length and task type; prefer lower-cost models when conditions are equal."""
    12. candidates = [m for m in models if m.max_tokens >= need_tokens]
    13. prefer_large = intent in {"reasoning", "compliance"}
    14. candidates.sort(key=lambda m: m.avg_cost, reverse=prefer_large)
    15. if not candidates:
    16. raise ValueError("No model meets the context-length requirement")
    17. return candidates[0]
    18. def chat_with_fallback(models: list, messages: list, max_tokens: int,
    19. intent: str, retries: int = 1) -> str:
    20. need = sum(len(m["content"]) for m in messages)
    21. candidates = [m for m in models if m.max_tokens >= need]
    22. candidates.sort(key=lambda m: m.avg_cost, reverse=intent in {"reasoning", "compliance"})
    23. for model in candidates:
    24. for attempt in range(retries + 1):
    25. started = time.perf_counter()
    26. try:
    27. return model.chat(messages, max_tokens)
    28. except Exception as exc: # Covers timeouts, rate limiting, service unavailability, etc.
    29. log.warning("Model %s call failed on attempt %d: %r", model.name, attempt + 1, exc)
    30. log.info("Model %s is unavailable; switching to the next candidate", model.name)
    31. raise RuntimeError("All candidate models are unavailable")

    Three implementation notes are important:

    • Routing decisions themselves should be lightweight, for example using rules or a small classification model, to avoid becoming a new latency bottleneck.
    • Record the selected model and routing reason for every call to support attribution analysis and continuous tuning.
    • Compute capacity freed by small models should flow back into the inference cluster rather than remain idle.

    5. Data Engineering and Agents: From “Conversation” to “Execution”

    Retrieval augmentation solves the “knowing” problem; agents need to solve the “doing” problem. When LLMs move from Q&A to task execution, the technical focus shifts from single inference to multi-step workflow orchestration.

    5.1 Engineering Points for Tool Calling

    • Interface contracts: Every tool needs a clear name, purpose description, and parameter structure. Tool responses should also be structured so the model can understand them and decide the next step.
    • Parameter validation: Model-generated parameters may be missing or out of range. They must be strictly validated on the code side before execution.
    • Human confirmation: Write operations such as creating orders, refunds, and deleting data must pass identity authentication, permission checks, or human confirmation.
    • Sandbox isolation: Tools involving code execution and file processing should run in isolated environments with resource usage limits.
    • Failure recovery: Multi-step tasks must be interruptible and retryable. Key steps should use idempotent design to avoid duplicate charges or duplicate orders.

    Code 5 is a skeleton for a tool-calling pipeline.

    1. # Code 5: Tool registration, invocation, and auditing
    2. import json
    3. TOOLS = {
    4. "query_order": {
    5. "description": "Query order status by order ID; read-only operation",
    6. "parameters": {"order_id": {"type": "string", "required": True}},
    7. "write": False,
    8. },
    9. "create_ticket": {
    10. "description": "Create a ticket; write operation; the caller must perform authentication and confirmation in the business layer",
    11. "parameters": {
    12. "summary": {"type": "string", "required": True},
    13. "priority": {"type": "string", "required": False, "default": "normal"},
    14. },
    15. "write": True,
    16. },
    17. }
    18. def call_tool(name: str, arguments: dict, executor, trace_id: str) -> dict:
    19. spec = TOOLS.get(name)
    20. if spec is None:
    21. return {"ok": False, "error": f"Unregistered tool: {name}"}
    22. missing = [key for key, rule in spec["parameters"].items() if rule["required"] and key not in arguments]
    23. if missing:
    24. return {"ok": False, "error": f"Missing required parameters: {missing}"}
    25. try:
    26. result = executor(name, arguments) # The executor handles permission checks, idempotency, and timeouts
    27. return {"ok": True, "result": result}
    28. except Exception as exc:
    29. return {"ok": False, "error": str(exc)}
    30. finally:
    31. # Structured audit log: who, in which session, called which tool, with parameter and result summaries
    32. # Redacted request and response records must be retained for traceability and compliance
    33. pass

    5.2 Agent Reliability Comes from Constraints

    The capability boundary of an agent depends on the tool set and process constraints, not on the length of the prompt. Instead of letting the model improvise freely, it is better to break business processes into explicit steps and define the input, output, and validation rules of each step. Outside key steps, there should always be an allowance to fall back to human handling.

    At the same time, an agent-oriented evaluation set is needed. It should cover multi-turn task completion rate, tool-call accuracy, exception recovery capability, and average execution steps. Agent failures are often chain reactions, so monitoring must extend to task granularity.

    6. Observability and FinOps: Turning Inference Systems into Measurable, Operable Infrastructure

    After LLM applications go live, common failures include latency spikes, declining output quality, runaway costs, and excessive calls from individual tenants. They are often discovered only after user feedback because the system lacks a unified observation perspective.

    6.1 Layered Monitoring System

    Layer Key metrics Purpose
    Infrastructure layer GPU utilization, memory usage, temperature, and power consumption Capacity planning and thermal evaluation
    Inference service layer Time to first token, generation speed, queue time, batch size, and cache hit rate Performance tuning and rate limiting
    Application layer Request volume, success rate, token usage, cost per call, and tool-call success rate Cost attribution and quality monitoring
    Business layer Task completion rate, user adoption rate, and human handoff rate Evaluating real business value

    6.2 From Instrumentation to Alerting

    Code 6 gives a lightweight instrumentation context manager. When wrapping key functions, it automatically records duration, status, and attributes. Its output can be connected directly to logging and monitoring/alerting systems.

    1. # Code 6: Lightweight instrumentation context manager
    2. import time
    3. from contextlib import contextmanager
    4. @contextmanager
    5. def trace_span(name: str, **attributes):
    6. record = {"name": name, "attributes": attributes, "status": "ok", "error": None}
    7. started = time.perf_counter()
    8. try:
    9. yield record # Callers can add model name, token counts, etc. to record["attributes"]
    10. except Exception as exc:
    11. record["status"], record["error"] = "error", repr(exc)
    12. raise
    13. finally:
    14. record["duration_ms"] = (time.perf_counter() - started) * 1000
    15. # Emit record as structured logs or metrics so the monitoring side can aggregate percentile latency and error rates
    16. pass

    The usage pattern is as follows:

    1. with trace_span("llm.chat", model="default", intent="qa") as span:
    2. answer = model.chat(messages, max_tokens=512)
    3. span["attributes"].update(request_cost(usage, pricing))

    6.3 FinOps: Make Every Unit of Compute Accountable

    FinOps introduces financial accountability into cloud and compute usage. It is especially important in LLM scenarios. Key practices include:

    • Tag resources by tenant, scenario, and feature to allocate costs to business units.
    • Set budgets and alert thresholds for each business line.
    • Periodically review cache hit rates and model-routing effectiveness, and retire inefficient call paths.
    • In elastic compute scenarios, configure scaling policies based on request fluctuations to balance response speed and cost.

    7. Security, Compliance, and Deployment Models

    When enterprise customers purchase LLM services, they often evaluate not only performance but also whether data and permissions are controllable. Protection is recommended across four layers:

    • Data security: Identify and mask sensitive information, define retention periods, and isolate data by tenant and role.
    • Access control: Retrieval results must be filtered by user permissions to avoid unauthorized access.
    • Content safety: Deploy content moderation on both input and output sides and retain complete call audit records.
    • Deployment models: Choose public cloud API calls, dedicated resources, or private deployment according to industry requirements. The technical architecture should support migrating the same codebase across different models.

    8. Phased Implementation Roadmap and Common Pitfalls

    8.1 Implementation Roadmap

    Phase Core objective Key actions Acceptance signals
    Startup Complete a closed loop for the scenario Integrate model APIs, build a minimal retrieval-augmented pipeline, and complete basic instrumentation End-to-end usability and observability of key metrics
    Growth Controlled cost and measurable performance Model routing, caching, batching, and evaluation sets Declining unit cost and stable regression performance
    Scale Stable multi-tenant operations Elastic scheduling, FinOps, permission isolation, and agent workflows Allocable costs and SLA compliance

    8.2 Common Pitfalls

    • Focusing only on leaderboard scores without building scenario-specific evaluation sets, so quality is judged subjectively.
    • Ignoring the nonlinear cost of long context; as contexts grow longer, bills go out of control.
    • Treating prompt engineering as a universal solution and ignoring data quality as the foundation.
    • Lacking observability, so problems can only be handled passively after user feedback.
    • Treating agents as “longer prompts” and ignoring tool contracts and process constraints.
    • Leaving compliance until late, adding permission and audit capabilities only before customer acceptance.

    Conclusion

    A valuation can grow tenfold within a year, but a technical foundation can only be accumulated line by line in code. An LLM company’s capital story will eventually return to operating reality: whether revenue comes from real usage, whether gross margin improves with scale, and whether customers are willing to renew. For enterprise customers, what matters is not the amount of funding raised, but whether this technical foundation can reliably, controllably, and economically support business operations. Whether a company adopts self-built clusters, elastic cloud compute, or AI infrastructure from Baidu AI Cloud, the measurement standard remains the same: deliver trusted intelligence at measurable cost.