LLM API Cost Calculation for Long Conversations: Formula, Examples, and Cost Controls

    This article explains how to estimate large language model API costs for long and multi-turn conversations. It covers token billing, a per-request cost formula, accumulated multi-turn costs, context trimming and summarization, usage logging, deployment considerations, API key security, and a Python reference implementation using an OpenAI-compatible chat/completions endpoint.

    1. Understand the Billing Unit

    Large language models are billed by token. A token is the smallest unit of text that the model splits input into. Depending on the tokenizer, one token may correspond to a Chinese character, half a Chinese character, or several English characters. Estimating tokens by character count therefore gives only a rough range. For formal budgeting, use the usage field returned by the vendor API.

    Costs usually consist of two parts. Input tokens include all content carried in the request, namely the system prompt and the full conversation history. Output tokens are the reply generated by the model. Most vendors charge more for output tokens than for input tokens. Some platforms offer discounts for input tokens that repeatedly hit a cache; this rule depends on the official price list.

    Prices change over time. All unit prices in this article are hypothetical and are used only to demonstrate the calculation method. Before choosing a model, check the official pricing page of the selected vendor and record the date of the query.

    2. Calculate the Cost of a Single Request

    The cost of a single request is calculated as follows:

    Cost = Input tokens ÷ 1,000,000 × Input unit price + Output tokens ÷ 1,000,000 × Output unit price

    Assume an input unit price of CNY 2 per million tokens, an output unit price of CNY 8 per million tokens, and 1,000 output tokens per reply. The table below lists costs at different context lengths. The last column assumes a fixed context length per turn and estimates how many turns a budget can support.

    Context length (input tokens) Input cost Output cost Total per request Turns supported by CNY 10
    10,000 CNY 0.020 CNY 0.008 CNY 0.028 About 357 turns
    50,000 CNY 0.100 CNY 0.008 CNY 0.108 About 92 turns
    150,000 CNY 0.300 CNY 0.008 CNY 0.308 About 32 turns

    Under the assumed unit prices, a single request with a 150,000-token context costs about CNY 0.3, far more than one cent. Using a cheaper model or enabling cache discounts will reduce the cost accordingly, but the actual unit prices still need to be used for recalculation.

    3. Multi-Turn Conversation Costs Accumulate Turn by Turn

    The key point in multi-turn conversations is that each request resends the full history. Assume each turn adds about 1,000 tokens to the history. The input size in turn n is then about n × 1,000 tokens.

    Take 100 consecutive turns as an example. The total input is about 1,000 × (1 + 2 + … + 100), or about 5.05 million tokens. At CNY 2 per million tokens, the input cost is about CNY 10.1. The output for 100 turns is about 100,000 tokens, costing about CNY 0.8. The total is about CNY 10.9. On this basis, a CNY 10 budget supports about 95 turns, far lower than the number obtained by directly dividing the budget by the single-request cost.

    This shows that cost grows roughly quadratically with conversation length rather than linearly. The cost of each turn rises as the history grows, so budget estimation must account for accumulation.

    If the history is trimmed, for example by capping the context at 60,000 tokens, the input cost per turn will stabilize at about CNY 0.12, and the total cost will grow linearly with the number of turns. How long a budget lasts depends on the number of turns per day and the average context length. Readers can plug their own data into the formula above to get a result closer to actual usage.

    4. Practices for Cost Control

    First, set a context limit. Trigger trimming or summarization when the history length exceeds 60% to 80% of the model context window. For example, if a model has a 128K limit, the threshold can be set at about 80K. After the threshold is exceeded, compress earlier conversation into a summary and keep only key information.

    Second, use a summary prompt. You can ask the model to generate a summary with the following instruction: “Please compress the following conversation into a summary of no more than 300 words, preserving the user’s goals, established conclusions, unresolved issues, and key data, and removing greetings and repetition.”

    Third, record usage. After each call, save the input and output token counts from the usage field, and track daily token volume, daily cost, average response time, and error rate. Set budget alerts in the vendor console so that abnormal costs can be detected in time.

    Fourth, start a new session when appropriate. After the topic changes, the old history contributes little to the current question but continues to increase input costs. Starting a new session can directly reduce costs.

    5. Deployment and Key Security

    Backend services can be deployed on cloud servers, container services, or serverless functions. Major cloud providers offer these services. When selecting a provider, compare four factors: network latency in the user’s region, data compliance requirements, price, and team familiarity. Logging and monitoring services should also be selected so that they can be replaced independently, avoiding deep lock-in with a single platform.

    API keys must be stored in backend environment variables or a secret management service. They must not be written into frontend code or version repositories. Assign the minimum necessary permissions to keys and, if the platform supports it, set spending limits. Rotate keys regularly. If a key is suspected of being leaked, revoke the old key in the console immediately, create a new key, and check call logs for abnormal requests.

    6. Reference Code

    The code below uses the OpenAI-compatible chat/completions endpoint format. Before running it, you need Python 3.9 or later and the requests library, which can be installed with pip install requests. Set the key, API base URL, and model name through environment variables.

    1. import os
    2. import time
    3. import requests
    4. API_KEY = os.getenv("MODEL_API_KEY")
    5. BASE_URL = os.getenv("MODEL_BASE_URL", "https://api.example.com/v1")
    6. MODEL = os.getenv("MODEL_NAME", "your-model-name")
    7. API_URL = BASE_URL.rstrip("/") + "/chat/completions"
    8. MAX_HISTORY_CHARS = 60000 # Conservative history limit estimated by character count
    9. if not API_KEY:
    10. raise RuntimeError("MODEL_API_KEY environment variable is not set")
    11. SYSTEM_PROMPT = {"role": "system", "content": "You are a professional technical assistant."}
    12. history = []
    13. def history_size(messages):
    14. # Rough character-based estimate, used only to trigger trimming
    15. return sum(len(m["content"]) for m in messages)
    16. def trim_history():
    17. # Remove the oldest user/assistant pair until total size is within limit
    18. while len(history) >= 2 and history_size([SYSTEM_PROMPT] + history) > MAX_HISTORY_CHARS:
    19. del history[:2]
    20. def chat(user_input):
    21. history.append({"role": "user", "content": user_input})
    22. trim_history()
    23. payload = {
    24. "model": MODEL,
    25. "messages": [SYSTEM_PROMPT] + history,
    26. }
    27. headers = {"Authorization": f"Bearer {API_KEY}"}
    28. for attempt in range(3):
    29. try:
    30. resp = requests.post(API_URL, json=payload, headers=headers, timeout=60)
    31. resp.raise_for_status()
    32. data = resp.json()
    33. reply = data["choices"][0]
    34. return reply["message"]["content"]
    35. except requests.RequestException:
    36. if attempt == 2:
    37. raise
    38. time.sleep(2 ** attempt)