How to Choose Models for Structured Generation: Multi-Model Routing to Cut Token Costs

    This article walks through a practical approach for evaluating large language models on structured extraction and generation tasks, such as turning messy text into tables or JSON. It explains how to compare model output quality, identify hidden cost differences (input token counting, output verbosity, and per-token pricing), and implement a lightweight routing layer that dispatches tasks to the cheapest suitable model. A Python code example demonstrates intent classification, fallback logic, JSON validation, and retry behavior, followed by a monitoring strategy with sample thresholds for production.

    When large language models move from experiments to real enterprise workflows, the question shifts from “can it do the task?” to “how much does it cost to do the task?” Structured extraction and generation—like producing Excel tables, CSV files, or JSON objects—are high-frequency, well-specified scenarios. This article uses such tasks as an example to show how to evaluate whether multiple models meet your quality bar, and how to control token expenses through multi-model routing.

    1. Testing Methodology for Structured Generation Tasks

    In data governance, financial reconciliation, and report generation, a common requirement is converting messy or unstructured text into a consistent table. For testing, we ask a model to produce a table from a given text with fixed column names, uniform date and amount formats, and no missing values. Scoring covers three criteria:

    • Data completeness: all required fields are present.
    • Format accuracy: dates and amounts follow the specified patterns.
    • Field alignment: values map correctly to the intended columns.

    In our tests, four models—including both standard and lightweight variants—passed all three criteria with acceptable accuracy. These results apply only to the specific sample set and configuration used. The model versions, prompt content, temperature, max_tokens limit, and sample size should be recorded together with the conclusions. If the sample size or text complexity changes, the outcome may differ.

    2. Same Output, Different Bill

    When outputs are nearly identical, cost becomes the deciding factor. In the original test, the four models produced the same table, but the token consumption per single call differed by up to about 85% between the most and least expensive. That number does not reveal model versions, input lengths, or the billing date, so readers should re-test with their own samples before adopting any conclusions.

    Three common reasons explain the cost gap:

    2.1 Input Token Counting Differences

    Different tokenizers split the same text in different ways, leading to different token counts. Some platforms also offer prompt caching: if a repeated system prompt hits the cache, the billing rules change. To compare input costs fairly, use the same input prompt and count tokens under the same billing scheme.

    2.2 Output Verbosity

    Structured tasks should return only the data, but some models prepend phrases like “Sure, here is the table you need:” or append explanatory notes after the table. These extra tokens inflate the output cost and force downstream code to strip them with regex.

    2.3 Model Tier and Price per Token

    Larger flagship models have higher unit prices. For well-defined table generation tasks, a lightweight model often meets the requirements, with a price per token that can be roughly one-tenth of a flagship model’s. Exact ratios depend on each platform’s published pricing.

    3. Route by Task Complexity

    If multiple models have similar capabilities but different prices, always using one model is rarely the most economical strategy. A routing layer can select the model based on task type. The design has three main parts:

    3.1 Task Classification

    Before a request reaches the LLM, a lightweight classifier determines the intent. Low-complexity tasks like “extract a table from text” or “convert format to CSV” are routed to a lightweight model. Complex tasks like “multi-step logical reasoning” or “complex code generation” go to a flagship model. Keyword rules can only cover common patterns, so the classifier should output a confidence score. If confidence falls below a threshold (for example, 0.7—adjust based on your own data), the request is sent to the standard model instead.

    3.2 Unified Access

    Most cloud LLM platforms provide a unified API gateway. Developers can call different models through the same interface and observe token consumption and success rates per model in the console. These metrics help tune the routing weights between models.

    3.3 Output Constraint

    For lightweight models, you can simplify the prompt by removing unnecessary modifiers and requesting a JSON response. Note that max_tokens only truncates the output when the limit is reached; it does not prevent the model from generating extra text. Therefore, always validate the output as JSON. If validation fails or the output is truncated, retry once with the same tier. If it still fails, upgrade to a stronger model.

    4. Routing Code Example

    Below is a simplified Python skeleton that demonstrates classification, retry, upgrade, and logging. In production, replace client with the platform’s SDK client and use real model names.

    1. import json
    2. import logging
    3. logger = logging.getLogger("router")
    4. MODELS = {
    5. "lightweight": {"name": "cost-effective-model-v1", "price_per_1k": 0.001},
    6. "standard": {"name": "balanced-model-v1", "price_per_1k": 0.008},
    7. "flagship": {"name": "high-end-model-v1", "price_per_1k": 0.05},
    8. }
    9. FALLBACK_ORDER = ["lightweight", "standard", "flagship"]
    10. def classify_task(prompt: str) -> tuple[str, float]:
    11. """Return task tier and confidence. The example uses keyword rules;
    12. in production, replace with a trained classifier."""
    13. light_kw = ["generate table", "convert to CSV", "extract fields", "format"]
    14. heavy_kw = ["logical reasoning", "architecture design", "complex code"]
    15. if any(k in prompt for k in light_kw):
    16. return "lightweight", 0.9
    17. if any(k in prompt for k in heavy_kw):
    18. return "flagship", 0.9
    19. return "standard", 0.5
    20. def valid_json(text: str) -> bool:
    21. try:
    22. json.loads(text)
    23. return True
    24. except json.JSONDecodeError:
    25. return False
    26. def call_model(client, model_name, prompt, data, max_tokens=1024):
    27. # In a real call, client is the platform SDK client.
    28. return client.chat(model=model_name, prompt=prompt, data=data, max_tokens=max_tokens)
    29. def execute_task(client, prompt, data, threshold=0.7):
    30. tier, confidence = classify_task(prompt)
    31. if confidence < threshold:
    32. tier = "standard"
    33. for tier_name in FALLBACK_ORDER[FALLBACK_ORDER.index(tier):]:
    34. model = MODELS[tier_name]["name"]
    35. for attempt in range(2):
    36. try:
    37. text = call_model(client, model, prompt, data)
    38. except Exception as exc:
    39. logger.warning("call failed model=%s attempt=%d error=%s", model, attempt, exc)
    40. continue
    41. if valid_json(text):
    42. logger.info("completed model=%s tier=%s", model, tier_name)
    43. return text
    44. logger.info("JSON validation failed model=%s attempt=%d", model, attempt)
    45. raise RuntimeError("all tiers failed to return a valid result")

    The example does not include cost logging. In production, record input tokens, output tokens, and unit price for every call, then aggregate by task type.

    5. Monitoring After Launch

    Once the routing system is live, continuously track the following metrics. The thresholds below are illustrative—adjust them according to your business baseline.

    Metric Calculation Sample Threshold Alert Action Owner
    Task success rate Proportion of requests that pass JSON validation and missing-field checks A drop of more than 5 percentage points for a task type Auto-upgrade that task type to the standard model and notify developers Backend development
    Average token consumption Mean input and output tokens per task type More than 20% increase compared to last week Review the bill, inspect prompt length and output length Platform operations
    Retry rate Proportion of requests that trigger a retry Above 5% Check prompt templates and classification rules Backend development
    Prompt changes Version history of templates Every modification Re-evaluate old vs. new templates on the test set for pass rate and cost Business development

    Conclusion

    In structured generation tasks, the capability gap between models is narrowing, but the cost gap remains significant. Teams should first verify each model’s pass rate on their own test set, then use a routing layer to keep both cost and quality within acceptable bounds. This approach is vendor-neutral and easy to adjust when model prices change.