Skip to content

Commit 89ae418

Browse files
authored
Merge pull request #5 from skewlight/podata_pr
feat: Support Data-Driven Prompt Optimizer
2 parents 22600f8 + e176b99 commit 89ae418

18 files changed

Lines changed: 2831 additions & 118 deletions

GEMINI.md

Lines changed: 169 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,29 @@
1-
# Vertex Prompt Management Extension
1+
# Vertex AI Gemini CLI Extension
22

3-
This extension provides tools to manage prompts in Vertex AI.
3+
This extension provides tools to manage prompts and use the data-driven prompt
4+
optimization in Vertex AI directly from the Gemini CLI.
45

5-
Whenever anyone wants to read or write vertex prompts, you must use the vertex
6-
management tools.
7-
8-
The available tools are:
6+
## Available Tools
97

8+
### Prompt Management Tools
109
- `create_prompt`: To save or create new prompts.
1110
- `read_prompt`: To retrieve existing prompts by ID or display name.
1211
- `update_prompt`: To modify existing prompts.
1312
- `delete_prompt`: To remove prompts.
1413
- `list_prompts`: To search and list prompts, useful for finding IDs.
1514

15+
### Data-Driven Optimization Tools
16+
- `run_data_driven_optimize`: Starts a data-driven prompt optimization job on
17+
Vertex AI using a configuration file stored in GCS.
18+
- `analyze_data_driven_optimize_results`: Analyzes the output of a Data-Driven
19+
Optimize job to identify trends and best-performing candidates.
20+
- `generate_html_report`: Generates a comprehensive HTML report with
21+
visualizations to help you understand optimization performance.
22+
- `write_data_driven_optimize_config`: Constructs and uploads a new JSON
23+
configuration for optimization jobs, incorporating suggested tuning parameters.
24+
25+
---
26+
1627
## Detailed Instructions for `create_prompt` Parameters
1728

