pull/709/head
harshalmore31 4 months ago
parent fdcf91e83a
commit 00256555b4

@ -0,0 +1,47 @@
{
"Agent_Data_Extractor": {
"system_prompt": "You are a data extraction agent. Your primary role is to retrieve and organize relevant data from diverse sources accurately and efficiently. You specialize in parsing structured and unstructured data, ensuring its integrity and usability for analysis or reporting."
},
"Agent_Summarizer": {
"system_prompt": "You are a summarization agent. Your main function is to condense large volumes of information into concise, clear, and meaningful summaries. You ensure that the key points are captured without losing the essence or context of the original content."
},
"Agent_Onboarding_Agent": {
"system_prompt": "You are an onboarding agent. Your focus is to guide new users through processes, systems, or platforms seamlessly. You provide step-by-step assistance, clarify complex concepts, and ensure users feel confident and well-informed throughout the onboarding journey."
},
"Agent_Finance_Agent": {
"system_prompt": "You are a seasoned finance analyst AI assistant. Your primary goal is to compose comprehensive, astute, impartial, and methodically arranged financial reports based on provided data and trends."
},
"Agent_Travel_Agent": {
"system_prompt": "You are a world-travelled AI tour guide assistant. Your main purpose is to draft engaging, insightful, unbiased, and well-structured travel reports on given locations, including history, attractions, and cultural insights."
},
"Agent_Academic_Research_Agent": {
"system_prompt": "You are an AI academic research assistant. Your primary responsibility is to create thorough, academically rigorous, unbiased, and systematically organized reports on a given research topic, following the standards of scholarly work."
},
"Agent_Default_Agent": {
"system_prompt": "You are an AI critical thinker research assistant. Your sole purpose is to write well-written, critically acclaimed, objective and structured reports on given text."
},
"Agent_Health_Security_Agent": {
"system_prompt": "Conduct a thorough analysis of the factory's working conditions focusing on health and safety standards. Examine the cleanliness of the workspace, the adequacy of ventilation systems, the appropriate spacing between workstations, and the availability and use of personal protective equipment by workers. Evaluate the compliance of these aspects with health and safety regulations. Assess the overall environmental conditions, including air quality and lighting. Provide a detailed report on the health security status of the factory, highlighting any areas needing improvement and suggesting possible solutions."
},
"Agent_Quality_Control_Agent": {
"system_prompt": "Scrutinize the quality of products manufactured in the factory. Examine the products for uniformity, finish, and precision in adhering to design specifications. Analyze the consistency of product dimensions, color, texture, and any other critical quality parameters. Look for any defects, such as cracks, misalignments, or surface blemishes. Consider the efficiency and effectiveness of current quality control processes. Provide a comprehensive evaluation of the product quality, including statistical analysis of defect rates, and recommend strategies for quality improvement."
},
"Agent_Productivity_Agent": {
"system_prompt": "Evaluate the factory's overall productivity by analyzing workflow efficiency, machine utilization, and employee engagement. Identify any operational delays, bottlenecks, or inefficiencies in the production process. Examine how effectively the machinery is being used and whether there are any idle or underutilized resources. Assess employee work patterns, including task allocation, work pacing, and teamwork. Look for signs of overwork or underutilization of human resources. Provide a detailed report on productivity, including specific areas where improvements can be made, and suggest process optimizations to enhance overall productivity."
},
"Agent_Safety_Agent": {
"system_prompt": "Inspect the factory's adherence to safety standards and protocols. Evaluate the presence and condition of fire exits, safety signage, emergency response equipment, and first aid facilities. Check for clear and unobstructed access to emergency exits. Assess the visibility and clarity of safety signs and instructions. Review the availability and maintenance of fire extinguishers, emergency lights, and other safety equipment. Ensure compliance with workplace safety regulations. Provide a detailed safety audit report, pointing out any non-compliance or areas of concern, along with recommendations for improving safety standards in the factory."
},
"Agent_Security_Agent": {
"system_prompt": "Assess the factory's security measures and systems. Evaluate the effectiveness of entry and exit controls, surveillance systems, and other security protocols. Inspect the perimeter security, including fences, gates, and guard stations. Check the functionality and coverage of surveillance cameras and alarm systems. Analyze access control measures for both personnel and vehicles. Identify potential security vulnerabilities or breaches. Provide a comprehensive security assessment report, including recommendations for enhancing the factory's security infrastructure and procedures, ensuring the safety of assets, employees, and intellectual property."
},
"Agent_Sustainability_Agent": {
"system_prompt": "Examine the factory's sustainability practices with a focus on waste management, energy usage, and implementation of eco-friendly processes. Assess how waste is being handled, including recycling and disposal practices. Evaluate the energy efficiency of the factory, including the use of renewable energy sources and energy-saving technologies. Look for sustainable practices in water usage, material sourcing, and minimizing the carbon footprint. Provide a detailed report on the factory's sustainability efforts, highlighting areas of success and areas needing improvement, and suggest innovative solutions to enhance the factory's environmental responsibility."
},
"Agent_Efficiency_Agent": {
"system_prompt": "Analyze the efficiency of the factory's manufacturing process, focusing on the layout, logistics, and level of automation. Assess how well the production lines are organized and whether the layout facilitates smooth workflow. Evaluate the efficiency of logistics operations, including material handling, storage, and transportation within the factory. Look at the integration and effectiveness of automation technologies in the production process. Identify any areas causing delays or inefficiencies. Provide an in-depth analysis of manufacturing efficiency, offering actionable insights and recommendations for optimizing the layout, logistics, and automation to improve overall operational efficiency."
},
"Agent_Hello": {
"system_prompt": "print(\"Hello_World\")\n\nKonichiwa"
}
}

