vectoramp 0.5.1

Official Rust client for the VectorAmp public 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
//! Intelligence service: non-streaming and streaming RAG queries.

use bytes::Bytes;
use futures_util::stream::{Stream, StreamExt};
use serde::Deserialize;

use crate::client::Client;
use crate::datasets::{push_pagination, Pagination};
use crate::errors::{Error, Result};
use crate::transport::Request;
use crate::types::{
    AppendMessageRequest, AskRequest, AskResponse, ConversationMessage, CreateSessionRequest,
    IntelligenceSession, MessageList, Metadata, SessionList, SessionMessage,
};

/// Optional knobs passed to [`IntelligenceService::ask_with`].
///
/// Every field defaults to `None`, which asks the API for its own default. In
/// particular a `None` `dataset_ids` searches every dataset the caller can see.
#[derive(Debug, Default, Clone)]
pub struct AskOptions {
    /// Datasets to scope the query to. `None` searches every accessible dataset.
    pub dataset_ids: Option<Vec<String>>,
    pub top_k: Option<u32>,
    pub conversation_history: Option<Vec<ConversationMessage>>,
    pub include_sources: Option<bool>,
}

impl AskOptions {
    /// Add one dataset id to the scope. Repeating this widens the scope rather
    /// than replacing it.
    pub fn with_dataset<S: Into<String>>(mut self, dataset_id: S) -> Self {
        self.dataset_ids
            .get_or_insert_with(Vec::new)
            .push(dataset_id.into());
        self
    }

    /// Set the entire dataset scope, replacing anything set before it.
    pub fn with_datasets<I, S>(mut self, dataset_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.dataset_ids = Some(dataset_ids.into_iter().map(Into::into).collect());
        self
    }

    /// Clear the scope so the query reaches every accessible dataset.
    ///
    /// That is what an absent `dataset_ids` means to the API; the old `"all"`
    /// sentinel is retired.
    pub fn with_all_datasets(mut self) -> Self {
        self.dataset_ids = None;
        self
    }

    /// Set the retrieval `top_k`.
    pub fn with_top_k(mut self, top_k: u32) -> Self {
        self.top_k = Some(top_k);
        self
    }

    /// Toggle source citations.
    pub fn with_sources(mut self, include: bool) -> Self {
        self.include_sources = Some(include);
        self
    }

    /// Attach conversation history.
    pub fn with_history(mut self, history: Vec<ConversationMessage>) -> Self {
        self.conversation_history = Some(history);
        self
    }
}

/// Normalize a dataset scope for the wire.
///
/// `POST /intelligence/query` reads an absent `dataset_ids` as "every dataset
/// the caller can see", so an empty scope collapses to `None` rather than being
/// sent as `[]` — which would be a narrower, different request. The retired
/// `"all"` sentinel says nothing an absent field does not, so it is dropped too.
fn normalize_dataset_ids(dataset_ids: Option<Vec<String>>) -> Option<Vec<String>> {
    let scope: Vec<String> = dataset_ids
        .unwrap_or_default()
        .into_iter()
        .map(|id| id.trim().to_owned())
        .filter(|id| !id.is_empty() && id != "all")
        .collect();
    (!scope.is_empty()).then_some(scope)
}

/// Service running retrieval-augmented question answering.
#[derive(Clone)]
pub struct IntelligenceService {
    client: Client,
}

impl IntelligenceService {
    pub(crate) fn new(client: Client) -> Self {
        Self { client }
    }

    /// Run a non-streaming intelligence query.
    pub async fn ask<S: Into<String>>(&self, query: S) -> Result<AskResponse> {
        self.ask_with(query.into(), AskOptions::default()).await
    }

    /// Run a non-streaming intelligence query with explicit options.
    pub async fn ask_with<S: Into<String>>(
        &self,
        query: S,
        options: AskOptions,
    ) -> Result<AskResponse> {
        let request = AskRequest {
            query: query.into(),
            dataset_ids: normalize_dataset_ids(options.dataset_ids),
            top_k: options.top_k,
            conversation_history: options.conversation_history,
            stream: false,
            include_sources: options.include_sources,
        };
        let body = serde_json::to_value(&request)?;
        self.client
            .dispatcher()
            .json(Request {
                method: "POST".into(),
                path: "/intelligence/query".into(),
                body: Some(body),
                ..Default::default()
            })
            .await
    }

