Nishanth88 commited on
Commit
21a1823
·
verified ·
1 Parent(s): 6eb6008

Upload 4 files

Browse files
Files changed (4) hide show
  1. .gitignore +41 -0
  2. README.md +57 -13
  3. app.py +54 -111
  4. requirements.txt +2 -1
.gitignore ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ env/
8
+ build/
9
+ develop-eggs/
10
+ dist/
11
+ downloads/
12
+ eggs/
13
+ .eggs/
14
+ lib/
15
+ lib64/
16
+ parts/
17
+ sdist/
18
+ var/
19
+ wheels/
20
+ *.egg-info/
21
+ .installed.cfg
22
+ *.egg
23
+
24
+ # Virtual Environment
25
+ venv/
26
+ ENV/
27
+ .env
28
+
29
+ # IDE
30
+ .idea/
31
+ .vscode/
32
+ *.swp
33
+ *.swo
34
+
35
+ # Logs
36
+ *.log
37
+ logs/
38
+
39
+ # Local development
40
+ .DS_Store
41
+ Thumbs.db
README.md CHANGED
@@ -1,13 +1,57 @@
1
- ---
2
- title: WebSearch
3
- emoji: 💬
4
- colorFrom: yellow
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 5.0.1
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Web Search Tool
3
+ emoji: 🔍
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 4.0.0
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # Web Search Tool
13
+
14
+ This Hugging Face Space provides an interactive web interface for searching information from the web using the smolagents library.
15
+
16
+ ## Features
17
+
18
+ - **Web Search**: Searches the web for information using DuckDuckGo
19
+ - **Interactive Interface**: Easy-to-use web interface powered by Gradio
20
+ - **Simple Design**: Straightforward search and results display
21
+
22
+ ## Usage
23
+
24
+ 1. Enter your query in the text box
25
+ 2. Click the "Submit" button
26
+ 3. Get information from the web
27
+
28
+ ## Example Queries
29
+
30
+ - "Latest developments in quantum computing"
31
+ - "Current trends in artificial intelligence"
32
+ - "Recent breakthroughs in renewable energy"
33
+
34
+ ## Technical Details
35
+
36
+ Built with:
37
+ - Python 3.9+
38
+ - Gradio for the web interface
39
+ - smolagents for web searching
40
+
41
+ ## Local Development
42
+
43
+ To run this project locally:
44
+
45
+ 1. Clone the repository
46
+ 2. Install dependencies: `pip install -r requirements.txt`
47
+ 3. Run the application: `python app.py`
48
+
49
+ ## License
50
+
51
+ This project is open-source and available under the MIT License.
52
+
53
+ ## Acknowledgments
54
+
55
+ - Built using Hugging Face Spaces
56
+ - Powered by smolagents library
57
+ - Interface created with Gradio
app.py CHANGED
@@ -1,111 +1,54 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
- from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, VisitWebpageTool, HfApiModel
4
-
5
- # Initialize HuggingFace client
6
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
7
-
8
- # Create the smolagents agent (without UserInputTool since we'll get input from Gradio)
9
- agent = CodeAgent(
10
- tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), FinalAnswerTool()],
11
- model=HfApiModel(),
12
- max_steps=8,
13
- verbosity_level=1
14
- )
15
-
16
- # Function to perform web research with a provided query
17
- def research_with_query(query):
18
- result = agent.run(f"""
19
- Think step by step:
20
-
21
- 1. The user has asked about: "{query}"
22
- 2. Use the DuckDuckGoSearchTool to search the web for information about this query.
23
- 3. From the search results, identify 1-2 relevant webpage URLs that might contain detailed information.
24
- 4. Use the VisitWebpageTool to visit each identified webpage and extract its content.
25
- 5. Combine the information from the search results and webpage visits.
26
- 6. Create a comprehensive bullet point summary of all collected information.
27
- 7. Each bullet point should start with "• " and be on a new line.
28
- 8. Use the FinalAnswerTool to present your bullet-point summary as the final answer.
29
-
30
- Make sure your bullet points are clear, well-organized, and directly relevant to the user's query.
31
- Include the most important and factual information from your research.
32
- """)
33
- return result
34
-
35
- def respond(
36
- message,
37
- history: list[tuple[str, str]],
38
- system_message,
39
- max_tokens,
40
- temperature,
41
- top_p,
42
- use_web_search,
43
- ):
44
- # Check if web search is enabled and message starts with a research request
45
- if use_web_search and message.strip().lower().startswith(("search:", "research:", "find info:")):
46
- query = message.split(":", 1)[1].strip()
47
-
48
- yield "Searching the web for information about your query. This may take a moment..."
49
-
50
- try:
51
- # Perform the web search and get bullet point summary
52
- research_results = research_with_query(query)
53
-
54
- # Return the research results
55
- yield f"Here's what I found about '{query}':\n\n{research_results}"
56
- except Exception as e:
57
- yield f"Sorry, I encountered an error while searching the web: {str(e)}"
58
- else:
59
- # Regular chat completion for normal messages
60
- messages = [{"role": "system", "content": system_message}]
61
-
62
- for val in history:
63
- if val[0]:
64
- messages.append({"role": "user", "content": val[0]})
65
- if val[1]:
66
- messages.append({"role": "assistant", "content": val[1]})
67
-
68
- messages.append({"role": "user", "content": message})
69
-
70
- response = ""
71
-
72
- for message in client.chat_completion(
73
- messages,
74
- max_tokens=max_tokens,
75
- stream=True,
76
- temperature=temperature,
77
- top_p=top_p,
78
- ):
79
- token = message.choices[0].delta.content
80
- response += token
81
- yield response
82
-
83
- # Create the Gradio interface
84
- demo = gr.ChatInterface(
85
- respond,
86
- additional_inputs=[
87
- gr.Textbox(
88
- value="You are a helpful assistant. When users ask you to search for information with 'search:', 'research:', or 'find info:', you will search the web for them.",
89
- label="System message"
90
- ),
91
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
92
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
93
- gr.Slider(
94
- minimum=0.1,
95
- maximum=1.0,
96
- value=0.95,
97
- step=0.05,
98
- label="Top-p (nucleus sampling)",
99
- ),
100
- gr.Checkbox(value=True, label="Enable web search (use 'search:', 'research:', or 'find info:' to search)")
101
- ],
102
- examples=[
103
- ["search: latest developments in quantum computing"],
104
- ["research: climate change impacts in 2023"],
105
- ["find info: benefits of meditation"],
106
- ["Hello! How are you today?"]
107
- ],
108
- )
109
-
110
- if __name__ == "__main__":
111
- demo.launch()
 
