ebbmem-client 0.2.0

Client SDK for the Ebb cognitive memory HTTP 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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
// Copyright 2026 Spectrayan — Proprietary

use std::collections::{HashSet, VecDeque};
use std::error::Error as StdError;
use std::future::Future;
use std::time::Duration;

use ebbmem_client_generated::apis::{self, configuration::Configuration};
use ebbmem_client_generated::models;

use crate::error::{self, EbbmemError};
use crate::SDK_VERSION;

#[derive(Clone)]
pub struct EbbmemClient {
    configuration: Configuration,
    namespace: Option<String>,
    max_retries: u32,
    timeout: Duration,
}

pub struct EbbmemClientBuilder {
    base_url: Option<String>,
    token: Option<String>,
    api_key: Option<String>,
    namespace: Option<String>,
    timeout: Option<Duration>,
    max_retries: Option<u32>,
    headers: Vec<(String, String)>,
    user_agent: Option<String>,
    base_url_set: bool,
    token_set: bool,
    api_key_set: bool,
    namespace_set: bool,
}

impl EbbmemClientBuilder {
    pub fn new() -> Self {
        Self {
            base_url: None,
            token: None,
            api_key: None,
            namespace: None,
            timeout: None,
            max_retries: None,
            headers: Vec::new(),
            user_agent: None,
            base_url_set: false,
            token_set: false,
            api_key_set: false,
            namespace_set: false,
        }
    }

    pub fn base_url(mut self, value: impl Into<String>) -> Self {
        self.base_url = Some(value.into());
        self.base_url_set = true;
        self
    }
    pub fn token(mut self, value: impl Into<String>) -> Self {
        self.token = Some(value.into());
        self.token_set = true;
        self
    }
    pub fn api_key(mut self, value: impl Into<String>) -> Self {
        self.api_key = Some(value.into());
        self.api_key_set = true;
        self
    }
    pub fn namespace(mut self, value: impl Into<String>) -> Self {
        self.namespace = Some(value.into());
        self.namespace_set = true;
        self
    }
    pub fn timeout(mut self, value: Duration) -> Self {
        self.timeout = Some(value);
        self
    }
    pub fn max_retries(mut self, value: u32) -> Self {
        self.max_retries = Some(value);
        self
    }
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    pub fn build(self) -> Result<EbbmemClient, EbbmemError> {
        let base_url = pick(self.base_url_set, self.base_url, "EBBMEM_ORIGIN").unwrap_or_default();
        let base_url = base_url.trim_end_matches('/').to_owned();
        if base_url.is_empty() {
            return Err(EbbmemError {
                status: None,
                code: None,
                message: "base_url is required (set it or EBBMEM_ORIGIN)".into(),
                details: None,
                request_id: None,
                retry_after: None,
            });
        }
        let token = pick(self.token_set, self.token, "EBBMEM_TOKEN");
        let api_key = pick(self.api_key_set, self.api_key, "EBBMEM_API_KEY");
        let namespace = pick(self.namespace_set, self.namespace, "EBBMEM_NAMESPACE");
        let timeout = self.timeout.unwrap_or(Duration::from_secs(30));
        let user_agent = self.user_agent.unwrap_or_else(|| format!("ebbmem-client-rust/{SDK_VERSION}"));
        let mut headers = reqwest::header::HeaderMap::new();
        for (name, value) in self.headers {
            if let (Ok(name), Ok(value)) = (
                reqwest::header::HeaderName::from_bytes(name.as_bytes()),
                reqwest::header::HeaderValue::from_str(&value),
            ) {
                headers.insert(name, value);
            }
        }
        let client = reqwest::Client::builder()
            .timeout(timeout)
            .user_agent(user_agent.clone())
            .default_headers(headers)
            .build()
            .map_err(|err| EbbmemError {
                status: None,
                code: None,
                message: err.to_string(),
                details: None,
                request_id: None,
                retry_after: None,
            })?;
        let mut configuration = Configuration::new();
        configuration.base_path = base_url;
        configuration.user_agent = Some(user_agent);
        configuration.client = client;
        configuration.bearer_access_token = token.filter(|value| !value.is_empty());
        configuration.api_key = api_key.filter(|value| !value.is_empty()).map(|key| apis::configuration::ApiKey {
            prefix: None,
            key,
        });
        Ok(EbbmemClient {
            configuration,
            namespace: namespace.filter(|value| !value.is_empty()),
            max_retries: self.max_retries.unwrap_or(2),
            timeout,
        })
    }
}

impl Default for EbbmemClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl EbbmemClient {
    pub fn builder() -> EbbmemClientBuilder {
        EbbmemClientBuilder::new()
    }

