国产精品电影_久久视频免费_欧美日韩国产激情_成年人视频免费在线播放_日本久久亚洲电影_久久都是精品_66av99_九色精品美女在线_蜜臀a∨国产成人精品_冲田杏梨av在线_欧美精品在线一区二区三区_麻豆mv在线看

多階段工作流加持,高級RAG代理如何實現智能對話與精準回答 原創

發布于 2025-7-10 09:22
瀏覽
0收藏

多階段工作流加持,高級RAG代理如何實現智能對話與精準回答-AI.x社區

在當今數字化時代,智能問答系統已經滲透到我們生活的方方面面,從在線客服到智能語音助手,它們都在努力為我們提供便捷的信息獲取方式。然而,傳統的問答系統在面對復雜的對話場景時,常常顯得力不從心。今天,就讓我們一起探索如何構建一個能夠應對復雜對話的高級RAG(Retrieval-Augmented Generation)代理,讓它具備改寫用戶問題、分類、驗證文檔相關性等強大功能,為用戶提供更加智能、精準的回答。

一、為什么需要高級RAG代理

傳統的RAG系統在處理簡單問題時表現尚可,但一旦遇到復雜的對話場景,比如用戶連續提出多個相關問題,或者問題涉及多個領域時,就容易出現回答不準確甚至無法回答的情況。這是因為傳統系統缺乏對話記憶和智能查詢處理能力。例如,當用戶在詢問某個產品的功能后,緊接著問“那它的價格是多少呢?”傳統系統可能就無法準確理解這個問題的上下文,從而給出不準確的回答。

為了解決這些問題,我們需要構建一個更加智能的高級RAG代理。它能夠通過以下幾個關鍵功能來提升對話的質量和準確性:

  1. 智能問題改寫:將用戶后續提出的問題轉化為獨立的查詢,使其能夠更好地被系統理解和處理。
  2. 智能主題檢測:確保查詢的問題都在我們的知識領域內,避免回答與主題無關的內容。
  3. 文檔質量評估:在生成回答之前,驗證檢索到的內容是否準確、相關,確保回答的質量。
  4. 自適應查詢增強:當初始查詢未能成功時,能夠迭代地改進搜索策略,提高檢索的成功率。
  5. 持久對話記憶:在多次交流中保持上下文的連貫性,讓對話更加自然流暢。

接下來,讓我們通過一個實際的場景——構建一個技術支援知識庫,來逐步實現這個高級RAG代理系統。

二、系統架構設計

我們的高級RAG代理采用了復雜的多階段工作流程,主要包括以下幾個核心組件:

  1. 查詢增強器(Query Enhancer):利用對話歷史改寫問題,使其更適合向量搜索。
  2. 主題驗證器(Topic Validator):判斷查詢是否與我們的知識領域相關。
  3. 內容檢索器(Content Retriever):從知識庫中檢索與問題相關的文檔。
  4. 相關性評估器(Relevance Assessor):評估檢索到的文檔的質量和相關性。
  5. 回答生成器(Response Generator):根據對話歷史和相關文檔生成上下文相關的回答。
  6. 查詢優化器(Query Optimizer):當需要時優化搜索查詢,提高檢索效率。

這種架構使得系統能夠處理復雜的對話,同時保持回答的質量和相關性,為用戶提供更加準確、有用的信息。

三、環境搭建與知識庫構建

(一)環境搭建

為了快速搭建我們的開發環境,我們使用了??uv??這個快速的Python包管理器。以下是具體的搭建步驟:

1.創建并激活虛擬環境

uv venv rag-env
source rag-env/bin/activate

這一步創建了一個名為??rag-env??的虛擬環境,并將其激活,為后續的開發提供了一個獨立的環境。

2.安裝所需包

uv pip install \
    langchain \
    langgraph \
    langchain-google-genai \
    langchain-community \
    python-dotenv \
    jupyterlab \
    ipykernel

這里安裝了構建RAG代理所需的核心依賴包,包括??langchain???、??langgraph??等,為系統的運行提供了必要的支持。

3.將虛擬環境注冊為Jupyter內核

python -m ipykernel install --user --name=rag-env --display-name "RAG Agent (uv)"

通過這一步,我們可以在Jupyter Notebook或JupyterLab中選擇??RAG Agent (uv)??作為內核,方便后續的開發和調試。

