File size: 14,896 Bytes
cba32bf
 
 
badebc5
 
7d3b433
 
 
f059638
 
 
 
 
 
 
 
 
 
cba32bf
7128a54
 
cba32bf
7d3b433
7128a54
 
7d3b433
 
 
 
7128a54
 
7d3b433
cba32bf
7128a54
cba32bf
7d3b433
2d0ade1
 
 
 
 
 
badebc5
7128a54
cba32bf
7128a54
badebc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7128a54
 
cba32bf
7128a54
 
cba32bf
 
 
 
7128a54
 
7d3b433
 
2d0ade1
 
 
 
 
7d3b433
 
2d0ade1
 
 
7d3b433
 
badebc5
 
 
 
 
 
 
 
 
 
 
7d3b433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7128a54
badebc5
aa4b2b0
 
 
 
 
0791c0f
 
 
 
aa4b2b0
09466d2
7d3b433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7128a54
 
7d3b433
7128a54
51d064e
d201423
 
 
 
51d064e
7128a54
7d3b433
 
 
 
 
7128a54
7d3b433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7128a54
7d3b433
 
7128a54
7d3b433
 
 
f059638
 
7d3b433
 
 
 
 
 
 
 
 
 
 
 
7128a54
51d064e
7d3b433
 
 
 
 
 
 
7128a54
7d3b433
 
 
 
51d064e
7d3b433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7128a54
7d3b433
 
 
 
 
 
f059638
 
 
7128a54
7d3b433
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
from huggingface_hub import InferenceClient
import gradio as gr
import random
import os
import subprocess
import threading
import time
import shutil
from typing import Dict, Tuple, List
import json
from rich import print as rprint
from rich.panel import Panel
from rich.progress import track
from rich.table import Table
from rich.prompt import Prompt, Confirm
from rich.markdown import Markdown
from rich.traceback import install
install()  # Enable rich tracebacks for easier debugging

# --- Constants ---

API_URL = "https://api-inference.huggingface.co/models/"
MODEL_NAME = "mistralai/Mixtral-8x7B-Instruct-v0.1"  # Replace with your desired model

# Chat Interface Parameters
DEFAULT_TEMPERATURE = 0.9
DEFAULT_MAX_NEW_TOKENS = 2048
DEFAULT_TOP_P = 0.95
DEFAULT_REPETITION_PENALTY = 1.2

# Local Server
LOCAL_HOST_PORT = 7860

# --- Agent Roles ---

agent_roles: Dict[str, Dict[str, bool]] = {
    "Web Developer": {"description": "A master of front-end and back-end web development.", "active": False},
    "Prompt Engineer": {"description": "An expert in crafting effective prompts for AI models.", "active": False},
    "Python Code Developer": {"description": "A skilled Python programmer who can write clean and efficient code.", "active": False},
    "Hugging Face Hub Expert": {"description": "A specialist in navigating and utilizing the Hugging Face Hub.", "active": False},
    "AI-Powered Code Assistant": {"description": "An AI assistant that can help with coding tasks and provide code snippets.", "active": False},
}

# --- Initial Prompt ---

selected_agent = list(agent_roles.keys())[0]
initial_prompt = f"""
You are an expert {selected_agent} who responds with complete program coding to client requests. 
Using available tools, please explain the researched information.
Please don't answer based solely on what you already know. Always perform a search before providing a response.
In special cases, such as when the user specifies a page to read, there's no need to search.
Please read the provided page and answer the user's question accordingly.
If you find that there's not much information just by looking at the search results page, consider these two options and try them out:
- Try clicking on the links of the search results to access and read the content of each page.
- Change your search query and perform a new search.
Users are extremely busy and not as free as you are.
Therefore, to save the user's effort, please provide direct answers.
BAD ANSWER EXAMPLE
- Please refer to these pages.
- You can write code referring these pages.
- Following page will be helpful.
GOOD ANSWER EXAMPLE
- This is the complete code:  -- complete code here --
- The answer of you question is -- answer here --
Please make sure to list the URLs of the pages you referenced at the end of your answer. (This will allow users to verify your response.)
Please make sure to answer in the language used by the user. If the user asks in Japanese, please answer in Japanese. If the user asks in Spanish, please answer in Spanish.
But, you can go ahead and search in English, especially for programming-related questions. PLEASE MAKE SURE TO ALWAYS SEARCH IN ENGLISH FOR THOSE.
"""

# --- Custom CSS ---

customCSS = """
#component-7 { 
  height: 1600px; 
  flex-grow: 4;
}
"""

# --- Functions ---

# Function to toggle the active state of an agent
def toggle_agent(agent_name: str) -> str:
    """Toggles the active state of an agent."""
    global agent_roles
    agent_roles[agent_name]["active"] = not agent_roles[agent_name]["active"]
    return f"{agent_name} is now {'active' if agent_roles[agent_name]['active'] else 'inactive'}"

