RichardHu commited on
Commit
2bb6630
·
verified ·
1 Parent(s): 0295215

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -96
app.py CHANGED
@@ -34,102 +34,61 @@
34
 
35
 
36
  import gradio as gr
37
- from tools import run_agentic_rag # 从tool模块导入工作流运行函数
38
- import time
39
-
40
- def format_history(history):
41
- """格式化执行历史用于显示"""
42
- formatted = []
43
- for entry in history:
44
- step = entry.get("step", "")
45
- status = entry.get("status", "")
46
- action = entry.get("action", "")
47
- details = ""
48
-
49
- if step == "检索" and status == "完成":
50
- docs = entry.get("documents", [])
51
- details = f"检索到 {len(docs)} 个文档"
52
-
53
- elif step == "生成" and status == "完成":
54
- answer = entry.get("answer", "")
55
- details = f"生成答案: {answer[:100]}..." if len(answer) > 100 else f"生成答案: {answer}"
56
-
57
- elif step == "验证" and status == "完成":
58
- verif = entry.get("verification", {})
59
- valid = verif.get("valid", False)
60
- feedback = verif.get("feedback", "")
61
- details = f"结果: {'通过' if valid else '失败'}, 反馈: {feedback}"
62
-
63
- elif step == "准备重试" and status == "完成":
64
- feedback = entry.get("feedback", "")
65
- details = f"反馈: {feedback}"
66
-
67
- elif "action" in entry:
68
- details = entry["action"]
69
-
70
- formatted.append(f"{step}: {status} {details}")
71
-
72
- return "\n".join(formatted)
73
 
74
- def process_query(question):
75
- """处理用户查询"""
76
- start_time = time.time()
77
-
78
- # 执行RAG工作流
79
- result = run_agentic_rag(question)
80
-
81
- # 准备结果显示
82
- documents = "\n\n".join([
83
- f"文档 {i+1}:\n{doc[:200]}..." if len(doc) > 200 else f"文档 {i+1}:\n{doc}"
84
- for i, doc in enumerate(result["documents"])
85
- ])
86
-
87
- end_time = time.time()
88
- process_time = f"{end_time - start_time:.2f}秒"
89
-
90
- return {
91
- "answer": result["answer"],
92
- "documents": documents,
93
- "history": format_history(result["history"]),
94
- "stats": f"重试次数: {result['retries_used']} | 处理时间: {process_time}"
95
- }
96
-
97
- # 创建Gradio界面
98
- with gr.Blocks(title="Agentic RAG with LangGraph") as demo:
99
- gr.Markdown("# 🧠 Agentic RAG 系统 (LangGraph 实现)")
100
- gr.Markdown("使用LangGraph实现的带有自我验证和重试机制的RAG系统")
 
 
 
 
 
 
 
 
 
 
101
 
102
- with gr.Row():
103
- with gr.Column():
104
- question = gr.Textbox(
105
- label="输入问题",
106
- placeholder="在此输入您的问题...",
107
- lines=3
108
- )
109
- submit_btn = gr.Button("提交", variant="primary")
110
 
111
- with gr.Column():
112
- answer = gr.Textbox(label="最终答案", interactive=False, lines=5)
113
- documents = gr.Textbox(label="相关文档", interactive=False, lines=10)
114
- history = gr.Textbox(label="执行历史", interactive=False, lines=15)
115
- stats = gr.Textbox(label="统计信息", interactive=False)
116
-
117
- # 事件处理
118
- submit_btn.click(
119
- fn=process_query,
120
- inputs=[question],
121
- outputs=[answer, documents, history, stats]
122
- )
123
-
124
- # 示例问题
125
- gr.Examples(
126
- examples=[
127
- "量子纠缠是什么?它有哪些实际应用?",
128
- "解释Transformer架构的核心创新点",
129
- "如何在PyTorch中实现一个简单的神经网络?"
130
- ],
131
- inputs=question
132
- )
133
-
134
- if __name__ == "__main__":
135
- demo.launch()
 
34
 
35
 
36
  import gradio as gr
37
+ import random
38
+ from langgraph.graph import StateGraph, END
39
+ from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, ToolMessage
40
+ from langchain_core.prompts import ChatPromptTemplate
41
+ from langchain_openai import ChatOpenAI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ # Import our custom tools from their modules
44
+ from tools import DuckDuckGoSearchTool, WeatherInfoTool, HubStatsTool
45
+ from retriever import load_guest_dataset
46
+
47
+ # 定义状态对象
48
+ class AgentState(TypedDict):
49
+ messages: List[BaseMessage] # 消息历史
50
+ plan: Optional[str] # 当前计划
51
+ tool_results: List[dict] # 工具执行结果
52
+ step_count: int # 当前步骤计数
53
+
54
+ # Initialize the model - 使用ChatOpenAI替代HfApiModel
55
+ model = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)
56
+
57
+ # Initialize the tools
58
+ search_tool = DuckDuckGoSearchTool()
59
+ weather_info_tool = WeatherInfoTool()
60
+ hub_stats_tool = HubStatsTool()
61
+ guest_info_tool = load_guest_dataset()
62
+
63
+ # 所有可用工具
64
+ TOOLS = {
65
+ "duckduckgo_search": search_tool,
66
+ "weather_info": weather_info_tool,
67
+ "hub_stats": hub_stats_tool,
68
+ "guest_info": guest_info_tool,
69
+ # 可以在这里添加基础工具
70
+ }
71
+
72
+ # ========================
73
+ # LangGraph 节点函数
74
+ # ========================
75
+
76
+ def plan_node(state: AgentState):
77
+ """规划节点 - 决定下一步行动"""
78
+ messages = state["messages"]
79
+ step_count = state["step_count"]
80
 
81
+ # 每3步进行规划
82
+ if step_count % 3 == 0:
83
+ # 创建规划提示
84
+ prompt = ChatPromptTemplate.from_messages([
85
+ ("system", "你是一个智能助手Alfred。根据对话历史和当前状态,规划下一步行动。"),
86
+ ("human", "当前对话历史:\n{messages}\n\n请规划下一步行动。")
87
+ ])
 
88
 
89
+ chain = prompt | model
90
+ response = chain.invoke({"messages": "\n".join([m.content for m in messages])})
91
+
92
+ return {
93
+ "plan": response.content,
94
+ "messages": messages