1use anyhow::{anyhow, Result};
7use memvid_core::enrich::{EnrichmentContext, EnrichmentEngine, EnrichmentResult};
8use memvid_core::types::{MemoryCard, MemoryCardBuilder, MemoryKind, Polarity};
9use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator};
10use reqwest::blocking::Client;
11use serde::{Deserialize, Serialize};
12use std::sync::Arc;
13use std::time::Duration;
14use tracing::{debug, info, warn};
15
16const EXTRACTION_PROMPT: &str = r#"You are a memory extraction assistant. Extract structured facts from the text.
18
19For each distinct fact, preference, event, or relationship mentioned, output a memory card in this exact format:
20MEMORY_START
21kind: <Fact|Preference|Event|Profile|Relationship|Other>
22entity: <the main entity this memory is about, use "user" for the human in the conversation>
23slot: <a short key describing what aspect of the entity>
24value: <the actual information>
25polarity: <Positive|Negative|Neutral>
26MEMORY_END
27
28Only extract information that is explicitly stated. Do not infer or guess.
29If there are no clear facts to extract, output MEMORY_NONE.
30
31Extract memories from this text:
32"#;
33
34#[derive(Debug, Serialize, Clone)]
36struct InputMessage {
37 role: String,
38 content: String,
39}
40
41#[derive(Debug, Serialize)]
43struct XaiRequest {
44 model: String,
45 input: Vec<InputMessage>,
46}
47
48#[derive(Debug, Deserialize)]
50struct XaiResponse {
51 output: Option<Vec<OutputItem>>,
52}
53
54#[derive(Debug, Deserialize)]
55struct OutputItem {
56 content: Option<Vec<ContentItem>>,
57}
58
59#[derive(Debug, Deserialize)]
60struct ContentItem {
61 text: Option<String>,
62}
63
64pub struct XaiEngine {
66 api_key: String,
68 model: String,
70 ready: bool,
72 parallelism: usize,
74 client: Option<Client>,
76}
77
78impl XaiEngine {
79 pub fn new() -> Self {
81 let api_key = std::env::var("XAI_API_KEY").unwrap_or_default();
82 Self {
83 api_key,
84 model: "grok-4-fast".to_string(),
85 ready: false,
86 parallelism: 20,
87 client: None,
88 }
89 }
90
91 pub fn with_model(model: &str) -> Self {
93 let api_key = std::env::var("XAI_API_KEY").unwrap_or_default();
94 Self {
95 api_key,
96 model: model.to_string(),
97 ready: false,
98 parallelism: 20,
99 client: None,
100 }
101 }
102
103 pub fn with_parallelism(mut self, n: usize) -> Self {
105 self.parallelism = n;
106 self
107 }
108
109 fn run_inference_blocking(
111 client: &Client,
112 api_key: &str,
113 model: &str,
114 text: &str,
115 ) -> Result<String> {
116 let prompt = format!("{}\n\n{}", EXTRACTION_PROMPT, text);
117
118 let request = XaiRequest {
119 model: model.to_string(),
120 input: vec![
121 InputMessage {
122 role: "system".to_string(),
123 content: "You are a memory extraction assistant that extracts structured facts.".to_string(),
124 },
125 InputMessage {
126 role: "user".to_string(),
127 content: prompt,
128 },
129 ],
130 };
131
132 let response = client
133 .post("https://api.x.ai/v1/responses")
134 .header("Authorization", format!("Bearer {}", api_key))
135 .header("Content-Type", "application/json")
136 .json(&request)
137 .send()
138 .map_err(|e| anyhow!("xAI API request failed: {}", e))?;
139
140 if !response.status().is_success() {
141 let status = response.status();
142 let body = response.text().unwrap_or_default();
143 return Err(anyhow!("xAI API error {}: {}", status, body));
144 }
145
146 let xai_response: XaiResponse = response
147 .json()
148 .map_err(|e| anyhow!("Failed to parse xAI response: {}", e))?;
149
150 xai_response
152 .output
153 .and_then(|outputs| outputs.into_iter().next())
154 .and_then(|output| output.content)
155 .and_then(|contents| contents.into_iter().next())
156 .and_then(|content| content.text)
157 .ok_or_else(|| anyhow!("No response from xAI"))
158 }
159
160 fn parse_output(output: &str, frame_id: u64, uri: &str, timestamp: i64) -> Vec<MemoryCard> {
162 let mut cards = Vec::new();
163
164 if output.contains("MEMORY_NONE") {
165 return cards;
166 }
167
168 for block in output.split("MEMORY_START") {
169 let block = block.trim();
170 if block.is_empty() || !block.contains("MEMORY_END") {
171 continue;
172 }
173
174 let block = block.split("MEMORY_END").next().unwrap_or("").trim();
175
176 let mut kind = None;
177 let mut entity = None;
178 let mut slot = None;
179 let mut value = None;
180 let mut polarity = Polarity::Neutral;
181
182 for line in block.lines() {
183 let line = line.trim();
184 if let Some(rest) = line.strip_prefix("kind:") {
185 kind = parse_memory_kind(rest.trim());
186 } else if let Some(rest) = line.strip_prefix("entity:") {
187 entity = Some(rest.trim().to_string());
188 } else if let Some(rest) = line.strip_prefix("slot:") {
189 slot = Some(rest.trim().to_string());
190 } else if let Some(rest) = line.strip_prefix("value:") {
191 value = Some(rest.trim().to_string());
192 } else if let Some(rest) = line.strip_prefix("polarity:") {
193 polarity = parse_polarity(rest.trim());
194 }
195 }
196
197 if let (Some(k), Some(e), Some(s), Some(v)) = (kind, entity, slot, value) {
198 if !e.is_empty() && !s.is_empty() && !v.is_empty() {
199 match MemoryCardBuilder::new()
200 .kind(k)
201 .entity(&e)
202 .slot(&s)
203 .value(&v)
204 .polarity(polarity)
205 .source(frame_id, Some(uri.to_string()))
206 .document_date(timestamp)
207 .engine("xai:grok-4-fast", "1.0.0")
208 .build(0)
209 {
210 Ok(card) => cards.push(card),
211 Err(err) => {
212 warn!("Failed to build memory card: {}", err);
213 }
214 }
215 }
216 }
217 }
218
219 cards
220 }
221
222 pub fn enrich_batch(
224 &self,
225 contexts: Vec<EnrichmentContext>,
226 ) -> Result<Vec<(u64, Vec<MemoryCard>)>> {
227 let client = self
228 .client
229 .as_ref()
230 .ok_or_else(|| anyhow!("xAI engine not initialized (init() not called)"))?
231 .clone();
232 let client = Arc::new(client);
233 let api_key = Arc::new(self.api_key.clone());
234 let model = Arc::new(self.model.clone());
235 let total = contexts.len();
236
237 info!(
238 "Starting parallel enrichment of {} frames with {} workers",
239 total, self.parallelism
240 );
241
242 let pool = rayon::ThreadPoolBuilder::new()
243 .num_threads(self.parallelism)
244 .build()
245 .map_err(|err| anyhow!("failed to build enrichment thread pool: {err}"))?;
246
247 let results: Vec<(u64, Vec<MemoryCard>)> = pool.install(|| {
248 contexts
249 .into_par_iter()
250 .enumerate()
251 .map(|(i, ctx)| {
252 if ctx.text.is_empty() {
253 return (ctx.frame_id, vec![]);
254 }
255
256 if i > 0 && i % 50 == 0 {
257 info!("Enrichment progress: {}/{} frames", i, total);
258 }
259
260 match Self::run_inference_blocking(&client, &api_key, &model, &ctx.text) {
261 Ok(output) => {
262 debug!(
263 "xAI output for frame {}: {}",
264 ctx.frame_id,
265 &output[..output.len().min(100)]
266 );
267 let cards =
268 Self::parse_output(&output, ctx.frame_id, &ctx.uri, ctx.timestamp);
269 (ctx.frame_id, cards)
270 }
271 Err(err) => {
272 warn!("xAI inference failed for frame {}: {}", ctx.frame_id, err);
273 (ctx.frame_id, vec![])
274 }
275 }
276 })
277 .collect()
278 });
279
280 info!(
281 "Parallel enrichment complete: {} frames processed",
282 results.len()
283 );
284 Ok(results)
285 }
286}
287
288fn parse_memory_kind(s: &str) -> Option<MemoryKind> {
289 match s.to_lowercase().as_str() {
290 "fact" => Some(MemoryKind::Fact),
291 "preference" => Some(MemoryKind::Preference),
292 "event" => Some(MemoryKind::Event),
293 "profile" => Some(MemoryKind::Profile),
294 "relationship" => Some(MemoryKind::Relationship),
295 "other" => Some(MemoryKind::Other),
296 _ => None,
297 }
298}
299
300fn parse_polarity(s: &str) -> Polarity {
301 match s.to_lowercase().as_str() {
302 "positive" => Polarity::Positive,
303 "negative" => Polarity::Negative,
304 _ => Polarity::Neutral,
305 }
306}
307
308impl EnrichmentEngine for XaiEngine {
309 fn kind(&self) -> &str {
310 "xai:grok-4-fast"
311 }
312
313 fn version(&self) -> &str {
314 "1.0.0"
315 }
316
317 fn init(&mut self) -> memvid_core::Result<()> {
318 if self.api_key.is_empty() {
319 return Err(memvid_core::MemvidError::EmbeddingFailed {
320 reason: "XAI_API_KEY environment variable not set".into(),
321 });
322 }
323 let client = crate::http::blocking_client(Duration::from_secs(60)).map_err(|err| {
324 memvid_core::MemvidError::EmbeddingFailed {
325 reason: format!("Failed to create xAI HTTP client: {err}").into(),
326 }
327 })?;
328 self.client = Some(client);
329 self.ready = true;
330 Ok(())
331 }
332
333 fn is_ready(&self) -> bool {
334 self.ready
335 }
336
337 fn enrich(&self, ctx: &EnrichmentContext) -> EnrichmentResult {
338 if ctx.text.is_empty() {
339 return EnrichmentResult::empty();
340 }
341
342 let client = match self.client.as_ref() {
343 Some(client) => client,
344 None => {
345 return EnrichmentResult::failed(
346 "xAI engine not initialized (init() not called)".to_string(),
347 )
348 }
349 };
350
351 match Self::run_inference_blocking(client, &self.api_key, &self.model, &ctx.text) {
352 Ok(output) => {
353 debug!("xAI output for frame {}: {}", ctx.frame_id, output);
354 let cards = Self::parse_output(&output, ctx.frame_id, &ctx.uri, ctx.timestamp);
355 EnrichmentResult::success(cards)
356 }
357 Err(err) => EnrichmentResult::failed(format!("xAI inference failed: {}", err)),
358 }
359 }
360}
361
362impl Default for XaiEngine {
363 fn default() -> Self {
364 Self::new()
365 }
366}