main 3b8d87c381c4 cached
10 files
43.1 KB
9.7k tokens
17 symbols
1 requests
Download .txt
Repository: marshmellow77/automated-prompt-engineering-from-scratch
Branch: main
Commit: 3b8d87c381c4
Files: 10
Total size: 43.1 KB

Directory structure:
gitextract_gl_wp18s/

├── .gitignore
├── 01_data_prep.py
├── 02_baseline.py
├── 03_ape.py
├── LICENSE
├── README.md
├── metaprompt_template.txt
├── prompt_evaluator.py
├── requirements.txt
└── review_prompt_template.txt

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
#   For a library or package, you might want to ignore these files since the code is
#   intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.
#Pipfile.lock

# poetry
#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
#   This is especially recommended for binary packages to ensure reproducibility, and is more
#   commonly ignored for libraries.
#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
#   in version control.
#   https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can
#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
#  and can be added to the global gitignore or merged into this file.  For a more nuclear
#  option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

runs/
bbh_navigate_cache/
bbh_nshapes_cache/

================================================
FILE: 01_data_prep.py
================================================
from datasets import load_dataset
import pandas as pd

dataset = load_dataset("lukaemon/bbh", "geometric_shapes", cache_dir="./bbh_nshapes_cache")
data = dataset["test"]
data = data.shuffle(seed=1234)

training = data.select(range(100))
df_train = pd.DataFrame({"question": training["input"], "answer": training["target"]})

test = data.select(range(100, 200))
df_test = pd.DataFrame({"question": test["input"], "answer": test["target"]})

df_train.to_csv("train.csv", index=False)
df_test.to_csv("test.csv", index=False)


================================================
FILE: 02_baseline.py
================================================
import asyncio
import pandas as pd
from prompt_evaluator import PromptEvaluator
from vertexai.generative_models import HarmBlockThreshold, HarmCategory


if __name__ == "__main__":
    df_train = pd.read_csv('test.csv')  # Load your training data

    target_model_name = "gemini-1.5-flash"
    target_model_config = {
        "temperature": 0, "max_output_tokens": 1000
    }
    review_model_name = "gemini-1.5-flash" 
    review_model_config = {
        "temperature": 0, "max_output_tokens": 10 
    }
    safety_settings = {
        HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
        HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
        HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
        HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
    }
    
    review_prompt_template_path = 'review_prompt_template.txt'  # Path to the review prompt text file

    evaluator = PromptEvaluator(
        df_train, target_model_name, target_model_config, review_model_name, review_model_config, safety_settings, review_prompt_template_path
    )
    
    prompt = input("Please enter the prompt for evaluation: ")
    asyncio.run(evaluator.main(prompt))

================================================
FILE: 03_ape.py
================================================
import asyncio
import os
import pandas as pd
from vertexai.generative_models import GenerativeModel, HarmBlockThreshold, HarmCategory
import re
import aiofiles
import datetime
import aioconsole
from prompt_evaluator import PromptEvaluator
import backoff


