|
|
|
|
|
import gradio as gr |
|
import os |
|
import importlib.util |
|
from typing import Any, Dict |
|
import requests |
|
|
|
|
|
def register_tool(tool_data): |
|
|
|
response = requests.post("https://huggingface.co/chat/tools/new", json=tool_data) |
|
return response.json() |
|
|
|
def create_tool(tool_name, tool_data): |
|
"""One tool to create them all. |
|
a AI model can wield this toolto create a new 'tool' script in the tools folder |
|
besides the values for the registration payload, |
|
the 'tool_data' should also be a string value 'tfn' which contains the code for the tool function script |
|
""" |
|
print("processing create_tool ") |
|
print(tool_name) |
|
print(dir(tool_data)) |
|
|
|
tool_payload = { |
|
"displayName": tool_data.get("displayName"), |
|
"description": tool_data.get("description"), |
|
"color": tool_data.get("color"), |
|
"icon": tool_data.get("icon"), |
|
"baseUrl": "K00B404/toolshed", |
|
"endpoint": "/router", |
|
"name": tool_data.get("name"), |
|
"inputs":tool_data.get("inputs"), |
|
"outputComponent": tool_data.get("outputComponent"), |
|
"outputComponentIdx": tool_data.get("outputComponentIdx"), |
|
"showOutput": tool_data.get("showOutput") |
|
} |
|
print(dir(tool_payload)) |
|
|
|
|
|
with open(f'./tools/{tool_data.get("name")}.py' 'w') as f: |
|
f.write(tool_data.get("tfn")) |
|
|
|
return register_tool(tool_payload) |
|
|
|
|
|
|
|
TOOLS_DIR = './tools' |
|
|
|
|
|
def load_methods_from_tools(): |
|
method_mapping = {} |
|
|
|
|
|
for filename in os.listdir(TOOLS_DIR): |
|
if filename.endswith('.py'): |
|
method_name = filename[:-3].lower() |
|
|
|
|
|
module_path = os.path.join(TOOLS_DIR, filename) |
|
spec = importlib.util.spec_from_file_location(method_name, module_path) |
|
module = importlib.util.module_from_spec(spec) |
|
spec.loader.exec_module(module) |
|
|
|
|
|
for attr in dir(module): |
|
if callable(getattr(module, attr)) and not attr.startswith("__"): |
|
method_mapping[method_name] = getattr(module, attr) |
|
|
|
return method_mapping |
|
|
|
|
|
method_mapping = load_methods_from_tools() |
|
|
|
|
|
def request_router(name: str, input_data: Dict[str, Any]) -> Dict[str, Any]: |
|
|
|
method = method_mapping.get(name) |
|
if method is None: |
|
return {"error": "Method not found"} |
|
|
|
|
|
try: |
|
output = method(input_data) |
|
return output |
|
except Exception as e: |
|
return {"error": str(e)} |
|
|
|
|
|
def launch_gradio_app(): |
|
with gr.Blocks() as demo: |
|
gr.Markdown("# Request Router API") |
|
with gr.Row(): |
|
name_input = gr.Textbox(label="Method Name") |
|
input_data_input = gr.Textbox(label="Input Data (JSON format)") |
|
output_output = gr.JSON(label="Output") |
|
|
|
submit_button = gr.Button("Submit") |
|
submit_button.click( |
|
fn=lambda name, input_data: request_router(name, eval(input_data)), |
|
inputs=[name_input, input_data_input], |
|
outputs=output_output |
|
) |
|
|
|
demo.launch() |
|
|
|
if __name__ == "__main__": |
|
launch_gradio_app() |