use crate::{
client::{Client, ProviderClient},
error::LlmError,
openai_compatible::classify_http_response,
types::{Content, WebCitation, WebSearchResult},
};
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize)]
struct SearchResponse {
results: Vec<SearchHit>,
}
#[derive(Deserialize)]
struct SearchHit {
title: String,
url: String,
#[serde(default)]
summary: String,
#[serde(default)]
snippet: String,
date: Option<String>,
}
pub(super) async fn search(transport: &Client, query: &str) -> Result<WebSearchResult, LlmError> {
let client = ProviderClient::new(transport.clone(), classify_http_response);
let path = search_path(client.base_url());
let response: SearchResponse = client.post_json(path, &json!({ "query": query })).await?;
Ok(into_result(response))
}
fn search_path(base_url: &str) -> &'static str {
if base_url.trim_end_matches('/').ends_with("/v1") {
"/tools/search"
} else {
"/v1/tools/search"
}
}
fn into_result(response: SearchResponse) -> WebSearchResult {
let (paragraphs, citations): (Vec<_>, Vec<_>) = response
.results
.into_iter()
.map(|hit| {
let text = if hit.summary.is_empty() { hit.snippet } else { hit.summary };
let day = hit.date.as_deref().and_then(|date| date.split('T').next());
let paragraph = match day {
Some(day) if !day.is_empty() => format!("{} ({day})\n{text}", hit.title),
_ => format!("{}\n{text}", hit.title),
};
(paragraph, WebCitation { title: hit.title, uri: hit.url })
})
.unzip();
let text = if paragraphs.is_empty() {
"No search results.".to_owned()
} else {
paragraphs.join("\n\n")
};
WebSearchResult { content: Content::Text(text), citations }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn search_is_addressed_under_v1_from_either_chat_base_url() {
assert_eq!(search_path("https://api.deepseek.com"), "/v1/tools/search");
assert_eq!(search_path("https://api.deepseek.com/"), "/v1/tools/search");
assert_eq!(search_path("https://api.deepseek.com/v1"), "/tools/search");
assert_eq!(search_path("https://api.deepseek.com/v1/"), "/tools/search");
}
#[test]
fn hits_become_dated_paragraphs_with_citations_in_order() {
let response: SearchResponse = serde_json::from_value(json!({ "results": [
{
"title": "The Book",
"url": "https://example.org/book",
"summary": "Ownership, explained at length.",
"snippet": "Ownership.",
"date": "2026-10-30T08:00:00Z",
"rerank_score": 2.4
},
{ "title": "A Guide", "url": "https://example.org/guide", "summary": "",
"snippet": "Borrowing.", "date": null }
]}))
.unwrap();
let result = into_result(response);
assert_eq!(
result.content.as_text(),
"The Book (2026-10-30)\nOwnership, explained at length.\n\nA Guide\nBorrowing."
);
let links: Vec<_> = result.citations.iter().map(|source| source.uri.as_str()).collect();
assert_eq!(links, ["https://example.org/book", "https://example.org/guide"]);
}
#[test]
fn an_empty_result_set_says_so() {
let result = into_result(SearchResponse { results: vec![] });
assert_eq!(result.content.as_text(), "No search results.");
assert!(result.citations.is_empty());
}
}