    /// Open a streaming intelligence query.
    ///
    /// The returned [`AskStream`] yields decoded server-sent events. The SDK
    /// always sets `stream: true` on the request body.
    pub async fn stream<S: Into<String>>(
        &self,
        query: S,
        options: AskOptions,
    ) -> Result<AskStream> {
        let request = AskRequest {
            query: query.into(),
            dataset_ids: normalize_dataset_ids(options.dataset_ids),
            top_k: options.top_k,
            conversation_history: options.conversation_history,
            stream: true,
            include_sources: options.include_sources,
        };
        let body = serde_json::to_value(&request)?;
        let stream = self
            .client
            .dispatcher()
            .stream(Request {
                method: "POST".into(),
                path: "/intelligence/query".into(),
                body: Some(body),
                stream: true,
                ..Default::default()
            })
            .await?;
        Ok(AskStream::new(stream))
    }

    /// Create a new intelligence session.
    ///
    /// Pass `()` for an empty session, or a [`CreateSessionRequest`] (also
    /// accepts a bare title via `&str`/`String`) to set a title, dataset scope,
    /// or metadata.
    pub async fn create_session<R: Into<CreateSessionRequest>>(
        &self,
        request: R,
    ) -> Result<IntelligenceSession> {
        let body = serde_json::to_value(request.into())?;
        self.client
            .dispatcher()
            .json(Request {
                method: "POST".into(),
                path: "/intelligence/sessions".into(),
                body: Some(body),
                ..Default::default()
            })
            .await
    }

    /// List intelligence sessions.
    ///
    /// Pagination is optional: pass `()` for defaults or a bare `limit`.
    pub async fn list_sessions<P: Into<Pagination>>(&self, pagination: P) -> Result<SessionList> {
        let (limit, _offset) = pagination.into().resolve();
        let mut req = Request {
            method: "GET".into(),
            path: "/intelligence/sessions".into(),
            ..Default::default()
        };
        // The sessions endpoint paginates by `limit` only.
        push_pagination(&mut req.query, limit, 0);
        self.client.dispatcher().json(req).await
    }

    /// Fetch one intelligence session by id.
    pub async fn get_session(&self, session_id: &str) -> Result<IntelligenceSession> {
        self.client
            .dispatcher()
            .json(Request {
                method: "GET".into(),
                path: format!("/intelligence/sessions/{session_id}"),
                ..Default::default()
            })
            .await
    }

    /// Delete an intelligence session.
    pub async fn delete_session(&self, session_id: &str) -> Result<()> {
        self.client
            .dispatcher()
            .empty(Request {
                method: "DELETE".into(),
                path: format!("/intelligence/sessions/{session_id}"),
                ..Default::default()
            })
            .await
    }

    /// Append a message to a session.
    pub async fn append_message<S: Into<String>, C: Into<String>>(
        &self,
        session_id: &str,
        role: S,
        content: C,
    ) -> Result<SessionMessage> {
        self.append_message_with(
            session_id,
            AppendMessageRequest {
                role: role.into(),
                content: content.into(),
                metadata: None,
            },
        )
        .await
    }

    /// Append a message to a session with explicit metadata.
    pub async fn append_message_with(
        &self,
        session_id: &str,
        request: AppendMessageRequest,
    ) -> Result<SessionMessage> {
        let body = serde_json::to_value(&request)?;
        self.client
            .dispatcher()
            .json(Request {
                method: "POST".into(),
                path: format!("/intelligence/sessions/{session_id}/messages"),
                body: Some(body),
                ..Default::default()
            })
            .await
    }

    /// List messages in a session.
    ///
    /// Pagination is optional: pass `()` for defaults or a bare `limit`.
    pub async fn list_messages<P: Into<Pagination>>(
        &self,
        session_id: &str,
        pagination: P,
    ) -> Result<MessageList> {
        let (limit, _offset) = pagination.into().resolve();
        let mut req = Request {
            method: "GET".into(),
            path: format!("/intelligence/sessions/{session_id}/messages"),
            ..Default::default()
        };
        push_pagination(&mut req.query, limit, 0);
        self.client.dispatcher().json(req).await
    }
}

