File size: 8,943 Bytes
cba32bf
 
 
badebc5
 
cba32bf
 
 
 
9f9dc99
cba32bf
 
badebc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba32bf
 
 
 
 
 
 
badebc5
 
cba32bf
 
 
 
 
 
 
 
 
 
 
 
 
 
badebc5
cba32bf
 
 
 
 
 
 
 
 
badebc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba32bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
badebc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba32bf
 
 
 
 
 
 
badebc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bbc8b4
badebc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba32bf
badebc5
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
from huggingface_hub import InferenceClient
import gradio as gr
import random
import os
import subprocess

API_URL = "https://api-inference.huggingface.co/models/"

client = InferenceClient(
    "mistralai/Mixtral-8x7B-Instruct-v0.1" 
)

def format_prompt(message, history, agent_role):
    """Formats the prompt with the selected agent role and conversation history."""
    prompt = f"""
You are an expert {agent_role} 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.
"""

    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

def generate(prompt, history, agent_role, temperature=0.9, max_new_tokens=2048, top_p=0.95, repetition_penalty=1.0):
    """Generates a response using the selected agent role 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_role)

    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

def change_agent(agent_name):
    """Updates the selected agent role."""
    global selected_agent
    selected_agent = agent_name
    return f"Agent switched to: {agent_name}"

# Define the available agent roles
agent_roles = [
    "Web Developer",
    "Prompt Engineer",
    "Python Code Developer",
    "Hugging Face Hub Expert",
    "AI-Powered Code Assistant"  # Agent 3
]

# Initialize the selected agent
selected_agent = agent_roles[0]

additional_inputs=[
    gr.Slider(
        label="Temperatur",
        value=0.9,
        minimum=0.0,
        maximum=1.0,
        step=0.05,
        interactive=True,
        info="Höhere Werte erzeugen vielfältigere Ausgaben",
    ),
    gr.Slider(
        label="Maximale neue Tokens",
        value=2048,
        minimum=64,
        maximum=4096,
        step=64,
        interactive=True,
        info="Die maximale Anzahl neuer Tokens",
    ),
    gr.Slider(
        label="Top-p (Nukleus-Sampling)",
        value=0.90,
        minimum=0.0,
        maximum=1,
        step=0.05,
        interactive=True,
        info="Höhere Werte probieren mehr niedrigwahrscheinliche Tokens aus",
    ),
    gr.Slider(
        label="Wiederholungsstrafe",
        value=1.2,
        minimum=1.0,
        maximum=2.0,
        step=0.05,
        interactive=True,
        info="Bestrafe wiederholte Tokens",
    )
]

# Define the initial prompt for the selected agent
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.
"""

customCSS = """
#component-7 { # dies ist die Standardelement-ID des Chatkomponenten
  height: 1600px; # passen Sie die Höhe nach Bedarf an
  flex-grow: 4;
}
"""

def run_code(code):
    """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}"

def chat_interface(message, history, agent_role, temperature=0.9, max_new_tokens=2048, top_p=0.95, repetition_penalty=1.0):
    """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
        response = generate(message, history, agent_role, temperature, max_new_tokens, top_p, repetition_penalty)
        return (message, response)

with gr.Blocks(theme='ParityError/Interstellar') as demo:
    gr.Dropdown(
        label="Agent auswählen",
        choices=agent_roles,
        value=selected_agent,
        interactive=True,
        show_label=True,
        type="index",
        allow_custom_value=False,
    ).change(change_agent, inputs=[gr.Dropdown], outputs=[gr.Textbox])
    
    with gr.Row():
        gr.ChatInterface(
            chat_interface,
            additional_inputs=[
                gr.Slider(
                    label="Temperatur",
                    value=0.9,
                    minimum=0.0,
                    maximum=1.0,
                    step=0.05,
                    interactive=True,
                    info="Höhere Werte erzeugen vielfältigere Ausgaben",
                ),
                gr.Slider(
                    label="Maximale neue Tokens",
                    value=2048,
                    minimum=64,
                    maximum=4096,
                    step=64,
                    interactive=True,
                    info="Die maximale Anzahl neuer Tokens",
                ),
                gr.Slider(
                    label="Top-p (Nukleus-Sampling)",
                    value=0.90,
                    minimum=0.0,
                    maximum=1,
                    step=0.05,
                    interactive=True,
                    info="Höhere Werte probieren mehr niedrigwahrscheinliche Tokens aus",
                ),
                gr.Slider(
                    label="Wiederholungsstrafe",
                    value=1.2,
                    minimum=1.0,
                    maximum=2.0,
                    step=0.05,
                    interactive=True,
                    info="Bestrafe wiederholte Tokens",
                )
            ],
        )

    demo.queue().launch(debug=True)