    pub fn memory(&self) -> Memory<'_> {
        Memory { client: self }
    }
    pub fn tasks(&self) -> Tasks<'_> {
        Tasks { client: self }
    }
    pub fn events(&self) -> Events<'_> {
        Events { client: self }
    }
    pub fn raw(&self) -> &Configuration {
        &self.configuration
    }

    pub async fn health(&self) -> Result<std::collections::HashMap<String, serde_json::Value>, Box<dyn StdError + Send + Sync>> {
        self.retry("health", None, |cfg| async move { apis::health_api::health(&cfg).await }).await
    }

    async fn retry<T, E, F, Fut>(&self, name: &str, idempotency_key: Option<&str>, mut op: F) -> Result<T, Box<dyn StdError + Send + Sync>>
    where
        F: FnMut(Configuration) -> Fut,
        Fut: Future<Output = Result<T, apis::Error<E>>>,
    {
        let idempotent = matches!(
            name,
            "recall" | "recall_federated" | "get" | "list" | "status" | "why_not" | "health" | "ready" | "tasks.get" | "tasks.list" | "tasks.cancel" | "forget"
        ) || ((name == "remember" || name == "remember_batch") && idempotency_key.is_some());
        let mut attempt = 0u32;
        loop {
            let mut cfg = self.configuration.clone();
            if let Some(key) = idempotency_key {
                let mut headers = reqwest::header::HeaderMap::new();
                if let Ok(value) = reqwest::header::HeaderValue::from_str(key) {
                    headers.insert("idempotency-key", value);
                }
                if let Ok(client) = reqwest::Client::builder().default_headers(headers).timeout(self.timeout).build() {
                    cfg.client = client;
                }
            }
            match op(cfg).await {
                Ok(value) => return Ok(value),
                Err(err) => {
                    let mapped = map_generated(err);
                    if attempt >= self.max_retries || !idempotent || !retryable_status(&mapped) {
                        return Err(error::classify(mapped));
                    }
                    let wait = backoff(attempt, &mapped);
                    tokio::time::sleep(wait).await;
                    attempt += 1;
                }
            }
        }
    }
}

impl std::fmt::Debug for EbbmemClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EbbmemClient")
            .field("base_url", &self.configuration.base_path)
            .field("token", &self.configuration.bearer_access_token.as_ref().map(|_| "set"))
            .field("api_key", &self.configuration.api_key.as_ref().map(|_| "set"))
            .finish()
    }
}

pub struct Memory<'a> {
    client: &'a EbbmemClient,
}