class APD:
    def __init__(self, num_prompts, starting_prompt, df_train, metaprompt_template_path, generation_model_name, generation_config, safety_settings, target_model_name, target_model_config, review_model_name, review_model_config, review_prompt_template_path):
        self.num_prompts = num_prompts
        self.starting_prompt = starting_prompt
        self.df_train = df_train
        self.metaprompt_template_path = metaprompt_template_path
        self.generation_model_name = generation_model_name
        self.generation_config = generation_config
        self.safety_settings = safety_settings

        # Initialize the generation model
        self.generation_model = GenerativeModel(self.generation_model_name)

        # Create the "runs" folder if it doesn't exist
        self.runs_folder = "runs"
        os.makedirs(self.runs_folder, exist_ok=True)
        
        self.run_folder = self.create_run_folder()
        self.prompt_history = os.path.join(self.run_folder, 'prompt_history.txt')
        self.prompt_history_chronlogical = os.path.join(self.run_folder, 'prompt_history_chronlogical.txt')
        
        # Initialize the PromptEvaluator
        self.prompt_evaluator = PromptEvaluator(
            df_train,
            target_model_name,
            target_model_config,
            review_model_name,
            review_model_config,
            safety_settings,
            review_prompt_template_path
        )

        self.user_feedback = ""
        self.best_prompt = starting_prompt
        self.best_accuracy = 0.0

    def create_run_folder(self):
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        run_folder = os.path.join(self.runs_folder, f'run_{timestamp}')  # Join with runs_folder
        os.makedirs(run_folder, exist_ok=True)
        return run_folder

    def create_prompt_subfolder(self, prompt_number):
        prompt_folder = os.path.join(self.run_folder, f'prompt_{prompt_number}')
        os.makedirs(prompt_folder, exist_ok=True)
        return prompt_folder

    def read_and_sort_prompt_accuracies(self, file_path):
        with open(file_path, 'r') as f:
            content = f.read()
        
        pattern = re.compile(r'<PROMPT>\n<PROMPT_TEXT>\n(.*?)\n</PROMPT_TEXT>\n<ACCURACY>\nAccuracy: ([0-9.]+)\n</ACCURACY>\n</PROMPT>', re.DOTALL)
        matches = pattern.findall(content)
        
        sorted_prompts = sorted(matches, key=lambda x: float(x[1]))  # Sort in ascending order
        return sorted_prompts

    def write_sorted_prompt_accuracies(self, file_path, sorted_prompts):
        sorted_prompts_string = ""
        with open(file_path, 'w') as f:
            for prompt, accuracy in sorted_prompts:
                s = f"<PROMPT>\n<PROMPT_TEXT>\n{prompt}\n</PROMPT_TEXT>\n<ACCURACY>\nAccuracy: {accuracy}\n</ACCURACY>\n</PROMPT>\n\n"
                f.write(s)
                sorted_prompts_string += s
                
        return sorted_prompts_string

    def update_metaprompt(self, file_path, metaprompt_template_path):
        sorted_prompts = self.read_and_sort_prompt_accuracies(file_path)
        sorted_prompts_string = self.write_sorted_prompt_accuracies(file_path, sorted_prompts)
                
        with open(metaprompt_template_path, 'r') as f:
            metaprompt_template = f.read()
        
        metaprompt = metaprompt_template.format(prompt_scores=sorted_prompts_string, human_feedback=self.user_feedback)
        
        return metaprompt

    @backoff.on_exception(backoff.expo, Exception, max_tries=5)
    async def generate_with_backoff(self, metaprompt):
        response = self.generation_model.generate_content(
            metaprompt,
            generation_config=self.generation_config,
            safety_settings=self.safety_settings,
            stream=False,
        )
        return response

    async def main(self):
        prompt_accuracies = []
        best_prompt = self.starting_prompt
        best_accuracy = 0.0

        for i in range(self.num_prompts + 1):
            await aioconsole.aprint("=" * 150)
            await aioconsole.aprint(f"Prompt number {i}")

            if i == 0:
                new_prompt = self.starting_prompt
                # Evaluate the starting prompt
                accuracy = await self.prompt_evaluator.evaluate_prompt(new_prompt)
                best_accuracy = accuracy
                prompt_accuracies.append((new_prompt, accuracy))
            else:
                metaprompt = self.update_metaprompt(self.prompt_history, self.metaprompt_template_path)
                
                try:
                    response = await self.generate_with_backoff(metaprompt)
                except Exception as e:
                    await aioconsole.aprint(f"Failed to generate content after retries: {e}")
                    continue
                
                await aioconsole.aprint("-" * 150)
                await aioconsole.aprint(response.text)
                await aioconsole.aprint("-" * 150)
                
                match = re.search(r'\[\[(.*?)\]\]', response.text, re.DOTALL)
                if match:
                    new_prompt = match.group(1)
                else:
                    await aioconsole.aprint("No new prompt found")
                    continue
            
            # Create a subfolder for the prompt
            prompt_folder = self.create_prompt_subfolder(i)

            # Save the prompt in a text file within the subfolder
            prompt_file_path = os.path.join(prompt_folder, 'prompt.txt')
            with open(prompt_file_path, 'w') as f:
                f.write(new_prompt)

            # Use the PromptEvaluator to evaluate the new prompt
            accuracy = await self.prompt_evaluator.evaluate_prompt(new_prompt)
            
            if i == 0:
                best_accuracy = starting_accuracy = accuracy
            
            prompt_accuracies.append((new_prompt, accuracy))
            await aioconsole.aprint("-" * 150)
            await aioconsole.aprint(f"Overall accuracy for prompt: {accuracy:.2f}")
            await aioconsole.aprint("=" * 150)

            # Update the best prompt if the current accuracy is higher
            if accuracy > best_accuracy:
                best_accuracy = accuracy
                best_prompt = new_prompt
            
            # Append to prompt_history.txt
            async with aiofiles.open(self.prompt_history, 'a') as f:
                await f.write(f"<PROMPT>\n<PROMPT_TEXT>\n{new_prompt}\n</PROMPT_TEXT>\n<ACCURACY>\nAccuracy: {accuracy:.2f}\n</ACCURACY>\n</PROMPT>\n\n")
        
            # Append to prompt_history_chronological.txt with prompt number
            async with aiofiles.open(self.prompt_history_chronlogical, 'a') as f:
                await f.write(f"Prompt number: {i}\nPrompt: {new_prompt}\nAccuracy: {accuracy:.2f}\n\n")
                await f.write("=" * 150 + "\n")
            
            # Save the evaluation results in a CSV file within the subfolder
            csv_file_path = os.path.join(prompt_folder, 'evaluation_results.csv')
            evaluation_results = {
                "question": self.df_train["question"],
                "answer": self.df_train["answer"],
                "model_response": self.df_train["model_response"],
                "is_correct": self.df_train["is_correct"]
            }
            evaluation_df = pd.DataFrame(evaluation_results)
            evaluation_df.to_csv(csv_file_path, index=False)

            # Read, sort, and write the updated prompt accuracies to prompt_history.txt
            sorted_prompts = self.read_and_sort_prompt_accuracies(self.prompt_history)
            self.write_sorted_prompt_accuracies(self.prompt_history, sorted_prompts)

        # Output the final best prompt and improvement in accuracy
        starting_accuracy = prompt_accuracies[0][1]  # Get the accuracy of the first prompt
        improvement = best_accuracy - starting_accuracy
        await aioconsole.aprint("=" * 150)
        await aioconsole.aprint(f"Final best prompt: {best_prompt}")
        await aioconsole.aprint(f"Accuracy of best prompt: {best_accuracy:.2f}")
        await aioconsole.aprint(f"Improvement in accuracy: {improvement:.2f}")

