yoagent 0.8.4

Simple, effective agent loop with tool execution and event streaming
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Google Generative AI (Gemini) provider.
//!
//! Uses the `streamGenerateContent` endpoint with SSE streaming.
//! API key is passed as a query parameter.

use super::traits::*;
use crate::types::*;
use async_trait::async_trait;
use futures::StreamExt;
use serde::Deserialize;
use tokio::sync::mpsc;
use tracing::{debug, warn};

pub struct GoogleProvider;

#[async_trait]
impl StreamProvider for GoogleProvider {
    async fn stream(
        &self,
        config: StreamConfig,
        tx: mpsc::UnboundedSender<StreamEvent>,
        cancel: tokio_util::sync::CancellationToken,
    ) -> Result<Message, ProviderError> {
        let model_config = config
            .model_config
            .as_ref()
            .ok_or_else(|| ProviderError::Other("ModelConfig required".into()))?;

        let base_url = &model_config.base_url;
        let url = format!(
            "{}/v1beta/models/{}:streamGenerateContent?alt=sse&key={}",
            base_url, config.model, config.api_key
        );

        let body = build_request_body(&config);
        debug!("Google GenAI request: model={}", config.model);

        let client = reqwest::Client::new();
        let mut request = client.post(&url).header("content-type", "application/json");

        for (k, v) in &model_config.headers {
            request = request.header(k, v);
        }

        // Google streams JSON chunks separated by newlines, not SSE.
        // With alt=sse, it does use SSE format.
        let response = request
            .json(&body)
            .send()
            .await
            .map_err(|e| ProviderError::Network(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(ProviderError::classify(
                status.as_u16(),
                &format!("Google API error {}: {}", status, body),
            ));
        }

        let mut content: Vec<Content> = Vec::new();
        let mut usage = Usage::default();
        let mut stop_reason = StopReason::Stop;

        let _ = tx.send(StreamEvent::Start);

        // Parse SSE stream
        let mut stream = response.bytes_stream();
        let mut buffer = String::new();

        loop {
            tokio::select! {
                _ = cancel.cancelled() => {
                    return Err(ProviderError::Cancelled);
                }
                chunk = stream.next() => {
                    match chunk {
                        None => break,
                        Some(Err(e)) => {
                            warn!("Google stream error: {}", e);
                            break;
                        }
                        Some(Ok(bytes)) => {
                            buffer.push_str(&String::from_utf8_lossy(&bytes));

                            // Process complete SSE events (handle both \n\n and \r\n\r\n)
                            while let Some(pos) = buffer.find("\n\n").or_else(|| buffer.find("\r\n\r\n")) {
                                let sep_len = if buffer[pos..].starts_with("\r\n\r\n") { 4 } else { 2 };
                                let event_str = buffer[..pos].to_string();
                                buffer = buffer[pos + sep_len..].to_string();

                                // Parse SSE data line (strip trailing \r)
                                let data = event_str
                                    .lines()
                                    .map(|l| l.trim_end_matches('\r'))
                                    .find(|l| l.starts_with("data: "))
                                    .map(|l| &l[6..])
                                    .unwrap_or("");

                                if data.is_empty() {
                                    continue;
                                }

                                let chunk: GoogleChunk = match serde_json::from_str(data) {
                                    Ok(c) => c,
                                    Err(e) => {
                                        warn!("Failed to parse Google chunk: {}", e);
                                        continue;
                                    }
                                };

                                // Process candidates
                                for candidate in &chunk.candidates.unwrap_or_default() {
                                    if let Some(c) = &candidate.content {
                                        for part in &c.parts {
                                            if let Some(text) = &part.text {
                                                // Skip empty text parts (sent during thinking)
                                                if text.is_empty() {
                                                    continue;
                                                }
                                                let text_idx = content.iter().position(|c| matches!(c, Content::Text { .. }));
                                                let idx = match text_idx {
                                                    Some(i) => i,
                                                    None => {
                                                        content.push(Content::Text { text: String::new() });
                                                        content.len() - 1
                                                    }
                                                };
                                                if let Some(Content::Text { text: t }) = content.get_mut(idx) {
                                                    t.push_str(text);
                                                }
                                                let _ = tx.send(StreamEvent::TextDelta {
                                                    content_index: idx,
                                                    delta: text.clone(),
                                                });
                                            }
                                            if let Some(fc) = &part.function_call {
                                                let id = fc.id.clone().unwrap_or_else(|| format!("google-fc-{}", content.len()));
                                                let args = fc.args.clone().unwrap_or(serde_json::Value::Object(Default::default()));
                                                let metadata = part.thought_signature.as_ref().map(|sig| {
                                                    serde_json::json!({"thought_signature": sig})
                                                });
                                                let idx = content.len();
                                                content.push(Content::ToolCall {
                                                    id: id.clone(),
                                                    name: fc.name.clone(),
                                                    arguments: args,
                                                    provider_metadata: metadata,
                                                });
                                                let _ = tx.send(StreamEvent::ToolCallStart {
                                                    content_index: idx,
                                                    id,
                                                    name: fc.name.clone(),
                                                });
                                                let _ = tx.send(StreamEvent::ToolCallEnd { content_index: idx });
                                                stop_reason = StopReason::ToolUse;
                                            }
                                        }
                                    }
                                    if let Some(reason) = &candidate.finish_reason {
                                        // Don't override ToolUse -- Gemini returns "STOP"
                                        // even when it emits function calls
                                        if stop_reason != StopReason::ToolUse {
                                            stop_reason = match reason.as_str() {
                                                "STOP" => StopReason::Stop,
                                                "MAX_TOKENS" | "RECITATION" => StopReason::Length,
                                                _ => StopReason::Stop,
                                            };
                                        }
                                    }
                                }

                                // Process usage
                                if let Some(u) = &chunk.usage_metadata {
                                    usage.input = u.prompt_token_count.unwrap_or(0);
                                    usage.output = u.candidates_token_count.unwrap_or(0);
                                    usage.total_tokens = u.total_token_count.unwrap_or(0);
                                    usage.cache_read = u.cached_content_token_count.unwrap_or(0);
                                }
                            }
                        }
                    }
                }
            }
        }

        let message = Message::Assistant {
            content,
            stop_reason,
            model: config.model.clone(),
            provider: model_config.provider.clone(),
            usage,
            timestamp: now_ms(),
            error_message: None,
        };

        let _ = tx.send(StreamEvent::Done {
            message: message.clone(),
        });
        Ok(message)
    }
}

fn build_request_body(config: &StreamConfig) -> serde_json::Value {
    let mut contents: Vec<serde_json::Value> = Vec::new();

    for msg in &config.messages {
        match msg {
            Message::User { content, .. } => {
                let parts = content_to_google_parts(content);
                contents.push(serde_json::json!({
                    "role": "user",
                    "parts": parts,
                }));
            }
            Message::Assistant { content, .. } => {
                let parts = content_to_google_parts(content);
                contents.push(serde_json::json!({
                    "role": "model",
                    "parts": parts,
                }));
            }
            Message::ToolResult {
                tool_call_id,
                tool_name,
                content,
                ..
            } => {
                let text = content
                    .iter()
                    .find_map(|c| match c {
                        Content::Text { text } => Some(text.clone()),
                        _ => None,
                    })
                    .unwrap_or_default();

                let mut fr = serde_json::json!({
                    "name": tool_name,
                    "response": {"result": text},
                });
                if !tool_call_id.is_empty() && !tool_call_id.starts_with("google-fc-") {
                    fr["id"] = serde_json::json!(tool_call_id);
                }
                let mut parts = vec![serde_json::json!({"functionResponse": fr})];

                // Append image parts if present
                for c in content {
                    if let Content::Image { data, mime_type } = c {
                        parts.push(serde_json::json!({
                            "inlineData": {"mimeType": mime_type, "data": data},
                        }));
                    }
                }

                contents.push(serde_json::json!({
                    "role": "user",
                    "parts": parts,
                }));
            }
        }
    }

    let mut body = serde_json::json!({
        "contents": contents,
    });

    if !config.system_prompt.is_empty() {
        body["systemInstruction"] = serde_json::json!({
            "parts": [{"text": config.system_prompt}],
        });
    }

    let mut generation_config = serde_json::json!({});
    if let Some(max) = config.max_tokens {
        generation_config["maxOutputTokens"] = serde_json::json!(max);
    }
    if let Some(temp) = config.temperature {
        generation_config["temperature"] = serde_json::json!(temp);
    }
    if generation_config != serde_json::json!({}) {
        body["generationConfig"] = generation_config;
    }

    if !config.tools.is_empty() {
        let declarations: Vec<serde_json::Value> = config
            .tools
            .iter()
            .map(|t| {
                serde_json::json!({
                    "name": t.name,
                    "description": t.description,
                    "parameters": t.parameters,
                })
            })
            .collect();
        body["tools"] = serde_json::json!([{
            "functionDeclarations": declarations,
        }]);
    }

    body
}

fn content_to_google_parts(content: &[Content]) -> Vec<serde_json::Value> {
    content
        .iter()
        .filter(|c| !matches!(c, Content::Text { text } if text.is_empty()))
        .filter_map(|c| match c {
            Content::Text { text } => Some(serde_json::json!({"text": text})),
            Content::Image { data, mime_type } => Some(serde_json::json!({
                "inlineData": {"mimeType": mime_type, "data": data},
            })),
            Content::ToolCall {
                id,
                name,
                arguments,
                provider_metadata,
            } => {
                let mut fc = serde_json::json!({"name": name, "args": arguments});
                if !id.is_empty() && !id.starts_with("google-fc-") {
                    fc["id"] = serde_json::json!(id);
                }
                let mut part = serde_json::json!({"functionCall": fc});
                if let Some(sig) = provider_metadata
                    .as_ref()
                    .and_then(|m| m.get("thought_signature"))
                    .and_then(|v| v.as_str())
                {
                    part["thoughtSignature"] = serde_json::json!(sig);
                }
                Some(part)
            }
            Content::Thinking { .. } => None,
        })
        .collect()
}

// Google API response types
#[derive(Deserialize)]
struct GoogleChunk {
    #[serde(default)]
    candidates: Option<Vec<GoogleCandidate>>,
    #[serde(default, rename = "usageMetadata")]
    usage_metadata: Option<GoogleUsageMetadata>,
}

#[derive(Deserialize)]
struct GoogleCandidate {
    #[serde(default)]
    content: Option<GoogleContent>,
    #[serde(default, rename = "finishReason")]
    finish_reason: Option<String>,
}

#[derive(Deserialize)]
struct GoogleContent {
    #[serde(default)]
    parts: Vec<GooglePart>,
}

#[derive(Deserialize)]
struct GooglePart {
    #[serde(default)]
    text: Option<String>,
    #[serde(default, rename = "functionCall")]
    function_call: Option<GoogleFunctionCall>,
    #[serde(default, rename = "thoughtSignature")]
    thought_signature: Option<String>,
}

#[derive(Deserialize)]
struct GoogleFunctionCall {
    name: String,
    #[serde(default)]
    args: Option<serde_json::Value>,
    #[serde(default)]
    id: Option<String>,
}

#[derive(Deserialize)]
struct GoogleUsageMetadata {
    #[serde(default, rename = "promptTokenCount")]
    prompt_token_count: Option<u64>,
    #[serde(default, rename = "candidatesTokenCount")]
    candidates_token_count: Option<u64>,
    #[serde(default, rename = "totalTokenCount")]
    total_token_count: Option<u64>,
    #[serde(default, rename = "cachedContentTokenCount")]
    cached_content_token_count: Option<u64>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_google_request() {
        let config = StreamConfig {
            model: "gemini-2.0-flash".into(),
            system_prompt: "Be helpful".into(),
            messages: vec![Message::user("Hello")],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: Some(1024),
            temperature: Some(0.7),
            model_config: None,
            cache_config: CacheConfig::default(),
        };

        let body = build_request_body(&config);
        assert!(body["contents"].is_array());
        assert_eq!(body["contents"][0]["role"], "user");
        assert!(body["systemInstruction"].is_object());
        assert_eq!(body["generationConfig"]["maxOutputTokens"], 1024);
        let temp = body["generationConfig"]["temperature"].as_f64().unwrap();
        assert!((temp - 0.7).abs() < 0.01);
    }

