prompt-ops

repository·main·Indexed 21 days ago

https://github.com/meta-llama/prompt-ops

A Python-based optimization framework for automatically refining system prompts for Llama models using data-driven methods like the Prompt Duel Optimizer (PDO). It features a YAML-based configuration system for managing data processing via DatasetAdapters, prompt optimization strategies (basic, llama, advanced), and evaluation through custom or built-in metrics such as ExactMatchMetric and StandardJSONMetric.

Tokens
38.4K
Snippets
132
Records
162
Agent score
73%

What's inside prompt-ops

  1. What is prompt-ops?

    main
    prompt-ops is a Python package designed to automatically optimize prompts for Llama models. It takes existing system prompts (often designed for other LLMs) and transforms them into prompts optimized for Llama's specific architecture, improving performance and reliability through template-based optimization and data-driven evaluation.
  2. What is PDO (Prompt Duel Optimizer)?

    main

    PDO (Prompt Duel Optimizer) is a dueling bandit optimization strategy designed to evolve and select high-performing prompts. It operates through the following lifecycle:

    1. Prompt Pool Management: Maintains a pool of different prompt variations.
    2. Dueling: Runs "duels" between prompts to compare their performance on a specific task.
    3. Thompson Sampling: Uses Thompson sampling to intelligently select which prompts to test in subsequent rounds.
    4. Evolution: Generates new prompt variations from the top-performing prompts in the pool.
    5. Ranking: Uses the Copeland ranking method to determine the final best prompts.

    This strategy is useful for tasks requiring complex reasoning, such as the "Web of Lies" logical reasoning task, where the goal is to find the most effective instruction set to improve model accuracy.

  3. Understand the prompt-ops project structure

    main

    A standard project created via prompt-ops create follows this directory structure:

    • .env: Environment variables (e.g., API keys).
    • README.md: Project documentation.
    • config.yaml: Configuration for the optimization task.
    • data/dataset.json: The dataset used for evaluation.
    • prompts/prompt.txt: The system prompt to be optimized.
    • results/: Directory where optimized prompts and performance metrics are saved.
  4. Dataset format for prompt-ops

    main

    The dataset must be in JSON format. Each entry requires a fields object containing the input (e.g., a customer message) and an answer field containing the expected ground truth JSON output.

    {
      "fields": {
        "input": "Subject: Urgent HVAC Repair Needed\n\nHi ProCare Support Team..."
      },
      "answer": "{\"categories\": {\"routine_maintenance_requests\": false, ...}, \"sentiment\": \"positive\", \"urgency\": \"high\"}"
    }
  5. Prepare your dataset for optimization

    main

    Optimization requires a JSON file containing query-response pairs (at least 50 examples recommended).

    Standard Format

    If your data follows this structure, prompt-ops will automatically use the StandardJSONAdapter:

    [
        {
            "question": "Your input query here",
            "answer": "Expected response here"
        },
        {
            "question": "Another input query",
            "answer": "Another expected response"
        }
    ]

    Custom Formats

    If your data does not match this structure, you must create a custom dataset adapter by extending the DatasetAdapter class.

    [
        {
            "question": "Your input query here",
            "answer": "Expected response here"
        }
    ]
  6. Configure inference providers in prompt-ops

    main

    You can switch between different LLM backends by modifying the model section in your YAML configuration files. prompt-ops uses LiteLLM as a unified API client, which automatically detects the provider based on the model name prefix (e.g., openrouter/, groq/, together_ai/) and maps it to the corresponding environment variable.

    Basic model configuration structure:

    model:
      name: "provider/model-name"
      temperature: 0.0
      max_tokens: 4096
    model:
      name: "openrouter/meta-llama/llama-3.1-8b-instruct"
      temperature: 0.0
      max_tokens: 40960
  7. Select a Dataset Adapter

    main

    Dataset adapters determine how prompt-ops reads your input data. Choose an adapter based on your data structure:

    Adapter TypeDataset Input FormatWhen to Use
    StandardJSONAdapter[{"question": "...", "answer": "..."}]Most common datasets with question and answer fields
    RAGJSONAdapter[{"question": "...", "context": "...", "answer": "..."}]Datasets that include retrieval contexts
    Custom AdapterAny specialized formatWhen existing adapters don't meet your needs
  8. Select Evaluation Metrics

    main

    Metrics are used to compare model predictions against ground truth. Select a metric based on your expected output format:

    Metric TypeUse CaseExpected FormatWhen to Use
    ExactMatchMetricSimple string matchingPlain text stringsWhen you need exact string matching between prediction and ground truth
    StandardJSONMetricStructured JSON evaluationJSON objects or stringsWhen evaluating structured JSON responses with specific fields to compare
    Custom MetricSpecialized evaluation needsAny custom formatWhen existing metrics don't meet your evaluation needs
  9. Project structure for MS MARCO PDO use case

    main

    The ms-marco-pdo directory follows this structure:

    • config.yaml: Contains the PDO optimization configuration.
    • prompts/prompt.txt: The initial prompt template used to seed the pool.
    • dataset/ms_marco_description.json: The MS MARCO-style QA samples used for evaluation.
    • results/: Directory where optimization results (rankings, best prompts, etc.) are generated.
    • MSMARCO_PDO_eval.ipynb: An optional notebook for evaluating and analyzing the optimization results.
    ms-marco-pdo/
    ├── config.yaml                 # PDO optimization configuration
    ├── prompts/
    │   └── prompt.txt             # Initial prompt template
    ├── dataset/
    │   └── ms_marco_description.json  # MS MARCO-style QA samples
    ├── results/                   # Optimization results (generated)
    └── MSMARCO_PDO_eval.ipynb     # Optional: evaluation/analysis notebook
  10. Configure inference providers via LiteLLM

    main

    prompt-ops uses LiteLLM as a unified API client. It automatically detects the provider from the model name string. For example:

    • openrouter/model-name requires OPENROUTER_API_KEY.
    • groq/model-name requires GROQ_API_KEY.

    Supported providers include OpenRouter, vLLM (local), and NVIDIA NIMs.

  11. Choose the right evaluation metric

    main

    Select a metric based on your data format and evaluation requirements:

    Metric TypeUse CaseExpected FormatWhen to Use
    ExactMatchMetricSimple string matchingPlain text stringsWhen you need exact string matching between prediction and ground truth
    StandardJSONMetricStructured JSON evaluationJSON objects or stringsWhen evaluating structured JSON responses with specific fields to compare
    Custom MetricSpecialized evaluation needsAny custom formatWhen existing metrics don't meet your evaluation needs