Spaces:
Runtime error
Runtime error
File size: 9,179 Bytes
cba32bf badebc5 cba32bf 9f9dc99 cba32bf 2d0ade1 badebc5 2d0ade1 badebc5 cba32bf 2d0ade1 cba32bf 2d0ade1 cba32bf badebc5 2d0ade1 badebc5 2d0ade1 cba32bf badebc5 cba32bf 2d0ade1 badebc5 2d0ade1 badebc5 aa4b2b0 0791c0f aa4b2b0 09466d2 aa4b2b0 51d064e d201423 51d064e 09466d2 51d064e 09466d2 51d064e 2d0ade1 |
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 |
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_roles):
"""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
def generate(prompt, history, agent_roles, temperature=0.9, max_new_tokens=2048, top_p=0.95, repetition_penalty=1.0):
"""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
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": {"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},
}
# Initialize the selected agent
selected_agent = list(agent_roles.keys())[0]
# 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 toggle_agent(agent_name):
"""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'}"
def get_agent_cluster():
"""Returns a dictionary of active agents."""
return {agent: agent_roles[agent]["active"] for agent in agent_roles}
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_cluster, 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
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)
with gr.Blocks(theme='ParityError/Interstellar') as demo:
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])
with gr.Row():
gr.ChatInterface(
fn=chat_interface,
chatbot=gr.Chatbot(), # Asegúrate de crear una instancia de Chatbot si es necesario
additional_inputs=[
gr.Slider(
label="Temperature",
value=0.9,
minimum=0.0,
maximum=1.0,
step=0.05,
interactive=True,
info="Higher values generate more diverse outputs",
),
gr.Slider(
label="Maximum New Tokens",
value=2048,
minimum=64,
maximum=4096,
step=64,
interactive=True,
info="The maximum number of new tokens",
),
gr.Slider(
label="Top-p (Nucleus Sampling)",
value=0.90,
minimum=0.0,
maximum=1,
step=0.05,
interactive=True,
info="Higher values sample more low-probability tokens",
),
gr.Slider(
label="Repetition Penalty",
value=1.2,
minimum=1.0,
maximum=2.0,
step=0.05,
interactive=True,
info="Penalize repeated tokens",
)
]
)
demo.queue().launch(debug=True) |