Cost Control for Long-Running LLM Conversations and Tool Calls

    Long-running conversations can make LLM costs grow far beyond initial estimates because every turn may resend the accumulated context. This article explains the token economics behind that growth, the additional costs introduced by tool calls, common sources of context bloat, and practical engineering strategies such as session splitting, history trimming, rolling summaries, tool-output compression, usage budgets, and monitoring.

    1. Background

    Many developers initially focus only on the price of a single request. In real applications, however, model interactions are often multi-turn. The primary cost driver becomes context length rather than the number of requests.

    A common pattern is that an individual task appears small and each request contains only a modest amount of content, yet the total daily usage greatly exceeds expectations. The cause is usually not one unusually expensive request. Instead, conversation history keeps accumulating, and every turn resubmits that history for processing.

    The key to cost control is therefore to understand how context grows and actively constrain it at the engineering level.

    2. Token Billing and Session Accumulation

    A token is a basic unit that a model uses to process text. A piece of text is divided into a number of tokens. Most platforms measure input and output separately, and input charges are usually related to all content submitted to the model.

    In a multi-turn conversation, an application generally submits previous messages together with the new question so that the model can understand the context. This means that the input for turn n contains the content from all previous turns.

    Assume that each turn adds approximately 2,000 tokens and that the conversation continues for 50 turns. The total input volume is:

    1. 2,000 × (1 + 2 + … + 50) = 2,000 × 1,275 = 2,550,000 tokens

    If each turn submitted only its own content, the total input would be just 100,000 tokens. The difference is approximately 25 times. As the number of turns increases, cumulative input grows approximately at a quadratic rate. This is the mathematical basis of runaway costs in long conversations.

    The following code provides a rough estimate of cumulative input and cost for different session lengths. The unit price is only an example; actual pricing should be based on the provider’s published documentation.

    1. def estimate_session_cost(turns: int, tokens_per_turn: int, price_per_million: float):
    2. """Estimate cumulative input tokens and cost for a multi-turn session."""
    3. context = 0
    4. total_input = 0
    5. for _ in range(turns):
    6. context += tokens_per_turn # Context grows with each turn
    7. total_input += context # The full context is submitted each turn
    8. cost = total_input / 1_000_000 * price_per_million
    9. return total_input, cost
    10. tokens, cost = estimate_session_cost(
    11. turns=50,
    12. tokens_per_turn=2000,
    13. price_per_million=1.0
    14. )
    15. print(f"Total input tokens: {tokens:,}, example cost: ${cost:.2f}")

    3. Additional Costs Introduced by Tool Calls

    Tool calls are another major source of context growth. Their cost generally appears in three ways.

    3.1 Tool Results Are Written Back into the Context

    Search results, web pages, and parsed files can be large. When these results are added to the conversation history, they may be resubmitted in every subsequent turn. A seemingly ordinary web retrieval can continue consuming context across the next several or dozen turns.

    3.2 Tools May Be Billed Separately

    Many platforms use a combined pricing model in which model calls and tools are billed independently. Common billable capabilities include web search, web retrieval, file parsing, optical character recognition, and speech processing.

    These charges are separate from model token costs and are easy to overlook.

    3.3 Billing Boundaries Vary by Platform

    Different platforms use different billing rules for similar tools. Some charge per call, some count returned content as tokens, and others do not charge extra for retrieved content but charge for the portion that enters the model context.

    When evaluating platforms and preparing a budget, verify each billing dimension individually rather than assuming that all providers use the same rules.

    4. Common Sources of Context Bloat

    When investigating unexpected costs, check the following areas one by one:

    • Historical tool outputs are not removed: Large search results from earlier turns remain in the conversation history.
    • The system prompt is long and repeated on every turn: The longer the fixed instructions, the higher the baseline cost of every request.
    • Sessions are not reset: A new task continues using an old session and carries irrelevant history into the new task.
    • The same content is retrieved repeatedly: The same web page or file is read multiple times, and the results are repeatedly added to the context.
    • Entire files are inserted into the context: The application sends a full file instead of providing only relevant sections or a summary.

    5. Engineering Strategies for Cost Control

    5.1 Split Sessions by Task

    Session boundaries should align with task boundaries. After a task is complete, start a new session and carry over only the necessary conclusions in a summary rather than the complete history.

    1. SYSTEM_PROMPT = "You are an assistant helping developers complete coding tasks."
    2. def start_new_task_session(summary: str, user_goal: str) -> list[dict]:
    3. """Start a new task with a summary instead of the complete history."""
    4. return [
    5. {"role": "system", "content": SYSTEM_PROMPT},
    6. {
    7. "role": "user",
    8. "content": f"Background summary: {summary}\nCurrent goal: {user_goal}"
    9. },
    10. ]

    5.2 Trim History and Use Rolling Summaries

    Before sending a request, trim the history according to a token budget. Keep newer messages in their original form and compress older messages into a summary when necessary. System messages should always be preserved.

    1. def trim_history(messages: list[dict], max_tokens: int, count_tokens) -> list[dict]:
    2. """Keep the newest messages within the token budget.
    3. System messages are preserved separately.
    4. """
    5. system_msgs = [m for m in messages if m["role"] == "system"]
    6. others = [m for m in messages if m["role"] != "system"]
    7. kept, total = [], sum(count_tokens(m["content"]) for m in system_msgs)
    8. for msg in reversed(others):
    9. cost = count_tokens(msg["content"])
    10. if total + cost > max_tokens:
    11. break
    12. kept.append(msg)
    13. total += cost
    14. return system_msgs + list(reversed(kept))

    With a rolling summary, the model periodically compresses early conversation turns into a summary, and the application replaces the original history with that summary. This can significantly reduce context length while preserving important decisions.

    Summary quality should be checked through sampling or other review methods to ensure that critical constraints are not lost during compression.

    5.3 Compress Tool Outputs

    Tool results should be processed before they are added to the context. Common techniques include:

    • Keep only the main content of a web page and remove navigation, footers, and other irrelevant elements.
    • Return only the sections of a parsed file that are relevant to the current question.
    • Limit list-based results to a fixed number of items and state the total count so the model knows that some information was omitted.
    1. def compact_tool_output(text: str, limit: int = 2000) -> str:
    2. """Keep the beginning and end when the output exceeds the limit."""
    3. if len(text) <= limit:
    4. return text
    5. head_len = limit // 2
    6. tail_len = limit // 4
    7. omitted = len(text) - head_len - tail_len
    8. return (
    9. f"{text[:head_len]}\n"
    10. f"...[approximately {omitted} characters omitted]...\n"
    11. f"{text[-tail_len:]}"
    12. )

    The truncation strategy should match the content type. For structured data, filtering by fields is usually more appropriate than truncating by character count.

    5.4 Set Usage Budgets and Alerts

    Cost control requires hard limits. At a minimum, consider three budget levels:

    1. Per session
    2. Per user per day
    3. Per application per day

    Trigger an alert when usage approaches a threshold. When the limit is reached, reject new requests or require manual approval.

    1. import logging
    2. logger = logging.getLogger("usage")
    3. class UsageBudget:
    4. def __init__(self, daily_limit_tokens: int, warn_ratio: float = 0.8):
    5. self.daily_limit = daily_limit_tokens
    6. self.warn_threshold = int(daily_limit_tokens * warn_ratio)
    7. self.used = 0
    8. def add(self, tokens: int) -> None:
    9. self.used += tokens
    10. if self.used >= self.daily_limit:
    11. raise RuntimeError("Daily token usage limit reached")
    12. if self.used >= self.warn_threshold:
    13. logger.warning(
    14. "Daily usage has exceeded %.0f%%",
    15. self.used / self.daily_limit * 100
    16. )

    Budget values should be based on real usage logs rather than intuition.

    5.5 Monitor Key Metrics

    After deployment, continuously monitor the following metrics:

    • Average and median turns per session
    • The distribution of input tokens per turn, especially P95 and maximum values
    • The proportion of requests involving tool calls and the average length of tool results
    • The growth rate of cumulative tokens per session, which can reveal abnormal sessions

    If a session’s cumulative token count rises sharply within a short period, the likely causes are missing history trimming or a tool that repeatedly returns large amounts of content. Such signals should trigger an alert, and the session identifier should be recorded for reproduction and investigation.

    6. Platform Selection and Cost Evaluation Checklist

    Before selecting a service or designing an implementation, verify the following:

    1. Whether model calls are billed by input tokens, output tokens, or both separately.
    2. Whether each tool is billed independently, and whether billing is based on call count, byte volume, or the number of tokens entering the context.
    3. Whether tool output is counted as input in subsequent turns.
    4. The context-window limit and the platform’s behavior when that limit is exceeded.
    5. Whether repeated prefixes support cached-input pricing, and whether the application meets the relevant conditions. Check the provider’s documentation for current requirements.
    6. Whether detailed usage records can be exported for reconciliation and anomaly investigation.

    7. Practical Recommendations

    Cost optimization should follow a “measure first, optimize second” process.

    First, add instrumentation to record input tokens, output tokens, tool calls, and session identifiers for every request. Next, use real data to identify the largest sources of cost, which are usually long histories or large tool outputs. Finally, apply trimming, compression, or session splitting to the main sources and compare the relevant metrics before and after optimization.

    Different task types can also use different model tiers. Simple question answering can use a smaller model, while complex reasoning can be routed to a more capable model. This helps control average cost while preserving quality for critical tasks.