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
110 fn run_inference_blocking(
112 client: &Client,
113 api_key: &str,
114 model: &str,
115 text: &str,
116 ) -> Result<String> {
117 let prompt = format!("{}\n\n{}", EXTRACTION_PROMPT, text);
118
119 let request = XaiRequest {
120 model: model.to_string(),
121 input: vec![
122 InputMessage {
123 role: "system".to_string(),
124 content: "You are a memory extraction assistant that extracts structured facts.".to_string(),
125 },
126 InputMessage {
127 role: "user".to_string(),
128 content: prompt,
129 },
130 ],
131 };
132
133 let response = client
134 .post("https://api.x.ai/v1/responses")
135 .header("Authorization", format!("Bearer {}", api_key))
136 .header("Content-Type", "application/json")
137 .json(&request)
138 .send()
139 .map_err(|e| anyhow!("xAI API request failed: {}", e))?;
140
141 if !response.status().is_success() {
142 let status = response.status();
143 let body = response.text().unwrap_or_default();
144 return Err(anyhow!("xAI API error {}: {}", status, body));
145 }
146
147 let xai_response: XaiResponse = response
148 .json()
149 .map_err(|e| anyhow!("Failed to parse xAI response: {}", e))?;
150
151 xai_response
153 .output
154 .and_then(|outputs| outputs.into_iter().next())
155 .and_then(|output| output.content)
156 .and_then(|contents| contents.into_iter().next())
157 .and_then(|content| content.text)
158 .ok_or_else(|| anyhow!("No response from xAI"))
159 }
160
161 fn parse_output(output: &str, frame_id: u64, uri: &str, timestamp: i64) -> Vec<MemoryCard> {
163 let mut cards = Vec::new();
164
165 if output.contains("MEMORY_NONE") {
166 return cards;
167 }
168
169 for block in output.split("MEMORY_START") {
170 let block = block.trim();
171 if block.is_empty() || !block.contains("MEMORY_END") {
172 continue;
173 }
174
175 let block = block.split("MEMORY_END").next().unwrap_or("").trim();
176
177 let mut kind = None;
178 let mut entity = None;
179 let mut slot = None;
180 let mut value = None;
181 let mut polarity = Polarity::Neutral;
182
183 for line in block.lines() {
184 let line = line.trim();
185 if let Some(rest) = line.strip_prefix("kind:") {
186 kind = parse_memory_kind(rest.trim());
187 } else if let Some(rest) = line.strip_prefix("entity:") {
188 entity = Some(rest.trim().to_string());
189 } else if let Some(rest) = line.strip_prefix("slot:") {
190 slot = Some(rest.trim().to_string());
191 } else if let Some(rest) = line.strip_prefix("value:") {
192 value = Some(rest.trim().to_string());
193 } else if let Some(rest) = line.strip_prefix("polarity:") {
194 polarity = parse_polarity(rest.trim());
195 }
196 }
197
198 if let (Some(k), Some(e), Some(s), Some(v)) = (kind, entity, slot, value) {
199 if !e.is_empty() && !s.is_empty() && !v.is_empty() {
200 match MemoryCardBuilder::new()
201 .kind(k)
202 .entity(&e)
203 .slot(&s)
204 .value(&v)
205 .polarity(polarity)
206 .source(frame_id, Some(uri.to_string()))
207 .document_date(timestamp)
208 .engine("xai:grok-4-fast", "1.0.0")
209 .build(0)
210 {
211 Ok(card) => cards.push(card),
212 Err(err) => {
213 warn!("Failed to build memory card: {}", err);
214 }
215 }
216 }
217 }
218 }
219
220 cards
221 }
222
223 pub fn enrich_batch(
225 &self,
226 contexts: Vec<EnrichmentContext>,
227 ) -> Result<Vec<(u64, Vec<MemoryCard>)>> {
228 let client = self
229 .client
230 .as_ref()
231 .ok_or_else(|| anyhow!("xAI engine not initialized (init() not called)"))?
232 .clone();
233 let client = Arc::new(client);
234 let api_key = Arc::new(self.api_key.clone());
235 let model = Arc::new(self.model.clone());
236 let total = contexts.len();
237
238 info!(
239 "Starting parallel enrichment of {} frames with {} workers",
240 total, self.parallelism
241 );
242
243 let pool = rayon::ThreadPoolBuilder::new()
244 .num_threads(self.parallelism)
245 .build()
246 .map_err(|err| anyhow!("failed to build enrichment thread pool: {err}"))?;
247
248 let results: Vec<(u64, Vec<MemoryCard>)> = pool.install(|| {
249 contexts
250 .into_par_iter()
251 .enumerate()
252 .map(|(i, ctx)| {
253 if ctx.text.is_empty() {
254 return (ctx.frame_id, vec![]);
255 }
256
257 if i > 0 && i % 50 == 0 {
258 info!("Enrichment progress: {}/{} frames", i, total);
259 }
260
261 match Self::run_inference_blocking(&client, &api_key, &model, &ctx.text) {
262 Ok(output) => {
263 debug!(
264 "xAI output for frame {}: {}",
265 ctx.frame_id,
266 &output[..output.len().min(100)]
267 );
268 let cards =
269 Self::parse_output(&output, ctx.frame_id, &ctx.uri, ctx.timestamp);
270 (ctx.frame_id, cards)
271 }
272 Err(err) => {
273 warn!("xAI inference failed for frame {}: {}", ctx.frame_id, err);
274 (ctx.frame_id, vec![])
275 }
276 }
277 })
278 .collect()
279 });
280
281 info!(
282 "Parallel enrichment complete: {} frames processed",
283 results.len()
284 );
285 Ok(results)
286 }
287}
288
289fn parse_memory_kind(s: &str) -> Option<MemoryKind> {
290 match s.to_lowercase().as_str() {
291 "fact" => Some(MemoryKind::Fact),
292 "preference" => Some(MemoryKind::Preference),
293 "event" => Some(MemoryKind::Event),
294 "profile" => Some(MemoryKind::Profile),
295 "relationship" => Some(MemoryKind::Relationship),
296 "other" => Some(MemoryKind::Other),
297 _ => None,
298 }
299}
300
301fn parse_polarity(s: &str) -> Polarity {
302 match s.to_lowercase().as_str() {
303 "positive" => Polarity::Positive,
304 "negative" => Polarity::Negative,
305 _ => Polarity::Neutral,
306 }
307}
308
309impl EnrichmentEngine for XaiEngine {
310 fn kind(&self) -> &str {
311 "xai:grok-4-fast"
312 }
313
314 fn version(&self) -> &str {
315 "1.0.0"
316 }
317
318 fn init(&mut self) -> memvid_core::Result<()> {
319 if self.api_key.is_empty() {
320 return Err(memvid_core::MemvidError::EmbeddingFailed {
321 reason: "XAI_API_KEY environment variable not set".into(),
322 });
323 }
324 let client = crate::http::blocking_client(Duration::from_secs(60)).map_err(|err| {
325 memvid_core::MemvidError::EmbeddingFailed {
326 reason: format!("Failed to create xAI HTTP client: {err}").into(),
327 }
328 })?;
329 self.client = Some(client);
330 self.ready = true;
331 Ok(())
332 }
333
334 fn is_ready(&self) -> bool {
335 self.ready
336 }
337
338 fn enrich(&self, ctx: &EnrichmentContext) -> EnrichmentResult {
339 if ctx.text.is_empty() {
340 return EnrichmentResult::empty();
341 }
342
343 let client = match self.client.as_ref() {
344 Some(client) => client,
345 None => {
346 return EnrichmentResult::failed(
347 "xAI engine not initialized (init() not called)".to_string(),
348 )
349 }
350 };
351
352 match Self::run_inference_blocking(client, &self.api_key, &self.model, &ctx.text) {
353 Ok(output) => {
354 debug!("xAI output for frame {}: {}", ctx.frame_id, output);
355 let cards = Self::parse_output(&output, ctx.frame_id, &ctx.uri, ctx.timestamp);
356 EnrichmentResult::success(cards)
357 }
358 Err(err) => EnrichmentResult::failed(format!("xAI inference failed: {}", err)),
359 }
360 }
361}
362
363impl Default for XaiEngine {
364 fn default() -> Self {
365 Self::new()
366 }
367}