Spaces:
Sleeping
Sleeping
Commit ·
726f816
1
Parent(s): dba87ef
fixed RAG state message issue
Browse filesFiles changed (2)
- agents/rag_agent.py+74-24
- app.py+4-14
63 unmodified lines646566676869137 unmodified lines2072082092102112122132142152162172182192202212222233 unmodified lines2272282292302312322332342356 unmodified lines2422432442452462472482492502511 unmodified line25325425525625725825926070 unmodified lines33133233333433533633733833934034134234334434534634734834935035135235335435535635735835936010 unmodified lines37137237337437537637737837938063 unmodified linesis_sufficient: bool = Falseretry_count: int = 0 # Track number of retries to prevent infinite loopsmax_retries: int = 3 # Maximum number of query rewrites allowedclass AgenticRAGChat(ChatInterface):137 unmodified lines"""Evaluate the documents retrieved from the retriever tool."""print("Evaluating documents...")# Get original user question and retrieved docsuser_question = state["messages"][0].contentretrieved_docs = state["messages"][-1].contentchain = DOCUMENT_EVALUATOR_PROMPT | self.evaluator_llmevaluation = chain.invoke({"question": user_question,"retrieved_docs": retrieved_docs})print(f"Evaluation result: {evaluation}")return {"is_sufficient": evaluation.is_sufficient,"feedback": evaluation.feedback3 unmodified lines"""Synthesize the final answer from retrieved documents."""print("Synthesizing answer...")user_question = state["messages"][0].contentretrieved_docs = state["messages"][-1].contentchain = DOCUMENT_SYNTHESIZER_PROMPT | self.llmanswer = chain.invoke({"question": user_question,6 unmodified lines"""Rewrite the query based on evaluation feedback."""print("Rewriting query...")user_question = state["messages"][0].contentretrieved_docs = state["messages"][-1].contentfeedback = state["feedback"]chain = QUERY_REWRITER_PROMPT | self.llmnew_query = chain.invoke({"question": user_question,1 unmodified line"retrieved_docs": retrieved_docs})print(f"Rewritten query: {new_query.content}")return {"messages": [new_query]}def _create_graph(self) -> Any:"""Create the agentic RAG graph."""70 unmodified lines# Convert chat history to messageshistory_messages = self._convert_history_to_messages(chat_history)# Add the current messagehistory_messages.append(HumanMessage(content=message))# Create initial state with full conversation historystate = AgenticRAGState(messages=history_messages, # Include full history instead of just current messagefeedback="",is_sufficient=False,retry_count=0,max_retries=3)# state = AgenticRAGState(# messages=[HumanMessage(content=message)],# feedback="",# is_sufficient=False,# retry_count=0,# max_retries=3 # Limit to 3 retries to prevent infinite loops# )try:# Run the workflow# Run the workflow with increased recursion limitconfig = {"recursion_limit": 30} # Increased but reasonable limitresult = self.graph.invoke(state, config=config)print("\n=== RAG QUERY COMPLETED ===")10 unmodified linesexcept Exception as e:print(f"Error in RAG processing: {e}")# Provide a more helpful fallback responseif "recursion" in str(e).lower():return ("I had difficulty finding the exact information you're looking for in the documents. ""Based on the available documents, I can see references to various offices and services, ""but I couldn't find specific details about Mission Support Services. ""You might want to try asking about a specific aspect or department.")return f"I encountered an error while searching for information: {str(e)}"63 unmodified lines64656667686970137 unmodified lines2082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442453 unmodified lines2492502512522532542552562572582592602612622632642652662672682692706 unmodified lines2772782792802812822832842852862872882892902912922932942952962972982993003011 unmodified line30330430530630730830931031131231370 unmodified lines38438538638738838939039139239339439539639739839940040140240340440540640740840941041141210 unmodified lines42342442542642742842943063 unmodified linesis_sufficient: bool = Falseretry_count: int = 0 # Track number of retries to prevent infinite loopsmax_retries: int = 3 # Maximum number of query rewrites allowedcurrent_query_index: int = 0 # Track which message is the current queryclass AgenticRAGChat(ChatInterface):137 unmodified lines"""Evaluate the documents retrieved from the retriever tool."""print("Evaluating documents...")# Check if we've hit max retriesif state.get("retry_count", 0) >= state.get("max_retries", 3):print(f"Max retries ({state.get('max_retries', 3)}) reached. Forcing synthesis with available documents.")return {"is_sufficient": True, # Force synthesis even if not perfect"feedback": "Maximum retries reached. Using available documents."}# Get the CURRENT user question, not the first message in history# Use the current_query_index to get the right messagecurrent_query_index = state.get("current_query_index", 0)# Find the current query messageuser_messages = [msg for msg in state["messages"] if isinstance(msg, HumanMessage)]if current_query_index < len(state["messages"]):user_question = state["messages"][current_query_index].contentelse:# Fallback: get the last user messageuser_question = user_messages[-1].content if user_messages else state["messages"][-1].content# Get the retrieved documents (should be the last message)retrieved_docs = state["messages"][-1].contentprint(f"Evaluating for query: '{user_question[:50]}...'") # Debug printchain = DOCUMENT_EVALUATOR_PROMPT | self.evaluator_llmevaluation = chain.invoke({"question": user_question,"retrieved_docs": retrieved_docs})print(f"Evaluation result: {evaluation} (Retry {state.get('retry_count', 0)}/{state.get('max_retries', 3)})")return {"is_sufficient": evaluation.is_sufficient,"feedback": evaluation.feedback3 unmodified lines"""Synthesize the final answer from retrieved documents."""print("Synthesizing answer...")# Get the CURRENT user question using the indexcurrent_query_index = state.get("current_query_index", 0)# Find the current query messageuser_messages = [msg for msg in state["messages"] if isinstance(msg, HumanMessage)]if current_query_index < len(state["messages"]):user_question = state["messages"][current_query_index].contentelse:# Fallback: get the last user messageuser_question = user_messages[-1].content if user_messages else state["messages"][-1].content# Get the retrieved documentsretrieved_docs = state["messages"][-1].contentprint(f"Synthesizing answer for: '{user_question[:50]}...'") # Debug printchain = DOCUMENT_SYNTHESIZER_PROMPT | self.llmanswer = chain.invoke({"question": user_question,6 unmodified lines"""Rewrite the query based on evaluation feedback."""print("Rewriting query...")# Increment retry countcurrent_retry = state.get("retry_count", 0)# Get the CURRENT user question using the indexcurrent_query_index = state.get("current_query_index", 0)# Find the current query messageuser_messages = [msg for msg in state["messages"] if isinstance(msg, HumanMessage)]if current_query_index < len(state["messages"]):user_question = state["messages"][current_query_index].contentelse:# Fallback: get the last user messageuser_question = user_messages[-1].content if user_messages else state["messages"][-1].contentretrieved_docs = state["messages"][-1].contentfeedback = state["feedback"]print(f"Rewriting query for: '{user_question[:50]}...'") # Debug printchain = QUERY_REWRITER_PROMPT | self.llmnew_query = chain.invoke({"question": user_question,1 unmodified line"retrieved_docs": retrieved_docs})print(f"Rewritten query (Attempt {current_retry + 1}/{state.get('max_retries', 3)}): {new_query.content}")return {"messages": [new_query],"retry_count": current_retry + 1 # Increment retry count}def _create_graph(self) -> Any:"""Create the agentic RAG graph."""70 unmodified lines# Convert chat history to messageshistory_messages = self._convert_history_to_messages(chat_history)# Mark the position where the current query starts# This is important for the evaluator to know which is the actual queryhistory_length = len(history_messages)# Add the current messagecurrent_query_message = HumanMessage(content=message)history_messages.append(current_query_message)# Create initial state with full conversation history# Store the index of the current query for referencestate = AgenticRAGState(messages=history_messages,feedback="",is_sufficient=False,retry_count=0,max_retries=3,# Add this to track the current query indexcurrent_query_index=history_length # This is the index of the current query)try:# Run the workflow with increased recursion limitconfig = {"recursion_limit": 30}result = self.graph.invoke(state, config=config)print("\n=== RAG QUERY COMPLETED ===")10 unmodified linesexcept Exception as e:print(f"Error in RAG processing: {e}")if "recursion" in str(e).lower():return ("I had difficulty finding the exact information you're looking for in the documents. ""Based on the available documents, I can see references to various topics, ""but I couldn't find specific details. You might want to try asking about a specific aspect.")return f"I encountered an error while searching for information: {str(e)}"
80 unmodified lines8182838485868788895 unmodified lines959697989910010110210310410510610710880 unmodified linesexamples=["What is 847 * 293?","What's today's date?","What's the weather in San Francisco?","Explain quantum computing in simple terms","Research the impact of AI on healthcare",],theme=gr.themes.Soft(),analytics_enabled=False,5 unmodified linesif __name__ == "__main__":# Create and launch the demodemo = create_demo()# Check if running in Hugging Face Spacesif os.environ.get("SPACE_ID"):# Hugging Face Spaces configurationdemo.launch(server_name="0.0.0.0",server_port=int(os.environ.get("PORT", 7860)))else:# Local development - use simple defaultsdemo.launch()80 unmodified lines8182838485868788895 unmodified lines9596979880 unmodified linesexamples=["What is 847 * 293?","What's today's date?",# "What's the weather in San Francisco?",# "Explain quantum computing in simple terms",# "Research the impact of AI on healthcare",],theme=gr.themes.Soft(),analytics_enabled=False,5 unmodified linesif __name__ == "__main__":# Create and launch the demodemo = create_demo()demo.launch()
agents/rag_agent.py+74-24
app.py+4-14