Choosing LLMs for STEM: Metrics, Scenarios, and API Integration

    For STEM and software work, fluent output is not enough: a model must justify formulas, pass tests, and behave predictably under fixed conditions. This article presents a repeatable selection process covering five evaluation metrics, scenario-based weighting, version regression testing, API integration with safe retries and logging, common error troubleshooting, and an implementation order. It also includes a test record template and OpenAI-compatible example code.

    Start with Test Conditions, Not First Impressions

    A fluent conversation does not mean the model can correctly derive a formula. Code that looks reasonable does not mean it will pass tests. Model selection needs consistent metrics, fixed test conditions, and repeatable records. The following steps explain how to proceed.

    1. Define Five Metrics Before Comparing Models

    Before comparing models, reproduce the metrics in the table below on your own test set.

    Metric Meaning Test method Decision rule
    Effective long-context window Context length the model can use reliably Bury a key piece of information in a long document, ask repeated questions at different lengths, and measure recall success rate Set the boundary at the length where success falls below 90%; use the largest length that reliably reached 90% before that
    Code pass rate Proportion of generated code that passes unit tests Prepare 50 problems with test cases; divide passed problems by total problems Higher is better; also examine variation across multiple runs
    Correct refusal rate Proportion of unsupported questions where the model clearly states it cannot answer Prepare 30 questions whose answers cannot be derived from the given materials Higher is better; providing specific content counts as failure
    Cost per 1K tokens Combined input and output unit price Use the official price list and weight by the real business input/output ratio Compare with budget; estimate total monthly cost from request volume
    P95 latency Response time not exceeded by 95% of requests Send the same request 100 times consecutively; take the 95th percentile duration Must not exceed the business-acceptable response time limit

    Keep Test Conditions Consistent

    Numbers can only be compared when test conditions are consistent. Fix the following for each test:

    • Model name and full version number; do not use aliases that update automatically.
    • Sampling parameters such as temperature. For code and factual tasks, set temperature to 0.
    • Prompts and system prompts, saved as files with recorded versions.
    • Run date and test set version.

    Also account for statistical variation. If 42 of 50 problems pass, the pass rate is 84%. A 95% confidence interval is approximately 74% to 94%. If the gap between two models is smaller than this range, you cannot directly conclude that one is better. Run each test set at least 3 times, take the median, and report the minimum and maximum. P95 latency is also affected by network and server load, so test at different times.

    Decision Rules (Thresholds Are Examples; Set Your Own)

    • The effective window must be no lower than the longest target document; otherwise, do not use the model for that type of long-document work.
    • P95 latency must not exceed the business limit.
    • Models with a correct refusal rate below the set floor (for example, 80%) should not be used for evidence-based Q&A.
    • Cost per request = input tokens ÷ 1000 × input price + output tokens ÷ 1000 × output price.

    Test Record Template

    1. Test date:
    2. Model name and full version:
    3. Temperature and other sampling parameters:
    4. Prompt version:
    5. Test set name and number of questions:
    6. Number of runs:
    7. Effective long-context window:
    8. Code pass rate (median, range):
    9. Correct refusal rate:
    10. Cost per 1K tokens (billing currency):
    11. P95 latency (seconds):
    12. Notes:

    2. Choose Models by Scenario

    Different tasks require different metrics. The weights below are starting points and can be adjusted for your business. The weights for each scenario total 100.

    Metric Academic long-form literature Code generation Everyday Q&A
    Effective long-context window 40 10 10
    Code pass rate 0 50 0
    Correct refusal rate 30 5 25
    Cost per 1K tokens 20 20 35
    P95 latency 10 15 30

    2.1 Academic Long-Form Literature Analysis

    A large parameter count does not mean the model performs well in the target discipline. Test using the following steps:

    1. Select 3 to 5 papers you are familiar with, and manually label the correct answers for experimental data, sample sizes, and method steps.
    2. Feed the full text into the model, check the effective window, and verify whether each answer matches the original text.
    3. Check whether the model’s training data covers literature from the last one or two years, and whether terminology in the target discipline is accurate.
    4. Use refusal tests: when faced with conclusions that are not in the source text, does the model fabricate an answer?
    5. Repeat the steps above for candidate models and compare the results.

    When not suitable: do not ask the model to directly generate a reference list, because it may fabricate paper titles and DOIs. Model output cannot replace manual verification; conclusions must be checked against the original text. OCR errors in scanned PDFs can affect results, so key data should be manually proofread first.

    2.2 Code Generation

    Questions can come from historical defects in your own projects, course question banks, or public benchmarks, with unit tests for each question. Pay attention to the following during testing:

    • Specify the language version and dependency versions.
    • Run in a container or sandbox, with access to the external network and production resources prohibited.
    • Run tests independently for each question to avoid shared state affecting results.
    • Use the same test command for all candidate models when calculating pass rates.

    When not suitable: passing tests does not mean code quality is good, nor does it replace code review. Code involving authentication, encryption, and permissions must be manually reviewed. When test coverage is insufficient, pass rates can be inflated.

    2.3 Everyday Q&A

    Sample questions from real question logs and stratify them into concept explanations, operational steps, and queries that require evidence. Prepare another 30 unsupported questions to test refusal capability.

    When not suitable: high-risk questions in medical, legal, and financial domains should not rely solely on model output. For time-sensitive questions, require the model to provide sources and verify them manually.

    3. Version Regression Testing Process

    Model providers update models, and behavior under the same name may change. Therefore, compare before and after every upgrade. Steps:

    1. Fix the baseline: record the current model version, parameters, and prompts.
    2. Select a candidate version and run it with the same test set and the same parameters.
    3. Run each set at least 3 times and calculate the median.
    4. Judge against thresholds. Example thresholds: a drop of more than 5 percentage points in success-rate metrics, a latency increase of more than 20%, or a cost increase of more than 10% is judged as a regression.
    5. After the regression test passes, perform a canary release, observe online error rates and user feedback, and then switch fully.
    6. Keep the test record as the baseline for the next comparison.

    Regression checklist:

    Check item Requirement
    Baseline version State the full version identifier; do not use aliases
    Candidate version Same as above
    Sampling parameters Consistent with baseline
    Test set version Same number of questions and version identifier
    Five metrics Provide median and range for each
    Regression decision State whether thresholds were exceeded and why
    Conclusion and rollback plan State whether to switch or keep the baseline, and describe rollback steps

    4. API Integration

    4.1 Integration Principles

    • Read keys from environment variables or a secret management service; do not write them into code or commit them to version control.
    • Set a timeout for all requests.
    • Retry only timeouts, connection failures, 429, and 5xx errors, using exponential backoff, with a maximum of 3 retries. Retrying request errors such as 400 and 401 is meaningless; report the error directly.
    • Logs should record only the request ID, model name, duration, and token usage. Do not log keys, or prompts and responses containing personal or confidential information.
    • Limit concurrent requests with a semaphore, for example, no more than 5 at the same time.
    • Track daily cost from the token usage returned per call, and alert when the budget is exceeded.

    4.2 Example Code

    The code below is written for the OpenAI-compatible chat API format. In actual use, replace the URL and model name according to the provider’s documentation.

    1. import logging
    2. import os
    3. import time
    4. import requests
    5. API_KEY = os.environ["LLM_API_KEY"]
    6. BASE_URL = os.environ["LLM_BASE_URL"]
    7. MODEL = os.environ["LLM_MODEL"]
    8. TIMEOUT = 30
    9. MAX_RETRIES = 3
    10. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    11. logging.basicConfig(level=logging.INFO)
    12. log = logging.getLogger("llm")
    13. def call_llm(prompt: str, temperature: float = 0.0) -> str:
    14. headers = {
    15. "Authorization": f"Bearer {API_KEY}",
    16. "Content-Type": "application/json",
    17. }
    18. payload = {
    19. "model": MODEL,
    20. "messages": [{"role": "user", "content": prompt}],
    21. "temperature": temperature,
    22. }
    23. url = f"{BASE_URL}/chat/completions"
    24. for attempt in range(1, MAX_RETRIES + 1):
    25. try:
    26. resp = requests.post(url, headers=headers, json=payload, timeout=TIMEOUT)
    27. if resp.status_code in RETRYABLE_STATUS:
    28. log.warning("retryable status=%d attempt=%d", resp.status_code, attempt)
    29. else:
    30. resp.raise_for_status()
    31. data = resp.json()
    32. usage = data.get("usage", {})
    33. log.info(
    34. "ok model=%s input_tokens=%s output_tokens=%s",
    35. MODEL,
    36. usage.get("prompt_tokens"),
    37. usage.get("completion_tokens"),
    38. )
    39. return data["choices"][0]["message"]["content"]
    40. except (requests.Timeout, requests.ConnectionError) as e:
    41. log.warning("network error attempt=%d: %s", attempt, type(e).__name__)
    42. if attempt < MAX_RETRIES:
    43. time.sleep(2 ** attempt)
    44. raise RuntimeError("Request failed after maximum retries")

    Before running, set the environment variables in the terminal (Linux or macOS):

    1. export LLM_API_KEY="your-key"
    2. export LLM_BASE_URL="provider-endpoint"
    3. export LLM_MODEL="specific-version"

    5. Common Error Troubleshooting

    Symptom Common cause Handling
    401 Unauthorized Wrong or expired key, or environment variable not loaded correctly Check the variable name and value for extra spaces; regenerate the key if necessary
    403 Forbidden The account has not enabled the model, or there are regional or permission restrictions Confirm the model activation status in the provider console
    404 Not Found Model name misspelled, or the version has been retired Check the provider’s model list and use a fixed valid version
    400 Context too long Input exceeds the model’s context window Split or truncate the input, and count input tokens first
    429 Too Many Requests Rate limit or quota exceeded Reduce concurrency, use exponential backoff retries, and check remaining quota
    500/503 Server error Temporary provider failure Keep retry logic and check the provider status page
    Timeout Network fluctuation, or output too long Increase the timeout appropriately, reduce max_tokens, or use streaming output
    Empty or truncated response max_tokens is too small, and finish_reason is length Increase max_tokens and check finish_reason in code

    6. Implementation Order

    1. Define the five metrics as described in section 1, and fix the test set and test record template.
    2. Compare candidate models using the scenario weights in section 2, and exclude models that fail to meet requirements.
    3. After selecting a model, record the full version number and test results as the baseline.
    4. Before each upgrade, run version regression as described in section 3, and perform a canary switch after it passes.
    5. Integrate the API as described in section 4, and use the error table to diagnose issues.