Reducing LLM Inference Costs and Engineering AI Agents in Practice

    This article covers three areas for teams moving LLM applications into production: where inference bottlenecks appear under high concurrency and which common optimizations address them, why AI agents fail in production and how process design and constraints improve task success rates, and what engineering work is needed when document parsing moves from traditional pipelines to vision-language models.

    1. Background: After Capability Gains, Engineering Becomes the Bottleneck

    As model capabilities improve, many teams shift their question from “Can the model do this?” to “Can the service run stably and at a reasonable cost?” Long context, multi-turn conversations, tool calls, and batch document processing all increase pressure on compute, GPU memory, and latency at the same time.

    This article addresses three questions:

    1. Under high concurrency, where are the bottlenecks in an inference service, and what problem does each common optimization solve?
    2. Why do AI agents tend to lose control, and how can process design and constraints improve task success rates?
    3. When document parsing moves from traditional pipelines to vision-language models, what additional engineering steps are needed?

    The optimization methods discussed here are common practices across the industry. Actual gains depend on model size, hardware, request distribution, and business metrics, so validate them with measured data before launch.

    2. Core Bottlenecks in High-Concurrency Inference

    2.1 Prefill and Decode Have Different Resource Profiles

    A generation request typically has two phases:

    • Prefill: The model processes the entire input prompt at once. This phase is compute-intensive and mainly consumes compute resources.
    • Decode: The model generates output tokens one at a time. Each step reads the model weights and the cached history, so this phase is mainly limited by memory bandwidth.

    The two phases have different bottlenecks, so running them under the same scheduling logic can cause them to interfere with each other. For example, a very long input can saturate compute during prefill. Other requests that are in the decode phase then stall noticeably, and their output pauses suddenly.

    2.2 The KV Cache Is the Main Consumer of GPU Memory

    To avoid repeated computation, inference caches the Key and Value tensors for each layer. This is called the KV cache. You can estimate its memory footprint with the following approximate formula:

    1. KV cache memory ≈ 2 × num_layers × num_kv_heads × head_dim × seq_len × num_concurrent_requests × bytes_per_element

    The factor of 2 accounts for the separate K and V caches. The formula shows that both concurrency and sequence length increase memory usage. Even a small number of long-context requests can occupy a large share of GPU memory and force other requests to queue.

    2.3 Uneven Request Lengths Create Batching Bubbles

    Traditional static batching requires all requests in a batch to start and finish together. If one request generates a long output, the slots of the requests that already finished sit idle. This is called a batching bubble. The more widely request lengths are spread, the more resources are wasted.

    3. Common Optimizations and When to Use Them

    3.1 Continuous Batching

    Continuous batching uses a single decode step as the scheduling unit. After each step, finished requests leave the batch immediately, and new requests from the waiting queue join right away. The following is a simplified sketch of the scheduling logic:

    1. from collections import deque
    2. def continuous_batching_loop(waiting: deque, running: list, max_batch_tokens: int):
    3. """Rebuild the batch in each scheduling cycle. Finished requests leave immediately, and new requests fill the freed slots."""
    4. while waiting or running:
    5. # 1. Remove finished requests and release their KV cache
    6. running = [r for r in running if not r.finished]
    7. # 2. Admit waiting requests while they fit within the token budget
    8. budget = max_batch_tokens - sum(r.current_len for r in running)
    9. while waiting and waiting[0].prompt_len <= budget:
    10. req = waiting.popleft()
    11. budget -= req.prompt_len
    12. running.append(req)
    13. # 3. Run one decode step for every running request (step_decode is the model's single-step decode function, omitted here)
    14. step_decode(running)

    This approach noticeably reduces batching bubbles and is a core capability of high-concurrency services. Two points matter during implementation. First, the token budget must account for the length already generated, so GPU memory does not overflow. Second, the scheduling policy needs clear priorities so that long requests do not hold resources indefinitely and starve other requests.

    3.2 Paged KV Cache Management

    If each request is allocated a contiguous block of GPU memory in advance, sized for the longest possible output, the result is a large amount of internal fragmentation. Paged management instead splits the KV cache into fixed-size blocks, allocates them on demand, and uses a block table to map logical positions to physical blocks.

    This approach borrows from virtual memory paging in operating systems. Its direct benefit is less memory fragmentation, which allows more concurrent requests to fit in the same amount of GPU memory.

    3.3 Prefix Caching

    Many business requests share the same system prompt, knowledge base snippets, or tool descriptions. Prefix caching stores the KV values for prefixes that were already computed. When a new request hits the cache, it reuses those values and computes only the differing part.

    Typical use cases include customer service bots with a fixed role definition, code review workflows with shared guidelines, and repeated Q&A over the same document. The hit rate depends on how much prefix repetition exists across requests, so confirm it with request log statistics.

    3.4 Chunked Prefill

    When a very long input enters the prefill phase, the system can split it into several chunks and process only one chunk per scheduling cycle. The remaining prefill work is interleaved with ongoing decode requests. This slightly increases the time to first token for the long request, but it prevents other users’ output from stalling for long periods.

    3.5 Quantization

    Quantization reduces the numerical precision of model weights or the KV cache to save memory and bandwidth. Common approaches include weight quantization and KV cache quantization.

    Quantization requires accuracy validation. Compare task accuracy before and after quantization on your own evaluation set. Pay particular attention to tasks that are sensitive to errors, such as numerical calculation, structured output, and long-context retrieval.

    3.6 Speculative Decoding

    Speculative decoding uses a smaller draft model to quickly generate several candidate tokens. The target model then verifies them in one pass. If the verification succeeds, the system has generated multiple tokens in a single step.

    The benefit depends on how closely the draft model matches the target model. The gains are more noticeable for highly predictable output, such as formatted output or code completion, and more limited for highly divergent creative tasks. The method usually does not change the output distribution, but it requires extra resources for the draft model, so evaluate it together with the deployment.

    3.7 Combining Optimizations

    More optimizations do not always mean better results. Introduce them in the following order:

    1. Start with continuous batching and paged caching. These form the foundation for high concurrency.
    2. Based on the request characteristics of your business, decide whether to enable prefix caching and chunked prefill.
    3. Introduce quantization where the accuracy loss is acceptable.
    4. Finally, evaluate the benefit and extra cost of speculative decoding.

    After introducing each change, compare the metrics before and after. Move to the next step only after you confirm the gain.

    4. Engineering Strategies for Long Text

    4.1 Longer Context Is Not Always Better

    Putting all materials into a single request causes three problems. Cost rises linearly with input length, the time to first token increases, and the model makes less effective use of information in the middle of the context. For long text processing, the key question is what to include, not how much you can fit.

    Common strategies include:

    • Retrieval-augmented generation (RAG): Retrieve the passages relevant to the question first, then send only those to the model.
    • Hierarchical summarization: Generate summaries for each section of a long document, then answer global questions based on the summaries.
    • Sliding-window chunking: For tasks that process text segment by segment, keep some overlap between chunks so that meaning is not cut off at the boundaries.

    4.2 Implementing Chunking

    The following is a simple chunking function with overlap:

    1. def chunk_text(text: str, size: int = 1000, overlap: int = 100) -> list[str]:
    2. """Split text by character count, keeping an overlap of `overlap` characters between adjacent chunks."""
    3. if overlap >= size:
    4. raise ValueError("overlap must be smaller than size")
    5. chunks, start = [], 0
    6. while start < len(text):
    7. chunks.append(text[start:start + size])
    8. start += size - overlap
    9. return chunks

    In real projects, split text along semantic boundaries, such as headings, paragraphs, code functions, or table rows, rather than splitting mechanically by character count. Choose the chunk size based on the model’s context window, the retrieval precision, and the granularity of the business questions, and tune it with an evaluation set.

    4.3 Use the Official Context Window Specifications

    The context window a model declares is an upper limit, not a recommended amount. As input approaches the limit, output quality and stability usually decline. In engineering practice, set a soft limit on input length, and send any input beyond that limit to the chunking or summarization pipeline.

    5. Engineering AI Agents

    5.1 Common Failure Causes

    Agents often perform well in demos but fail in production. The main causes include:

    1. Vague tool descriptions: Unclear parameter meanings lead the model to fill in wrong fields or pass invalid values.
    2. Missing state management: In multi-step tasks, earlier results are lost or referenced incorrectly.
    3. Infinite loops: The model repeatedly calls the same tool without making useful progress.
    4. No error recovery: When a tool fails, the whole task stops, or the model ignores the error and continues.
    5. No confirmation for high-risk actions: Operations such as deleting files, sending messages, or changing permissions run without approval.
    6. No evaluation: Quality is judged by subjective impression alone, so regressions go unnoticed after changes.

    5.2 Core Architecture: A Constrained Execution Loop

    A controllable agent usually runs a loop of decide, validate, execute, and observe. The model decides the next action, and the program handles validation, execution, and fallback. The following is a simplified example:

    1. MAX_STEPS = 8
    2. DESTRUCTIVE_TOOLS = {"delete_file", "send_message"}
    3. def run_agent(task: str, llm, tools, confirm) -> str:
    4. history = [{"role": "user", "content": task}]
    5. for _ in range(MAX_STEPS):
    6. action = llm.decide(history, tool_schemas=tools.schemas())
    7. if action.type == "final":
    8. return action.content
    9. name, args = action.tool, action.arguments
    10. # Allowlist check: only registered tools can be called
    11. if name not in tools:
    12. history.append(error_msg(f"Unknown tool: {name}"))
    13. continue
    14. # Parameter validation: types, ranges, and required fields
    15. ok, reason = tools.validate(name, args)
    16. if not ok:
    17. history.append(error_msg(reason))
    18. continue
    19. # High-risk operations require human confirmation
    20. if name in DESTRUCTIVE_TOOLS and not confirm(name, args):
    21. history.append(error_msg("User rejected this operation"))
    22. continue
    23. # Set a timeout for tool calls and return results in a structured form
    24. result = tools.call(name, args, timeout=10)
    25. history.append(observation(result))
    26. raise RuntimeError("Maximum number of steps exceeded, task terminated")

    This code applies several principles: a tool allowlist, parameter validation, a step limit, timeout control, and human confirmation. error_msg and observation are helper functions that normalize results before they are added to the history.

    5.3 State and Memory

    Multi-step tasks should store key state explicitly in the program, rather than relying entirely on the model’s conversation history.