# Function to get the active agent cluster
def get_agent_cluster() -> Dict[str, bool]:
    """Returns a dictionary of active agents."""
    return {agent: agent_roles[agent]["active"] for agent in agent_roles}

# Function to execute code
def run_code(code: str) -> str:
    """Executes the provided code and returns the output."""
    try:
        output = subprocess.check_output(
            ['python', '-c', code],
            stderr=subprocess.STDOUT,
            universal_newlines=True,
        )
        return output
    except subprocess.CalledProcessError as e:
        return f"Error: {e.output}"

# Function to format the prompt
def format_prompt(message: str, history: list[Tuple[str, str]], agent_roles: list[str]) -> str:
    """Formats the prompt with the selected agent roles and conversation history."""
    prompt = f"""
You are an expert agent cluster, consisting of {', '.join(agent_roles)}. 
Respond with complete program coding to client requests. 
Using available tools, please explain the researched information.
Please don't answer based solely on what you already know. Always perform a search before providing a response.
In special cases, such as when the user specifies a page to read, there's no need to search.
Please read the provided page and answer the user's question accordingly.
If you find that there's not much information just by looking at the search results page, consider these two options and try them out:
- Try clicking on the links of the search results to access and read the content of each page.
- Change your search query and perform a new search.
Users are extremely busy and not as free as you are.
Therefore, to save the user's effort, please provide direct answers.
BAD ANSWER EXAMPLE
- Please refer to these pages.
- You can write code referring these pages.
- Following page will be helpful.
GOOD ANSWER EXAMPLE
- This is the complete code:  -- complete code here --
- The answer of you question is -- answer here --
Please make sure to list the URLs of the pages you referenced at the end of your answer. (This will allow users to verify your response.)
Please make sure to answer in the language used by the user. If the user asks in Japanese, please answer in Japanese. If the user asks in Spanish, please answer in Spanish.
But, you can go ahead and search in English, especially for programming-related questions. PLEASE MAKE SURE TO ALWAYS SEARCH IN ENGLISH FOR THOSE.
"""

    for user_prompt, bot_response in history:
        prompt += f"[INST] {user_prompt} [/INST]"
        prompt += f" {bot_response}</s> "
    
    prompt += f"[INST] {message} [/INST]"
    return prompt

# Function to generate a response
def generate(prompt: str, history: list[Tuple[str, str]], agent_roles: list[str], temperature: float = DEFAULT_TEMPERATURE, max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS, top_p: float = DEFAULT_TOP_P, repetition_penalty: float = DEFAULT_REPETITION_PENALTY) -> str:
    """Generates a response using the selected agent roles and parameters."""
    temperature = float(temperature)
    if temperature < 1e-2:
        temperature = 1e-2
    top_p = float(top_p)

    generate_kwargs = dict(
        temperature=temperature,
        max_new_tokens=max_new_tokens,
        top_p=top_p,
        repetition_penalty=repetition_penalty,
        do_sample=True,
        seed=random.randint(0, 10**7),
    )

    formatted_prompt = format_prompt(prompt, history, agent_roles)

    stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
    output = ""

    for response in stream:
        output += response.token.text
        yield output
    return output

# Function to handle user input and generate responses
def chat_interface(message: str, history: list[Tuple[str, str]], agent_cluster: Dict[str, bool], temperature: float, max_new_tokens: int, top_p: float, repetition_penalty: float) -> Tuple[str, str]:
    """Handles user input and generates responses."""
    if message.startswith("python"): 
        # User entered code, execute it 
        code = message[9:-3] 
        output = run_code(code) 
        return (message, output) 
    else:
        # User entered a normal message, generate a response
        active_agents = [agent for agent, is_active in agent_cluster.items() if is_active]
        response = generate(message, history, active_agents, temperature, max_new_tokens, top_p, repetition_penalty)
        return (message, response)

# Function to create a new web app instance
def create_web_app(app_name: str, code: str) -> None:
    """Creates a new web app instance with the given name and code."""
    # Create a new directory for the app
    os.makedirs(app_name, exist_ok=True)

    # Create the app.py file
    with open(os.path.join(app_name, 'app.py'), 'w') as f:
        f.write(code)

    # Create the requirements.txt file
    with open(os.path.join(app_name, 'requirements.txt'), 'w') as f:
        f.write("gradio\nhuggingface_hub")

    # Print a success message
    print(f"Web app '{app_name}' created successfully!")

# Function to handle the "Create Web App" button click
def create_web_app_button_click(code: str) -> str:
    """Handles the "Create Web App" button click."""
    # Get the app name from the user
    app_name = gr.Textbox.get().strip()

    # Validate the app name
    if not app_name:
        return "Please enter a valid app name."

    # Create the web app instance
    create_web_app(app_name, code)

    # Return a success message
    return f"Web app '{app_name}' created successfully!"

# Function to handle the "Deploy" button click
def deploy_button_click(app_name: str, code: str) -> str:
    """Handles the "Deploy" button click."""
    # Get the app name from the user
    app_name = gr.Textbox.get().strip()

    # Validate the app name
    if not app_name:
        return "Please enter a valid app name."

    # Deploy the web app instance
    # ... (Implement deployment logic here)

    # Return a success message
    return f"Web app '{app_name}' deployed successfully!"

