hibam1 Claude Opus 5.5 commited on
Commit
066fbc2
·
1 Parent(s): 8c5c24b

Use OpenAI/Ollama models, ddgs search, add .env.example, trim deps

Browse files
Files changed (8) hide show
  1. .env.example +4 -0
  2. .gitignore +5 -0
  3. Gradio_UI.py +0 -296
  4. app.py +74 -62
  5. requirements.txt +4 -5
  6. tools/final_answer.py +0 -14
  7. tools/visit_webpage.py +0 -45
  8. tools/web_search.py +0 -27
.env.example ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copy to .env and fill in: cp .env.example .env
2
+ # "openai" (needs OPENAI_API_KEY) or "ollama" (local, free)
3
+ MODEL_PROVIDER=openai
4
+ OPENAI_API_KEY=
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .env
2
+ .venv/
3
+ __pycache__/
4
+ .gradio/
5
+ .DS_Store
Gradio_UI.py DELETED
@@ -1,296 +0,0 @@
1
- #!/usr/bin/env python
2
- # coding=utf-8
3
- # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
- import mimetypes
17
- import os
18
- import re
19
- import shutil
20
- from typing import Optional
21
-
22
- from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
23
- from smolagents.agents import ActionStep, MultiStepAgent
24
- from smolagents.memory import MemoryStep
25
- from smolagents.utils import _is_package_available
26
-
27
-
28
- def pull_messages_from_step(
29
- step_log: MemoryStep,
30
- ):
31
- """Extract ChatMessage objects from agent steps with proper nesting"""
32
- import gradio as gr
33
-
34
- if isinstance(step_log, ActionStep):
35
- # Output the step number
36
- step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
37
- yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
38
-
39
- # First yield the thought/reasoning from the LLM
40
- if hasattr(step_log, "model_output") and step_log.model_output is not None:
41
- # Clean up the LLM output
42
- model_output = step_log.model_output.strip()
43
- # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
44
- model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
45
- model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
46
- model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
47
- model_output = model_output.strip()
48
- yield gr.ChatMessage(role="assistant", content=model_output)
49
-
50
- # For tool calls, create a parent message
51
- if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
52
- first_tool_call = step_log.tool_calls[0]
53
- used_code = first_tool_call.name == "python_interpreter"
54
- parent_id = f"call_{len(step_log.tool_calls)}"
55
-
56
- # Tool call becomes the parent message with timing info
57
- # First we will handle arguments based on type
58
- args = first_tool_call.arguments
59
- if isinstance(args, dict):
60
- content = str(args.get("answer", str(args)))
61
- else:
62
- content = str(args).strip()
63
-
64
- if used_code:
65
- # Clean up the content by removing any end code tags
66
- content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
67
- content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
68
- content = content.strip()
69
- if not content.startswith("```python"):
70
- content = f"```python\n{content}\n```"
71
-
72
- parent_message_tool = gr.ChatMessage(
73
- role="assistant",
74
- content=content,
75
- metadata={
76
- "title": f"🛠️ Used tool {first_tool_call.name}",
77
- "id": parent_id,
78
- "status": "pending",
79
- },
80
- )
81
- yield parent_message_tool
82
-
83
- # Nesting execution logs under the tool call if they exist
84
- if hasattr(step_log, "observations") and (
85
- step_log.observations is not None and step_log.observations.strip()
86
- ): # Only yield execution logs if there's actual content
87
- log_content = step_log.observations.strip()
88
- if log_content:
89
- log_content = re.sub(r"^Execution logs:\s*", "", log_content)
90
- yield gr.ChatMessage(
91
- role="assistant",
92
- content=f"{log_content}",
93
- metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
94
- )
95
-
96
- # Nesting any errors under the tool call
97
- if hasattr(step_log, "error") and step_log.error is not None:
98
- yield gr.ChatMessage(
99
- role="assistant",
100
- content=str(step_log.error),
101
- metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
102
- )
103
-
104
- # Update parent message metadata to done status without yielding a new message
105
- parent_message_tool.metadata["status"] = "done"
106
-
107
- # Handle standalone errors but not from tool calls
108
- elif hasattr(step_log, "error") and step_log.error is not None:
109
- yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
110
-
111
- # Calculate duration and token information
112
- step_footnote = f"{step_number}"
113
- if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
114
- token_str = (
115
- f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
116
- )
117
- step_footnote += token_str
118
- if hasattr(step_log, "duration"):
119
- step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
120
- step_footnote += step_duration
121
- step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
122
- yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
123
- yield gr.ChatMessage(role="assistant", content="-----")
124
-
125
-
126
- def stream_to_gradio(
127
- agent,
128
- task: str,
129
- reset_agent_memory: bool = False,
130
- additional_args: Optional[dict] = None,
131
- ):
132
- """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
133
- if not _is_package_available("gradio"):
134
- raise ModuleNotFoundError(
135
- "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
136
- )
137
- import gradio as gr
138
-
139
- total_input_tokens = 0
140
- total_output_tokens = 0
141
-
142
- for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
143
- # Track tokens if model provides them
144
- if hasattr(agent.model, "last_input_token_count"):
145
- total_input_tokens += agent.model.last_input_token_count
146
- total_output_tokens += agent.model.last_output_token_count
147
- if isinstance(step_log, ActionStep):
148
- step_log.input_token_count = agent.model.last_input_token_count
149
- step_log.output_token_count = agent.model.last_output_token_count
150
-
151
- for message in pull_messages_from_step(
152
- step_log,
153
- ):
154
- yield message
155
-
156
- final_answer = step_log # Last log is the run's final_answer
157
- final_answer = handle_agent_output_types(final_answer)
158
-
159
- if isinstance(final_answer, AgentText):
160
- yield gr.ChatMessage(
161
- role="assistant",
162
- content=f"**Final answer:**\n{final_answer.to_string()}\n",
163
- )
164
- elif isinstance(final_answer, AgentImage):
165
- yield gr.ChatMessage(
166
- role="assistant",
167
- content={"path": final_answer.to_string(), "mime_type": "image/png"},
168
- )
169
- elif isinstance(final_answer, AgentAudio):
170
- yield gr.ChatMessage(
171
- role="assistant",
172
- content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
173
- )
174
- else:
175
- yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
176
-
177
-
178
- class GradioUI:
179
- """A one-line interface to launch your agent in Gradio"""
180
-
181
- def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
182
- if not _is_package_available("gradio"):
183
- raise ModuleNotFoundError(
184
- "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
185
- )
186
- self.agent = agent
187
- self.file_upload_folder = file_upload_folder
188
- if self.file_upload_folder is not None:
189
- if not os.path.exists(file_upload_folder):
190
- os.mkdir(file_upload_folder)
191
-
192
- def interact_with_agent(self, prompt, messages):
193
- import gradio as gr
194
-
195
- messages.append(gr.ChatMessage(role="user", content=prompt))
196
- yield messages
197
- for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
198
- messages.append(msg)
199
- yield messages
200
- yield messages
201
-
202
- def upload_file(
203
- self,
204
- file,
205
- file_uploads_log,
206
- allowed_file_types=[
207
- "application/pdf",
208
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
209
- "text/plain",
210
- ],
211
- ):
212
- """
213
- Handle file uploads, default allowed types are .pdf, .docx, and .txt
214
- """
215
- import gradio as gr
216
-
217
- if file is None:
218
- return gr.Textbox("No file uploaded", visible=True), file_uploads_log
219
-
220
- try:
221
- mime_type, _ = mimetypes.guess_type(file.name)
222
- except Exception as e:
223
- return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
224
-
225
- if mime_type not in allowed_file_types:
226
- return gr.Textbox("File type disallowed", visible=True), file_uploads_log
227
-
228
- # Sanitize file name
229
- original_name = os.path.basename(file.name)
230
- sanitized_name = re.sub(
231
- r"[^\w\-.]", "_", original_name
232
- ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
233
-
234
- type_to_ext = {}
235
- for ext, t in mimetypes.types_map.items():
236
- if t not in type_to_ext:
237
- type_to_ext[t] = ext
238
-
239
- # Ensure the extension correlates to the mime type
240
- sanitized_name = sanitized_name.split(".")[:-1]
241
- sanitized_name.append("" + type_to_ext[mime_type])
242
- sanitized_name = "".join(sanitized_name)
243
-
244
- # Save the uploaded file to the specified folder
245
- file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
246
- shutil.copy(file.name, file_path)
247
-
248
- return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
249
-
250
- def log_user_message(self, text_input, file_uploads_log):
251
- return (
252
- text_input
253
- + (
254
- f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
255
- if len(file_uploads_log) > 0
256
- else ""
257
- ),
258
- "",
259
- )
260
-
261
- def launch(self, **kwargs):
262
- import gradio as gr
263
-
264
- with gr.Blocks(fill_height=True) as demo:
265
- stored_messages = gr.State([])
266
- file_uploads_log = gr.State([])
267
- chatbot = gr.Chatbot(
268
- label="Agent",
269
- type="messages",
270
- avatar_images=(
271
- None,
272
- "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
273
- ),
274
- resizeable=True,
275
- scale=1,
276
- )
277
- # If an upload folder is provided, enable the upload feature
278
- if self.file_upload_folder is not None:
279
- upload_file = gr.File(label="Upload a file")
280
- upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
281
- upload_file.change(
282
- self.upload_file,
283
- [upload_file, file_uploads_log],
284
- [upload_status, file_uploads_log],
285
- )
286
- text_input = gr.Textbox(lines=1, label="Chat Message")
287
- text_input.submit(
288
- self.log_user_message,
289
- [text_input, file_uploads_log],
290
- [stored_messages, text_input],
291
- ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
292
-
293
- demo.launch(debug=True, share=True, **kwargs)
294
-
295
-
296
- __all__ = ["stream_to_gradio", "GradioUI"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,69 +1,81 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
 
 
 
2
  import datetime
3
- import requests
4
- import pytz
5
- import yaml
6
- from tools.final_answer import FinalAnswerTool
7
 
8
- from Gradio_UI import GradioUI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
- @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
- Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
- """
19
- return "What magic will you build ?"
20
 