4.添加LLM API密鑰: 在項目根目錄下創建一個??.env??文件,并添加你的Gemini API密鑰:

GOOGLE_API_KEY=your_google_gemini_api_key_here

這樣,我們就可以在系統中使用Gemini的高級推理能力來處理復雜的查詢了。

5.加載依賴

from dotenv import load_dotenv
load_dotenv()

# Core LangChain components
from langchain.schema import Document
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import Chroma
from langchain_core.prompts import ChatPromptTemplate

# Graph and state management
from typing import TypedDict, List
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage
from pydantic import BaseModel, Field
from langgraph.graph import StateGraph, END
from langgraph.checkpoint.memory import MemorySaver

這里導入了構建系統所需的各種模塊和類,為后續的功能實現提供了基礎。

(二)知識庫構建

為了更好地展示系統的功能,我們構建了一個名為“TechFlow Solutions”的技術支援知識庫。以下是構建知識庫的代碼:

# 初始化嵌入模型
embedding_model = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")

# 創建全面的技術支援知識庫
knowledge_documents = [
    Document(
        page_cnotallow="TechFlow Solutions offers three main service tiers: Basic Support ($29/month) includes email support and basic troubleshooting, Professional Support ($79/month) includes priority phone support and advanced diagnostics, Enterprise Support ($199/month) includes 24/7 dedicated support and custom integrations.",
        metadata={"source": "pricing_guide.pdf", "category": "pricing"},
    ),
    Document(
        page_cnotallow="Our cloud infrastructure services include: Virtual Private Servers starting at $15/month, Managed Databases from $45/month, Content Delivery Network at $0.08/GB, and Load Balancing services at $25/month. All services include 99.9% uptime guarantee.",
        metadata={"source": "infrastructure_pricing.pdf", "category": "services"},
    ),
    Document(
        page_cnotallow="TechFlow Solutions was founded in 2018 by Maria Rodriguez, a former Google engineer with 15 years of experience in cloud architecture. The company has grown from 3 employees to over 150 team members across 12 countries, specializing in enterprise cloud solutions.",
        metadata={"source": "company_history.pdf", "category": "company"},
    ),
    Document(
        page_cnotallow="Our technical support team operates 24/7 for Enterprise customers, business hours (9 AM - 6 PM EST) for Professional customers, and email-only support for Basic customers. Average response times: Enterprise (15 minutes), Professional (2 hours), Basic (24 hours).",
        metadata={"source": "support_procedures.pdf", "category": "support"},
    )
]

# 構建向量數據庫
vector_store = Chroma.from_documents(knowledge_documents, embedding_model)
document_retriever = vector_store.as_retriever(search_kwargs={"k": 2})

這個知識庫涵蓋了定價、服務、公司信息、支持流程等多個方面,能夠滿足用戶在技術支援方面的多種查詢需求。同時,通過為每個文檔添加豐富的元數據,我們可以更好地組織和過濾文檔,提高檢索的效率和準確性。

四、核心組件實現

(一)查詢增強器——智能問題改寫

查詢增強器的作用是根據對話歷史改寫用戶的問題,使其成為一個獨立的、適合向量搜索的查詢。以下是其實現代碼:

