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+ name + "!!"
|
| 5 |
+
|
| 6 |
+
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
|
| 7 |
+
demo.launch()
|
| 8 |
+
|
| 9 |
+
# import os
|
| 10 |
+
# import sys
|
| 11 |
+
# import json
|
| 12 |
+
# import argparse
|
| 13 |
+
# import time
|
| 14 |
+
# import io
|
| 15 |
+
# import uuid
|
| 16 |
+
# from PIL import Image
|
| 17 |
+
# from typing import List, Dict, Any, Iterator
|
| 18 |
+
# import gradio as gr
|
| 19 |
+
|
| 20 |
+
# # Add the project root to the Python path
|
| 21 |
+
# current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 22 |
+
# project_root = os.path.dirname(os.path.dirname(os.path.dirname(current_dir)))
|
| 23 |
+
# sys.path.insert(0, project_root)
|
| 24 |
+
|
| 25 |
+
# from opentools.models.initializer import Initializer
|
| 26 |
+
# from opentools.models.planner import Planner
|
| 27 |
+
# from opentools.models.memory import Memory
|
| 28 |
+
# from opentools.models.executor import Executor
|
| 29 |
+
# from opentools.models.utlis import make_json_serializable
|
| 30 |
+
|
| 31 |
+
# solver = None
|
| 32 |
+
|
| 33 |
+
# class ChatMessage:
|
| 34 |
+
# def __init__(self, role: str, content: str, metadata: dict = None):
|
| 35 |
+
# self.role = role
|
| 36 |
+
# self.content = content
|
| 37 |
+
# self.metadata = metadata or {}
|
| 38 |
+
|
| 39 |
+
# class Solver:
|
| 40 |
+
# def __init__(
|
| 41 |
+
# self,
|
| 42 |
+
# planner,
|
| 43 |
+
# memory,
|
| 44 |
+
# executor,
|
| 45 |
+
# task: str,
|
| 46 |
+
# task_description: str,
|
| 47 |
+
# output_types: str = "base,final,direct",
|
| 48 |
+
# index: int = 0,
|
| 49 |
+
# verbose: bool = True,
|
| 50 |
+
# max_steps: int = 10,
|
| 51 |
+
# max_time: int = 60,
|
| 52 |
+
# output_json_dir: str = "results",
|
| 53 |
+
# root_cache_dir: str = "cache"
|
| 54 |
+
# ):
|
| 55 |
+
# self.planner = planner
|
| 56 |
+
# self.memory = memory
|
| 57 |
+
# self.executor = executor
|
| 58 |
+
# self.task = task
|
| 59 |
+
# self.task_description = task_description
|
| 60 |
+
# self.index = index
|
| 61 |
+
# self.verbose = verbose
|
| 62 |
+
# self.max_steps = max_steps
|
| 63 |
+
# self.max_time = max_time
|
| 64 |
+
# self.output_json_dir = output_json_dir
|
| 65 |
+
# self.root_cache_dir = root_cache_dir
|
| 66 |
+
|
| 67 |
+
# self.output_types = output_types.lower().split(',')
|
| 68 |
+
# assert all(output_type in ["base", "final", "direct"] for output_type in self.output_types), "Invalid output type. Supported types are 'base', 'final', 'direct'."
|
| 69 |
+
|
| 70 |
+
# # self.benchmark_data = self.load_benchmark_data()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# def stream_solve_user_problem(self, user_query: str, user_image: Image.Image, messages: List[ChatMessage]) -> Iterator[List[ChatMessage]]:
|
| 75 |
+
# """
|
| 76 |
+
# Streams intermediate thoughts and final responses for the problem-solving process based on user input.
|
| 77 |
+
|
| 78 |
+
# Args:
|
| 79 |
+
# user_query (str): The text query input from the user.
|
| 80 |
+
# user_image (Image.Image): The uploaded image from the user (PIL Image object).
|
| 81 |
+
# messages (list): A list of ChatMessage objects to store the streamed responses.
|
| 82 |
+
# """
|
| 83 |
+
|
| 84 |
+
# if user_image:
|
| 85 |
+
# # # Convert PIL Image to bytes (for processing)
|
| 86 |
+
# # img_bytes_io = io.BytesIO()
|
| 87 |
+
# # user_image.save(img_bytes_io, format="PNG") # Convert image to PNG bytes
|
| 88 |
+
# # img_bytes = img_bytes_io.getvalue() # Get bytes
|
| 89 |
+
|
| 90 |
+
# # Use image paths instead of bytes,
|
| 91 |
+
# os.makedirs(os.path.join(self.root_cache_dir, 'images'), exist_ok=True)
|
| 92 |
+
# img_path = os.path.join(self.root_cache_dir, 'images', str(uuid.uuid4()) + '.jpg')
|
| 93 |
+
# user_image.save(img_path)
|
| 94 |
+
# else:
|
| 95 |
+
# img_path = None
|
| 96 |
+
|
| 97 |
+
# # Set query cache
|
| 98 |
+
# _cache_dir = os.path.join(self.root_cache_dir)
|
| 99 |
+
# self.executor.set_query_cache_dir(_cache_dir)
|
| 100 |
+
|
| 101 |
+
# # Step 1: Display the received inputs
|
| 102 |
+
# if user_image:
|
| 103 |
+
# messages.append(ChatMessage(role="assistant", content=f"π Received Query: {user_query}\nπΌοΈ Image Uploaded"))
|
| 104 |
+
# else:
|
| 105 |
+
# messages.append(ChatMessage(role="assistant", content=f"π Received Query: {user_query}"))
|
| 106 |
+
# yield messages
|
| 107 |
+
|
| 108 |
+
# # Step 2: Add "thinking" status while processing
|
| 109 |
+
# messages.append(ChatMessage(
|
| 110 |
+
# role="assistant",
|
| 111 |
+
# content="",
|
| 112 |
+
# metadata={"title": "β³ Thinking: Processing input..."}
|
| 113 |
+
# ))
|
| 114 |
+
|
| 115 |
+
# # Step 3: Initialize problem-solving state
|
| 116 |
+
# start_time = time.time()
|
| 117 |
+
# step_count = 0
|
| 118 |
+
# json_data = {"query": user_query, "image": "Image received as bytes"}
|
| 119 |
+
|
| 120 |
+
# # Step 4: Query Analysis
|
| 121 |
+
# import pdb; pdb.set_trace()
|
| 122 |
+
# query_analysis = self.planner.analyze_query(user_query, img_path)
|
| 123 |
+
# json_data["query_analysis"] = query_analysis
|
| 124 |
+
# messages.append(ChatMessage(role="assistant", content=f"π Query Analysis:\n{query_analysis}"))
|
| 125 |
+
# yield messages
|
| 126 |
+
|
| 127 |
+
# # Step 5: Execution loop (similar to your step-by-step solver)
|
| 128 |
+
# while step_count < self.max_steps and (time.time() - start_time) < self.max_time:
|
| 129 |
+
# step_count += 1
|
| 130 |
+
# messages.append(ChatMessage(role="assistant", content=f"π Step {step_count}: Generating next step..."))
|
| 131 |
+
# yield messages
|
| 132 |
+
|
| 133 |
+
# # Generate the next step
|
| 134 |
+
# next_step = self.planner.generate_next_step(
|
| 135 |
+
# user_query, img_path, query_analysis, self.memory, step_count, self.max_steps
|
| 136 |
+
# )
|
| 137 |
+
# context, sub_goal, tool_name = self.planner.extract_context_subgoal_and_tool(next_step)
|
| 138 |
+
|
| 139 |
+
# # Display the step information
|
| 140 |
+
# messages.append(ChatMessage(
|
| 141 |
+
# role="assistant",
|
| 142 |
+
# content=f"π Step {step_count} Details:\n- Context: {context}\n- Sub-goal: {sub_goal}\n- Tool: {tool_name}"
|
| 143 |
+
# ))
|
| 144 |
+
# yield messages
|
| 145 |
+
|
| 146 |
+
# # Handle tool execution or errors
|
| 147 |
+
# if tool_name not in self.planner.available_tools:
|
| 148 |
+
# messages.append(ChatMessage(role="assistant", content=f"β οΈ Error: Tool '{tool_name}' is not available."))
|
| 149 |
+
# yield messages
|
| 150 |
+
# continue
|
| 151 |
+
|
| 152 |
+
# # Execute the tool command
|
| 153 |
+
# tool_command = self.executor.generate_tool_command(
|
| 154 |
+
# user_query, img_path, context, sub_goal, tool_name, self.planner.toolbox_metadata[tool_name]
|
| 155 |
+
# )
|
| 156 |
+
# explanation, command = self.executor.extract_explanation_and_command(tool_command)
|
| 157 |
+
# result = self.executor.execute_tool_command(tool_name, command)
|
| 158 |
+
# result = make_json_serializable(result)
|
| 159 |
+
|
| 160 |
+
# messages.append(ChatMessage(role="assistant", content=f"β
Step {step_count} Result:\n{json.dumps(result, indent=4)}"))
|
| 161 |
+
# yield messages
|
| 162 |
+
|
| 163 |
+
# # Step 6: Memory update and stopping condition
|
| 164 |
+
# self.memory.add_action(step_count, tool_name, sub_goal, tool_command, result)
|
| 165 |
+
# stop_verification = self.planner.verificate_memory(user_query, img_path, query_analysis, self.memory)
|
| 166 |
+
# conclusion = self.planner.extract_conclusion(stop_verification)
|
| 167 |
+
|
| 168 |
+
# messages.append(ChatMessage(role="assistant", content=f"π Step {step_count} Conclusion: {conclusion}"))
|
| 169 |
+
# yield messages
|
| 170 |
+
|
| 171 |
+
# if conclusion == 'STOP':
|
| 172 |
+
# break
|
| 173 |
+
|
| 174 |
+
# # Step 7: Generate Final Output (if needed)
|
| 175 |
+
# if 'final' in self.output_types:
|
| 176 |
+
# final_output = self.planner.generate_final_output(user_query, img_path, self.memory)
|
| 177 |
+
# messages.append(ChatMessage(role="assistant", content=f"π― Final Output:\n{final_output}"))
|
| 178 |
+
# yield messages
|
| 179 |
+
|
| 180 |
+
# if 'direct' in self.output_types:
|
| 181 |
+
# direct_output = self.planner.generate_direct_output(user_query, img_path, self.memory)
|
| 182 |
+
# messages.append(ChatMessage(role="assistant", content=f"πΉ Direct Output:\n{direct_output}"))
|
| 183 |
+
# yield messages
|
| 184 |
+
|
| 185 |
+
# # Step 8: Completion Message
|
| 186 |
+
# messages.append(ChatMessage(role="assistant", content="β
Problem-solving process complete."))
|
| 187 |
+
# yield messages
|
| 188 |
+
|
| 189 |
+
# def parse_arguments():
|
| 190 |
+
# parser = argparse.ArgumentParser(description="Run the OpenTools demo with specified parameters.")
|
| 191 |
+
# parser.add_argument("--llm_engine_name", default="gpt-4o", help="LLM engine name.")
|
| 192 |
+
# parser.add_argument("--max_tokens", type=int, default=2000, help="Maximum tokens for LLM generation.")
|
| 193 |
+
# parser.add_argument("--run_baseline_only", type=bool, default=False, help="Run only the baseline (no toolbox).")
|
| 194 |
+
# parser.add_argument("--task", default="minitoolbench", help="Task to run.")
|
| 195 |
+
# parser.add_argument("--task_description", default="", help="Task description.")
|
| 196 |
+
# parser.add_argument(
|
| 197 |
+
# "--output_types",
|
| 198 |
+
# default="base,final,direct",
|
| 199 |
+
# help="Comma-separated list of required outputs (base,final,direct)"
|
| 200 |
+
# )
|
| 201 |
+
# parser.add_argument("--enabled_tools", default="Generalist_Solution_Generator_Tool", help="List of enabled tools.")
|
| 202 |
+
# parser.add_argument("--root_cache_dir", default="demo_solver_cache", help="Path to solver cache directory.")
|
| 203 |
+
# parser.add_argument("--output_json_dir", default="demo_results", help="Path to output JSON directory.")
|
| 204 |
+
# parser.add_argument("--max_steps", type=int, default=10, help="Maximum number of steps to execute.")
|
| 205 |
+
# parser.add_argument("--max_time", type=int, default=60, help="Maximum time allowed in seconds.")
|
| 206 |
+
# parser.add_argument("--verbose", type=bool, default=True, help="Enable verbose output.")
|
| 207 |
+
# return parser.parse_args()
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# def solve_problem_gradio(user_query, user_image):
|
| 211 |
+
# """
|
| 212 |
+
# Wrapper function to connect the solver to Gradio.
|
| 213 |
+
# Streams responses from `solver.stream_solve_user_problem` for real-time UI updates.
|
| 214 |
+
# """
|
| 215 |
+
# global solver # Ensure we're using the globally defined solver
|
| 216 |
+
|
| 217 |
+
# if solver is None:
|
| 218 |
+
# return [["assistant", "β οΈ Error: Solver is not initialized. Please restart the application."]]
|
| 219 |
+
|
| 220 |
+
# messages = [] # Initialize message list
|
| 221 |
+
# for message_batch in solver.stream_solve_user_problem(user_query, user_image, messages):
|
| 222 |
+
# yield [[msg.role, msg.content] for msg in message_batch] # Ensure correct format for Gradio Chatbot
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
# def main(args):
|
| 227 |
+
# global solver
|
| 228 |
+
# # Initialize Tools
|
| 229 |
+
# enabled_tools = args.enabled_tools.split(",") if args.enabled_tools else []
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
# # Instantiate Initializer
|
| 233 |
+
# initializer = Initializer(
|
| 234 |
+
# enabled_tools=enabled_tools,
|
| 235 |
+
# model_string=args.llm_engine_name
|
| 236 |
+
# )
|
| 237 |
+
|
| 238 |
+
# # Instantiate Planner
|
| 239 |
+
# planner = Planner(
|
| 240 |
+
# llm_engine_name=args.llm_engine_name,
|
| 241 |
+
# toolbox_metadata=initializer.toolbox_metadata,
|
| 242 |
+
# available_tools=initializer.available_tools
|
| 243 |
+
# )
|
| 244 |
+
|
| 245 |
+
# # Instantiate Memory
|
| 246 |
+
# memory = Memory()
|
| 247 |
+
|
| 248 |
+
# # Instantiate Executor
|
| 249 |
+
# executor = Executor(
|
| 250 |
+
# llm_engine_name=args.llm_engine_name,
|
| 251 |
+
# root_cache_dir=args.root_cache_dir,
|
| 252 |
+
# enable_signal=False
|
| 253 |
+
# )
|
| 254 |
+
|
| 255 |
+
# # Instantiate Solver
|
| 256 |
+
# solver = Solver(
|
| 257 |
+
# planner=planner,
|
| 258 |
+
# memory=memory,
|
| 259 |
+
# executor=executor,
|
| 260 |
+
# task=args.task,
|
| 261 |
+
# task_description=args.task_description,
|
| 262 |
+
# output_types=args.output_types, # Add new parameter
|
| 263 |
+
# verbose=args.verbose,
|
| 264 |
+
# max_steps=args.max_steps,
|
| 265 |
+
# max_time=args.max_time,
|
| 266 |
+
# output_json_dir=args.output_json_dir,
|
| 267 |
+
# root_cache_dir=args.root_cache_dir
|
| 268 |
+
# )
|
| 269 |
+
|
| 270 |
+
# # Test Inputs
|
| 271 |
+
# # user_query = "How many balls are there in the image?"
|
| 272 |
+
# # user_image_path = "/home/sheng/toolbox-agent/mathvista_113.png" # Replace with your actual image path
|
| 273 |
+
|
| 274 |
+
# # # Load the image as a PIL object
|
| 275 |
+
# # user_image = Image.open(user_image_path).convert("RGB") # Ensure it's in RGB mode
|
| 276 |
+
|
| 277 |
+
# # print("\n=== Starting Problem Solving ===\n")
|
| 278 |
+
# # messages = []
|
| 279 |
+
# # for message_batch in solver.stream_solve_user_problem(user_query, user_image, messages):
|
| 280 |
+
# # for message in message_batch:
|
| 281 |
+
# # print(f"{message.role}: {message.content}")
|
| 282 |
+
|
| 283 |
+
# # messages = []
|
| 284 |
+
# # solver.stream_solve_user_problem(user_query, user_image, messages)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# # def solve_problem_stream(user_query, user_image):
|
| 288 |
+
# # messages = [] # Ensure it's a list of [role, content] pairs
|
| 289 |
+
|
| 290 |
+
# # for message_batch in solver.stream_solve_user_problem(user_query, user_image, messages):
|
| 291 |
+
# # yield message_batch # Stream messages correctly in tuple format
|
| 292 |
+
|
| 293 |
+
# # solve_problem_stream(user_query, user_image)
|
| 294 |
+
|
| 295 |
+
# # ========== Gradio Interface ==========
|
| 296 |
+
# with gr.Blocks() as demo:
|
| 297 |
+
# gr.Markdown("# π§ OctoTools AI Solver") # Title
|
| 298 |
+
|
| 299 |
+
# with gr.Row():
|
| 300 |
+
# user_query = gr.Textbox(label="Enter your query", placeholder="Type your question here...")
|
| 301 |
+
# user_image = gr.Image(type="pil", label="Upload an image") # Accepts multiple formats
|
| 302 |
+
|
| 303 |
+
# run_button = gr.Button("Run") # Run button
|
| 304 |
+
# chatbot_output = gr.Chatbot(label="Problem-Solving Output")
|
| 305 |
+
|
| 306 |
+
# # Link button click to function
|
| 307 |
+
# run_button.click(fn=solve_problem_gradio, inputs=[user_query, user_image], outputs=chatbot_output)
|
| 308 |
+
|
| 309 |
+
# # Launch the Gradio app
|
| 310 |
+
# demo.launch()
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# if __name__ == "__main__":
|
| 315 |
+
# args = parse_arguments()
|
| 316 |
+
# main(args)
|