1829
When using `tools.create_prompt`, pay special attention to how the following
@@ -260,4 +271,155 @@ When using `tools.update_prompt`, the following arguments are sourced. Note that
260271
If any tool call fails with an error indicating a project permission issue (e.g., "Permission denied on project 'project-id'"), you must:
261272
1. Inform the user about the permission error.
262273
2. Ask the user to provide a valid project ID.
263-
3. Retry the original tool call, adding the `project_id` parameter with the user-provided value.
274+
3. Retry the original tool call, adding the `project_id` parameter with the user-provided value.
275+
276+
---
277+
278+
## Data-Driven Prompt Optimizer Overall Guide
279+
280+
For a general understanding of Data-Driven Prompt Optimizer and its
281+
capabilities, please
282+
refer to the Data-Driven Optimize Overall Guide:
283+
284+
@./src/vertex/prompt_optimizer/docs/data_driven_optimize_overall_guide.md
285+
286+
## Optimization Tool Details
287+
288+
The extension provides a suite of tools to parse and analyze the output of a
289+
Data-Driven Prompt Optimizer job. The `output_path` for these tools stores
290+
the outputs
291+
of a run and can be a GCS path or a local directory. While the Data-Driven
292+
Optimize job currently only outputs to GCS, results can be copied to the local
293+
file system for analysis.
294+
295+
1. `analyze_data_driven_optimize_results(output_path: str, top_n_prompts:
296+
int = 10, analysis_data_path: str = None)`: Analyzes results and
297+
returns a JSON object containing the analysis data summary. If
298+
`analysis_data_path` is provided, it saves the results into three separate
299+
files to avoid size limits and returns a **minimal summary** with
300+
file paths
301+
and the best prompt score. The three files are:
302+
- `{analysis_data_path}`: Core metadata (config, comparison, best
303+
prompt).
304+
- `*_metrics.json`: Detailed metrics for all candidates (no prompt text).
305+
- `*_prompts.json`: Mapping of top candidates' keys to full prompt texts.
306+
307+
2. `generate_html_report(analysis_data: Dict[str, Any] =
308+
None, report_path: str = "data_driven_optimize_analysis_report.html",
309+
suggested_config_data: Dict[str, Any] = None, top_n_prompts: int = 10,
310+
analysis_data_path: str = None)`: Generates a comprehensive HTML report. If
311+
`analysis_data_path` is provided, it automatically loads and re-joins the
312+
metadata, metrics, and prompts from the three split files.
313+
314+
3. `write_data_driven_optimize_config`: Construct and
315+
write to GCS a new JSON configuration file for Data-Driven Optimize job
316+
using a dict of parameters (including `prompt_optimizer_method` and
317+
`target_model_endpoint_url` for Nano) and optionally an path to an
318+
existing config to make modifications on top of.
319+
320+
4. `run_data_driven_optimize`: Starts a data-driven prompt optimization job on
321+
Vertex AI using the SDK's `client.prompts.launch_optimization_job` method.
322+
Supports specifying the `prompt_optimizer_method`. The `config_gcs_path`
323+
must point to a JSON file in GCS.
324+
325+
## Optimization Method Considerations
326+
- **VAPO**: Standard prompt optimization. The `batch_size` parameter
327+
will be automatically removed during configuration generation to ensure SDK
328+
compatibility.
329+
- **OPTIMIZATION_TARGET_GEMINI_NANO**: Specialized target for Gemini Nano.
330+
Requires a `target_model_endpoint_url`. Supports `batch_size`.
331+
332+
## Optimization Tuning Considerations
333+
334+
Only suggest modifications for the parameters explicitly listed as tunable in
335+
the Data-Driven Optimize Tuning Guide:
336+
337+
@./src/vertex/prompt_optimizer/docs/data_driven_optimize_tuning_guide.md
338+
339+
with the *sole exception* of **path-related fields** to prevent overwriting
340+
previous results. Ensure you only modify the parameters listed in the approved
341+
list. If a user asks to modify a parameter that is not on the approved list
342+
(and is not a path-related field), confirm with the user before proceeding.
343+
344+
## Optimization Workflows
345+
346+
- **Initial Setup**: When asked to help configure a new optimization run, use
347+
the example configuration in the Overall Guide as a valid default base.
348+
349+
1. **Identify Essential Parameters**: Proactively ask the user for the
350+
following required fields:
351+
- `project` (Your Google Cloud project ID)
352+
- `train_input_data_path`
353+
- `test_input_data_path`
354+
- `output_path`
355+
- `prompt_template` (ensure it includes `{{ placeholder }}` syntax)
356+
- `eval_metrics_types` (e.g., `["exact_match"]`)
357+
- `eval_metrics_weights` (e.g., `[1.0]`)
358+
- `prompt_optimizer_method` (VAPO or OPTIMIZATION_TARGET_GEMINI_NANO)
359+
- `target_model` (e.g., gemini-2.5-flash)
360+
- `target_model_endpoint_url` (Required ONLY for Gemini Nano)
361+
362+
2. **Task-Specific Configuration**: You must ensure the optimization job
363+
correctly maps the data by defining `data_vars` and `label_variable`.
364+
- **Automated Inference**: You MUST attempt to read the first few lines of
365+
the training dataset (using `run_shell_command` with `gcloud storage
366+
cat`)
367+
to identify column names.
368+
- **Mapping**: Based on the data headers, automatically suggest:
369+
- `data_vars`: all relevant columns.
370+
- `label_variable`: the ground truth column.
371+
- `demo_and_query_template`: (Optional) The tool will automatically
372+
generate a default if you don't provide one.
373+
- *Clarification*: If you cannot access the data or the headers are
374+
ambiguous, ask the user to confirm the column names.
375+
376+
3. **Apply Sensible Defaults**: Use the default values provided in the
377+
example configuration of the Overall Guide for all other fields, unless
378+
the user specifies otherwise. This includes QPS limits and model
379+
locations.
380+
381+
Once gathered, use `write_data_driven_optimize_config` to create the
382+
initial configuration file.
383+
384+
- **Analysis and Suggestions**: When asked to analyze results for a GCS or
385+
local path `output_path`, perform these steps sequentially in a single turn:
386+
387+
1. **Analyze**: Call `analyze_data_driven_optimize_results(output_path,
388+
analysis_data_path="analysis_data.json")`. Store this output locally.
389+
2. **Formulate Suggestions**: Immediately after receiving results, and
390+
without prompting the user, process the data to construct a
391+
`suggested_config_data` dictionary. This dictionary should contain:
392+
- `"suggested_config"`: Modifications to allowed tuning knobs,
393+
path-related fields (with a new version suffix), and optionally the
394+
`prompt_template` (for baseline shifts). Ensure you prioritize
395+
modifying parameters listed in the approved list.
396+
- `"rationale"`: A clear explanation of your reasoning based on the
397+
Tuning Guide.
398+
399+
*Do not generate any other text or explanation for the user during this
400+
internal phase.*
401+
3. **Generate Report**: Call `generate_html_report(analysis_data_path=
402+
"analysis_data.json",
403+
report_path="data_driven_optimize_analysis_report.html",
404+
suggested_config_data=suggested_config_data)`.
405+
406+
**Note:** Steps 1-3 should be executed in immediate succession without user
407+
interaction. Only after the report is generated should you propose applying
408+
the suggestions via `write_data_driven_optimize_config`.
409+
410+
- **Agreement Logic**: If the user agrees to apply suggestions, use the
411+
`write_data_driven_optimize_config` tool with the modified parameters,
412+
ensuring you update the `output_path` with a new version suffix.
413+
When ready to run, use the `run_data_driven_optimize` tool, ensuring you
414+
ask for the `service_account`.
415+
- **Reusing Results**: If a report or further analysis is requested
416+
later, use
417+
the stored JSON output rather than re-running the analysis tool.
418+
- **General Suggestions**: If a user asks for next steps without a previous
419+
analysis, run the workflow above first to ensure your advice is grounded.
420+
421+
For detailed explanations of the Data-Driven Optimize output files and their
422+
structure, including how to interpret metrics and candidate information, please
423+
refer to the Data-Driven Optimize Output Guide:
424+
425+
@./src/vertex/prompt_optimizer/docs/data_driven_optimize_output_analysis.md

