> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# 用OPIK优化LLM提示
- URL: https://www.hubwiz.com/blog/prompt-optimization-with-opik/
- Published: 2026-01-17T02:43:46.000Z
- Updated: 2026-01-17T02:45:00.000Z
- Description: 使用 OPIK 和 MetaPromptOptimizer 为 LLM 代理自动优化和评估提示。
- Author: admin
- Tags: TOOL, PROMPT OPTIMIZATION, OPIK, METAPROMPTOPTIMIZER, #Import 2026-10-14 14:41

在大型语言模型快速发展的世界中，为大多数终端用户构建可靠 AI 代理时，编写完美提示仍然是最耗时的部分之一。程序员有奢侈条件，可以轻松使用多个库来迭代，并在多个提示变体上自动测量性能。

这很重要，因为即使措辞的小变化也可能在同一任务上使性能摆动 20-50%。如果您作为普通用户可以让 LLM 自动改进其自身的提示，而不必每次都支付昂贵的 API 调用费用，该怎么办？如果您可以用几行代码做到这一点，并轻松分析性能增长，该怎么办？

今天我们将探讨一个解决复杂推理任务的代理如何在几次自动迭代后从 34% 准确率提升到 97%，相对提升 184%。本文是一个完整的、适合初学者的指南，教您如何自己复制和使用此技术，包括完整设置、代码、优势、缺点以及何时应该（或不应该）使用它。

