Skip to content

Commit

Permalink
[FEAT][CLU][Generate Prompts]
Browse files Browse the repository at this point in the history
  • Loading branch information
Your Name committed Oct 12, 2024
1 parent fb5427e commit e22a367
Show file tree
Hide file tree
Showing 13 changed files with 511 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,10 @@ nav:
- Understanding Agent Evaluation Mechanisms: "guides/agent_evals.md"
- Agent Glossary: "swarms/glossary.md"
- The Ultimate Technical Guide to the Swarms CLI; A Step-by-Step Developers Guide: "swarms/cli/cli_guide.md"
- Prompting Guide:
- The Essence of Enterprise-Grade Prompting: "swarms/prompts/essence.md"
- An Analysis on Prompting Strategies: "swarms/prompts/overview.md"
- Managing Prompts in Production: "swarms/prompts/main.md"
- Corporate:
- Hiring: "corporate/hiring.md"
- Swarms Goals & Milestone Tracking; A Vision for 2024 and Beyond: "corporate/2024_2025_goals.md"
170 changes: 170 additions & 0 deletions docs/swarms/prompts/essence.md

Large diffs are not rendered by default.

File renamed without changes.
File renamed without changes.
File renamed without changes.
17 changes: 17 additions & 0 deletions prompt_35fb57dc-df1c-481a-92b2-ac7c06e0b028.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"prompt_history": {
"id": "a0c46768e82e4397bea6b87d2ece7fc7",
"name": "openai-prompt-generator-optimizer-prompt",
"description": "Generate and or optimize existing prompts",
"content": "Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.\n\n# Guidelines\n\n- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.\n- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.\n- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!\n - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.\n - Conclusion, classifications, or results should ALWAYS appear last.\n- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.\n - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.\n- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.\n- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.\n- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.\n- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.\n- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)\n - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.\n - JSON should never be wrapped in code blocks (```) unless explicitly requested.\n\nThe final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no \"---\")\n\n[Concise instruction describing the task - this should be the first line in the prompt, no section header]\n\n[Additional details as needed.]\n\n[Optional sections with headings or bullet points for detailed steps.]\n\n# Steps [optional]\n\n[optional: a detailed breakdown of the steps necessary to accomplish the task]\n\n# Output Format\n\n[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]\n\n# Examples [optional]\n\n[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]\n[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]\n\n# Notes [optional]\n\n[optional: edge cases, details, and an area to call or repeat out specific important considerations]",
"created_at": "2024-10-11 15:59:18",
"last_modified_at": "2024-10-11 15:59:18",
"edit_count": 0,
"edit_history": [],
"autosave": true,
"autosave_folder": "prompts",
"parent_folder": "agent_workspace"
},
"timestamp": "2024-10-11 15:59:27",
"prompt": "Analyze healthcare insurance documents to extract key information such as policyholder details, coverage options, exclusions, and claim procedures.\n\n- Identify and summarize important sections such as terms and conditions, benefits, and limitations.\n- Highlight any ambiguous language or potential red flags.\n- Consider the relevance of the extracted information for policyholders or potential claimants.\n\n# Steps\n\n1. **Read the Document**: Begin by thoroughly reviewing the healthcare insurance document.\n2. **Extract Key Information**:\n - Policyholder details (e.g., name, contact information).\n - Coverage options (e.g., medical services covered, limits).\n - Exclusions (e.g., services not covered under the policy).\n - Claim procedures (e.g., how to file a claim).\n3. **Summarize Findings**: Create a concise summary of the key points identified.\n4. **Highlight Issues**: Note any unclear terms or potential concerns in the language used.\n\n# Output Format\n\nProvide the output in a structured format, ideally as a JSON object. The output should include:\n- A summary section that captures the key points.\n- A section for highlighting any ambiguous or concerning language.\n- A list format for the extracted key information.\n\nExample JSON structure:\n```json\n{\n \"summary\": \"Brief summary of the document.\",\n \"key_information\": {\n \"policyholder_details\": {\n \"name\": \"[Name]\",\n \"contact_information\": \"[Contact Info]\"\n },\n \"coverage_options\": \"[Coverage Options]\",\n \"exclusions\": \"[Exclusions]\",\n \"claim_procedures\": \"[Claim Procedures]\"\n },\n \"issues\": \"[Ambiguous Language or Concerns]\"\n}\n```\n\n# Examples\n\n**Example 1:**\n- **Input**: A healthcare insurance document detailing coverage for mental health services.\n- **Output**:\n```json\n{\n \"summary\": \"This document covers mental health services, including therapy and medication.\",\n \"key_information\": {\n \"policyholder_details\": {\n \"name\": \"John Doe\",\n \"contact_information\": \"[email protected]\"\n },\n \"coverage_options\": \"Up to 20 therapy sessions per year.\",\n \"exclusions\": \"No coverage for experimental treatments.\",\n \"claim_procedures\": \"Submit claims through the online portal.\"\n },\n \"issues\": \"The term 'experimental treatments' is not clearly defined.\"\n}\n```\n\n**Example 2:**\n- **Input**: A complex document with multiple policies and addendums.\n- **Output**:\n```json\n{\n \"summary\": \"This document outlines multiple insurance plans with various benefits and exclusions.\",\n \"key_information\": {\n \"policyholder_details\": {\n \"name\": \"Jane Smith\",\n \"contact_information\": \"[email protected]\"\n },\n \"coverage_options\": \"Comprehensive coverage including dental and vision.\",\n \"exclusions\": \"No coverage for pre-existing conditions.\",\n \"claim_procedures\": \"Claims must be filed within 30 days of service.\"\n },\n \"issues\": \"The definition of 'pre-existing conditions' is vague.\"\n}\n```\n(Note: Real examples should provide more detailed summaries and potentially longer lists of key information.)"
}
49 changes: 49 additions & 0 deletions prompt_generator_agent_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import os
from swarms import Agent
from swarm_models import OpenAIChat
from swarms.prompts.prompt_generator_optimizer import (
prompt_generator_sys_prompt,
)
from dotenv import load_dotenv
from swarms.agents.prompt_generator_agent import PromptGeneratorAgent

