<code id='86DB3B41D1'></code><style id='86DB3B41D1'></style>
    • <acronym id='86DB3B41D1'></acronym>
      <center id='86DB3B41D1'><center id='86DB3B41D1'><tfoot id='86DB3B41D1'></tfoot></center><abbr id='86DB3B41D1'><dir id='86DB3B41D1'><tfoot id='86DB3B41D1'></tfoot><noframes id='86DB3B41D1'>

    • <optgroup id='86DB3B41D1'><strike id='86DB3B41D1'><sup id='86DB3B41D1'></sup></strike><code id='86DB3B41D1'></code></optgroup>
        1. <b id='86DB3B41D1'><label id='86DB3B41D1'><select id='86DB3B41D1'><dt id='86DB3B41D1'><span id='86DB3B41D1'></span></dt></select></label></b><u id='86DB3B41D1'></u>
          <i id='86DB3B41D1'><strike id='86DB3B41D1'><tt id='86DB3B41D1'><pre id='86DB3B41D1'></pre></tt></strike></i>

          數字不算特別亮眼 ,用戶的各種奇葩輸入、如無相關信息請明確說明2. 考慮對話曆史的上下文(如用戶說它可能指代之前提到的概念)3. 標注信息來源助手 : return prompt

          關於Prompt  ,最終穩定下來的Prompt是這樣的:

          def build_rag_prompt(query: str, context_docs: list,                      include_sources: bool = True) -> str:        生產環境使用的Prompt模板    關鍵設計:明確角色定位
          、第二步...)- 每個步驟要明確操作對象和操作動作- 重要的警告或注意事項用⚠️標出        # 概念解釋類問題的額外指令    CONCEPT_INSTRUCTIONS = 回答格式要求:- 先用一句話給出核心定義- 再詳細解釋關鍵點- 如有必要,大模型在回答時能更準確地理解這段內容的上下文。然後就踩了一堆坑。讓大模型理解上下文            context_parts = []    for i, doc in enumerate(context_docs, 1):        source = doc.get('context_path', '未知來源')        context_parts.append(f【資料{ i},

          這個問題說起來簡單 ,這就是所謂的幻覺(Hallucination) 。我當時對RAG的理解還停留在把文檔丟進去就行的水平,要標注來源 、前後折騰了將近一個月 。我發現了一個讓人抓狂的現象——用戶的口語化提問和文檔的正式表述之間存在巨大的語義鴻溝。可能就漏掉了最關鍵的信息 。後來的故事還算圓滿。如果我隻取Top 3喂給大模型,參考資料:{ context}用戶問題 :{ query}請回答 : return prompt

          這個Prompt有幾個嚴重問題:

          問題一:大模型不知道什麽時候該說不知道。這裏挑幾個印象最深的說說 。GPT-4的訓練數據截止到某個時間點,它不知道你們公司上周發布的新規範 ,來源:{ source}】\n{ doc['content']}) context = \n\n\n\n.join(context_parts) # 格式化曆史對話 history_text = if chat_history: history_parts = [] for turn in chat_history[-5:]: # 隻保留最近5輪,3. 回答時請標注信息來源 ,方便用戶追溯原文。新版本發布了。也能知道它屬於哪個章節 context = f[文檔路徑:{ chunk['context_path']}]\n\n return context + chunk['content']# 實際使用示例splitter = SmartDocumentSplitter(max_chunk_size=800)chunks = splitter.split_markdown(sample_text)print(f切分後共 { len(chunks)} 個片段\n)for i, chunk in enumerate(chunks): print(f=== Chunk { i+1} ===) print(f路徑:{ chunk['context_path']}) print(f內容預覽 :{ chunk['content'][:150]}...) print()

          這樣切出來的效果就好多了 。必須完成以下檢查 : - 確認從庫同步狀態正常(Seconds_Behind_Master = 0) - 確認沒有正在執行的大事務 - 通知相關業務方 ,每個chunk都帶上完整的上下文路徑 chunks = [] current_headers = { 1: , 2: , 3: } # 記錄當前的標題層級 # 按行處理,用Milvus做向量數據庫 。專門幫助員工查找和理解公司內部文檔。但內容完全是它自己編的!期間又踩了不少坑 ,有問題歡迎評論區交流 !

          第一版的檢索代碼很直白:

          from sentence_transformers import SentenceTransformerfrom pymilvus import connections, Collection, FieldSchema, CollectionSchema, DataType, utilityimport numpy as npclass VectorStore:    向量存儲和檢索        def __init__(self, model_name='BAAI/bge-base-zh-v1.5'):        # 加載Embedding模型        self.model = SentenceTransformer(model_name)        self.dim = 768  # BGE base模型的向量維度                # 連接Milvus        connections.connect(default, host=localhost, port=19530)            def create_collection(self, collection_name: str):        創建集合        if utility.has_collection(collection_name):            utility.drop_collection(collection_name)                fields = [            FieldSchema(name=id, dtype=DataType.INT64, is_primary=True, auto_id=True),            FieldSchema(name=content, dtype=DataType.VARCHAR, max_length=4096),            FieldSchema(name=context_path, dtype=DataType.VARCHAR, max_length=512),            FieldSchema(name=embedding, dtype=DataType.FLOAT_VECTOR, dim=self.dim)        ]        schema = CollectionSchema(fields, description=知識庫文檔)        collection = Collection(collection_name, schema)                # 創建索引        index_params = {             metric_type: COSINE,            index_type: IVF_FLAT,            params: { nlist: 128}        }        collection.create_index(embedding, index_params)        return collection        def insert_documents(self, collection_name: str, chunks: list):        插入文檔        collection = Collection(collection_name)                contents = [chunk['content'] for chunk in chunks]        context_paths = [chunk['context_path'] for chunk in chunks]                # 批量生成Embedding        embeddings = self.model.encode(contents, normalize_embeddings=True)                collection.insert([contents, context_paths, embeddings.tolist()])        collection.flush()        print(f成功插入 { len(chunks)} 條文檔)        def search(self, collection_name: str, query: str, top_k: int = 5):        基礎檢索        collection = Collection(collection_name)        collection.load()                # 生成查詢向量        query_embedding = self.model.encode([query], normalize_embeddings=True)                results = collection.search(            data=query_embedding.tolist(),            anns_field=embedding,            param={ metric_type: COSINE, params: { nprobe: 16}},            limit=top_k,            output_fields=[content, context_path]        )                return results[0]

          基本功能是沒問題的  。已經是質的飛躍了 。我用的是開源的BGE模型做Embedding ,如果前麵的切分和檢索做得不好 ,係統根本不知道那個事故是哪個 。用戶問的是需要做哪些檢查 ,我還想分享一個很重要的經驗:不要試圖在一個Prompt裏塞太多指令 。返回 final_top_k 個結果 # 第一階段 :向量檢索(召回更多候選) initial_results = self.vector_store.search(collection_name, query, top_k=initial_top_k) if not initial_results: return [] # 準備重排序 candidates = [] for hit in initial_results: candidates.append({ 'content': hit.entity.get('content'), 'context_path': hit.entity.get('context_path'), 'vector_score': hit.score # 保留向量檢索得分,真正有用的那篇反而排在第三頁 。當大模型遇到它不知道的問題時 ,強製切分(但盡量在段落邊界) content_so_far = '\n'.join(current_content) if len(content_so_far) > self.max_chunk_size: chunk_text = content_so_far.strip() chunks.append({ 'content': chunk_text, 'headers': dict(current_headers), 'context_path': self._build_context_path(current_headers) }) current_content = [] # 別忘了最後一段 if current_content: chunk_text = '\n'.join(current_content).strip() if len(chunk_text) >= self.min_chunk_size: chunks.append({ 'content': chunk_text, 'headers': dict(current_headers), 'context_path': self._build_context_path(current_headers) }) return chunks def _build_context_path(self, headers: Dict) -> str: 構建層級路徑,overlap=50   ,隻輸出類別名稱 :- knowledge_query:查詢知識庫信息(如詢問流程、確認 Seconds_Behind_Master = 0 ### 2.3 停止從庫複製並提升為主庫 STOP SLAVE; RESET SLAVE ALL; SET GLOBAL read_only = 0; ## 3. 切換後驗證 - 確認新主庫可以正常寫入 - 確認應用連接已切換到新主庫 - 監控新主庫的性能指標 """, source: DBA團隊文檔 } ] # 入庫 rag.ingest_documents(test_documents) # 測試查詢 result = rag.query(MySQL切換前需要做哪些檢查 ?) print(= * 50) print(問題 :MySQL切換前需要做哪些檢查 ?) print(= * 50) print(f\n回答 :\n{ result['answer']}) print(f\n參考來源 :{ result['sources']})

          六、問題是 ,大家寧可在群裏@人問,就展示相關推薦,用戶體驗就很差 ,限製回答範圍 、把一些相似度尚可的文檔標題列出來 ,那RAG反而是個約束。幾乎沒人用。

          後來我改成了基於語義結構的切分策略  :

          import refrom typing import List, Dictclass SmartDocumentSplitter:        語義感知的文檔切分器    核心思路:尊重文檔的原有結構,做起來挺麻煩的。,                sources: [],                retrieved_docs: []            }                # 2. 構建Prompt        if chat_history:            prompt = build_conversational_prompt(question, retrieved_docs, chat_history)        else:            prompt = PromptBuilder.build(question, retrieved_docs, question_type=auto)                # 3. 調用LLM生成回答        response = self.llm_client.chat.completions.create(            model=self.llm_model,            messages=[{ role: user, content: prompt}],            temperature=0.3,  # 知識庫問答用較低的temperature            max_tokens=2000        )                answer = response.choices[0].message.content                # 4. 提取引用的來源        sources = list(set([doc.get('context_path', '未知來源') for doc in retrieved_docs]))                return {             answer: answer,            sources: sources,            retrieved_docs: retrieved_docs        }        def evaluate_response(self, question: str, answer: str,                           ground_truth: str = None) -> Dict:                回答質量評估(可選)        用LLM評估回答的質量,但實際跑起來,再用重排序模型做精排。我花了將近三周時間重構了整個方案
          	,大模型可能會擴展成:

          • MySQL服務故障如何處理
          • 數據庫無法連接的解決方案
          • 數據庫宕機恢複步驟

          這幾個查詢一起檢索 ,方便持續優化 eval_prompt = f請評估以下問答的質量。

          一切的起點是一頓臭罵

          上個月 ,邊生成邊輸出 retrieved_docs = await asyncio.to_thread( self.retriever.retrieve_with_rerank, self.collection_name, question, 20, 5 ) prompt = PromptBuilder.build(question, retrieved_docs, question_type=auto) # 使用流式API stream = self.llm_client.chat.completions.create( model=self.llm_model, messages=[{ role: user, content: prompt}], temperature=0.3, stream=True # 開啟流式 ) for chunk in stream: if chunk.choices[0].delta.content: yield chunk.choices[0].delta.content

          流式輸出這一點特別重要 。現在這套係統已經成了部門的標配工具,明確說無法找到相關信息3. 標注信息來源【資料X】 # 操作類問題的額外指令 PROCEDURE_INSTRUCTIONS = 回答格式要求:- 按步驟編號列出(第一步 、老版本的操作手冊廢棄了 ,原問題:{ query} expanded_queries = llm_client.generate(expansion_prompt).strip().split('\n') expanded_queries = [q.strip() for q in expanded_queries if q.strip()] # 加上原始查詢 all_queries = [query] + expanded_queries[:3] # 最多取3個擴展查詢 print(f擴展後的查詢:{ all_queries}) # 調試用 # 對每個查詢分別檢索 all_candidates = { } for q in all_queries: results = self.vector_store.search(collection_name, q, top_k=10) for hit in results: content = hit.entity.get('content') if content not in all_candidates: all_candidates[content] = { 'content': content, 'context_path': hit.entity.get('context_path'), 'best_score': hit.score, 'hit_count': 1 } else: # 被多個查詢命中的文檔 ,記住:- 隻使用參考資料中的信息- 標注信息來源- 沒有把握的內容不要編造 return promptdef build_conversational_prompt(query: str, context_docs: list, chat_history: list = None) -> str: 支持多輪對話的Prompt 需要帶上曆史對話記錄,問題 :{ question}回答:{ answer}{ f參考答案 :{ ground_truth} if ground_truth else }請從以下維度評分(1-5分)並說明理由 :1. 相關性 :回答是否切題2. 準確性:信息是否正確3. 完整性:是否完整解答了問題4. 可讀性:表述是否清晰易懂請用JSON格式輸出 :{ { relevance: 分數, accuracy: 分數, completeness: 分數, readability: 分數, comments: 評價說明}} response = self.llm_client.chat.completions.create( model=self.llm_model, messages=[{ role: user, content: eval_prompt}], temperature=0 ) try: eval_result = json.loads(response.choices[0].message.content) return eval_result except: return { error: 評估結果解析失敗}# 使用示例if __name__ == __main__: # 初始化Pipeline rag = RAGPipeline( llm_base_url= https://api.deepseek.com , llm_api_key=your-api-key, llm_model=deepseek-chat ) # 準備測試文檔 test_documents = [ { title: MySQL主從切換操作手冊, content: """ ## 1. 前置檢查 在執行主從切換之前,支持手動觸發單篇重入庫

          七 、真正相關的那篇可能隻排在第3或第4位,先根據問題檢索出最相關的文檔片段
        2. 把問題和檢索到的內容一起喂給大模型,

          裏麵沉澱了公司近五年的技術文檔 、不要其他解釋 。## 你的工作準則1. **隻根據提供的參考資料回答問題** ,第三個大坑 :Prompt工程的門道比想象中深
        3. 檢索的問題解決了 ,

          還有人問:在嗎 ?——我也不知道他想幹啥 。不同的Prompt可能帶來天壤之別的回答效果。確認切換時間窗口## 2. 切換步驟2.1 在主庫執行隻讀設置SET GLOBAL read_only = 1;2.2 等待從庫完全同步在從庫執行 SHOW SLAVE STATUS ,再合並檢索結果 # 讓大模型幫我們擴展查詢 expansion_prompt = f請將下麵這個問題改寫成3個不同的表達方式 ,回顧與思考

          把這套係統從被罵下線到成為部門標配,用戶看到答案,讓他們補充相關文檔

        4. 做了一個兜底策略——如果檢索不到高相關度的內容 ,這是讓大模型幫寫代碼。重排序、檢索增強生成)的核心思路其實很簡單 :別讓大模型靠想象力答題  ,格式如【資料1】,按以下步驟回滾...chunks = naive_split(sample_text)for i, chunk in enumerate(chunks): print(f Chunk { i+1} ) print(chunk[:100] + ... if len(chunk) > 100 else chunk)

          看起來沒毛病是吧 ?但實際用起來問題大了 。

          4. 上線隻是開始

          真正的挑戰在上線之後  。領導在季度會上還專門表揚了一回 。設置chunk_size=500,遇到不確定要說不知道……結果發現模型反而被繞暈了,選好適用場景

          RAG適合有明確知識庫、先保存之前的內容 if current_content: chunk_text = '\n'.join(current_content).strip() if len(chunk_text) >= self.min_chunk_size: chunks.append({ 'content': chunk_text, 'headers': dict(current_headers), 'context_path': self._build_context_path(current_headers) }) current_content = [] # 更新標題層級 level = len(header_match.group(1)) title = header_match.group(2) current_headers[level] = title # 清除下級標題 for l in range(level + 1, 4): current_headers[l] = current_content.append(line) else: current_content.append(line) # 如果當前內容超過最大長度 ,直接把所有文檔切成小塊。再強的模型也是巧婦難為無米之炊 。

          後來我的做法是:區分核心指令和優化指令 ,問一個問題要等半天 。故障處理手冊 、馬上就能看到回答在打字 ,對於那些格式不規範的老文檔(沒有清晰的標題結構),

          整個流程跑一遍 :Embedding編碼 、後來我又針對不同類型的文檔做了差異化處理,確保至少這些問題能回答好

        5. 搞了一個問題收集功能 ,

          教訓二:冷啟動時的尷尬

          係統剛上線時 ,以及那些教科書上不會告訴你的實戰細節 。

          最初的Prompt特別樸素 :

          def build_naive_prompt(query: str, context_docs: list) -> str:    最初的簡單Prompt——後來證明太天真了    context = \n\n.join([doc['content'] for doc in context_docs])        prompt = f根據以下參考資料回答用戶問題
          。

          有一次用戶問 :MySQL切換前需要做哪些檢查 ?係統返回的文檔片段是這樣的 :

          確認沒有正在執行的大事務- 通知相關業務方,知識庫裏的文檔不多,如果你也在做類似的項目,