本文的完整代码可以从[这里](https://github.com/comet-ml/opik?ref=hubwiz.com)获取。

## 1、什么是自动提示优化？

自动提示优化（有时称为自动提示工程或 APE）将提示编写视为优化问题：

1. 从初始提示开始（甚至是一个平庸的）。
2. 在小规模标记示例任务数据集上运行它。
3. 使用评分函数（精确匹配、BLEU、自定义 LLM-as-judge 等）测量输出质量。
4. 使用 LLM 生成新的候选提示。
5. 测试最佳候选并重复直到性能停止改进。

诸如"使用无梯度方法的自动提示优化"（2023）之类的论文以及 DSPy、LangChain 的 PromptOptimizer 和现在的 OPIK 等工具已经使这对日常开发者变得实用。

## 2、为什么 OPIK + MetaPromptOptimizer 胜出？

- 100% 开源且免费（Apache 2.0）
- 使用 Ollama、LM Studio 或任何 OpenAI 兼容端点完全本地运行
- 内置跟踪仪表板（像 LangSmith 但免费）
- 优化的一类 API 简单
- 支持您可以编码的任何评估指标

## 3、环境设置（耗时 <10 分钟）

### 3.1 创建新环境

```
python -m venv opik-apo
source opik-apo/bin/activate   # Windows: opik-apo\Scripts\activate
pip install opik[all] datasets sentence-transformers
```

### 3.2 安装并运行本地 LLM（可选但推荐）

```
# Example with Ollama
ollama pull llama3.2:8b-instruct-qat
ollama serve
```

### 3.3 准备小型评估数据集

您只需要 20、100 个高质量示例。这是一个快速 GSM8K 风格的 JSONL 示例（保存为 `eval_data.jsonl`）：

```
{"question": "Janet's ducks lay 16 eggs per day. She eats 3 for breakfast, gives 8 to friends, and her bakery uses the rest. How many eggs does the bakery receive?", "answer": "5"}
{"question": "A store sells apples for $2 each or 6 for $10. How much do you save per apple by buying 6?", "answer": "0.33"}
```

### 3.4 完整工作优化脚本

```
import opik
from opik import track
from opik.opimization import MetaPromptOptimizer
from opik.opimization.evaluation_metrics import LevenshteinRatio
from opik.integrations.langchain import OpikTracer
from langchain_community.llms import Ollama
from langchain.prompts import PromptTemplate
import json

# 1. Initialize Opik (local by default)
opik_client = opik.Opik()

# 2. Load evaluation dataset
def load_dataset(path="eval_data.jsonl"):
    data = []
    with open(path) as f:
        for line in f:
            item = json.loads(line)
            data.append({"input": item["question"], "expected": item["answer"]})
    return data

eval_dataset = load_dataset()

# 3. Define your base prompt template
initial_prompt = """You are an expert assistant. Your task is answer questions accurately and concisely. Consider the context carefully before responding.

Question: {input}
Answer:"""

prompt_template = PromptTemplate.from_template(initial_prompt)

# 4. Create the LLM (local or OpenAI)
llm = Ollama(model="llama3.2:8b-instruct-qat", temperature=0.2)
# llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.2)  # for cloud

# 5. Define the chain you want to optimize
@track
def math_chain(question):
    prompt = prompt_template.format(input=question)
    response = llm.invoke(prompt)
    return response.strip()

# 6. Define evaluation function
def evaluation_function(task):
    expected = task["expected"]
    generated = math_chain(task["input"])
    score = LevenshteinRatio()(expected, generated)
    return score

# 7. Run the optimizer
optimizer = MetaPromptOptimizer(
    task="You are an expert at solving math word problems.",
    evaluation_dataset=eval_dataset,
    evaluation_function=evaluation_function,
    llm=llm,
    n_iterations=5,           # usually 3-7 is enough
    population_size=10
)

best_prompt = optimizer.run()
print("\n=== BEST PROMPT FOUND ===\n")

print(best_prompt)
```

运行它：

```
python optimize_prompt.py

```

5 次迭代后，您将在 [http://localhost:5173](http://localhost:5173/?ref=hubwiz.com) 看到仪表板，其中包含每个候选提示、其分数和最终获胜者。

## 4、优化器可能发现的示例

之前（34% 精确匹配）：

```
You are an expert assistant. Your task is answer questions accurately and concisely. Consider the context carefully before responding
```

之后（97% 精确匹配）：

![](https://www.hubwiz.com/blog/content/images/2026/01/image-493.png)

## 5、使用场景

这种方法的优势：

![](https://www.hubwiz.com/blog/content/images/2026/01/image-494.png)

- 显著性能提升（50-200% 相对改进常见）
- 完全可重现和可审计（每次迭代都记录）
- 本地工作 -> 初始设置后无令牌成本
- 无需梯度 -> 与任何黑箱 LLM 一起工作
- 以最小更改转移到新任务

缺点和限制：

- 需要良好的评估数据集（垃圾输入-垃圾输出）
- 本地 LLM 生成候选提示可能较慢
- 小数据集过度优化的风险（记忆）
- 优化器本身多次使用 LLM（每次运行 50-200 次调用）
- 可能产生过于冗长或奇怪的提示，这些提示有效但看起来丑陋

何时应该使用 MetaPromptOptimizer：

- 您有 20+ 个标记示例
- 您正在使用本地或廉价 LLM（Llama-3.2、Phi-3、Gemma-2 等）
- 您想要可重现的代理性能，而无需不断手动调整
- 您正在构建可靠性比延迟更重要的产品

何时应该跳过它

- 您的任务有 <10 个示例
- 您已经在使用 DSPy（它有自己的优化器）
- 您需要 <100ms 延迟且无法承受长提示
- 您正在微调模型本身（微调通常击败提示优化）

## 6、结束语

自动提示优化只是学术研究领域的日子已经一去不复返了。今天它是一个实用工具，可以轻松在您的机器上运行，与手动优化相比获得显著改进。使用 **OPIK 的** MetaPromptOptimizer，您可以轻松从一个平庸的提示开始，在不到 30 分钟内将其变成感觉像最先进的一次性代理的工具，并看到否则需要数周手动迭代的收益。

**从小开始：** 拿您已经有的任何代理，收集 30 个黄金示例，运行上面的脚本，并观察准确率图表的攀升。提示工程的未来不是手工编写更好的提示，而是构建为您编写更好提示的系统。

---

原文链接：[I Boosted My LLM Agent Performance By 184% Using OPIK](https://medium.com/coding-nexus/184-performance-boost-by-opik-automatic-prompt-optimization-af08f7a6d4a7?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处