def enhance_user_query(state: ConversationState):
    """
    根據對話歷史改寫用戶問題,創建適合向量搜索的獨立查詢。
    """
    print(f"Enhancing query: {state['current_query'].content}")
    
    # 初始化新查詢處理的狀態
    state["retrieved_documents"] = []
    state["topic_relevance"] = ""
    state["enhanced_query"] = ""
    state["should_generate"] = False
    state["optimization_attempts"] = 0
    
    # 確保存在對話歷史
    if "conversation_history" not in state or state["conversation_history"] is None:
        state["conversation_history"] = []
    
    # 如果當前問題不在對話歷史中,則將其添加進去
    if state["current_query"] not in state["conversation_history"]:
        state["conversation_history"].append(state["current_query"])
    
    # 檢查是否存在對話上下文
    if len(state["conversation_history"]) > 1:
        # 提取上下文和當前問題
        previous_messages = state["conversation_history"][:-1]
        current_question = state["current_query"].content
        
        # 構建上下文感知的提示
        context_messages = [
            SystemMessage(
                cnotallow="""You are an expert query reformulator. Transform the user's question into a standalone, 
                search-optimized query that incorporates relevant context from the conversation history.
                
                Guidelines:
                - Make the question self-contained and clear
                - Preserve the user's intent while adding necessary context
                - Optimize for vector database retrieval
                - Keep the reformulated query concise but comprehensive"""
            )
        ]
        context_messages.extend(previous_messages)
        context_messages.append(HumanMessage(cnotallow=f"Current question: {current_question}"))
        
        # 生成增強后的查詢
        enhancement_prompt = ChatPromptTemplate.from_messages(context_messages)
        llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp", temperature=0.1)
        
        formatted_prompt = enhancement_prompt.format()
        response = llm.invoke(formatted_prompt)
        enhanced_question = response.content.strip()
        
        print(f"Enhanced query: {enhanced_question}")
        state["enhanced_query"] = enhanced_question
    else:
        # 對話中的第一個問題 - 直接使用原問題
        state["enhanced_query"] = state["current_query"].content
        print(f"First query - using original: {state['enhanced_query']}")
    
    return state

這個組件通過結合對話歷史和當前問題,生成一個更加清晰、獨立的查詢,提高了問題在向量數據庫中的檢索效果,同時保留了用戶原始問題的意圖。

(二)主題驗證器——智能領域分類

主題驗證器的作用是判斷用戶的問題是否在我們的知識領域內。以下是其實現代碼:

class TopicRelevance(BaseModel):
    """主題分類的結構化輸出"""
    classification: str = Field(
        descriptinotallow="問題是否與TechFlow Solutions的服務、定價、公司信息等有關?回答'RELEVANT'或'IRRELEVANT'"
    )
    confidence: str = Field(
        descriptinotallow="置信度:'HIGH'、'MEDIUM'或'LOW'"
    )

def validate_topic_relevance(state: ConversationState):
    """
    判斷用戶問題是否在我們的知識領域內。
    使用增強后的查詢以提高分類準確性。
    """
    print("Validating topic relevance...")
    
    classification_prompt = SystemMessage(
        cnotallow="""You are a topic classifier for TechFlow Solutions support system.
        
        RELEVANT topics include:
        - TechFlow Solutions services (cloud infrastructure, migration, DevOps)
        - Pricing for any TechFlow Solutions products or services
        - Company information (history, team, locations)
        - Support procedures and response times
        - Security and compliance features
        - Technical specifications and capabilities
        
        IRRELEVANT topics include:
        - General technology questions not specific to TechFlow
        - Other companies' products or services
        - Personal questions unrelated to business
        - Weather, news, or general knowledge queries
        
        根據包含對話上下文的增強查詢進行分類。"""
    )
    
    user_question = HumanMessage(
        cnotallow=f"Enhanced query to classify: {state['enhanced_query']}"
    )
    
    # 創建分類鏈
    classification_chain = ChatPromptTemplate.from_messages([classification_prompt, user_question])
    llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp", temperature=0)
    
    structured_llm = llm.with_structured_output(TopicRelevance)
    classifier = classification_chain | structured_llm
    
    result = classifier.invoke({})
    state["topic_relevance"] = result.classification.strip()
    
    print(f"Topic classification: {state['topic_relevance']} (Confidence: {result.confidence})")
    return state

這個組件通過明確定義系統能夠處理的問題范圍,并結合增強后的查詢進行分類,提高了分類的準確性。同時,它還提供了置信度評分,讓我們對分類結果有更多的了解。

(三)內容檢索器——智能文檔檢索

內容檢索器的作用是從知識庫中檢索與問題相關的文檔。以下是其實現代碼:

def fetch_relevant_content(state: ConversationState):
    """
    使用增強后的查詢從知識庫中檢索文檔。
    """
    print("Fetching relevant documents...")
    
    # 使用增強后的查詢進行檢索
    retrieved_docs = document_retriever.invoke(state["enhanced_query"])
    
    print(f"Retrieved {len(retrieved_docs)} documents")
    for i, doc in enumerate(retrieved_docs):
        print(f"   Document {i+1}: {doc.page_content[:50]}...")
    
    state["retrieved_documents"] = retrieved_docs
    return state

