File size: 8,438 Bytes
52b638f
5a0d86a
7f53c1a
 
5a0d86a
 
 
719e83e
 
 
 
 
 
7f53c1a
5a0d86a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f53c1a
5a0d86a
 
 
 
 
 
7f53c1a
5a0d86a
7f53c1a
5a0d86a
60f49cc
 
5a0d86a
 
7f53c1a
 
 
 
 
 
 
 
5a0d86a
7f53c1a
 
60f49cc
7f53c1a
 
 
 
 
 
 
 
 
 
5a0d86a
7f53c1a
 
5a0d86a
 
 
 
 
7f53c1a
 
 
 
 
60f49cc
5a0d86a
 
7f53c1a
 
 
5a0d86a
7f53c1a
 
 
 
 
5a0d86a
7f53c1a
 
60f49cc
 
7f53c1a
5a0d86a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f53c1a
 
 
 
 
5a0d86a
7f53c1a
 
 
 
 
5a0d86a
7f53c1a
5a0d86a
7f53c1a
5a0d86a
 
 
 
 
 
 
 
7f53c1a
 
5a0d86a
7f53c1a
5a0d86a
7f53c1a
 
 
 
 
 
 
 
 
 
 
5a0d86a
7f53c1a
 
 
5a0d86a
7f53c1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a0d86a
7f53c1a
 
 
 
 
 
 
 
5a0d86a
 
 
 
 
 
7f53c1a
 
 
 
 
 
52b638f
 
7f53c1a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import gradio as gr
from typing import Dict, List, Set
import os
import logging
import inspect
from huggingface_hub import login
from smolagents import ToolCollection, CodeAgent, Tool, HfApiModel
from dotenv import load_dotenv

#local setup (load token when not on spaces)
# load_dotenv(verbose=True)
# login(token=os.getenv('HF_TOKEN'))

# Configure logging
logging.basicConfig(level=logging.INFO)
logging.warning('Starting application...')

# Global variables
publishtoken = None
tool_Collections: dict[str, ToolCollection] = {}
loaded_tools: Set[Tool] = set()

# API keys for litellm providers
litellm_api_keys = {
    'xai': '',
    'HF': '',
    'grok': '',
    'anthropic': '',
    'openAI': '',
}

def all_tools_names() -> List[str]:
    """Return a list of all tool names from loaded collections."""
    all_tools = []
    for collection in tool_Collections.values():
        if isinstance(collection, ToolCollection):
            all_tools.extend(tool.name for tool in collection.tools)
        else:
            all_tools.extend(collection)
    return all_tools

def filter_tools(tools):
    """Filter out base tools from a list of tools."""
    if tools is None:
        logging.warning("Received None for tools, defaulting to an empty list.")
        tools = []

    base_tools_names = ['web search']
    return [tool for tool in tools if tool not in base_tools_names]

def load_collection_from_space(agent: CodeAgent, collection_slug: str) -> List[str]:
    """Load a collection of tools from a Hugging Face space."""
    if collection_slug not in tool_Collections:
        tool_collection = ToolCollection(
            collection_slug=collection_slug,
            trust_remote_code=True
        )

        tool_Collections[collection_slug] = [tool.name for tool in tool_collection.tools]

        for tool in tool_collection.tools:
            if agent.tools.get(tool.name) is None:
                agent.tools[tool.name] = tool
                loaded_tools.add(tool)
            else:
                agent.tools[tool.name] = tool

    return all_tools_names()

def createAgent() -> CodeAgent:
    """Create and return a CodeAgent instance."""
    agent = CodeAgent(
        tools=filter_tools(list(loaded_tools)),
        model=HfApiModel(),
        additional_authorized_imports=["smolagents", "subprocess", "typing", "os", "inspect", "open", "requests"],
        add_base_tools=True,
        planning_interval=None,
    )

    # Add base tools to the collection
    for tool in agent.tools:
        if tool not in loaded_tools:
            if "base tools" not in tool_Collections:
                tool_Collections["base tools"] = []
            tool_Collections["base tools"].append(tool)

    return agent

# Initialize the agent
agent = createAgent()

def dropdown_update_choices(choices):
    return gr.update(choices=choices, value=None)

def process_logs(agent):
    logs = ""
    if hasattr(agent, 'logs'):
        for entry in agent.logs:
            if hasattr(entry, 'llm_output'):
                logs += str(entry.llm_output) + "\n"
        return logs
    return "No logs available."

