razvanfischer commited on
Commit
5f5a29d
·
1 Parent(s): 7c6c2ea

Initial draft

Browse files
.idea/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
.idea/Agents_Course_Final_Project.iml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/venv" />
6
+ </content>
7
+ <orderEntry type="jdk" jdkName="Python 3.11 (Agents_Course_Final_Project)" jdkType="Python SDK" />
8
+ <orderEntry type="sourceFolder" forTests="false" />
9
+ </component>
10
+ <component name="PyDocumentationSettings">
11
+ <option name="format" value="PLAIN" />
12
+ <option name="myDocStringFormat" value="Plain" />
13
+ </component>
14
+ </module>
.idea/inspectionProfiles/Project_Default.xml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <profile version="1.0">
3
+ <option name="myName" value="Project Default" />
4
+ <inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
5
+ <option name="ignoredPackages">
6
+ <value>
7
+ <list size="12">
8
+ <item index="0" class="java.lang.String" itemvalue="blinker" />
9
+ <item index="1" class="java.lang.String" itemvalue="joblib" />
10
+ <item index="2" class="java.lang.String" itemvalue="Werkzeug" />
11
+ <item index="3" class="java.lang.String" itemvalue="tzdata" />
12
+ <item index="4" class="java.lang.String" itemvalue="MarkupSafe" />
13
+ <item index="5" class="java.lang.String" itemvalue="numpy" />
14
+ <item index="6" class="java.lang.String" itemvalue="click" />
15
+ <item index="7" class="java.lang.String" itemvalue="uuid" />
16
+ <item index="8" class="java.lang.String" itemvalue="pandas" />
17
+ <item index="9" class="java.lang.String" itemvalue="pytz" />
18
+ <item index="10" class="java.lang.String" itemvalue="itsdangerous" />
19
+ <item index="11" class="java.lang.String" itemvalue="Flask" />
20
+ </list>
21
+ </value>
22
+ </option>
23
+ </inspection_tool>
24
+ </profile>
25
+ </component>
.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
.idea/misc.xml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (Agents_Course_Final_Project)" project-jdk-type="Python SDK" />
4
+ </project>
.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/Agents_Course_Final_Project.iml" filepath="$PROJECT_DIR$/.idea/Agents_Course_Final_Project.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
app.py CHANGED
@@ -7,6 +7,15 @@ import asyncio
7
  from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec
8
  from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
9
  from llama_index.core.agent.workflow import AgentWorkflow
 
 
 
 
 
 
 
 
 
10
 
11
 
12
  # (Keep Constants as is)
@@ -18,13 +27,41 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
18
  class BasicAgent:
19
  def __init__(self):
20
  self.llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct")
21
- self.search_tool = DuckDuckGoSearchToolSpec()
22
- self.agent = AgentWorkflow.from_tools_or_functions([self.search_tool], llm=self.llm)
 
 
 
 
23
  print("BasicAgent initialized.")
24
 
25
  async def __call__(self, question: str) -> str:
