A framework for automated LLM prompt optimization.
Project description
Prompt Forge
简体中文 | English
Prompt Forge is a Python framework designed for the automated optimization of prompts for large language models (LLMs). Inspired by the iterative training processes used in machine learning, Prompt Forge aims to systematically discover highly effective prompts based on evaluation metrics and datasets, particularly for scenarios involving API-only LLM access.
This framework helps users move beyond manual prompt tuning, which can be time-consuming and prone to suboptimal results, especially on large datasets. By treating prompt structures as architectures and using an LLM-based optimizer, Prompt Forge iteratively refines prompts to maximize performance according to user-defined metrics.
Features (Planned/Included)
- Structured Prompt Templates: Define prompts using composable sections (e.g., Role, Task, Constraints, Examples). Includes built-in templates (RCTCRE, APE, CRISPE, BROKE).
- Automated Optimization Loop: Mimics ML training with epochs and batches.
- Two-Step LLM-Based Optimizer: Utilizes a powerful LLM (OptimizerLLM) to first analyze feedback and generate optimization directions, then apply those directions to modify the prompt, using structured JSON communication.
- Configurable Update Granularity: Control the scope and intensity of prompt changes (from micro-adjustments to full rewrites).
- Extensible Components: Easily add custom datasets, LLM clients, evaluation metrics, prompt templates, and update strategies.
- Multi-Metric Evaluation: Define and weight multiple metrics to guide optimization towards complex goals, returning detailed results.
- API-Only Focus: Designed to work with LLMs accessible only via APIs.
Installation
pip install ptforge
Quick Start
import os
import logging
from ptforge import (
PromptOptimizer, OptimizationConfig, get_template, JsonlDataset,
ExactMatchAccuracy, Evaluator, LLMBasedUpdater, OpenAIClient, UpdateGranularity
)
# Configure logging
logging.basicConfig(level=logging.INFO)
# Ensure API keys are set (e.g., via environment variables)
# os.environ["OPENAI_API_KEY"] = "your-key"
# os.environ["OPENAI_API_BASE"] = "your-base-url-if-needed" # Optional
try:
# 1. Setup Components
target_llm = OpenAIClient(model="gpt-3.5-turbo") # Or your preferred model/client
optimizer_llm = OpenAIClient(model="gpt-4o") # Powerful model recommended for optimization
dataset = JsonlDataset("examples/dummy_data.jsonl") # Path relative to execution
initial_template = get_template(
"RCTCRE",
initial_values={
"role": "Assistant answering questions.",
"task": "Answer concisely: {{input}}",
"context": "General knowledge question.",
"constraints": None,
"response_format": "Plain text.",
"examples": None,
},
optimizable_sections={"role", "task", "constraints", "context", "response_format"}
)
evaluator = Evaluator(metrics=[(ExactMatchAccuracy(case_sensitive=False), 1.0)])
updater = LLMBasedUpdater(
optimizer_llm_client=optimizer_llm,
task_description="Answer general knowledge questions concisely and accurately."
)
config = OptimizationConfig(epochs=2, batch_size=4, update_granularity=UpdateGranularity.SECTION_REPHRASE)
# 2. Initialize Optimizer
optimizer = PromptOptimizer(target_llm, initial_template, dataset, evaluator, updater, config)
# 3. Run Optimization
# Use context managers if your client supports them (OpenAIClient does)
with target_llm, optimizer_llm:
best_template, result = optimizer.optimize()
# 4. Use Results
print(f"Optimization finished. Best score: {result.best_score}")
print("Best template sections:")
for section in best_template.list_sections():
print(f"--- {section} ---")
print(best_template.get_section(section) or "(Empty/None)")
except Exception as e:
logging.error(f"Optimization failed: {e}", exc_info=True)
Contributing
Contributions are welcome! Please refer to the contributing guidelines.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ptforge-0.1.1.tar.gz.
File metadata
- Download URL: ptforge-0.1.1.tar.gz
- Upload date:
- Size: 39.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
67803acd51df8943d8f4864d92f1e54ad292e24e1a477768d49272bdb44df833
|
|
| MD5 |
781495560c51f3dc8e631779c1303167
|
|
| BLAKE2b-256 |
01b2cbeda9bc0a6e8507bf9d31f32f008dfef445779057a74869c3b0e52f1742
|
File details
Details for the file ptforge-0.1.1-py3-none-any.whl.
File metadata
- Download URL: ptforge-0.1.1-py3-none-any.whl
- Upload date:
- Size: 48.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
64bf121b9dbb1492130c76e91beb81f70be899e775780fee76799c45bc684df6
|
|
| MD5 |
fbb138bd069620062c6f3457c71ff43c
|
|
| BLAKE2b-256 |
f5a93f4bde21cb76f06b9bae776d1861ebe7248e1d4be80355f948e584f5098d
|