impl Memory<'_> {
    pub async fn remember(
        &self,
        content: &str,
        vector: Option<Vec<f64>>,
        tags: Option<Vec<String>>,
        importance: Option<f64>,
        idempotency_key: Option<&str>,
    ) -> Result<models::MemoryOperationResponse, Box<dyn StdError + Send + Sync>> {
        let mut body = models::RememberRequestModel::default();
        body.content = content.to_owned();
        body.vector = vector.map(Some);
        body.tags = tags.map(Some);
        body.importance = importance;
        let ns = self.client.namespace.clone();
        self.client
            .retry("remember", idempotency_key, move |cfg| {
                let body = body.clone();
                let ns = ns.clone();
                async move { apis::memory_api::remember(&cfg, body, ns.as_deref()).await }
            })
            .await
    }

    pub async fn recall(
        &self,
        query: &str,
        limit: Option<i32>,
        vector: Option<Vec<f64>>,
    ) -> Result<models::RecallResponseModel, Box<dyn StdError + Send + Sync>> {
        let mut body = models::RecallRequestModel::default();
        body.query = query.to_owned();
        body.limit = limit;
        body.vector = vector.map(Some);
        body.reinforce = Some(false);
        let ns = self.client.namespace.clone();
        self.client
            .retry("recall", None, move |cfg| {
                let body = body.clone();
                let ns = ns.clone();
                async move { apis::memory_api::recall(&cfg, body, ns.as_deref()).await }
            })
            .await
    }

    pub async fn get(&self, memory_id: &str) -> Result<models::MemoryRow, Box<dyn StdError + Send + Sync>> {
        let id = memory_id.to_owned();
        let ns = self.client.namespace.clone();
        self.client
            .retry("get", None, move |cfg| {
                let id = id.clone();
                let ns = ns.clone();
                async move { apis::memory_api::get_memory(&cfg, &id, None, ns.as_deref()).await }
            })
            .await
    }

    /// Auto-paginating cursor iterator. Call `next` until it returns `None`.
    pub fn list(&self, limit: i32) -> MemoryList<'_> {
        MemoryList {
            client: self.client,
            limit,
            cursor: None,
            seen: HashSet::new(),
            buffer: VecDeque::new(),
            done: false,
        }
    }

    pub async fn status(&self) -> Result<models::MemoryStatusResponse, Box<dyn StdError + Send + Sync>> {
        let ns = self.client.namespace.clone();
        self.client
            .retry("status", None, move |cfg| {
                let ns = ns.clone();
                async move { apis::memory_api::status(&cfg, None, ns.as_deref()).await }
            })
            .await
    }

    pub async fn forget(&self, memory_id: &str, purge: bool) -> Result<models::ResponseForgetmemory, Box<dyn StdError + Send + Sync>> {
        let id = memory_id.to_owned();
        let ns = self.client.namespace.clone();
        self.client
            .retry("forget", None, move |cfg| {
                let id = id.clone();
                let ns = ns.clone();
                async move { apis::memory_api::forget_memory(&cfg, &id, Some(purge), None, ns.as_deref()).await }
            })
            .await
    }

    pub async fn remember_batch(
        &self,
        items: Vec<serde_json::Value>,
        idempotency_key: Option<&str>,
    ) -> Result<models::BatchRememberResponse, Box<dyn StdError + Send + Sync>> {
        let encoded = items.into_iter().map(models::ItemsInner::from_value).collect();
        let body = models::BatchRememberRequestModel::new(encoded);
        let ns = self.client.namespace.clone();
        self.client
            .retry("remember_batch", idempotency_key, move |cfg| {
                let body = body.clone();
                let ns = ns.clone();
                async move { apis::memory_api::remember_batch(&cfg, body, ns.as_deref()).await }
            })
            .await
    }

    pub async fn recall_federated(
        &self,
        query: &str,
        limit: Option<i32>,
    ) -> Result<Vec<models::FederatedRecallCandidate>, Box<dyn StdError + Send + Sync>> {
        let mut body = models::FederatedRecallRequest::new(query.to_owned());
        body.limit = limit;
        let ns = self.client.namespace.clone();
        self.client
            .retry("recall_federated", None, move |cfg| {
                let body = body.clone();
                let ns = ns.clone();
                async move { apis::memory_api::recall_federated(&cfg, body, ns.as_deref()).await }
            })
            .await
    }

    pub async fn update(
        &self,
        memory_id: &str,
        request: models::UpdateMemoryRequest,
    ) -> Result<models::MemoryRow, Box<dyn StdError + Send + Sync>> {
        let id = memory_id.to_owned();
        let ns = self.client.namespace.clone();
        self.client
            .retry("update", None, move |cfg| {
                let id = id.clone();
                let request = request.clone();
                let ns = ns.clone();
                async move { apis::memory_api::update_memory(&cfg, &id, request, None, ns.as_deref()).await }
            })
            .await
    }

    pub async fn reinforce(
        &self,
        memory_id: &str,
        delta: f64,
    ) -> Result<models::ReinforceResponse, Box<dyn StdError + Send + Sync>> {
        let mut body = models::ReinforceRequestModel::new(models::MemoryId1::from_str_id(memory_id));
        body.delta = Some(delta);
        let ns = self.client.namespace.clone();
        self.client
            .retry("reinforce", None, move |cfg| {
                let body = body.clone();
                let ns = ns.clone();
                async move { apis::memory_api::reinforce(&cfg, body, ns.as_deref()).await }
            })
            .await
    }

    pub async fn reflect(
        &self,
        namespace: Option<&str>,
    ) -> Result<models::ReflectResponse, Box<dyn StdError + Send + Sync>> {
        let mut body = models::ReflectRequestModel::new();
        let ns = namespace
            .map(str::to_owned)
            .or_else(|| self.client.namespace.clone());
        body.namespace = ns.clone().map(Some);
        self.client
            .retry("reflect", None, move |cfg| {
                let body = body.clone();
                let ns = ns.clone();
                async move { apis::memory_api::reflect(&cfg, body, ns.as_deref()).await }
            })
            .await
    }

    pub async fn why_not(
        &self,
        memory_id: &str,
        query: &str,
    ) -> Result<models::WhyNotResponse, Box<dyn StdError + Send + Sync>> {
        let body = models::WhyNotRequestModel::new(models::MemoryId1::from_str_id(memory_id), query.to_owned());
        let ns = self.client.namespace.clone();
        self.client
            .retry("why_not", None, move |cfg| {
                let body = body.clone();
                let ns = ns.clone();
                async move { apis::memory_api::why_not(&cfg, body, ns.as_deref()).await }
            })
            .await
    }
}

