-
-
Notifications
You must be signed in to change notification settings - Fork 245
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Your Name
committed
Oct 12, 2024
1 parent
fb5427e
commit e22a367
Showing
13 changed files
with
511 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
File renamed without changes.
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.)" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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." | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,5 +17,5 @@ | |
"OPERATIONS_AGENT_PROMPT", | ||
"PRODUCT_AGENT_PROMPT", | ||
"DOCUMENTATION_WRITER_SOP", | ||
"Prompt" | ||
"Prompt", | ||
] |
Oops, something went wrong.