/// One decoded server-sent event from the intelligence stream.
#[derive(Debug, Default, Clone)]
pub struct StreamEvent {
    /// The SSE `event:` name, when present.
    pub event: String,
    /// `chunk_type` field from the JSON body, when present.
    pub chunk_type: String,
    /// `content` field from the JSON body, when present.
    pub content: String,
    /// Free-form metadata attached to the chunk.
    pub metadata: Option<Metadata>,
    /// Raw JSON body bytes.
    pub raw: Vec<u8>,
}

#[derive(Debug, Default, Deserialize)]
struct StreamPayload {
    #[serde(default)]
    chunk_type: String,
    #[serde(default)]
    content: String,
    #[serde(default)]
    metadata: Option<Metadata>,
}

type ByteStream = Box<dyn Stream<Item = std::result::Result<Bytes, reqwest::Error>> + Send + Unpin>;

/// Async iterator over [`StreamEvent`]s produced by an intelligence stream.
pub struct AskStream {
    inner: ByteStream,
    buffer: Vec<u8>,
    done: bool,
    pending_event: String,
    pending_data: Vec<String>,
}

impl AskStream {
    fn new(inner: ByteStream) -> Self {
        Self {
            inner,
            buffer: Vec::new(),
            done: false,
            pending_event: String::new(),
            pending_data: Vec::new(),
        }
    }

    /// Pull the next event from the stream. Returns `Ok(None)` at EOF.
    pub async fn next_event(&mut self) -> Result<Option<StreamEvent>> {
        loop {
            if let Some(event) = self.try_take_event() {
                return Ok(Some(event));
            }
            if self.done {
                if !self.pending_data.is_empty() {
                    let data = std::mem::take(&mut self.pending_data).join("\n");
                    let event = std::mem::take(&mut self.pending_event);
                    return Ok(Some(decode_event(event, data.into_bytes())));
                }
                return Ok(None);
            }
            match self.inner.next().await {
                Some(Ok(chunk)) => {
                    self.buffer.extend_from_slice(&chunk);
                }
                Some(Err(e)) => return Err(Error::Http(e)),
                None => {
                    self.done = true;
                    if !self.buffer.is_empty() {
                        // Flush any final pending lines without a trailing
                        // blank-line separator.
                        let line = std::mem::take(&mut self.buffer);
                        self.consume_line(&line);
                    }
                }
            }
        }
    }

    fn try_take_event(&mut self) -> Option<StreamEvent> {
        loop {
            let newline_pos = self.buffer.iter().position(|b| *b == b'\n')?;
            let line: Vec<u8> = self.buffer.drain(..=newline_pos).collect();
            // Drop trailing \r and \n.
            let mut end = line.len();
            if end > 0 && line[end - 1] == b'\n' {
                end -= 1;
            }
            if end > 0 && line[end - 1] == b'\r' {
                end -= 1;
            }
            let line = &line[..end];

            if line.is_empty() {
                if !self.pending_data.is_empty() {
                    let data = std::mem::take(&mut self.pending_data).join("\n");
                    let event = std::mem::take(&mut self.pending_event);
                    return Some(decode_event(event, data.into_bytes()));
                }
                self.pending_event.clear();
                continue;
            }
            self.consume_line(line);
        }
    }

    fn consume_line(&mut self, line: &[u8]) {
        if line.is_empty() {
            return;
        }
        if line[0] == b':' {
            // Comment line.
            return;
        }
        // Find optional ":" separator.
        if let Some(colon) = line.iter().position(|b| *b == b':') {
            let field = &line[..colon];
            let mut rest = &line[colon + 1..];
            if !rest.is_empty() && rest[0] == b' ' {
                rest = &rest[1..];
            }
            match field {
                b"event" => {
                    self.pending_event = String::from_utf8_lossy(rest).into_owned();
                }
                b"data" => {
                    self.pending_data
                        .push(String::from_utf8_lossy(rest).into_owned());
                }
                _ => {}
            }
        }
    }
}

fn decode_event(event: String, raw: Vec<u8>) -> StreamEvent {
    let payload: StreamPayload = serde_json::from_slice(&raw).unwrap_or_default();
    StreamEvent {
        event,
        chunk_type: payload.chunk_type,
        content: payload.content,
        metadata: payload.metadata,
        raw,
    }
}