1
+ import gradio as gr
2
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, HfApiModel, Tool, tool, VisitWebpageTool
3
+
4
+ @tool
5
+ def search_web(query: str) -> str:
6
+ """
7
+ Searches the web for information.
8
+
9
+ Args:
10
+ query: The search query string
11
+
12
+ Returns:
13
+ str: Search results summary
14
+ """
15
+ search_tool = DuckDuckGoSearchTool()
16
+ return search_tool.forward(query)
17
+
18
+ # Create the agent
19
+ agent = CodeAgent(
20
+ tools=[
21
+ DuckDuckGoSearchTool(),
22
+ VisitWebpageTool(),
23
+ search_web
24
+ ],
25
+ model=HfApiModel(),
26
+ max_steps=5,
27
+ verbosity_level=2
28
+ )
29
+
30
+ def process_query(query):
31
+ """Process the user query using the agent."""
32
+ try:
33
+ result = agent.run(query)
34
+ return result
35
+ except Exception as e:
36
+ return f"An error occurred: {str(e)}"
37
+
38
+ # Create Gradio interface
39
+ iface = gr.Interface(
40
+ fn=process_query,
41
+ inputs=gr.Textbox(label="Enter your query", placeholder="What would you like to know about?"),
42
+ outputs=gr.Textbox(label="Results"),
43
+ title="Web Search Tool",
44
+ description="Enter any topic to get information from the web.",
45
+ examples=[
46
+ ["Latest developments in quantum computing"],
47
+ ["Current trends in artificial intelligence"],
48
+ ["Recent breakthroughs in renewable energy"]
49
+ ]
50
+ )
51
+
52
+ # Launch the app
53
+ if __name__ == "__main__":
54
+ iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1 +1,2 @@
1
- huggingface_hub==0.25.2
 
 
1
+ gradio>=4.0.0
2
+ smolagents>=0.1.0