mrhenu commited on
Commit
88a1dd9
·
verified ·
1 Parent(s): 9d14022

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -153
app.py CHANGED
@@ -1,154 +1,155 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import pandas as pd
5
- from langchain import hub
6
- from langchain.agents import AgentExecutor, create_react_agent
7
- from langchain_community.tools import DuckDuckGoSearchRun
8
- from langchain_huggingface import HuggingFaceEndpoint
9
-
10
- # --- Constants ---
11
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
-
13
- # --- New LangChain Agent Definition ---
14
- class LangChainAgent:
15
- def __init__(self):
16
- print("Initializing LangChainAgent...")
17
-
18
- # 1. Set up the LLM (The "Brain") using the recommended HuggingFaceEndpoint
19
- self.llm = HuggingFaceEndpoint(
20
- repo_id="mistralai/Mistral-7B-Instruct-v0.2",
21
- task="conversational",
22
- max_new_tokens=512,
23
- do_sample=False,
24
- )
25
- print("LLM initialized.")
26
-
27
- # 2. Define the Tools
28
- self.tools = [DuckDuckGoSearchRun()]
29
- print("Tools initialized.")
30
-
31
- # 3. Get the Prompt Template
32
- self.prompt = hub.pull("hwchase17/react")
33
- print("Prompt template pulled.")
34
-
35
- # 4. Create the Agent
36
- self.agent = create_react_agent(self.llm, self.tools, self.prompt)
37
- print("Agent created.")
38
-
39
- # 5. Create the Agent Executor
40
- self.agent_executor = AgentExecutor(
41
- agent=self.agent,
42
- tools=self.tools,
43
- verbose=True,
44
- handle_parsing_errors=True,
45
- max_iterations=5,
46
- )
47
- print("Agent Executor created. Initialization complete.")
48
-
49
- def __call__(self, question: str) -> str:
50
- """
51
- This method is executed for each question.
52
- """
53
- print(f"Agent received question: {question}")
54
-
55
- try:
56
- response = self.agent_executor.invoke({"input": question})
57
- final_answer = response.get("output", "Error: Could not parse final answer.")
58
- except Exception as e:
59
- print(f"Error during agent execution: {e}")
60
- final_answer = "Error: Agent failed to execute."
61
-
62
- print(f"Agent returning answer: {final_answer}")
63
- return str(final_answer)
64
-
65
- # --- Main Application Logic (Uses our new agent) ---
66
- def run_and_submit_all(profile: gr.OAuthProfile | None):
67
- """
68
- Fetches all questions, runs the LangChainAgent on them, submits all answers,
69
- and displays the results.
70
- """
71
- space_id = os.getenv("SPACE_ID")
72
-
73
- if profile:
74
- username = f"{profile.username}"
75
- print(f"User logged in: {username}")
76
- else:
77
- print("User not logged in.")
78
- return "Please Login to Hugging Face with the button.", None
79
-
80
- api_url = DEFAULT_API_URL
81
- questions_url = f"{api_url}/questions"
82
- submit_url = f"{api_url}/submit"
83
-
84
- # 1. Instantiate Agent
85
- try:
86
- agent = LangChainAgent()
87
- except Exception as e:
88
- print(f"Error instantiating agent: {e}")
89
- return f"Error initializing agent: {e}", None
90
-
91
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
92
-
93
- # 2. Fetch Questions
94
- try:
95
- response = requests.get(questions_url, timeout=20)
96
- response.raise_for_status()
97
- questions_data = response.json()
98
- except Exception as e:
99
- return f"An unexpected error occurred fetching questions: {e}", None
100
-
101
- # 3. Run your Agent
102
- results_log = []
103
- answers_payload = []
104
- for item in questions_data:
105
- task_id = item.get("task_id")
106
- question_text = item.get("question")
107
- submitted_answer = agent(question_text)
108
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
109
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
110
-
111
- # 4. Prepare Submission
112
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
113
-
114
- # 5. Submit
115
- try:
116
- response = requests.post(submit_url, json=submission_data, timeout=60)
117
- response.raise_for_status()
118
- result_data = response.json()
119
- final_status = (
120
- f"Submission Successful!\n"
121
- f"User: {result_data.get('username')}\n"
122
- f"Overall Score: {result_data.get('score', 'N/A')}% "
123
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
124
- f"Message: {result_data.get('message', 'No message received.')}"
125
- )
126
- results_df = pd.DataFrame(results_log)
127
- return final_status, results_df
128
- except Exception as e:
129
- status_message = f"An unexpected error occurred during submission: {e}"
130
- results_df = pd.DataFrame(results_log)
131
- return status_message, results_df
132
-
133
- # --- Gradio Interface (Unchanged) ---
134
- with gr.Blocks() as demo:
135
- gr.Markdown("# Agent Evaluation Runner (LangChain Version)")
136
- gr.Markdown(
137
- """
138
- **Instructions:**
139
- 1. Log in to your Hugging Face account using the button below.
140
- 2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
141
- """
142
- )
143
- gr.LoginButton()
144
- run_button = gr.Button("Run Evaluation & Submit All Answers")
145
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
146
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
147
-
148
- run_button.click(
149
- fn=run_and_submit_all,
150
- outputs=[status_output, results_table]
151
- )
152
-
153
- if __name__ == "__main__":
 