21
  @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
 
24
  Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
 
 
26
  """
27
- try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
33
- except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
-
36
-
37
- final_answer = FinalAnswerTool()
38
-
39
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
-
42
- model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
- )
48
-
49
-
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
-
53
- with open("prompts.yaml", 'r') as stream:
54
- prompt_templates = yaml.safe_load(stream)
55
-
56
- agent = CodeAgent(
57
- model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
- max_steps=6,
60
- verbosity_level=1,
61
- grammar=None,
62
- planning_interval=None,
63
- name=None,
64
- description=None,
65
- prompt_templates=prompt_templates
66
- )
67
-
68
-
69
- GradioUI(agent).launch()
 
1
+ import os
2
+
3
+ from dotenv import load_dotenv
4
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel, OpenAIServerModel, tool
5
  import datetime
 
 
 
 
6
 
7
+ load_dotenv() # reads MODEL_PROVIDER and OPENAI_API_KEY from .env
8
+
9
+ # "openai" (cloud, needs OPENAI_API_KEY) or "ollama" (local, free)
10
+ MODEL_PROVIDER = os.getenv("MODEL_PROVIDER", "openai")
11
+
12
+ OPENAI_MODEL_ID = "gpt-4.1-mini" # any chat model your OpenAI account has access to
13
+ OLLAMA_MODEL_ID = "qwen2:7b" # any model listed by `ollama list`
14
+
15
+
16
+ def build_model():
17
+ if MODEL_PROVIDER == "openai":
18
+ return OpenAIServerModel(
19
+ model_id=OPENAI_MODEL_ID,
20
+ api_key=os.environ["OPENAI_API_KEY"],
21
+ )
22
+ if MODEL_PROVIDER == "ollama":
23
+ return LiteLLMModel(
24
+ model_id=f"ollama_chat/{OLLAMA_MODEL_ID}",
25
+ api_base="http://127.0.0.1:11434",
26
+ num_ctx=8192,
27
+ )
28
+ raise ValueError(f"Unknown MODEL_PROVIDER {MODEL_PROVIDER!r}, use 'openai' or 'ollama'")
29
+
30
+
31
+ model = build_model()
32
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  @tool
35
+ def suggest_menu(occasion: str) -> str:
36
+ """
37
+ Suggests a menu based on the occasion.
38
  Args:
