LLM API Pay-as-You-Go Costs: A Minimal Chat Tool Guide

    This article explains token-based billing for LLM APIs, calculates per-turn costs for short- and long-context chat, shows how to compare pay-as-you-go pricing with monthly plans using a break-even point, and walks through a minimal command-line chat tool with key-management considerations.

    1. Understand the Billing Unit

    LLM APIs usually charge by token. A token is the basic unit of text that the model processes. In Chinese, one character is generally close to one token; in English, about four characters are close to one token. The exact conversion depends on the model’s tokenizer, and actual usage should be based on the statistics returned by the platform.

    The cost has two parts. Input tokens are all the content you send to the model, including conversation history. Output tokens are the answer generated by the model. The unit price for output tokens is usually higher than for input tokens.

    The calculations below use a set of assumed prices only to demonstrate the method. For real prices, refer to the official pricing page of the platform you use:

    • Input: 2 CNY per million tokens
    • Output: 8 CNY per million tokens

    The cost per turn is calculated as: input tokens × input unit price + output tokens × output unit price.

    2. Costs in Two Typical Scenarios

    Scenario 1: Short-context daily Q&A. Each turn has about 1,000 input tokens (the new question plus a small amount of history) and about 500 output tokens.

    • Input cost: 1,000 × 2 ÷ 1,000,000 = 0.002 CNY
    • Output cost: 500 × 8 ÷ 1,000,000 = 0.004 CNY
    • Total: about 0.006 CNY per turn

    At this rate, 10 CNY can support about 1,600 turns. If you chat 50 turns per day, that is about 0.3 CNY per day and about 9 CNY per month (30 days).

    Scenario 2: Long context. The session accumulates to about 100,000 tokens. Each turn sends 100,000 input tokens and generates 1,000 output tokens.

    • Input cost: 100,000 × 2 ÷ 1,000,000 = 0.2 CNY
    • Output cost: 1,000 × 8 ÷ 1,000,000 = 0.008 CNY
    • Total: about 0.208 CNY per turn

    For the same 10 CNY, only about 48 turns are possible.

    The comparison between the two scenarios shows that context length is the main cost variable. Every request resends the conversation history, so the input cost grows linearly as the conversation gets longer. In the same conversation, later turns become more expensive.

    3. Comparing Pay-as-You-Go with Monthly Plans

    Monthly plan prices, quotas, and billing rules vary by platform, so they cannot be generalized. The way to judge is to calculate the break-even point:

    Break-even turns = monthly plan price ÷ per-turn pay-as-you-go cost

    Assume a plan costs 30 CNY per month. In the short-context scenario, the per-turn cost is 0.006 CNY, so the break-even point is 30 ÷ 0.006 = 5,000 turns. If your monthly usage is below 5,000 turns, pay-as-you-go is cheaper. If your monthly usage is far above this amount, the monthly plan is more cost-effective.

    When comparing, also check the plan’s quota limit, available models, and validity period. Some plans include only certain models, or charge a higher unit price after the quota is exceeded.

    4. Build a Minimal Chat Tool

    To build a usable command-line chat tool, the core requires only three steps:

    1. Create an API key on the model platform and save it in an environment variable.
    2. Maintain a message history, and send the history together with the new question on each request.
    3. After receiving the answer, append it to the history and print it for the user.

    The code below can be run directly. Before running it, execute pip install requests and replace LLM_API_URL and LLM_MODEL with the endpoint address and model name for your platform.

    1. import os
    2. import requests
    3. API_URL = os.environ.get("LLM_API_URL", "https://api.example-llm.com/v1/chat/completions")
    4. MODEL = os.environ.get("LLM_MODEL", "your-model-name")
    5. API_KEY = os.environ.get("LLM_API_KEY")
    6. MAX_HISTORY_TURNS = 10
    7. if not API_KEY:
    8. raise SystemExit("Please set the LLM_API_KEY environment variable")
    9. def trim_history(messages, max_turns=MAX_HISTORY_TURNS):
    10. """Keep system messages and only the most recent max_turns turns (one user + one assistant per turn)."""
    11. system_msgs = [m for m in messages if m["role"] == "system"]
    12. others = [m for m in messages if m["role"] != "system"]
    13. return system_msgs + others[-max_turns * 2:]
    14. def chat(messages):
    15. headers = {"Authorization": f"Bearer {API_KEY}"}
    16. payload = {"model": MODEL, "messages": messages}
    17. try:
    18. resp = requests.post(API_URL, headers=headers, json=payload, timeout=30)
    19. resp.raise_for_status()
    20. data = resp.json()
    21. except (requests.RequestException, ValueError) as e:
    22. raise RuntimeError(f"Request failed: {e}") from e
    23. try:
    24. return data["choices"][0]["message"]["content"]
    25. except (KeyError, IndexError, TypeError) as e:
    26. raise RuntimeError(f"Unexpected response format: {data}") from e
    27. def main():
    28. history = [{"role": "system", "content": "You are a helpful assistant."}]
    29. while True:
    30. user_input = input("You: ").strip()
    31. if not user_input:
    32. continue
    33. if user_input.lower() in ("exit", "quit"):
    34. break
    35. history.append({"role": "user", "content": user_input})
    36. try:
    37. reply = chat(trim_history(history))
    38. except RuntimeError as e:
    39. print(e)
    40. history.pop()
    41. continue
    42. history.append({"role": "assistant", "content": reply})
    43. print("AI:", reply)
    44. if __name__ == "__main__":
    45. main()

    There are several points to note in the code. The key is read from an environment variable and is not written into the code. The request has a timeout, and when the network is abnormal or the API returns an error, the program gives a message instead of crashing directly. If a request fails, the program removes the user message that was just added, avoiding an incomplete history.

    5. Engineering Considerations

    Key management. API keys must not be written into frontend code or committed to a Git repository. Store keys in server-side environment variables or a configuration center, and add the .env file to .gitignore. It is advisable to rotate keys regularly. If you suspect that a key has leaked, revoke the old key in the console immediately and generate a new one. Platforms usually support usage caps and usage alerts; enabling them helps detect abnormal calls in time. Use different keys for different services where possible, so that if one key has a problem, the impact is limited.