Opik Agent Optimizer is designed to be a flexible framework for prompt and agent optimization. While
it provides a suite of powerful built-in algorithms, you might have unique optimization strategies or
specialized needs. This guide shows how to build your own optimizer by extending the BaseOptimizer
class that all built-in optimizers use.
All optimizers in the SDK extend BaseOptimizer, giving you access to the same infrastructure:
To design a new optimization algorithm within Opik’s ecosystem, your optimizer needs to interact with several key components:
Prompt (ChatPrompt): Your optimizer takes a ChatPrompt object as input. The chat prompt
is a list of messages, where each message has a role, content, and optional additional
fields. This includes variables that need to be replaced with actual values.
Evaluation Mechanism (Metric & Dataset): Your optimizer needs a way to score candidate
prompts. This is achieved by creating a metric (function that takes dataset_item and
llm_output as arguments and returns a float) and an evaluation dataset.
Optimization Loop: This is the heart of your custom optimizer. It involves:
metric and dataset to get a score for each candidate.Returning Results (OptimizationResult): Upon completion, your optimizer returns an
OptimizationResult object that standardizes how results are reported, including the best prompt
found, its score, history of the optimization process, and cost/usage metrics.
Extend BaseOptimizer and define your DEFAULT_PROMPTS - the internal prompts your algorithm uses:
This is the core method implementing your optimization logic:
Your custom logic to create new prompt variations. Use get_prompt() to access internal prompts (which respects user’s prompt_overrides):
The BaseOptimizer class provides robust mechanisms for prompt evaluation that all existing optimizers leverage. Your
custom optimizer reuses these internal evaluation utilities to ensure consistency with the Opik ecosystem.
For complex generation, use Pydantic models for structured LLM responses:
Opik is continuously evolving, and community contributions are valuable!
BaseOptimizer to create custom optimization algorithms with full access to Opik’s infrastructureDEFAULT_PROMPTS for your algorithm’s internal prompts - users can customize these via prompt_overridesoptimize_prompt() with your optimization logic, using the inherited evaluate_prompt() to score candidatesOptimizationResult objects for consistent reporting and dashboard integration_llm_calls.call_model() for LLM interactions with automatic cost/usage trackingWe encourage you to explore the existing optimizer algorithms to see different approaches to these challenges.