39
+ occasion: The type of occasion for the party. Allowed values are:
40
+ - "casual": Menu for casual party.
41
+ - "formal": Menu for formal party.
42
+ - "superhero": Menu for superhero party.
43
+ - "custom": Custom menu.
44
  """
45
+ if occasion == "casual":
46
+ return "Pizza, snacks, and drinks."
47
+ elif occasion == "formal":
48
+ return "3-course dinner with wine and dessert."
49
+ elif occasion == "superhero":
50
+ return "Buffet with high-energy and healthy food."
51
+ else:
52
+ return "Custom menu for the butler."
53
+
54
+
55
+ def main_v1() -> None:
56
+ # Example 1: search the web for a party playlist
57
+ music_agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=model)
58
+ music_agent.run("Search for the best music recommendations for a party at the Wayne's mansion.")
59
+
60
+ # Example 2: use the custom menu tool
61
+ menu_agent = CodeAgent(tools=[suggest_menu], model=model)
62
+ menu_agent.run("Prepare a formal menu for the party.")
63
+
64
+ def main() -> None:
65
+ agent = CodeAgent(tools=[], model=model, additional_authorized_imports=['datetime'])
66
+
67
+ agent.run(
68
+ """
69
+ Alfred needs to prepare for the party. Here are the tasks:
70
+ 1. Prepare the drinks - 30 minutes
71
+ 2. Decorate the mansion - 60 minutes
72
+ 3. Set up the menu - 45 minutes
73
+ 4. Prepare the music and playlist - 45 minutes
74
+
75
+ If we start right now, at what time will the party be ready?
76
+ """
77
+ )
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,5 +1,4 @@
1
- markdownify
2
- smolagents==1.13.0
3
- requests
4
- duckduckgo_search
5
- pandas
 
1
+ smolagents[openai,litellm]
2
+ ddgs
3
+ python-dotenv
4
+ datetime
 
tools/final_answer.py DELETED
@@ -1,14 +0,0 @@
1
- from typing import Any, Optional
2
- from smolagents.tools import Tool
3
-
4
- class FinalAnswerTool(Tool):
5
- name = "final_answer"
6
- description = "Provides a final answer to the given problem."
7
- inputs = {'answer': {'type': 'any', 'description': 'The final answer to the problem'}}
8
- output_type = "any"
9
-
10
- def forward(self, answer: Any) -> Any:
11
- return answer
12
-
13
- def __init__(self, *args, **kwargs):
14
- self.is_initialized = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/visit_webpage.py DELETED
@@ -1,45 +0,0 @@
1
- from typing import Any, Optional
2
- from smolagents.tools import Tool
3
- import requests
4
- import markdownify
5
- import smolagents
6
-
7
- class VisitWebpageTool(Tool):
8
- name = "visit_webpage"
9
- description = "Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."
10
- inputs = {'url': {'type': 'string', 'description': 'The url of the webpage to visit.'}}
11
- output_type = "string"
12
-
13
- def forward(self, url: str) -> str:
14
- try:
15
- import requests
16
- from markdownify import markdownify
17
- from requests.exceptions import RequestException
18
-
19
- from smolagents.utils import truncate_content
20
- except ImportError as e:
21
- raise ImportError(
22
- "You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."
23
- ) from e
24
- try:
25
- # Send a GET request to the URL with a 20-second timeout
26
- response = requests.get(url, timeout=20)
27
- response.raise_for_status() # Raise an exception for bad status codes
28
-
29
- # Convert the HTML content to Markdown
30
- markdown_content = markdownify(response.text).strip()
31
-
32
- # Remove multiple line breaks
33
- markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
34
-
35
- return truncate_content(markdown_content, 10000)
36
-
37
- except requests.exceptions.Timeout:
38
- return "The request timed out. Please try again later or check the URL."
39
- except RequestException as e:
40
- return f"Error fetching the webpage: {str(e)}"
41
- except Exception as e:
42
- return f"An unexpected error occurred: {str(e)}"
43
-
44
- def __init__(self, *args, **kwargs):
45
- self.is_initialized = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/web_search.py DELETED
@@ -1,27 +0,0 @@
1
- from typing import Any, Optional
2
- from smolagents.tools import Tool
3
- import duckduckgo_search
4
-
5
- class DuckDuckGoSearchTool(Tool):
6
- name = "web_search"
7
- description = "Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results."
8
- inputs = {'query': {'type': 'string', 'description': 'The search query to perform.'}}
9
- output_type = "string"
10
-
11
- def __init__(self, max_results=10, **kwargs):
12
- super().__init__()
13
- self.max_results = max_results
14
- try:
15
- from duckduckgo_search import DDGS
16
- except ImportError as e:
17
- raise ImportError(
18
- "You must install package `duckduckgo_search` to run this tool: for instance run `pip install duckduckgo-search`."
19
- ) from e
20
- self.ddgs = DDGS(**kwargs)
21
-
22
- def forward(self, query: str) -> str:
23
- results = self.ddgs.text(query, max_results=self.max_results)
24
- if len(results) == 0:
25
- raise Exception("No results found! Try a less restrictive/shorter query.")
26
- postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" for result in results]
27
- return "## Search Results\n\n" + "\n\n".join(postprocessed_results)