### Start vLLM Server Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/inference_providers.md Installs vLLM and starts a local inference server for a specified model. ```bash pip install vllm vllm serve meta-llama/Llama-3.1-8B-Instruct --tensor-parallel-size=1 ``` -------------------------------- ### Install Prompt-ops from Source Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb Install the prompt-ops package from its GitHub repository. This is the recommended installation method. Ensure you have git installed. ```python !git clone https://github.com/meta-llama/prompt-ops.git ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/README.md Install all necessary frontend dependencies using npm. ```bash npm install ``` -------------------------------- ### Example Optimized Prompt Output Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/basic/readme.md This is an example of the output saved in the results directory after running optimization. It includes the system prompt, few-shot examples, and expected JSON output format for analysis. ```yaml system: |- Analyze the customer's message and determine the level of urgency, sentiment, and relevant categories. Extract and return a json with the keys "urgency", "sentiment", and "categories". The "urgency" key should have a value of "high", "medium", or "low", the "sentiment" key should have a value of "negative", "neutral", or "positive", and the "categories" key should have a dictionary with categories as keys and boolean values indicating whether the category is a best matching support category tag. The categories should include "emergency_repair_services", "routine_maintenance_requests", "quality_and_safety_concerns", "specialized_cleaning_services", "general_inquiries", "sustainability_and_environmental_practices", "training_and_support_requests", "cleaning_services_scheduling", "customer_feedback_and_complaints", and "facility_management_issues". Few-shot examples: Example 1: Question: Our office bathroom needs cleaning urgently. The toilets are clogged and there's water on the floor. Answer: {"urgency": "high", "sentiment": "negative", "categories": {"emergency_repair_services": true, "specialized_cleaning_services": true, "facility_management_issues": true, "emergency_repair_services": false, "routine_maintenance_requests": false, "quality_and_safety_concerns": false, "general_inquiries": false, "sustainability_and_environmental_practices": false, "training_and_support_requests": false, "customer_feedback_and_complaints": false}} ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/backend/tests/README.md Install project dependencies and run the full test suite. Use the `--cov` flag to generate a coverage report. ```bash cd frontend/backend pip install -r requirements.txt pytest pytest --cov ``` -------------------------------- ### Install prompt-ops from Source Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/pdo_tutorial_101.ipynb Installs the prompt-ops library from source in development mode. This is useful for accessing the latest features or contributing to the project. ```bash # Install from source # Clone and install in development mode (editable install) !git clone -b pdo-notebook https://github.com/meta-llama/prompt-ops.git !cd prompt-ops && pip install -e . ``` -------------------------------- ### Install prompt-ops from Source Source: https://github.com/meta-llama/prompt-ops/blob/main/README.md Installs prompt-ops using pip after cloning the repository. This is the recommended method to ensure you have the latest stable version. ```bash conda create -n prompt-ops python=3.10 conda activate prompt-ops git clone https://github.com/meta-llama/prompt-ops.git cd prompt-ops pip install -e . ``` -------------------------------- ### Install prompt-ops Package Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/pdo_tutorial_101.ipynb Installs the prompt-ops library using pip. This is the first step to using PDO. ```bash # Install prompt-ops pip install prompt-ops ``` -------------------------------- ### Pre-Optimization Summary Example Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/advanced/logging.md An example of the detailed summary provided before the optimization process begins, showing configuration details like models, metrics, and parameters. ```text === Pre-Optimization Summary === Task Model : openai/gpt-4o-mini Proposer Model : openai/gpt-4o Metric : facility_metric Train / Val size : 100 / 25 MIPRO Params : {"auto_user":"basic","auto_dspy":"light","max_labeled_demos":5,"max_bootstrapped_demos":4,"num_candidates":10,"num_threads":18,"init_temperature":0.5,"seed":9} Guidance : Use chain-of-thought reasoning and show your work step by step... Baseline score : 0.4200 ``` -------------------------------- ### Setup Model for LiteLLM Adapter Source: https://github.com/meta-llama/prompt-ops/blob/main/use-cases/web-of-lies-pdo/PDO_web_of_lies_eval.ipynb Configures and initializes a model using the LiteLLM adapter. Ensure OPENROUTER_API_BASE and OPENROUTER_API_KEY environment variables are set. ```python model = setup_model( adapter_type="litellm", model_name="openrouter/meta-llama/llama-3.3-70b-instruct", api_base=os.environ.get("OPENROUTER_API_BASE", "https://openrouter.ai/api/v1"), api_key=os.environ.get("OPENROUTER_API_KEY"), max_tokens=4096, temperature=0.0, ) ``` -------------------------------- ### Install prompt-ops in development mode Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/backend/README.md Install the prompt-ops package in editable mode from the repository root. This is necessary for development. ```bash cd /path/to/prompt-ops pip install -e . ``` -------------------------------- ### Install prompt-ops as editable package Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb After cloning, navigate into the prompt-ops directory and install the package in editable mode. This command also handles dependency installation. ```bash !cd prompt-ops && pip install -e . ``` -------------------------------- ### Run Backend Server Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/README.md Start the FastAPI backend server with auto-reloading enabled. Ensure the virtual environment is activated. ```bash cd frontend/backend source venv/bin/activate # On Windows: venv\Scripts\activate uvicorn main:app --reload --port 8001 ``` -------------------------------- ### Run Frontend Development Server Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/README.md Start the React frontend development server with hot reloading enabled. ```bash cd frontend npm run dev ``` -------------------------------- ### Start Fine-tuning Process Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb Initiates the fine-tuning process using the configured Trainer. This will train the model on the provided dataset. ```python trainer.train() ``` -------------------------------- ### Install Prompt Ops using Conda or Pip Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/basic/readme.md These commands show how to set up a Python virtual environment using Conda and install the prompt-ops library either from PyPI or from source. Choose the installation method that best suits your development environment. ```bash # Create a virtual environment conda create -n prompt-ops python=3.10 conda activate prompt-ops # Install from PyPI pip install prompt-ops # OR install from source git clone https://github.com/meta-llama/prompt-ops.git cd prompt-ops pip install -e . ``` -------------------------------- ### Run Prompt Optimization Source: https://github.com/meta-llama/prompt-ops/blob/main/use-cases/hotpotqa/README.md Execute the prompt migration command from the root directory of the project to start the optimization process. ```bash prompt-ops migrate --config configs/hotpotqa.yaml ``` -------------------------------- ### Install Prompt-ops from PyPI Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb Alternatively, install the prompt-ops package from PyPI. Note that the PyPI version might be older (e.g., 0.0.7) and may have naming transition issues. ```python # Alternative: Install from PyPI (may have naming transition issues, still on version 0.0.7) ``` -------------------------------- ### Setup Model and Load Dataset Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/pdo_tutorial_101.ipynb Initializes the language model using specified adapter, model name, and API credentials. Loads the dataset from a JSON file. Ensure environment variables for API key and base are set if using defaults. ```python import os, json import numpy as np from pathlib import Path import sys sys.path.append(os.path.abspath("../../src")) from prompt_ops.core.model import setup_model # Load dataset DATA_PATH = "prompt-ops/use-cases/ms-marco-pdo/dataset/ms_marco_description.json" rows = json.load(open(DATA_PATH, "r")) # Model for answering and for judging (same adapter; different prompts) model = setup_model( adapter_type="litellm", model_name="openrouter/meta-llama/llama-3.3-70b-instruct", api_base=os.environ.get("OPENROUTER_API_BASE", "https://openrouter.ai/api/v1"), api_key=os.environ.get("OPENROUTER_API_KEY"), max_tokens=4096, temperature=0.0, ) ``` -------------------------------- ### Clone Prompt Ops Repository Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/README.md Clone the prompt-ops repository and navigate into the frontend directory to begin setup. ```bash git clone https://github.com/meta-llama/prompt-ops.git cd prompt-ops/frontend ``` -------------------------------- ### Complete Facility Configuration Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/intermediate/readme.md This example shows all available options for the facility management classification task in a single YAML file. It includes settings for model, dataset, prompt, metric, and optimization. ```yaml # Model Configuration model: name: "openrouter/meta-llama/llama-3.3-70b-instruct" api_base: "https://openrouter.ai/api/v1" temperature: 0.0 max_tokens: 2048 top_p: 0.95 cache: false # Dataset Configuration dataset: adapter_class: "prompt_ops.core.datasets.ConfigurableJSONAdapter" path: "../use-cases/facility-support-analyzer/facility_v2_test.json" train_size: 0.7 validation_size: 0.15 # These parameters can be placed directly at the dataset level input_field: ["fields", "input"] golden_output_field: "answer" # Optional parameters seed: 42 shuffle: true # Prompt Configuration prompt: file: "../use-cases/facility-support-analyzer/facility_prompt_sys.txt" # Reference to prompt file instead of inline text inputs: ["question"] outputs: ["answer"] # Metric Configuration metric: class: "prompt_ops.core.metrics.FacilityMetric" strict_json: false output_field: "answer" # Optimization Settings optimization: strategy: "basic" max_rounds: 3 max_examples_per_round: 5 max_prompt_length: 2048 num_candidates: 5 bootstrap_examples: 4 num_threads: 36 max_errors: 5 disable_progress_bar: false save_intermediate: false model_family: "llama" ``` -------------------------------- ### Prompt-ops Configuration File Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/advanced/readme.md Example configuration file for prompt-ops, specifying dataset adapter, metric, model, and prompt template for a customer service use case. ```yaml # customer_service_config.yaml dataset: adapter_class: "path.to.your.module.CustomerServiceAdapter" path: "/path/to/customer_service.json" metric: class: "path.to.your.module.CustomerServiceMetric" params: weights: categories: 0.5 sentiment: 0.3 urgency: 0.2 model: provider: "openrouter" name: "meta-llama/llama-3-70b-instruct" prompt: template: | Analyze the following customer service message and provide: 1. Urgency level (high, medium, or low) 2. Sentiment (positive, negative, or neutral) 3. Categories that apply (maintenance, billing, etc.) Message: {{question}} Respond in JSON format with the following structure: {"urgency": "...", "sentiment": "...", "categories": {"category1": true, ...}} ``` -------------------------------- ### Clone MS MARCO PDO Example Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/pdo_tutorial_101.ipynb Clones the pre-configured MS MARCO PDO example project. This allows you to explore and work with a practical implementation of prompt-ops for an open-ended QA task. ```bash # Clone the pre-configured MS MARCO PDO example !cd prompt-ops/use-cases/ms-marco-pdo && ls -la ``` -------------------------------- ### Frontend Development Commands Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/README.md Common commands for frontend development, including starting the dev server, building for production, previewing, and linting. ```bash # Start with hot reload npm run dev # Build for production npm run build # Preview production build npm run preview # Lint code npm run lint ``` -------------------------------- ### MS MARCO Dataset Structure Example Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/pdo_tutorial_101.ipynb Example JSON structure for a question-answer pair from the MS MARCO dataset, suitable for PDO tasks. ```json { "question": "what is the purpose of an mri", "answer": "Magnetic resonance imaging (MRI) is a medical imaging technique used to visualize internal structures of the body in detail. MRI makes use of the property of nuclear magnetic resonance (NMR) to image nuclei of atoms inside the body. An MRI scan can be used as an extremely accurate method of disease detection throughout the body and is most often used after other testing fails to provide sufficient information to confirm a patient's diagnosis." } ``` -------------------------------- ### Customer Service Dataset Example (JSON) Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/advanced/readme.md Example of a raw customer service dataset in JSON format. This structure is used as input for custom adapters. ```json [ { "customer_message": "The heating in my apartment isn't working and it's freezing!", "priority": "high", "categories": {"maintenance": true, "heating": true}, "sentiment": "negative" }, ... ] ``` -------------------------------- ### Define Initial Prompt for PDO Source: https://github.com/meta-llama/prompt-ops/blob/main/use-cases/ms-marco-pdo/MSMARCO_PDO_eval.ipynb This is the concise, domain-agnostic starting instruction used to seed the Prompt Duel Optimizer (PDO). It is designed to be neutral to allow for exploration of useful variants during optimization. ```python initial_prompt = """You are an expert answerer. Read the question and the provided context (if any). Write a concise, accurate answer in your own words. """ ``` -------------------------------- ### Setup and Baseline Evaluation Source: https://github.com/meta-llama/prompt-ops/blob/main/use-cases/ms-marco-pdo/MSMARCO_PDO_eval.ipynb Sets up the model, loads the dataset, and evaluates baseline prompts. It defines a helper function for JSON parsing and a function to generate answers for a given instruction. ```python import os, json import numpy as np from pathlib import Path import sys sys.path.append(os.path.abspath("../../src")) from prompt_ops.core.model import setup_model # Load dataset DATA_PATH = "dataset/ms_marco_description.json" rows = json.load(open(DATA_PATH, "r")) # Model for answering and for judging (same adapter; different prompts) model = setup_model( adapter_type="litellm", model_name="openrouter/meta-llama/llama-3.3-70b-instruct", api_base=os.environ.get("OPENROUTER_API_BASE", "https://openrouter.ai/api/v1"), api_key=os.environ.get("OPENROUTER_API_KEY"), max_tokens=4096, temperature=0.0, ) # Helper def _try_json_parse(s: str): try: start = s.find("{"); end = s.rfind("}") + 1 blob = s[start:end] if (start >= 0 and end > start) else s return json.loads(blob) except Exception: return {} # Baselines and PDO instruction BASELINES = { "Initial Prompt": """You are an expert answerer. Read the question and the provided context (if any). Write a concise, accurate answer in your own words. """, } def predict_answers(instruction: str): prompts = [] for r in rows: q = r["question"].strip() prompts.append(f"{instruction}\n\nQuestion:\n{q}") return model.generate_batch(prompts, max_threads=10, temperature=0.0) results = {} # Evaluate baselines for name, instr in BASELINES.items(): print(f"evaluating... {name}") preds = predict_answers(instr) s, _ = judge_scores(preds) results[name] = float(np.mean(s)) if len(s) else 0.0 ``` -------------------------------- ### Run the FastAPI server Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/backend/README.md Start the FastAPI development server using uvicorn. The server will reload automatically on code changes. ```bash uvicorn main:app --reload --port 8001 ``` -------------------------------- ### Prompt Transformation Example Source: https://github.com/meta-llama/prompt-ops/blob/main/README.md Compares an original proprietary LM prompt with an optimized Llama prompt for extracting and structuring information into a JSON format. ```text You are a helpful assistant. Extract and return a JSON with the following keys and values: 1. "urgency": one of `high`, `medium`, `low` 2. "sentiment": one of `negative`, `neutral`, `positive` 3. "categories": Create a dictionary with categories as keys and boolean values (True/False), where the value indicates whether the category matches tags like `emergency_repair_services`, `routine_maintenance_requests`, etc. Your complete message should be a valid JSON string that can be read directly. ``` ```text You are an expert in analyzing customer service messages. Your task is to categorize the following message based on urgency, sentiment, and relevant categories. Analyze the message and return a JSON object with these fields: 1. "urgency": Classify as "high", "medium", or "low" based on how quickly this needs attention 2. "sentiment": Classify as "negative", "neutral", or "positive" based on the customer's tone 3. "categories": Create a dictionary with facility management categories as keys and boolean values Only include these exact keys in your response. Return a valid JSON object without code blocks, prefixes, or explanations. ``` -------------------------------- ### BasicOptimizationStrategy Source: https://context7.com/meta-llama/prompt-ops/llms.txt Uses DSPy's MIPROv2 optimizer to generate improved prompt instructions and few-shot examples via a two-stage process: bootstrapped demo generation followed by Bayesian instruction search. ```APIDOC ## `BasicOptimizationStrategy` Uses DSPy's MIPROv2 optimizer to generate improved prompt instructions and few-shot examples via a two-stage process: bootstrapped demo generation followed by Bayesian instruction search. ### Initialization Parameters - **`model_name`** (str) - The name of the model to use. - **`metric`** (Metric) - The metric to use for evaluation. - **`task_model`** (Model) - The task model. - **`prompt_model`** (Model) - The prompt model. - **`auto`** (str) - Optimization mode ('basic', 'intermediate', 'advanced'). Defaults to 'basic'. - **`max_bootstrapped_demos`** (int) - Maximum number of bootstrapped demos. - **`max_labeled_demos`** (int) - Maximum number of labeled demos. - **`num_candidates`** (int) - Number of candidates to generate. - **`minibatch`** (bool) - Whether to use minibatches. - **`minibatch_size`** (int) - Size of the minibatches. - **`compute_baseline`** (bool) - Whether to compute the baseline. - **`num_threads`** (int) - Number of threads to use. - **`seed`** (int) - Random seed for reproducibility. ### Methods #### `run` Executes the optimization process. - **Parameters**: - `prompt_data` (dict) - Dictionary containing the prompt text, input fields, and output fields. - **Returns**: - `optimized_program` (Program) - The optimized program. ``` -------------------------------- ### YAML Configuration for Prompt Optimization Source: https://context7.com/meta-llama/prompt-ops/llms.txt Defines the central configuration for the optimization pipeline, including prompt source, dataset, models, metric, and strategy. This example shows a complete configuration for facility support analysis. ```yaml # config.yaml — complete example for facility support analysis system_prompt: file: "prompts/prompt.txt" # path to the original system prompt inputs: ["question"] # DSPy input field names outputs: ["answer"] # DSPy output field names dataset: path: "data/dataset.json" input_field: ["fields", "input"] # nested path support: item["fields"]["input"] golden_output_field: "answer" train_size: 0.25 # 25% training validation_size: 0.25 # 25% validation, rest is test model: task_model: "openrouter/meta-llama/llama-3.3-70b-instruct" proposer_model: "openrouter/meta-llama/llama-3.3-70b-instruct" temperature: 0.0 max_tokens: 2048 metric: class: "prompt_ops.core.metrics.FacilityMetric" strict_json: false output_field: "answer" optimization: strategy: "basic" # "basic" (MIPROv2) or "pdo" (dueling bandits) num_threads: 4 # Optional: logging export logging: level: "INFO" export_path: "logs/run_${TIMESTAMP}.json" ``` -------------------------------- ### Implement a Custom DatasetAdapter Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/dataset_adapter_selection_guide.md Create a custom adapter when existing adapters cannot handle complex structures or require specialized processing logic. This example shows the basic structure for overriding the DatasetAdapter class, including initialization and the adapt method for custom data transformation. ```python from prompt_ops.core.datasets import DatasetAdapter class MyCustomAdapter(DatasetAdapter): def __init__(self, dataset_path, **kwargs): super().__init__(dataset_path) # Initialize any custom parameters self.special_param = kwargs.get('special_param') def adapt(self): # Load raw data raw_data = self.load_raw_data() # Transform into standardized format standardized_data = [] for item in raw_data: # Your custom transformation logic here # This is where you can implement any special processing standardized_example = { "inputs": { "question": self._process_question(item), # Add any other input fields }, "outputs": { "answer": self._process_answer(item), # Add any other output fields }, "metadata": self._extract_metadata(item) } standardized_data.append(standardized_example) return standardized_data def _process_question(self, item): # Custom question processing logic pass def _process_answer(self, item): # Custom answer processing logic pass def _extract_metadata(self, item): # Extract any relevant metadata return {} ``` -------------------------------- ### Set Up API Key and Run Optimization Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/intermediate/readme.md Prepare your environment by creating a .env file with your API key, then execute the prompt-ops migration command with your configuration file. ```bash # Create a .env file with your API key echo "OPENROUTER_API_KEY=your_key_here" > .env # Run optimization prompt-ops migrate --config configs/facility.yaml ``` -------------------------------- ### Create a New Prompt-Ops Project Source: https://github.com/meta-llama/prompt-ops/blob/main/README.md Creates a new project directory with sample configuration and dataset files. Navigate into the created directory to proceed. ```bash prompt-ops create my-project cd my-project ``` -------------------------------- ### Set Up Backend Virtual Environment Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/README.md Set up a Python virtual environment for the backend and activate it. Use `venv\Scripts\activate` on Windows. ```bash cd backend python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt ``` -------------------------------- ### Create Sample Project with Prompt Ops Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb Use the `prompt-ops create` command to generate a new project structure, including directories for data and prompts, configuration files, and sample datasets. ```python # Create a sample project !prompt-ops create my-cerebras-project ``` -------------------------------- ### Create a New Prompt Ops Project Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/basic/readme.md This command initializes a new prompt-ops project, creating necessary sample files for the Facility Support Analyzer use case in the current directory. Navigate into the newly created project directory afterward. ```bash prompt-ops create my-project cd my-project ``` -------------------------------- ### Create a New PDO Project Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/pdo_tutorial_101.ipynb Initializes a new project directory for PDO optimization. Replace 'my-pdo-project' with your desired project name. ```bash # Create a new PDO project prompt-ops create my-pdo-project ``` -------------------------------- ### Install pytest-cov for Coverage Reports Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/backend/tests/README.md If coverage reports are not generated, ensure `pytest-cov` is installed and then run pytest with the `--cov` flag, specifying the target directory. ```bash pip install pytest-cov pytest --cov=. tests/ ``` -------------------------------- ### Truncate Few-Shot Examples in Prompts Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb Use this function to shorten long questions and answers in few-shot examples for better readability. It limits the number of question lines and the character count of answers. ```python import glob import os import re from IPython.display import display, HTML def truncate_examples(text, max_question_lines=3, max_answer_chars=100): """ Truncates few-shot examples to make them more readable. Shows only the first few lines of questions and truncates answers. """ def truncate_section(match): full_text = match.group(0) # Extract question part question_match = re.search(r'Question:(.*?)Answer:', full_text, re.DOTALL) answer_match = re.search(r'Answer:(.*?)(?=Example \d+:|$)', full_text, re.DOTALL) result = match.group(1) # Keep "Example N:" if question_match: question = question_match.group(1).strip() lines = question.split('\n') if len(lines) > max_question_lines: truncated = '\n'.join(lines[:max_question_lines]) result += f"\n Question: {truncated}\n [...truncated {len(lines) - max_question_lines} more lines...]" else: result += f"\n Question: {question}" if answer_match: answer = answer_match.group(1).strip() if len(answer) > max_answer_chars: result += f"\n Answer: {answer[:max_answer_chars]}... [truncated]" else: result += f"\n Answer: {answer}" return result + "\n " # Find and truncate each example pattern = r'(Example \d+:)(.*?)(?=Example \d+:|$)' truncated = re.sub(pattern, truncate_section, text, flags=re.DOTALL) return truncated # Load the original prompt with open('my-cerebras-project/prompts/prompt.txt', 'r') as f: original_prompt = f.read() # Find the most recent result file result_files = glob.glob('my-cerebras-project/results/*.yaml') if result_files: latest_result = max(result_files, key=os.path.getctime) # Load the optimized prompt using simple text parsing with open(latest_result, 'r') as f: content = f.read() # Split on 'config:' and take the first part (the system prompt) system_section = content.split('config:')[0] optimized_prompt = system_section.replace('system: |-', '').strip() # Truncate examples in both prompts original_truncated = truncate_examples(original_prompt) optimized_truncated = truncate_examples(optimized_prompt) # Create HTML output with word wrapping (dark theme) html_output = f"""