ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
Documentation
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! DeepSeek's search endpoint (`POST /v1/tools/search`): a query in, ranked
//! results out. It involves no model, unlike the hosted search tools.

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,
    /// The longer summary written for a model to read.
    #[serde(default)]
    summary: String,
    /// The short one written for display.
    #[serde(default)]
    snippet: String,
    /// Publication time in RFC 3339, when the engine knows it.
    date: Option<String>,
}

/// The query goes out unchecked: the endpoint refuses a blank or over-long
/// one itself, naming what to change.
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))
}

/// Search lives under `/v1`, and the chat base URL may be the API root or
/// its `/v1` alias.
fn search_path(base_url: &str) -> &'static str {
    if base_url.trim_end_matches('/').ends_with("/v1") {
        "/tools/search"
    } else {
        "/v1/tools/search"
    }
}

/// One paragraph per hit — its title, its date when known, and its summary —
/// with the links as citations in the same order.
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());
    }
}