這個組件通過向量數據庫,根據增強后的查詢快速檢索出與問題相關的文檔,為后續的回答生成提供了基礎。

(四)相關性評估器——文檔質量控制

相關性評估器的作用是評估檢索到的文檔的質量和相關性。以下是其實現代碼:

class DocumentRelevance(BaseModel):
    """文檔相關性評估的結構化輸出"""
    relevance: str = Field(
        descriptinotallow="該文檔是否與回答問題相關?回答'RELEVANT'或'IRRELEVANT'"
    )
    reasoning: str = Field(
        descriptinotallow="簡要說明文檔相關或不相關的原因"
    )

def assess_document_relevance(state: ConversationState):
    """
    評估每個檢索到的文檔,確定它是否與回答用戶問題相關。
    """
    print("Assessing document relevance...")
    
    assessment_prompt = SystemMessage(
        cnotallow="""You are a document relevance assessor. Evaluate whether each document 
        contains information that can help answer the user's question.
        
        A document is RELEVANT if it contains:
        - Direct answers to the question
        - Supporting information that contributes to a complete answer
        - Context that helps understand the topic
        
        A document is IRRELEVANT if it:
        - Contains no information related to the question
        - Discusses completely different topics
        - Provides no value for answering the question
        
        在評估時要嚴格但公正。"""
    )
    
    llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp", temperature=0)
    structured_llm = llm.with_structured_output(DocumentRelevance)
    
    relevant_documents = []
    
    for i, doc in enumerate(state["retrieved_documents"]):
        assessment_query = HumanMessage(
            cnotallow=f"""Question: {state['enhanced_query']}
            
            Document to assess:
            {doc.page_content}
            
            Is this document relevant for answering the question?"""
        )
        
        assessment_chain = ChatPromptTemplate.from_messages([assessment_prompt, assessment_query])
        assessor = assessment_chain | structured_llm
        
        result = assessor.invoke({})
        
        print(f"Document {i+1}: {result.relevance} - {result.reasoning}")
        
        if result.relevance.strip().upper() == "RELEVANT":
            relevant_documents.append(doc)
    
    # 更新狀態,保留相關文檔
    state["retrieved_documents"] = relevant_documents
    state["should_generate"] = len(relevant_documents) > 0
    
    print(f"Final relevant documents: {len(relevant_documents)}")
    return state

這個組件通過嚴格評估每個文檔的相關性,過濾掉不相關的文檔,確保回答的質量和準確性。同時,它還提供了相關性評估的原因,讓我們對評估結果有更深入的了解。

(五)回答生成器——上下文感知的回答創建

回答生成器的作用是根據對話歷史和相關文檔生成上下文相關的回答。以下是其實現代碼:

def generate_contextual_response(state: ConversationState):
    """
    根據對話歷史和相關文檔生成最終的回答。
    """
    print("Generating contextual response...")
    
    if "conversation_history" not in state or state["conversation_history"] is None:
        raise ValueError("對話歷史是回答生成所必需的")
    
    # 提取回答生成所需的組件
    conversation_context = state["conversation_history"]
    relevant_docs = state["retrieved_documents"]
    enhanced_question = state["enhanced_query"]
    
    # 創建全面的回答模板
    response_template = """You are a knowledgeable TechFlow Solutions support agent. Generate a helpful, 
    accurate response based on the conversation history and retrieved documents.
    
    Guidelines:
    - Use information from the provided documents to answer the question
    - Maintain conversation context and refer to previous exchanges when relevant
    - Be conversational and helpful in tone
    - If the documents don't fully answer the question, acknowledge limitations
    - Provide specific details when available (prices, timeframes, etc.)
    
    Conversation History:
    {conversation_history}
    
    Retrieved Knowledge:
    {document_context}
    
    Current Question: {current_question}
    
    Generate a helpful response:"""
    
    response_prompt = ChatPromptTemplate.from_template(response_template)
    llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp", temperature=0.3)
    
    # 創建回答生成鏈
    response_chain = response_prompt | llm
    
    # 生成回答
    response = response_chain.invoke({
        "conversation_history": conversation_context,
        "document_context": relevant_docs,
        "current_question": enhanced_question
    })
    
    generated_response = response.content.strip()
    
    # 將回答添加到對話歷史中
    state["conversation_history"].append(AIMessage(cnotallow=generated_response))
    
    print(f"Generated response: {generated_response[:100]}...")
    return state

