1#[allow(dead_code, unused_imports)]
2use std::fs;
3use std::path::{Path, PathBuf};
4use std::time::{Duration, Instant};
5
6use anyhow::{Context, anyhow, bail};
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_mins(5);
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct ProviderRunConfig {
15 pub run_id: String,
16 pub task_description: String,
17 pub commit_sha: String,
18 pub repo_path: PathBuf,
19 pub provider: String,
20 pub model: String,
21 pub prompt_template: String,
22 pub target_files: Vec<PathBuf>,
23 pub budget_tokens: u64,
24 pub temperature: f32,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum ArmType {
31 Baseline,
32 Treatment,
33}
34
35impl ArmType {
36 fn label(self) -> &'static str {
37 match self {
38 Self::Baseline => "baseline",
39 Self::Treatment => "treatment",
40 }
41 }
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct ArmResult {
47 pub arm_type: ArmType,
48 pub provider: String,
51 pub model: String,
53 pub commit_sha: String,
55 pub input_tokens: u64,
56 pub cached_tokens: u64,
57 pub output_tokens: u64,
58 pub cost_micros: u64,
59 pub latency_ms: u64,
60 pub output_content: String,
61 pub proxy_observed: bool,
62 pub measurement_method: String,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct ComparisonSummary {
68 pub token_savings_ratio: f64,
69 pub cost_savings_ratio: f64,
70 pub quality_preserved: Option<bool>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct ProviderRunResult {
76 pub run_id: String,
77 pub baseline: ArmResult,
78 pub treatment: ArmResult,
79 pub comparison: ComparisonSummary,
80}
81
82pub async fn execute_provider_run(
84 config: ProviderRunConfig,
85) -> Result<ProviderRunResult, anyhow::Error> {
86 validate_config(&config)?;
87 let (prompt, context) = load_task_material(&config)?;
88
89 let baseline_config = config.clone();
90 let baseline_prompt = prompt.clone();
91 let baseline = tokio::task::spawn_blocking(move || {
92 execute_arm(&baseline_config, ArmType::Baseline, &baseline_prompt)
93 })
94 .await
95 .context("baseline provider task failed to join")??;
96
97 let treatment_config = config.clone();
98 let treatment_prompt = prompt.clone();
99 let treatment = tokio::task::spawn_blocking(move || {
100 execute_arm(&treatment_config, ArmType::Treatment, &treatment_prompt)
101 })
102 .await
103 .context("treatment provider task failed to join")??;
104
105 let comparison = compare_arms(&baseline, &treatment);
106 let result = ProviderRunResult {
107 run_id: config.run_id.clone(),
108 baseline,
109 treatment,
110 comparison,
111 };
112
113 save_artifacts(&config, &prompt, &context, &result)?;
114 Ok(result)
115}
116
117fn validate_config(config: &ProviderRunConfig) -> anyhow::Result<()> {
118 if config.run_id.trim().is_empty() {
119 bail!("provider run id must not be empty");
120 }
121 if config.provider.trim().is_empty() {
122 bail!("provider must not be empty");
123 }
124 if config.model.trim().is_empty() {
125 bail!("model must not be empty");
126 }
127 if config.budget_tokens == 0 {
128 bail!("budget_tokens must be greater than zero");
129 }
130 if !config.temperature.is_finite() || config.temperature < 0.0 {
131 bail!("temperature must be finite and non-negative");
132 }
133 Ok(())
134}
135
136fn load_task_material(config: &ProviderRunConfig) -> anyhow::Result<(String, String)> {
137 let template_path = resolve_repo_path(&config.repo_path, Path::new(&config.prompt_template));
138 let template = fs::read_to_string(&template_path)
139 .with_context(|| format!("failed to read prompt template {}", template_path.display()))?;
140
141 let mut context_parts = Vec::with_capacity(config.target_files.len());
142 for target in &config.target_files {
143 let path = resolve_repo_path(&config.repo_path, target);
144 let content = fs::read_to_string(&path)
145 .with_context(|| format!("failed to read target file {}", path.display()))?;
146 let display_path = path
147 .strip_prefix(&config.repo_path)
148 .unwrap_or(&path)
149 .display();
150 context_parts.push(format!("===== {display_path} =====\n{content}"));
151 }
152 let context = context_parts.join("\n\n");
153 let target_files = config
154 .target_files
155 .iter()
156 .map(|path| path.display().to_string())
157 .collect::<Vec<_>>()
158 .join("\n");
159 let repo_path = config.repo_path.display().to_string();
160
161 let prompt = render_prompt(
162 &template,
163 &[
164 ("{run_id}", config.run_id.as_str()),
165 ("{task_description}", config.task_description.as_str()),
166 ("{commit_sha}", config.commit_sha.as_str()),
167 ("{repo_path}", &repo_path),
168 ("{provider}", config.provider.as_str()),
169 ("{model}", config.model.as_str()),
170 ("{target_files}", &target_files),
171 ("{context}", &context),
172 ],
173 );
174
175 Ok((prompt, context))
176}
177
178fn resolve_repo_path(repo_path: &Path, path: &Path) -> PathBuf {
179 if path.is_absolute() {
180 path.to_path_buf()
181 } else {
182 repo_path.join(path)
183 }
184}
185
186fn render_prompt(template: &str, replacements: &[(&str, &str)]) -> String {
187 let mut rendered = template.to_owned();
188 for (placeholder, value) in replacements {
189 rendered = rendered.replace(placeholder, value);
190 }
191 if !template.contains("{context}") {
192 if let Some((_, context)) = replacements.iter().find(|(key, _)| *key == "{context}") {
193 rendered.push_str("\n\n## Review context\n\n");
194 rendered.push_str(context);
195 }
196 }
197 rendered
198}
199
200fn execute_arm(
201 config: &ProviderRunConfig,
202 arm_type: ArmType,
203 prompt: &str,
204) -> anyhow::Result<ArmResult> {
205 let provider = config.provider.trim().to_ascii_lowercase();
206 let base_url = if arm_type == ArmType::Treatment {
207 proxy_base_url()
208 } else {
209 direct_base_url(&provider)
210 };
211 let url = request_url(&base_url, &provider, &config.model);
212 let payload = request_payload(config, &provider, prompt);
213 let payload = serde_json::to_vec(&payload).context("failed to encode provider request")?;
214 let api_key = provider_api_key(&provider);
215 let started = Instant::now();
216
217 let response = send_provider_request(
218 &url,
219 &provider,
220 &api_key,
221 &config.run_id,
222 arm_type,
223 &payload,
224 )
225 .with_context(|| format!("{arm_type:?} provider request failed"))?;
226 let latency_ms = elapsed_ms(started);
227 let headers = response.headers;
228 let response_body = response.body;
229 let body: Value = serde_json::from_str(&response_body)
230 .with_context(|| format!("{arm_type:?} provider returned invalid JSON: {response_body}"))?;
231
232 let output_content = extract_output_content(&body, &provider)
233 .ok_or_else(|| anyhow!("{arm_type:?} provider response contained no text content"))?;
234 let usage = usage_metrics(&body, &headers);
235 let estimated_input = estimate_tokens(prompt);
236 let estimated_output = estimate_tokens(&output_content);
237 let input_tokens = usage.input_tokens.unwrap_or(estimated_input);
238 let output_tokens = usage.output_tokens.unwrap_or(estimated_output);
239 let had_provider_token_usage = usage.input_tokens.is_some() && usage.output_tokens.is_some();
240 let measurement_method = if had_provider_token_usage {
241 "provider_reported"
242 } else if input_tokens > 0 || output_tokens > 0 {
243 "estimated"
244 } else {
245 "unavailable"
246 };
247 let cost_micros = cost_from_headers(&headers).or_else(|| {
248 if input_tokens == 0 && output_tokens == 0 {
249 None
250 } else {
251 estimated_cost_micros(&config.model, input_tokens, output_tokens)
252 }
253 });
254
255 Ok(ArmResult {
256 arm_type,
257 provider,
258 model: config.model.clone(),
259 commit_sha: config.commit_sha.clone(),
260 input_tokens,
261 cached_tokens: usage.cached_tokens.unwrap_or(0),
262 output_tokens,
263 cost_micros: cost_micros.unwrap_or(0),
264 latency_ms,
265 output_content,
266 proxy_observed: arm_type == ArmType::Treatment,
267 measurement_method: measurement_method.to_owned(),
268 })
269}
270
271struct ProviderResponse {
272 body: String,
273 headers: Vec<(String, String)>,
274}
275
276fn send_provider_request(
277 url: &str,
278 provider: &str,
279 api_key: &str,
280 run_id: &str,
281 arm_type: ArmType,
282 payload: &[u8],
283) -> anyhow::Result<ProviderResponse> {
284 let agent = crate::core::http_client::ureq_agent(
285 ureq::config::Config::builder()
286 .tls_config(crate::core::http_client::platform_tls_config())
287 .timeout_global(Some(request_timeout()))
288 .build(),
289 );
290 let mut request = agent
291 .post(url)
292 .header("Content-Type", "application/json")
293 .header("x-leanctx-provider-run-id", run_id)
294 .header("x-leanctx-provider-run-arm", arm_type.label());
295 if provider == "anthropic" {
296 if !api_key.is_empty() {
297 request = request.header("x-api-key", api_key);
298 }
299 request = request.header("anthropic-version", "2023-06-01");
300 } else if !api_key.is_empty() {
301 request = request.header("Authorization", &format!("Bearer {api_key}"));
302 }
303
304 let response = request
305 .send(payload)
306 .map_err(|error| anyhow!("HTTP request failed: {error}"))?;
307 let headers = response
308 .headers()
309 .iter()
310 .filter_map(|(name, value)| {
311 Some((
312 name.as_str().to_ascii_lowercase(),
313 value.to_str().ok()?.to_owned(),
314 ))
315 })
316 .collect();
317 let body = response
318 .into_body()
319 .read_to_string()
320 .map_err(|error| anyhow!("failed to read provider response: {error}"))?;
321 Ok(ProviderResponse { body, headers })
322}
323
324fn request_payload(config: &ProviderRunConfig, provider: &str, prompt: &str) -> Value {
325 if provider == "anthropic" {
326 serde_json::json!({
327 "model": config.model,
328 "max_tokens": config.budget_tokens,
329 "temperature": config.temperature,
330 "messages": [{"role": "user", "content": prompt}],
331 })
332 } else if matches!(provider, "gemini" | "google") {
333 serde_json::json!({
334 "contents": [{"role": "user", "parts": [{"text": prompt}]}],
335 "generationConfig": {
336 "maxOutputTokens": config.budget_tokens,
337 "temperature": config.temperature,
338 },
339 })
340 } else {
341 serde_json::json!({
342 "model": config.model,
343 "max_tokens": config.budget_tokens,
344 "temperature": config.temperature,
345 "messages": [{"role": "user", "content": prompt}],
346 "stream": false,
347 })
348 }
349}
350
351fn extract_output_content(body: &Value, provider: &str) -> Option<String> {
352 if provider == "anthropic" {
353 if let Some(content) = body.get("content").and_then(Value::as_array) {
354 let text = content
355 .iter()
356 .filter_map(|block| block.get("text").and_then(Value::as_str))
357 .collect::<Vec<_>>()
358 .join("");
359 if !text.is_empty() {
360 return Some(text);
361 }
362 }
363 }
364 if matches!(provider, "gemini" | "google") {
365 if let Some(text) = body
366 .get("candidates")
367 .and_then(Value::as_array)
368 .and_then(|candidates| candidates.first())
369 .and_then(|candidate| candidate.get("content"))
370 .and_then(|content| content.get("parts"))
371 .and_then(Value::as_array)
372 .map(|parts| {
373 parts
374 .iter()
375 .filter_map(|part| part.get("text").and_then(Value::as_str))
376 .collect::<Vec<_>>()
377 .join("")
378 })
379 .filter(|text| !text.is_empty())
380 {
381 return Some(text);
382 }
383 }
384 body.get("output_text")
385 .and_then(Value::as_str)
386 .or_else(|| body.get("content").and_then(Value::as_str))
387 .or_else(|| {
388 body.get("choices")
389 .and_then(Value::as_array)
390 .and_then(|choices| choices.first())
391 .and_then(|choice| choice.get("message"))
392 .and_then(|message| message.get("content"))
393 .and_then(Value::as_str)
394 })
395 .or_else(|| {
396 body.get("choices")
397 .and_then(Value::as_array)
398 .and_then(|choices| choices.first())
399 .and_then(|choice| choice.get("text"))
400 .and_then(Value::as_str)
401 })
402 .map(str::to_owned)
403 .filter(|text| !text.is_empty())
404}
405
406#[derive(Default)]
407struct UsageMetrics {
408 input_tokens: Option<u64>,
409 cached_tokens: Option<u64>,
410 output_tokens: Option<u64>,
411}
412
413fn usage_metrics(body: &Value, headers: &[(String, String)]) -> UsageMetrics {
414 let usage = body.get("usage");
415 let input_tokens = usage.and_then(|usage| {
416 first_json_u64(
417 usage,
418 &["input_tokens", "prompt_tokens", "promptTokenCount"],
419 )
420 });
421 let cached_tokens = usage.and_then(|usage| {
422 first_json_u64(
423 usage,
424 &[
425 "cache_read_input_tokens",
426 "cache_read_tokens",
427 "cached_tokens",
428 "cachedContentTokenCount",
429 ],
430 )
431 });
432 let output_tokens = usage.and_then(|usage| {
433 first_json_u64(
434 usage,
435 &["output_tokens", "completion_tokens", "candidatesTokenCount"],
436 )
437 });
438
439 UsageMetrics {
440 input_tokens: input_tokens.or_else(|| {
441 header_u64(
442 headers,
443 &[
444 "x-leanctx-input-tokens",
445 "x-leanctx-compressed-input-tokens",
446 "x-provider-input-tokens",
447 ],
448 )
449 }),
450 cached_tokens: cached_tokens.or_else(|| {
451 header_u64(
452 headers,
453 &["x-leanctx-cached-tokens", "x-provider-cached-tokens"],
454 )
455 }),
456 output_tokens: output_tokens.or_else(|| {
457 header_u64(
458 headers,
459 &["x-leanctx-output-tokens", "x-provider-output-tokens"],
460 )
461 }),
462 }
463}
464
465fn first_json_u64(value: &Value, keys: &[&str]) -> Option<u64> {
466 keys.iter()
467 .find_map(|key| value.get(*key).and_then(json_u64))
468 .or_else(|| {
469 value
470 .get("prompt_tokens_details")
471 .and_then(|details| details.get("cached_tokens"))
472 .and_then(json_u64)
473 })
474}
475
476fn json_u64(value: &Value) -> Option<u64> {
477 value.as_u64().or_else(|| {
478 value
479 .as_f64()
480 .filter(|number| number.is_finite() && *number >= 0.0)
481 .map(|number| number.round() as u64)
482 })
483}
484
485fn header_u64(headers: &[(String, String)], names: &[&str]) -> Option<u64> {
486 names.iter().find_map(|name| {
487 headers
488 .iter()
489 .find(|(header, _)| header == name)
490 .and_then(|(_, value)| value.trim().parse::<u64>().ok())
491 })
492}
493
494fn cost_from_headers(headers: &[(String, String)]) -> Option<u64> {
495 headers.iter().find_map(|(name, value)| {
496 if !name.contains("cost") {
497 return None;
498 }
499 let value = value.trim().trim_start_matches('$');
500 if name.contains("micro") {
501 return value.parse::<u64>().ok();
502 }
503 let dollars = value.parse::<f64>().ok()?;
504 if !dollars.is_finite() || dollars < 0.0 {
505 return None;
506 }
507 Some((dollars * 1_000_000.0).round() as u64)
508 })
509}
510
511fn estimate_tokens(text: &str) -> u64 {
512 if text.is_empty() {
513 return 0;
514 }
515 text.len().div_ceil(4) as u64
516}
517
518fn estimated_cost_micros(model: &str, input_tokens: u64, output_tokens: u64) -> Option<u64> {
519 let usd = crate::core::benchmark_study::llm_client::cost_for_tokens(
520 model,
521 input_tokens,
522 output_tokens,
523 );
524 if usd.is_finite() && usd >= 0.0 {
525 Some((usd * 1_000_000.0).round() as u64)
526 } else {
527 None
528 }
529}
530
531fn compare_arms(baseline: &ArmResult, treatment: &ArmResult) -> ComparisonSummary {
532 ComparisonSummary {
533 token_savings_ratio: savings_ratio(baseline.input_tokens, treatment.input_tokens),
534 cost_savings_ratio: savings_ratio(baseline.cost_micros, treatment.cost_micros),
535 quality_preserved: None,
536 }
537}
538
539fn savings_ratio(baseline: u64, treatment: u64) -> f64 {
540 if baseline == 0 {
541 0.0
542 } else {
543 (baseline as f64 - treatment as f64) / baseline as f64
544 }
545}
546
547fn elapsed_ms(started: Instant) -> u64 {
548 started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64
549}
550
551fn request_timeout() -> Duration {
552 std::env::var("LEAN_CTX_PROVIDER_RUN_TIMEOUT_SECS")
553 .ok()
554 .and_then(|value| value.parse::<u64>().ok())
555 .map(Duration::from_secs)
556 .filter(|timeout| !timeout.is_zero())
557 .unwrap_or(DEFAULT_REQUEST_TIMEOUT)
558}
559
560fn direct_base_url(provider: &str) -> String {
561 let env_name = format!(
562 "LEAN_CTX_PROVIDER_RUN_{}_BASE_URL",
563 provider.to_ascii_uppercase().replace('-', "_")
564 );
565 std::env::var(&env_name)
566 .or_else(|_| std::env::var("LEAN_CTX_PROVIDER_RUN_BASE_URL"))
567 .or_else(|_| std::env::var(format!("{}_BASE_URL", provider.to_ascii_uppercase())))
568 .unwrap_or_else(|_| match provider {
569 "anthropic" => "https://api.anthropic.com".to_owned(),
570 "gemini" | "google" => "https://generativelanguage.googleapis.com".to_owned(),
571 _ => "https://api.openai.com".to_owned(),
572 })
573}
574
575fn proxy_base_url() -> String {
576 std::env::var("LEAN_CTX_PROVIDER_RUN_PROXY_URL")
577 .or_else(|_| std::env::var("LEAN_CTX_PROXY_URL"))
578 .unwrap_or_else(|_| format!("http://127.0.0.1:{}", crate::proxy_setup::default_port()))
579}
580
581fn provider_api_key(provider: &str) -> String {
582 let env_name = format!(
583 "{}_API_KEY",
584 provider.to_ascii_uppercase().replace('-', "_")
585 );
586 if let Ok(key) = std::env::var(&env_name) {
587 return key;
588 }
589 if provider == "anthropic" {
590 std::env::var("ANTHROPIC_API_KEY").unwrap_or_default()
591 } else {
592 std::env::var("OPENAI_API_KEY").unwrap_or_default()
593 }
594}
595
596fn request_url(base_url: &str, provider: &str, model: &str) -> String {
597 let base = base_url.trim_end_matches('/');
598 if matches!(provider, "gemini" | "google") {
599 format!("{base}/v1beta/models/{model}:generateContent")
600 } else if provider == "anthropic" {
601 format!("{base}/v1/messages")
602 } else {
603 format!("{base}/v1/chat/completions")
604 }
605}
606
607fn save_artifacts(
608 config: &ProviderRunConfig,
609 prompt: &str,
610 context: &str,
611 result: &ProviderRunResult,
612) -> anyhow::Result<()> {
613 let run_dir = poc_run_directory(config);
614 fs::create_dir_all(&run_dir)
615 .with_context(|| format!("failed to create POC run directory {}", run_dir.display()))?;
616 write_json(&run_dir.join("config.json"), config)?;
617 write_json(&run_dir.join("baseline.json"), &result.baseline)?;
618 write_json(&run_dir.join("treatment.json"), &result.treatment)?;
619 write_json(&run_dir.join("comparison.json"), &result.comparison)?;
620 write_json(&run_dir.join("result.json"), result)?;
621 fs::write(run_dir.join("prompt.txt"), prompt)
622 .with_context(|| format!("failed to write {}", run_dir.join("prompt.txt").display()))?;
623 fs::write(run_dir.join("context.txt"), context)
624 .with_context(|| format!("failed to write {}", run_dir.join("context.txt").display()))?;
625 fs::write(
626 run_dir.join("baseline.output.txt"),
627 &result.baseline.output_content,
628 )
629 .with_context(|| format!("failed to write baseline output in {}", run_dir.display()))?;
630 fs::write(
631 run_dir.join("treatment.output.txt"),
632 &result.treatment.output_content,
633 )
634 .with_context(|| format!("failed to write treatment output in {}", run_dir.display()))?;
635 Ok(())
636}
637
638fn write_json<T: Serialize>(path: &Path, value: &T) -> anyhow::Result<()> {
639 let json = serde_json::to_vec_pretty(value).context("failed to serialize run artifact")?;
640 fs::write(path, json).with_context(|| format!("failed to write {}", path.display()))?;
641 Ok(())
642}
643
644fn poc_run_directory(config: &ProviderRunConfig) -> PathBuf {
645 let root = std::env::var_os("LEAN_CTX_POC_RUN_DIR")
646 .or_else(|| std::env::var_os("LEAN_CTX_POC_DIR"))
647 .or_else(|| std::env::var_os("LEAN_CTX_RUN_DIR"))
648 .map(PathBuf::from)
649 .unwrap_or_else(|| config.repo_path.join(".lean-ctx").join("poc").join("runs"));
650 root.join(safe_path_component(&config.run_id))
651}
652
653fn safe_path_component(value: &str) -> String {
654 let sanitized = value
655 .chars()
656 .map(|character| {
657 if character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') {
658 character
659 } else {
660 '_'
661 }
662 })
663 .collect::<String>();
664 if sanitized.is_empty() {
665 "run".to_owned()
666 } else {
667 sanitized
668 }
669}
670
671#[cfg(test)]
672mod tests {
673 use super::*;
674
675 #[test]
676 fn matched_ratio_reports_savings_and_regressions() {
677 assert!((savings_ratio(100, 25) - 0.75).abs() < f64::EPSILON);
678 assert!((savings_ratio(100, 125) + 0.25).abs() < f64::EPSILON);
679 assert_eq!(savings_ratio(0, 0), 0.0);
680 }
681
682 #[test]
683 fn cost_headers_accept_usd_and_micros() {
684 let headers = vec![
685 ("x-litellm-response-cost".to_owned(), "0.00042".to_owned()),
686 ("x-provider-cost-micros".to_owned(), "7".to_owned()),
687 ];
688 assert_eq!(cost_from_headers(&headers), Some(420));
689 assert_eq!(
690 cost_from_headers(&[("x-provider-cost-micros".to_owned(), "7".to_owned())]),
691 Some(7)
692 );
693 }
694
695 #[test]
696 fn prompt_context_is_added_when_template_has_no_context_slot() {
697 let rendered = render_prompt("Review this task", &[("{context}", "file body")]);
698 assert!(rendered.contains("Review context"));
699 assert!(rendered.contains("file body"));
700 }
701
702 #[test]
703 fn output_parsers_cover_provider_shapes() {
704 let anthropic = serde_json::json!({
705 "content": [{"type": "text", "text": "hello"}]
706 });
707 let openai = serde_json::json!({
708 "choices": [{"message": {"content": "world"}}]
709 });
710 assert_eq!(
711 extract_output_content(&anthropic, "anthropic").as_deref(),
712 Some("hello")
713 );
714 assert_eq!(
715 extract_output_content(&openai, "openai").as_deref(),
716 Some("world")
717 );
718 }
719}