    #[test]
    fn test_content_to_google_parts_text() {
        let content = vec![Content::Text {
            text: "hello".into(),
        }];
        let parts = content_to_google_parts(&content);
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0]["text"], "hello");
    }

    #[test]
    fn test_content_to_google_parts_filters_empty_text() {
        let content = vec![
            Content::Text { text: "".into() },
            Content::Text {
                text: "hello".into(),
            },
            Content::Text { text: "".into() },
        ];
        let parts = content_to_google_parts(&content);
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0]["text"], "hello");
    }

    #[test]
    fn test_content_to_google_parts_tool_call() {
        let content = vec![Content::ToolCall {
            id: "tc-1".into(),
            name: "bash".into(),
            arguments: serde_json::json!({"command": "ls"}),
            provider_metadata: None,
        }];
        let parts = content_to_google_parts(&content);
        assert_eq!(parts[0]["functionCall"]["name"], "bash");
    }

    #[test]
    fn test_parse_chunk_with_function_call_and_thought_signature() {
        let data = r#"{"candidates": [{"content": {"parts": [{"functionCall": {"name": "bash", "args": {"command": "echo hi"}, "id": "abc123"}, "thoughtSignature": "SIG_DATA"}], "role": "model"}, "finishReason": "STOP", "index": 0}], "usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5, "totalTokenCount": 15}}"#;

        let chunk: GoogleChunk = serde_json::from_str(data).unwrap();
        let candidates = chunk.candidates.unwrap();
        assert_eq!(candidates.len(), 1);

        let parts = &candidates[0].content.as_ref().unwrap().parts;
        assert_eq!(parts.len(), 1);

        let fc = parts[0].function_call.as_ref().unwrap();
        assert_eq!(fc.name, "bash");
        assert_eq!(fc.id.as_deref(), Some("abc123"));
        assert_eq!(fc.args.as_ref().unwrap()["command"], "echo hi");

        assert_eq!(parts[0].thought_signature.as_deref(), Some("SIG_DATA"));
    }

    #[test]
    fn test_parse_chunk_with_empty_text() {
        // Gemini sends empty text parts during thinking -- these should parse fine
        let data = r#"{"candidates": [{"content": {"parts": [{"text": ""}], "role": "model"}, "index": 0}]}"#;

        let chunk: GoogleChunk = serde_json::from_str(data).unwrap();
        let candidates = chunk.candidates.unwrap();
        let parts = &candidates[0].content.as_ref().unwrap().parts;
        assert_eq!(parts[0].text.as_deref(), Some(""));
    }

    #[test]
    fn test_parse_chunk_with_crlf_sse() {
        // Simulate \r\n line endings from Google's API
        let raw = "data: {\"candidates\": [{\"content\": {\"parts\": [{\"text\": \"Blue\"}], \"role\": \"model\"}, \"finishReason\": \"STOP\", \"index\": 0}]}\r\n\r\n";

        // Verify our separator detection works
        let pos = raw.find("\n\n").or_else(|| raw.find("\r\n\r\n"));
        assert!(pos.is_some(), "Should find separator");
        let sep_start = pos.unwrap();
        let is_crlf = raw[sep_start..].starts_with("\r\n\r\n");
        assert!(is_crlf, "Should detect \\r\\n\\r\\n separator");

        let event_str = &raw[..sep_start];
        let data = event_str
            .lines()
            .map(|l| l.trim_end_matches('\r'))
            .find(|l| l.starts_with("data: "))
            .map(|l| &l[6..])
            .unwrap();

        let chunk: GoogleChunk = serde_json::from_str(data).unwrap();
        let candidates = chunk.candidates.unwrap();
        let text = &candidates[0].content.as_ref().unwrap().parts[0].text;
        assert_eq!(text.as_deref(), Some("Blue"));
    }

    #[test]
    fn test_thought_signature_round_trip() {
        let content = vec![Content::ToolCall {
            id: "abc123".into(),
            name: "bash".into(),
            arguments: serde_json::json!({"command": "echo hi"}),
            provider_metadata: Some(serde_json::json!({"thought_signature": "SIG_DATA"})),
        }];

        let parts = content_to_google_parts(&content);
        assert_eq!(parts.len(), 1);

        assert_eq!(parts[0]["functionCall"]["name"], "bash");
        assert_eq!(parts[0]["functionCall"]["id"], "abc123");
        assert_eq!(parts[0]["functionCall"]["args"]["command"], "echo hi");
        assert_eq!(parts[0]["thoughtSignature"], "SIG_DATA");
    }

    #[test]
    fn test_tool_call_without_thought_signature() {
        // Synthetic IDs (google-fc-*) should not be sent to Gemini
        let content = vec![Content::ToolCall {
            id: "google-fc-0".into(),
            name: "bash".into(),
            arguments: serde_json::json!({"command": "ls"}),
            provider_metadata: None,
        }];

        let parts = content_to_google_parts(&content);
        assert!(parts[0]["functionCall"].get("id").is_none());
        assert!(parts[0].get("thoughtSignature").is_none());
    }

    #[test]
    fn test_function_response_includes_id() {
        let config = StreamConfig {
            model: "gemini-2.5-flash".into(),
            system_prompt: "".into(),
            messages: vec![
                Message::Assistant {
                    content: vec![Content::ToolCall {
                        id: "abc123".into(),
                        name: "bash".into(),
                        arguments: serde_json::json!({"command": "echo hi"}),
                        provider_metadata: None,
                    }],
                    stop_reason: StopReason::ToolUse,
                    model: "test".into(),
                    provider: "test".into(),
                    usage: Usage::default(),
                    timestamp: 0,
                    error_message: None,
                },
                Message::ToolResult {
                    tool_call_id: "abc123".into(),
                    tool_name: "bash".into(),
                    content: vec![Content::Text { text: "hi".into() }],
                    is_error: false,
                    timestamp: 0,
                },
            ],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: None,
            temperature: None,
            model_config: None,
            cache_config: CacheConfig::default(),
        };

        let body = build_request_body(&config);
        let msgs = body["contents"].as_array().unwrap();
        let tool_result = &msgs[1]["parts"][0]["functionResponse"];
        assert_eq!(tool_result["name"], "bash");
        assert_eq!(tool_result["id"], "abc123");
        assert_eq!(tool_result["response"]["result"], "hi");
    }

    #[test]
    fn test_function_response_synthetic_id_omitted() {
        let config = StreamConfig {
            model: "gemini-2.5-flash".into(),
            system_prompt: "".into(),
            messages: vec![
                Message::Assistant {
                    content: vec![Content::ToolCall {
                        id: "google-fc-0".into(),
                        name: "bash".into(),
                        arguments: serde_json::json!({"command": "ls"}),
                        provider_metadata: None,
                    }],
                    stop_reason: StopReason::ToolUse,
                    model: "test".into(),
                    provider: "test".into(),
                    usage: Usage::default(),
                    timestamp: 0,
                    error_message: None,
                },
                Message::ToolResult {
                    tool_call_id: "google-fc-0".into(),
                    tool_name: "bash".into(),
                    content: vec![Content::Text {
                        text: "output".into(),
                    }],
                    is_error: false,
                    timestamp: 0,
                },
            ],
            tools: vec![],
            thinking_level: ThinkingLevel::Off,
            api_key: "test".into(),
            max_tokens: None,
            temperature: None,
            model_config: None,
            cache_config: CacheConfig::default(),
        };

        let body = build_request_body(&config);
        let msgs = body["contents"].as_array().unwrap();
        let tool_result = &msgs[1]["parts"][0]["functionResponse"];
        assert!(
            tool_result.get("id").is_none(),
            "Synthetic ID should not be included"
        );
    }
}