這個組件通過結合對話歷史和相關文檔,生成一個既符合上下文又準確的回答,使對話更加自然流暢。

(六)查詢優化器——自適應搜索改進

查詢優化器的作用是在初始檢索未能成功時優化搜索查詢。以下是其實現代碼:

def optimize_search_query(state: ConversationState):
    """
    當初始檢索未能成功時,優化搜索查詢。
    包含循環預防機制,避免無限優化循環。
    """
    print("Optimizing search query...")
    
    current_attempts = state.get("optimization_attempts", 0)
    
    # 防止無限優化循環
    if current_attempts >= 2:
        print("?Maximum optimization attempts reached")
        return state
    
    current_query = state["enhanced_query"]
    
    optimization_prompt = SystemMessage(
        cnotallow="""You are a search query optimizer. The current query didn't retrieve relevant documents.
        
        Create an improved version that:
        - Uses different keywords or synonyms
        - Adjusts the query structure for better matching
        - Maintains the original intent while improving searchability
        - Considers alternative ways to express the same concept
        
        只提供優化后的查詢,無需解釋。"""
    )
    
    optimization_request = HumanMessage(
        cnotallow=f"Current query that needs optimization: {current_query}"
    )
    
    optimization_chain = ChatPromptTemplate.from_messages([optimization_prompt, optimization_request])
    llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp", temperature=0.2)
    
    formatted_prompt = optimization_chain.format()
    response = llm.invoke(formatted_prompt)
    optimized_query = response.content.strip()
    
    # 更新狀態
    state["enhanced_query"] = optimized_query
    state["optimization_attempts"] = current_attempts + 1
    
    print(f"Optimized query (attempt {current_attempts + 1}): {optimized_query}")
    return state

這個組件通過優化搜索查詢,提高了檢索的成功率,同時通過限制優化嘗試次數,避免了無限循環的問題。

五、工作流編排與智能路由

為了實現系統的整體功能,我們需要將各個組件按照一定的順序連接起來,并根據不同的情況做出智能的路由決策。以下是工作流的編排代碼:

def route_by_topic(state: ConversationState):
    """根據主題相關性分類進行路由"""
    print("Routing based on topic relevance...")
    
    relevance = state.get("topic_relevance", "").strip().upper()
    
    if relevance == "RELEVANT":
        print("   → Proceeding to content retrieval")
        return "fetch_content"
    else:
        print("   → Routing to off-topic handler")
        return "handle_off_topic"

def route_by_document_quality(state: ConversationState):
    """根據文檔相關性評估進行路由"""
    print("Routing based on document quality...")
    
    optimization_attempts = state.get("optimization_attempts", 0)
    
    if state.get("should_generate", False):
        print("   → Generating response with relevant documents")
        return "generate_response"
    elif optimization_attempts >= 2:
        print("   → Maximum optimization attempts reached")
        return "handle_no_results"
    else:
        print("   → Optimizing query for better results")
        return "optimize_query"

# 邊緣情況的輔助函數
def handle_off_topic_queries(state: ConversationState):
    """處理超出知識領域的問題"""
    print("Handling off-topic query...")
    
    if "conversation_history" not in state or state["conversation_history"] is None:
        state["conversation_history"] = []
    
    off_topic_response = """我專注于幫助解答有關TechFlow Solutions服務、定價和公司信息的問題。 
    您的問題似乎超出了我的專業領域。 
    
    我可以幫助您了解:
    - 我們的云基礎設施服務和定價
    - 支持流程和響應時間  
    - 公司信息和團隊詳情
    - 安全和合規特性
    
    您是否有關于TechFlow Solutions的具體問題需要幫助?"""
    
    state["conversation_history"].append(AIMessage(cnotallow=off_topic_response))
    return state

def handle_no_relevant_results(state: ConversationState):
    """處理在優化后仍未找到相關文檔的情況"""
    print("No relevant results found after optimization...")
    
    if "conversation_history" not in state or state["conversation_history"] is None:
        state["conversation_history"] = []
    
    no_results_response = """抱歉,我在當前知識庫中未能找到能夠回答您問題的具體信息。 
    
    這可能是因為:
    - 該信息在我們的文檔中不可用
    - 您的問題可能需要進一步明確
    - 您可能需要直接聯系我們的支持團隊
    
    如需立即幫助,您可以聯系我們的支持團隊,郵箱為support@techflow.com,或撥打1-800-TECHFLOW。"""
    
    state["conversation_history"].append(AIMessage(cnotallow=no_results_response))
    return state

