How LLM API Pricing Works and What to Watch for When Deploying AI Agents
This article explains how LLM API usage is billed, including token-based pricing, time-of-day pricing, and a worked cost estimate. It also covers how AI agents move from suggesting code to executing tasks, the core components of an agent, and the infrastructure and security controls that enterprises need before deploying one.
Large language models are moving from chat-based Q&A into business systems. Developers need to account for two costs: the fees for API calls, and the risks and infrastructure costs of agents that run tasks automatically. This article covers both.
How Is LLM API Usage Billed?
LLM providers offer different product forms for different users. Free web or app chat versions for individuals usually come free or with a basic quota. These cover everyday needs such as text polishing, simple code snippet generation, and data organization suggestions. The exact scope depends on the model version and the use case. Developers who want to connect model capabilities to their own systems and pay by call volume need to use an API.
Most commercial closed-source model APIs charge by token. Some platforms also offer free tiers or credits for new users. Open-source models deployed locally or on your own servers do not require per-token payments to a model provider. However, you bear the cost of compute, GPU memory, and operations. The two options must be costed separately.
How Does Time-of-Day Pricing Work?
Some providers set different prices for different hours based on compute load. A common approach charges more during weekday daytime peak hours, for example 9:00 to 12:00 and 14:00 to 18:00. It charges less at night, during lunch breaks, and on weekends. The exact time windows and discounts follow each provider’s published price list, and they vary widely between providers.
For latency-tolerant tasks such as large-scale data cleaning or offline document parsing, developers can send requests during low-price hours and run them asynchronously. This lowers cost, but it requires a task queue, retry logic, and a process for collecting results. Without these, the savings may be offset by the time spent troubleshooting manually.
How Do Tokens Convert, and How Do You Estimate Cost?
A token is the basic unit a model uses to split text. It is not the same as a character or a word. Punctuation, spaces, English words, and Chinese characters are each split into one or more tokens. There is no fixed conversion ratio for Chinese text, and tokenizers differ between models. In common cases, one Chinese character corresponds to about 1 to 2 tokens. You cannot estimate a bill with a fixed coefficient. Instead, measure actual token counts with the target model’s tokenizer.
Each API call is billed separately for input tokens and output tokens:
Cost per call = input tokens ÷ 1,000,000 × input price + output tokens ÷ 1,000,000 × output price
Both prices are in CNY per million tokens. Check the provider’s price list for current values.
Consider an example. Suppose the model generates a technical document of about 800 Chinese characters during peak hours, from a prompt of about 100 Chinese characters. At 1 to 2 tokens per character, the input is about 100 to 200 tokens, and the output is about 800 to 1,600 tokens. For easy calculation, assume an input price of 2 CNY per million tokens and an output price of 8 CNY per million tokens. These prices are for illustration only and do not represent any provider’s quote. Using 200 input tokens and 1,600 output tokens:
Input cost = 200 ÷ 1,000,000 × 2 = 0.0004 CNYOutput cost = 1,600 ÷ 1,000,000 × 8 = 0.0128 CNYTotal per call = 0.0132 CNY
Generation length varies, so reserve a 20% buffer on output tokens. That means estimating 1,920 output tokens, which brings the cost per call to about 0.01576 CNY.
In high-frequency applications, cost overruns usually come from two sources. The first is prompts that keep growing, which increases input tokens on every call. The second is runaway output, for example when no maximum output length is set or when the model gets stuck repeating itself. For this reason, add a token budget management module early in system design. It should include at least these checks:
- Set maximum input and output token limits for each endpoint.
- Log input tokens, output tokens, and cost for every call, and aggregate them daily.
- Set daily and monthly budget thresholds. Send an alert when spending approaches a threshold, and pause non-critical tasks when it is exceeded.
- Regularly remove redundant system prompts and old conversation history.
- Test samples with the target model’s tokenizer to calibrate your estimates.
How Do AI Agents Move from Advice to Closed-Loop Delivery?
In traditional chat mode, a model can only output text. Developers copy the code, run it locally, and send the error messages back to the model. Then the cycle repeats. This loop depends on manual relay, so it is slow.
AI agent tools aim to let the model take part in execution directly. Take the task of fixing a failing unit test. An agent can read the code repository, locate the relevant files, modify the code, run the tests in a sandbox, and then keep fixing based on the error logs. After the tests pass, it submits a change request. The whole process requires four capabilities: planning, memory, tool use, and an execution environment.
Components of an Agent
- Planning: Breaks a complex requirement into subtasks in a defined order, and adjusts the plan based on results.
- Memory: Stores task progress, attempted solutions, and key context to avoid repeating work.
- Tool use: Accesses code repositories, databases, and terminal commands through function calls. Each tool needs clear parameters and permissions.
- Execution sandbox: Provides an isolated environment for running generated code, so the model receives real execution results.
Comparison: Chat Mode and Agent Mode
In chat mode, the workflow is: ask a question, receive code as text, paste it manually, run it locally, and ask again if there is an error. Every round requires human intervention.
In agent mode, the workflow is: provide a requirement, generate code, run the tests in a sandbox, read the logs and fix issues, and create a change request once the tests pass. If test coverage is sufficient and permissions are controlled, this flow can form a highly automated pipeline that reduces repetitive manual work.
Selection Checklist
Before choosing an agent tool, confirm the following:
- Planning: Does it support task decomposition and re-planning after a failure?
- Memory: Does it save context across steps, and can the saved content be cleared?
- Tool permissions: Can each tool be authorized separately? Is there a read-only mode?
- Sandbox isolation: Is the execution environment separated from production systems, credentials, and the internal network?
- Auditing: Are tool calls, file changes, and command executions all logged?
- Human approval: Can approval checkpoints be set for critical actions such as merging code and deploying?
What Should Enterprises Consider When Deploying Agents?
When an enterprise introduces an agent that can execute actions, it needs to consider both infrastructure capacity and security boundaries.
How Should Infrastructure Be Built?
An agent generates large amounts of state data, logs, and intermediate artifacts during operation. A common approach is to archive code artifacts and test reports in object storage, use a message queue to decouple task scheduling from execution nodes to handle concurrency, and use a container platform to create and destroy execution sandboxes on demand, scaling elastically with workload. The specific products to use should depend on the team’s existing cloud environment and operations capabilities.
How Should Security Boundaries Be Set?
Letting a model execute code or operate production environments directly introduces risks such as accidental operations, data leakage, and runaway costs. At a minimum, the following measures should be in place:
- Network isolation: The execution environment may only access the necessary dependency sources, and arbitrary outbound connections are blocked.
- Credential isolation: Production keys are never placed in the sandbox. Required credentials are granted temporarily through short-lived tokens.
- Operation auditing: All tool calls, file reads and writes, and command executions are sent to a central logging service with monitoring and alerts configured.
- Resource limits: Each task has limits on runtime, memory, and number of calls, which prevents infinite loops from consuming budget.
- Human oversight: Key steps such as code merges, production deployments, and permission changes require engineer approval before they proceed.
A sandbox reduces risk but cannot eliminate it. An agent can still generate incorrect code or misread a requirement, so approval checkpoints should not be skipped.
Summary
LLM API costs need to be calculated precisely by token count and time of day. Rough estimates are not enough. Agent tools are shifting models from advisors to executors, but their value depends on whether permission controls, auditing, and human approval are in place. Developers can start with small-scale tasks to verify cost tracking and the sandbox workflow. After confirming the data, they can gradually expand the scope.