README.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
# Vertex AI Gemini CLI Extension
22

3-
This extension provides tools to manage prompts in Vertex AI directly from the Gemini CLI. It allows you to create, read, update, list, and delete prompts, making it easier to integrate prompt management into your development workflow.
3+
This extension provides tools to manage prompts and work with data-driven prompt optimizer in Vertex AI directly from the Gemini CLI. It allows you to create, read, update, list, and delete prompts, making it easier to integrate prompt management into your development workflow.
44

55
## Features
66

7+
### Prompt Management
78
* **Create Prompt**: Save new prompts with specified content, system instructions, model, and display name.
89
* **Read Prompt**: Retrieve existing prompts by their ID.
910
* **Update Prompt**: Modify the content, system instructions, or model of an existing prompt.
1011
* **Delete Prompt**: Remove prompts using their ID.
1112
* **List Prompts**: Search and list prompts, useful for finding prompt IDs based on display names.
1213

14+
### Data-Driven Prompt Optimizer
15+
* **Configuration Generation**: Create the input configurations required to run data-driven prompt optimizer.
16+
* **Job Execution**: Run large-scale prompt optimization jobs directly on Vertex AI.
17+
* **Results Analysis**: Perform deep-dive analysis of optimization results, including learning curves and candidate comparisons.
18+
* **Automated Reporting**: Generate comprehensive HTML reports with tuning suggestions for subsequent runs.
19+
1320
## Prerequisites
1421

