Skip to main content

paper/cli/
answer.rs

1use super::{AnswerArgs, Workspace, EXIT_FOUND, EXIT_NOT_FOUND};
2use crate::core::answer::Answer;
3use crate::core::config::Config;
4use crate::core::models::chat::ChatClient;
5use crate::core::models::polish::{self, Extract, PolishEngine};
6use anyhow::Result;
7use std::time::Duration;
8
9/// How many local passages are offered to the polishing engine.
10const MAX_POLISH_EXTRACTS: usize = 5;
11
12pub async fn run(args: AnswerArgs) -> Result<i32> {
13    let ws = Workspace::new();
14    let roots = ws.search_roots(&args.root);
15    let filters = args.filters()?;
16    let hits = ws
17        .pipeline()?
18        .search_with(&args.question, &roots, &filters)?;
19    let mut answer = Answer::from_hits(&args.question, &hits);
20
21    if args.polish && !answer.not_found {
22        match polish_answer(&args, &hits).await {
23            Ok((text, engine)) => {
24                answer.text = text;
25                answer.engine = engine;
26            }
27            Err(err) => {
28                // Any failure keeps the verbatim extract: a polished answer is a
29                // convenience, never a requirement, and the citations stay exact.
30                eprintln!("note: polish failed ({err}); returning the verbatim extract");
31            }
32        }
33    } else if args.polish {
34        eprintln!("note: nothing to polish; returning the verbatim extract");
35    }
36
37    if args.json {
38        println!("{}", serde_json::to_string_pretty(&answer)?);
39    } else {
40        println!("{}", answer.render());
41    }
42    Ok(if answer.not_found {
43        EXIT_NOT_FOUND
44    } else {
45        EXIT_FOUND
46    })
47}
48
49/// Ask the configured engine to rewrite the extract.
50///
51/// Returns the polished text and a label naming the engine, so the answer
52/// always says which engine produced it.
53async fn polish_answer(
54    args: &AnswerArgs,
55    hits: &[crate::core::search::Hit],
56) -> Result<(String, String)> {
57    if offline() {
58        anyhow::bail!("PAPER_OFFLINE is set, so no engine may be contacted");
59    }
60    let engine = PolishEngine::parse(&args.engine)?;
61    let config = Config::load()?;
62
63    let (base_url, api_key, model, timeout) = match engine {
64        PolishEngine::Local => (
65            config.local_engine.base_url.clone(),
66            None,
67            config.local_engine.model.clone(),
68            config.local_engine.timeout_secs,
69        ),
70        PolishEngine::OpenRouter => {
71            let key = if config.openrouter.api_key.is_empty() {
72                std::env::var("OPENROUTER_API_KEY").unwrap_or_default()
73            } else {
74                config.openrouter.api_key.clone()
75            };
76            if key.is_empty() {
77                anyhow::bail!(
78                    "no OpenRouter API key: set OPENROUTER_API_KEY or [openrouter] api_key in the config"
79                );
80            }
81            (
82                "https://openrouter.ai".to_string(),
83                Some(key),
84                config.openrouter.model.clone(),
85                config.openrouter.timeout_secs,
86            )
87        }
88    };
89
90    if model.trim().is_empty() {
91        anyhow::bail!("no model configured for the {} engine", engine.as_str());
92    }
93
94    // The extracts are the passages the answer may draw on: the same hits the
95    // extractive answer cites, with their exact references.
96    let extracts: Vec<Extract> = hits
97        .iter()
98        .filter(|hit| !matches!(hit.confidence, crate::core::search::Confidence::Low))
99        .take(MAX_POLISH_EXTRACTS)
100        .map(|hit| Extract {
101            reference: citation_reference(hit),
102            text: hit.content.clone(),
103        })
104        .collect();
105    if extracts.is_empty() {
106        anyhow::bail!("no extract with enough confidence to polish");
107    }
108
109    let client = ChatClient::new(
110        &base_url,
111        api_key,
112        &model,
113        Duration::from_secs(timeout.max(1)),
114    )?;
115    let text = polish::polish(&client, engine, &args.question, &extracts).await?;
116    let label = format!("{}/{}", engine.as_str(), client.model());
117    Ok((text, label))
118}
119
120/// `path:line_start-line_end`, matching what the extractive answer prints.
121fn citation_reference(hit: &crate::core::search::Hit) -> String {
122    let mut reference = hit.path.clone();
123    if let Some(anchor) = &hit.anchor {
124        reference.push_str(&format!(" [{anchor}]"));
125    }
126    if hit.line_start > 0 {
127        reference.push_str(&format!(":{}-{}", hit.line_start, hit.line_end));
128    } else if hit.page > 0 {
129        reference.push_str(&format!(":p.{}", hit.page));
130    }
131    reference
132}
133
134fn offline() -> bool {
135    std::env::var("PAPER_OFFLINE")
136        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
137        .unwrap_or(false)
138}