Arize Prompt Optimization

Arize Prompt Optimization

Improves and debugs LLM prompts by pulling them from production traces, gathering evaluation signal and running a data-driven optimization loop with the ax CLI.

Skill files3 files

references/

SKILL.md458 lines
1
---
2
name: arize-prompt-optimization
3
description: Optimizes, improves, and debugs LLM prompts using production trace data, evaluations, and annotations. Extracts prompts from spans, gathers performance signal, and runs a data-driven optimization loop using the ax CLI. Use when the user mentions optimize prompt, improve prompt, make AI respond better, improve output quality, prompt engineering, prompt tuning, or system prompt improvement.
4
metadata:
5
author: arize
6
version: "1.0"
7
compatibility: Requires the ax CLI and a configured Arize profile.
8
---
9
10
# Arize Prompt Optimization Skill
11
12
> **`SPACE`** — All `--space` flags and the `ARIZE_SPACE` env var accept a space **name** (e.g., `my-workspace`) or a base64 space **ID** (e.g., `U3BhY2U6...`). Find yours with `ax spaces list`.
13
14
## Concepts
15
16
### Where Prompts Live in Trace Data
17
18
LLM applications emit spans following OpenInference semantic conventions. Prompts are stored in different span attributes depending on the span kind and instrumentation:
19
20
| Column | What it contains | When to use |
21
|--------|-----------------|-------------|
22
| `attributes.llm.input_messages` | Structured chat messages (system, user, assistant, tool) in role-based format | **Primary source** for chat-based LLM prompts |
23
| `attributes.llm.input_messages.roles` | Array of roles: `system`, `user`, `assistant`, `tool` | Extract individual message roles |
24
| `attributes.llm.input_messages.contents` | Array of message content strings | Extract message text |
25
| `attributes.input.value` | Serialized prompt or user question (generic, all span kinds) | Fallback when structured messages are not available |
26
| `attributes.llm.prompt_template.template` | Template with `{variable}` placeholders (e.g., `"Answer {question} using {context}"`) | When the app uses prompt templates |
27
| `attributes.llm.prompt_template.variables` | Template variable values (JSON object) | See what values were substituted into the template |
28
| `attributes.output.value` | Model response text | See what the LLM produced |
29
| `attributes.llm.output_messages` | Structured model output (including tool calls) | Inspect tool-calling responses |
30
31
### Finding Prompts by Span Kind
32
33
- **LLM span** (`attributes.openinference.span.kind = 'LLM'`): Check `attributes.llm.input_messages` for structured chat messages, OR `attributes.input.value` for a serialized prompt. Check `attributes.llm.prompt_template.template` for the template.
34
- **Chain/Agent span**: `attributes.input.value` contains the user's question. The actual LLM prompt lives on **child LLM spans** -- navigate down the trace tree.
35
- **Tool span**: `attributes.input.value` has tool input, `attributes.output.value` has tool result. Not typically where prompts live.
36
37
### Performance Signal Columns
38
39
These columns carry the feedback data used for optimization:
40
41
| Column pattern | Source | What it tells you |
42
|---------------|--------|-------------------|
43
| `annotation.<name>.label` | Human reviewers | Categorical grade (e.g., `correct`, `incorrect`, `partial`) |
44
| `annotation.<name>.score` | Human reviewers | Numeric quality score (e.g., 0.0 - 1.0) |
45
| `annotation.<name>.text` | Human reviewers | Freeform explanation of the grade |
46
| `eval.<name>.label` | LLM-as-judge evals | Automated categorical assessment |
47
| `eval.<name>.score` | LLM-as-judge evals | Automated numeric score |
48
| `eval.<name>.explanation` | LLM-as-judge evals | Why the eval gave that score -- **most valuable for optimization** |
49
| `attributes.input.value` | Trace data | What went into the LLM |
50
| `attributes.output.value` | Trace data | What the LLM produced |
51
| `{experiment_name}.output` | Experiment runs | Output from a specific experiment |
52
53
## Prerequisites
54
55
Proceed directly with the task — run the `ax` command you need. Do NOT check versions, env vars, or profiles upfront.
56
57
If an `ax` command fails, troubleshoot based on the error:
58
- `command not found` or version error → see references/ax-setup.md
59
- `401 Unauthorized` / missing API key → run `ax profiles show` to inspect the current profile. If the profile is missing or the API key is wrong, follow references/ax-profiles.md to create/update it. If the user doesn't have their key, direct them to https://app.arize.com/admin > API Keys
60
- Space unknown → run `ax spaces list` to pick by name, or ask the user
61
- Project unclear → ask the user, or run `ax projects list -o json --limit 100` and present as selectable options
62
- LLM provider call fails (missing OPENAI_API_KEY / ANTHROPIC_API_KEY) → run `ax ai-integrations list --space SPACE` to check for platform-managed credentials. If none exist, ask the user to provide the key or create an integration via the **arize-ai-provider-integration** skill
63
- **Security:** Never read `.env` files or search the filesystem for credentials. Use `ax profiles` for Arize credentials and `ax ai-integrations` for LLM provider keys. If credentials are not available through these channels, ask the user.
64
65
## Phase 1: Extract the Current Prompt
66
67
### Find LLM spans containing prompts
68
69
```bash
70
# Sample LLM spans (where prompts live)
71
ax spans export PROJECT --filter "attributes.openinference.span.kind = 'LLM'" -l 10 --stdout
72
73
# Filter by model
74
ax spans export PROJECT --filter "attributes.llm.model_name = 'gpt-4o'" -l 10 --stdout
75
76
# Filter by span name (e.g., a specific LLM call)
77
ax spans export PROJECT --filter "name = 'ChatCompletion'" -l 10 --stdout
78
```
79
80
### Export a trace to inspect prompt structure
81
82
```bash
83
# Export all spans in a trace
84
ax spans export PROJECT --trace-id TRACE_ID
85
86
# Export a single span
87
ax spans export PROJECT --span-id SPAN_ID
88
```
89
90
### Extract prompts from exported JSON
91
92
```bash
93
# Extract structured chat messages (system + user + assistant)
94
jq '.[0] | {
95
messages: .attributes.llm.input_messages,
96
model: .attributes.llm.model_name
97
}' trace_*/spans.json
98
99
# Extract the system prompt specifically
100
jq '[.[] | select(.attributes.llm.input_messages.roles[]? == "system")] | .[0].attributes.llm.input_messages' trace_*/spans.json
101
102
# Extract prompt template and variables
103
jq '.[0].attributes.llm.prompt_template' trace_*/spans.json
104
105
# Extract from input.value (fallback for non-structured prompts)
106
jq '.[0].attributes.input.value' trace_*/spans.json
107
```
108
109
### Reconstruct the prompt as messages
110
111
Once you have the span data, reconstruct the prompt as a messages array:
112
113
```json
114
[
115
{"role": "system", "content": "You are a helpful assistant that..."},
116
{"role": "user", "content": "Given {input}, answer the question: {question}"}
117
]
118
```
119
120
If the span has `attributes.llm.prompt_template.template`, the prompt uses variables. Preserve these placeholders (`{variable}` or `{{variable}}`) -- they are substituted at runtime.
121
122
## Phase 2: Gather Performance Data
123
124
### From traces (production feedback)
125
126
```bash
127
# Find error spans -- these indicate prompt failures
128
ax spans export PROJECT \
129
--filter "status_code = 'ERROR' AND attributes.openinference.span.kind = 'LLM'" \
130
-l 20 --stdout
131
132
# Find spans with low eval scores
133
ax spans export PROJECT \
134
--filter "annotation.correctness.label = 'incorrect'" \
135
-l 20 --stdout
136
137
# Find spans with high latency (may indicate overly complex prompts)
138
ax spans export PROJECT \
139
--filter "attributes.openinference.span.kind = 'LLM' AND latency_ms > 10000" \
140
-l 20 --stdout
141
142
# Export error traces for detailed inspection
143
ax spans export PROJECT --trace-id TRACE_ID
144
```
145
146
### From datasets and experiments
147
148
```bash
149
# Export a dataset (ground truth examples)
150
ax datasets export DATASET_NAME --space SPACE
151
# -> dataset_*/examples.json
152
153
# Export experiment results (what the LLM produced)
154
ax experiments export EXPERIMENT_NAME --dataset DATASET_NAME --space SPACE
155
# -> experiment_*/runs.json
156
```
157
158
### Merge dataset + experiment for analysis
159
160
Join the two files by `example_id` to see inputs alongside outputs and evaluations:
161
162
```bash
163
# Count examples and runs
164
jq 'length' dataset_*/examples.json
165
jq 'length' experiment_*/runs.json
166
167
# View a single joined record
168
jq -s '
169
.[0] as $dataset |
170
.[1][0] as $run |
171
($dataset[] | select(.id == $run.example_id)) as $example |
172
{
173
input: $example,
174
output: $run.output,
175
evaluations: $run.evaluations
176
}
177
' dataset_*/examples.json experiment_*/runs.json
178
179
# Find failed examples (where eval score < threshold)
180
jq '[.[] | select(.evaluations.correctness.score < 0.5)]' experiment_*/runs.json
181
```
182
183
### Identify what to optimize
184
185
Look for patterns across failures:
186
187
1. **Compare outputs to ground truth**: Where does the LLM output differ from expected?
188
2. **Read eval explanations**: `eval.*.explanation` tells you WHY something failed
189
3. **Check annotation text**: Human feedback describes specific issues
190
4. **Look for verbosity mismatches**: If outputs are too long/short vs ground truth
191
5. **Check format compliance**: Are outputs in the expected format?
192
193
## Phase 3: Optimize the Prompt
194
195
### The Optimization Meta-Prompt
196
197
Use this template to generate an improved version of the prompt. Fill in the three placeholders and send it to your LLM (GPT-4o, Claude, etc.):
198
199
````
200
You are an expert in prompt optimization. Given the original baseline prompt
201
and the associated performance data (inputs, outputs, evaluation labels, and
202
explanations), generate a revised version that improves results.
203
204
ORIGINAL BASELINE PROMPT
205
========================
206
207
{PASTE_ORIGINAL_PROMPT_HERE}
208
209
========================
210
211
PERFORMANCE DATA
212
================
213
214
The following records show how the current prompt performed. Each record
215
includes the input, the LLM output, and evaluation feedback:
216
217
{PASTE_RECORDS_HERE}
218
219
================
220
221
HOW TO USE THIS DATA
222
223
1. Compare outputs: Look at what the LLM generated vs what was expected
224
2. Review eval scores: Check which examples scored poorly and why
225
3. Examine annotations: Human feedback shows what worked and what didn't
226
4. Identify patterns: Look for common issues across multiple examples
227
5. Focus on failures: The rows where the output DIFFERS from the expected
228
value are the ones that need fixing
229
230
ALIGNMENT STRATEGY
231
232
- If outputs have extra text or reasoning not present in the ground truth,
233
remove instructions that encourage explanation or verbose reasoning
234
- If outputs are missing information, add instructions to include it
235
- If outputs are in the wrong format, add explicit format instructions
236
- Focus on the rows where the output differs from the target -- these are
237
the failures to fix
238
239
RULES
240
241
Maintain Structure:
242
- Use the same template variables as the current prompt ({var} or {{var}})
243
- Don't change sections that are already working
244
- Preserve the exact return format instructions from the original prompt
245
246
Avoid Overfitting:
247
- DO NOT copy examples verbatim into the prompt
248
- DO NOT quote specific test data outputs exactly
249
- INSTEAD: Extract the ESSENCE of what makes good vs bad outputs
250
- INSTEAD: Add general guidelines and principles
251
- INSTEAD: If adding few-shot examples, create SYNTHETIC examples that
252
demonstrate the principle, not real data from above
253
254
Goal: Create a prompt that generalizes well to new inputs, not one that
255
memorizes the test data.
256
257
OUTPUT FORMAT
258
259
Return the revised prompt as a JSON array of messages:
260
261
[
262
{"role": "system", "content": "..."},
263
{"role": "user", "content": "..."}
264
]
265
266
Also provide a brief reasoning section (bulleted list) explaining:
267
- What problems you found
268
- How the revised prompt addresses each one
269
````
270
271
### Preparing the performance data
272
273
Format the records as a JSON array before pasting into the template:
274
275
```bash
276
# From dataset + experiment: join and select relevant columns
277
jq -s '
278
.[0] as $ds |
279
[.[1][] | . as $run |
280
($ds[] | select(.id == $run.example_id)) as $ex |
281
{
282
input: $ex.input,
283
expected: $ex.expected_output,
284
actual_output: $run.output,
285
eval_score: $run.evaluations.correctness.score,
286
eval_label: $run.evaluations.correctness.label,
287
eval_explanation: $run.evaluations.correctness.explanation
288
}
289
]
290
' dataset_*/examples.json experiment_*/runs.json
291
292
# From exported spans: extract input/output pairs with annotations
293
jq '[.[] | select(.attributes.openinference.span.kind == "LLM") | {
294
input: .attributes.input.value,
295
output: .attributes.output.value,
296
status: .status_code,
297
model: .attributes.llm.model_name
298
}]' trace_*/spans.json
299
```
300
301
### Applying the revised prompt
302
303
After the LLM returns the revised messages array:
304
305
1. Compare the original and revised prompts side by side
306
2. Verify all template variables are preserved
307
3. Check that format instructions are intact
308
4. Test on a few examples before full deployment
309
310
## Phase 4: Iterate
311
312
### The optimization loop
313
314
```
315
1. Extract prompt -> Phase 1 (once)
316
2. Run experiment -> ax experiments create ...
317
3. Export results -> ax experiments export EXPERIMENT_NAME --dataset DATASET_NAME --space SPACE
318
4. Analyze failures -> jq to find low scores
319
5. Run meta-prompt -> Phase 3 with new failure data
320
6. Apply revised prompt
321
7. Repeat from step 2
322
```
323
324
### Measure improvement
325
326
```bash
327
# Compare scores across experiments
328
# Experiment A (baseline)
329
jq '[.[] | .evaluations.correctness.score] | add / length' experiment_a/runs.json
330
331
# Experiment B (optimized)
332
jq '[.[] | .evaluations.correctness.score] | add / length' experiment_b/runs.json
333
334
# Find examples that flipped from fail to pass
335
jq -s '
336
[.[0][] | select(.evaluations.correctness.label == "incorrect")] as $fails |
337
[.[1][] | select(.evaluations.correctness.label == "correct") |
338
select(.example_id as $id | $fails | any(.example_id == $id))
339
] | length
340
' experiment_a/runs.json experiment_b/runs.json
341
```
342
343
### A/B compare two prompts
344
345
1. Create two experiments against the same dataset, each using a different prompt version
346
2. Export both: `ax experiments export EXP_A` and `ax experiments export EXP_B`
347
3. Compare average scores, failure rates, and specific example flips
348
4. Check for regressions -- examples that passed with prompt A but fail with prompt B
349
350
## Prompt Engineering Best Practices
351
352
Apply these when writing or revising prompts:
353
354
| Technique | When to apply | Example |
355
|-----------|--------------|---------|
356
| Clear, detailed instructions | Output is vague or off-topic | "Classify the sentiment as exactly one of: positive, negative, neutral" |
357
| Instructions at the beginning | Model ignores later instructions | Put the task description before examples |
358
| Step-by-step breakdowns | Complex multi-step processes | "First extract entities, then classify each, then summarize" |
359
| Specific personas | Need consistent style/tone | "You are a senior financial analyst writing for institutional investors" |
360
| Delimiter tokens | Sections blend together | Use `---`, `###`, or XML tags to separate input from instructions |
361
| Few-shot examples | Output format needs clarification | Show 2-3 synthetic input/output pairs |
362
| Output length specifications | Responses are too long or short | "Respond in exactly 2-3 sentences" |
363
| Reasoning instructions | Accuracy is critical | "Think step by step before answering" |
364
| "I don't know" guidelines | Hallucination is a risk | "If the answer is not in the provided context, say 'I don't have enough information'" |
365
366
### Variable preservation
367
368
When optimizing prompts that use template variables:
369
370
- **Single braces** (`{variable}`): Python f-string / Jinja style. Most common in Arize.
371
- **Double braces** (`{{variable}}`): Mustache style. Used when the framework requires it.
372
- Never add or remove variable placeholders during optimization
373
- Never rename variables -- the runtime substitution depends on exact names
374
- If adding few-shot examples, use literal values, not variable placeholders
375
376
## Workflows
377
378
### Optimize a prompt from a failing trace
379
380
1. Find failing traces:
381
```bash
382
ax traces list PROJECT --filter "status_code = 'ERROR'" --limit 5
383
```
384
2. Export the trace:
385
```bash
386
ax spans export PROJECT --trace-id TRACE_ID
387
```
388
3. Extract the prompt from the LLM span:
389
```bash
390
jq '[.[] | select(.attributes.openinference.span.kind == "LLM")][0] | {
391
messages: .attributes.llm.input_messages,
392
template: .attributes.llm.prompt_template,
393
output: .attributes.output.value,
394
error: .attributes.exception.message
395
}' trace_*/spans.json
396
```
397
4. Identify what failed from the error message or output
398
5. Fill in the optimization meta-prompt (Phase 3) with the prompt and error context
399
6. Apply the revised prompt
400
401
### Optimize using a dataset and experiment
402
403
1. Find the dataset and experiment:
404
```bash
405
ax datasets list --space SPACE
406
ax experiments list --dataset DATASET_NAME --space SPACE
407
```
408
2. Export both:
409
```bash
410
ax datasets export DATASET_NAME --space SPACE
411
ax experiments export EXPERIMENT_NAME --dataset DATASET_NAME --space SPACE
412
```
413
3. Prepare the joined data for the meta-prompt
414
4. Run the optimization meta-prompt
415
5. Create a new experiment with the revised prompt to measure improvement
416
417
### Debug a prompt that produces wrong format
418
419
1. Export spans where the output format is wrong:
420
```bash
421
ax spans export PROJECT \
422
--filter "attributes.openinference.span.kind = 'LLM' AND annotation.format.label = 'incorrect'" \
423
-l 10 --stdout > bad_format.json
424
```
425
2. Look at what the LLM is producing vs what was expected
426
3. Add explicit format instructions to the prompt (JSON schema, examples, delimiters)
427
4. Common fix: add a few-shot example showing the exact desired output format
428
429
### Reduce hallucination in a RAG prompt
430
431
1. Find traces where the model hallucinated:
432
```bash
433
ax spans export PROJECT \
434
--filter "annotation.faithfulness.label = 'unfaithful'" \
435
-l 20 --stdout
436
```
437
2. Export and inspect the retriever + LLM spans together:
438
```bash
439
ax spans export PROJECT --trace-id TRACE_ID
440
jq '[.[] | {kind: .attributes.openinference.span.kind, name, input: .attributes.input.value, output: .attributes.output.value}]' trace_*/spans.json
441
```
442
3. Check if the retrieved context actually contained the answer
443
4. Add grounding instructions to the system prompt: "Only use information from the provided context. If the answer is not in the context, say so."
444
445
## Troubleshooting
446
447
| Problem | Solution |
448
|---------|----------|
449
| `ax: command not found` | See references/ax-setup.md |
450
| `No profile found` | No profile is configured. See references/ax-profiles.md to create one. |
451
| No `input_messages` on span | Check span kind -- Chain/Agent spans store prompts on child LLM spans, not on themselves |
452
| Prompt template is `null` | Not all instrumentations emit `prompt_template`. Use `input_messages` or `input.value` instead |
453
| Variables lost after optimization | Verify the revised prompt preserves all `{var}` placeholders from the original |
454
| Optimization makes things worse | Check for overfitting -- the meta-prompt may have memorized test data. Ensure few-shot examples are synthetic |
455
| No eval/annotation columns | Run evaluations first (via Arize UI or SDK), then re-export |
456
| Experiment output column not found | The column name is `{experiment_name}.output` -- check exact experiment name via `ax experiments get` |
457
| `jq` errors on span JSON | Ensure you're targeting the correct file path (e.g., `trace_*/spans.json`) |
458

