exa_api_client 0.1.5

A Rust client for interacting with the Exa/Metaphor systems API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
use reqwest::{Client, Error as ReqwestError};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use serde_json::json;



//implement keyword search
#[derive(Debug, Error)]
pub enum ExaApiError {
    #[error("network error: {0}")]
    NetworkError(#[from] ReqwestError),
    #[error("API error: {0}")]
    ApiError(String),
}

#[derive(Serialize, Deserialize, Debug,Default)]
pub struct TextOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_characters: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_html_tags: Option<bool>,
}

#[derive(Serialize, Deserialize, Debug,Default)]
pub struct HighlightsOptions {
    pub num_sentences: Option<u32>,
    pub highlights_per_url: Option<u32>,
    pub query: Option<String>,
}

#[derive(Serialize, Deserialize, Debug,Default)]
pub struct ContentsRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<TextOptions>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub highlights: Option<HighlightsOptions>,
}


#[derive(Serialize, Deserialize, Debug,Default)]
 pub struct CommonRequestOptions {
     num_results: Option<u32>,
     include_domains: Option<Vec<String>>,
     exclude_domains: Option<Vec<String>>,
     start_crawl_date: Option<String>,
     end_crawl_date: Option<String>,
     start_published_date: Option<String>,
     end_published_date: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct SearchParams {
    query: String,
    use_autoprompt: Option<bool>,
    #[serde(flatten)]
    common: CommonRequestOptions,
    #[serde(skip_serializing_if = "Option::is_none")]
    contents: Option<ContentsRequest>,
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    search_type: Option<String>,
}


// fix the text 


impl SearchParams {
    pub fn new(query: &str) -> Self {
        SearchParams {
            query: query.to_string(),
            ..Default::default()
        }
    }

    pub fn use_autoprompt(mut self, value: bool) -> Self {
        self.use_autoprompt = Some(value);
        self
    }

    pub fn search_type(mut self, search_type: &str) -> Self {
        self.search_type = Some(search_type.to_string());
        self
    }

    pub fn num_results(mut self, value: u32) -> Self {
        self.common.num_results = Some(value);
        self
    }

    pub fn include_domains(mut self, domains: Vec<String>) -> Self {
        self.common.include_domains = Some(domains);
        self
    }

    pub fn exclude_domains(mut self, domains: Vec<String>) -> Self {
        self.common.exclude_domains = Some(domains);
        self
    }

    pub fn start_crawl_date(mut self, date: &str) -> Self {
        self.common.start_crawl_date = Some(date.to_string());
        self
    }

    pub fn end_crawl_date(mut self, date: &str) -> Self {
        self.common.end_crawl_date = Some(date.to_string());
        self
    }

    pub fn start_published_date(mut self, date: &str) -> Self {
        self.common.start_published_date = Some(date.to_string());
        self
    }

    pub fn end_published_date(mut self, date: &str) -> Self {
        self.common.end_published_date = Some(date.to_string());
        self
    }

    pub fn text(mut self, max_characters: Option<u32>, include_html_tags: Option<bool>) -> Self {
        let text = TextOptions {
            max_characters,
            include_html_tags,
        };
        self.contents.get_or_insert_with(Default::default).text = Some(text);
        self
    }

    pub fn highlights(mut self, num_sentences: Option<u32>, highlights_per_url: Option<u32>, query: Option<&str>) -> Self {
        let query_str = query.map(|q| q.to_string());
        let highlights = HighlightsOptions {
            num_sentences,
            highlights_per_url,
            query: query_str,
        };
        self.contents.get_or_insert_with(Default::default).highlights = Some(highlights);
        self
    }

  
}

// make each of these option::is_none
// findsimilar  
#[derive( Serialize,Deserialize, Debug,Default)]
pub struct FindSimilarParams {
     url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
     exclude_source_domain: Option<bool>,
    #[serde(flatten)]
     common: CommonRequestOptions,
    #[serde(skip_serializing_if = "Option::is_none")]
    contents: Option<ContentsRequest>,


}

impl FindSimilarParams {
    pub fn new(url: &str) -> Self {
        FindSimilarParams {
            url: url.to_string(),
            ..Default::default()
        }
    }

    pub fn exclude_source_domain(mut self, value: bool) -> Self {
        self.exclude_source_domain = Some(value);
        self
    }

    pub fn num_results(mut self, value: u32) -> Self {
        self.common.num_results = Some(value);
        self
    }

    pub fn include_domains(mut self, domains: Vec<String>) -> Self {
        self.common.include_domains = Some(domains);
        self
    }

    pub fn exclude_domains(mut self, domains: Vec<String>) -> Self {
        self.common.exclude_domains = Some(domains);
        self
    }

    pub fn start_crawl_date(mut self, date: &str) -> Self {
        self.common.start_crawl_date = Some(date.to_string());
        self
    }

    pub fn end_crawl_date(mut self, date: &str) -> Self {
        self.common.end_crawl_date = Some(date.to_string());
        self
    }

    pub fn start_published_date(mut self, date: &str) -> Self {
        self.common.start_published_date = Some(date.to_string());
        self
    }

    pub fn end_published_date(mut self, date: &str) -> Self {
        self.common.end_published_date = Some(date.to_string());
        self
    }


    pub fn text(mut self, max_characters: Option<u32>, include_html_tags: Option<bool>) -> Self {
        let text = TextOptions {
            max_characters,
            include_html_tags,
        };
        self.contents.get_or_insert_with(Default::default).text = Some(text);
        self
    }

    pub fn highlights(mut self, num_sentences: Option<u32>, highlights_per_url: Option<u32>, query: Option<&str>) -> Self {
        let query_str = query.map(|q| q.to_string());
        let highlights = HighlightsOptions {
            num_sentences,
            highlights_per_url,
            query: query_str,
        };
        self.contents.get_or_insert_with(Default::default).highlights = Some(highlights);
        self
    }

}



// Answers 

// Answer request parameters
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct AnswerParams {
    pub query: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<serde_json::Value>,
}

impl AnswerParams {
    pub fn new(query: &str) -> Self {
        AnswerParams {
            query: query.to_string(),
            ..Default::default()
        }
    }

    pub fn stream(mut self, value: bool) -> Self {
        self.stream = Some(value);
        self
    }

    pub fn text(mut self, value: bool) -> Self {
        self.text = Some(value);
        self
    }

    pub fn system_prompt(mut self, prompt: &str) -> Self {
        self.system_prompt = Some(prompt.to_string());
        self
    }

    pub fn model(mut self, model: &str) -> Self {
        self.model = Some(model.to_string());
        self
    }

    pub fn output_schema(mut self, schema: serde_json::Value) -> Self {
        self.output_schema = Some(schema);
        self
    }
}

// Answer citation result
#[derive(Serialize, Deserialize, Debug)]
pub struct AnswerCitation {
    pub id: String,
    pub url: String,
    pub title: Option<String>,
    pub author: Option<String>,
    pub published_date: Option<String>,
    pub text: Option<String>,
    pub image: Option<String>,
    pub favicon: Option<String>,
}

// Cost breakdown structures
#[derive(Serialize, Deserialize, Debug)]
pub struct CostBreakdown {
    pub search: Option<f64>,
    pub contents: Option<f64>,
    pub breakdown: Option<CostDetails>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct CostDetails {
    pub keyword_search: Option<f64>,
    pub neural_search: Option<f64>,
    pub content_text: Option<f64>,
    pub content_highlight: Option<f64>,
    pub content_summary: Option<f64>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct PerRequestPrices {
    pub neural_search_1_25_results: Option<f64>,
    pub neural_search_26_100_results: Option<f64>,
    pub neural_search_100_plus_results: Option<f64>,
    pub keyword_search_1_100_results: Option<f64>,
    pub keyword_search_100_plus_results: Option<f64>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct PerPagePrices {
    pub content_text: Option<f64>,
    pub content_highlight: Option<f64>,
    pub content_summary: Option<f64>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct CostDollars {
    pub total: f64,
    pub break_down: Option<Vec<CostBreakdown>>,
    pub per_request_prices: Option<PerRequestPrices>,
    pub per_page_prices: Option<PerPagePrices>,
}

// Answer response
#[derive(Serialize, Deserialize, Debug)]
pub struct AnswerResponse {
    pub answer: serde_json::Value, // Can be string or structured object
    pub citations: Vec<AnswerCitation>,
    pub cost_dollars: Option<CostDollars>,
}

// Streaming chunk for future streaming implementation
#[derive(Debug)]
pub struct StreamChunk {
    pub content: Option<String>,
    pub citations: Option<Vec<AnswerCitation>>,
}

impl StreamChunk {
    pub fn has_data(&self) -> bool {
        self.content.is_some() || self.citations.is_some()
    }
}



// find contents 
#[derive(Serialize, Deserialize, Debug,Default)]
pub struct ContentsParams {
    pub ids: Vec<String>,
    pub text: Option<TextOptions>,
    pub highlights: Option<HighlightsOptions>,

}

impl ContentsParams {
    pub fn new(ids: Vec<String>) -> Self {
        ContentsParams {
            ids,
            ..Default::default()
        }
    }

    pub fn text(mut self, max_characters: Option<u32>, include_html_tags: Option<bool>) -> Self {
        let text = TextOptions {
            max_characters,
            include_html_tags,
        };
        self.text = Some(text);
        self
    }

    
    pub fn highlights(mut self, num_sentences: Option<u32>, highlights_per_url: Option<u32>, query: Option<&str>) -> Self {
        let query_str = query.map(|q| q.to_string());
        let highlights = HighlightsOptions {
            num_sentences,
            highlights_per_url,
            query: query_str,
        };
        self.highlights = Some(highlights);
        self
    }
}


//use std::collections::HashMap;

#[derive(Serialize, Deserialize, Debug)]
pub struct ResponseResult {
    pub title: Option<String>,
    pub url: String,
    pub published_date: Option<String>,
    pub author: Option<String>,
    pub id: String,
    pub score: Option<f64>,
    pub text: Option<String>,
    pub highlights: Option<Vec<String>>,
    pub highlight_scores: Option<Vec<f64>>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SearchResponse {
    pub results: Vec<ResponseResult>,
    pub autoprompt_string: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ContentsResponse {
    pub results: Vec<ResponseResult>,
    pub autoprompt_string: Option<String>,

}

#[derive(Serialize, Deserialize, Debug)]
pub struct FindSimilarResponse {
    pub results: Vec<ResponseResult>,
    pub autoprompt_string: Option<String>,

}




pub struct ExaApiClient {
    pub base_url: String,
    pub api_key: String,
    pub client: Client,
}

impl ExaApiClient {
    pub fn new(api_key:  &str) -> Self {
        ExaApiClient {
            base_url: "https://api.exa.ai".to_string(),
            api_key: api_key.to_string(),
            client: Client::new(),
        }
    }

    pub async fn search(&self, params: SearchParams) -> Result<SearchResponse, ExaApiError> {
        let url = format!("{}/search", self.base_url);
        let response = self.client.post(&url)
            .json(&params)
            .header("x-api-key", &self.api_key)
            .send()
            .await?;

        if response.status().is_success() {
            let search_response = response.json::<SearchResponse>().await?;
            Ok(search_response)
        } else {
            let error_msg = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            Err(ExaApiError::ApiError(error_msg))
        }
    }

    pub async fn find_similar(&self, params: FindSimilarParams) -> Result<FindSimilarResponse, ExaApiError> {
        let url = format!("{}/findSimilar", self.base_url);
        let response = self.client.post(&url)
            .json(&params)
            .header("x-api-key", &self.api_key)
            .send()
            .await?;

        if response.status().is_success() {
            let find_similar_response = response.json::<FindSimilarResponse>().await?;
            Ok(find_similar_response)
        } else {
            let error_msg: String = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            Err(ExaApiError::ApiError(error_msg))
        }
    }

   
    pub async fn contents(&self, params: ContentsParams) -> Result<ContentsResponse, ExaApiError> {
        let url = format!("{}/contents", self.base_url);
        let response = self.client.post(&url)
            .json(&params)
            .header("x-api-key", &self.api_key)
            .send()
            .await?;

        if response.status().is_success() {
            let contents_response = response.json::<ContentsResponse>().await?;
            Ok(contents_response)
        } else {
            let error_msg = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            Err(ExaApiError::ApiError(error_msg))
        }
    }

    pub async fn answer(&self, params: AnswerParams) -> Result<AnswerResponse, ExaApiError> {
        let url = format!("{}/answer", self.base_url);
        let response = self.client.post(&url)
            .json(&params)
            .header("x-api-key", &self.api_key)
            .send()
            .await?;

        if response.status().is_success() {
            let answer_response = response.json::<AnswerResponse>().await?;
            Ok(answer_response)
        } else {
            let error_msg = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
            Err(ExaApiError::ApiError(error_msg))
        }
    }


}