use std::error::Error;
use rig_agent::AgentBuilder;
use rig_agent::tool::{Tool, ToolContext};
use rig_core::providers::openai::OpenAI;
use rig_core::providers::{opencode, openrouter};
use rig_core::test_utils::{MockCompletionModel, MockTurn};
use rig_evals::evaluators::TrajectoryMode;
use rig_evals::{
Case, Dataset, Experiment, JunitFile, LlmJudge, Markdown, Report, Target, TargetError,
TargetOutput, ToolCall, evaluators, target_fn,
};
use serde::Deserialize;
use serde_json::{Value, json};
type Result<T = ()> = std::result::Result<T, Box<dyn Error>>;
const DATASET: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/evals/support.jsonl");
const JUNIT: &str = "target/evals/junit.xml";
const RUBRIC: &str = "Is the answer polite, correct and on topic?";
const LIVE_PREAMBLE: &str = "You are the support desk. Use the tools to look up and refund orders. \
Store hours are 9 to 5, Monday to Friday. To cancel a subscription, open Settings, \
then Billing. Apologize when an order arrived broken.";
enum Backend {
Scripted,
Live { client: OpenAI, model: String },
}
impl Backend {
fn from_env() -> Result<Self> {
if let Ok(model) = std::env::var("RIG_MODEL")
&& let Some(name) = model.strip_prefix("opencode-go/")
{
if name.is_empty() {
return Err("RIG_MODEL is opencode-go/ with no model name".into());
}
let key = std::env::var("OPENCODE_GO_API_KEY")
.or_else(|_| std::env::var("OPENCODE_API_KEY"))?;
return Ok(Self::Live {
client: opencode::go_new(key),
model: name.to_owned(),
});
}
let model = std::env::var("OPENROUTER_MODEL").unwrap_or_default();
let key = std::env::var("OPENROUTER_API_KEY").unwrap_or_default();
match (model.is_empty(), key.is_empty()) {
(false, false) => Ok(Self::Live {
client: openrouter::from_env()?,
model,
}),
(true, true) => Ok(Self::Scripted),
_ => {
eprintln!(
"note: set both OPENROUTER_MODEL and OPENROUTER_API_KEY for a live run; using scripted models"
);
Ok(Self::Scripted)
}
}
}
}
#[derive(Deserialize)]
struct OrderArgs {
id: u64,
}
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
struct DeskError(String);
struct LookupOrder;
impl Tool for LookupOrder {
const NAME: &'static str = "lookup_order";
type Error = DeskError;
type Args = OrderArgs;
type Output = String;
fn description(&self) -> String {
"Look up an order by its number.".to_owned()
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {"id": {"type": "integer", "description": "The order number"}},
"required": ["id"],
})
}
async fn call(
&self,
_context: &mut ToolContext,
args: OrderArgs,
) -> std::result::Result<String, DeskError> {
Ok(format!(
"Order {} arrived broken and is eligible for a refund.",
args.id
))
}
}
struct Refund;
impl Tool for Refund {
const NAME: &'static str = "refund";
type Error = DeskError;
type Args = OrderArgs;
type Output = String;
fn description(&self) -> String {
"Issue a refund for an order by its number.".to_owned()
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {"id": {"type": "integer", "description": "The order number"}},
"required": ["id"],
})
}
async fn call(
&self,
_context: &mut ToolContext,
args: OrderArgs,
) -> std::result::Result<String, DeskError> {
Ok(format!("Refund issued for order {}.", args.id))
}
}
fn scripted_target() -> impl Target {
target_fn(|case: Case| async move {
let output = match case.id.as_str() {
"refund" => {
TargetOutput::new("A refund was issued for order 7.").with_tool_calls(vec![
ToolCall::new("lookup_order", json!({"id": 7})),
ToolCall::new("refund", json!({"id": 7})),
])
}
"hours" => TargetOutput::new("We are open 9 to 5, Monday to Friday."),
"greeting" => TargetOutput::new("Hello! How can I help?"),
"refund-followup" => TargetOutput::new("A refund was issued for order 7.")
.with_tool_calls(vec![ToolCall::new("refund", json!({"id": 7}))]),
"order9" => TargetOutput::new("Order 9 has shipped.")
.with_tool_calls(vec![ToolCall::new("lookup_order", json!({"id": 9}))]),
"cancel" => TargetOutput::new("Cancel under Settings, then Billing."),
other => return Err(TargetError::from(format!("no scripted answer for {other}"))),
};
Ok::<_, TargetError>(output)
})
}
fn scripted_judge() -> LlmJudge {
let verdicts = (0..6)
.map(|_| MockTurn::text(r#"{"score": 0.9, "reasoning": "Polite, correct and on topic."}"#));
let agent = AgentBuilder::new(MockCompletionModel::from_turns(verdicts)).build();
LlmJudge::new(agent, RUBRIC).threshold(0.7)
}
fn experiment(target: impl Target + 'static, judge: LlmJudge, exact: bool) -> Result<Experiment> {
let mut experiment = Experiment::new("support-bot")
.dataset(Dataset::load(DATASET)?)
.target(target);
if exact {
experiment = experiment.evaluator(evaluators::equals().not_applicable_without_reference());
}
Ok(experiment
.evaluator(
evaluators::trajectory(TrajectoryMode::InOrder).not_applicable_without_reference(),
)
.evaluator(evaluators::no_error())
.evaluator(judge)
.concurrency(1)
.sink(JunitFile::new(JUNIT))
.sink(Markdown::stdout()))
}
async fn run(backend: Backend) -> Result<Report> {
match backend {
Backend::Scripted => {
eprintln!("mode: scripted (no key)");
Ok(experiment(scripted_target(), scripted_judge(), true)?
.run()
.await?)
}
Backend::Live { client, model } => {
eprintln!("mode: live, model {model}");
let agent = AgentBuilder::new(client.completion(&model))
.preamble(LIVE_PREAMBLE)
.tool(LookupOrder)
.tool(Refund)
.default_max_turns(4)
.build();
let judge =
LlmJudge::goal_success(AgentBuilder::new(client.completion(&model)).build())
.threshold(0.7);
Ok(experiment(agent, judge, false)?.run().await?)
}
}
}
fn all_trials_errored(report: &Report) -> bool {
!report.trials.is_empty()
&& report.trials.iter().all(|result| {
result.trial.error.is_some()
|| result
.scores
.iter()
.any(|score| score.label.as_deref() == Some("error"))
})
}
#[tokio::main]
async fn main() -> Result {
let report = run(Backend::from_env()?).await?;
eprintln!("JUnit written to {JUNIT}");
if !report.passed() {
if all_trials_errored(&report) {
eprintln!(
"hint: every trial errored, so the provider may be rate-limiting (429); wait and run again, or lower Experiment::concurrency"
);
}
std::process::exit(1);
}
Ok(())
}