Open-Weight LLMs in Production: Evaluation, Long-Context Optimization, and Long-Running Agent Debugging
Deploying open-weight LLMs in production raises three practical questions: how well a model performs on your tasks, how to control long-context inference cost, and how to trace failures in long-running agents. This article provides evaluation tables, quantization and LoRA validation steps, prefill/decode optimization guidance, RAG versus long-context selection rules, and agent logging and debugging checklists. It also covers common mistakes and licensing and compliance considerations.
Putting an open-weight LLM into a production system requires answering three questions first: how well the model performs on your tasks, how to reduce the cost of long-context inference, and whether you can locate the cause when a long-running agent fails. This article addresses these three questions in order. Each section provides a table or checklist that can be used directly.
1. Evaluate and Select Models with Your Own Sample Set
Open weights allow teams to deploy models in private environments, keep data in-domain, and fine-tune based on the weights. However, public leaderboard scores cannot represent business performance. Two models that are close on public benchmarks may differ widely on specific tasks such as contract review or ticket classification.
We recommend sampling real examples from business workflows and covering common requests and edge cases. There is no universal standard for sample size. In practice, you can first stratify by task type, keep dozens or more examples per stratum, and then judge whether differences are reliable based on result variance.
| Dimension | Measurement method | Measurement notes | Pass criteria | Recommended frequency |
|---|---|---|---|---|
| Accuracy | Calculate correctness against labeled answers | Stratify by task; do not look only at the overall result | Set by the business according to risk level; high-risk tasks have separate thresholds | After each model or prompt change |
| Response latency | Record first-token latency (TTFT) and overall duration; take P95 | Fix concurrency and input-length distribution; keep the test environment as close to production as possible | Meets the time limit for interactive scenarios | Before launch and after capacity expansion |
| Cost per request | Count input and output tokens and convert using the billing unit price | Include extra tokens caused by retries and tool calls | Within budget | Weekly |
| Long context | Build localization questions from long documents; record hit rate bucketed by context length | Compare the same question set at different lengths | Decay as length increases is acceptable to the business | After model or chunking strategy changes |
| Multi-constraint instruction following | Check output format, banned words, and field completeness | Validate rules programmatically; do not rely on manual spot checks | Violation rate below the team-defined threshold | Every change |
| Tool-call success rate | Count the proportion of calls with valid parameters and successful execution | Distinguish parameter errors, timeouts, and permission denials | Failed calls can be retried or handed off to a human; the retry limit must be clear | Daily |
The thresholds and frequencies above are only starting points. Teams should calibrate them to business risk and record the calibration results in the evaluation document.
2. Quantization and LoRA Must Be Validated Separately on the Target Task
Quantization may reduce accuracy, and the magnitude depends on the model, quantization method, and task type. The benefit of LoRA depends on the quality and quantity of training data. If the baseline model already meets requirements, LoRA may not bring a clear improvement.
Run validation in the following steps:
- Split samples into training, validation, and test sets. The test set must not participate in any tuning.
- Compare the original model, the quantized model, and the LoRA model on the same test set.
- Agree on rollback conditions in advance. If a key metric drops beyond the threshold, do not launch that version.
- Record the model version, quantization method, LoRA rank, training data hash, and evaluation results for reproducibility.
The methods described in this article do not guarantee any specific result. Final conclusions should be based on the team’s own test results.
3. Long-Context Inference Optimization: Split by Prefill and Decode
Long-context inference has two phases. In prefill, the model processes the full input; computation grows with input length and is the main source of first-token latency. In decode, tokens are generated one by one and depend on the KV cache; memory usage grows with sequence length and concurrency. The two phases have different bottlenecks and therefore different optimizations.
| Method | Phase | Main effect | Applicable boundary | Fields to record |
|---|---|---|---|---|
| Prefix caching | Prefill | Reuse fixed system prompts and document prefixes | The prefix must match exactly to hit | cache_hit_ratio |
| Chunked prefill | Prefill | Split long inputs to reduce blocking of other requests | Lowers tail latency; total throughput may decrease slightly | prefill_tokens, chunk_size |
| Continuous batching | Prefill and decode | Dynamically merge requests to improve throughput | Single-request latency may increase | batch_size, queue_wait_ms |
| KV cache quantization | Decode | Reduce memory usage | May affect long-distance recall; validate with long-context evaluation | kv_dtype, long-context hit rate |
| Input compression (summarization, deduplication, removal of irrelevant history) | Prefill | Reduce input token count | May lose key information; retain original text citations | Token counts before and after compression, information retention rate |
| Limit output length and stop conditions | Decode | Control generation duration | Setting it too small will truncate answers | max_new_tokens, truncation rate |
Parameter names differ across inference frameworks. Refer to the documentation of the framework you use.
Recommended measurement process:
- Measure baseline TTFT, overall latency, and memory usage by input-length bucket (for example, 1k, 8k, and 32k).
- Change only one variable at a time and re-measure on the same buckets.
- Record prompt_tokens, completion_tokens, ttft_ms, decode throughput, and gpu_mem_used for cost conversion.
- After optimization, rerun the long-context evaluation to confirm that hit rate has not dropped significantly.
4. RAG or Long Context: Selection Rules
The two approaches can be combined. A common pattern is to retrieve relevant snippets first and then place the results into a longer context window. The table below provides initial judgment criteria. The final choice should be based on evaluation with your sample set.
| Condition | Tendency | Reason |
|---|---|---|
| Total document volume far exceeds the context window | RAG | Cannot fit everything into context |
| Material size for a single task is controllable, such as one contract | Long context | Avoids retrieval omissions and simplifies the workflow |
| Answers are scattered across multiple places and require cross-paragraph reasoning | Long context, with dedicated testing | Retrieval may miss related passages |
| Knowledge base is updated frequently | RAG | Updating the index costs less than retraining or rewriting prompts |
| Citable sources are required | RAG | Retrieval results include their own provenance |
| High request volume and sensitivity to per-request cost | RAG | Sends only relevant snippets, consuming fewer tokens |
| Latency-sensitive | Short context or RAG | Long inputs increase prefill time |
5. Definition of Long-Running Agents and Observable Fields
A long-running agent executes tasks across multiple reasoning rounds and multiple tool calls and may run for minutes to hours. Unlike single-turn question answering or simple function calling, its task state must be persisted, failures must be recoverable from checkpoints, and some steps require retries or human takeover.
Debugging depends on logs, so every step should record the fields below.
| Field | Meaning | Desensitization requirement |
|---|---|---|
| trace_id | Globally unique identifier for one task | None |
| step | Step number within the task | None |
| tool_name | Name of the tool called | None |
| arguments | Tool parameters | Replace sensitive values with placeholders; keep only field names and types |
| started_at, duration_ms | Step start time and duration | None |
| prompt_tokens, completion_tokens | Input and output token counts | None |
| model_version | Model and version number | None |
| error_code | Error classification code | None |
| retry_count | Number of retries for this step | None |
| permission_scope | Permission scope used for the call | None |
| human_takeover | Whether handed off to a human; Boolean | None |
| final_status | Final task status | None |
Logs must not contain plaintext secrets, tokens, or personally identifiable information. Log access should be consistent with access to production data.
6. Debugging Steps
When a long-running agent task fails, troubleshoot in the following order:
- Use trace_id to reconstruct the full step sequence and find the first step with an anomaly.
- Classify the error: non-compliant model output, tool parameter error, tool execution failure, permission denial, or timeout.
- Check the input context for that step and confirm whether the required information exists and whether it was lost during truncation or compression.
- Reproduce with the same input at a fixed temperature to determine whether the issue occurs consistently.
- For parameter errors, check the tool schema validation and the model output format constraints.
- Check whether retries are caused by the same error. Ineffective retries amplify cost, so set an upper limit.
- Record the reason for human takeover and add the sample to the evaluation set.
7. Common Mistakes
- Using public leaderboards instead of business evaluation.
- Looking only at average latency and ignoring P95 and first-token latency.
- Counting only successful tool calls and ignoring failure categories.
- Not recording failed trajectories, making retrospective analysis impossible.
- Deploying a quantized model without regression testing.
8. Licensing and Compliance
- Open-weight license terms vary. Commercial use, redistribution, and restrictions on training-data use must be confirmed by legal.
- Data in evaluation samples and logs must be desensitized, and access to sample sets should follow the principle of least privilege.
- Tool-call permissions should follow the principle of least privilege. An agent should not have write or delete permissions beyond what the task requires.
- The thresholds, frequencies, and fields in this article are reference starting points. Teams need to calibrate them based on their own business risk.
