AI Tool Selection and RAG Integration: From Evaluation to Production
This article provides a practical guide on selecting AI tools and integrating Retrieval-Augmented Generation (RAG) from evaluation to production. It covers tool capability boundaries, a scoring matrix for selection, prompt engineering templates, code integration with permission filtering, a minimal RAG implementation checklist, and critical deployment thresholds to ensure security and accuracy.
Before introducing AI tools, teams must answer two questions: which category of tasks does this tool solve, and who takes responsibility if errors occur? The following sections detail tool boundaries, selection scoring, prompt templates, code integration, a RAG integration checklist, and deployment thresholds.
I. Capability Boundaries of Four Tool Categories
| Tool Category | Common Forms | Capability Boundaries | Minimum Verification Sample | Exit Conditions |
|---|---|---|---|---|
| Text Generation & Processing | Conversational assistants, LLM APIs | Good at Q&A, summarization, rewriting, and structured output; facts require line-by-line verification | 20 real requirement documents, requesting an API list output | Fact error rate exceeds the team’s threshold, or it cannot stably output the agreed format |
| Code Assistance | IDE plugins, code review tools | Good at completing boilerplate code, generating unit test drafts, and suggesting exception paths | 10 functions from the same module, comparing compilation and test pass rates of generated code | High rework volume, or false positive rate is so high that reviewers start ignoring prompts |
| Image Generation | Text-to-image services, image editing tools | Suitable for UI sketches, illustration drafts, and material alternatives | 5 sets of brand style descriptions, checking style consistency and licensing terms | Licensing terms do not meet commercial requirements, or style cannot be stably reproduced |
| Multimodal Understanding | Vision-language models, document parsing services | Recognize text and structures in invoices, reports, and drawings | 50 real invoices, comparing field-by-field with manual entry results | Field errors require manual correction one by one, and review time exceeds manual entry |
During selection, do not just look at demo effects. Demos usually use cherry-picked inputs, and the conclusions cannot represent real business scenarios. Each type of tool should be run with your own real samples first, and actual values should be recorded.
II. Selection Matrix and Scoring Weights
During evaluation, score each candidate tool item by item according to the table below, with each item scored from 1 to 5. The total weight is 100%. Teams can adjust weights based on business risks, but the reasons for adjustments must be recorded in the evaluation notes.
| Metric | Weight | Scoring Description |
|---|---|---|
| Task Accuracy | 30% | Accuracy on real samples, based on measured values |
| Data Privacy & Retention Policy | 20% | Whether input data is used for training, and whether retention duration can be configured |
| Controllability | 15% | Whether output format can be constrained, and whether system-level rules can be set |
| Cost | 15% | Estimated monthly cost based on the billing metric, including peak call volumes |
| Concurrency & Quota | 10% | Response time and rate-limiting rules under peak concurrency |
| Integration Cost | 10% | Effort required to integrate with existing auth, logging, and ticketing systems |
For the cost item, it is recommended to write it as “billing metric plus estimation conditions,” such as the price per 1,000 calls, average input/output length, and monthly call volume. Different services may have different billing units, and comparing unit prices directly can easily lead to wrong conclusions.
Below is the test record template. Each metric should retain original samples and model outputs for re-testing.
| Sample ID | Tool Name | Task Type | Metric | Measured Value | Tester | Test Date |
|---|---|---|---|---|---|---|
| S-001 | To be filled | API list generation | Field completeness rate | To be filled | To be filled | To be filled |
III. Text Tools: Prompt Templates and Verification Checklist
A prompt should simultaneously include the role, task, input material, output format, and prohibited actions. The template below can be reused directly. Requirement documents pasted into the template must be desensitized first.
Role: You are a backend engineer responsible for requirement sorting.Task: Output an API list based on the requirement document in <doc>.Input material:<doc>{Paste the desensitized requirement document here}</doc>Output format: Markdown table with columns: API name, path, request method, request parameters, response fields.Constraints:1. Only use information present in <doc>; do not supplement fields outside the document.2. Mark uncertain fields uniformly as "To be confirmed".3. The output must not contain phone numbers, ID card numbers, keys, or internal domain names.
You can add two or three sets of examples after the template, known as Few-shot prompting. Examples can unify the output format, but they may also cause the model to mimic biases in the examples, such as fixing field naming habits. The comparison method is to run the same batch of samples with both prompted and unprompted versions, and then decide whether to keep the examples based on accuracy and manual scoring.
After the model outputs, check item by item according to the table below. If any item fails, regenerate or modify it manually; do not publish it directly.
| Check Item | Verification Method | Judgment |
|---|---|---|
| Facts | Compare line by line with the original text to confirm that every conclusion has a source | Delete all content without source evidence or mark as “To be confirmed” |
| Numbers | Verify amounts, version numbers, dates, and quantities | Must exactly match the original text |
| Proper Nouns | Verify product names, person names, API names, and system names | Must match the original text without being replaced or simplified |
| Format | Verify the number of table columns, field names, and order | Must match the template |
| Tone | Read through the text to check if the tone is consistent | The tone must be consistent within the same document |
IV. Code Assistance Tool Integration and Review
Intelligent programming tools read the current file, related files, and dependency declarations, then combine comments and function signatures to generate code. The more complete the prompt, the closer the result is to being runnable. Below is a reproducible minimal example: a search interface with permission filtering, corresponding to the “filter first, retrieve later” scenario in RAG.
Runtime environment: Node.js 20, Express 4, TypeScript 5.
mkdir rag-demo && cd rag-demonpm init -ynpm install express@4npm install -D typescript ts-node @types/express @types/nodemkdir src
Create tsconfig.json in the project root directory:
{"compilerOptions": {"target": "ES2022","module": "commonjs","strict": true,"esModuleInterop": true}}
Write the following code into src/server.ts:
// Language: TypeScript (Node.js 20); Framework: Express 4import express, { NextFunction, Request, Response } from "express";type Role = "public" | "engineer" | "finance";interface Chunk {id: string;docId: string;text: string;allowedRoles: Role[];vector: number[];}const ROLES: readonly Role[] = ["public", "engineer", "finance"];const DIM = 64;// Bag-of-words vector for demonstration purposes. Replace with a real embedding model in production.function embed(text: string): number[] {const v = new Array<number>(DIM).fill(0);for (const ch of text.toLowerCase()) {if (/\s/.test(ch)) continue;const code = ch.codePointAt(0) ?? 0;v[code % DIM] += 1;}const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)) || 1;return v.map((x) => x / norm);}function cosine(a: number[], b: number[]): number {let s = 0;for (let i = 0; i < a.length; i++) s += a[i] * b[i];return s;}const sources: Omit<Chunk, "vector">[] = [{id: "c1",docId: "policy-ai-001",text: "Employees can only input desensitized business data into approved AI tools.",allowedRoles: ["public", "engineer", "finance"],},{id: "c2",docId: "sec-rag-002",text: "RAG retrieval results must first be filtered by user permissions before being passed to the model to generate an answer.",allowedRoles: ["engineer"],},{id: "c3",docId: "fin-report-003",text: "Budget amounts in monthly expense reports must be reviewed by finance personnel before public release.",allowedRoles: ["finance"],},];const index: Chunk[] = sources.map((c) => ({ ...c, vector: embed(c.text) }));// Filter by permissions first, then calculate similarity and sort.function searchAllowed(query: string, role: Role, topK: number) {const q = embed(query);return index.filter((c) => c.allowedRoles.includes(role)).map((c) => ({ id: c.id, docId: c.docId, text: c.text, score: cosine(q, c.vector) })).sort((a, b) => b.score - a.score).slice(0, topK);}function isRole(x: unknown): x is Role {return typeof x === "string" && (ROLES as readonly string[]).includes(x);}const app = express();app.use(express.json({ limit: "16kb" }));app.post("/api/search", (req: Request, res: Response) => {// For demonstration only: In production, get the role from a gateway-verified token; never trust client request headers.const role = req.header("x-user-role");if (!isRole(role)) {res.status(401).json({ error: "unauthorized" });return;}const query = req.body?.query;if (typeof query !== "string" || query.trim().length === 0 || query.length > 500) {res.status(400).json({ error: "query must be 1 to 500 characters" });return;}const topK = req.body?.topK ?? 3;if (!Number.isInteger(topK) || topK < 1 || topK > 10) {res.status(400).json({ error: "topK must be an integer from 1 to 10" });return;}const hits = searchAllowed(query.trim(), role, topK);// Audit logs only record the role, query length, and hit document IDs; they do not record the original query text.console.log(JSON.stringify({time: new Date().toISOString(),role,queryLength: query.length,docIds: hits.map((h) => h.docId),}));res.json({ results: hits });});app.use((err: { status?: number }, _req: Request, res: Response, _next: NextFunction) => {res.status(err.status ?? 500).json({ error: "request failed" });});const port = Number(process.env.PORT ?? 3000);app.listen(port, () => {console.log(`listening on port ${port}`);});
Start the service and test it:
npx ts-node src/server.tscurl -s -X POST http://localhost:3000/api/search \-H 'Content-Type: application/json' \-H 'x-user-role: public' \-d '{"query":"What data can employees input"}'
The expected results are as follows. The public role can only retrieve policy-ai-001 and cannot see sec-rag-002. The engineer role can retrieve c1 and c2. A request without the x-user-role header returns 401.
Code generated must be manually reviewed. During the review, focus on the following: whether the role comes from verified identity information, whether input length and value ranges are limited, whether logs avoid recording the original text, and whether permission branches have corresponding tests. The bag-of-words vector in the example is only used to demonstrate the flow. After integrating a real embedding model, permission filtering must still occur before sorting.
V. Minimal Implementation Checklist for RAG Knowledge Base Integration
The core process of RAG is to split enterprise documents into chunks, build a vector index, retrieve chunks based on user permissions, and then have the model generate an answer based on the chunks. Each step must have verifiable deliverables.
| Step | What to Do | Check Items |
|---|---|---|
| 1. Document Splitting | Split by title or paragraph, keeping document ID, section name, version number, and permission tags for each chunk | Chunks can be traced back to original positions; no tables or code are lost after splitting |
| 2. Vector Retrieval | Filter by permissions first, then perform similarity sorting, and set topK and similarity thresholds | Chunks without permission will not enter the candidate set; thresholds are determined by evaluation sets, not by guessing |
| 3. Prompt Template | Require the model to answer only based on the given chunks, and explicitly state when information is insufficient | Answers include document IDs; when information is insufficient, output “Cannot answer based on available materials” |
| 4. Evaluation | Build a golden Q&A set, recording recall rate, answer accuracy, and citation accuracy | Re-run evaluation after changing splitting parameters or models, and save the values |
| 5. Permission Audit | Record user role, time, query length, and hit document IDs, and periodically review permission configurations | Logs do not contain sensitive original text; permissions of departed and transferred personnel are revoked within the agreed timeframe |
There is no universally optimal value for splitting parameters. A common starting point is a few hundred characters per chunk, with a small overlap between adjacent chunks, and then comparing the recall rates of different settings using a golden Q&A set. Specific numbers should be based on your own evaluation results.
VI. Risks and Deployment Thresholds
The following situations cannot go live or enter the production environment:
- Generated code without manual review, especially for authentication, authorization, payment, and encryption logic.
- Financial, legal, or compliance conclusions without review.
- Writing customer data, keys, or internal domain names into prompts, code, or logs.
- Third-party tools with unconfirmed data retention and training terms.
- Search interfaces without permission filtering, or where permissions are self-declared by the client.
VII. Acceptance Checklist
Confirm the following items one by one before going live, and enter the production environment only after all pass.
- The selection matrix has been scored using real samples, and test records have been archived.
- Prompt templates have been desensitized, and the output verification checklist has been executed.
- Code examples have been run in the target environment and passed manual review.
- The five steps of RAG all have deliverables, and evaluation values have been saved.
- Permissions come from unified identity authentication, and audit logs have been verified to not contain sensitive original text.