def get_tools():
    return [{"name": tool.name, "description": tool.description} for tool in agent.tools.values()]

def get_functions():
    return agent.python_executor.custom_tools

def get_function_code(selected_function_name):
    func = get_functions().get(selected_function_name)
    if func:
        try:
            return inspect.getsource(func)
        except OSError:
            return "Source code not available."
    return "Function not found."

def get_tool_description(selected_tool_name):
    
    tools = get_tools()
    print("Selected tool name:", selected_tool_name)
    print("Tools:",tools )
    for tool in tools:
        if tool["name"] == selected_tool_name:
            return tool["description"]
    return "No description available."

def refresh_ui_elements():
    print("Refreshing UI elements...")
    updated_tools = get_tools()
    updated_functions = get_functions()

    tool_names = [tool["name"] for tool in updated_tools]
    print("Tool names:", tool_names)
    function_names = list(updated_functions.keys())

    current_tool = tool_names[0] if tool_names else None
    current_function = function_names[0] if function_names else None

    tool_description = get_tool_description(current_tool)
    function_code = get_function_code(current_function) if current_function else ""

    tool_dropdown_update = dropdown_update_choices(tool_names)
    function_dropdown_update = dropdown_update_choices(function_names)

    return tool_dropdown_update, function_dropdown_update, tool_description, function_code

def update_agent(collection_slug: str):
    load_collection_from_space(agent, collection_slug=collection_slug)
    return refresh_ui_elements()

def respond(message, console_output, chat_history):
    try:
        bot_message = agent.run(message)
        new_console_output = process_logs(agent)

        chat_history.extend([
            {"role": "user", "content": message},
            {"role": "assistant", "content": bot_message}
        ])

        updated_console = console_output + f"\nQuery: {message}\nLogs: {new_console_output}"
        ui_updates = refresh_ui_elements()

        return "", updated_console, chat_history, *ui_updates
    except Exception as e:
        logging.error(f"Error in respond function: {e}")
        return f"An error occurred: {str(e)}", console_output, chat_history, None, None, None, None

with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column():
            with gr.Tab("Chat"):
                gr.Markdown("<center><h1>smolAgent Chat</h1></center>")
                chatbot = gr.Chatbot(type="messages")
                msg = gr.Textbox()
                clear = gr.ClearButton([msg, chatbot])

            with gr.Tab("Console"):
                outputbox = gr.Textbox(lines=25, scale=1, interactive=False)

            with gr.Tab("Config"):
                gr.Markdown("## Configure litellm API Keys")
                api_key_inputs = {
                    provider: gr.Textbox(
                        label=f'{provider} API Key',
                        placeholder='Enter key',
                        type='password',
                        value=litellm_api_keys[provider]
                    ) for provider in litellm_api_keys
                }

        with gr.Column():
            gr.Markdown("<center><h1>Tool Collection</h1></center>")
            tools = get_tools()

            tool_dropdown = gr.Dropdown(
                show_label=False,
                choices=[tool["name"] for tool in tools],
                value=tools[0]["name"] if tools else None,
                type="value",
                allow_custom_value=False,
                scale=3
            )

            description_textbox = gr.Textbox(
                label="Tool Description",
                value=get_tool_description(tool_dropdown.value),
                interactive=False,
            )

            slug = gr.Textbox(label="Collection Slug", value="Mightypeacock/agent-tools-6777c9699c231b7a1e87fa31")
            greet_btn = gr.Button("Load")


            gr.Markdown("<center><h2>Functions</h2></center>")
            functions = get_functions()
            function_dropdown = gr.Dropdown(
                label="Select Function",
                choices=list(functions.keys()),
                value=None if not functions.keys() else list(functions.keys())[0],
                type="value",
            )

            code = gr.Code(label="Function Code", language="python")

            tool_dropdown.change(
                fn=get_tool_description,
                inputs=[tool_dropdown],
                outputs=description_textbox,
            )

            function_dropdown.change(
                fn=get_function_code,
                inputs=function_dropdown,
                outputs=code,
            )
            greet_btn.click(
                fn=update_agent,
                inputs=slug,
                outputs=[tool_dropdown, function_dropdown, description_textbox, code],
                api_name="load_HF_Collection"
            )

    msg.submit(
        respond,
        inputs=[msg, outputbox, chatbot],
        outputs=[msg, outputbox, chatbot, tool_dropdown, function_dropdown, description_textbox, code]
    )

if __name__ == "__main__":
    demo.launch(show_error=True, debug=True)