load_dotenv()

# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")

# Create an instance of the OpenAIChat class
model = OpenAIChat(
openai_api_key=api_key,
model_name="gpt-4o-mini",
temperature=0.1,
max_tokens=2000,
)

# Initialize the agent
agent = Agent(
agent_name="Prompt-Optimizer",
system_prompt=prompt_generator_sys_prompt.get_prompt(),
llm=model,
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="optimizer_agent.json",
user_name="swarms_corp",
retry_attempts=1,
context_length=200000,
return_step_meta=False,
# output_type="json",
output_type="string",
)


# Main Class
prompt_generator = PromptGeneratorAgent(agent)

# Run the agent
prompt_generator.run(
"Generate an amazing prompt for analyzing healthcare insurance documents"
)
2 changes: 2 additions & 0 deletions swarms/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from swarms.agents.create_agents_from_yaml import (
create_agents_from_yaml,
)
from swarms.agents.prompt_generator_agent import PromptGeneratorAgent


__all__ = [
Expand All @@ -29,4 +30,5 @@
"check_exit",
"check_end",
"create_agents_from_yaml",
"PromptGeneratorAgent",
]
84 changes: 84 additions & 0 deletions swarms/agents/cli_prompt_generator_func.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import os
from swarms import Agent
from swarm_models import OpenAIChat
from swarms.prompts.prompt_generator_optimizer import (
prompt_generator_sys_prompt,
)
from dotenv import load_dotenv
from swarms.agents.prompt_generator_agent import PromptGeneratorAgent
from yaml import dump

load_dotenv()


def generate_prompt(
num_loops: int = 1,
autosave: bool = True,
save_to_yaml: bool = False,
prompt: str = None,
save_format: str = "yaml",
) -> None:
"""
This function creates and runs a prompt generator agent with default settings for number of loops and autosave.
Args:
num_loops (int, optional): The number of loops to run the agent. Defaults to 1.
autosave (bool, optional): Whether to autosave the agent's state. Defaults to True.
save_to_yaml (bool, optional): Whether to save the agent's configuration to a YAML file. Defaults to False.
prompt (str): The prompt to generate.
save_format (str, optional): The format in which to save the generated prompt. Defaults to "yaml".
Returns:
None
"""
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")

# Create an instance of the OpenAIChat class
model = OpenAIChat(
openai_api_key=api_key,
model_name="gpt-4o-mini",
temperature=0.1,
max_tokens=2000,
)

# Initialize the agent
agent = Agent(
agent_name="Prompt-Optimizer",
system_prompt=prompt_generator_sys_prompt.get_prompt(),
llm=model,
max_loops=num_loops,
autosave=autosave,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="optimizer_agent.json",
user_name="swarms_corp",
retry_attempts=1,
context_length=200000,
return_step_meta=False,
output_type="string",
)

# Main Class
prompt_generator = PromptGeneratorAgent(agent)

# Run the agent
prompt_generator.run(prompt, save_format)

if save_to_yaml:
with open("agent_config.yaml", "w") as file:
dump(agent.config, file)


# # Example usage
# if __name__ == "__main__":
# try:
# create_and_run_agent(
# num_loops=1,
# autosave=True,
# save_to_yaml=True,
# prompt="Generate an amazing prompt for analyzing healthcare insurance documents",
# )
# except Exception as e:
# logger.error(f"An error occurred: {e}")
91 changes: 91 additions & 0 deletions swarms/agents/prompt_generator_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import json
import time
import uuid