通過這些路由函數,我們可以根據問題的主題相關性和文檔的質量,智能地將問題引導到不同的處理流程中,確保系統能夠高效、準確地處理各種情況。

六、完整工作流組裝

最后,我們將所有的組件和路由邏輯組裝成一個完整的工作流。以下是組裝代碼:

# 初始化對話記憶
conversation_memory = MemorySaver()

# 創建工作流圖
workflow = StateGraph(ConversationState)

# 添加所有處理節點
workflow.add_node("enhance_query", enhance_user_query)
workflow.add_node("validate_topic", validate_topic_relevance)
workflow.add_node("handle_off_topic", handle_off_topic_queries)
workflow.add_node("fetch_content", fetch_relevant_content)
workflow.add_node("assess_relevance", assess_document_relevance)
workflow.add_node("generate_response", generate_contextual_response)
workflow.add_node("optimize_query", optimize_search_query)
workflow.add_node("handle_no_results", handle_no_relevant_results)

# 定義工作流連接
workflow.add_edge("enhance_query", "validate_topic")

# 根據主題相關性進行條件路由
workflow.add_conditional_edges(
    "validate_topic",
    route_by_topic,
    {
        "fetch_content": "fetch_content",
        "handle_off_topic": "handle_off_topic",
    },
)

# 內容處理流程
workflow.add_edge("fetch_content", "assess_relevance")

# 根據文檔質量進行條件路由
workflow.add_conditional_edges(
    "assess_relevance",
    route_by_document_quality,
    {
        "generate_response": "generate_response",
        "optimize_query": "optimize_query", 
        "handle_no_results": "handle_no_results",
    },
)

# 優化循環
workflow.add_edge("optimize_query", "fetch_content")

# 終止節點
workflow.add_edge("generate_response", END)
workflow.add_edge("handle_no_results", END)
workflow.add_edge("handle_off_topic", END)

# 設置入口點
workflow.set_entry_point("enhance_query")

# 編譯工作流
advanced_rag_agent = workflow.compile(checkpointer=conversation_memory)

通過這個完整的工作流,我們的高級RAG代理能夠高效地處理各種復雜的對話場景,為用戶提供準確、有用的信息。

七、測試我們的高級RAG代理

現在,讓我們通過幾個測試場景來檢驗我們的系統。以下是測試代碼和結果:

測試1:超出主題范圍的問題

print("?? Testing Advanced RAG Agent\n")

# 測試1:超出主題范圍的問題
print("=== Test 1: Off-Topic Query ===")
test_input = {"current_query": HumanMessage(cnotallow="What's the weather like today?")}
result = advanced_rag_agent.invoke(
    input=test_input, 
    cnotallow={"configurable": {"thread_id": "test_session_1"}}
)
print(f"Response: {result['conversation_history'][-1].content}\n")

輸出結果:

Testing Advanced RAG Agent

=== Test 1: Off-Topic Query ===
 Enhancing query: What's the weather like today?
 First query - using original: What's the weather like today?
 Validating topic relevance...
 Topic classification: IRRELEVANT (Confidence: HIGH)
 Routing based on topic relevance...
   → Routing to off-topic handler
 Handling off-topic query...
Response: 我專注于幫助解答有關TechFlow Solutions服務、定價和公司信息的問題。 
    您的問題似乎超出了我的專業領域。 
    
    我可以幫助您了解:
    - 我們的云基礎設施服務和定價
    - 支持流程和響應時間  
    - 公司信息和團隊詳情
    - 安全和合規特性
    
    您是否有關于TechFlow Solutions的具體問題需要幫助?

測試2:關于定價的在主題范圍內的問題

# 測試2:關于定價的在主題范圍內的問題
print("=== Test 2: Service Pricing Query ===")
test_input = {"current_query": HumanMessage(cnotallow="What are your support service pricing options?")}
result = advanced_rag_agent.invoke(
    input=test_input,
    cnotallow={"configurable": {"thread_id": "test_session_2"}}
)
print(f"Response: {result['conversation_history'][-1].content}\n")

