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.

    1. Role: You are a backend engineer responsible for requirement sorting.
    2. Task: Output an API list based on the requirement document in <doc>.
    3. Input material:
    4. <doc>
    5. {Paste the desensitized requirement document here}
    6. </doc>
    7. Output format: Markdown table with columns: API name, path, request method, request parameters, response fields.
    8. Constraints:
    9. 1. Only use information present in <doc>; do not supplement fields outside the document.
    10. 2. Mark uncertain fields uniformly as "To be confirmed".
    11. 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.

    1. mkdir rag-demo && cd rag-demo
    2. npm init -y
    3. npm install express@4
    4. npm install -D typescript ts-node @types/express @types/node
    5. mkdir src

    Create tsconfig.json in the project root directory:

    1. {
    2. "compilerOptions": {
    3. "target": "ES2022",
    4. "module": "commonjs",
    5. "strict": true,
    6. "esModuleInterop": true
    7. }
    8. }

    Write the following code into src/server.ts:

    1. // Language: TypeScript (Node.js 20); Framework: Express 4
    2. import express, { NextFunction, Request, Response } from "express";
    3. type Role = "public" | "engineer" | "finance";
    4. interface Chunk {
    5. id: string;
    6. docId: string;
    7. text: string;
    8. allowedRoles: Role[];
    9. vector: number[];
    10. }
    11. const ROLES: readonly Role[] = ["public", "engineer", "finance"];
    12. const DIM = 64;
    13. // Bag-of-words vector for demonstration purposes. Replace with a real embedding model in production.
    14. function embed(text: string): number[] {
    15. const v = new Array<number>(DIM).fill(0);
    16. for (const ch of text.toLowerCase()) {
    17. if (/\s/.test(ch)) continue;
    18. const code = ch.codePointAt(0) ?? 0;
    19. v[code % DIM] += 1;
    20. }
    21. const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)) || 1;
    22. return v.map((x) => x / norm);
    23. }
    24. function cosine(a: number[], b: number[]): number {
    25. let s = 0;
    26. for (let i = 0; i < a.length; i++) s += a[i] * b[i];
    27. return s;
    28. }
    29. const sources: Omit<Chunk, "vector">[] = [
    30. {
    31. id: "c1",
    32. docId: "policy-ai-001",
    33. text: "Employees can only input desensitized business data into approved AI tools.",
    34. allowedRoles: ["public", "engineer", "finance"],
    35. },
    36. {
    37. id: "c2",
    38. docId: "sec-rag-002",
    39. text: "RAG retrieval results must first be filtered by user permissions before being passed to the model to generate an answer.",
    40. allowedRoles: ["engineer"],
    41. },
    42. {
    43. id: "c3",
    44. docId: "fin-report-003",
    45. text: "Budget amounts in monthly expense reports must be reviewed by finance personnel before public release.",
    46. allowedRoles: ["finance"],
    47. },
    48. ];
    49. const index: Chunk[] = sources.map((c) => ({ ...c, vector: embed(c.text) }));
    50. // Filter by permissions first, then calculate similarity and sort.
    51. function searchAllowed(query: string, role: Role, topK: number) {
    52. const q = embed(query);
    53. return index
    54. .filter((c) => c.allowedRoles.includes(role))
    55. .map((c) => ({ id: c.id, docId: c.docId, text: c.text, score: cosine(q, c.vector) }))
    56. .sort((a, b) => b.score - a.score)
    57. .slice(0, topK);
    58. }
    59. function isRole(x: unknown): x is Role {
    60. return typeof x === "string" && (ROLES as readonly string[]).includes(x);
    61. }
    62. const app = express();
    63. app.use(express.json({ limit: "16kb" }));
    64. app.post("/api/search", (req: Request, res: Response) => {
    65. // For demonstration only: In production, get the role from a gateway-verified token; never trust client request headers.
    66. const role = req.header("x-user-role");
    67. if (!isRole(role)) {
    68. res.status(401).json({ error: "unauthorized" });
    69. return;
    70. }
    71. const query = req.body?.query;
    72. if (typeof query !== "string" || query.trim().length === 0 || query.length > 500) {
    73. res.status(400).json({ error: "query must be 1 to 500 characters" });
    74. return;
    75. }
    76. const topK = req.body?.topK ?? 3;
    77. if (!Number.isInteger(topK) || topK < 1 || topK > 10) {
    78. res.status(400).json({ error: "topK must be an integer from 1 to 10" });
    79. return;
    80. }
    81. const hits = searchAllowed(query.trim(), role, topK);
    82. // Audit logs only record the role, query length, and hit document IDs; they do not record the original query text.
    83. console.log(
    84. JSON.stringify({
    85. time: new Date().toISOString(),
    86. role,
    87. queryLength: query.length,
    88. docIds: hits.map((h) => h.docId),
    89. })
    90. );
    91. res.json({ results: hits });
    92. });
    93. app.use((err: { status?: number }, _req: Request, res: Response, _next: NextFunction) => {
    94. res.status(err.status ?? 500).json({ error: "request failed" });
    95. });
    96. const port = Number(process.env.PORT ?? 3000);
    97. app.listen(port, () => {
    98. console.log(`listening on port ${port}`);
    99. });

    Start the service and test it:

    1. npx ts-node src/server.ts
    2. curl -s -X POST http://localhost:3000/api/search \
    3. -H 'Content-Type: application/json' \
    4. -H 'x-user-role: public' \
    5. -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:

    1. Generated code without manual review, especially for authentication, authorization, payment, and encryption logic.
    2. Financial, legal, or compliance conclusions without review.
    3. Writing customer data, keys, or internal domain names into prompts, code, or logs.
    4. Third-party tools with unconfirmed data retention and training terms.
    5. 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.