Skip to main content

oxirs_chat/
knowledge_bases.rs

1//! External Knowledge Base Integrations
2//!
3//! Provides connectors for Wikipedia, PubMed, and other external knowledge sources
4//! to enhance RAG capabilities with authoritative external data.
5
6use anyhow::{anyhow, Context, Result};
7use reqwest::Client;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use std::time::Duration;
11use tracing::{debug, info, warn};
12
13/// Knowledge base query result
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct KnowledgeBaseResult {
16    /// Source knowledge base
17    pub source: String,
18    /// Result title
19    pub title: String,
20    /// Content/summary
21    pub content: String,
22    /// Full URL to the resource
23    pub url: String,
24    /// Relevance score (0.0 - 1.0)
25    pub relevance: f32,
26    /// Additional metadata
27    pub metadata: HashMap<String, String>,
28}
29
30/// Wikipedia API connector
31pub struct WikipediaConnector {
32    client: Client,
33    api_endpoint: String,
34    language: String,
35}
36
37impl WikipediaConnector {
38    /// Create a new Wikipedia connector
39    pub fn new(language: Option<String>) -> Result<Self> {
40        let language = language.unwrap_or_else(|| "en".to_string());
41        let api_endpoint = format!("https://{}.wikipedia.org/w/api.php", language);
42
43        let client = Client::builder()
44            .timeout(Duration::from_secs(30))
45            .user_agent("OxiRS-Chat/0.1.0")
46            .build()
47            .context("Failed to create HTTP client for Wikipedia")?;
48
49        info!("Initialized Wikipedia connector for language: {}", language);
50
51        Ok(Self {
52            client,
53            api_endpoint,
54            language,
55        })
56    }
57
58    /// Search Wikipedia articles
59    pub async fn search(
60        &self,
61        query: &str,
62        max_results: usize,
63    ) -> Result<Vec<KnowledgeBaseResult>> {
64        debug!("Searching Wikipedia for: {}", query);
65
66        // Use Wikipedia's opensearch API
67        let response = self
68            .client
69            .get(&self.api_endpoint)
70            .query(&[
71                ("action", "opensearch"),
72                ("search", query),
73                ("limit", &max_results.to_string()),
74                ("format", "json"),
75            ])
76            .send()
77            .await
78            .context("Failed to send request to Wikipedia API")?;
79
80        if !response.status().is_success() {
81            return Err(anyhow!("Wikipedia API error: {}", response.status()));
82        }
83
84        let search_results: WikipediaSearchResponse = response
85            .json()
86            .await
87            .context("Failed to parse Wikipedia search response")?;
88
89        let mut results = Vec::new();
90
91        for i in 0..search_results.1.len() {
92            let title = &search_results.1[i];
93            let description = search_results.2.get(i).cloned().unwrap_or_default();
94            let url = search_results.3.get(i).cloned().unwrap_or_default();
95
96            // Get article content
97            let content = self.get_article_summary(title).await.unwrap_or(description);
98
99            results.push(KnowledgeBaseResult {
100                source: "wikipedia".to_string(),
101                title: title.clone(),
102                content,
103                url,
104                relevance: 1.0 - (i as f32 / max_results as f32), // Decreasing relevance
105                metadata: {
106                    let mut meta = HashMap::new();
107                    meta.insert("language".to_string(), self.language.clone());
108                    meta
109                },
110            });
111        }
112
113        info!(
114            "Found {} Wikipedia results for query: {}",
115            results.len(),
116            query
117        );
118        Ok(results)
119    }
120
121    /// Get article summary
122    async fn get_article_summary(&self, title: &str) -> Result<String> {
123        let response = self
124            .client
125            .get(&self.api_endpoint)
126            .query(&[
127                ("action", "query"),
128                ("prop", "extracts"),
129                ("exintro", "1"),
130                ("explaintext", "1"),
131                ("titles", title),
132                ("format", "json"),
133            ])
134            .send()
135            .await?;
136
137        let result: serde_json::Value = response.json().await?;
138
139        // Extract summary from nested JSON structure
140        if let Some(pages) = result["query"]["pages"].as_object() {
141            for (_page_id, page_data) in pages {
142                if let Some(extract) = page_data["extract"].as_str() {
143                    return Ok(extract.to_string());
144                }
145            }
146        }
147
148        Err(anyhow!("Failed to extract summary from Wikipedia response"))
149    }
150}
151
152/// PubMed API connector
153pub struct PubMedConnector {
154    client: Client,
155    api_endpoint: String,
156    api_key: Option<String>,
157}
158
159impl PubMedConnector {
160    /// Create a new PubMed connector
161    pub fn new(api_key: Option<String>) -> Result<Self> {
162        let api_endpoint = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils".to_string();
163
164        let client = Client::builder()
165            .timeout(Duration::from_secs(30))
166            .user_agent("OxiRS-Chat/0.1.0 (contact: support@oxirs.org)")
167            .build()
168            .context("Failed to create HTTP client for PubMed")?;
169
170        info!("Initialized PubMed connector");
171
172        Ok(Self {
173            client,
174            api_endpoint,
175            api_key,
176        })
177    }
178
179    /// Search PubMed articles
180    pub async fn search(
181        &self,
182        query: &str,
183        max_results: usize,
184    ) -> Result<Vec<KnowledgeBaseResult>> {
185        debug!("Searching PubMed for: {}", query);
186
187        // Step 1: Search for PMIDs
188        let pmids = self.search_pmids(query, max_results).await?;
189
190        // Step 2: Fetch article details for each PMID
191        let mut results = Vec::new();
192
193        for (i, pmid) in pmids.iter().enumerate() {
194            match self.fetch_article_details(pmid).await {
195                Ok(article) => {
196                    results.push(KnowledgeBaseResult {
197                        source: "pubmed".to_string(),
198                        title: article.title,
199                        content: article.abstract_text,
200                        url: format!("https://pubmed.ncbi.nlm.nih.gov/{}/", pmid),
201                        relevance: 1.0 - (i as f32 / max_results as f32),
202                        metadata: {
203                            let mut meta = HashMap::new();
204                            meta.insert("pmid".to_string(), pmid.clone());
205                            meta.insert("authors".to_string(), article.authors.join(", "));
206                            if let Some(doi) = article.doi {
207                                meta.insert("doi".to_string(), doi);
208                            }
209                            meta
210                        },
211                    });
212                }
213                Err(e) => {
214                    warn!("Failed to fetch PubMed article {}: {}", pmid, e);
215                }
216            }
217
218            // Rate limiting: PubMed allows 3 requests/second without API key, 10 with key
219            let delay_ms = if self.api_key.is_some() { 100 } else { 340 };
220            tokio::time::sleep(Duration::from_millis(delay_ms)).await;
221        }
222
223        info!(
224            "Found {} PubMed results for query: {}",
225            results.len(),
226            query
227        );
228        Ok(results)
229    }
230
231    /// Search for PMIDs matching the query
232    async fn search_pmids(&self, query: &str, max_results: usize) -> Result<Vec<String>> {
233        let max_results_str = max_results.to_string();
234        let mut params = vec![
235            ("db", "pubmed"),
236            ("term", query),
237            ("retmax", max_results_str.as_str()),
238            ("retmode", "json"),
239        ];
240
241        if let Some(ref api_key) = self.api_key {
242            params.push(("api_key", api_key));
243        }
244
245        let response = self
246            .client
247            .get(format!("{}/esearch.fcgi", self.api_endpoint))
248            .query(&params)
249            .send()
250            .await
251            .context("Failed to send search request to PubMed")?;
252
253        if !response.status().is_success() {
254            return Err(anyhow!("PubMed API error: {}", response.status()));
255        }
256
257        let search_result: PubMedSearchResponse = response
258            .json()
259            .await
260            .context("Failed to parse PubMed search response")?;
261
262        Ok(search_result.esearchresult.idlist)
263    }
264
265    /// Fetch article details for a specific PMID
266    async fn fetch_article_details(&self, pmid: &str) -> Result<PubMedArticle> {
267        let mut params = vec![("db", "pubmed"), ("id", pmid), ("retmode", "xml")];
268
269        if let Some(ref api_key) = self.api_key {
270            params.push(("api_key", api_key));
271        }
272
273        let response = self
274            .client
275            .get(format!("{}/efetch.fcgi", self.api_endpoint))
276            .query(&params)
277            .send()
278            .await
279            .context("Failed to fetch article from PubMed")?;
280
281        let xml_text = response.text().await?;
282
283        // Parse XML (simplified - in production, use a proper XML parser)
284        self.parse_pubmed_xml(&xml_text)
285    }
286
287    /// Parse PubMed XML response (simplified implementation)
288    fn parse_pubmed_xml(&self, xml: &str) -> Result<PubMedArticle> {
289        // Extract title
290        let title =
291            Self::extract_xml_tag(xml, "ArticleTitle").unwrap_or_else(|| "Untitled".to_string());
292
293        // Extract abstract
294        let abstract_text = Self::extract_xml_tag(xml, "AbstractText")
295            .unwrap_or_else(|| "No abstract available".to_string());
296
297        // Extract authors (simplified)
298        let authors = Self::extract_authors(xml);
299
300        // Extract DOI
301        let doi = Self::extract_doi(xml);
302
303        Ok(PubMedArticle {
304            title,
305            abstract_text,
306            authors,
307            doi,
308        })
309    }
310
311    fn extract_xml_tag(xml: &str, tag: &str) -> Option<String> {
312        let start_tag = format!("<{}>", tag);
313        let end_tag = format!("</{}>", tag);
314
315        let start_pos = xml.find(&start_tag)? + start_tag.len();
316        let end_pos = xml[start_pos..].find(&end_tag)? + start_pos;
317
318        Some(xml[start_pos..end_pos].trim().to_string())
319    }
320
321    fn extract_authors(xml: &str) -> Vec<String> {
322        let mut authors = Vec::new();
323
324        // Simple extraction - in production, use proper XML parser
325        let mut current_pos = 0;
326        while let Some(lastname_start) = xml[current_pos..].find("<LastName>") {
327            let lastname_start = current_pos + lastname_start + 10;
328            if let Some(lastname_end) = xml[lastname_start..].find("</LastName>") {
329                let lastname = &xml[lastname_start..lastname_start + lastname_end];
330
331                // Try to find ForeName
332                let forename =
333                    if let Some(forename_start) = xml[lastname_start..].find("<ForeName>") {
334                        let forename_start = lastname_start + forename_start + 10;
335                        xml[forename_start..]
336                            .find("</ForeName>")
337                            .map(|forename_end| &xml[forename_start..forename_start + forename_end])
338                    } else {
339                        None
340                    };
341
342                let full_name = if let Some(first) = forename {
343                    format!("{} {}", first, lastname)
344                } else {
345                    lastname.to_string()
346                };
347
348                authors.push(full_name);
349                current_pos = lastname_start + lastname_end;
350            } else {
351                break;
352            }
353        }
354
355        authors
356    }
357
358    fn extract_doi(xml: &str) -> Option<String> {
359        // Look for DOI in ArticleId elements
360        if let Some(doi_start) = xml.find(r#"<ArticleId IdType="doi">"#) {
361            let doi_start = doi_start + 25;
362            if let Some(doi_end) = xml[doi_start..].find("</ArticleId>") {
363                return Some(xml[doi_start..doi_start + doi_end].trim().to_string());
364            }
365        }
366        None
367    }
368}
369
370/// Knowledge base manager coordinating multiple sources
371pub struct KnowledgeBaseManager {
372    wikipedia: Option<WikipediaConnector>,
373    pubmed: Option<PubMedConnector>,
374}
375
376impl KnowledgeBaseManager {
377    /// Create a new knowledge base manager
378    pub fn new() -> Self {
379        Self {
380            wikipedia: None,
381            pubmed: None,
382        }
383    }
384
385    /// Enable Wikipedia integration
386    pub fn with_wikipedia(mut self, language: Option<String>) -> Result<Self> {
387        self.wikipedia = Some(WikipediaConnector::new(language)?);
388        Ok(self)
389    }
390
391    /// Enable PubMed integration
392    pub fn with_pubmed(mut self, api_key: Option<String>) -> Result<Self> {
393        self.pubmed = Some(PubMedConnector::new(api_key)?);
394        Ok(self)
395    }
396
397    /// Search all enabled knowledge bases
398    pub async fn search_all(
399        &self,
400        query: &str,
401        max_results_per_source: usize,
402    ) -> Result<Vec<KnowledgeBaseResult>> {
403        let mut all_results = Vec::new();
404
405        // Search Wikipedia
406        if let Some(ref wikipedia) = self.wikipedia {
407            match wikipedia.search(query, max_results_per_source).await {
408                Ok(mut results) => all_results.append(&mut results),
409                Err(e) => warn!("Wikipedia search failed: {}", e),
410            }
411        }
412
413        // Search PubMed
414        if let Some(ref pubmed) = self.pubmed {
415            match pubmed.search(query, max_results_per_source).await {
416                Ok(mut results) => all_results.append(&mut results),
417                Err(e) => warn!("PubMed search failed: {}", e),
418            }
419        }
420
421        // Sort by relevance
422        all_results.sort_by(|a, b| {
423            b.relevance
424                .partial_cmp(&a.relevance)
425                .unwrap_or(std::cmp::Ordering::Equal)
426        });
427
428        Ok(all_results)
429    }
430}
431
432impl Default for KnowledgeBaseManager {
433    fn default() -> Self {
434        Self::new()
435    }
436}
437
438// Type definitions for API responses
439
440type WikipediaSearchResponse = (String, Vec<String>, Vec<String>, Vec<String>);
441
442#[derive(Debug, Deserialize)]
443struct PubMedSearchResponse {
444    esearchresult: PubMedSearchResult,
445}
446
447#[derive(Debug, Deserialize)]
448struct PubMedSearchResult {
449    idlist: Vec<String>,
450}
451
452#[derive(Debug)]
453struct PubMedArticle {
454    title: String,
455    abstract_text: String,
456    authors: Vec<String>,
457    doi: Option<String>,
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463
464    #[tokio::test]
465    async fn test_wikipedia_connector_creation() {
466        let connector = WikipediaConnector::new(Some("en".to_string()));
467        assert!(connector.is_ok());
468    }
469
470    #[tokio::test]
471    async fn test_pubmed_connector_creation() {
472        let connector = PubMedConnector::new(None);
473        assert!(connector.is_ok());
474    }
475
476    #[tokio::test]
477    async fn test_knowledge_base_manager() {
478        let manager = KnowledgeBaseManager::new()
479            .with_wikipedia(Some("en".to_string()))
480            .expect("should succeed");
481
482        assert!(manager.wikipedia.is_some());
483    }
484
485    #[test]
486    fn test_xml_tag_extraction() {
487        let xml = "<ArticleTitle>Test Title</ArticleTitle>";
488        let result = PubMedConnector::extract_xml_tag(xml, "ArticleTitle");
489        assert_eq!(result, Some("Test Title".to_string()));
490    }
491}