1522
* You have the [Gemini CLI](https://github.com/google-gemini/gemini-cli) installed.
@@ -33,6 +40,8 @@ export GOOGLE_CLOUD_LOCATION="us-central1"
3340

3441
## Usage
3542

43+
### Prompt Management Examples
44+
3645
Once installed and configured, you can use the Vertex AI prompt management tools by passing natural language commands to the Gemini CLI.
3746

3847
Here are a few examples:
@@ -54,6 +63,25 @@ Here are a few examples:
5463

5564
For more detailed information on all available commands and their parameters, please refer to the `extension/commands` files.
5665

66+
### Prompt Optimizer Examples
67+
68+
* **Analyze optimization results**:
69+
```bash
70+
gemini "analyze my data drive prompt optimizer results at gs://your-bucket/optimization-run-1/"
71+
```
72+
73+
* **Configure a new optimization job**:
74+
```bash
75+
gemini "help me configure a new optimization job based on my existing config at gs://your-bucket/config.json"
76+
```
77+
78+
* **Run optimization job**:
79+
```bash
80+
gemini "start a data driven prompt optimizer job using my config at gs://your-bucket/config-new.json"
81+
```
82+
83+
For more detailed information on all available commands and workflows, please refer to the `GEMINI.md` file in this repository.
84+
5785
## Development
5886

5987
### Local Development Setup
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
name = "analyze_data_driven_optimize_results"
2+
description = "Analyzes the output of a Data-Driven Optimize job and saves the results."
3+
prompt = """
4+
You are tasked with generating parameters for a `prompt_optimizer.analyzer.analyze_results` tool call.
5+
6+
**Parameters:**
7+
8+
1. **`output_path` (string, required):**
9+
* **Source:** The GCS, Google Drive, or local path containing the job results. This is usually provided by the user.
10+
11+
2. **`analysis_data_path` (string, optional):**
12+
* **Default:** "analysis_data.json"
13+
* **Source:** The local path where the analysis metadata will be saved.
14+
15+
3. **`top_n_prompts` (integer, optional):**
16+
* **Default:** 10
17+
* **Source:** The number of top-performing prompts to include in the analysis.
18+
19+
**Workflow Integration:**
20+
Refer to the "Analysis and Suggestions" workflow in `GEMINI.md`. This tool is the first step in a chain that includes formulating suggestions and generating an HTML report.
21+
"""
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
name = "generate_html_report"
2+
description = "Generates a comprehensive HTML report from Data-Driven Optimize analysis results."
3+
prompt = """
4+
You are tasked with generating parameters for a `prompt_optimizer.analyzer.generate_report` tool call.
5+
6+
**Parameters:**
7+
8+
1. **`analysis_data_path` (string, required):**
9+
* **Source:** The path to the JSON file generated by `analyze_results`.
10+
11+
2. **`report_path` (string, optional):**
12+
* **Default:** "data_driven_optimize_analysis_report.html"
13+
* **Source:** The path where the HTML report will be saved.
14+
15+
3. **`suggested_config_data` (object, optional):**
16+
* **Source:** A dictionary containing `"suggested_config"` (modifications) and `"rationale"`. You must formulate this based on the `analysis_data` from the previous step using the guidelines in `src/vertex/prompt_optimizer/docs/data_driven_optimize_tuning_guide.md`.
17+
18+
4. **`top_n_prompts` (integer, optional):**
19+
* **Default:** 10
20+
21+
**Workflow Integration:**
22+
Refer to the "Analysis and Suggestions" workflow in `GEMINI.md`. This tool is the final step in the analysis chain.
23+
"""
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
name = "run_data_driven_optimize"
2+
description = "Starts a data-driven prompt optimization job on Vertex AI."
3+
prompt = """
4+
You are tasked with generating parameters for a `run_data_driven_optimize` tool call.
5+
6+
**Parameters:**
7+
8+
1. **`config_gcs_path` (string, required):**
9+
* **Source:** The GCS URI to the configuration JSON file.
10+
11+
2. **`service_account` (string, required):**
12+
* **Source:** The service account email to run the job (typically `{project_number}-compute@developer.gserviceaccount.com`). Ask the user if not known.
13+
14+
3. **`prompt_optimizer_method` (string, required):**
15+
* **Source:** The method for prompt optimization. Either "VAPO" or "OPTIMIZATION_TARGET_GEMINI_NANO".
16+
17+
4. **`wait_for_completion` (boolean, optional):**
18+
* **Default:** false
19+
* **Source:** Whether to block until the job completes.
20+
21+
**Clarification Policy:**
22+
If `config_gcs_path`, `service_account` or `prompt_optimizer_method` is missing, ask the user for it.
23+
"""
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
name = "write_data_driven_optimize_config"
2+
description = "Constructs and uploads a Data-Driven Optimize configuration file to GCS."
3+
prompt = """
4+
You are tasked with generating parameters for a `prompt_optimizer.config.write_config` tool call.
5+
6+
**Parameters:**
7+
8+
1. **`gcs_config_uri` (string, required):**
9+
* **Source:** The destination GCS URI for the config file.
10+
11+
2. **`prompt_optimizer_method` (string, required):**
12+
* **Source:** The method for prompt optimization. Either "VAPO" or "OPTIMIZATION_TARGET_GEMINI_NANO". If "VAPO", `batch_size` will be automatically removed from the config.
13+
14+
3. **`target_model_endpoint_url` (string, optional):**
15+
* **Source:** The custom endpoint URL for the target model. This is required ONLY for the Gemini Nano optimization target.
16+
17+
4. **`base_config` (object, optional):**
18+
* **Source:** A dictionary representing the base configuration.
19+
20+
5. **`modifications` (object, optional):**
21+
* **Source:** A dictionary of modifications to apply to the JSON configuration file. Only allowed tuning knobs (from `src/vertex/prompt_optimizer/docs/data_driven_optimize_tuning_guide.md`) and path-related fields should be included. Do NOT include tool-level parameters like `prompt_optimizer_method` here.
22+
23+
6. **`base_config_path` (string, optional):**
24+
* **Source:** A GCS path to an existing config file to use as a base.
25+
26+
**Clarification Policy:**
27+
If `gcs_config_uri` or `prompt_optimizer_method` is missing, ask the user for it.
28+
"""

gemini-extension.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "vertex",
3-
"version": "0.1.0",
3+
"version": "0.2.0",
44
"mcpServers": {
55
"VertexMcpServer": {
66
"command": "${extensionPath}/run.sh",

pyproject.toml

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
[project]
22
name = "vertex"
3-
version = "0.1.0"
3+
version = "0.2.0"
44
requires-python = ">=3.10"
55
dependencies = [
6-
"google-cloud-aiplatform",
6+
"google-cloud-aiplatform>=1.138.0",
77
"google-generativeai",
88
"pydantic",
99
"absl-py",
1010
"mcp[cli]>=1.21.2",
11+
"google-cloud-storage",
12+
"pandas",
13+
"matplotlib",
1114
]
1215

16+
[build-system]
17+
requires = ["setuptools>=61.0"]
18+
build-backend = "setuptools.build_meta"
19+
1320
[project.optional-dependencies]
1421
dev = ["ruff~=0.5.5", "pyright", "pytest", "ipython", "pre-commit"]
1522

0 commit comments

Comments
 (0)