LLM Selection in the Agent Era: Efficiency-First Engineering Practices

    In the era of AI agents, multi-step task execution makes token consumption the primary cost driver. This article explores efficiency-first engineering practices for large language model (LLM) selection and application. It covers building a task cost model, tiered model selection based on task complexity, strategies to reduce output and compress input tokens, managing tool calls, controlling multi-agent orchestration costs, and conducting joint evaluations focused on quality and security.

    1. Background: Tokens Become the Core Cost in the Agent Era

    Early LLM applications primarily focused on single-turn Q&A, where inputs and outputs were short, making costs easy to estimate. In the Agent stage, a task typically involves task decomposition, information retrieval, tool calling, result parsing, and plan revision. Each step requires re-carrying the context and generates new output. Therefore, the total task cost is determined by multiple factors rather than just the price of a single call.

    Engineering teams usually focus on three metrics:

    • Input token count: The longer the context, the higher the base cost per call.
    • Output token count: More verbose generation increases inference time and cost.
    • Number of tool calls: Each call may trigger a new round of model inference.

    These three metrics interact. For instance, returning raw logs from a tool directly into the context increases both input tokens and the length of subsequent analysis text generated by the model.

    2. Cost Model: Deconstructing Task Costs

    A simplified formula can estimate the cost of a single task:

    Task Cost ≈ Σ (Round i Input Tokens × Input Unit Price + Round i Output Tokens × Output Unit Price) + Number of Tool Calls × Tool Cost per Call

    Unit prices depend on the service provider’s pricing and should be based on actual billing. What is truly controllable in engineering is the token count and the number of call rounds. The following example passes prices as parameters to avoid hardcoding them:

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Turn:
    4. input_tokens: int
    5. output_tokens: int
    6. tool_calls: int = 0
    7. def estimate_cost(turns, price_in, price_out, tool_cost=0.0):
    8. """price_in / price_out are the unit prices per million tokens, provided by configuration."""
    9. total = 0.0
    10. for t in turns:
    11. total += t.input_tokens / 1_000_000 * price_in
    12. total += t.output_tokens / 1_000_000 * price_out
    13. total += t.tool_calls * tool_cost
    14. return total

    With this function, you can perform offline replays on the same batch of historical tasks to compare the total tokens and call counts of different strategies, without relying on online guessing.

    3. Model Tiering: Selecting Capabilities by Task Difficulty

    Using a single model for all tasks often means paying too high a cost for simple tasks. A more reasonable approach is tiering:

    • Complex planning, architecture design, and difficult troubleshooting: Use the most capable model, accepting a higher unit price.
    • Daily coding, documentation organization, structured extraction: Use the main workhorse model, balancing quality and cost.
    • Classification, routing, simple rewriting, batch processing: Use a lightweight model, prioritizing throughput and latency.

    Selection should not rely solely on public benchmark scores. Teams should base decisions on the pass rate of their own task sets, as different businesses have varying requirements for format, accuracy, and response time.

    Routing can be implemented with simple rules, combined with an escalation mechanism:

    1. def pick_model(task):
    2. if task.kind in {"architecture", "root_cause"}:
    3. return "strong"
    4. if task.kind in {"classify", "simple_extract"}:
    5. return "light"
    6. return "workhorse"
    7. def run_with_fallback(task, call_model, validate):
    8. result = call_model(pick_model(task), task)
    9. if not validate(result):
    10. # If the main model's result fails validation, escalate to the strong model for one retry
    11. result = call_model("strong", task)
    12. return result

    The escalation mechanism controls quality risks while preventing all tasks from using high-priced models.

    4. Engineering Methods to Reduce Output Tokens

    Output tokens are often more expensive than input tokens and easier to lose control over. Common methods include:

    1. Constrain output structure: Require the model to return only JSON or specific fields, removing pleasantries, repetitive descriptions, and irrelevant explanations.
    2. Incremental output: When modifying code, return only the changed snippet (e.g., unified diff or a specific function) rather than the entire file.
    3. Control inference verbosity: State in the instructions that only conclusions and key evidence are needed. For steps requiring auditing, retain necessary step records without expanding the rest.
    4. Set a max_tokens limit and check if the response is incomplete due to truncation.

    Below is a prompt example for a code modification scenario:

    1. You are a code modification assistant. Output only the modifications in unified diff format, without explanations.
    2. If the modification cannot be completed, output only one line: ERROR: reason.

    Constrained outputs are shorter and easier for programs to parse and apply directly, reducing manual rework costs.

    5. Compressing Inputs: Keeping Only Useful Information in Context

    Input tokens accumulate with each round. Without control, the cost of long tasks will trend upward. Compression can be approached from the following angles:

    • Filter tool results before returning: For example, keep only the error level, filename, and line number from logs.
    • Retrieve long documents by section or paragraph, injecting only the relevant parts.
    • Periodically generate status summaries for multi-turn conversations, replacing early raw records with summaries.
    • Place fixed guidelines and instructions in a stable prompt prefix. If the server supports caching for repeated prefixes, stable prefixes can reduce duplicate billing.

    Example of log filtering:

    1. def trim_log(lines, keywords=("ERROR", "FAILED"), max_lines=50):
    2. hits = [line for line in lines if any(k in line for k in keywords)]
    3. return hits[:max_lines]

    Filtering logic should be designed alongside business scenarios. Too broad keywords will retain noise, while too strict ones may lose root cause information; thus, validation with an evaluation set is necessary.

    6. Reducing Unnecessary Tool Calls

    Each tool call may bring a round of inference, so call governance is as important as token optimization. Common practices include:

    • Plan first: List required information at the beginning of a task and fetch it in batches to avoid trial-and-error.
    • Result caching: Reuse existing results for queries with identical parameters within the same session.
    • State checking: Do not repeatedly query confirmed states to reduce invalid calls.
    • Call limits: Set a maximum number of calls for a single task. Once exceeded, require the model to report current progress and wait for confirmation.

    Call limits also prevent the model from repeatedly trying wrong approaches, which is especially common in tasks without explicit termination conditions.

    7. Cost Control in Multi-Agent Orchestration

    Multi-agent collaboration can split complex tasks among different roles, but adding each role increases the overhead of context passing and repeated inference. Control should focus on:

    • Clear role boundaries: Each sub-task receives only the context needed to complete the work.
    • Pass structured handoff tickets between sub-tasks, including goals, inputs, constraints, and output formats, rather than the full conversation history.
    • Set up a summarization role to deduplicate and integrate conclusions, preventing multiple roles from repeatedly discovering the same issue.
    • Set concurrency limits for parallel sub-tasks to prevent call volumes from spiraling out of control in a short time.

    The structure of the handoff ticket can be uniformly defined for reuse and auditing:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class Handoff:
    4. goal: str
    5. inputs: dict
    6. constraints: list = field(default_factory=list)
    7. output_format: str = "json"

    8. Joint Evaluation Premised on Quality

    Cost optimization must be premised on quality. It is recommended to establish an internal evaluation set where each sample includes input, expected result, and validation method. Core metrics include:

    • Task success rate.
    • Average input and output tokens.
    • Average tool calls.
    • End-to-end latency.
    • Cost per successful task, i.e., total cost divided by the number of successful tasks.

    The last metric best reflects the true effect. A solution with a low unit price but also a low success rate may incur higher hidden costs from retries and manual corrections.

    1. def cost_per_success(results):
    2. """Each item in results contains passed (boolean) and cost (float)."""
    3. total = sum(r["cost"] for r in results)
    4. passed = sum(1 for r in results if r["passed"])
    5. return total / passed if passed else float("inf")

    Evaluation should be completed before deployment and re-run periodically afterwards, as model versions, prompts, and business data will change.

    9. Security and Compliance Considerations

    Cost optimization cannot come at the expense of security. Note the following:

    • Inject keys and tokens via environment variables or secret management services; do not write them into prompts, code, or logs.
    • Tool permissions follow the principle of least privilege. Write operations such as deletion, publishing, and permission changes should require manual confirmation.
    • Perform structural validation and whitelist checks on model outputs before execution to prevent incorrect formats or unauthorized instructions from taking effect.
    • Desensitize user data before saving logs.

    10. Implementation Roadmap

    1. Review existing tasks, calculate token consumption and tool call counts by type, and identify cost-intensive areas.
    2. Establish an evaluation set and determine a quality baseline, such as the minimum task success rate.
    3. Prioritize low-risk improvements, including output format constraints, tool result trimming, and call limits.
    4. Introduce model tiering and routing rules; verify in grayscale first, then gradually expand the scope.
    5. Continuously monitor the cost per successful task.