To build a deployable internal knowledge Q&A system, first create an evaluation set, then define chunking and metadata, implement hybrid retrieval and reranking, and finally enforce citation constraints and production gates. This article provides directly adaptable Python chunking functions, batch indexing scripts, retrieval and citation assembly skeletons, and evaluation scripts, plus a chunking parameter comparison table, failure diagnosis table, and gray release acceptance checklist; addresses, keys, thresholds, and usage numbers in examples are marked as placeholder values or example assumptions.

Key takeaways
- 1. First create a 30-question evaluation set with standard chunk IDs, then write chunking and retrieval; without standard answers, you cannot distinguish 'not retrieved' from 'retrieved but unused'.
- 2. Chunking should attach four metadata fields to each chunk: doc_id, version, effective date, and permission label; provenance and permission filtering depend on them.
- 3. Hybrid retrieval (keyword plus vector) is better than single-path recall; rerank and take the top 3–5 chunks, controlling both missed recall and context length.
- 4. The prompt must state 'answer only from the given chunks, refuse if unsupported, and attach chunk IDs to each item', and the server must parse and validate it, rather than only asking the model to cooperate.
- 5. Before launch, set explicit configurations for timeout, retry limit, per-request input and output token limits, and validate gates with paired cases.
- Audience
- Backend engineers, platform engineers, and knowledge base maintainers who want to connect internal policy documents, product manuals, and ticket records into a Q&A service
- Estimated time
- About 90 minutes to complete chunking, an index skeleton, and a 30-question evaluation set (example estimate, depending on document cleanliness and the existing vector store)
- Prerequisites
- Available model invocation credentials, readable document sources, a vector or full-text index service, and the ability to log input and output tokens per request
How to implement RAG knowledge Q&A: build the evaluation set before writing retrieval
To build a deployable internal RAG knowledge Q&A system, the order is fixed in five steps: first prepare an evaluation set with standard chunk IDs, then define chunking and metadata, then perform hybrid retrieval and reranking, then assemble citation constraints, and finally close the loop with timeout and usage gates. Skipping the evaluation set and directly tuning retrieval makes all later parameter changes impossible to attribute. The scope of this article is as of December 6, 2026. Addresses, keys, thresholds, and usage numbers in example code are placeholder values or illustrative assumptions; model capabilities are based on the AGTCloud Model Library real-time display.
Treat the evaluation set as the interface definition of this system: every question must be able to answer “which chunk contains the standard answer,” “which chunks were recalled this time,” and “which chunk was finally cited.” Once these three fields are complete, hit rate, citation accuracy, and refusal rate can be automatically calculated, and changes to chunk granularity, recall count, and prompts will have a comparable baseline.
| Stage | Deliverable | Acceptance criteria | Common consequences of skipping |
|---|---|---|---|
| Evaluation set | 30 questions with standard chunk IDs | Each question can be mapped to a unique document chunk | Metrics cannot be attributed |
| Document chunking | Chunk table and four metadata types | Clauses and tables are not broken across chunks | Answers are missing half a sentence |
| Index construction | Vector index that can be rebuilt in batches | Can be incrementally updated by doc_id | Residual old versions |
| Retrieval and reranking | Two-path recall configuration and truncation count | Standard chunk enters the candidate list | Missed recall |
| Citation assembly | Prompt template and parsing validation | Fabricated citations are blocked by the server | Sources are untrustworthy |
| Launch gate | Timeout, retry, and usage limits | Paired test cases verify effectiveness | Usage amplification |
This table can be used directly as a project schedule: the deliverable in each row is a deliverable and inspectable entity, not an unverifiable description such as “tuning completed.” The following sections are expanded in the same order, and any one section can be used independently for a code review.
The boundary between evaluation sets and debug samples in RAG knowledge Q&A
An evaluation set is not the same as casually picked debug samples. Debug samples are used to check whether the pipeline works; an evaluation set must be fixed, reproducible, include standard answer locations, and cover multiple question types: those that can be directly hit, those requiring cross-chunk merging, those that should be refused, and those involving version changes. It is recommended to prepare several entries for each of the 4 categories, starting with 30 in total, then only add without changing, to ensure metrics remain comparable over time.
The “should be refused” category is the easiest to omit, but it directly determines whether fabricated content will fill knowledge gaps after launch. Without such questions, the refusal rate can never be measured, and the model’s behavior when chunks are empty has no regression protection.
Document chunking for RAG knowledge Q&A: granularity, overlap, and metadata
The goal of chunking is not to cut text evenly, but to make “a complete answer” fall within a single chunk as much as possible. Semantic chunking based on headings and clause boundaries is usually better than fixed character-count chunking; retaining a small amount of overlap between adjacent chunks can prevent conclusions that cross boundaries from being truncated. The Python function below includes a locally runnable self-test and does not depend on any external service.
import re
def split_by_heading(text, doc_id, version, effective_date, acl,
target_chars=400, overlap_chars=60):
"""按标题切分,长段落再按目标长度滑窗;overlap 保留跨边界上下文。
所有参数为示例假设起步值,请按评测集调整。"""
parts = re.split(r'(?m)^(#{1,3}\s+.+)$', text)
chunks, section = [], '概述'
buf = []
for part in parts:
if re.match(r'^#{1,3}\s+', part or ''):
if buf:
chunks.extend(_window(''.join(buf), section, target_chars, overlap_chars))
buf = []
section = part.lstrip('#').strip()
else:
buf.append(part or '')
if buf:
chunks.extend(_window(''.join(buf), section, target_chars, overlap_chars))
out = []
for i, c in enumerate(chunks):
out.append({
'chunk_id': f'{doc_id}-{version}-{i:04d}',
'doc_id': doc_id, 'version': version,
'effective_date': effective_date, 'acl': acl,
'section': c['section'], 'text': c['text'],
})
return out
def _window(text, section, size, overlap):
step = max(1, size - overlap)
return [{'section': section, 'text': text[i:i + size]}
for i in range(0, len(text), step)]
if __name__ == '__main__':
demo = '# 报销标准\n交通费按实际票据报销。\n## 时限\n须在 30 天内提交。'
rows = split_by_heading(demo, 'FIN-001', 'v3', '2026-12-01', 'finance')
print(len(rows), rows[0]['chunk_id'], rows[0]['section'])
assert all({'doc_id', 'version', 'effective_date', 'acl'} <= set(r) for r in rows)The most critical part of this code is the four metadata types: doc_id is used for incremental rebuild by document, version and effective_date are used to retire old versions, and acl is used to filter chunks by identity during queries. Source display, version retirement, and permission control all depend on these fields; missing any one type requires later rework to backfill data.
| Chunking parameters | Starting values (illustrative assumptions) | Impact of increasing | Impact of decreasing |
|---|---|---|---|
| Target chunk length | 300–500 tokens | Answers are more complete; input tokens increase | Lower cost, but clauses are easily cut off |
| Adjacent overlap | 50–80 tokens | Cross-boundary conclusions are more stable; redundancy increases | Less redundancy; boundary information is lost |
| Recall count | Top 3–5 chunks | Broader coverage; noise and input volume increase | Shorter context; missed recall increases |
| Recall from each of the two paths | 20 each | More candidates for reranking | Exact hits are more easily missed |
| Minimum chunk length | 50 tokens | Reduces fragmented chunks | May miss short clauses |
The values in the table are starting values, not production defaults. When adjusting, use the evaluation set criterion “whether the standard chunk falls completely within a single chunk”: if a clause is split and the answer is missing, prefer switching to semantic-boundary chunking rather than simply increasing chunk length—increasing length will also push up input tokens.
Why metadata for RAG knowledge Q&A must include an effective date
Internal policy documents often have the situation where “old and new versions are valid simultaneously for a period.” If chunks only have doc_id but no effective date, retrieval cannot determine which version should be cited for the current question, and answers will mix two sets of standards. With effective_date and version, you can filter by the question’s time context during queries and directly take old chunks offline from the index after the new version becomes effective.
The same applies to permission fields: mixing chunks with different confidentiality levels in one index and then relying on prompts to ask the model “not to cite confidential content” is unreliable; filtering by acl during the recall stage is a constraint that can be verified by code.
Index construction for RAG knowledge Q&A: vectorization and batch writing
The index must support incremental rebuild by doc_id instead of starting from scratch in full every time. The skeleton below leaves “vector generation” as a placeholder function, so batch processing and deduplication logic can run locally; after replacing it with your own embedding client, the rest of the code requires no changes.
VECTOR_DIM = 768 # 示例假设维度,以所用嵌入模型的实际输出为准
def embed(text):
"""占位:替换为自己的嵌入客户端,返回长度等于 VECTOR_DIM 的向量。"""
raise NotImplementedError('接入你使用的嵌入服务')
def build_index(chunks, store):
"""按 doc_id 增量重建:先删该文档旧片段,再写入当前版本。
store 只需实现 delete_by_doc(doc_id) 与 upsert(chunk_id, vector, payload)。"""
by_doc = {}
for c in chunks:
by_doc.setdefault(c['doc_id'], []).append(c)
report = {'docs': len(by_doc), 'chunks': 0, 'skipped': 0}
for doc_id, rows in by_doc.items():
store.delete_by_doc(doc_id)
for c in rows:
if len(c['text'].strip()) < 50: # 示例假设:过滤碎片
report['skipped'] += 1
continue
vec = embed(c['text'])
if len(vec) != VECTOR_DIM:
raise ValueError(f"向量维度不符: {c['chunk_id']}")
payload = {k: c[k] for k in
('doc_id', 'version', 'effective_date', 'acl', 'section', 'text')}
store.upsert(c['chunk_id'], vec, payload)
report['chunks'] += 1
return report
class MemoryStore:
"""本地可跑的内存实现,用于自测批处理与去重逻辑。"""
def __init__(self):
self.rows = {}
def delete_by_doc(self, doc_id):
self.rows = {k: v for k, v in self.rows.items()
if v['payload']['doc_id'] != doc_id}
def upsert(self, chunk_id, vector, payload):
self.rows[chunk_id] = {'vector': vector, 'payload': payload}
if __name__ == '__main__':
import types
store = MemoryStore()
fake = types.SimpleNamespace(embed=None)
# 用确定性假向量跑通流程(不作任何效果验证)
globals()['embed'] = lambda t: [0.0] * VECTOR_DIM
sample = [{'chunk_id': 'FIN-001-v3-0000', 'doc_id': 'FIN-001',
'version': 'v3', 'effective_date': '2026-12-01',
'acl': 'finance', 'section': '报销标准',
'text': '交通费按实际票据报销,须在 30 天内提交申请。' + '补充说明。' * 20}]
print(build_index(sample, store), 'rows=', len(store.rows))This skeleton bakes three easily overlooked items into the code: delete-then-write by document, fragmented-chunk filtering, and vector dimension validation. The first is especially important—append-only without deletion can leave multiple versions of the same document in the index, showing up during evaluation as 'the answer cites an old version', and it is hard to see directly from the hit rate metric.
Retrieval recall for RAG knowledge Q&A: hybrid retrieval and reranking
Queries over internal documents frequently hit IDs, model numbers, and clause numbers; pure vector recall is unstable for this kind of exact match. Keyword recall handles exact hits, while vector recall handles semantic matches with different wording. Merge and deduplicate the two routes, then rerank and take the top several into the context. The skeleton below can be run directly as a self-test.
def hybrid_search(query, keyword_index, vector_index, acl,
per_route=20, top_k=4):
"""两路召回 + 权限过滤 + 合并去重 + 重排截断。
per_route / top_k 均为示例假设值,按评测集调整。"""
kw = keyword_index.search(query, limit=per_route)
vec = vector_index.search(query, limit=per_route)
merged = {}
for hit in kw + vec:
c = hit['payload']
if acl not in c['acl']:
continue # 权限过滤在召回阶段做
prev = merged.get(c['chunk_id'])
score = hit['score']
if prev is None or score > prev['score']:
merged[c['chunk_id']] = {'chunk_id': c['chunk_id'],
'score': score, 'payload': c}
ranked = sorted(merged.values(), key=lambda x: x['score'], reverse=True)
return ranked[:top_k]
class FakeIndex:
def __init__(self, rows, base):
self.rows, self.base = rows, base
def search(self, query, limit):
return [{'score': self.base + i / 10.0, 'payload': r}
for i, r in enumerate(self.rows[:limit])]
if __name__ == '__main__':
rows = [{'chunk_id': f'D-{i:04d}', 'acl': 'finance', 'text': f'条款 {i}'}
for i in range(30)]
out = hybrid_search('报销时限', FakeIndex(rows, 0.5), FakeIndex(rows, 0.7),
acl='finance', per_route=20, top_k=4)
print('top_k=', len(out), 'ids=', [o['chunk_id'] for o in out])
assert len(out) == 4
denied = hybrid_search('报销时限', FakeIndex(rows, 0.5), FakeIndex(rows, 0.7),
acl='guest', per_route=20, top_k=4)
assert denied == [], '权限过滤必须拦下未授权片段'| Retrieval strategy | Questions it handles well | Typical failure | Mitigation |
|---|---|---|---|
| Keyword recall | Exact matching of IDs, model numbers, and clause numbers | Misses recall when wording changes | Add synonyms and tokenization rules |
| Vector recall | Semantically similar but worded differently | Exact ID hits are unstable | Merge with the keyword route |
| Merge and deduplicate the two routes | Covers both exact and semantic matching | Scores from the two routes are not directly comparable | Normalize each route before reranking |
| Truncate after reranking | Controls how many chunks enter the context | Overly tight truncation causes missed recall | Tune top_k using the evaluation set |
| Filter by version | Periods when old and new policies coexist | Missing effective-date field | Populate metadata during chunking |
| Filter by permission | Mixed-index documents with different confidentiality levels | Filtering placed after generation | Move it to the recall stage |
Note the paired test case in the self-test: an authorized identity receives 4 candidates, while an unauthorized identity returns an empty list. If permission filtering is written only in the prompt, the second assertion will fail—this kind of paired case shows whether the gate is actually running better than merely 'passing once'.
Why reranking cannot be skipped in RAG knowledge Q&A
The two recall routes use different score scales, so mixing them directly by raw score lets one route systematically dominate. The reranking stage uses the same model to score each 'question + candidate chunk' pair, then sorts them uniformly, so the most relevant chunks can occupy the limited top positions. Skipping reranking and simply increasing top_k pushes noisy chunks into the context as well, raising input tokens while citation accuracy actually drops.
Reranking cost scales with the number of candidates, so per_route and top_k must be tuned together: first fix top_k, then gradually adjust the recall count for each route and observe whether the proportion of 'standard chunks entering candidates' on the evaluation set improves.
Citation assembly for RAG knowledge Q&A: prompt and server-side validation
During assembly, retrieved chunks are numbered and placed into the prompt in a fixed order, and every conclusion must include a chunk ID, with an explicit refusal when there is no basis. After generation, the server parses citation IDs and checks one by one whether they appear in the current recall list—this step must be done in code, not only by asking the model to cooperate through the prompt.
import re
SYSTEM = ('你是内部知识问答助手。只依据下面给出的片段回答问题;'
'每个结论后用 [片段ID] 标注来源;片段中没有依据时,'
'只回答「资料中未找到依据」,不要推测。')
def build_prompt(question, candidates):
lines = [SYSTEM, '', '可用片段:']
for c in candidates:
lines.append(f"[{c['chunk_id']}] {c['payload']['section']}: "
f"{c['payload']['text']}")
lines += ['', f'问题:{question}', '回答:']
return '\n'.join(lines)
def validate_citations(answer, candidates):
"""服务端解析引用:伪造或缺失的引用一律判失败并改为拒答。"""
valid = {c['chunk_id'] for c in candidates}
cited = re.findall(r'\[([A-Za-z0-9\-]+)\]', answer)
if not cited:
return {'ok': False, 'reason': 'NO_CITATION'}
forged = [x for x in cited if x not in valid]
if forged:
return {'ok': False, 'reason': 'FORGED_CITATION', 'ids': forged}
return {'ok': True, 'cited': cited}
if __name__ == '__main__':
cands = [{'chunk_id': 'FIN-001-v3-0000',
'payload': {'section': '时限', 'text': '须在 30 天内提交。'}}]
print(build_prompt('报销时限?', cands).splitlines()[0])
good = '须在 30 天内提交 [FIN-001-v3-0000]'
bad = '须在 60 天内提交 [FIN-001-v9-9999]'
print('该放行:', validate_citations(good, cands))
print('该拦下:', validate_citations(bad, cands))
assert validate_citations(good, cands)['ok'] is True
assert validate_citations(bad, cands)['ok'] is False| Assembly element | Implementation | Validation location | Consequence if missing |
|---|---|---|---|
| Chunk numbering | Use chunk_id as the unique citation identifier | Server-side parsing against the recall list | Source cannot be verified |
| Answer based only on chunks | Hard-code system instructions and place fixed segments first | Spot-check consistency between answers and chunks | The model supplements external knowledge on its own |
| Refuse when unsupported | Provide an explicit refusal message | Track refusal rate and empty-recall proportion | Fabricated content fills gaps |
| Citation format | Fixed bracketed-ID format | Parse with regex and check each one | Fabricated citations slip through |
| Chunk order | Use the fixed order from the reranked list | Compare against the recall list in logs | Difficult to reproduce |
| Place fixed segments first | Put system instructions first and the question last | Check whether the template inserts dynamic variables | Cache hit rate drops |
The two cases in the self-test are intentionally paired: valid citations should pass, while fabricated chunk IDs should be blocked and return a refusal. Seeing only '0 fabricated citations' does not mean validation is effective; it could also mean the parsing function was never called—so you must check both that what should be blocked is blocked and that what should pass is allowed.
Evaluation set for RAG knowledge Q&A: hit, citation, and refusal metrics
Evaluation should calculate three metrics separately: whether standard chunks enter candidates (hit rate), whether the final answer cites standard chunks (citation accuracy), and whether unsupported scenarios are correctly refused (refusal accuracy). Combining them into a single score mixes retrieval issues, assembly issues, and generation-constraint issues, and cannot guide the next action.
def evaluate(cases, search_fn, generate_fn, top_k=4):
"""cases: [{question, gold_chunk_id, expect_abstain}]
返回三类指标,全部为计数比值,不涉及任何单价或评分。"""
stat = {'total': len(cases), 'hit': 0, 'cited': 0,
'abstain_ok': 0, 'abstain_expected': 0}
for case in cases:
cands = search_fn(case['question'], top_k=top_k)
ids = {c['chunk_id'] for c in cands}
if case['gold_chunk_id'] in ids:
stat['hit'] += 1
answer = generate_fn(case['question'], cands)
if case['expect_abstain']:
stat['abstain_expected'] += 1
if '资料中未找到依据' in answer:
stat['abstain_ok'] += 1
elif case['gold_chunk_id'] in answer:
stat['cited'] += 1
n = stat['total']
stat['hit_rate'] = round(stat['hit'] / n, 3)
stat['cite_rate'] = round(stat['cited'] / n, 3)
if stat['abstain_expected']:
stat['abstain_rate'] = round(stat['abstain_ok'] / stat['abstain_expected'], 3)
return stat
if __name__ == '__main__':
cases = [{'question': '报销时限', 'gold_chunk_id': 'D-0000',
'expect_abstain': False},
{'question': '不存在的政策', 'gold_chunk_id': '',
'expect_abstain': True}]
search = lambda q, top_k: [{'chunk_id': 'D-0000',
'payload': {'section': '时限', 'text': '30 天内'}}]
def gen(q, cands):
if not cands and '不存在' in q:
return '资料中未找到依据'
return '须在 30 天内提交 [D-0000]'
print(evaluate(cases, search, gen))| Metric | Definition | What a low value indicates | Priority action |
|---|---|---|---|
| Hit rate | Proportion of standard chunks entering the candidate list | Chunking or recall has problems | Change chunk boundaries, add a keyword route, tune per_route |
| Citation accuracy | Proportion of answers citing standard chunks | Assembly or prompt constraints are weak | Fix chunk order and add citation-parsing validation |
| Refusal accuracy | Proportion of unsupported scenarios correctly refused | The model is fabricating fill-in content | Provide an explicit refusal message and include it in regression |
| Number of fabricated citations | Number of times citation IDs are not in the recall list | Validation is not effective or not running | Run paired cases to confirm the parsing function |
| Input tokens per request | Measured usage of the assembled prompt | Chunks too long or too many | Compress chunks and lower top_k |
| Timeout proportion | Proportion of requests exceeding the configured threshold | Reranking or retrieval pipeline is too long | Add timeouts and fallback responses |
This metrics table can be plugged directly into a regression script: each time you change chunking, recall, or prompts, run only the same batch of 30 questions and see how the three metrics change separately. If the hit rate does not move but citation accuracy drops, the problem is definitely on the assembly side; rebuilding the index in that case is wasted effort.
Example assumptions for RAG knowledge Q&A: how to read a 30-question evaluation set
Using a set ofExample assumptionsHow to read the metrics: assume that among 30 questions, 5 belong to scenarios that should be refused, and the remaining 25 have standard chunks. If 22 are hit, 18 have correct citations, and 3 of the should-refuse cases are correctly refused, then the hit rate is 22/30 ≈ 73.3%, citation correctness rate is 18/30 = 60.0%, and refusal correctness rate is 3/5 = 60.0%. All figures above are demonstration numbers and do not represent any business-measured values or model performance.
The differences among the three metrics are clues for attribution: 22 hits but only 18 citations means that 4 candidates clearly contained the correct chunk but were not cited, so check assembly and prompt constraints; investigate chunking and recall only when the hit rate itself is low. Turning the differences into a fixed report is more helpful for locating issues than repeatedly reviewing a few subjective samples.
RAG knowledge Q&A launch gates: timeout, retry, and usage caps
Before launch, put four hard constraints in the same configuration: single-request timeout, retry cap, single-request input and output token caps, and refusal when there is no basis. Centralized configuration makes it easy to change only one place during canary rollout and easy for monitoring to read directly; caps scattered across prompts and business code often turn out not to take effect until load testing.
# 示例配置(示例假设值,非生产默认值)
retrieval:
per_route: 20 # 每路召回条数
top_k: 4 # 重排后进入上下文的条数
timeout_ms: 800 # 检索阶段超时
acl_filter_at: recall # 权限过滤必须在召回阶段
generation:
timeout_seconds: 30
max_input_tokens: 4000
max_output_tokens: 800
require_citation: true
on_no_evidence: abstain # 无依据时明确拒答
retry:
max_attempts: 2
backoff: [1s, 2s]
never_retry: [SCHEMA_INVALID, FORGED_CITATION, ACL_DENIED]
budget:
max_total_tokens_per_task: 8000
on_exceeded: return_partial_with_degraded_flag
observability:
per_request_fields: [request_id, hit_ids, top_k, in_tokens, out_tokens,
elapsed_ms, cited_ids, degraded, acl]| Gate | Example assumed value | Action when exceeded | Paired validation cases |
|---|---|---|---|
| Single-request timeout | 30 seconds | Return a degraded result and tag it | Normal request passes / consecutive timeouts hit the cap |
| Retry cap | 2 attempts | Stop retrying and log it | Timeout can be retried / fabricated citations are not retried |
| Single-request input cap | 4,000 tokens | Compress chunks and alert | Long document truncated / short document not truncated |
| Single-request output cap | 800 tokens | Truncate and mark | Long answer limited / normal answer complete |
| Citation validation | 100% parsing | Fabricated citations are changed to refusal | Valid citations pass / fabricated IDs are blocked |
| Permission filtering | Effective at the recall stage | Unauthorized chunks do not enter candidates | Authorized hit / unauthorized returns empty |
In the table, 100% parsing means coverage of every answer, not a performance promise. Pay special attention to the never_retry list: fabricated citations, parameter validation failures, and insufficient permissions are deterministic results; retrying any number of times will be the same and only causes duplicate billing and amplifies log noise.
RAG knowledge Q&A troubleshooting table: map symptoms back to the pipeline
The most time-consuming part of troubleshooting is not fixing bugs but reconstructing the scene. After linking hit lists, citation lists, usage, and latency in logs by request_id, the table below can map most symptoms directly to pipeline stages.
| Symptom | Priority check stage | Observed fields | Action |
|---|---|---|---|
| Answer cites an old version | Chunk metadata and index | version, effective_date | Delete then write by doc_id and take old chunks offline |
| Standard chunks never enter candidates | Chunking and recall | hit_ids, per_route | Use semantic chunking and add a keyword route |
| Candidates contain the correct chunk but the answer is wrong | Assembly and prompt | cited_ids, chunk order | Fix the order and add citation parsing validation |
| Fabricated chunk ID | Server-side validation | Fabricated citation count | Run paired cases to confirm the parsing function is called |
| Input tokens rise month by month | Context and history | in_tokens, top_k | Compress chunks and summarize multi-turn history |
| Timeout proportion rises | Retrieval and reranking | elapsed_ms, candidate count | Reduce per_route and add reranking timeout |
| Cost fluctuates with failure rate | Retry policy | max_attempts, degraded | Add deterministic errors to the no-retry list |
This table is also suitable to paste directly into the operations manual: every row has explicit observed fields and does not rely on subjective judgment. The first row is especially common—when the index only appends and does not delete, old and new versions are hit together, while the hit-rate metric looks completely normal.
RAG knowledge Q&A canary acceptance and metric-definition checks
Before canary rollout, use an acceptance table to leave evidence item by item; if any item lacks evidence, restrict the scope to read-only. The six items below correspond one-to-one to the earlier evaluation set, metadata, retrieval, citation validation, gates, and logs, making it easy to copy directly into the release ticket.
| No. | Acceptance item | Pass criteria | Evidence form |
|---|---|---|---|
| 1 | Evaluation set is fixed | 30 questions with standard chunk IDs and can be rerun | Evaluation set file and two run logs |
| 2 | Metadata is complete | Four categories of fields are non-empty on every chunk | Chunk table sampling |
| 3 | Incremental rebuild takes effect | After rebuild, old-version chunks are no longer hit | Version switch case |
| 4 | Citation validation takes effect | Valid citations pass and fabricated citations are blocked | Paired test cases |
| 5 | Gates take effect | After consecutive timeouts, attempts hit the cap | Load test logs and usage readings |
| 6 | Log fields are complete | One failed request chain can be fully reconstructed | Log sample by request_id |
Run normal cases first: a valid question passes in one attempt; check whether the hit list and citation list are consistent.
Then run permission cases: an unauthorized identity cannot obtain any candidates; confirm that filtering happens at the recall stage.
Then run refusal cases: when the knowledge base has no basis, return a fixed refusal message and do not fabricate chunk IDs.
Finally run gate cases: when there are consecutive timeouts and budget exhaustion, return a result tagged with degraded.
During the canary period, it is recommended to cross-check actual usage by day with AGTCloud console time-period data to confirm that input and output token records have no omissions; review candidate model context length and capability definitions in AGTCloud model library to determine whether retrieved chunks and multi-turn history will squeeze the output space.
The parameter tuning order also starts from the engineering side: first reduce top_k from 5 to 4, add deterministic errors to the no-retry list, and supplement chunks with effective dates and permission fields; these changes can be canary-released, rolled back, and measured. Switching models changes both effectiveness and cost, so it should be placed last, and after rechecking the context parameters in the AGTCloud Model Library, re-run the same evaluation set.
Integrate the 6 tables from this article into project documentation for reuse: use the stage table for scheduling, the chunking parameter table for configuration, the retrieval strategy table for recall, the citation validation table for review, the gate table for release orders, and the fault localization table for operations. They do not depend on specific model versions, and will not become invalid due to changes in parameters or prices.
About 纳磁科技 AGTCloud
AGTCloud (official website agtcloud.cn) is a large-model API service platform under 纳磁科技, providing developers with unified access to and invocation management of multiple model capabilities. This article is organized and published by the AGTCloud Resource Center, and the content is continuously updated across three directions: industry insights, practical guides, and knowledge encyclopedia. The model list, pricing, interfaces, and billing terms are subject to the real-time display on the official website /models page and official documentation.
Frequently asked questions
Do the evaluation set first. Prepare 30 real questions, annotate the document and chunk ID containing the standard answer for each, then tune chunk granularity. The evaluation set provides the only observable baseline: hit rate, citation accuracy, and refusal rate can be compared before and after changes using the same questions. If chunking is tuned first and evaluation is added later, parameter changes cause metric fluctuations that cannot be attributed, and quality can only be judged from a few subjective samples.
Source
Chen Yizhou
API Engineering
AGTCloud technical column author for API development, focusing on large-model API access, interface compatibility, SDK integration, and application development. Content covers Python API calls, OpenAI-compatible interfaces, streaming output, error handling, concurrency optimization, and development practices, helping developers reduce model access and migration costs.