@ -33,9 +33,9 @@ def load_prompts_from_json() -> Dict[str, str]:
if not os.path.exists(PROMPT_JSON_PATH): if not os.path.exists(PROMPT_JSON_PATH):
# Load default prompts # Load default prompts
return { return {
"agent.data_extractor": "You are a data extraction agent...", "agent.Agent_Data_Extractor": "You are a data extraction agent...",
"agent.summarizer": "You are a summarization agent...", "agent.Agent_Summarizer": "You are a summarization agent...",
"agent.onboarding_agent": "You are an onboarding agent..." "agent.Agent_Onboarding_Agent": "You are an onboarding agent..."
} }
with open(PROMPT_JSON_PATH, 'r', encoding='utf-8') as f: with open(PROMPT_JSON_PATH, 'r', encoding='utf-8') as f:
@ -44,17 +44,17 @@ def load_prompts_from_json() -> Dict[str, str]:
except json.JSONDecodeError: except json.JSONDecodeError:
# Load default prompts # Load default prompts
return { return {
"agent.data_extractor": "You are a data extraction agent...", "agent.Agent_Data_Extractor": "You are a data extraction agent...",
"agent.summarizer": "You are a summarization agent...", "agent.Agent_Summarizer": "You are a summarization agent...",
"agent.onboarding_agent": "You are an onboarding agent..." "agent.Agent_Onboarding_Agent": "You are an onboarding agent..."
} }
if not isinstance(data, dict): if not isinstance(data, dict):
# Load default prompts # Load default prompts
return { return {
"agent.data_extractor": "You are a data extraction agent...", "agent.Agent_Data_Extractor": "You are a data extraction agent...",
"agent.summarizer": "You are a summarization agent...", "agent.Agent_Summarizer": "You are a summarization agent...",
"agent.onboarding_agent": "You are an onboarding agent..." "agent.Agent_Onboarding_Agent": "You are an onboarding agent..."
} }
prompts = {} prompts = {}
@ -67,9 +67,9 @@ def load_prompts_from_json() -> Dict[str, str]:
if not prompts: if not prompts:
# Load default prompts # Load default prompts
return { return {
"agent.data_extractor": "You are a data extraction agent...", "agent.Agent_Data_Extractor": "You are a data extraction agent...",
"agent.summarizer": "You are a summarization agent...", "agent.Agent_Summarizer": "You are a summarization agent...",
"agent.onboarding_agent": "You are an onboarding agent..." "agent.Agent_Onboarding_Agent": "You are an onboarding agent..."
} }
return prompts return prompts
@ -77,14 +77,15 @@ def load_prompts_from_json() -> Dict[str, str]:
except Exception: except Exception:
# Load default prompts # Load default prompts
return { return {
"agent.data_extractor": "You are a data extraction agent...", "agent.Agent_Data_Extractor": "You are a data extraction agent...",
"agent.summarizer": "You are a summarization agent...", "agent.Agent_Summarizer": "You are a summarization agent...",
"agent.onboarding_agent": "You are an onboarding agent..." "agent.Agent_Onboarding_Agent": "You are an onboarding agent..."
} }
AGENT_PROMPTS = load_prompts_from_json() AGENT_PROMPTS = load_prompts_from_json()
def initialize_agents(dynamic_temp: float, agent_keys: List[str]) -> List[Agent]: def initialize_agents(dynamic_temp: float, agent_keys: List[str], model_name: str,
provider: str, api_key: str, temperature:float, max_tokens:int) -> List[Agent]:
agents = [] agents = []
seen_names = set() seen_names = set()
for agent_key in agent_keys: for agent_key in agent_keys:
@ -102,10 +103,18 @@ def initialize_agents(dynamic_temp: float, agent_keys: List[str]) -> List[Agent]
counter += 1 counter += 1
seen_names.add(agent_name) seen_names.add(agent_name)
llm = LiteLLM(
model_name=model_name,
system_prompt=agent_prompt,
temperature=temperature,
max_tokens = max_tokens,
)
agent = Agent( agent = Agent(
agent_name=f"Agent-{agent_name}", agent_name=f"Agent-{agent_name}",
system_prompt=agent_prompt, system_prompt=agent_prompt,
llm=model, llm=llm,
max_loops=1, max_loops=1,
autosave=True, autosave=True,
verbose=True, verbose=True,
@ -115,7 +124,7 @@ def initialize_agents(dynamic_temp: float, agent_keys: List[str]) -> List[Agent]
retry_attempts=1, retry_attempts=1,
context_length=200000, context_length=200000,
output_type="string", # here is the output type which is string output_type="string", # here is the output type which is string
temperature=dynamic_temp, # THIS LINE IS CHANGED temperature=dynamic_temp,
) )
agents.append(agent) agents.append(agent)
@ -773,6 +782,7 @@ def create_app():
with gr.Row(): with gr.Row():
# max tokens slider
max_tokens_slider = gr.Slider( max_tokens_slider = gr.Slider(
label="Max Tokens", label="Max Tokens",
minimum=100, minimum=100,
@ -821,7 +831,19 @@ def create_app():
- Use exact agent names from the prompts above - Use exact agent names from the prompts above
""" """
) )
# Create Agent Prompt Section
with gr.Accordion("Create Agent Prompt", open=False) as create_prompt_accordion:
with gr.Row():
with gr.Column():
new_agent_name_input = gr.Textbox(label="New Agent Name")
with gr.Column():
new_agent_prompt_input = gr.Textbox(label="New Agent Prompt", lines=3)
with gr.Row():
with gr.Column():
create_agent_button = gr.Button("Save New Prompt")
generate_agent_button = gr.Button("Generate_Final_p")
with gr.Column():
create_agent_status = gr.Textbox(label="Status", interactive=False)
# with gr.Row(): # with gr.Row():
@ -861,6 +883,8 @@ def create_app():
lines=10 lines=10
) )
def update_flow_agents(agent_keys): def update_flow_agents(agent_keys):
"""Update flow agents based on selected agent prompts.""" """Update flow agents based on selected agent prompts."""
if not agent_keys: if not agent_keys:
@ -875,6 +899,13 @@ def create_app():
flow = " -> ".join(selected_flow_agents) flow = " -> ".join(selected_flow_agents)
return flow return flow
def update_agent_dropdown():
"""Update agent dropdown when a new agent is added"""
global AGENT_PROMPTS
AGENT_PROMPTS = load_prompts_from_json()
available_prompts = list(AGENT_PROMPTS.keys()) if AGENT_PROMPTS else ["No agents available"]
return gr.update(choices = available_prompts, value = available_prompts[0] if available_prompts else None)
def update_ui_for_swarm_type(swarm_type): def update_ui_for_swarm_type(swarm_type):
"""Update UI components based on selected swarm type.""" """Update UI components based on selected swarm type."""
is_agent_rearrange = swarm_type == "AgentRearrange" is_agent_rearrange = swarm_type == "AgentRearrange"
@ -894,36 +925,107 @@ def create_app():
models = filtered_models.get(provider, []) models = filtered_models.get(provider, [])
return gr.update(choices=models, value=models[0] if models else None) return gr.update(choices=models, value=models[0] if models else None)
async def run_task_wrapper(task, max_loops, dynamic_temp, swarm_type, agent_prompt_selector, flow_text): def save_new_agent_prompt(agent_name, agent_prompt):
"""Saves a new agent prompt to the JSON file."""
try:
if not agent_name or not agent_prompt:
return "Error: Agent name and prompt cannot be empty."
if not agent_name.isalnum() and not "_" in agent_name:
return "Error : Agent name must be alphanumeric or underscore(_) "
if "agent."+agent_name in AGENT_PROMPTS:
return "Error : Agent name already exists"
with open(PROMPT_JSON_PATH, 'r+', encoding='utf-8') as f:
try:
data = json.load(f)
except json.JSONDecodeError:
data = {}
data[agent_name] = {"system_prompt": agent_prompt}
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()
return "New agent prompt saved successfully"
except Exception as e:
return f"Error saving agent prompt {str(e)}"
async def run_task_wrapper(task, max_loops, dynamic_temp, swarm_type, agent_prompt_selector, flow_text,
provider, model_name, api_key, temperature, max_tokens):
"""Execute the task and update the UI with progress.""" """Execute the task and update the UI with progress."""
try: try:
if not task: if not task:
yield "Please provide a task description.", "Error: Missing task" yield "Please provide a task description.", "Error: Missing task", ""
return return
if not agent_prompt_selector or len(agent_prompt_selector) == 0: if not agent_prompt_selector or len(agent_prompt_selector) == 0:
yield "Please select at least one agent.", "Error: No agents selected" yield "Please select at least one agent.", "Error: No agents selected", ""
return
if not provider:
yield "Please select a provider.", "Error: No provider selected", ""
return return
if not model_name:
yield "Please select a model.", "Error: No model selected", ""
return
if not api_key:
yield "Please enter an API Key", "Error: API Key is required", ""
return
# Update status # Update status
yield "Processing...", "Running task..." yield "Processing...", "Running task...", ""
# Prepare flow for AgentRearrange # Prepare flow for AgentRearrange
flow = None flow = None
if swarm_type == "AgentRearrange": if swarm_type == "AgentRearrange":
if not flow_text: if not flow_text:
yield "Please provide the agent flow configuration.", "Error: Flow not configured" yield "Please provide the agent flow configuration.", "Error: Flow not configured", ""
return return
flow = flow_text flow = flow_text
# Save API key to .env
env_path = find_dotenv()
if provider == "openai":
set_key(env_path, "OPENAI_API_KEY", api_key)
elif provider == "anthropic":
set_key(env_path, "ANTHROPIC_API_KEY", api_key)
elif provider == "cohere":
set_key(env_path, "COHERE_API_KEY", api_key)
elif provider == "gemini":
set_key(env_path, "GEMINI_API_KEY", api_key)
elif provider == "mistral":
set_key(env_path, "MISTRAL_API_KEY", api_key)
elif provider == "groq":
set_key(env_path, "GROQ_API_KEY", api_key)
elif provider == "nvidia_nim":
set_key(env_path, "NVIDIA_NIM_API_KEY", api_key)
elif provider == "huggingface":
set_key(env_path, "HUGGINGFACE_API_KEY", api_key)
elif provider == "perplexity":
set_key(env_path, "PERPLEXITY_API_KEY", api_key)
else:
yield f"Error: {provider} this provider is not present", f"Error: {provider} not supported", ""
return
# Execute task # Execute task
result, router, error = await execute_task( result, router, error = await execute_task(
task=task, task=task,
max_loops=max_loops, max_loops=max_loops,
dynamic_temp=dynamic_temp, # THIS LINE IS CHANGED dynamic_temp=dynamic_temp,
swarm_type=swarm_type, swarm_type=swarm_type,
agent_keys=agent_prompt_selector, agent_keys=agent_prompt_selector,
flow=flow flow=flow,
model_name=model_name,
provider=provider,
api_key=api_key,
temperature=temperature,
max_tokens = max_tokens,
) )
if error: if error:
@ -982,6 +1084,16 @@ def create_app():
inputs=[provider_dropdown], inputs=[provider_dropdown],
outputs=[model_dropdown] outputs=[model_dropdown]
) )
# Event for creating new agent prompts
create_agent_button.click(
fn=save_new_agent_prompt,
inputs=[new_agent_name_input, new_agent_prompt_input],
outputs=[create_agent_status]
).then(
fn=update_agent_dropdown,
inputs=None,
outputs=[agent_prompt_selector]
)
# Create event trigger # Create event trigger
# Create event trigger for run button # Create event trigger for run button

Loading…
Cancel
Save