輸出結果:

=== Test 2: Service Pricing Query ===
 Enhancing query: What are your support service pricing options?
?? First query - using original: What are your support service pricing options?
?? Validating topic relevance...
???  Topic classification: RELEVANT (Confidence: HIGH)
?? Routing based on topic relevance...
   → Proceeding to content retrieval
?? Fetching relevant documents...
?? Retrieved 2 documents
   Document 1: TechFlow Solutions offers three main service tiers...
   Document 2: Our cloud infrastructure services include: Virtual...
?? Assessing document relevance...
?? Document 1: RELEVANT - The document directly answers the question by listing the names, features, and prices of the support service tiers offered by TechFlow Solutions.
?? Document 2: IRRELEVANT - The document describes pricing options for cloud infrastructure services, not support services. Therefore, it's not relevant to the question about support service pricing.
? Final relevant documents: 1
?? Routing based on document quality...
   → Generating response with relevant documents
?? Generating contextual response...
?? Generated response: We have three support service tiers available. Basic Support is $29 per month and includes email sup...
Response: We have three support service tiers available. Basic Support is $29 per month and includes email support and basic troubleshooting. Professional Support is $79 per month, providing priority phone support and advanced diagnostics. Finally, Enterprise Support, at $199 per month, includes 24/7 dedicated support and custom integrations.

通過這兩個測試,我們可以看到我們的高級RAG代理能夠準確地處理不同類型的用戶問題,無論是超出主題范圍的問題,還是在主題范圍內的復雜問題,都能給出準確、有用的回答。

八、總結

我們成功構建了一個能夠處理復雜對話的高級RAG代理。這個系統通過多個AI技術的協同工作,實現了更加智能、上下文感知、可靠的對話AI。關鍵的創新點包括:

  1. 上下文感知的問題改寫:使對話更加自然流暢。
  2. 多層質量控制:通過分類和分級確保回答的質量。
  3. 迭代改進檢索:提高檢索的成功率。
  4. 強大的工作流管理:具備完善的錯誤處理機制。

這個架構為構建能夠處理復雜、多輪對話的生產級RAG應用提供了堅實的基礎,能夠在保持高質量和相關性的同時,為用戶提供準確、有用的信息。


本文轉載自????Halo咯咯????    作者:基咯咯


