k-dovan commited on
Commit
2a78199
·
1 Parent(s): f25fc0e

add text2iamge tool to agent

Browse files
Files changed (6) hide show
  1. Gradio_UI.py +11 -1
  2. agent.json +4 -2
  3. app.py +7 -4
  4. requirements.txt +2 -1
  5. tools/text2image.py +15 -0
  6. tools/web_search.py +7 -2
Gradio_UI.py CHANGED
@@ -104,6 +104,16 @@ def pull_messages_from_step(
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"})
@@ -153,7 +163,7 @@ def stream_to_gradio(
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):
 
104
  # Update parent message metadata to done status without yielding a new message
105
  parent_message_tool.metadata["status"] = "done"
106
 
107
+ # Display generated images captured as observations
108
+ if getattr(step_log, "observations_images", None):
109
+ for image in step_log.observations_images:
110
+ image_path = AgentImage(image).to_string()
111
+ yield gr.ChatMessage(
112
+ role="assistant",
113
+ content={"path": image_path, "mime_type": "image/png"},
114
+ metadata={"title": "🖼️ Output Image", "status": "done"},
115
+ )
116
+
117
  # Handle standalone errors but not from tool calls
118
  elif hasattr(step_log, "error") and step_log.error is not None:
119
  yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
 
163
  ):
164
  yield message
165
 
166
+ final_answer = getattr(step_log, "final_answer", step_log)
167
  final_answer = handle_agent_output_types(final_answer)
168
 
169
  if isinstance(final_answer, AgentText):
agent.json CHANGED
@@ -2,7 +2,8 @@
2
  "tools": [
3
  "web_search",
4
  "visit_webpage",
5
- "final_answer"
 
6
  ],
7
  "model": {
8
  "class": "HfApiModel",
@@ -48,6 +49,7 @@
48
  "queue",
49
  "time",
50
  "collections",
51
- "re"
 
52
  ]
53
  }
 
2
  "tools": [
3
  "web_search",
4
  "visit_webpage",
5
+ "final_answer",
6
+ "image_generator"
7
  ],
8
  "model": {
9
  "class": "HfApiModel",
 
49
  "queue",
50
  "time",
51
  "collections",
52
+ "re",
53
+ "PIL"
54
  ]
55
  }
app.py CHANGED
@@ -4,6 +4,8 @@ import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
 
 
7
  import spaces
8
 
9
  from Gradio_UI import GradioUI
@@ -36,6 +38,7 @@ def get_current_time_in_timezone(timezone: str) -> str:
36
 
37
 
38
  final_answer = FinalAnswerTool()
 
39
 
40
  # 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:
41
  # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
@@ -47,19 +50,19 @@ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may
47
  custom_role_conversions=None,
48
  )
49
 
50
- @space.GPU
51
  def load_my_tool():
52
- return load_tool("agents-course/text-to-image", trust_remote_code=True)
53
 
54
  # Import tool from Hub
55
- image_generation_tool = load_my_tool()
56
 
57
  with open("prompts.yaml", 'r') as stream:
58
  prompt_templates = yaml.safe_load(stream)
59
 
60
  agent = CodeAgent(
61
  model=model,
62
- tools=[final_answer], ## add your tools here (don't remove final answer)
63
  max_steps=6,
64
  verbosity_level=1,
65
  grammar=None,
 
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
+ from tools.web_search import DuckDuckGoSearchTool
8
+ from tools.text2image import TextToImageTool
9
  import spaces
10
 
11
  from Gradio_UI import GradioUI
 
38
 
39
 
40
  final_answer = FinalAnswerTool()
41
+ web_search = DuckDuckGoSearchTool()
42
 
43
  # 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:
44
  # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
 
50
  custom_role_conversions=None,
51
  )
52
 
53
+ @spaces.GPU
54
  def load_my_tool():
55
+ return TextToImageTool()
56
 
57
  # Import tool from Hub
58
+ image_generator = load_my_tool()
59
 
60
  with open("prompts.yaml", 'r') as stream:
61
  prompt_templates = yaml.safe_load(stream)
62
 
63
  agent = CodeAgent(
64
  model=model,
65
+ tools=[final_answer, web_search, image_generator], ## add your tools here (don't remove final answer)
66
  max_steps=6,
67
  verbosity_level=1,
68
  grammar=None,
requirements.txt CHANGED
@@ -2,6 +2,7 @@ markdownify
2
  smolagents==1.13.0
3
  requests
4
  duckduckgo_search
 
5
  pandas
6
  gradio==5.23.1
7
- spaces
 
2
  smolagents==1.13.0
3
  requests
4
  duckduckgo_search
5
+ ddgs==9.16.0
6
  pandas
7
  gradio==5.23.1
8
+ spaces==0.51.3
tools/text2image.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import Tool
2
+ from huggingface_hub import InferenceClient
3
+
4
+
5
+ class TextToImageTool(Tool):
6
+ description = "This tool creates an image according to a prompt, which is a text description."
7
+ name = "image_generator"
8
+ inputs = {"prompt": {"type": "string", "description": "The image generator prompt. Don't hesitate to add details in the prompt to make the image look better, like 'high-res, photorealistic', etc."}}
9
+ output_type = "image"
10
+ model_sdxl = "black-forest-labs/FLUX.1-schnell"
11
+ client = InferenceClient(model_sdxl)
12
+
13
+
14
+ def forward(self, prompt):
15
+ return self.client.text_to_image(prompt)
tools/web_search.py CHANGED
@@ -1,6 +1,6 @@
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"
@@ -12,7 +12,7 @@ class DuckDuckGoSearchTool(Tool):
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`."
@@ -25,3 +25,8 @@ class DuckDuckGoSearchTool(Tool):
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)
 
 
 
 
 
 
1
  from typing import Any, Optional
2
  from smolagents.tools import Tool
3
+ import ddgs
4
 
5
  class DuckDuckGoSearchTool(Tool):
6
  name = "web_search"
 
12
  super().__init__()
13
  self.max_results = max_results
14
  try:
15
+ from ddgs 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`."
 
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)
28
+
29
+ if __name__ == "__main__":
30
+ tool = DuckDuckGoSearchTool(max_results=5)
31
+ query = "Tổng bí thư hiện tại của Việt Nam là ai?"
32
+ print(tool.forward(query))