pub struct MemoryList<'a> {
    client: &'a EbbmemClient,
    limit: i32,
    cursor: Option<String>,
    seen: HashSet<String>,
    buffer: VecDeque<models::MemoryRow>,
    done: bool,
}

impl MemoryList<'_> {
    pub async fn next(&mut self) -> Result<Option<models::MemoryRow>, Box<dyn StdError + Send + Sync>> {
        if self.buffer.is_empty() && !self.done {
            self.fill().await?;
        }
        Ok(self.buffer.pop_front())
    }

    async fn fill(&mut self) -> Result<(), Box<dyn StdError + Send + Sync>> {
        let page_cursor = self.cursor.clone();
        let ns = self.client.namespace.clone();
        let limit = self.limit;
        let page = self
            .client
            .retry("list", None, move |cfg| {
                let page_cursor = page_cursor.clone();
                let ns = ns.clone();
                async move {
                    apis::memory_api::list_memories(
                        &cfg,
                        page_cursor.as_deref(),
                        Some(limit),
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        ns.as_deref(),
                    )
                    .await
                }
            })
            .await?;
        if let Some(items) = page.items.clone() {
            self.buffer.extend(items);
        }
        let next = page.next_cursor.clone().flatten().filter(|value| !value.is_empty());
        let more = page.has_more.unwrap_or(false);
        match next {
            Some(value) if more && self.seen.insert(value.clone()) => self.cursor = Some(value),
            _ => self.done = true,
        }
        Ok(())
    }
}

pub struct Tasks<'a> {
    client: &'a EbbmemClient,
}

impl Tasks<'_> {
    pub async fn get(&self, task_id: &str) -> Result<std::collections::HashMap<String, serde_json::Value>, Box<dyn StdError + Send + Sync>> {
        let id = task_id.to_owned();
        self.client
            .retry("tasks.get", None, move |cfg| {
                let id = id.clone();
                async move { apis::tasks_api::get_task(&cfg, &id).await }
            })
            .await
    }

    pub async fn list(&self, limit: Option<i32>) -> Result<std::collections::HashMap<String, serde_json::Value>, Box<dyn StdError + Send + Sync>> {
        let ns = self.client.namespace.clone();
        self.client
            .retry("tasks.list", None, move |cfg| {
                let ns = ns.clone();
                async move { apis::tasks_api::list_tasks(&cfg, None, ns.as_deref(), limit).await }
            })
            .await
    }

    pub async fn cancel(&self, task_id: &str) -> Result<std::collections::HashMap<String, serde_json::Value>, Box<dyn StdError + Send + Sync>> {
        let id = task_id.to_owned();
        self.client
            .retry("tasks.cancel", None, move |cfg| {
                let id = id.clone();
                async move { apis::tasks_api::cancel_task(&cfg, &id).await }
            })
            .await
    }
}

pub struct Events<'a> {
    client: &'a EbbmemClient,
}

impl Events<'_> {
    /// Calls the generated `streamEvents` operation. The generator materializes the body.
    pub async fn stream(&self, token: Option<&str>) -> Result<models::StreamEventsResponse200, Box<dyn StdError + Send + Sync>> {
        let ns = self.client.namespace.clone();
        let token = token.map(str::to_owned);
        self.client
            .retry("events.stream", None, move |cfg| {
                let ns = ns.clone();
                let token = token.clone();
                async move {
                    apis::events_api::stream_events(&cfg, None, None, ns.as_deref(), None, None, token.as_deref()).await
                }
            })
            .await
    }
}

fn pick(explicit: bool, value: Option<String>, env_name: &str) -> Option<String> {
    if explicit {
        return value;
    }
    std::env::var(env_name).ok().map(|item| item.trim().to_owned()).filter(|item| !item.is_empty())
}

fn map_generated<T>(err: apis::Error<T>) -> EbbmemError {
    match err {
        apis::Error::ResponseError(content) => error::parse_body(Some(content.status.as_u16()), &content.content),
        other => EbbmemError {
            status: None,
            code: None,
            message: other.to_string(),
            details: None,
            request_id: None,
            retry_after: None,
        },
    }
}

fn retryable_status(err: &EbbmemError) -> bool {
    matches!(err.status, None | Some(429) | Some(502) | Some(503) | Some(504))
}

fn backoff(attempt: u32, err: &EbbmemError) -> Duration {
    if let Some(seconds) = err.retry_after {
        return Duration::from_secs_f64(seconds.max(0.0));
    }
    let base = (0.2 * 2f64.powi(attempt as i32)).min(8.0);
    let jitter = (attempt as f64 * 0.013) % (base / 2.0);
    Duration::from_secs_f64(base + jitter)
}