?著作權歸作者所有,如需轉載,請注明出處,否則將追究法律責任
收藏
回復
舉報
回復
相關推薦
外国成人直播| 久久国产高清| 欧美一级专区免费大片| 日韩黄色动漫| 中文字幕日本不卡| 黄色一级大片在线观看| 国产一二精品视频| 一本一生久久a久久精品综合蜜 | 国产91在线播放精品| 欧美一级理论片| 在线免费观看黄色网址| 国产在线青青草| 免费欧美日韩国产三级电影| 精品国产乱码久久久久久郑州公司| 成人av资源电影网站| 欧亚精品在线观看| 台湾亚洲精品一区二区tv| 色诱女教师一区二区三区| 中文字幕一区久| 亚洲色无码播放| 三上悠亚一区二区| 深夜福利国产精品| 日本精品在线观看| 欧美亚洲第一页| 成人综合久久| 91成人免费看| 久久精品成人| 一区二区不卡视频| 成人的网站免费观看| 动漫av免费观看| 一区二区三区在线看| 国产无套粉嫩白浆在线2022年| 日韩国产精品大片| 国产一区二区三区黄视频| 欧美一区二区三区成人久久片| 韩日视频一区| 久久久神马电影| f2c人成在线观看免费视频| 91精品国产综合久久香蕉的特点| 精品国产丝袜高跟鞋| 欧美变态tickle挠乳网站| 日韩成人伦理| 一区二区亚洲精品国产| 国产精品3区| 国产91精品久久久久久| 色综合久久网| 欧洲国产精品| 成人午夜视频在线| 99视频免费| 在线观看中文字幕不卡| 97超碰在线公开在线看免费| 亚洲美女性视频| 动漫视频在线一区| 成人观看高清在线观看免费| 99re国产精品| 国产老熟妇精品观看| 亚洲免费在线视频| 98在线视频| 在线亚洲欧美视频| 欧美女王vk| 日韩中文一区二区三区| 99re这里只有精品6| 欧美日夜夜逼| 日韩精品免费在线观看| 蜜臀av一区| 日韩久久在线| 国产精品久久网站| 黄色视屏免费在线观看| 久久最新资源网| 亚洲午夜一级| 已婚少妇美妙人妻系列| 日本道精品一区二区三区 | 国内精品写真在线观看| 黄色一级免费大片| 欧美男女性生活在线直播观看| 不卡亚洲精品| 国产91精品一区二区绿帽| www.亚洲色图| av影片免费在线观看| 久久九九热免费视频| 国内精品亚洲| 国产美女av| 亚洲人成电影网站色xx| 中文字幕一区二区精品区| www黄色日本| 欧美成人aa大片| 精品一区不卡| 黄色一级视频在线播放| 欧美视频在线一区二区三区 | 5月婷婷6月丁香| 在线国产电影不卡| 国产乱论精品| 国产激情片在线观看| 色综合 综合色| 日韩精品一区二区三区中文| 日韩高清专区| 天天综合色天天综合色h| 成人永久在线| 天天成人综合网| 欧洲另类一二三四区| 日韩高清一区| 男人添女人下部视频免费| 欧美顶级少妇做爰| 亚洲精品一区二区在线看| 一区二区成人网| 视频在线观看一区二区| 老色鬼精品视频在线观看播放| 性欧美孕妇孕交| 97欧美精品一区二区三区| 国产精品一区不卡| 日本在线视频www鲁啊鲁| 99热国产免费| 亚洲成a人片在线观看中文| 99久热这里只有精品视频免费观看| 一道本在线观看视频| 日韩欧美一区中文| 国产视频久久| 午夜视频成人| 久草精品电影| 欧美综合视频在线观看| 欧美伊人久久| 精品美女视频在线观看免费软件| 国产精品久久电影观看| 中文字幕一区日韩精品欧美| 亚洲一区二区三区四区电影| www黄色日本| 精品国产一区二区在线| 国产a区久久久| xxxxxx欧美| 欧美这里只有精品| 中文字幕精品—区二区| 成年人午夜久久久| 久久99成人| 偷窥自拍亚洲色图| 国产精品国产三级国产aⅴ9色| 一区二区三区在线观看国产| 欧美码中文字幕在线| 美女的诞生在线观看高清免费完整版中文| 国产91在线视频| 五月天久久比比资源色| 欧美成人高清| 羞羞的视频在线看| 黄色网址在线免费看| 亚洲性视频网址| 久久久精品黄色| 国产成人一区| 国产在线你懂得| 日本免费一区二区三区| 亚洲国产成人精品女人久久久| 韩国毛片一区二区三区| 国产a亚洲精品| 国产黄色网页| 99re在线视频观看| 欧美成人激情免费网| 国产精品一区二区久久不卡 | 亚洲第一网中文字幕| 日日骚欧美日韩| 超碰国产一区| 色七七在线观看| 日韩暖暖在线视频| 欧美性猛交xxxxxxxx| 免费xxxx性欧美18vr| 日韩一级特黄| 黄动漫在线观看| 农村寡妇一区二区三区| 国产亚洲激情视频在线| 国产精品你懂的| 欧美三级视频| 欧美黑人粗大| 91在线精品| 久久草.com| 久久久精品国产网站| 亚洲一区av在线| 日韩中文字幕不卡| 一区二区三区四区高清视频| 一级香蕉视频在线观看| 精品国产aⅴ麻豆| www.午夜精品| 欧美午夜电影在线| 国产精品99久久久久久宅男| 日韩精品导航| 国内小视频在线看| 激情六月婷婷| 亚洲最新免费视频| 欧美在线视频观看| 亚洲国产欧美久久| 依依成人综合视频| 精品一区二区三区免费观看 | 日韩高清一区二区| 9l亚洲国产成人精品一区二三 | 综合中文字幕亚洲| 丝袜a∨在线一区二区三区不卡| 美女精品久久| 尤物在线网址| 69国产精品视频| 亚洲黄色一区二区三区| 韩国福利视频一区| 亚洲成色999久久网站| 亚洲一区二区视频在线观看| 韩国女主播成人在线观看|