### 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"""
Original Prompt
{original_truncated.replace('<', '<').replace('>', '>')}
Optimized Prompt
{optimized_truncated.replace('<', '<').replace('>', '>')}
""" display(HTML(html_output)) else: print("No result files found. Make sure the optimization process completed successfully.") ``` -------------------------------- ### Create a New Prompt Optimization Project Source: https://context7.com/meta-llama/prompt-ops/llms.txt Scaffolds a new project directory with essential files for prompt optimization. Use the default model or specify a different provider and model. ```bash # Create a project using the default OpenRouter Llama model prompt-ops create my-project ``` ```bash # Create with a different model provider (Groq) prompt-ops create my-project --model groq/meta-llama/llama-4-maverick-17b-128e-instruct ``` ```text # Resulting project layout: # my-project/ # ├── .env ← add your API key here # ├── README.md # ├── config.yaml # ├── data/ # │ └── dataset.json ← sample QA pairs # ├── prompts/ # │ └── prompt.txt ← original system prompt # └── results/ ← created on first run ``` -------------------------------- ### Clone prompt-ops repository Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb Use this command to clone the prompt-ops repository from GitHub. Ensure you have git installed and configured. ```bash git clone https://github.com/meta-llama/prompt-ops.git ``` -------------------------------- ### Initialize and Use PromptMigrator in Python Source: https://context7.com/meta-llama/prompt-ops/llms.txt Set up models, metrics, and datasets to optimize prompts using the PromptMigrator. This involves configuring DSPy adapters and loading datasets before running the optimization and evaluation. ```python import dspy from prompt_ops.core.migrator import PromptMigrator from prompt_ops.core.prompt_strategies import BasicOptimizationStrategy from prompt_ops.core.datasets import ConfigurableJSONAdapter, load_dataset from prompt_ops.core.metrics import FacilityMetric from prompt_ops.core.model import setup_model # 1. Set up model (DSPy adapter for BasicOptimizationStrategy) task_model = setup_model( model_name="openrouter/meta-llama/llama-3.3-70b-instruct", adapter_type="dspy", api_key="sk-or-...", max_tokens=2048, temperature=0.0, ) # 2. Set up metric and dataset metric = FacilityMetric(output_field="answer", strict_json=False) adapter = ConfigurableJSONAdapter( dataset_path="data/dataset.json", input_field=["fields", "input"], golden_output_field="answer", ) # 3. Build strategy and migrator strategy = BasicOptimizationStrategy( model_name="llama-3.3-70b-instruct", metric=metric, task_model=task_model, prompt_model=task_model, auto="basic", # "basic" | "intermediate" | "advanced" num_threads=4, compute_baseline=True, ) migrator = PromptMigrator( strategy=strategy, task_model=task_model, prompt_model=task_model, ) # 4. Load dataset with train/val/test splits trainset, valset, testset = migrator.load_dataset_with_adapter( adapter, train_size=0.25, validation_size=0.25, ) # 5. Optimize original_prompt = open("prompts/prompt.txt").read() optimized_program = migrator.optimize( prompt_data={ "text": original_prompt, "inputs": ["question"], "outputs": ["answer"], }, trainset=trainset, valset=valset, testset=testset, save_to_file=True, file_path="results/optimized.json", save_yaml=True, ) print(optimized_program.signature.instructions) # → "You are an expert in analyzing customer service messages. Your task is..." # 6. Evaluate on test set score = migrator.evaluate(program=optimized_program, devset=testset) print(f"Test score: {score:.3f}") ``` -------------------------------- ### Display Sample System Prompt Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb Use the `cat` command to display the content of the `prompt.txt` file. This file contains the system prompt that will be used for optimization and evaluation. ```python !cat my-cerebras-project/prompts/prompt.txt ``` -------------------------------- ### Troubleshoot Import Errors Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/backend/tests/README.md If tests fail with import errors, ensure you are in the correct directory (`frontend/backend`) and have installed all necessary dependencies. ```bash cd frontend/backend pip install -r requirements.txt ``` -------------------------------- ### Unit Test Template Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/backend/tests/README.md A template for writing unit tests, including setup for testing a specific function and handling expected exceptions. ```python """Unit tests for new_module.py""" import pytest from new_module import function_to_test class TestNewFeature: """Tests for new feature.""" def test_basic_functionality(self): """Test basic use case.""" result = function_to_test("input") assert result == "expected" def test_error_handling(self): """Test error conditions.""" with pytest.raises(ValueError): function_to_test("invalid") ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/meta-llama/prompt-ops/blob/main/frontend/README.md Create a `.env` file in the `frontend/backend` directory to store API keys. Ensure the `OPENROUTER_API_KEY` is provided. ```bash # In frontend/backend/.env OPENROUTER_API_KEY=your_openrouter_api_key_here OPENAI_API_KEY=your_openai_api_key_here # Optional: for fallback enhance feature ``` -------------------------------- ### Configure BasicOptimizationStrategy in Python Source: https://context7.com/meta-llama/prompt-ops/llms.txt Instantiate BasicOptimizationStrategy with a specific metric and model configuration for prompt optimization. This strategy uses DSPy's MIPROv2 optimizer for bootstrapped demo generation and Bayesian instruction search. ```python from prompt_ops.core.prompt_strategies import BasicOptimizationStrategy from prompt_ops.core.metrics import StandardJSONMetric metric = StandardJSONMetric( output_fields=["urgency", "sentiment"], required_fields=["urgency", "sentiment", "categories"], nested_fields={"categories": ["emergency_repair", "routine_maintenance"]}, strict_json=False, ) strategy = BasicOptimizationStrategy( model_name="llama-3.3-70b-instruct", metric=metric, task_model=task_model, prompt_model=task_model, # MIPROv2 parameters auto="basic", # maps to DSPy "light" mode (~10 trials) max_bootstrapped_demos=4, max_labeled_demos=5, num_candidates=10, minibatch=True, minibatch_size=25, compute_baseline=True, # evaluate original prompt first num_threads=4, seed=42, ) # strategy.run() is called internally by PromptMigrator.optimize() optimized = strategy.run({ "text": "You are a helpful assistant. Extract urgency, sentiment, and categories as JSON.", "inputs": ["question"], "outputs": ["answer"], }) print(optimized.signature.instructions) ``` -------------------------------- ### Store Optimized Prompt Source: https://github.com/meta-llama/prompt-ops/blob/main/use-cases/ms-marco-pdo/MSMARCO_PDO_eval.ipynb This variable stores the final optimized prompt string after the PDO process. It is designed to guide the model in providing clear, step-by-step explanations for user questions. ```python OPTIMIZED_PROMPT = ( """Embody the role of a knowledgeable researcher and provide a clear, step-by-step explanation to answer the user's question, utilizing the provided context and avoiding technical jargon unless absolutely necessary, to ensure a concise and accurate response.""" ) ``` -------------------------------- ### Configure Prompt with Inline Text or File Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/intermediate/readme.md Set up your prompt using either inline text with placeholders or by referencing an external file. Specify which dataset fields map to prompt inputs and which model response fields to capture. ```yaml prompt: # Option 1: Inline Text text: | Giving the following message: --- {{question}} --- Extract and return a json with the following keys and values: - "urgency" as one of `high`, `medium`, `low` - "sentiment" as one of `negative`, `neutral`, `positive` - "categories" Create a dictionary with categories as keys and boolean values... # Option 2: File Path file: "../use-cases/facility-support-analyzer/facility_prompt_sys.txt" inputs: ["question"] outputs: ["answer"] ``` -------------------------------- ### Set up Training Arguments for Fine-tuning Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb Configures the training arguments for fine-tuning the model. This includes setting the output directory, learning rate, and number of epochs. ```python from transformers import TrainingArguments, Trainer output_dir = "./cerebras-gpt-111m-finetuned" training_args = TrainingArguments( output_dir=output_dir, overwrite_output_dir=True, num_train_epochs=1, per_device_train_batch_size=4, save_steps=10_000, save_total_limit=2, learning_rate=2e-5, warmup_steps=500, logging_dir=f"{output_dir}/logs", logging_steps=50, fp16=True # Use mixed precision if supported ) ``` -------------------------------- ### Run PDO Migration Source: https://github.com/meta-llama/prompt-ops/blob/main/use-cases/ms-marco-pdo/MSMARCO_PDO_eval.ipynb This code snippet loads environment variables, including the OPENROUTER_API_KEY, and then executes the prompt-ops migrate command using a specified configuration file. Ensure your .env file and config.yaml are correctly set up. ```python from dotenv import load_dotenv load_dotenv("/Users/yuanchenwu/Downloads/prompt-ops/local.env") !prompt-ops migrate --config config.yaml --log-level INFO ``` -------------------------------- ### Run Migration with Configuration Source: https://github.com/meta-llama/prompt-ops/blob/main/docs/inference_providers.md Use this command to run a migration with a specified configuration file. Ensure the config file path is correct. ```bash prompt-ops migrate --config configs/your_config.yaml ``` -------------------------------- ### Evaluate Optimized Prompt with LLM Judge Source: https://github.com/meta-llama/prompt-ops/blob/main/use-cases/ms-marco-pdo/MSMARCO_PDO_eval.ipynb This function scores predictions against ground truth using a judge prompt and guided JSON decoding. It falls back to free-form decoding if JSON schema is unsupported. ```python def judge_scores(preds: list[str]): """Judge with guided JSON decoding (fallback to free-form if unsupported).""" import json as _json import numpy as _np scores = [] explanations = [] judge_prompts = [] for pred, r in zip(preds, rows): judge_prompts.append( JUDGE_PROMPT.format( question=r["question"], ground_truth=r["answer"], prediction=pred, ) ) response_format = { "type": "json_schema", "json_schema": { "name": "judge_score", "schema": { "type": "object", "properties": { "explanation": { "type": "string", "description": "Detailed reasoning based on the comparison", }, "score": { "type": "integer", "description": "Score from 1 to 5", "enum": [1, 2, 3, 4, 5], }, }, "required": ["explanation", "score"], "additionalProperties": False, }, "strict": True, }, } try: outs = model.generate_batch( judge_prompts, max_threads=10, temperature=0.0, response_format=response_format ) except Exception: outs = model.generate_batch( judge_prompts, max_threads=10, temperature=0.0 ) for o in outs: obj = _try_json_parse(o) score = obj.get("score", 0) exp = obj.get("explanation", "") try: score = float(score) except Exception: score = 0.0 scores.append(score) explanations.append(exp) return _np.array(scores), explanations ``` -------------------------------- ### Define Optimized Prompt String Source: https://github.com/meta-llama/prompt-ops/blob/main/use-cases/web-of-lies-pdo/PDO_web_of_lies_eval.ipynb Stores a detailed, optimized prompt string designed for logical reasoning tasks like Web of Lies. The prompt guides the model through analyzing statements, making assumptions, and determining truthfulness. ```python optimized_prompt='''Analyze the given statements about individuals telling the truth or lying, state assumptions about the truthfulness of each person based on the chain of statements, and determine the truthfulness of the last person mentioned in the question. For example, if Person A says Person B is lying and Person B says Person C is telling the truth, and it's given that Person A is lying, then Person B must be telling the truth, which means Person C is also telling the truth. Another example: if Person X claims Person Y is lying and Person Y says Person Z is truthful, but it's known that Person X is truthful, then Person Y is lying, and thus Person Z's truthfulness depends on the statement Person Y made about them. Apply this reasoning process to the given statements, as in the case where Person P says Person Q is lying, Person Q says Person R is telling the truth, and Person R says Person S is lying - determine the truthfulness of Person S based on the assumptions made about each person's statement.''' ``` -------------------------------- ### Load and Display Optimized Prompt Source: https://github.com/meta-llama/prompt-ops/blob/main/notebook/prompt_ops_101_cerebras.ipynb This Python code loads the latest optimized prompt from the results directory, extracts the system prompt, truncates few-shot examples for readability, and prepares it for HTML display. It requires glob, os, re, and IPython.display. ```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 result_files = glob.glob('my-cerebras-project/results/*.yaml') if result_files: latest_result = max(result_files, key=os.path.getctime) # Simple approach: just read and split 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] system_prompt = system_section.replace('system: |-', '').strip() # Truncate the examples system_prompt_truncated = truncate_examples(system_prompt) # Create HTML output with word wrapping (dark theme) html_output = f"""