26
- response = await self.agent.run(question)
27
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  def run_and_submit_all( profile: gr.OAuthProfile | None):
30
  """
@@ -179,25 +216,28 @@ with gr.Blocks() as demo:
179
  )
180
 
181
  if __name__ == "__main__":
182
- print("\n" + "-"*30 + " App Starting " + "-"*30)
183
- # Check for SPACE_HOST and SPACE_ID at startup for information
184
- space_host_startup = os.getenv("SPACE_HOST")
185
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
186
-
187
- if space_host_startup:
188
- print(f" SPACE_HOST found: {space_host_startup}")
189
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
190
- else:
191
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
192
-
193
- if space_id_startup: # Print repo URLs if SPACE_ID is found
194
- print(f" SPACE_ID found: {space_id_startup}")
195
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
196
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
197
- else:
198
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
199
-
200
- print("-"*(60 + len(" App Starting ")) + "\n")
201
-
202
- print("Launching Gradio Interface for Basic Agent Evaluation...")
203
- demo.launch(debug=True, share=False)
 
 
 
 
7
  from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec
8
  from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
9
  from llama_index.core.agent.workflow import AgentWorkflow
10
+ from llama_index.core import SummaryIndex
11
+ from llama_index.readers.web import SimpleWebPageReader
12
+ from llama_index.core.agent.workflow import (
13
+ AgentInput,
14
+ AgentOutput,
15
+ ToolCall,
16
+ ToolCallResult,
17
+ AgentStream,
18
+ )
19
 
20
 
21
  # (Keep Constants as is)
 
27
  class BasicAgent:
28
  def __init__(self):
29
  self.llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct")
30
+ system_prompt = """
31
+ You are a helpful assistant that answers questions. If you don't know the answer, you can search the web for information.
32
+ If you are searching the web, keep the query very concise in order to get good results.
33
+ """
34
+ self.agent = AgentWorkflow.from_tools_or_functions([search_web], llm=self.llm,
35
+ system_prompt=system_prompt)
36
  print("BasicAgent initialized.")
37
 
38
  async def __call__(self, question: str) -> str:
39
+ handler = self.agent.run(user_msg=question)
40
+ async for event in handler.stream_events():
41
+ if isinstance(event, AgentStream):
42
+ print(event.delta, end="", flush=True)
43
+ elif isinstance(event, ToolCallResult):
44
+ print(event.tool_name) # the tool name
45
+ print(event.tool_kwargs) # the tool kwargs
46
+ print(event.tool_output) # the tool output
47
+ response = await handler
48
+ return str(response)
49
+
50
+ async def search_web(query: str) -> str:
51
+ """Useful for using the web to answer questions. Keep the query very concise in order to get good results."""
52
+ client = DuckDuckGoSearchToolSpec()
53
+ search_res = client.duckduckgo_instant_search(query)
54
+ return str(search_res)
55
+ # print("Search res: ", search_res)
56
+ # web_pages = [search_res[i]['url'] if 'url' in search_res[i] else None for i in range(len(search_res))]
57
+ # web_pages = [web_pages[0]]
58
+ # documents = SimpleWebPageReader(html_to_text=True).load_data(
59
+ # web_pages
60
+ # )
61
+ # return documents
62
+ # # documents = SimpleWebPageReader(html_to_text=True).load_data(
63
+ # # ["http://paulgraham.com/worked.html"]
64
+ # # )
65
 
66
  def run_and_submit_all( profile: gr.OAuthProfile | None):
67
  """
 
216
  )
217
 
218
  if __name__ == "__main__":
219
+ agent = BasicAgent()
220
+ answ = asyncio.run(agent("Who is Michael Jackson?"))
221
+
222
+ # print("\n" + "-"*30 + " App Starting " + "-"*30)
223
+ # # Check for SPACE_HOST and SPACE_ID at startup for information
224
+ # space_host_startup = os.getenv("SPACE_HOST")
225
+ # space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
226
+ #
227
+ # if space_host_startup:
228
+ # print(f"SPACE_HOST found: {space_host_startup}")
229
+ # print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
230
+ # else:
231
+ # print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
232
+ #
233
+ # if space_id_startup: # Print repo URLs if SPACE_ID is found
234
+ # print(f"✅ SPACE_ID found: {space_id_startup}")
235
+ # print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
236
+ # print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
237
+ # else:
238
+ # print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
239
+ #
240
+ # print("-"*(60 + len(" App Starting ")) + "\n")
241
+ #
242
+ # print("Launching Gradio Interface for Basic Agent Evaluation...")
243
+ # demo.launch(debug=True, share=False)
requirements.txt CHANGED
@@ -1,8 +1,10 @@
1
  gradio
 
2
  requests
3
  llama-index
4
  llama-index-vector-stores-chroma
5
  llama-index-llms-huggingface-api
6
  llama-index-embeddings-huggingface
7
  llama-index-tools-duckduckgo
 
8
  syncio
 
1
  gradio
2
+ gradio[oauth]
3
  requests
4
  llama-index
5
  llama-index-vector-stores-chroma
6
  llama-index-llms-huggingface-api
7
  llama-index-embeddings-huggingface
8
  llama-index-tools-duckduckgo
9
+ llama-index-readers-web
10
  syncio