import yaml
from dotenv import load_dotenv
from loguru import logger

from swarms.structs.agent import Agent
from swarms.prompts.prompt_generator_optimizer import (
prompt_generator_sys_prompt,
)

load_dotenv()


class PromptGeneratorAgent:
"""
A class representing a prompt generator agent.
Attributes:
----------
agent : Agent
The underlying agent instance.
"""

def __init__(self, agent: Agent):
"""
Initializes the PromptGeneratorAgent instance.
Args:
----
agent : Agent
The agent instance to be used for prompt generation.
"""
self.agent = agent

def run(self, task: str, format: str = "json") -> str:
"""
Runs the prompt generator agent with the given task description and saves the generated prompt with the given metadata in the specified format.
Args:
----
task : str
The task description to be used for prompt generation.
metadata : Dict[str, Any]
The metadata to be saved along with the prompt.
format : str, optional
The format in which the prompt should be saved (default is "json").
Returns:
-------
str
The generated prompt.
"""
prompt = self.agent.run(task)
self.save_prompt(prompt, format)
return prompt

def save_prompt(
self,
prompt: str,
format: str = "yaml",
):
"""
Saves the generated prompt with the given metadata in the specified format using the prompt generator sys prompt model dump.
Args:
----
prompt : str
The generated prompt to be saved.
metadata : Dict[str, Any]
The metadata to be saved along with the prompt.
format : str, optional
The format in which the prompt should be saved (default is "json").
"""
data = {
"prompt_history": prompt_generator_sys_prompt.model_dump(),
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"prompt": prompt,
}
if format == "json":
with open(f"prompt_{uuid.uuid4()}.json", "w") as f:
json.dump(data, f, indent=4)
elif format == "yaml":
with open(f"prompt_{uuid.uuid4()}.yaml", "w") as f:
yaml.dump(data, f)
else:
logger.error(
"Invalid format. Only 'json' and 'yaml' are supported."
)
36 changes: 36 additions & 0 deletions swarms/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from swarms.agents.create_agents_from_yaml import (
create_agents_from_yaml,
)
from swarms.agents.cli_prompt_generator_func import generate_prompt

console = Console()

Expand Down Expand Up @@ -42,6 +43,7 @@ def show_help():
[bold white]check-login[/bold white] : Checks if you're logged in and starts the cache
[bold white]read-docs[/bold white] : Redirects you to swarms cloud documentation!
[bold white]run-agents[/bold white] : Run your Agents from your specified yaml file. Specify the yaml file with path the `--yaml-file` arg. Example: `--yaml-file agents.yaml`
[bold white]generate-prompt[/bold white] : Generate a prompt through automated prompt engineering. Requires an OPENAI Key in your `.env` Example: --prompt "Generate a prompt for an agent to analyze legal docs"
For more details, visit: https://docs.swarms.world
"""
Expand Down Expand Up @@ -113,6 +115,7 @@ def main():
"get-api-key",
"check-login",
"run-agents",
"generate-prompt", # Added new command for generating prompts
],
help="Command to run",
)
Expand All @@ -122,6 +125,27 @@ def main():
default="agents.yaml",
help="Specify the YAML file for running agents",
)
parser.add_argument(
"--prompt",
type=str,
help="Specify the task for generating a prompt",
)
parser.add_argument(
"--num-loops",
type=int,
default=1,
help="Specify the number of loops for generating a prompt",
)
parser.add_argument(
"--autosave",
action="store_true",
help="Enable autosave for the prompt generator",
)
parser.add_argument(
"--save-to-yaml",
action="store_true",
help="Save the generated prompt to a YAML file",
)

args = parser.parse_args()

Expand All @@ -140,6 +164,18 @@ def main():
create_agents_from_yaml(
yaml_file=args.yaml_file, return_type="tasks"
)
elif args.command == "generate-prompt":
if args.prompt_task:
generate_prompt(
num_loops=args.num_loops,
autosave=args.autosave,
save_to_yaml=args.save_to_yaml,
prompt=args.prompt_task,
)
else:
console.print(
"[bold red]Please specify a task for generating a prompt using '--prompt-task'.[/bold red]"
)
else:
console.print(
"[bold red]Unknown command! Type 'help' for usage.[/bold red]"
Expand Down
2 changes: 1 addition & 1 deletion swarms/prompts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@
"OPERATIONS_AGENT_PROMPT",
"PRODUCT_AGENT_PROMPT",
"DOCUMENTATION_WRITER_SOP",
"Prompt"
"Prompt",
]
Loading

0 comments on commit e22a367

Please sign in to comment.