154
  demo.launch()
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import pandas as pd
5
+ from langchain import hub
6
+ from langchain.agents import AgentExecutor, create_react_agent
7
+ from langchain_community.tools import DuckDuckGoSearchRun
8
+ from langchain_huggingface import HuggingFaceEndpoint
9
+
10
+ # --- Constants ---
11
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
+
13
+ # --- New LangChain Agent Definition ---
14
+ class LangChainAgent:
15
+ def __init__(self):
16
+ print("Initializing LangChainAgent...")
17
+
18
+ # 1. Set up the LLM (The "Brain") using a stable model
19
+ self.llm = HuggingFaceEndpoint(
20
+ repo_id="google/flan-t5-xxl",
21
+ task="text-generation",
22
+ model_kwargs={
23
+ "max_new_tokens": 512,
24
+ }
25
+ )
26
+ print("LLM initialized with google/flan-t5-xxl.")
27
+
28
+ # 2. Define the Tools
29
+ self.tools = [DuckDuckGoSearchRun()]
30
+ print("Tools initialized.")
31
+
32
+ # 3. Get the Prompt Template
33
+ self.prompt = hub.pull("hwchase17/react")
34
+ print("Prompt template pulled.")
35
+
36
+ # 4. Create the Agent
37
+ self.agent = create_react_agent(self.llm, self.tools, self.prompt)
38
+ print("Agent created.")
39
+
40
+ # 5. Create the Agent Executor
41
+ self.agent_executor = AgentExecutor(
42
+ agent=self.agent,
43
+ tools=self.tools,
44
+ verbose=True,
45
+ handle_parsing_errors=True,
46
+ max_iterations=5,
47
+ )
48
+ print("Agent Executor created. Initialization complete.")
49
+
50
+ def __call__(self, question: str) -> str:
51
+ """
52
+ This method is executed for each question.
53
+ """
54
+ print(f"Agent received question: {question}")
55
+
56
+ try:
57
+ response = self.agent_executor.invoke({"input": question})
58
+ final_answer = response.get("output", "Error: Could not parse final answer.")
59
+ except Exception as e:
60
+ print(f"Error during agent execution: {e}")
61
+ final_answer = "Error: Agent failed to execute."
62
+
63
+ print(f"Agent returning answer: {final_answer}")
64
+ return str(final_answer)
65
+
66
+ # --- Main Application Logic (Uses our new agent) ---
67
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
68
+ """
69
+ Fetches all questions, runs the LangChainAgent on them, submits all answers,
70
+ and displays the results.
71
+ """
72
+ space_id = os.getenv("SPACE_ID")
73
+
74
+ if profile:
75
+ username = f"{profile.username}"
76
+ print(f"User logged in: {username}")
77
+ else:
78
+ print("User not logged in.")
79
+ return "Please Login to Hugging Face with the button.", None
80
+
81
+ api_url = DEFAULT_API_URL
82
+ questions_url = f"{api_url}/questions"
83
+ submit_url = f"{api_url}/submit"
84
+
85
+ # 1. Instantiate Agent
86
+ try:
87
+ agent = LangChainAgent()
88
+ except Exception as e:
89
+ print(f"Error instantiating agent: {e}")
90
+ return f"Error initializing agent: {e}", None
91
+
92
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
93
+
94
+ # 2. Fetch Questions
95
+ try:
96
+ response = requests.get(questions_url, timeout=20)
97
+ response.raise_for_status()
98
+ questions_data = response.json()
99
+ except Exception as e:
100
+ return f"An unexpected error occurred fetching questions: {e}", None
101
+
102
+ # 3. Run your Agent
103
+ results_log = []
104
+ answers_payload = []
105
+ for item in questions_data:
106
+ task_id = item.get("task_id")
107
+ question_text = item.get("question")
108
+ submitted_answer = agent(question_text)
109
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
110
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
111
+
112
+ # 4. Prepare Submission
113
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
114
+
115
+ # 5. Submit
116
+ try:
117
+ response = requests.post(submit_url, json=submission_data, timeout=60)
118
+ response.raise_for_status()
119
+ result_data = response.json()
120
+ final_status = (
121
+ f"Submission Successful!\n"
122
+ f"User: {result_data.get('username')}\n"
123
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
124
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
125
+ f"Message: {result_data.get('message', 'No message received.')}"
126
+ )
127
+ results_df = pd.DataFrame(results_log)
128
+ return final_status, results_df
129
+ except Exception as e:
130
+ status_message = f"An unexpected error occurred during submission: {e}"
131
+ results_df = pd.DataFrame(results_log)
132
+ return status_message, results_df
133
+
134
+ # --- Gradio Interface (Unchanged) ---
135
+ with gr.Blocks() as demo:
136
+ gr.Markdown("# Agent Evaluation Runner (LangChain Version)")
137
+ gr.Markdown(
138
+ """
139
+ **Instructions:**
140
+ 1. Log in to your Hugging Face account using the button below.
141
+ 2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
142
+ """
143
+ )
144
+ gr.LoginButton()
145
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
146
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
147
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
148
+
149
+ run_button.click(
150
+ fn=run_and_submit_all,
151
+ outputs=[status_output, results_table]
152
+ )
153
+
154
+ if __name__ == "__main__":
155
  demo.launch()