Upload folder using huggingface_hub
Browse filesFiles changed (16)
- .gemini/extensions/vertex/src/vertex.egg-info/PKG-INFOAdded+20
- .gemini/extensions/vertex/src/vertex.egg-info/SOURCES.txtAdded+16
- .gemini/extensions/vertex/src/vertex.egg-info/dependency_links.txtAdded+1
- .gemini/extensions/vertex/src/vertex.egg-info/requires.txtAdded+15
- .gemini/extensions/vertex/src/vertex.egg-info/top_level.txtAdded+1
- .gemini/extensions/vertex/src/vertex/__init__.pyAdded
- .gemini/extensions/vertex/src/vertex/prompt_optimizer/analyzer.pyAdded+842
- .gemini/extensions/vertex/src/vertex/prompt_optimizer/docs/data_driven_optimize_output_analysis.mdAdded+143
- .gemini/extensions/vertex/src/vertex/prompt_optimizer/docs/data_driven_optimize_overall_guide.mdAdded+180
- .gemini/extensions/vertex/src/vertex/prompt_optimizer/docs/data_driven_optimize_tuning_guide.mdAdded+266
- .gemini/extensions/vertex/src/vertex/prompt_optimizer/docs/few_shot_prompt_optimization_guide.mdAdded+28
- .gemini/extensions/vertex/src/vertex/prompt_optimizer/prompt_optimizer.pyAdded+271
- .gemini/extensions/vertex/src/vertex/prompt_optimizer/storage.pyAdded+101
- .gemini/extensions/vertex/src/vertex/prompt_optimizer/utils.pyAdded+35
- .gemini/extensions/vertex/src/vertex/server.pyAdded+54
- .gemini/extensions/vertex/src/vertex/tools.pyAdded+302
1234567891011121314151617181920Metadata-Version: 2.4Name: vertexVersion: 0.2.0Requires-Python: >=3.10License-File: LICENSERequires-Dist: google-cloud-aiplatform>=1.138.0Requires-Dist: google-generativeaiRequires-Dist: pydanticRequires-Dist: absl-pyRequires-Dist: mcp[cli]>=1.21.2Requires-Dist: google-cloud-storageRequires-Dist: pandasRequires-Dist: matplotlibProvides-Extra: devRequires-Dist: ruff~=0.5.5; extra == "dev"Requires-Dist: pyright; extra == "dev"Requires-Dist: pytest; extra == "dev"Requires-Dist: ipython; extra == "dev"Requires-Dist: pre-commit; extra == "dev"Dynamic: license-file12345678910111213141516LICENSEREADME.mdpyproject.tomlsrc/vertex/__init__.pysrc/vertex/server.pysrc/vertex/tools.pysrc/vertex.egg-info/PKG-INFOsrc/vertex.egg-info/SOURCES.txtsrc/vertex.egg-info/dependency_links.txtsrc/vertex.egg-info/requires.txtsrc/vertex.egg-info/top_level.txtsrc/vertex/prompt_optimizer/analyzer.pysrc/vertex/prompt_optimizer/prompt_optimizer.pysrc/vertex/prompt_optimizer/storage.pysrc/vertex/prompt_optimizer/utils.pytests/test_tools.py1
123456789101112131415google-cloud-aiplatform>=1.138.0google-generativeaipydanticabsl-pymcp[cli]>=1.21.2google-cloud-storagepandasmatplotlib
[dev]ruff~=0.5.5pyrightpytestipythonpre-commit1vertex123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842"""Tools for analyzing the output of a Data-Driven Optimize job."""
import base64import difflibimport htmlimport ioimport jsonimport osimport refrom typing import Any
import matplotlibfrom absl import logging
matplotlib.use("Agg")import matplotlib.pyplot as pltimport pandas as pdfrom matplotlib.ticker import MaxNLocator
from . import storage, utils
BytesIO = io.BytesIO
UCB_TRAIN_KEY = "ucb_train"FULL_TRAIN_KEY = "full_train"FULL_TEST_KEY = "full_test"UCB_TRAIN_SCORE_KEY = "score_" + UCB_TRAIN_KEYFULL_TRAIN_SCORE_KEY = "score_" + FULL_TRAIN_KEYFULL_TEST_SCORE_KEY = "score_" + FULL_TEST_KEY
EXPECTED_TEMPLATES_COUNT = 2
def get_best_prompt(output_path: str) -> str: """Parses the output files to find the best performing prompt.""" try: best_prompt_data = storage.read_file_from_base( output_path, "optimized_results.json" ) return best_prompt_data.get("prompt", "Prompt not found in file.") except (FileNotFoundError, RuntimeError) as e: raise RuntimeError( "Could not retrieve best prompt. Ensure the optimization job completed" " successfully and the output directory contains" f" 'optimized_results.json'. Original error: {e}" ) from e
def get_performance_comparison(output_path: str) -> dict[str, Any]: """Compares the initial and best prompts evaluated on the full test set.""" test_templates = None if storage.file_exists_in_base(output_path, "test_templates.json"): try: test_templates = storage.read_file_from_base( output_path, "test_templates.json" ) except (FileNotFoundError, RuntimeError) as e: print( "Warning: Could not read test_templates.json from" f" {output_path}. Comparison will be unavailable. Original error: {e}" )
ucb_templates = None if storage.file_exists_in_base(output_path, "templates.json"): try: ucb_templates = storage.read_file_from_base( output_path, "templates.json" ) except (FileNotFoundError, RuntimeError): print( f"Warning: Could not read templates.json from {output_path}. " "Comparison will be unavailable. Original error: {e}" )
initial_prompt = "Not available" best_prompt = "Not available" initial_full_test_metrics = {} best_full_test_metrics = {} initial_ucb_metrics = {} best_ucb_metrics = {}
if test_templates and len(test_templates) == EXPECTED_TEMPLATES_COUNT: initial_prompt = test_templates[0].get("prompt") best_prompt = test_templates[1].get("prompt") initial_full_test_metrics = test_templates[0].get("metrics") best_full_test_metrics = test_templates[1].get("metrics")
if ucb_templates: # Find initial prompt (step 0) for t in ucb_templates: if t.get("step") == 0: initial_ucb_metrics = t.get("metrics") break # Find best prompt by prompt text for t in ucb_templates: if t.get("prompt") == best_prompt: best_ucb_metrics = t.get("metrics") break
return { "initial_prompt": { "prompt": initial_prompt, "ucb_metrics": initial_ucb_metrics, "full_test_metrics": initial_full_test_metrics, }, "best_prompt": { "prompt": best_prompt, "ucb_metrics": best_ucb_metrics, "full_test_metrics": best_full_test_metrics, }, }
def _load_raw_template_files(output_path: str) -> dict[str, Any]: """Loads all relevant template JSON files into a structured dict."""
def _read_json_if_exists(path, filename): try: if storage.file_exists_in_base(path, filename): logging.info("File %s exists, attempting to read.", filename) return storage.read_file_from_base(path, filename) except (FileNotFoundError, RuntimeError) as e: logging.warning("Failed to read file %s: %s", filename, e) return None
files = { UCB_TRAIN_KEY: "templates.json", FULL_TRAIN_KEY: "all_candidates_full_train_templates.json", FULL_TEST_KEY: "all_candidates_full_test_templates.json", }
data = {} for key, template_file in files.items(): templates = _read_json_if_exists(output_path, template_file) if templates: data[key] = {"templates": templates} logging.info("Read %d templates for %s.", len(templates), key) return data
def _infer_metric_name(data_dict: dict[str, Any]) -> str: """Infers the metric name from the loaded template data.""" for key in [UCB_TRAIN_KEY, FULL_TRAIN_KEY, FULL_TEST_KEY]: templates = data_dict.get(key, {}).get("templates") if templates: name = next( ( k for k in templates[0].get("metrics", {}) if k not in ["row_count", "uid"] ), None, ) if name: return name raise RuntimeError("Could not determine metric name for ranking.")
def _get_all_metrics_ranked( output_path: str, use_uid_as_candidate_key: bool = False,) -> tuple[list[dict[str, Any]], str, dict[str, Any]]: """Gets a ranked list of all prompt candidates with detailed info.""" data = _load_raw_template_files(output_path) metric_name = _infer_metric_name(data) logging.info("Determined metric name: %s", metric_name)
# Dict of candidate results & info keyed by candidate_key candidates = {} # Mapping of candidate_key to full prompt text prompts_map = {} # Internal mapping: identity -> key, uid -> key identity_to_key = {} uid_to_key = {}
def _process_candidate_result(result_set_key: str): if result_set_key not in data: return
templates = data[result_set_key]["templates"] for template in templates: uid = template.get("metrics", {}).get("uid") step = template.get("step") prompt = template.get("prompt") identity = (step, prompt)
# Map identity or UID to a unique candidate key if identity in identity_to_key: candidate_key = identity_to_key[identity] elif uid and str(uid) in uid_to_key: candidate_key = uid_to_key[str(uid)] else: candidate_key = ( str(uid) if uid else f"s{step}_n{len(identity_to_key)}" ) identity_to_key[identity] = candidate_key if uid: uid_to_key[str(uid)] = candidate_key
if candidate_key not in candidates: candidates[candidate_key] = { "uid": uid, "step": step, "candidate_key": candidate_key, } prompts_map[candidate_key] = prompt
# Back-fill UID if found in subsequent file if uid and not candidates[candidate_key]["uid"]: candidates[candidate_key]["uid"] = uid uid_to_key[str(uid)] = candidate_key
candidates[candidate_key]["score_" + result_set_key] = template.get( "metrics", {} ).get(metric_name)
_process_candidate_result(UCB_TRAIN_KEY) _process_candidate_result(FULL_TRAIN_KEY) _process_candidate_result(FULL_TEST_KEY)
if not candidates: raise RuntimeError("No candidate data found to rank prompts.")
candidate_list = list(candidates.values()) sort_priority = [ UCB_TRAIN_SCORE_KEY, FULL_TRAIN_SCORE_KEY, FULL_TEST_SCORE_KEY, ] sort_key = next( (k for k in sort_priority if any(k in c for c in candidate_list)), None )
if not sort_key: raise RuntimeError("No valid scores found to rank prompts.")
sorted_candidates = sorted( [c for c in candidate_list if c.get(sort_key) is not None], key=lambda x: x[sort_key], reverse=True, ) return sorted_candidates, metric_name, prompts_map
def _create_learning_curve_plot(df: pd.DataFrame, metric_name: str) -> str: """Generates the learning curve plot as a base64 encoded string.""" plt.figure(figsize=(12, 7)) plotted_anything = False
def _plot_series(score_key, label, marker, linestyle): nonlocal plotted_anything if score_key in df.columns: subset = df.dropna(subset=[score_key, "step"]) if not subset.empty: best_prompts_by_step = subset.loc[ subset.groupby("step")[score_key].idxmax() ] if not best_prompts_by_step.empty: plt.plot( best_prompts_by_step["step"], best_prompts_by_step[score_key], marker=marker, linestyle=linestyle, label=label, ) plotted_anything = True
_plot_series(UCB_TRAIN_SCORE_KEY, "Training Score (Mini-batches)", "o", "-") _plot_series(FULL_TRAIN_SCORE_KEY, "Full Training Set Score", "x", "--") _plot_series(FULL_TEST_SCORE_KEY, "Full Test Set Score", "s", ":")
plt.title("Best Prompt Performance Over Optimization Steps") plt.xlabel("Optimization Step") plt.ylabel(f"Score ({metric_name})") plt.grid(True, which="both", linestyle="--", linewidth=0.5) plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True)) if plotted_anything: plt.legend() plt.tight_layout() buf = BytesIO() plt.savefig(buf, format="png") plt.close() return base64.b64encode(buf.getvalue()).decode("utf-8")
def _render_dict_diff( old_dict: dict, new_dict: dict, indent: int = 0) -> tuple[str, str]: """Renders two dicts side-by-side with HTML highlighting for diffs.""" old_lines = [] new_lines = [] indent_str = " " * indent all_keys = sorted(list(set(old_dict.keys()) | set(new_dict.keys())))
old_lines.append(indent_str + "{") new_lines.append(indent_str + "{")
for key in all_keys: key_str = html.escape(json.dumps(key)) old_val = old_dict.get(key) new_val = new_dict.get(key)
old_exists = key in old_dict new_exists = key in new_dict
val_diff = old_val != new_val line_class = ( "optimizer_diff_chg" if val_diff or not old_exists or not new_exists else "" )
o_line = f"{indent_str} {key_str}: " n_line = f"{indent_str} {key_str}: "
if not new_exists: o_line += html.escape(json.dumps(old_val)) n_line += "" line_class = "optimizer_diff_sub" elif not old_exists: o_line += "" n_line += html.escape(json.dumps(new_val)) line_class = "optimizer_diff_add" elif isinstance(old_val, dict) and isinstance(new_val, dict): o_s, n_s = _render_dict_diff(old_val, new_val, indent + 1) o_line = f"{indent_str} {key_str}:\n{o_s}" n_line = f"{indent_str} {key_str}:\n{n_s}" elif isinstance(old_val, list) and isinstance(new_val, list): if old_val == new_val: o_line += html.escape(json.dumps(old_val)) n_line += html.escape(json.dumps(new_val)) else: o_line += f"{html.escape(json.dumps(old_val))}" n_line += f"{html.escape(json.dumps(new_val))}" else: # Primitive types o_line += html.escape(json.dumps(old_val)) n_line += html.escape(json.dumps(new_val))
if line_class: old_lines.append(f'<span class="{line_class}">{o_line}</span>') new_lines.append(f'<span class="{line_class}">{n_line}</span>') else: old_lines.append(o_line) new_lines.append(n_line)
old_lines.append(indent_str + "}") new_lines.append(indent_str + "}") return "\n".join(old_lines), "\n".join(new_lines)
def _format_value(value): if isinstance(value, float): return f"{value:.4f}" return value if value is not None else "N/A"
def _load_analysis_data(analysis_data_path: str) -> dict[str, Any]: """Loads and re-joins split analysis data files.""" try: with open(analysis_data_path) as f: analysis_data = json.load(f)
# Load split files metrics_path = analysis_data_path.replace(".json", "_metrics.json") prompts_path = analysis_data_path.replace(".json", "_prompts.json")
if os.path.exists(metrics_path): with open(metrics_path) as f: analysis_data["all_metrics_ranked"] = json.load(f)
if not os.path.exists(prompts_path): return analysis_data
with open(prompts_path) as f: prompts_map = json.load(f)
# Re-join prompts into all_metrics_ranked for p in analysis_data.get("all_metrics_ranked", []): ck = p.get("candidate_key") if ck in prompts_map: p["prompt"] = prompts_map[ck]
# Re-join prompts into comparison section comp = analysis_data.get("comparison", {}) for key in ["initial_prompt", "best_prompt"]: target = comp.get(key) if isinstance(target, dict): # Use UID from full_test_metrics to find the prompt uid = target.get("full_test_metrics", {}).get("uid") if uid and str(uid) in prompts_map: target["prompt"] = prompts_map[str(uid)]
return analysis_data except Exception as e: raise RuntimeError( f"Failed to load analysis data from {analysis_data_path}: {e}" ) from e
def _render_config_section( config: dict[str, Any], suggested_config_data: dict[str, Any] | None) -> str: """Renders the HTML section for the run configuration and suggestions.""" base_config = config or {} rationale_html = "" modifications_html = ""
if suggested_config_data: modifications = suggested_config_data.get("suggested_config", {}) merged_config = utils.merge_configs(base_config, modifications)
if "rationale" in suggested_config_data: rationale_html = f""" <h3>Rationale for Suggested Modifications:</h3> <p>{suggested_config_data['rationale']}</p> """
if modifications: modifications_html = "<h3>Summary of Suggested Changes:</h3><ul>" for key, value in modifications.items(): modifications_html += f"<li><b>{key}:</b> {value}</li>" modifications_html += "</ul>"
old_config_html, new_config_html = _render_dict_diff( base_config, merged_config )
config_display_html = f""" {modifications_html} <div style="display: flex;"> <div style="flex: 1; padding-right: 10px;"> <h3>Current Run Config:</h3> <pre class="optimizer-pre">{old_config_html}</pre> </div> <div style="flex: 1; padding-left: 10px;"> <h3>Config for Next Run (Changes Highlighted):</h3> <pre class="optimizer-pre">{new_config_html}</pre> </div> </div> """ else: base_config_str = json.dumps(base_config, indent=2) config_display_html = f""" <div style="display: flex;"> <div style="flex: 1; padding-right: 10px;"> <h3>Current Run Config:</h3> <pre class="optimizer-pre">{base_config_str}</pre> </div> <div style="flex: 1; padding-left: 10px;"> <h3>Config for Next Run:</h3> <p>No suggested modifications provided.</p> </div> </div> """
return f""" <div class="card"> <h2>Run Configuration</h2> {rationale_html} {config_display_html} </div> """
def _render_comparison_section(comparison: dict[str, Any] | None) -> str: """Renders the HTML section for the performance comparison.""" if not comparison: comparison_html = ( '<p class="error">Prompt comparison data is not available.</p>' ) elif "error" in comparison: comparison_html = f'<p class="error">Prompt comparison failed: {comparison["error"]}</p>' else: initial_prompt_str = comparison.get("initial_prompt", {}).get( "prompt", "N/A" ) best_prompt_str = comparison.get("best_prompt", {}).get("prompt", "N/A") a_words = re.split(r"(\s+)", initial_prompt_str) b_words = re.split(r"(\s+)", best_prompt_str) s = difflib.SequenceMatcher(None, a_words, b_words, autojunk=False) a_out, b_out = [], [] for tag, i1, i2, j1, j2 in s.get_opcodes(): a_segment = "".join(a_words[i1:i2]) b_segment = "".join(b_words[j1:j2])
a_segment_html = a_segment.replace("\n", "<br>") b_segment_html = b_segment.replace("\n", "<br>")
if tag == "replace": a_out.append(f'<span class="diff_chg">{a_segment_html}</span>') b_out.append(f'<span class="diff_chg">{b_segment_html}</span>') elif tag == "delete": a_out.append(f'<span class="diff_sub">{a_segment_html}</span>') elif tag == "insert": b_out.append(f'<span class="diff_add">{b_segment_html}</span>') elif tag == "equal": a_out.append(a_segment_html) b_out.append(b_segment_html)
initial_prompt_html = "".join(a_out) best_prompt_html = "".join(b_out) diff = f""" <table class="diff"> <tr> <td class="diff_header" width="50%">Initial Prompt</td> <td class="diff_header" width="50%">Best Prompt</td> </tr> <tr> <td class="prompt">{initial_prompt_html}</td> <td class="prompt">{best_prompt_html}</td> </tr> </table> """
def _render_metrics_table(metrics_dict): html_str = '<td><table style="border: none;">' if isinstance(metrics_dict, dict): for key, value in metrics_dict.items(): html_str += ( "<tr><td" f' style="border: none;"><b>{key}</b></td><td style="border:' f' none;">{_format_value(value)}</td></tr>' ) else: html_str += '<tr><td style="border: none;">N/A</td></tr>' html_str += "</table></td>" return html_str
initial_full_test_metrics_html = _render_metrics_table( comparison.get("initial_prompt", {}).get("full_test_metrics", "N/A") ) best_full_test_metrics_html = _render_metrics_table( comparison.get("best_prompt", {}).get("full_test_metrics", "N/A") ) initial_ucb_metrics_html = _render_metrics_table( comparison.get("initial_prompt", {}).get("ucb_metrics", "N/A") ) best_ucb_metrics_html = _render_metrics_table( comparison.get("best_prompt", {}).get("ucb_metrics", "N/A") )
comparison_html = f""" <h4>Metrics</h4> <table> <tr> <th></th> <th>Initial Prompt</th> <th>Best Prompt</th> </tr> <tr> <td><strong>Training Metrics (Mini-batches)</strong></td> {initial_ucb_metrics_html} {best_ucb_metrics_html} </tr> <tr> <td><strong>Full Test Set Metrics</strong></td> {initial_full_test_metrics_html} {best_full_test_metrics_html} </tr> </table> <h4>Prompt Comparison</h4> {diff} """
return f""" <div class="card"> <h2>Performance Comparison</h2> {comparison_html} </div> """
def _render_top_prompts_section( all_metrics_ranked: list[dict[str, Any]], top_n_prompts: int, metric_source: str | None, metric_name: str | None,) -> str: """Renders the HTML section for the top ranked prompts.""" if not all_metrics_ranked: return ""
ranking_info = "" if metric_source and metric_name: src_label = metric_source.replace( "ucb_train", "Training (Mini-batches)" ) ranking_info = ( f"<p><i>Ranked by {src_label} Score on metric {metric_name}</i></p>" )
rows = [] for p in all_metrics_ranked[:top_n_prompts]: prompt_html = p.get("prompt", "N/A").replace("\n", "<br>") rows.append( f"""<tr> <td>{p.get('step', 'N/A')}</td> {'<td>' + _format_value(p.get(UCB_TRAIN_SCORE_KEY)) + '</td>' if UCB_TRAIN_SCORE_KEY in p else ''} {'<td>' + _format_value(p.get(FULL_TRAIN_SCORE_KEY)) + '</td>' if FULL_TRAIN_SCORE_KEY in p else ''} {'<td>' + _format_value(p.get(FULL_TEST_SCORE_KEY)) + '</td>' if FULL_TEST_SCORE_KEY in p else ''} <td><div class='prompt scrollable-prompt'>{prompt_html}</div></td> </tr>""" )
return f""" <div class="card"> <h2>Top {top_n_prompts} Ranked Prompts</h2> {ranking_info} <table> <tr> <th>Step</th> {"<th>Training Score (Mini-batches)</th>" if UCB_TRAIN_SCORE_KEY in all_metrics_ranked[0] else ""} {"<th>Train Score (Full)</th>" if FULL_TRAIN_SCORE_KEY in all_metrics_ranked[0] else ""} {"<th>Test Score (Full)</th>" if FULL_TEST_SCORE_KEY in all_metrics_ranked[0] else ""} <th>Prompt</th> </tr> {''.join(rows)} </table> </div> """
def generate_report( analysis_data: dict[str, Any] | None = None, report_path: str = "data_driven_optimize_analysis_report.html", suggested_config_data: dict[str, Any] | None = None, top_n_prompts: int = 10, analysis_data_path: str | None = None,) -> None: """Generates a comprehensive HTML report from Data-Driven Optimize analysis results.""" if analysis_data_path: analysis_data = _load_analysis_data(analysis_data_path)
if not analysis_data: raise ValueError( "Either analysis_data or analysis_data_path must be provided." )
config = analysis_data.get("config") comparison = analysis_data.get("comparison") all_metrics_ranked = analysis_data.get("all_metrics_ranked") metric_source = analysis_data.get("metric_source") metric_name = analysis_data.get("metric_name")
# 1. Learning Curve Plot plot_html = "<p>Not enough data to generate a learning curve plot.</p>" if all_metrics_ranked and metric_name: try: df = pd.DataFrame(all_metrics_ranked) plot_b64 = _create_learning_curve_plot(df, metric_name) plot_html = f'<img src="data:image/png;base64,{plot_b64}" alt="Learning Curve">' except Exception as e: # pylint: disable=broad-except plot_html = f"<p>Couldn't plot learning curve: {e}</p>"
# 2. Render Sections comparison_section = _render_comparison_section(comparison) top_prompts_section = ( _render_top_prompts_section( all_metrics_ranked, top_n_prompts, metric_source, metric_name ) if all_metrics_ranked else "" ) config_section = ( _render_config_section(config, suggested_config_data) if config else "" )
main_html = f""" <html> <head> <title>Data-Driven Optimize Analysis Report</title> <style> body {{ font-family: sans-serif; margin: 2em; }} h1, h2, h3, h4 {{ color: #333; }} .card {{ border: 1px solid #ddd; border-radius: 5px; padding: 1em; margin-bottom: 1em; }} .prompt {{ font-family: monospace; background-color: #f5f5f5; padding: 0.5em; border-radius: 3px; white-space: pre-wrap; }} table {{ border-collapse: collapse; width: 100%; }} th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }} th {{ background-color: #f2f2f2; }} .suggestion {{ background-color: #e7f3ff; border-left: 5px solid #2196F3; padding: 10px; margin-top: 10px; }} .error {{ color: #D8000C; background-color: #FFBABA; padding: 10px; }} table.diff {{font-family:monospace; border:medium;}} .diff_header {{background-color:#e0e0e0}} .diff_next {{background-color:#c0c0c0}} .diff_add {{background-color:#aaffaa}} .diff_chg {{background-color:#ffff77}} .diff_sub {{background-color:#ffaaaa}} .scrollable-prompt {{ max-height: 200px; overflow-y: auto; display: block; }} .optimizer-pre {{ white-space: pre-wrap; word-wrap: break-word; }} .optimizer_diff_chg {{ background-color: #ffff77; display: block; }} .optimizer_diff_add {{ background-color: #aaffaa; display: block; }} .optimizer_diff_sub {{ background-color: #ffaaaa; display: block; }} </style> </head> <body> <h1>Data-Driven Optimize Analysis Report</h1> {comparison_section} <div class="card"> <h2>Learning Curve</h2> {plot_html} </div> {top_prompts_section} {config_section} </body> </html> """ if report_path.startswith("gs://"): storage.write_gcs_file(report_path, main_html) else: with open(report_path, "w") as f: f.write(main_html)
def analyze_results( output_path: str, analysis_data_path: str, top_n_prompts: int = 10,) -> dict[str, Any]: """Analyzes results and saves the detailed data to files."""
def _read_json_if_exists(path, filename): if storage.file_exists_in_base(path, filename): try: return storage.read_file_from_base(path, filename) except (FileNotFoundError, RuntimeError): return None return None
config = _read_json_if_exists(output_path, "config.json")
try: best_prompt_text = get_best_prompt(output_path) except RuntimeError as e: best_prompt_text = f"Error: Could not retrieve best prompt: {e}"
comparison: dict[str, Any] = {} try: comparison = get_performance_comparison(output_path) except (RuntimeError, ValueError) as e: comparison = { "error": ( f"Could not retrieve initial v.s. best performance comparison: {e}" ) }
all_metrics_ranked, metric_name, prompts_map = [], "", {} try: all_metrics_ranked, metric_name, prompts_map = _get_all_metrics_ranked( output_path ) except RuntimeError as e: logging.info("Could not retrieve ranked prompts: %s", e)
full_analysis_data = { "config": config, "best_prompt": best_prompt_text, "comparison": comparison, "metric_name": metric_name, "metric_source": UCB_TRAIN_KEY, }
# Define split file paths metrics_path = analysis_data_path.replace(".json", "_metrics.json") prompts_path = analysis_data_path.replace(".json", "_prompts.json")
try: # Save core metadata with open(analysis_data_path, "w") as f: json.dump(full_analysis_data, f) logging.info("Saved core analysis data to %s", analysis_data_path)
# Save detailed metrics (all_metrics_ranked WITHOUT prompt text) with open(metrics_path, "w") as f: json.dump(all_metrics_ranked, f) logging.info("Saved metrics to %s", metrics_path)
relevant_keys = set() for p in all_metrics_ranked[:top_n_prompts]: relevant_keys.add(p.get("candidate_key"))
# Add comparison prompts if comparison and isinstance(comparison, dict): for key in ["initial_prompt", "best_prompt"]: prompt_data = comparison.get(key) if isinstance(prompt_data, dict): metrics = prompt_data.get("full_test_metrics") if isinstance(metrics, dict): uid = metrics.get("uid") if uid: relevant_keys.add(str(uid))
filtered_prompts_map = { k: v for k, v in prompts_map.items() if k in relevant_keys }
with open(prompts_path, "w") as f: json.dump(filtered_prompts_map, f) logging.info( "Saved %d prompts to %s", len(filtered_prompts_map), prompts_path ) except Exception as e: logging.error("Failed to save analysis data: %s", e)
# Create a copy of all_metrics_ranked without prompt text for the summary. summary_metrics = [] for p in all_metrics_ranked: p_copy = p.copy() p_copy.pop("prompt", None) summary_metrics.append(p_copy)
return { "message": ( f"Analysis complete. Full results saved to {analysis_data_path}" ), "analysis_data_path": analysis_data_path, "metrics_path": metrics_path, "prompts_path": prompts_path, "best_prompt": best_prompt_text, "all_metrics_ranked": summary_metrics, "config_summary": { "project": config.get("project") if config else "N/A", "target_model": config.get("target_model") if config else "N/A", "eval_metrics": config.get("eval_metrics_types") if config else "N/A", "num_steps": config.get("num_steps") if config else "N/A", }, "best_prompt_score": ( comparison.get("best_prompt", {}) .get("full_test_metrics", {}) .get(metric_name) if ( isinstance(comparison, dict) and isinstance(comparison.get("best_prompt"), dict) and isinstance( comparison["best_prompt"].get("full_test_metrics"), dict ) ) else "N/A" ), "total_candidates": len(all_metrics_ranked), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143# Guide to Analyzing Data-Driven Optimize Output
## 1. Prerequisites: GCS Authentication
Before using the Python tools described in this guide, you must authenticateyour local environment with Google Cloud. The tools need to access the outputfiles stored in a GCS bucket, which requires proper permissions.
## 2. Introduction
After a Data-Driven Optimize (Prompt Optimizer) job completes, it writes anumber of files to the specified output path. This can be a Google CloudStorage (GCS) bucket or a local directory. This document explains what thesefiles are and how to use the provided tools to analyze them.
## 3. Data-Driven Optimize Output Files
The output directory contains several JSON files that capture the results ofthe optimization.
- **`optimized_results.json`**: Contains the single best prompt template found.
The entries in the following pairs of files have corresponding orders, andtheir contents can be zipped together for detailed analysis:
- **Training Results During Optimization Process**: - **`templates.json`**: Contains all templates evaluated during the optimization process, along with their summary metrics. - **`eval_results.json`**: Contains detailed, per-row training results on minibatches during the optimization process. This file is for manual, in-depth analysis and is not read by the analysis tools.- **Initial and Best Templates on Full Test Set**: - **`test_templates.json`**: Contains your original prompt and the best prompt, along with their summary metrics on the full test dataset. The best prompt is selected based on the metric from training only. - **`test_eval_results.json`**: Contains the detailed, per-row evaluation scores for the original and best prompts on the full test dataset. This file is for manual, in-depth analysis and is not read by the analysis tools.- **Eval of All Candidates on Full Test Set**: - **`all_candidates_full_test_templates.json`**: A list of *all* prompt candidates, along with their summary metrics on the full test set. - **`all_candidates_full_test_eval_results.json`**: Contains detailed, per-row evaluation results for each candidate prompt on the full test set. This file is for manual, in-depth analysis and is not read by the analysis tools.- **Eval of All Candidates on Full Training Set**: - **`all_candidates_full_train_templates.json`**: A list of *all* prompt candidates, along with their summary metrics on the full training set. - **`all_candidates_full_train_eval_results.json`**: Contains detailed, per-row evaluation results for each candidate prompt on the full training set. This file is for manual, in-depth analysis and is not read by the analysis tools.
### Controlling Output File Generation
Not all output files are generated by default. Their creation depends on yourjob's configuration. This is important because the analysis tools are designedto handle missing files gracefully, but you may want to enable certain outputsfor a more complete analysis.
Here are the key flags that control which files are generated:
- **Providing Test Data (`test_input_data_path`)**: This parameter is **optional but highly recommended**. When you provide a test dataset, the `test_templates.json` and `test_eval_results.json` files are generated, which provide a final comparison between your original prompt and the best-optimized prompt. Without a test set, you cannot accurately measure the generalization performance of your prompts.
- **`eval_all_candidates_on_full_test`**: This is an **optional** boolean flag. When set to `True` (and a test set is provided), the job will generate `all_candidates_full_test_templates.json` and `all_candidates_full_test_eval_results.json`. These files allow for a deep-dive analysis into the performance of *every* candidate on the test set. **Warning:** Enabling this flag can be computationally expensive and significantly increase the job's runtime.
- **`eval_all_candidates_on_full_train`**: This is an **optional** boolean flag. When set to `True`, the job will generate `all_candidates_full_train_templates.json` and `all_candidates_full_train_eval_results.json`. These enable a detailed comparison of performance on the full training set versus the test set, and against batch training results, which is crucial for identifying overfitting. **Warning:** Enabling this flag can be computationally expensive and significantly increase the job's runtime.
## 4. Data File Structure Details
**Key Fields:**
- In `_templates.json` files (e.g., `all_candidates_full_train_templates.json`, `test_templates.json`): - **`step`**: The optimization step where this candidate was generated or selected. - **`metrics`**: This object contains aggregated evaluation results (e.g., `ROUGE_L/mean` or `exact_match/mean`). The specific metric name will vary depending on the `eval_metric` configured. It also contains the "uid" which is an unique identifier consistent across all result files. - **`prompt`**: The prompt string itself.
- In `_eval_results.json` files (e.g., `all_candidates_full_train_eval_results.json`, `test_eval_results.json`): - **`summary_results`**: This object contains the aggregated metrics for the entire evaluation. - **`metrics_table`**: This object contains the per-row evaluation results, useful for detailed debugging.
## 5. Generating an Analysis Report
The recommended way to analyze your results is to use a multi-step processinvolving the tools provided and your reasoning capabilities:
1. **Analyze Results:** First, call `analyze_data_driven_optimize_results(output_path, analysis_data_path="path/to/analysis_data.json")` to process the raw output files. Providing `analysis_data_path` is highly recommended as it saves the results into three separate files to avoid system size limits: - `analysis_data.json`: Core metadata (config, comparison, best prompt). - `analysis_data_metrics.json`: Detailed metrics for all candidates (no prompt text). - `analysis_data_prompts.json`: Mapping of top candidates' keys to full prompt texts. This tool returns a **minimal summary object** with the paths to the saved files and the best prompt score.2. **Formulate Suggestions:** You should then analyze the `analysis_data` summary. Based on the guidelines in the **Data-Driven Optimize Tuning Guide**, formulate suggestions for the next run. This should result in a `suggested_config_data` dictionary, containing: - `"suggested_config"`: A dictionary of configuration modifications. - `"rationale"`: A string explaining the reasoning behind the suggestions.3. **Generate HTML Report:** Finally, call `generate_html_report()` passing either the `analysis_data` object or the `analysis_data_path` obtained in Step 1, along with the `suggested_config_data`. Passing `analysis_data_path` is the most efficient way to handle large analysis results as it automatically re-joins the metadata, metrics, and prompts from the three split files.
You can then open the generated HTML file in any web browser to view the fullanalysis. For a deeper understanding of how to interpret these results anditerate, please refer to the Data-Driven Optimize Tuning Guide.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180# Guide to Data-Driven Optimize (Prompt Optimizer)
## 1. Introduction to Data-Driven Optimize
Data-Driven Optimize (Prompt Optimizer), also known as Auto Prompt Optimization,is a powerful Vertex AI feature designed to enhance the performance of yourLarge Language Models (LLMs). Manually iterating on prompts to find the onethat performs best can be time-consuming and inefficient. Data-Driven Optimizeautomates this process using a data-driven approach.
### What problem does it solve?
Data-Driven Optimize addresses the challenge of prompt engineering. Instead ofrelying on intuition to create the perfect prompt, you can use Data-DrivenOptimize to systematically test and discover prompts that yield the bestresults for your specific task, based on your own data.
### How does it work?
The process is straightforward:1. **You provide a starting point:** This includes a base prompt (or just a task description), a dataset with examples, and a metric to measure success.2. **The Optimizer takes over:** It runs a sophisticated tuning job that generates many new prompt variations.3. **Evaluation and Ranking:** Each new prompt is tested against your dataset, and its performance is scored based on the evaluation metric you chose.4. **You get the best prompt:** The service returns a ranked list of the best-performing prompts, which you can then integrate into your application.
This document serves as a detailed guide to configuring the parameters for aData-Driven Optimize job to ensure a successful and effective optimization run.
## 2. Configuration Parameters
A Data-Driven Optimize job is configured using a flat JSON file. The parametersare detailed below.
### 2.1. Job Configuration
This section covers settings related to the execution and output of your job.
* **`project`**: (Required) Your Google Cloud project ID.* **`output_path`**: (Required) The Cloud Storage URI (e.g., `gs://your-bucket/folder/`) where the optimization job will save its results. This path **must** be a GCS location. * **Suggestion:** It is highly recommended to create a unique folder for each optimization job's output. This helps in keeping results organized and avoids potential conflicts. Note that while the job requires a GCS path, the analysis tools can read the output files from GCS or a local copy.
### 2.2. Model and Prompt Configuration
This section deals with the models, prompts, and instructions that form thecore of the optimization.
* **`prompt_optimizer_method`**: (Required) The method for prompt optimization. Supported values: - `VAPO`: Standard prompt optimization. - `OPTIMIZATION_TARGET_GEMINI_NANO`: Specialized target for Gemini Nano.* **`target_model`**: (Required) The model you are optimizing the prompt for (e.g., "gemini-2.5-flash", "gemini-nano").* **`target_model_location`**: (Optional) The Google Cloud location for the target model (e.g., `us-central1`).* **`target_model_qps`**: (Optional) The maximum queries per second for the target model. Defaults to a sensible value like 5.* **`optimizer_model`**: (Optional) The powerful model used to generate mutant prompt variations (e.g., "gemini-2.5-pro"). If not specified, a default high-performing model is used.* **`optimizer_model_location`**: (Optional) The Google Cloud location for the optimizer model.* **`optimizer_model_qps`**: (Optional) QPS limit for the optimizer model.* **`eval_model`**: The model used for model-based evaluation. If not specified, it defaults to the `target_model`.* **`eval_model_location`**: (Optional) The Google Cloud location for the evaluation model.* **`eval_model_qps`**: (Optional) QPS limit for the evaluation model.* **`prompt_template`**: (Required) The prompt template, which defines the structure of the prompt. It often includes placeholders for input variables (e.g., `Input: {{ query }}`).* **`demo_and_query_template`**: (Optional) A template used to format few-shot examples (demos) and the query itself during optimization. * **Note:** If omitted, the agent will automatically generate a default template using your `data_vars` and `label_variable`.* **`target_model_endpoint_url`**: (Required for Gemini Nano) The base URL of a custom endpoint for the target model.
### 2.3. Data and Evaluation Configuration
This section covers the data used for training and testing, and the metric forevaluation.
* **`train_input_data_path`**: (Required) The Cloud Storage URI of the JSONL or CSV file containing the training data. This path **must** be a GCS location.* **`test_input_data_path`**: (Required) The Cloud Storage URI of the JSONL or CSV file containing the testing/evaluation data.* **`data_vars`**: (Required) A list of variable names corresponding to the columns in your data files that should be used in the templates. * **Note:** These are typically inferred automatically by the agent from your dataset headers.* **`label_variable`**: (Required) The name of the variable/column containing the ground truth labels. * **Note:** This is typically inferred automatically by the agent from your dataset headers.* **`batch_size`**: (Optional) The number of data points used to evaluate a candidate prompt in each mini step. Note: If `prompt_optimizer_method` is `VAPO`, `batch_size` is supported. However, if it's currently not supported in the SDK for your specific version, it will be automatically removed from the config file.* **`eval_metrics_types`**: (Required) A list of standard evaluation metrics to optimize your prompts for (e.g., `["exact_match"]`, `["ROUGE_L"]`).* **`eval_metrics_weights`**: (Optional) A list of weights corresponding to the metrics in `eval_metrics_types`. Defaults to `[1.0]` if a single metric is used.* **`eval_qps`**: (Optional) Overall QPS limit for evaluation.
### 2.4. Optimization Strategy
* **`num_steps`**: (Required) The total number of optimization steps to run.* **`population_size`**: (Optional) The number of candidate prompts to maintain in the population.* **`num_mutants_per_candidate`**: (Optional) The number of new mutant prompts to generate from each survivor.
### 2.5. Example JSON Configuration
```json{ "project": "your-gcp-project-id", "output_path": "gs://your-bucket/data-driven-optimize-output/run-1/", "target_model": "gemini-2.5-flash", "target_model_location": "us-central1", "target_model_qps": 5, "optimizer_model": "gemini-2.5-pro", "optimizer_model_location": "us-central1", "optimizer_model_qps": 3, "eval_model": "gemini-2.5-flash", "eval_model_location": "us-central1", "eval_model_qps": 5, "prompt_template": "Classify the following text into one of the following categories: Business, Sci/Tech, World, Sports. Output the category name only.", "demo_and_query_template": "text:\n{{input}}\n\nanswer:\n{{output}}", "train_input_data_path": "gs://your-bucket/data/training-data.csv", "test_input_data_path": "gs://your-bucket/data/test-data.csv", "data_vars": ["input", "output"], "label_variable": "output", "eval_metrics_types": ["exact_match"], "eval_metrics_weights": [1.0], "num_steps": 10, "batch_size": 20, "population_size": 10, "num_mutants_per_candidate": 2}```
### 2.6. Understanding the Optimization Process
The core of the optimization process uses an evolutionary algorithm to discoverhigh-performing prompts. Here's a brief overview:
1. **Initialization:** Start with an initial pool of candidate prompts.2. **Selection Loop (within an iteration):** For a number of steps (`num_ucb_steps`), the algorithm selects promising candidates and evaluates them on new mini-batches of data to refine performance estimates.3. **Survival Selection:** After the selection steps, the top candidates (based on `population_size`) are preserved for the next generation.4. **Mutation:** New candidate prompts are generated by mutating the survivors. Each survivor produces multiple variants (`num_mutants_per_candidate`).5. **New Pool:** These new mutants form the candidate pool for the next major iteration.
This iterative process continues for a specified number of training steps,balancing the discovery of new prompt ideas with the refinement of establishedgood ones.
## 3. Further Reading
* [Data-Driven Optimize Official Documentation](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/learn/prompts/data-driven-optimizer)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266# Guide to Tuning Data-Driven Optimize Jobs
## 1. Introduction
After reviewing the initial results from a Data-Driven Optimize job, the nextstep is to decide how to improve them in the next run. This guide provides aframework for interpreting the results to diagnose common issues and suggestsconcrete changes to your configuration for the next iteration.
## 2. Core Diagnostic Questions
The analysis of a Data-Driven Optimize run can be distilled into few keyquestions.
### Question 0: What do we see about the data?
It's crucial to understand the data presented in the`analyze_data_driven_optimize_results` tool output. This tool processes the rawoutput files and provides a structured JSON object containing all the necessaryinformation for analysis.
1. **Examine the Analysis Output:** Inspect the JSON object returned by `analyze_data_driven_optimize_results`. Key top-level keys include: - `config`: The configuration used for the Data-Driven Optimize job (summarized if saving to file). - `best_prompt`: The prompt with the highest score based on the `metric_source` (present in the metadata file). - `comparison`: Metrics comparing the initial prompt and the best prompt on the training batches and full test set (if available). - `all_metrics_ranked`: A list of all candidates and their scores across different evaluations. **Note: Full prompt text is excluded from this list to save space and is stored separately. When saving to a file, this list is omitted from the chat summary to avoid payload limits.** This list contains the data needed to analyze learning curves and is available in the `*_metrics.json` file. - `metric_name`: The name of the metric being optimized. - `metric_source`: Indicates the data source used for ranking in `all_metrics_ranked`.
2. **Identify Available Datasets and Metrics:** The `all_metrics_ranked` list is the most important part for this. Each element in this list is a dictionary representing a prompt candidate, and contains scores from *all* available evaluation configurations. The presence of certain keys within these dictionaries indicates which datasets were evaluated: - **`score_ucb_train`**: Always present. Represents the score on the training mini-batches. - **`score_full_train`**: Present if `eval_all_candidates_on_full_train` was true in the config. - **`score_full_test`**: Present if `eval_all_candidates_on_full_test` was true in the config.
The `comparison` object will also reflect metrics for the initial and best prompts, typically on the test set data if configured. Understanding the distinctions between these datasets is vital for diagnosing issues like overfitting or noisy evaluations.
3. **Assess Data Noise:** To analyze trends and noise, you need to process the `all_metrics_ranked` list to extract scores for each `step`. For example, examine the variance or trends of `score_ucb_train`, `score_full_train`, and `score_full_test`. - **Noisy Data:** Significant fluctuations (e.g., large ups and downs) in training scores across steps suggest noise in the evaluations. - **Stable Data:** Relatively smooth trends in scores suggest more reliable evaluations.
### Question 1: Is the optimization process actually learning?
First, we need to determine if the optimizer is successfully finding betterprompts on the **training data**. To do this, analyze the training score valueswithin the `all_metrics_ranked` list. You should look at the trend of themaximum training score at each step.
- **What to look for:** A generally upward trend in the training score across the optimization steps.- **Good sign:** The score is increasing from one step to the next. This means the algorithm is generating better prompts and successfully identifying them.- **Bad sign:** The training score is flat, erratic, or decreasing. This suggests a problem with the optimization process itself or noise in the metric.
### Question 2: Is the learning generalizing to unseen data?
If the model is learning on the training data, we then need to see if thatlearning translates to better performance on the **full test data**. This tellsus if we are overfitting.
- **What to look for:** Compare the trend of the training score with the test score at each step within the `all_metrics_ranked` data. This requires test scores to be available.- **Good sign:** Both the train score and the test score are increasing. This is the ideal scenario, indicating that the prompts are getting better and the improvements are generalizing.- **Bad sign (Overfitting):** The training score is increasing, but the test score is flat or decreasing. This is a classic sign of overfitting. The optimizer is finding prompts that are too specific to your training examples and do not perform well on new, unseen examples.- **Other Gaps:** Also, pay attention to the gap between mini-batch training scores and full training scores (if available). A large or inconsistent gap here might suggest that the mini-batches are not representative of the full training set, potentially due to a small `batch_size`.
### Question 3: Is the starting metric too high and already saturated?
## 3. Tunable Parameters
**Important**: The parameters listed in this section are the primary and**only** tuning knobs that should be modified for Data-Driven Optimize jobs.Other parameters are not intended for user modification and can lead tounexpected results.
The following parameters are the knobs that can be adjusted to tune theData-Driven Optimize optimization process:- `num_steps`- `batch_size`- `population_size`- `num_mutants_per_candidate`- `num_ucb_steps`
### Impact of Tuning Knobs
- **`num_steps`**: The total number of optimization steps to run. More steps allow for more exploration but increase runtime.- **`batch_size`**: The number of data points used to evaluate a candidate prompt in each mini step. Larger batches provide more stable score estimates but increase the computational cost of each step. A common batch size is between 20-50.- **`population_size`**: Controls the number of elite candidates preserved at each iteration. A larger size maintains more diversity, potentially avoiding local optima but slowing down convergence.- **`num_mutants_per_candidate`**: Determines the exploration breadth around each elite candidate. More mutants increase the chances of finding improvements but require more evaluations.- **`num_ucb_steps`**: Controls how many times candidates are selected and evaluated *within* an iteration. More steps lead to more accurate estimates of each candidate's performance before selection, but increases the computational cost per iteration.
## 4. Common Scenarios and Next Steps
**General Guidance:**
- **Prioritize Addressing Noise:** If the metrics appear noisy, address this first by increasing `batch_size` and/or `num_ucb_steps`. It is difficult to diagnose other issues like overfitting if the underlying metrics are not stable.- If the training score is not improving, increasing `num_ucb_steps` or `batch_size` can help get more stable estimates for candidate selection.- To increase exploration, you can increase `population_size` or `num_mutants_per_candidate`.- **Resource Consideration:** The total number of model inference calls per iteration is determined by a combination of the number of candidates in the pool, the number of selection steps (`num_ucb_steps`), and the `batch_size`. Balancing these parameters is crucial to achieve the best quality with highest efficiency. When suggesting changes, always consider the trade-off between potential quality gains and the increased computational cost.
Based on the answers to the questions above, here are some common scenarios andsuggested actions. It's best to first check for and address noisy metricsbefore diving into other potential issues.
### Scenario 1: Metrics are Noisy or Train Score is Flat/Erratic
**Diagnosis:** Scores fluctuate significantly across steps, or the trainingscore is flat or erratic. This makes it difficult to determine if changes inscores are due to better prompts or random chance.
**Suggestions:**- **Increase `batch_size`:** This is often the most effective way to reduce noise, as it provides a more stable estimate of prompt performance on a larger sample of data.- **Increase `num_ucb_steps`:** More selection steps allow for more evaluations of each candidate, which can help in getting more reliable score estimates before the next generation.- **Improve Data Quality:** Examine the data for inconsistencies or errors. A cleaner dataset leads to a more stable metric.- **Run on the full dataset (for small datasets):** If your training dataset is relatively small, the noise from sampling can be high. Consider configuring the job to evaluate on the full training dataset at each step.
### Scenario 2: Both Train and Test scores are improving.
**Diagnosis:** This is the ideal outcome. The process is working as expected.
**Suggestion:**- You can stop if you are satisfied with the performance.- To potentially achieve even better results, you can try another run using the best prompt from this job as the new starting point.
### Scenario 3: Train score improves, but Test score is flat or decreasing.
**Diagnosis:** Overfitting. The prompts are becoming too tailored to thetraining data.
**Suggestions:**- **Add more data:** The most effective way to combat overfitting is to increase the number of diverse, high-quality examples in your training set.- **Enable full test evaluation:** For a more granular view of overfitting, you can evaluate every candidate prompt on the full test set. This allows for a detailed analysis of how each candidate generalizes.- **Enable full training evaluation:** For a detailed comparison between training and test performance, you can evaluate all candidate prompts against the full training set. This identifies performance gaps between seen and unseen data.
## 5. Advanced Tuning Lessons
This section provides a more structured approach to tuning, based on the`analyze_data_driven_optimize_results` output.
### I. Key Signals to Examine
Before making changes, diagnose the current state of optimization by looking atthese specific signal combinations:
1. **The "Best" Step Location** - **What to look for:** At what step do the highest scores occur? - **Why:** This indicates if the process is "undertrained" (peaked at the end) or "saturated" (peaked early).2. **Metric Stability** - **What to look for:** How much do training scores fluctuate? - **Why:** High volatility usually indicates that the sample size is too small to get a stable estimate of prompt quality.3. **Generalization Gaps** - **What to look for:** How do the trends of training and test scores compare? - **Why:** This separates healthy learning from overfitting.
### II. Tuning Guidelines & Heuristics
1. **The Hierarchy of Levers** When results are unstable or stalling, apply fixes in this order: - **Increase `batch_size` (Primary):** This is the most effective lever for stabilizing metrics and providing a smoother optimization gradient. - **Increase `num_ucb_steps` (Secondary):** Use this to further refine candidate selection. - **Adjust `num_steps` (Tertiary):** Change this only after the metric is stable.
### III. Budget and Resource Management
Tuning parameters have a direct impact on the number of model inference calls,and thus the overall cost and time required for optimization.
1. **Resource-Neutral Tuning** If you have a fixed budget, you must trade off one parameter for another: - **To increase exploration without increasing cost:** If you increase the number of mutant variants, you should decrease the population size or batch size proportionally. - **To increase stability without increasing cost:** If you increase the batch size, you must decrease the number of tracked candidates or selection steps.
2. **Cost Efficiency Heuristic** - **Increasing the number of steps** is the most direct way to spend more budget. It doesn't change the complexity of each step, just the duration. - **Increasing the population size** is the most expensive way to spend budget, as it increases the number of candidates that must be tracked and evaluated in every subsequent step.
## 6. New suggested config
Name the new config file base on the original config name. Add a suffix indexand a name to indicate the change. Only modify the Tuning Knobs and Inherit therest of the parameters from the original config.12345678910111213141516171819202122232425262728# Few-Shot Prompt Optimizer
The **Few-Shot Prompt Optimizer** helps you improve your system instructions by learning from examples.
You provide your current instructions you want to tune along with a CSV file containing questions(prompts), the model's current responses, and your feedback. The optimizer analyzes where the model fell short and automatically updates your instructions to fix those gaps.
Your example data must be saved as a CSV file in Google Cloud Storage (GCS). You can format your feedback using one of two methods:
## Method 1: Target Responses
Use this method to show the optimizer exactly what the model *should* have said. The tool compares the actual output to your ideal output and adjusts the instructions to bridge the gap.
Your CSV must include these three columns:
* **`prompt`**: The original user instruction or question.* **`model_response`**: The current model output that needs improvement.* **`target_response`**: The ideal, correct response you want the model to generate.
## Method 2: Rubrics (Grading Criteria)
Use this method to score responses based on specific rules. The tool learns from which rules the model passed or failed. Rubrics can be consistent across all rows or customized for each individual example.
Your CSV must include these four columns:
* **`prompt`**: The original user instruction or question.* **`model_response`**: The actual output generated by the model.* **`rubrics`**: A list of specific grading criteria (formatted as a string representation of a Python list of strings, e.g., `"['Tone is polite', 'Mentions pricing']"`).* **`rubrics_evaluations`**: True/False scores indicating if the model met each rule (formatted as a string representation of a Python list of booleans, e.g., `"['True', 'False']"`).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""Tools for Vertex AI Prompt Optimizer."""
import jsonfrom typing import Any
import vertexaifrom google.cloud import storagefrom vertexai._genai import Client
from . import storage as storage_utilsfrom . import utils
class PromptOptimizer: def __init__(self, project: str, location: str): """Initializes the Vertex AI client and accesses the prompt_optimizer.""" try: vertexai.init(project=project, location=location) self.client = Client(project=project, location=location) self.storage_client = storage.Client(project=project) self.project = project self.location = location print( "Initialized Vertex AI and Storage Clients for project:" f" {project}, location: {location}" ) except Exception as e: print( "Error initializing Google Cloud Clients. Ensure gcloud is" f" authenticated and APIs are enabled: {e}\n" )
self.client = None self.optimizer = None self.storage_client = None self.project = None self.location = "us-central1"
def write_config( self, gcs_config_uri: str, prompt_optimizer_method: str, target_model_endpoint_url: str | None = None, base_config: dict[str, Any] | None = None, modifications: dict[str, Any] | None = None, base_config_path: str | None = None, ) -> str: """Constructs a JSON configuration for Data-Driven Optimize and uploads it to GCS.
This tool generates a JSON configuration file based on the provided parameters and uploads it to the specified Google Cloud Storage URI. This configuration file is required to run data-driven prompt optimization.
Args: gcs_config_uri: The GCS URI where the generated VAPO config JSON file will be saved (e.g., 'gs://my-bucket/vapo/config.json'). prompt_optimizer_method: The method for prompt optimization. Either 'VAPO' or 'OPTIMIZATION_TARGET_GEMINI_NANO'. target_model_endpoint_url: The custom endpoint URL for the target model. Required for Gemini Nano target. base_config: Optional. A dictionary representing the base configuration. modifications: Optional. A dictionary representing the modifications to apply to the base config. base_config_path: Optional. Path to a base config file. If provided and `base_config` is None, this config will be loaded.
Returns: A string containing a success message and details about the uploaded configuration file, including a link to the Vertex AI console. """ if not self.storage_client: raise ValueError("Google Cloud Storage client not initialized.") if not gcs_config_uri.startswith( "gs://" ) or not gcs_config_uri.endswith(".json"): raise ValueError( "Error: `gcs_config_uri` must be a valid GCS URI ending in .json." )
config_dict = {} if base_config: config_dict = base_config.copy() elif base_config_path: try: base_bucket_name, base_object_name = base_config_path[5:].split( "/", 1 ) base_bucket = self.storage_client.get_bucket(base_bucket_name) base_blob = base_bucket.blob(base_object_name) config_dict = json.loads(base_blob.download_as_string()) except Exception as e: raise RuntimeError( f"Error reading base config from {base_config_path}: {e}" ) from e
if modifications: config_dict = utils.merge_configs(config_dict, modifications)
# Ensure tool-level parameters don't leak into the config file. config_dict.pop("prompt_optimizer_method", None)
if prompt_optimizer_method == "VAPO": # Remove parameters not supported by VAPO in the config file yet. config_dict.pop("batch_size", None) config_dict.pop("target_model_endpoint_url", None)
if target_model_endpoint_url and prompt_optimizer_method != "VAPO": config_dict["target_model_endpoint_url"] = target_model_endpoint_url
# Automatically generate demo_and_query_template if missing if "demo_and_query_template" not in config_dict: data_vars = config_dict.get("data_vars", []) label_var = config_dict.get("label_variable") if data_vars and label_var: input_vars = [v for v in data_vars if v != label_var] template_parts = [] for v in input_vars: template_parts.append(f"{v.capitalize()}: {{{{{v}}}}}") template_parts.append( f"{label_var.capitalize()}: {{{{{label_var}}}}}" ) config_dict["demo_and_query_template"] = "\n".join( template_parts )
try: bucket_name, object_name = gcs_config_uri[5:].split("/", 1) json_str = json.dumps(config_dict, indent=2) bucket = self.storage_client.get_bucket(bucket_name) blob = bucket.blob(object_name) blob.upload_from_string(json_str, content_type="application/json") return ( "Successfully created and uploaded configuration to:" f" {gcs_config_uri}\n\n" f"Remember to ensure the service account running the Vertex AI job" f" has necessary permissions " f"to access GCS (`input_data_path`, `output_path`) and Vertex AI." ) except Exception as e: raise RuntimeError( f"Error creating or uploading configuration to GCS: {e}" ) from e
def run_data_driven_optimize( self, config_gcs_path: str, service_account: str, prompt_optimizer_method: str, wait_for_completion: bool = False, ) -> str: """Starts a data-driven prompt optimization job on Vertex AI.
This method uses a dataset and configurable metrics. The `config_gcs_path` must point to a JSON file in Google Cloud Storage.
Args: config_gcs_path: The Google Cloud Storage URI (e.g., "gs://your-bucket/config.json") to a JSON file containing the Prompt Optimizer configuration. This is required. service_account: The service account email to run the job. This is required. prompt_optimizer_method: The method for prompt optimization. Either 'VAPO' or 'OPTIMIZATION_TARGET_GEMINI_NANO'. wait_for_completion: If True, the tool will block until the Vertex AI CustomJob completes. Defaults to False.
Returns: A string indicating the status and details of the optimization job, including a link to the Vertex AI console. """ if not self.client: raise ValueError( "Vertex AI client not initialized. Please check your setup (gcloud" " auth, project/location)." ) if not config_gcs_path.startswith( "gs://" ) or not config_gcs_path.endswith(".json"): raise ValueError( "Error: config_gcs_path must be a valid GCS URI to a JSON file" " (e.g., 'gs://your-bucket/config.json')." )
# Set the optimizer method based on user choice try: optimizer_method = getattr( vertexai.types.PromptOptimizerMethod, prompt_optimizer_method ) except AttributeError: raise ValueError( f"Invalid prompt_optimizer_method: {prompt_optimizer_method}. Must be" " 'VAPO' or 'OPTIMIZATION_TARGET_GEMINI_NANO'." )
vapo_config = { "config_path": config_gcs_path, "service_account": service_account, "wait_for_completion": wait_for_completion, }
try: # Using the new launch_optimization_job method in the prompts module job = self.client.prompts.launch_optimization_job( method=optimizer_method, config=vapo_config, ) # Deprecated method for reference: # job = self.client.prompt_optimizer.optimize( # method=optimizer_method, # config=vapo_config, # ) job_id = job.name.split("/")[-1] if job.name else "N/A" dashboard_url = f"https://console.cloud.google.com/vertex-ai/locations/{self.location}/training/{job_id}/cpu?project={self.project}" response_msg = "--- Data-Driven Optimization Job Started via Vertex AI SDK ---\n" response_msg += f"Vertex AI CustomJob Name: {job.name}\n" response_msg += f"Job ID: {job_id}\n" response_msg += f"Current State: {job.state.name}\n" response_msg += f"View job status and logs at: {dashboard_url}\n" if wait_for_completion: response_msg += "\nWaiting for job to complete...\n" response_msg += f"Job finished with state: {job.state.name}\n" else: response_msg += ( "\nJob is running in the background. Check the provided URL for" " progress.\n" ) return response_msg except ValueError as ve: raise ValueError(f"Configuration Error: {ve}") from ve except RuntimeError as re: raise RuntimeError( f"Job Execution Error: {re}. Check Vertex AI logs for details." ) from re except Exception as e: raise RuntimeError(f"An unexpected error occurred: {e}") from e
def run_few_shot_optimization( self, prompt_to_optimize: str, example_path: str, method: str, ) -> str: """Applies few shot prompt optimization to a prompt using user provided dataset and method.
Args: prompt_to_optimize: The zero-based index of the prompt to improve. example_path: GCS path to the csv file containg few-shot examples method: The optimization method to use for few shot prompt improvement. The method should be one of the following: - TARGET_RESPONSE: Optimize the prompt to match the target response. - RUBRICS: Optimize the prompt to improve the rubrics scores.
Returns: Optimized prompt. """ if not self.client: raise ValueError( "Error: Client was not initialized properly. Try authenticating then rerunning" )
example_df = storage_utils._read_csv_from_gcs(example_path) optimization_target = utils._get_optimization_target(method) config = vertexai.types.OptimizeConfig( optimization_target=optimization_target, examples_dataframe=example_df, ) response = self.client.prompts.optimize( prompt=prompt_to_optimize, config=config, ) return response.parsed_response.suggested_prompt123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Utility functions for reading from and writing to GCS or local paths."""
import ioimport jsonfrom pathlib import Pathfrom typing import Any
import pandas as pdfrom google.cloud import storage
EXPECTED_GCS_PARTS = 2
def _parse_gcs_uri(gcs_uri: str) -> tuple[str, str]: """Parses a GCS URI into bucket and object names.""" if not gcs_uri.startswith("gs://"): raise ValueError("Invalid GCS URI. Must start with 'gs://'.") parts = gcs_uri[5:].split("/", 1) if len(parts) != EXPECTED_GCS_PARTS: raise ValueError( "Invalid GCS URI format. Expected 'gs://bucket/object'." ) return parts[0], parts[1]
def _read_json_from_gcs(gcs_uri: str) -> Any: """Reads and parses a JSON file from GCS.""" try: storage_client = storage.Client() bucket_name, blob_name = _parse_gcs_uri(gcs_uri) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(blob_name) return json.loads(blob.download_as_string()) except Exception as e: raise RuntimeError(f"Failed to read from GCS URI {gcs_uri}: {e}") from e
def _read_csv_from_gcs(path: str) -> pd.DataFrame: if not _is_gcs_path(path) or not path.endswith(".csv"): raise ValueError( "Few-shot examples must be stored as CSV file in a GCS bucket, ", f"but `{path}` was provided", ) try: storage_client = storage.Client() bucket_name, blob_name = _parse_gcs_uri(path) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(blob_name) csv_bytes = blob.download_as_bytes() return pd.read_csv(io.BytesIO(csv_bytes)) except Exception as e: raise RuntimeError(f"Failed to read from GCS URI {path}: {e}") from e
def _write_json_to_gcs(data: Any, gcs_uri: str): """Writes a JSON object to a GCS file.""" storage_client = storage.Client() bucket_name, blob_name = _parse_gcs_uri(gcs_uri) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(blob_name) blob.upload_from_string(json.dumps(data, indent=2), "application/json")
def write_gcs_file(gcs_uri: str, content: str, content_type: str = "text/html"): """Writes string content to a GCS file.""" storage_client = storage.Client() bucket_name, blob_name = _parse_gcs_uri(gcs_uri) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(blob_name) blob.upload_from_string(content, content_type)
def _is_gcs_path(path: str) -> bool: """Checks if a path is a GCS URI.""" return path.startswith("gs://")
def read_file_from_base(base_path: str, file_name: str) -> Any: """Reads a JSON file from a local or GCS base path.""" if _is_gcs_path(base_path): file_path = f"{base_path.rstrip('/')}/{file_name}" return _read_json_from_gcs(file_path) else: file_path = str(Path(base_path) / file_name) if not Path(file_path).exists(): raise FileNotFoundError(f"File not found at {file_path}") with open(file_path) as f: return json.load(f)
def file_exists_in_base(base_path: str, file_name: str) -> bool: """Checks if a file exists in a local or GCS base path.""" if _is_gcs_path(base_path): file_path = f"{base_path.rstrip('/')}/{file_name}" storage_client = storage.Client() bucket_name, blob_name = _parse_gcs_uri(file_path) bucket = storage_client.bucket(bucket_name) return storage.Blob(bucket=bucket, name=blob_name).exists() else: file_path = str(Path(base_path) / file_name) return Path(file_path).exists()1234567891011121314151617181920212223242526272829303132333435"""Common utility functions."""
from typing import Any
import vertexai
def merge_configs( base_config: dict[str, Any], modifications: dict[str, Any]) -> dict[str, Any]: """Deep merges modifications into a base configuration.""" merged_config = base_config.copy() for key, value in modifications.items(): if value is None: if key in merged_config: del merged_config[key] elif isinstance(value, dict) and isinstance( merged_config.get(key), dict ): merged_config[key] = merge_configs(merged_config[key], value) else: merged_config[key] = value return merged_config
def _get_optimization_target(method: str) -> vertexai.types.OptimizeTarget: """Returns the optimization target for the given method.""" if method == "TARGET_RESPONSE": return vertexai.types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE elif method == "RUBRICS": return ( vertexai.types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS ) else: raise ValueError(f"Unsupported optimization method: {method}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Module for defining tools for the CLI agent."""
import osfrom collections.abc import Sequence
from absl import appfrom mcp.server import fastmcp
from . import toolsfrom .prompt_optimizer import analyzer, prompt_optimizer
def main(argv: Sequence[str]) -> None: if len(argv) > 1: raise app.UsageError("Too many command-line arguments.")
prompt_manager = tools.VertexPromptManager()
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT") or "" location_id = os.environ.get("GOOGLE_CLOUD_LOCATION") or "us-central1" optimizer_tools = prompt_optimizer.PromptOptimizer( project=project_id, location=location_id )
# Create an MCP server mcp = fastmcp.FastMCP("VertexMcpServer")
mcp.add_tool(prompt_manager.read_prompt) mcp.add_tool(prompt_manager.create_prompt) mcp.add_tool(prompt_manager.update_prompt) mcp.add_tool(prompt_manager.delete_prompt) mcp.add_tool(prompt_manager.list_prompts)
mcp.add_tool( optimizer_tools.write_config, name="write_data_driven_optimize_config" ) mcp.add_tool( optimizer_tools.run_data_driven_optimize, name="run_data_driven_optimize", ) mcp.add_tool( optimizer_tools.run_few_shot_optimization, name="run_few_shot_optimization", ) mcp.add_tool( analyzer.analyze_results, name="analyze_data_driven_optimize_results" ) mcp.add_tool(analyzer.generate_report, name="generate_html_report")
mcp.run()
if __name__ == "__main__": app.run(main)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302"""Module for defining tools for Vertex AI Prompt management."""
import itertoolsimport os
import pydanticfrom google.api_core import exceptionsfrom google.genai import _commonfrom google.genai import types as genai_typesfrom vertexai import types as vertexai_typesfrom vertexai._genai import Client
_DEFAULT_LOCATION = "us-central1"_MAX_PREVIEW_LENGTH = 100 # Define the maximum length for preview
class PromptDetails(_common.BaseModel): """Class for holding prompt details."""
prompt_id: str = pydantic.Field(..., description="The ID of the prompt.") display_name: str = pydantic.Field( ..., description="The display name of the prompt." ) system_instruction: str = pydantic.Field( ..., description="The system instruction for the prompt." ) contents: str = pydantic.Field( ..., description="The combined contents of the prompt." )
def _build_content(text: str, role: str) -> genai_types.Content: """Build the content data for the prompt.""" part = genai_types.Part(text=text) content = genai_types.Content(role=role, parts=[part]) return content
def _build_contents(text: str, role: str) -> list[genai_types.Content]: return [_build_content(text, role)]
def _truncate_text(text: str, max_length: int) -> str: """Truncates text to max_length and appends an ellipsis if truncated.""" if len(text) > max_length: return text[:max_length] + "..." return text
def _build_prompt_details( prompt: vertexai_types.Prompt, truncate_texts: bool = False) -> PromptDetails: """Helper function to format a single Prompt object into a dictionary.""" if not prompt: raise ValueError("Prompt is None. Cannot format to PromptDetails.")
prompt_data = getattr(prompt, "prompt_data", None) display_name = prompt.dataset.display_name or "N/A"
system_instruction_text = "" if prompt_data and prompt_data.system_instruction: si_parts = getattr(prompt_data.system_instruction, "parts", None) if si_parts is not None: system_instruction_text = "".join( part.text for part in si_parts if hasattr(part, "text") and part.text is not None ) if truncate_texts: system_instruction_text = _truncate_text( system_instruction_text, _MAX_PREVIEW_LENGTH )
contents_combined = "" if prompt_data and prompt_data.contents: all_content_texts = [] for content in prompt_data.contents: if content: content_parts = getattr(content, "parts", None) if content_parts is not None: part_texts = [ part.text for part in content_parts if hasattr(part, "text") and part.text is not None ] if part_texts: all_content_texts.append("".join(part_texts))
contents_combined = "".join(all_content_texts) if truncate_texts: contents_combined = _truncate_text( contents_combined, _MAX_PREVIEW_LENGTH )
return PromptDetails( prompt_id=prompt.prompt_id, display_name=display_name, system_instruction=system_instruction_text, contents=contents_combined, )
class VertexPromptManager: """Class for managing Vertex AI prompts."""
def __init__(self): self._project_id = None self._location_id = None pass
def _get_client( self, project_id: str | None = None, location_id: str | None = None, ) -> Client: """Helper to get a Vertex AI client, with env var fallback and prompting.""" final_project_id = ( project_id or self._project_id or os.environ.get("GOOGLE_CLOUD_PROJECT") )
if not final_project_id: raise ValueError( "Error: Google Cloud Project ID is required. Please set the " "GOOGLE_CLOUD_PROJECT environment variable or provide 'project_id' " "in your Gemini CLI command." ) final_location_id = ( location_id or self._location_id or os.environ.get("GOOGLE_CLOUD_LOCATION", _DEFAULT_LOCATION) ) self._project_id = final_project_id self._location_id = final_location_id print( f"Using Project: {final_project_id}, Location: {final_location_id}" ) return Client(project=final_project_id, location=final_location_id)
def read_prompt( self, prompt_id: str, project_id: str | None = None, location_id: str | None = None, ) -> PromptDetails: """Get the prompt content with given prompt id.""" prompt = self._get_prompt(prompt_id, project_id, location_id) return _build_prompt_details(prompt)
def create_prompt( self, content: str, system_instruction: str, model: str, display_name: str, project_id: str | None = None, location_id: str | None = None, ) -> PromptDetails: """Create a prompt with given content, system instruction, model and display name.""" client = self._get_client(project_id, location_id) contents = _build_contents(content, "user")
si = None if system_instruction: if isinstance(system_instruction, str): # If a plain string is provided, create genai_types.Content si = _build_content(system_instruction, "system") elif isinstance(system_instruction, list): # If it's a list, extract the single genai_types.Content if len(system_instruction) == 1 and isinstance( system_instruction[0], genai_types.Content ): si = system_instruction[0] else: raise TypeError( "If system_instruction is a list, it must contain exactly one" " genai_types.Content object." ) else: raise TypeError( "system_instruction must be str, list[genai_types.Content], or" f" None, but got {type(system_instruction).__name__}" )
# Convert si to a dictionary using .dict() if it exists, # as the PromptData likely expects a dictionary for system_instruction. si_dict = si.dict() if si else None
prompt_data = vertexai_types.PromptData( model=model, contents=contents, system_instruction=si_dict, generation_config=genai_types.GenerationConfig( temperature=0.1, top_p=0.95, top_k=20, candidate_count=1, max_output_tokens=100, ), )
prompt = vertexai_types.Prompt(prompt_data=prompt_data)
create_config = vertexai_types.CreatePromptConfig( prompt_display_name=display_name )
return _build_prompt_details( client.prompts.create(prompt=prompt, config=create_config) )
# TODO(b/455906163): Add support for updating display name of a prompt. def update_prompt( self, prompt_id: str, project_id: str | None = None, location_id: str | None = None, content: str | None = None, system_instruction: str | None = None, model: str | None = None, ) -> PromptDetails: """Update a prompt with given prompt_id and new content, system instruction, model.""" client = self._get_client(project_id, location_id) prompt = self._get_prompt( prompt_id, project_id, location_id ) # Pass project_id/location_id
if content is not None: prompt.prompt_data.contents = _build_contents(content, "user") if system_instruction is not None: prompt.prompt_data.system_instruction = _build_content( system_instruction, "system" ) if model is not None: prompt.prompt_data.model = model
try: return _build_prompt_details( client.prompts.create_version( prompt=prompt, prompt_id=prompt_id ) ) except Exception as e: raise ValueError(f"Failed to update prompt {prompt_id}.") from e
def delete_prompt( self, prompt_id: str, project_id: str | None = None, location_id: str | None = None, ) -> None: """Delete a prompt with given prompt_id.""" client = self._get_client(project_id, location_id) try: client.prompts.delete(prompt_id=prompt_id) # Use local client except exceptions.NotFound as e: raise ValueError(f"Prompt {prompt_id} not found.") from e except Exception as e: raise ValueError(f"Failed to delete prompt {prompt_id}.") from e
def list_prompts( self, display_name: str | None = None, page_size: int | None = 10, project_id: str | None = None, location_id: str | None = None, ) -> list[PromptDetails]: """Lists Vertex prompts matching a given display name.""" client = self._get_client(project_id, location_id) filter_str = "" if display_name: filter_str = f'display_name=~"(?i).*{display_name}.*"' list_config = vertexai_types.ListPromptsConfig( filter=filter_str, page_size=page_size )
raw_prompt_refs = client.prompts.list(config=list_config) prompt_refs = list(itertools.islice(raw_prompt_refs, page_size)) prompts = [ self._get_prompt(prompt_id=ref.prompt_id or "") for ref in prompt_refs ] valid_prompts = [p for p in prompts if p is not None] formatted_prompts = [ _build_prompt_details(prompt=p, truncate_texts=True) for p in valid_prompts ] return formatted_prompts
def _get_prompt( self, prompt_id: str, project_id: str | None = None, location_id: str | None = None, ) -> vertexai_types.Prompt: """Get the prompt content with given prompt id.""" client = self._get_client(project_id, location_id) try: return client.prompts.get(prompt_id=prompt_id) except exceptions.NotFound as e: raise ValueError(f"Prompt {prompt_id} not found.") from e.gemini/extensions/vertex/src/vertex.egg-info/PKG-INFOAdded+20
.gemini/extensions/vertex/src/vertex.egg-info/SOURCES.txtAdded+16
.gemini/extensions/vertex/src/vertex.egg-info/dependency_links.txtAdded+1
.gemini/extensions/vertex/src/vertex.egg-info/requires.txtAdded+15
.gemini/extensions/vertex/src/vertex.egg-info/top_level.txtAdded+1
.gemini/extensions/vertex/src/vertex/__init__.pyAdded
.gemini/extensions/vertex/src/vertex/prompt_optimizer/analyzer.pyAdded+842
.gemini/extensions/vertex/src/vertex/prompt_optimizer/docs/data_driven_optimize_output_analysis.mdAdded+143
.gemini/extensions/vertex/src/vertex/prompt_optimizer/docs/data_driven_optimize_overall_guide.mdAdded+180
.gemini/extensions/vertex/src/vertex/prompt_optimizer/docs/data_driven_optimize_tuning_guide.mdAdded+266
.gemini/extensions/vertex/src/vertex/prompt_optimizer/docs/few_shot_prompt_optimization_guide.mdAdded+28
.gemini/extensions/vertex/src/vertex/prompt_optimizer/prompt_optimizer.pyAdded+271
.gemini/extensions/vertex/src/vertex/prompt_optimizer/storage.pyAdded+101
.gemini/extensions/vertex/src/vertex/prompt_optimizer/utils.pyAdded+35
.gemini/extensions/vertex/src/vertex/server.pyAdded+54
.gemini/extensions/vertex/src/vertex/tools.pyAdded+302