Building a Lightweight Code-Assistant Agent: Architecture and API Cost Calculation
This article walks through the practical side of building a lightweight code-assistant agent on top of a large language model (LLM) API. It starts with the two pain points that make teams hesitant about LLM APIs—inconsistent output quality and unpredictable billing—then defines the capability boundary such an agent needs (long-context handling, complex code generation and review, and a highly available concurrent architecture). From there it builds a token-based cost model with a worked example for analyzing a mid-sized codebase, and finishes with workflow strategies that keep costs under control: cache-first prompting, RAG-based code retrieval, and streaming output combined with an asynchronous task queue. Readers will come away with a concrete way to estimate per-call API cost and a reference architecture that balances model capability against spend.
1. The Pain Points: Why Engineering Teams Both Love and Distrust LLM APIs
Large language models (LLMs) have spread quickly through software engineering, and more and more technical teams are wiring up LLM APIs to build their own code-assistant agents in the hope of a step change in development productivity. In practice, though, two problems dominate:
- Inconsistent model capability. Output quality swings noticeably on complex code logic and long-context dependencies.
- Unpredictable API cost. The LLM market is crowded and prices change often. A workflow can be running smoothly one day and blow through the project budget the next morning with an unexpectedly large bill.
The task for a technical lead is therefore to find a balance: a model with enough code comprehension and generation ability, at a call cost that stays within what the organization can absorb—the “lightweight” range.
2. Core Requirements: Defining the Capability Boundary
Before starting the project, it is worth pinning down what “lightweight” and “highly available” mean here. For an internal developer-productivity tool, the requirements usually concentrate on three areas:
- Long-context handling. Modern software projects are medium-to-large, with codebases that easily reach hundreds of thousands of lines. The agent has to ingest and understand large context windows (typically hundreds of thousands of tokens of input) before it can produce accurate cross-file refactoring advice.
- Complex code generation and review. Beyond basic completion, the model must write complex algorithms driven by business logic, and even perform vulnerability review and performance optimization.
- High concurrency and high availability. Team-level usage means frequent concurrent calls, so the backend needs elastic scaling. This can typically be built on general cloud-native infrastructure such as the container platform and message queue services offered by Baidu AI Cloud.
3. The Technical Ledger: A Realistic API Cost Model
Setting marketing claims aside, cost is the metric developers care about most. Mainstream LLM APIs generally bill per million tokens (1M tokens), split into input cost, output cost, and cache-read cost. Using the published rates of a mainstream LLM API as an example:
- Input: CNY 0.8 per 1M tokens
- Output: CNY 2.8 per 1M tokens
- Cache read: CNY 0.23 per 1M tokens
Suppose we write a script that has the agent analyze the core modules of a mid-sized project. The task feeds the model roughly 500,000 tokens of context (system prompt, business conventions, and code files) and asks for about 20,000 tokens of suggested changes and refactored code.
At the standard rates, a single call costs:
(0.5 * 0.8) + (0.02 * 2.8) = 0.4 + 0.056 = CNY 0.456 per call
At reduced or promotional rates, where prices are roughly halved, the same call drops to about CNY 0.228. A single call looks cheap, but when an automated pipeline triggers it at high frequency—for example, a full code review on every Git commit—the accumulated bill is still significant. Cost control therefore has to be designed into the architecture rather than bolted on later.
4. Architecture: A Low-Cost, Highly Available Agent Workflow
To protect analysis quality while driving API cost down as far as possible, the workflow has to be designed carefully. These are the strategies that proved most useful in practice.
1. Cache-first prompting. Use the context-caching capability of the LLM API to cache the parts that do not change: the system prompt, the project architecture description, and general coding conventions. Subsequent requests then carry only the changed code snippets, and billing hits the cache-read rate first (usually far below the standard input rate), which cuts input cost substantially.
2. RAG-based precise code retrieval. Do not blindly stuff the entire codebase into the context. Object storage and vector retrieval from Baidu AI Cloud can be used to stand up a local RAG (retrieval-augmented generation) service. When the agent receives a review task, it first retrieves the top-K most relevant code files from the vector database and then assembles them into the prompt. This reduces input tokens and also keeps the model’s attention from scattering, improving generation accuracy.
3. Streaming output and an asynchronous task architecture. Code generation takes a relatively long time to produce output. Streaming improves the user experience and pairs well with an asynchronous task queue for peak shaving. The simplified scheduler below uses a message queue to smooth the API call rate and prevent concurrency limits from causing failed requests or duplicate billing:
import jsonfrom queue import Queueimport threadingclass CodeReviewAgent:def __init__(self, api_client):self.api_client = api_clientself.task_queue = Queue()def add_review_task(self, repo_context, target_file):# Pass only the target file and the most relevant context to keep the input smalltask_payload = {"system_prompt": "You are a senior architect. Review the following code...","context": repo_context,"target_code": target_file}self.task_queue.put(task_payload)def process_tasks(self):while True:task = self.task_queue.get()if task is None:breaktry:# Call the LLM API with caching enabledresponse = self.api_client.chat(model="code-assistant-v1",messages=[{"role": "system", "content": task["system_prompt"]},{"role": "user", "content": task["context"] + task["target_code"]}],enable_cache=True)self.save_review_result(response)except Exception as e:print(f"API call failed, adding to retry queue: {e}")finally:self.task_queue.task_done()# Start multiple consumer threadsagent = CodeReviewAgent(api_client=my_api_client)for _ in range(5):threading.Thread(target=agent.process_tasks, daemon=True).start()
5. Summary and Outlook
LLM APIs have reshaped the software development process, but connecting to them without regard for cost will not survive in enterprise applications. As the cost model and workflow design above show, building a lightweight and efficient code-assistant agent comes down to fitting the concrete business scenario, managing input and output tokens precisely, and using caching plus a RAG architecture to balance capability against cost. As LLM inference technology improves and cloud-native infrastructure matures, developers will be able to reach these gains with an even lower barrier to entry.