© arize · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,335 prompts

More by @OpenSourceBuffGuy

See all
Young woman packs gym bag in bedroom prompt image

Young woman packs gym bag in bedroom

Generates a 30-second early-2000s Japanese gym-day vlog in MiniDV camcorder style, with second-by-second beats and a locked character, era and continuity.

video-prompt, vlog, home-video, timed-beats, character-consistency, reference-image, handheld, multi-shot, photorealistic, japan, woman, fitness, guardrails, seedance, candid, long-form, vintage, tracking-shot

Woman stares blankly into open refrigerator prompt image

Woman stares blankly into open refrigerator

Generates a 30-second, 12-shot candid home-video montage of a woman in her messy apartment with her dog, with Korean dialogue, handheld drift and detailed ambient sound.

video-prompt, reference-image, face-reference, character-consistency, timed-beats, multi-shot, handheld, home-video, film-grain, candid, lip-sync, animals, pet-care, natural-light, camera-movement, humorous, casual, woman, korea, structured-output, long-form, vlog, cozy

Woman walks golden retriever in analog vlog prompt image

Woman walks golden retriever in analog vlog

Generates a handheld analog-style morning vlog of a woman walking her golden retriever, with scripted spoken lines and camera placement notes.

video-prompt, seedance, vlog, handheld, film-grain, lip-sync, home-video, pov, selfie, camera-movement, animals, pet-care, cozy, candid, natural-light, golden-hour, woman, structured-output, for-content-creators, long-form, casual, character-design, short-film

Reviews

Loading reviews…

Discussion

Loading comments…