# Function to handle the "Local Host" button click
def local_host_button_click(app_name: str, code: str) -> str:
    """Handles the "Local Host" button click."""
    # Get the app name from the user
    app_name = gr.Textbox.get().strip()

    # Validate the app name
    if not app_name:
        return "Please enter a valid app name."

    # Start the local server
    os.chdir(app_name)
    subprocess.Popen(['gradio', 'run', 'app.py', '--share', '--server_port', str(LOCAL_HOST_PORT)])

    # Return a success message
    return f"Web app '{app_name}' running locally on port {LOCAL_HOST_PORT}!"

# Function to handle the "Ship" button click
def ship_button_click(app_name: str, code: str) -> str:
    """Handles the "Ship" button click."""
    # Get the app name from the user
    app_name = gr.Textbox.get().strip()

    # Validate the app name
    if not app_name:
        return "Please enter a valid app name."

    # Ship the web app instance
    # ... (Implement shipping logic here)

    # Return a success message
    return f"Web app '{app_name}' shipped successfully!"

# --- Gradio Interface ---

with gr.Blocks(theme='ParityError/Interstellar') as demo:
    # --- Agent Selection ---
    with gr.Row():
        for agent_name, agent_data in agent_roles.items():
            button = gr.Button(agent_name, variant="secondary")
            textbox = gr.Textbox(agent_data["description"], interactive=False)
            button.click(toggle_agent, inputs=[button], outputs=[textbox])

    # --- Chat Interface ---
    with gr.Row():
        chatbot = gr.Chatbot()
        chat_interface_input = gr.Textbox(label="Enter your message", placeholder="Ask me anything!")
        chat_interface_output = gr.Textbox(label="Response", interactive=False)

        # Parameters
        temperature_slider = gr.Slider(
            label="Temperature",
            value=DEFAULT_TEMPERATURE,
            minimum=0.0,
            maximum=1.0,
            step=0.05,
            interactive=True,
            info="Higher values generate more diverse outputs",
        )
        max_new_tokens_slider = gr.Slider(
            label="Maximum New Tokens",
            value=DEFAULT_MAX_NEW_TOKENS,
            minimum=64,
            maximum=4096,
            step=64,
            interactive=True,
            info="The maximum number of new tokens",
        )
        top_p_slider = gr.Slider(
            label="Top-p (Nucleus Sampling)",
            value=DEFAULT_TOP_P,
            minimum=0.0,
            maximum=1,
            step=0.05,
            interactive=True,
            info="Higher values sample more low-probability tokens",
        )
        repetition_penalty_slider = gr.Slider(
            label="Repetition Penalty",
            value=DEFAULT_REPETITION_PENALTY,
            minimum=1.0,
            maximum=2.0,
            step=0.05,
            interactive=True,
            info="Penalize repeated tokens",
        )

        # Submit Button
        submit_button = gr.Button("Submit")

        # Chat Interface Logic
        submit_button.click(
            chat_interface,
            inputs=[
                chat_interface_input,
                chatbot,
                get_agent_cluster,
                temperature_slider,
                max_new_tokens_slider,
                top_p_slider,
                repetition_penalty_slider,
            ],
            outputs=[
                chatbot,
                chat_interface_output,
            ],
        )

    # --- Web App Creation ---
    with gr.Row():
        app_name_input = gr.Textbox(label="App Name", placeholder="Enter your app name")
        code_output = gr.Textbox(label="Code", interactive=False)
        create_web_app_button = gr.Button("Create Web App")
        deploy_button = gr.Button("Deploy")
        local_host_button = gr.Button("Local Host")
        ship_button = gr.Button("Ship")

        # Web App Creation Logic
        create_web_app_button.click(
            create_web_app_button_click,
            inputs=[code_output],
            outputs=[gr.Textbox(label="Status", interactive=False)],
        )

        # Deploy the web app
        deploy_button.click(
            deploy_button_click,
            inputs=[app_name_input, code_output],
            outputs=[gr.Textbox(label="Status", interactive=False)],
        )

        # Local host the web app
        local_host_button.click(
            local_host_button_click,
            inputs=[app_name_input, code_output],
            outputs=[gr.Textbox(label="Status", interactive=False)],
        )

        # Ship the web app
        ship_button.click(
            ship_button_click,
            inputs=[app_name_input, code_output],
            outputs=[gr.Textbox(label="Status", interactive=False)],
        )

    # --- Connect Chat Output to Code Output ---
    chat_interface_output.change(
        lambda x: x,
        inputs=[chat_interface_output],
        outputs=[code_output],
    )

    # --- Initialize Hugging Face Client ---
    client = InferenceClient(repo_id=MODEL_NAME, token=os.environ.get("HF_TOKEN"))

    # --- Launch Gradio ---
    demo.queue().launch(debug=True)