Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,59 +1,148 @@
|
|
1 |
api_key = "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"
|
2 |
|
3 |
-
import argparse
|
4 |
import streamlit as st
|
5 |
-
from
|
6 |
-
from
|
7 |
-
from
|
8 |
-
from
|
9 |
-
from
|
10 |
-
|
11 |
-
import
|
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 |
|
|
|
1 |
api_key = "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"
|
2 |
|
|
|
3 |
import streamlit as st
|
4 |
+
from langchain_groq import ChatGroq
|
5 |
+
from langchain_community.utilities import ArxivAPIWrapper, WikipediaAPIWrapper
|
6 |
+
from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun, DuckDuckGoSearchRun
|
7 |
+
from langchain.agents import initialize_agent, AgentType
|
8 |
+
from langchain.callbacks import StreamlitCallbackHandler
|
9 |
+
import os
|
10 |
+
import requests
|
11 |
+
import pandas as pd
|
12 |
+
from dotenv import load_dotenv
|
13 |
+
|
14 |
+
# Load environment variables
|
15 |
+
load_dotenv()
|
16 |
+
|
17 |
+
# Constants for Basic Agent Evaluation
|
18 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
19 |
+
|
20 |
+
# Initialize search tools
|
21 |
+
api_wrapper_arxiv = ArxivAPIWrapper(top_k_results=1, doc_content_chars_max=250)
|
22 |
+
arxiv = ArxivQueryRun(api_wrapper=api_wrapper_arxiv)
|
23 |
+
api_wrapper_wiki = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=250)
|
24 |
+
wiki = WikipediaQueryRun(api_wrapper=api_wrapper_wiki)
|
25 |
+
search = DuckDuckGoSearchRun(name="Search")
|
26 |
+
|
27 |
+
# Streamlit app layout
|
28 |
+
st.title("Langchain - Chat with Search & Evaluation")
|
29 |
+
|
30 |
+
# Sidebar for settings
|
31 |
+
st.sidebar.title("Settings")
|
32 |
+
api_key = st.sidebar.text_input("Enter your Groq API Key:", type="password")
|
33 |
+
|
34 |
+
# Initialize chat messages
|
35 |
+
if "messages" not in st.session_state:
|
36 |
+
st.session_state["messages"] = [
|
37 |
+
{"role": "assistant", "content": "Hi, I am a Chatbot who can search the web and evaluate questions. How can I help you?"}
|
38 |
+
]
|
39 |
+
|
40 |
+
# Display chat messages
|
41 |
+
for msg in st.session_state.messages:
|
42 |
+
st.chat_message(msg["role"]).write(msg["content"])
|
43 |
+
|
44 |
+
# Chat input
|
45 |
+
if prompt := st.chat_input(placeholder="What is machine learning?"):
|
46 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
47 |
+
st.chat_message("user").write(prompt)
|
48 |
+
|
49 |
+
if not api_key:
|
50 |
+
st.error("Please enter your Groq API key in the sidebar.")
|
51 |
+
st.stop()
|
52 |
+
|
53 |
+
llm = ChatGroq(groq_api_key=api_key, model_name="Llama3-8b-8192", streaming=True)
|
54 |
+
tools = [search, arxiv, wiki]
|
55 |
+
|
56 |
+
search_agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, handle_parsing_errors=True)
|
57 |
+
|
58 |
+
with st.chat_message("assistant"):
|
59 |
+
st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
|
60 |
+
response = search_agent.run(st.session_state.messages, callbacks=[st_cb])
|
61 |
+
st.session_state.messages.append({'role': 'assistant', "content": response})
|
62 |
+
st.write(response)
|
63 |
+
|
64 |
+
# Basic Agent Evaluation Section
|
65 |
+
st.sidebar.title("Basic Agent Evaluation")
|
66 |
+
|
67 |
+
def run_evaluation():
|
68 |
+
"""Function to run the evaluation using the current Groq-powered agent"""
|
69 |
+
if not api_key:
|
70 |
+
st.error("Please enter your Groq API key in the sidebar.")
|
71 |
+
return "API key required", pd.DataFrame()
|
72 |
+
|
73 |
+
username = "streamlit_user" # Default username for Streamlit
|
74 |
+
api_url = DEFAULT_API_URL
|
75 |
+
questions_url = f"{api_url}/questions"
|
76 |
+
submit_url = f"{api_url}/submit"
|
77 |
+
space_id = os.getenv("SPACE_ID", "local")
|
78 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id != "local" else "local_execution"
|
79 |
+
|
80 |
+
# 1. Instantiate Agent
|
81 |
+
try:
|
82 |
+
llm = ChatGroq(groq_api_key=api_key, model_name="Llama3-8b-8192")
|
83 |
+
tools = [search, arxiv, wiki]
|
84 |
+
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, handle_parsing_errors=True)
|
85 |
+
except Exception as e:
|
86 |
+
return f"Error initializing agent: {e}", pd.DataFrame()
|
87 |
+
|
88 |
+
# 2. Fetch Questions
|
89 |
+
try:
|
90 |
+
response = requests.get(questions_url, timeout=15)
|
91 |
+
response.raise_for_status()
|
92 |
+
questions_data = response.json()
|
93 |
+
if not questions_data:
|
94 |
+
return "Fetched questions list is empty or invalid format.", pd.DataFrame()
|
95 |
+
except Exception as e:
|
96 |
+
return f"Error fetching questions: {e}", pd.DataFrame()
|
97 |
+
|
98 |
+
# 3. Run Agent
|
99 |
+
results_log = []
|
100 |
+
answers_payload = []
|
101 |
+
for item in questions_data:
|
102 |
+
task_id = item.get("task_id")
|
103 |
+
question_text = item.get("question")
|
104 |
+
if not task_id or question_text is None:
|
105 |
+
continue
|
106 |
+
try:
|
107 |
+
submitted_answer = agent.run(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 |
+
except Exception as e:
|
111 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
112 |
+
|
113 |
+
if not answers_payload:
|
114 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
115 |
+
|
116 |
+
# 4. Prepare and Submit
|
117 |
+
submission_data = {
|
118 |
+
"username": username,
|
119 |
+
"agent_code": agent_code,
|
120 |
+
"answers": answers_payload
|
121 |
+
}
|
122 |
+
|
123 |
+
try:
|
124 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
125 |
+
response.raise_for_status()
|
126 |
+
result_data = response.json()
|
127 |
+
final_status = (
|
128 |
+
f"Submission Successful!\n"
|
129 |
+
f"User: {result_data.get('username')}\n"
|
130 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
131 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
132 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
133 |
+
)
|
134 |
+
return final_status, pd.DataFrame(results_log)
|
135 |
+
except Exception as e:
|
136 |
+
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
137 |
+
|
138 |
+
# Evaluation button in sidebar
|
139 |
+
if st.sidebar.button("Run Evaluation & Submit Answers"):
|
140 |
+
with st.spinner("Running evaluation and submitting answers..."):
|
141 |
+
status, results = run_evaluation()
|
142 |
+
|
143 |
+
st.sidebar.text_area("Evaluation Status", value=status, height=150)
|
144 |
+
|
145 |
+
if not results.empty:
|
146 |
+
st.subheader("Evaluation Results")
|
147 |
+
st.dataframe(results)
|
148 |
|