if __name__ == "__main__":
    num_prompts = 5
    starting_prompt = "Solve the given problem about geometric shapes. Think step by step."
    
    df_train = pd.read_csv('train.csv')  # Load your training data

    metaprompt_template_path = 'metaprompt_template.txt'
    generation_model_name = "gemini-1.5-pro"
    generation_config = {
        "temperature": 0.7,
    }
    safety_settings = {
        HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
        HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
        HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
        HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
    }
    target_model_name = "gemini-1.5-flash"
    target_model_config = {
        "temperature": 0, "max_output_tokens": 1000
    }
    review_model_name = "gemini-1.5-flash" 
    review_model_config = {
        "temperature": 0, "max_output_tokens": 10 
    }
    review_prompt_template_path = 'review_prompt_template.txt'  # Path to the review prompt text file

    apd = APD(
        num_prompts, starting_prompt, df_train, 
        metaprompt_template_path, generation_model_name, generation_config, safety_settings, 
        target_model_name, target_model_config, review_model_name, review_model_config, review_prompt_template_path
    )

    asyncio.run(apd.main())

================================================
FILE: LICENSE
================================================
Attribution-NonCommercial-ShareAlike 4.0 International

=======================================================================

Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.

Using Creative Commons Public Licenses

Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.

     Considerations for licensors: Our public licenses are
     intended for use by those authorized to give the public
     permission to use material in ways otherwise restricted by
     copyright and certain other rights. Our licenses are
     irrevocable. Licensors should read and understand the terms
     and conditions of the license they choose before applying it.
     Licensors should also secure all rights necessary before
     applying our licenses so that the public can reuse the
     material as expected. Licensors should clearly mark any
     material not subject to the license. This includes other CC-
     licensed material, or material used under an exception or
     limitation to copyright. More considerations for licensors:
    wiki.creativecommons.org/Considerations_for_licensors

     Considerations for the public: By using one of our public
     licenses, a licensor grants the public permission to use the
     licensed material under specified terms and conditions. If
     the licensor's permission is not necessary for any reason--for
     example, because of any applicable exception or limitation to
     copyright--then that use is not regulated by the license. Our
     licenses grant only permissions under copyright and certain
     other rights that a licensor has authority to grant. Use of
     the licensed material may still be restricted for other
     reasons, including because others have copyright or other
     rights in the material. A licensor may make special requests,
     such as asking that all changes be marked or described.
     Although not required by our licenses, you are encouraged to
     respect those requests where reasonable. More considerations
     for the public:
    wiki.creativecommons.org/Considerations_for_licensees

=======================================================================

Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Public License

