memvid_cli/enrich/
gemini.rs

1//! Gemini (Google) enrichment engine using Gemini 2.5 Flash.
2//!
3//! This engine uses the Google AI Studio API to extract structured memory cards
4//! from text content. Supports parallel batch processing for speed.
5
6use 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
16/// The extraction prompt for Gemini
17const 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/// Gemini API request
35#[derive(Debug, Serialize)]
36struct GeminiRequest {
37    contents: Vec<GeminiContent>,
38    #[serde(rename = "generationConfig")]
39    generation_config: GenerationConfig,
40}
41
42#[derive(Debug, Serialize)]
43struct GeminiContent {
44    parts: Vec<GeminiPart>,
45}
46
47#[derive(Debug, Serialize)]
48struct GeminiPart {
49    text: String,
50}
51
52#[derive(Debug, Serialize)]
53struct GenerationConfig {
54    temperature: f32,
55    #[serde(rename = "maxOutputTokens")]
56    max_output_tokens: u32,
57}
58
59/// Gemini API response
60#[derive(Debug, Deserialize)]
61struct GeminiResponse {
62    candidates: Option<Vec<Candidate>>,
63}
64
65#[derive(Debug, Deserialize)]
66struct Candidate {
67    content: CandidateContent,
68}
69
70#[derive(Debug, Deserialize)]
71struct CandidateContent {
72    parts: Vec<CandidatePart>,
73}
74
75#[derive(Debug, Deserialize)]
76struct CandidatePart {
77    text: Option<String>,
78}
79
80/// Gemini enrichment engine using Gemini 2.5 Flash with parallel processing.
81pub struct GeminiEngine {
82    /// API key
83    api_key: String,
84    /// Model to use
85    model: String,
86    /// Whether the engine is initialized
87    ready: bool,
88    /// Number of parallel workers (default: 20)
89    parallelism: usize,
90    /// Shared HTTP client (built in `init`)
91    client: Option<Client>,
92}
93
94impl GeminiEngine {
95    /// Create a new Gemini engine.
96    pub fn new() -> Self {
97        let api_key = std::env::var("GOOGLE_API_KEY")
98            .or_else(|_| std::env::var("GEMINI_API_KEY"))
99            .unwrap_or_default();
100        Self {
101            api_key,
102            model: "gemini-2.5-flash".to_string(),
103            ready: false,
104            parallelism: 20,
105            client: None,
106        }
107    }
108
109    /// Create with a specific model.
110    pub fn with_model(model: &str) -> Self {
111        let api_key = std::env::var("GOOGLE_API_KEY")
112            .or_else(|_| std::env::var("GEMINI_API_KEY"))
113            .unwrap_or_default();
114        Self {
115            api_key,
116            model: model.to_string(),
117            ready: false,
118            parallelism: 20,
119            client: None,
120        }
121    }
122
123    /// Set parallelism level.
124    pub fn with_parallelism(mut self, n: usize) -> Self {
125        self.parallelism = n;
126        self
127    }
128
129    /// Run inference via Gemini API (blocking, thread-safe).
130    fn run_inference_blocking(
131        client: &Client,
132        api_key: &str,
133        model: &str,
134        text: &str,
135    ) -> Result<String> {
136        let prompt = format!("{}\n\n{}", EXTRACTION_PROMPT, text);
137
138        let request = GeminiRequest {
139            contents: vec![GeminiContent {
140                parts: vec![GeminiPart { text: prompt }],
141            }],
142            generation_config: GenerationConfig {
143                temperature: 0.0,
144                max_output_tokens: 1024,
145            },
146        };
147
148        let url = format!(
149            "https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent?key={}",
150            model, api_key
151        );
152
153        let response = client
154            .post(&url)
155            .header("Content-Type", "application/json")
156            .json(&request)
157            .send()
158            .map_err(|e| anyhow!("Gemini API request failed: {}", e))?;
159
160        if !response.status().is_success() {
161            let status = response.status();
162            let body = response.text().unwrap_or_default();
163            return Err(anyhow!("Gemini API error {}: {}", status, body));
164        }
165
166        let gemini_response: GeminiResponse = response
167            .json()
168            .map_err(|e| anyhow!("Failed to parse Gemini response: {}", e))?;
169
170        gemini_response
171            .candidates
172            .and_then(|c| c.into_iter().next())
173            .and_then(|c| c.content.parts.into_iter().next())
174            .and_then(|p| p.text)
175            .ok_or_else(|| anyhow!("No text response from Gemini"))
176    }
177
178    /// Parse the LLM output into memory cards.
179    fn parse_output(output: &str, frame_id: u64, uri: &str, timestamp: i64) -> Vec<MemoryCard> {
180        let mut cards = Vec::new();
181
182        if output.contains("MEMORY_NONE") {
183            return cards;
184        }
185
186        for block in output.split("MEMORY_START") {
187            let block = block.trim();
188            if block.is_empty() || !block.contains("MEMORY_END") {
189                continue;
190            }
191
192            let block = block.split("MEMORY_END").next().unwrap_or("").trim();
193
194            let mut kind = None;
195            let mut entity = None;
196            let mut slot = None;
197            let mut value = None;
198            let mut polarity = Polarity::Neutral;
199
200            for line in block.lines() {
201                let line = line.trim();
202                if let Some(rest) = line.strip_prefix("kind:") {
203                    kind = parse_memory_kind(rest.trim());
204                } else if let Some(rest) = line.strip_prefix("entity:") {
205                    entity = Some(rest.trim().to_string());
206                } else if let Some(rest) = line.strip_prefix("slot:") {
207                    slot = Some(rest.trim().to_string());
208                } else if let Some(rest) = line.strip_prefix("value:") {
209                    value = Some(rest.trim().to_string());
210                } else if let Some(rest) = line.strip_prefix("polarity:") {
211                    polarity = parse_polarity(rest.trim());
212                }
213            }
214
215            if let (Some(k), Some(e), Some(s), Some(v)) = (kind, entity, slot, value) {
216                if !e.is_empty() && !s.is_empty() && !v.is_empty() {
217                    match MemoryCardBuilder::new()
218                        .kind(k)
219                        .entity(&e)
220                        .slot(&s)
221                        .value(&v)
222                        .polarity(polarity)
223                        .source(frame_id, Some(uri.to_string()))
224                        .document_date(timestamp)
225                        .engine("gemini:gemini-2.5-flash", "1.0.0")
226                        .build(0)
227                    {
228                        Ok(card) => cards.push(card),
229                        Err(err) => {
230                            warn!("Failed to build memory card: {}", err);
231                        }
232                    }
233                }
234            }
235        }
236
237        cards
238    }
239
240    /// Process multiple frames in parallel and return all cards.
241    pub fn enrich_batch(
242        &self,
243        contexts: Vec<EnrichmentContext>,
244    ) -> Result<Vec<(u64, Vec<MemoryCard>)>> {
245        let client = self
246            .client
247            .as_ref()
248            .ok_or_else(|| anyhow!("Gemini engine not initialized (init() not called)"))?
249            .clone();
250        let client = Arc::new(client);
251        let api_key = Arc::new(self.api_key.clone());
252        let model = Arc::new(self.model.clone());
253        let total = contexts.len();
254
255        info!(
256            "Starting parallel enrichment of {} frames with {} workers",
257            total, self.parallelism
258        );
259
260        let pool = rayon::ThreadPoolBuilder::new()
261            .num_threads(self.parallelism)
262            .build()
263            .map_err(|err| anyhow!("failed to build enrichment thread pool: {err}"))?;
264
265        let results: Vec<(u64, Vec<MemoryCard>)> = pool.install(|| {
266            contexts
267                .into_par_iter()
268                .enumerate()
269                .map(|(i, ctx)| {
270                    if ctx.text.is_empty() {
271                        return (ctx.frame_id, vec![]);
272                    }
273
274                    if i > 0 && i % 50 == 0 {
275                        info!("Enrichment progress: {}/{} frames", i, total);
276                    }
277
278                    match Self::run_inference_blocking(&client, &api_key, &model, &ctx.text) {
279                        Ok(output) => {
280                            debug!(
281                                "Gemini output for frame {}: {}",
282                                ctx.frame_id,
283                                &output[..output.len().min(100)]
284                            );
285                            let cards =
286                                Self::parse_output(&output, ctx.frame_id, &ctx.uri, ctx.timestamp);
287                            (ctx.frame_id, cards)
288                        }
289                        Err(err) => {
290                            warn!(
291                                "Gemini inference failed for frame {}: {}",
292                                ctx.frame_id, err
293                            );
294                            (ctx.frame_id, vec![])
295                        }
296                    }
297                })
298                .collect()
299        });
300
301        info!(
302            "Parallel enrichment complete: {} frames processed",
303            results.len()
304        );
305        Ok(results)
306    }
307}
308
309fn parse_memory_kind(s: &str) -> Option<MemoryKind> {
310    match s.to_lowercase().as_str() {
311        "fact" => Some(MemoryKind::Fact),
312        "preference" => Some(MemoryKind::Preference),
313        "event" => Some(MemoryKind::Event),
314        "profile" => Some(MemoryKind::Profile),
315        "relationship" => Some(MemoryKind::Relationship),
316        "other" => Some(MemoryKind::Other),
317        _ => None,
318    }
319}
320
321fn parse_polarity(s: &str) -> Polarity {
322    match s.to_lowercase().as_str() {
323        "positive" => Polarity::Positive,
324        "negative" => Polarity::Negative,
325        _ => Polarity::Neutral,
326    }
327}
328
329impl EnrichmentEngine for GeminiEngine {
330    fn kind(&self) -> &str {
331        "gemini:gemini-2.5-flash"
332    }
333
334    fn version(&self) -> &str {
335        "1.0.0"
336    }
337
338    fn init(&mut self) -> memvid_core::Result<()> {
339        if self.api_key.is_empty() {
340            return Err(memvid_core::MemvidError::EmbeddingFailed {
341                reason: "GOOGLE_API_KEY or GEMINI_API_KEY environment variable not set".into(),
342            });
343        }
344        let client = crate::http::blocking_client(Duration::from_secs(60)).map_err(|err| {
345            memvid_core::MemvidError::EmbeddingFailed {
346                reason: format!("Failed to create Gemini HTTP client: {err}").into(),
347            }
348        })?;
349        self.client = Some(client);
350        self.ready = true;
351        Ok(())
352    }
353
354    fn is_ready(&self) -> bool {
355        self.ready
356    }
357
358    fn enrich(&self, ctx: &EnrichmentContext) -> EnrichmentResult {
359        if ctx.text.is_empty() {
360            return EnrichmentResult::empty();
361        }
362
363        let client = match self.client.as_ref() {
364            Some(client) => client,
365            None => {
366                return EnrichmentResult::failed(
367                    "Gemini engine not initialized (init() not called)".to_string(),
368                )
369            }
370        };
371
372        match Self::run_inference_blocking(client, &self.api_key, &self.model, &ctx.text) {
373            Ok(output) => {
374                debug!("Gemini output for frame {}: {}", ctx.frame_id, output);
375                let cards = Self::parse_output(&output, ctx.frame_id, &ctx.uri, ctx.timestamp);
376                EnrichmentResult::success(cards)
377            }
378            Err(err) => EnrichmentResult::failed(format!("Gemini inference failed: {}", err)),
379        }
380    }
381}
382
383impl Default for GeminiEngine {
384    fn default() -> Self {
385        Self::new()
386    }
387}