Lightweight Flagship LLMs in Practice: Code Generation Evaluation and Cost Control

    This guide explains how to evaluate lightweight flagship language models for code generation, using a browser-based construction of a regular heptagon as the test task. It covers reproducible testing, HTML and GIF validation, common implementation failures, execution safety, and a practical method for estimating and reducing daily API costs.

    1. What Is a Lightweight Flagship Model?

    A lightweight flagship model is a model positioned between a provider’s most capable and entry-level offerings: it is cheaper and faster than the top-tier model while delivering stronger capabilities than the basic model. Both “lightweight” and “flagship” are relative terms.

    Parameter count is not a reliable selection criterion. Most providers do not publish parameter sizes, and models with similar parameter counts can perform very differently because of differences in training and compression methods.

    When selecting a model, use three observable metrics:

    • Price per token
    • Time to first token and output speed
    • Pass rate on your own test set

    Only when all three are available can you determine which workloads a model is suitable for.

    The boundaries should also be clear. Lightweight flagship models work well for frequent, structured tasks such as code completion, template-based HTML generation, and API documentation conversion. For tasks involving long-chain reasoning, cross-file refactoring, or high error costs, establish a baseline with the most capable model first. Then evaluate whether the lightweight model can replace it.

    2. Testing Methodology and Version Tracking

    Evaluation results are useful only when they can be reproduced. Save the following fields together with every test result:

    • Model name and version, using the complete value passed in the model field
    • Request date and access region
    • Sampling parameters: temperature, top_p, and max_tokens
    • Runtime environment, including browser version and GIF export library version
    • Input token count, output token count, and cache-hit status for every request

    Run each test case at least five times and record the number of successful runs. Lightweight models can produce noticeably different outputs across runs, so a single result cannot represent overall performance.

    The following script uses an OpenAI-compatible API. The endpoint, API key, and model name are loaded from environment variables and should not be hard-coded.

    1. import os, json, time
    2. from openai import OpenAI
    3. client = OpenAI(
    4. base_url=os.environ["LLM_BASE_URL"],
    5. api_key=os.environ["LLM_API_KEY"],
    6. )
    7. MODEL = os.environ["LLM_MODEL"] # Set the exact model version
    8. PROMPT = open("prompt_heptagon.txt", encoding="utf-8").read()
    9. def run_once(i):
    10. start = time.time()
    11. resp = client.chat.completions.create(
    12. model=MODEL,
    13. messages=[{"role": "user", "content": PROMPT}],
    14. temperature=0.2,
    15. max_tokens=8192,
    16. )
    17. text = resp.choices[0].message.content
    18. with open(f"out_{i}.html", "w", encoding="utf-8") as f:
    19. f.write(text)
    20. return {
    21. "run": i,
    22. "latency_s": round(time.time() - start, 2),
    23. "prompt_tokens": resp.usage.prompt_tokens,
    24. "completion_tokens": resp.usage.completion_tokens,
    25. }
    26. if __name__ == "__main__":
    27. logs = [run_once(i) for i in range(5)]
    28. with open("runs.json", "w", encoding="utf-8") as f:
    29. json.dump(logs, f, ensure_ascii=False, indent=2)

    Model responses are often wrapped in an ```html code block. Remove the fence markers before saving the response; otherwise, the browser cannot open the file directly.

    3. Test Case: Constructing a Regular Heptagon with a Two-Marked Ruler

    The geometric background is important. A regular heptagon cannot be constructed using straightedge and compass alone, as established by the Gauss–Wantzel theorem. A two-marked ruler is a non-standard construction tool whose marks can slide during construction while remaining aligned with a specified curve or point. With this tool, a regular heptagon can be constructed.

    The test therefore has two layers:

    1. Whether the geometric construction is valid
    2. Whether the code correctly renders the construction process

    Use the following test prompt:

    Create an HTML page that demonstrates constructing a regular heptagon with a two-marked ruler. First, draw a square and construct the perpendicular bisector of its bottom edge. Then use the lower-right vertex E as the center of circle E, with the square’s diagonal as the radius. Next, use the two-marked ruler while keeping it aligned with the lower-left vertex D. Move the ruler’s first mark along circle E until its second mark passes through the perpendicular bisector of the bottom edge. Complete all omitted straightedge-and-compass construction steps, including the usual steps needed to determine the center. When using the compass, moving points may leave a trace, but only the necessary parts of the construction should remain visible. Finally, add a feature that exports the animation as a GIF.

    Check every generated page against the following criteria:

    1. The page opens successfully without console errors.
    2. The square and the perpendicular bisector of its bottom edge are positioned correctly, with an error no greater than 0.5% of the canvas width.
    3. The radius of circle E equals the length of the diagonal.
    4. During the two-marked ruler movement, only the necessary trajectory segments remain visible.
    5. The seven final vertices form a regular heptagon, with a relative side-length error no greater than 1%.
    6. Clicking the export button downloads a playable GIF.

    Common failures and troubleshooting methods include:

    • Blank page: The canvas may not have obtained a 2D context, or the script may have executed before the DOM was loaded. Move the script to the end of the body, or wrap it in a DOMContentLoaded handler.
    • Empty GIF or GIF with only one frame: The animation loop may not call the frame-capture function, or the frame interval may be zero. Call addFrame for every frame and set a reasonable delay.
    • Upside-down drawing: Canvas uses a downward-pointing y-axis, while geometric formulas typically use a mathematical coordinate system. Flip the y coordinate once before drawing.
    • All trajectories retained or all trajectories missing: The canvas may not be cleared on every frame, or auxiliary lines and trajectories may be drawn on the same layer. Put trajectories and auxiliary graphics on separate canvases so they can be cleared independently.

    Open generated HTML in an isolated environment, such as a separate origin or a sandboxed iframe. Model-generated code is untrusted and should not be executed directly on a main site or on a page containing an authenticated session.

    4. Cost Calculation and Optimization Checklist

    The daily cost formula is:

    Daily cost = Total input tokens × Input price × (1 − Cache hit rate) + Total input tokens × Cache hit rate × Cached input price + Total output tokens × Output price

    The following example uses hypothetical figures to demonstrate the calculation method. These prices are not actual quotations; use the provider’s current pricing documentation for real calculations.

    Assume:

    • 2,000 requests per day
    • 3,000 input tokens per request
    • 2,000 output tokens per request
    • 40% cache hit rate
    • Uncached input price: 4 currency units per million tokens
    • Cached input price: 1 currency unit per million tokens
    • Output price: 8 currency units per million tokens

    Total input volume is:

    2,000 × 3,000 = 6 million tokens

    The cached portion is 2.4 million tokens, costing 2.4 currency units. The uncached portion is 3.6 million tokens, costing 14.4 currency units.

    Total output volume is:

    2,000 × 2,000 = 4 million tokens

    At the assumed output price, this costs 32 currency units. The total is therefore approximately 48.8 currency units per day.

    In this example, output accounts for the largest share of the cost. Optimization should therefore begin by controlling output length—for example, by limiting max_tokens and instructing the model to return code only.

    Caching

    Caching can reduce the cost of repeated or reusable input content. When estimating savings, separate cached and uncached input tokens and apply their respective prices rather than treating all input tokens as having the same rate.