Rashmi0801 commited on
Commit
80328ae
·
verified ·
1 Parent(s): 2292b12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -55
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 langchain.agents import create_tool_calling_agent, AgentExecutor
6
- from langchain_core.runnables import Runnable
7
- from crewai_tools import ScrapeWebsiteTool
8
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
9
- from langchain_community.chat_models import ChatLiteLLM
10
- from litellm import completion
11
- import importlib
12
-
13
- # Define your custom LLM wrapper class
14
- class CustomLLM(ChatLiteLLM):
15
- def __init__(self):
16
- super().__init__(model="gpt-4")
17
-
18
- def _call(self, prompt: str, stop=None):
19
- response = completion(model="gpt-4", messages=[{"role": "user", "content": prompt}])
20
- return response.choices[0].message["content"]
21
-
22
- # Define your agent class
23
- class GaiaAgent:
24
- def __init__(self):
25
- self.llm = CustomLLM()
26
-
27
- self.prompt = ChatPromptTemplate.from_messages([
28
- ("system", "You are a helpful assistant."),
29
- MessagesPlaceholder(variable_name="chat_history"),
30
- ("human", "{input}"),
31
- MessagesPlaceholder(variable_name="agent_scratchpad"),
32
- ])
33
-
34
- self.tools = [
35
- ScrapeWebsiteTool()
36
- ]
37
-
38
- self.agent: Runnable = create_tool_calling_agent(self.llm, self.tools, self.prompt)
39
- self.agent_executor: AgentExecutor = AgentExecutor(agent=self.agent, tools=self.tools, verbose=True)
40
-
41
- def run(self):
42
- st.title("🧠 GAIA-compatible Agent")
43
- user_input = st.text_input("Enter your query")
44
- if user_input:
45
- response = self.agent_executor.invoke({"input": user_input})
46
- st.write("Response:", response)
47
-
48
- # Main CLI-compatible entry point
49
- if __name__ == "__main__":
50
- parser = argparse.ArgumentParser()
51
- parser.add_argument("--import", type=str, required=False, help="Module to import (ignored for static agent)")
52
- parser.add_argument("--class", type=str, required=False, help="Class name to instantiate (ignored for static agent)")
53
- parser.add_argument("--device", type=str, default="cpu", help="Device type (not used in this agent)")
54
- args = parser.parse_args()
55
-
56
- # Directly instantiate and run the predefined GaiaAgent class
57
- agent = GaiaAgent()
58
- agent.run()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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