By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International Public License
("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.


Section 1 -- Definitions.

  a. Adapted Material means material subject to Copyright and Similar
     Rights that is derived from or based upon the Licensed Material
     and in which the Licensed Material is translated, altered,
     arranged, transformed, or otherwise modified in a manner requiring
     permission under the Copyright and Similar Rights held by the
     Licensor. For purposes of this Public License, where the Licensed
     Material is a musical work, performance, or sound recording,
     Adapted Material is always produced where the Licensed Material is
     synched in timed relation with a moving image.

  b. Adapter's License means the license You apply to Your Copyright
     and Similar Rights in Your contributions to Adapted Material in
     accordance with the terms and conditions of this Public License.

  c. BY-NC-SA Compatible License means a license listed at
     creativecommons.org/compatiblelicenses, approved by Creative
     Commons as essentially the equivalent of this Public License.

  d. Copyright and Similar Rights means copyright and/or similar rights
     closely related to copyright including, without limitation,
     performance, broadcast, sound recording, and Sui Generis Database
     Rights, without regard to how the rights are labeled or
     categorized. For purposes of this Public License, the rights
     specified in Section 2(b)(1)-(2) are not Copyright and Similar
     Rights.

  e. Effective Technological Measures means those measures that, in the
     absence of proper authority, may not be circumvented under laws
     fulfilling obligations under Article 11 of the WIPO Copyright
     Treaty adopted on December 20, 1996, and/or similar international
     agreements.

  f. Exceptions and Limitations means fair use, fair dealing, and/or
     any other exception or limitation to Copyright and Similar Rights
     that applies to Your use of the Licensed Material.

  g. License Elements means the license attributes listed in the name
     of a Creative Commons Public License. The License Elements of this
     Public License are Attribution, NonCommercial, and ShareAlike.

  h. Licensed Material means the artistic or literary work, database,
     or other material to which the Licensor applied this Public
     License.

  i. Licensed Rights means the rights granted to You subject to the
     terms and conditions of this Public License, which are limited to
     all Copyright and Similar Rights that apply to Your use of the
     Licensed Material and that the Licensor has authority to license.

  j. Licensor means the individual(s) or entity(ies) granting rights
     under this Public License.

  k. NonCommercial means not primarily intended for or directed towards
     commercial advantage or monetary compensation. For purposes of
     this Public License, the exchange of the Licensed Material for
     other material subject to Copyright and Similar Rights by digital
     file-sharing or similar means is NonCommercial provided there is
     no payment of monetary compensation in connection with the
     exchange.

  l. Share means to provide material to the public by any means or
     process that requires permission under the Licensed Rights, such
     as reproduction, public display, public performance, distribution,
     dissemination, communication, or importation, and to make material
     available to the public including in ways that members of the
     public may access the material from a place and at a time
     individually chosen by them.

  m. Sui Generis Database Rights means rights other than copyright
     resulting from Directive 96/9/EC of the European Parliament and of
     the Council of 11 March 1996 on the legal protection of databases,
     as amended and/or succeeded, as well as other essentially
     equivalent rights anywhere in the world.

  n. You means the individual or entity exercising the Licensed Rights
     under this Public License. Your has a corresponding meaning.


Section 2 -- Scope.

  a. License grant.

       1. Subject to the terms and conditions of this Public License,
          the Licensor hereby grants You a worldwide, royalty-free,
          non-sublicensable, non-exclusive, irrevocable license to
          exercise the Licensed Rights in the Licensed Material to:

            a. reproduce and Share the Licensed Material, in whole or
               in part, for NonCommercial purposes only; and

            b. produce, reproduce, and Share Adapted Material for
               NonCommercial purposes only.

       2. Exceptions and Limitations. For the avoidance of doubt, where
          Exceptions and Limitations apply to Your use, this Public
          License does not apply, and You do not need to comply with
          its terms and conditions.

       3. Term. The term of this Public License is specified in Section
          6(a).

       4. Media and formats; technical modifications allowed. The
          Licensor authorizes You to exercise the Licensed Rights in
          all media and formats whether now known or hereafter created,
          and to make technical modifications necessary to do so. The
          Licensor waives and/or agrees not to assert any right or
          authority to forbid You from making technical modifications
          necessary to exercise the Licensed Rights, including
          technical modifications necessary to circumvent Effective
          Technological Measures. For purposes of this Public License,
          simply making modifications authorized by this Section 2(a)
          (4) never produces Adapted Material.

       5. Downstream recipients.

            a. Offer from the Licensor -- Licensed Material. Every
               recipient of the Licensed Material automatically
               receives an offer from the Licensor to exercise the
               Licensed Rights under the terms and conditions of this
               Public License.

            b. Additional offer from the Licensor -- Adapted Material.
               Every recipient of Adapted Material from You
               automatically receives an offer from the Licensor to
               exercise the Licensed Rights in the Adapted Material
               under the conditions of the Adapter's License You apply.

            c. No downstream restrictions. You may not offer or impose
               any additional or different terms or conditions on, or
               apply any Effective Technological Measures to, the
               Licensed Material if doing so restricts exercise of the
               Licensed Rights by any recipient of the Licensed
               Material.

       6. No endorsement. Nothing in this Public License constitutes or
          may be construed as permission to assert or imply that You
          are, or that Your use of the Licensed Material is, connected
          with, or sponsored, endorsed, or granted official status by,
          the Licensor or others designated to receive attribution as
          provided in Section 3(a)(1)(A)(i).

  b. Other rights.

       1. Moral rights, such as the right of integrity, are not
          licensed under this Public License, nor are publicity,
          privacy, and/or other similar personality rights; however, to
          the extent possible, the Licensor waives and/or agrees not to
          assert any such rights held by the Licensor to the limited
          extent necessary to allow You to exercise the Licensed
          Rights, but not otherwise.

       2. Patent and trademark rights are not licensed under this
          Public License.

       3. To the extent possible, the Licensor waives any right to
          collect royalties from You for the exercise of the Licensed
          Rights, whether directly or through a collecting society
          under any voluntary or waivable statutory or compulsory
          licensing scheme. In all other cases the Licensor expressly
          reserves any right to collect such royalties, including when
          the Licensed Material is used other than for NonCommercial
          purposes.


Section 3 -- License Conditions.

Your exercise of the Licensed Rights is expressly made subject to the
following conditions.

  a. Attribution.

       1. If You Share the Licensed Material (including in modified
          form), You must:

            a. retain the following if it is supplied by the Licensor
               with the Licensed Material:

                 i. identification of the creator(s) of the Licensed
                    Material and any others designated to receive
                    attribution, in any reasonable manner requested by
                    the Licensor (including by pseudonym if
                    designated);

                ii. a copyright notice;

               iii. a notice that refers to this Public License;

                iv. a notice that refers to the disclaimer of
                    warranties;

                 v. a URI or hyperlink to the Licensed Material to the
                    extent reasonably practicable;

            b. indicate if You modified the Licensed Material and
               retain an indication of any previous modifications; and

            c. indicate the Licensed Material is licensed under this
               Public License, and include the text of, or the URI or
               hyperlink to, this Public License.

       2. You may satisfy the conditions in Section 3(a)(1) in any
          reasonable manner based on the medium, means, and context in
          which You Share the Licensed Material. For example, it may be
          reasonable to satisfy the conditions by providing a URI or
          hyperlink to a resource that includes the required
          information.
       3. If requested by the Licensor, You must remove any of the
          information required by Section 3(a)(1)(A) to the extent
          reasonably practicable.

  b. ShareAlike.

     In addition to the conditions in Section 3(a), if You Share
     Adapted Material You produce, the following conditions also apply.

       1. The Adapter's License You apply must be a Creative Commons
          license with the same License Elements, this version or
          later, or a BY-NC-SA Compatible License.

       2. You must include the text of, or the URI or hyperlink to, the
          Adapter's License You apply. You may satisfy this condition
          in any reasonable manner based on the medium, means, and
          context in which You Share Adapted Material.

       3. You may not offer or impose any additional or different terms
          or conditions on, or apply any Effective Technological
          Measures to, Adapted Material that restrict exercise of the
          rights granted under the Adapter's License You apply.


Section 4 -- Sui Generis Database Rights.

Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:

  a. for the avoidance of doubt, Section 2(a)(1) grants You the right
     to extract, reuse, reproduce, and Share all or a substantial
     portion of the contents of the database for NonCommercial purposes
     only;

  b. if You include all or a substantial portion of the database
     contents in a database in which You have Sui Generis Database
     Rights, then the database in which You have Sui Generis Database
     Rights (but not its individual contents) is Adapted Material,
     including for purposes of Section 3(b); and

  c. You must comply with the conditions in Section 3(a) if You Share
     all or a substantial portion of the contents of the database.

For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.


Section 5 -- Disclaimer of Warranties and Limitation of Liability.

  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.

  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.

  c. The disclaimer of warranties and limitation of liability provided
     above shall be interpreted in a manner that, to the extent
     possible, most closely approximates an absolute disclaimer and
     waiver of all liability.


Section 6 -- Term and Termination.

  a. This Public License applies for the term of the Copyright and
     Similar Rights licensed here. However, if You fail to comply with
     this Public License, then Your rights under this Public License
     terminate automatically.

  b. Where Your right to use the Licensed Material has terminated under
     Section 6(a), it reinstates:

       1. automatically as of the date the violation is cured, provided
          it is cured within 30 days of Your discovery of the
          violation; or

       2. upon express reinstatement by the Licensor.

     For the avoidance of doubt, this Section 6(b) does not affect any
     right the Licensor may have to seek remedies for Your violations
     of this Public License.

  c. For the avoidance of doubt, the Licensor may also offer the
     Licensed Material under separate terms or conditions or stop
     distributing the Licensed Material at any time; however, doing so
     will not terminate this Public License.

  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
     License.


Section 7 -- Other Terms and Conditions.

  a. The Licensor shall not be bound by any additional or different
     terms or conditions communicated by You unless expressly agreed.

  b. Any arrangements, understandings, or agreements regarding the
     Licensed Material not stated herein are separate from and
     independent of the terms and conditions of this Public License.


Section 8 -- Interpretation.

  a. For the avoidance of doubt, this Public License does not, and
     shall not be interpreted to, reduce, limit, restrict, or impose
     conditions on any use of the Licensed Material that could lawfully
     be made without permission under this Public License.

  b. To the extent possible, if any provision of this Public License is
     deemed unenforceable, it shall be automatically reformed to the
     minimum extent necessary to make it enforceable. If the provision
     cannot be reformed, it shall be severed from this Public License
     without affecting the enforceability of the remaining terms and
     conditions.

  c. No term or condition of this Public License will be waived and no
     failure to comply consented to unless expressly agreed to by the
     Licensor.

  d. Nothing in this Public License constitutes or may be interpreted
     as a limitation upon, or waiver of, any privileges and immunities
     that apply to the Licensor or You, including from the legal
     processes of any jurisdiction or authority.

=======================================================================

Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.

Creative Commons may be contacted at creativecommons.org.



================================================
FILE: README.md
================================================
# An in-depth tutorial on Automated Prompt Engineering

This is the code repo for my [blog post](https://towardsdatascience.com/automated-prompt-engineering-the-definitive-hands-on-guide-1476c8cd3c50) on Towards Data Science. If you cannot access the blog post please ping me directly.


================================================
FILE: metaprompt_template.txt
================================================
<EXPLANATION>
I have some prompts along with their corresponding accuracies.
The prompts are arranged in ascending order based on their accuracy, where higher accuracy indicate better quality.
</EXPLANATION>

<PROMPTS>
{prompt_scores}
</PROMPTS>

Each prompt was used together with a problem statement around geometric shapes.

<EXAMPLE>
<QUESTION>
This SVG path element <path d="M 55.57,80.69 L 57.38,65.80 M 57.38,65.80 L 48.90,57.46 M 48.90,57.46 L 45.58,47.78 M 45.58,47.78 L 53.25,36.07 L 66.29,48.90 L 78.69,61.09 L 55.57,80.69"/> draws a Options: (A) circle (B) heptagon (C) hexagon (D) kite (E) line (F) octagon (G) pentagon (H) rectangle (I) sector (J) triangle
</QUESTION>
<ANSWER>
(B)
</ANSWER>
</EXAMPLE>

<TASK>
Write a new prompt that will achieve an accuracy as high as possible and that is different from the old ones.
</TASK>


<RULES>
- It is very important that the new prompt is distinct from ALL the old ones!
- Ensure that you analyse the prompts with a high accuracy and reuse the patterns that worked in the past
- Ensure that you analyse the prompts with a low accuracy and avoid the patterns that didn't worked in the past
- Think out loud before creating the prompt. Describe what has worked in the past and what hasn't. Only then create the new prompt.
- Use all available information like prompt length, formal/informal use of language, etc for your analysis.
- Be creative, try out different ways of prompting the model. You may even come up with hypothetical scenarios that might improve the accuracy.
- You are generating system prompts. This means that there should be no placeholders in the prompt, as they cannot be filled at runtime. Instead focus on general instructions that will help the model to solve the task.
- Write your new prompt in double square brackets. Use only plain text for the prompt text and do not add any markdown (i.e. no hashtags, backticks, quotes, etc).
</RULES>

================================================
FILE: prompt_evaluator.py
================================================
import asyncio
import pandas as pd
from vertexai.generative_models import GenerativeModel
from tqdm.asyncio import tqdm_asyncio
import backoff

class ReviewModelError(Exception):
    """Custom exception for review model errors."""
    pass

class PromptEvaluator:
    def __init__(self, df_train, target_model_name, target_model_config, review_model_name, review_model_config, safety_settings, review_prompt_template_path):
        self.df_train = df_train
        self.target_model_name = target_model_name
        self.target_model_config = target_model_config
        self.review_model_name = review_model_name
        self.review_model_config = review_model_config
        self.safety_settings = safety_settings
        self.review_prompt_template_path = review_prompt_template_path

        self.target_model = GenerativeModel(self.target_model_name)
        self.review_model = GenerativeModel(self.review_model_name)

    @backoff.on_exception(backoff.expo, Exception, max_tries=5)
    async def generate_target_model_response(self, question, prompt):
        target_model = GenerativeModel(
            self.target_model_name,
            generation_config=self.target_model_config,
            safety_settings=self.safety_settings,
            system_instruction=prompt
        )

        response = await target_model.generate_content_async(
            question,
            stream=False,
        )
        return response.text

    @backoff.on_exception(backoff.expo, Exception, max_tries=5)
    async def generate_review_model_response(self, review_prompt):
        review_response = await self.review_model.generate_content_async(
            [review_prompt],
            generation_config=self.review_model_config,
            safety_settings=self.safety_settings,
            stream=False,
        )
        return review_response.text.strip().lower()

    async def generate_and_review(self, row, prompt):
        try:
            model_response = await self.generate_target_model_response(row["question"], prompt)

            # Load the review prompt from the text file
            with open(self.review_prompt_template_path, 'r') as f:
                review_prompt_template = f.read().strip()

            # Fill in the review prompt with the model response and ground truth
            review_prompt = review_prompt_template.format(model_response=model_response, ground_truth=row['answer'])

            # Now use the review model to compare the model response with the ground truth
            review_result = await self.generate_review_model_response(review_prompt)

            # Check if the target model returned a valid response
            if not model_response or not isinstance(model_response, str):
                raise ReviewModelError("Target model did not return a valid response.")

            # Assert that the review model returns either 'true' or 'false'
            if review_result not in ['true', 'false']:
                raise ReviewModelError("Review model did not return a valid response.")

            is_correct = review_result == 'true'  # Check if the response is 'True'

            return row.name, model_response, is_correct 
        except ReviewModelError as e:
            print(f"Error: {e}. The review model did not return a valid response. Terminating the program.")
            raise  # Re-raise the exception to be caught in the main function
        except Exception as e:
            print(f"An error occurred: {e}. Terminating the program.")
            raise  # Re-raise the exception to be caught in the main function

    async def evaluate_prompt(self, prompt):
        tasks = [self.generate_and_review(row, prompt) for _, row in self.df_train.iterrows()]

        # Create a tqdm progress bar
        with tqdm_asyncio(total=len(tasks), desc="Evaluating Prompt") as pbar:

            async def wrapped_task(task):
                result = await task
                pbar.update(1)  # Update progress bar after task completion
                return result

            # Run tasks with progress bar updates
            results = await asyncio.gather(*[wrapped_task(task) for task in tasks])

        # Prepare results for saving
        evaluation_results = []
        for index, model_response, is_correct in results:
            if index is not None:  # Check if the index is valid
                self.df_train.loc[index, 'model_response'] = model_response
                self.df_train.loc[index, 'is_correct'] = is_correct
                evaluation_results.append({
                    'question': self.df_train.loc[index, 'question'],
                    'ground_truth': self.df_train.loc[index, 'answer'],
                    'model_response': model_response,
                    'is_correct': is_correct
                })

        overall_accuracy = sum(self.df_train["is_correct"]) / len(self.df_train)

        # Save results to CSV
        results_df = pd.DataFrame(evaluation_results)
        results_csv_path = 'evaluation_results.csv'
        results_df.to_csv(results_csv_path, index=False)

        return overall_accuracy

    async def main(self, prompt):
        try:
            accuracy = await self.evaluate_prompt(prompt)
            print(f"Overall accuracy for the prompt: {accuracy:.2f}")
        except ReviewModelError:
            print("The program has terminated due to an invalid response from the review model.")
        except Exception as e:
            print(f"The program has terminated due to an unexpected error: {e}")

================================================
FILE: requirements.txt
================================================
aioconsole==0.7.1
aiofiles==24.1.0
backoff==2.2.1
datasets==2.18.0
datasets==2.20.0
google_cloud_aiplatform==1.43.0
google_cloud_aiplatform==1.61.0
numpy==2.1.0
pandas==2.2.2
tqdm==4.66.2
tqdm==4.66.5


================================================
FILE: review_prompt_template.txt
================================================
You are a review model tasked with evaluating the correctness of a response to a navigation problem. 
The response may contain detailed steps and explanations, but the final answer is the key point. 
Please determine if the final answer provided in the response is correct based on the ground truth number. 
Respond with 'True' if the final answer is correct and 'False' if it is not. 
Only respond with 'True' or 'False', nothing else.

Model Response:
{model_response}

Ground Truth:
{ground_truth}
Download .txt
gitextract_gl_wp18s/

├── .gitignore
├── 01_data_prep.py
├── 02_baseline.py
├── 03_ape.py
├── LICENSE
├── README.md
├── metaprompt_template.txt
├── prompt_evaluator.py
├── requirements.txt
└── review_prompt_template.txt
Download .txt
SYMBOL INDEX (17 symbols across 2 files)

FILE: 03_ape.py
  class APD (line 13) | class APD:
    method __init__ (line 14) | def __init__(self, num_prompts, starting_prompt, df_train, metaprompt_...
    method create_run_folder (line 49) | def create_run_folder(self):
    method create_prompt_subfolder (line 55) | def create_prompt_subfolder(self, prompt_number):
    method read_and_sort_prompt_accuracies (line 60) | def read_and_sort_prompt_accuracies(self, file_path):
    method write_sorted_prompt_accuracies (line 70) | def write_sorted_prompt_accuracies(self, file_path, sorted_prompts):
    method update_metaprompt (line 80) | def update_metaprompt(self, file_path, metaprompt_template_path):
    method generate_with_backoff (line 92) | async def generate_with_backoff(self, metaprompt):
    method main (line 101) | async def main(self):

FILE: prompt_evaluator.py
  class ReviewModelError (line 7) | class ReviewModelError(Exception):
  class PromptEvaluator (line 11) | class PromptEvaluator:
    method __init__ (line 12) | def __init__(self, df_train, target_model_name, target_model_config, r...
    method generate_target_model_response (line 25) | async def generate_target_model_response(self, question, prompt):
    method generate_review_model_response (line 40) | async def generate_review_model_response(self, review_prompt):
    method generate_and_review (line 49) | async def generate_and_review(self, row, prompt):
    method evaluate_prompt (line 81) | async def evaluate_prompt(self, prompt):
    method main (line 117) | async def main(self, prompt):
Condensed preview — 10 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (46K chars).
[
  {
    "path": ".gitignore",
    "chars": 3184,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
  },
  {
    "path": "01_data_prep.py",
    "chars": 522,
    "preview": "from datasets import load_dataset\nimport pandas as pd\n\ndataset = load_dataset(\"lukaemon/bbh\", \"geometric_shapes\", cache_"
  },
  {
    "path": "02_baseline.py",
    "chars": 1260,
    "preview": "import asyncio\nimport pandas as pd\nfrom prompt_evaluator import PromptEvaluator\nfrom vertexai.generative_models import H"
  },
  {
    "path": "03_ape.py",
    "chars": 9923,
    "preview": "import asyncio\nimport os\nimport pandas as pd\nfrom vertexai.generative_models import GenerativeModel, HarmBlockThreshold,"
  },
  {
    "path": "LICENSE",
    "chars": 20846,
    "preview": "Attribution-NonCommercial-ShareAlike 4.0 International\n\n================================================================"
  },
  {
    "path": "README.md",
    "chars": 286,
    "preview": "# An in-depth tutorial on Automated Prompt Engineering\n\nThis is the code repo for my [blog post](https://towardsdatascie"
  },
  {
    "path": "metaprompt_template.txt",
    "chars": 1923,
    "preview": "<EXPLANATION>\nI have some prompts along with their corresponding accuracies.\nThe prompts are arranged in ascending order"
  },
  {
    "path": "prompt_evaluator.py",
    "chars": 5533,
    "preview": "import asyncio\nimport pandas as pd\nfrom vertexai.generative_models import GenerativeModel\nfrom tqdm.asyncio import tqdm_"
  },
  {
    "path": "requirements.txt",
    "chars": 201,
    "preview": "aioconsole==0.7.1\naiofiles==24.1.0\nbackoff==2.2.1\ndatasets==2.18.0\ndatasets==2.20.0\ngoogle_cloud_aiplatform==1.43.0\ngoog"
  },
  {
    "path": "review_prompt_template.txt",
    "chars": 500,
    "preview": "You are a review model tasked with evaluating the correctness of a response to a navigation problem. \nThe response may c"
  }
]

About this extraction

This page contains the full source code of the marshmellow77/automated-prompt-engineering-from-scratch GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 10 files (43.1 KB), approximately 9.7k tokens, and a symbol index with 17 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!