File size: 6,639 Bytes
30ee88a aa018e3 0fc97a4 6b84d68 30ee88a 0fc97a4 30ee88a 0fc97a4 30ee88a 6b84d68 aa018e3 6b84d68 0fc97a4 aa018e3 0fc97a4 aa018e3 6b84d68 aa018e3 6b84d68 aa018e3 0fc97a4 aa018e3 6b84d68 aa018e3 0fc97a4 aa018e3 0fc97a4 30ee88a aa018e3 0fc97a4 30ee88a 0fc97a4 aa018e3 0fc97a4 aa018e3 0fc97a4 aa018e3 6b84d68 aa018e3 0fc97a4 aa018e3 0fc97a4 aa018e3 0fc97a4 aa018e3 0fc97a4 aa018e3 0fc97a4 30ee88a 0fc97a4 aa018e3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
import gradio as gr
from langchain_core.messages import HumanMessage, AIMessage
from core.rag_agent import RAGAgent
import traceback
# Initialize components
rag_agent = None
def initialize_agent():
"""Initialize RAG agent lazily"""
global rag_agent
if rag_agent is None:
rag_agent = RAGAgent()
return rag_agent
def chat_with_agent(message, history):
"""Handle chat interactions with the RAG agent"""
if not message.strip():
return history
try:
agent = initialize_agent()
# Convert Gradio history format (dict with role/content) to LangChain messages
messages = []
if history:
for msg_dict in history:
if msg_dict["role"] == "user":
messages.append(HumanMessage(content=msg_dict["content"]))
elif msg_dict["role"] == "assistant":
messages.append(AIMessage(content=msg_dict["content"]))
# Add current user message
messages.append(HumanMessage(content=message))
# Create initial state
initial_state = {
"messages": messages,
}
# Invoke the agent graph
result = agent.agent_graph.invoke(
initial_state,
config=agent.get_config()
)
# Extract AI response
result_messages = result.get("messages", [])
ai_messages = [m for m in result_messages if isinstance(m, AIMessage)]
if ai_messages:
# Get the last AI message
response = ai_messages[-1].content
# Add routing info as metadata (optional)
rag_method = result.get("rag_method", "UNKNOWN")
response_with_metadata = f"{response}\n\n*[Source: {rag_method}]*"
# Return history in Gradio's dict format
new_history = history + [
{"role": "user", "content": message},
{"role": "assistant", "content": response_with_metadata}
]
return new_history
else:
new_history = history + [
{"role": "user", "content": message},
{"role": "assistant", "content": "β οΈ No response generated. Please try again."}
]
return new_history
except Exception as e:
error_msg = f"β Error: {str(e)}"
print(f"Chat error: {e}")
traceback.print_exc()
new_history = history + [
{"role": "user", "content": message},
{"role": "assistant", "content": error_msg}
]
return new_history
def reset_conversation():
"""Reset the conversation thread"""
global rag_agent
if rag_agent:
rag_agent.reset_thread()
return [] # Clear chat history
def create_gradio_ui():
"""Create the complete Gradio interface"""
with gr.Blocks(title="RAG Agent with Agentic Memory") as demo:
gr.Markdown("""
# π€ RAG Agent with Agentic Memory
Chat with an intelligent agent that uses:
- π **Local Knowledge Base** (ChromaDB) - Research papers on DeepAnalyze, AgentMem, SAM3, etc.
- π **Web Search** (Tavily) - Real-time information and current events
- π **Wikipedia** - General knowledge
- π **ArXiv** - Academic papers
""")
with gr.Row():
with gr.Column(scale=4):
gr.Markdown("### π¬ Chat Interface")
chatbot = gr.Chatbot(
label="Conversation",
height=500,
show_label=False,
)
with gr.Row():
msg = gr.Textbox(
label="Your Message",
placeholder="Ask me anything about your documents or general knowledge...",
scale=5,
show_label=False
)
submit_btn = gr.Button("Send π€", variant="primary", scale=1)
with gr.Row():
clear_btn = gr.Button("π Reset Conversation", variant="secondary")
with gr.Column(scale=1):
gr.Markdown("### π Agent Status")
status_box = gr.Markdown("*Ready*")
gr.Markdown("### π‘ Example Queries")
gr.Markdown("""
**Local Documents (RAG):**
- What is DeepAnalyze?
- Explain SAM 3 architecture
- What is AgentMem?
**Web Search:**
- Latest AI news in 2025
- Current events in technology
**General:**
- What is 15 Γ 7?
- Explain machine learning
""")
# Event handlers
def submit_message(message, history):
"""Handle message submission"""
if not message.strip():
return history, ""
# Get response
new_history = chat_with_agent(message, history)
return new_history, ""
# Wire up events
msg.submit(
fn=submit_message,
inputs=[msg, chatbot],
outputs=[chatbot, msg]
)
submit_btn.click(
fn=submit_message,
inputs=[msg, chatbot],
outputs=[chatbot, msg]
)
clear_btn.click(
fn=reset_conversation,
outputs=[chatbot]
)
gr.Markdown("""
---
### π§ How it works:
1. **Type your question** in the text box
2. The agent will:
- π§ Analyze your query to determine the best source
- π Search relevant sources (Local docs, Web, Wikipedia)
- π Generate a comprehensive answer
- πΎ Remember conversation context for follow-up questions
3. Use **Reset Conversation** to start a new thread
---
*Powered by LangGraph + LangChain + ChromaDB + Anthropic Claude*
""")
return demo
if __name__ == "__main__":
demo = create_gradio_ui()
print("π Starting Gradio interface...")
print("π Running on: http://127.0.0.1:7860")
demo.launch(
share=False,
server_name="127.0.0.1",
server_port=7860,
show_error=True
) |