lellm-provider 0.4.1

Provider adapters for LeLLM — OpenAI, Anthropic, and more
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
//! Google Gemini Provider 适配器。
//!
//! 使用 Gemini API 原生格式(非 OpenAI 兼容)。
//! Endpoint: `POST /v1beta/models/{model}:generateContent`

use bytes::Bytes;
use http::HeaderMap;
use lellm_core::{
    ChatRequest, ChatResponse, ContentBlock, LlmError, Message, TextBlock, TokenUsage, ToolCall,
    ToolChoice,
};
use std::borrow::Cow;

use super::codec::{
    AuthStyle, Capabilities, ChatCodec, CodecRequest, ModelCapabilities, ProviderMeta, StreamChunk,
    StreamParseResult, ToolCallDelta,
};
use super::stream::sse_frame::SseFrame;

/// Google Gemini 协议编解码器。
#[derive(Debug, Clone)]
pub struct GoogleCodec;

// ── ProviderMeta ──

impl ProviderMeta for GoogleCodec {
    fn provider_id(&self) -> &'static str {
        "google"
    }

    fn default_base_url(&self) -> &'static str {
        "https://generativelanguage.googleapis.com"
    }

    fn auth_style(&self) -> AuthStyle {
        AuthStyle::Bearer
    }
}

// ── ChatCodec ──

impl ChatCodec for GoogleCodec {
    fn encode(&self, req: &ChatRequest, stream: bool) -> Result<CodecRequest, LlmError> {
        // Gemini: system 消息放在 system_instruction 字段,不在 contents 数组中
        let mut system_instruction: Option<serde_json::Value> = None;
        let mut contents: Vec<serde_json::Value> = Vec::new();

        for m in &req.messages {
            match m {
                Message::System { content } => {
                    let text: String = content
                        .iter()
                        .filter_map(|b| b.as_text())
                        .collect::<Vec<_>>()
                        .join("");
                    if !text.is_empty() {
                        system_instruction =
                            Some(serde_json::json!({"role": "user", "parts": [{"text": text}]}));
                    }
                }
                Message::User { content } => {
                    let parts = serialize_google_parts(content)?;
                    if !parts.is_empty() {
                        contents.push(serde_json::json!({"role": "user", "parts": parts}));
                    }
                }
                Message::Assistant { content } => {
                    let parts = serialize_google_parts(content)?;
                    if !parts.is_empty() {
                        contents.push(serde_json::json!({"role": "model", "parts": parts}));
                    }
                }
                Message::ToolResult {
                    tool_call_id,
                    is_error: _,
                    content,
                } => {
                    let parts = serialize_google_tool_result_parts(content);
                    contents.push(serde_json::json!({
                        "role": "function",
                        "parts": [{
                            "functionResponse": {
                                "name": tool_call_id,
                                "response": {
                                    "name": tool_call_id,
                                    "content": parts
                                }
                            }
                        }]
                    }));
                }
            }
        }

        // 构建 Gemini 请求 body
        let mut body = serde_json::Map::new();
        if let Some(si) = system_instruction {
            body.insert("systemInstruction".into(), si);
        }
        body.insert(
            "contents".into(),
            serde_json::to_value(contents).map_err(|e| LlmError::Parse {
                detail: format!("Failed to serialize contents: {}", e),
            })?,
        );

        // generationConfig
        let mut gen_config = serde_json::Map::new();
        if let Some(temp) = req.temperature {
            gen_config.insert("temperature".into(), temp.into());
        }
        if let Some(max_tokens) = req.max_tokens {
            gen_config.insert("maxOutputTokens".into(), max_tokens.into());
        }
        if let Some(top_p) = req.top_p {
            gen_config.insert("topP".into(), top_p.into());
        }
        if let Some(seed) = req.seed {
            gen_config.insert("seed".into(), seed.into());
        }
        if let Some(ref stop_sequences) = req.stop_sequences {
            gen_config.insert(
                "stopSequences".into(),
                serde_json::to_value(stop_sequences).unwrap(),
            );
        }
        // Gemini 不支持 thinking tokens,静默忽略 reasoning 配置

        if !gen_config.is_empty() {
            body.insert(
                "generationConfig".into(),
                serde_json::Value::Object(gen_config),
            );
        }

        // 工具
        if let Some(ref tools) = req.tools {
            body.insert(
                "tools".into(),
                serde_json::json!([{
                    "functionDeclarations": serialize_google_tools(tools)
                }]),
            );
        }

        // tool_choice 映射
        if let Some(ref tool_choice) = req.tool_choice {
            body.insert(
                "toolConfig".into(),
                serde_json::json!({
                    "functionCallingConfig": serialize_google_tool_choice(tool_choice)
                }),
            );
        }

        // Provider 特有参数(extra 最后合并,允许覆盖标准字段)
        if let Some(ref extra) = req.extra {
            for (k, v) in extra {
                body.insert(k.clone(), v.clone());
            }
        }

        let body_bytes = serde_json::to_vec(&body).map_err(|e| LlmError::Parse {
            detail: format!("Failed to serialize request body: {}", e),
        })?;

        // 构建 path:/v1beta/models/{model}:generateContent
        // 流式通过 query param ?alt=sse 控制
        let path_str = if stream {
            format!("/v1beta/models/{}:generateContent?alt=sse", req.model)
        } else {
            format!("/v1beta/models/{}:generateContent", req.model)
        };

        let mut headers = HeaderMap::new();
        headers.insert(
            "content-type",
            "application/json".parse().map_err(|_| LlmError::Parse {
                detail: "Invalid header value".into(),
            })?,
        );

        Ok(CodecRequest {
            path: Cow::Owned(path_str),
            headers,
            body: Bytes::from(body_bytes),
        })
    }

    fn decode(&self, body: &[u8]) -> Result<ChatResponse, LlmError> {
        let raw: serde_json::Value = serde_json::from_slice(body).map_err(|e| LlmError::Parse {
            detail: format!("Invalid JSON: {}", e),
        })?;

        // 检查 prompts/usageMetadata (safety filtering 等错误)
        if let Some(block_reason) = raw
            .get("promptFeedback")
            .and_then(|p| p.get("blockReason"))
            .and_then(|b| b.as_str())
        {
            return Err(LlmError::Provider {
                provider: "google".into(),
                status: Some(400),
                code: None,
                message: format!("Prompt blocked: {}", block_reason),
            });
        }

        let candidates =
            raw.get("candidates")
                .and_then(|c| c.as_array())
                .ok_or(LlmError::Parse {
                    detail: "Missing candidates array".into(),
                })?;

        if candidates.is_empty() {
            // 可能是 safety filtering
            return Err(LlmError::Provider {
                provider: "google".into(),
                status: Some(400),
                code: None,
                message: "No candidates in response (possibly safety filtered)".into(),
            });
        }

        let candidate = &candidates[0];
        let parts = candidate
            .get("content")
            .and_then(|c| c.get("parts"))
            .and_then(|p| p.as_array())
            .ok_or(LlmError::Parse {
                detail: "Missing parts in candidate".into(),
            })?;

        let mut content: Vec<ContentBlock> = Vec::new();
        for part in parts {
            if let Some(text) = part
                .get("text")
                .and_then(|t| t.as_str())
                .filter(|s| !s.is_empty())
            {
                content.push(ContentBlock::Text(TextBlock {
                    text: text.into(),
                    cache_control: None,
                }));
            }
            if let Some(func_call) = part.get("functionCall") {
                let name = func_call
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let args = func_call
                    .get("args")
                    .cloned()
                    .unwrap_or(serde_json::Value::Object(Default::default()));

                content.push(ContentBlock::ToolCall(ToolCall {
                    id: name.clone(), // Gemini 没有独立的 tool_call_id,用函数名
                    name,
                    arguments: args,
                }));
            }
        }

        // 解析 usageMetadata
        let usage_val = raw.get("usageMetadata");
        let usage = TokenUsage {
            prompt_tokens: usage_val
                .and_then(|u| u.get("promptTokenCount"))
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as u32,
            completion_tokens: usage_val
                .and_then(|u| u.get("candidatesTokenCount"))
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as u32,
            total_tokens: usage_val
                .and_then(|u| u.get("totalTokenCount"))
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as u32,
        };

        Ok(ChatResponse::new(content, usage, raw))
    }

    fn decode_sse(&self, frame: &SseFrame) -> Result<StreamParseResult, LlmError> {
        let data = &frame.data;
        if data.is_empty() {
            return Ok(StreamParseResult::empty());
        }

        let val: serde_json::Value = serde_json::from_str(data).map_err(|e| LlmError::Parse {
            detail: format!("Invalid SSE JSON: {}", e),
        })?;

        // Gemini 流式返回 candidates 数组
        let candidates = val.get("candidates").and_then(|c| c.as_array());
        if let Some(candidates) = candidates.filter(|c| !c.is_empty()) {
            let candidate = &candidates[0];
            let content = candidate.get("content");
            if let Some(content) = content {
                let parts = content.get("parts").and_then(|p| p.as_array());
                if let Some(parts) = parts {
                    let mut results: Vec<StreamChunk> = Vec::new();

                    for part in parts {
                        // 文本增量
                        if let Some(text) = part.get("text").and_then(|t| t.as_str())
                            && !text.is_empty()
                        {
                            results.push(StreamChunk::TextDelta(text.into()));
                        }

                        // 工具调用增量
                        if let Some(func_call) = part.get("functionCall") {
                            let name = func_call
                                .get("name")
                                .and_then(|v| v.as_str())
                                .map(|s| s.to_string());
                            let args = func_call.get("args").map(|v| v.to_string());

                            results.push(StreamChunk::ToolCallDelta(ToolCallDelta {
                                index: 0,
                                id: None,
                                name,
                                arguments_delta: args,
                            }));
                        }
                    }

                    // finishReason 存在即表示本轮结束
                    if candidate.get("finishReason").is_some() {
                        results.push(StreamChunk::Done);
                    }

                    if !results.is_empty() {
                        return Ok(StreamParseResult { chunks: results });
                    }
                }
            }
        }

        // usageMetadata 可能在最后一个 chunk 中
        if let Some(usage_val) = val.get("usageMetadata") {
            let usage = TokenUsage {
                prompt_tokens: usage_val
                    .get("promptTokenCount")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) as u32,
                completion_tokens: usage_val
                    .get("candidatesTokenCount")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) as u32,
                total_tokens: usage_val
                    .get("totalTokenCount")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) as u32,
            };
            return Ok(StreamParseResult::chunk(StreamChunk::Usage(usage)));
        }

        Ok(StreamParseResult::empty())
    }
}

// ── ModelCapabilities ──

impl ModelCapabilities for GoogleCodec {
    fn capabilities_for(&self, model: &str) -> Capabilities {
        let mut caps = Capabilities::default();
        let lower = model.to_lowercase();
        // Gemini 2.0 Flash 及 Pro 支持工具调用
        if lower.contains("gemini") {
            caps.supports_tool_call = true;
        }
        // Gemini 2.0 Pro 支持图片
        if lower.contains("pro") || lower.contains("2.0") {
            caps.supports_image_input = true;
        }
        caps
    }
}

/// 将 ContentBlock 序列化为 Gemini parts 数组。
fn serialize_google_parts(blocks: &[ContentBlock]) -> Result<Vec<serde_json::Value>, LlmError> {
    let mut parts = Vec::new();
    for block in blocks {
        match block {
            ContentBlock::Text(tb) => {
                parts.push(serde_json::json!({"text": tb.text}));
            }
            ContentBlock::Thinking(_) => {
                // Gemini 不支持 thinking blocks,静默跳过
            }
            ContentBlock::ToolCall(tc) => {
                parts.push(serde_json::json!({
                    "functionCall": {
                        "name": tc.name,
                        "args": tc.arguments
                    }
                }));
            }
            ContentBlock::Image { source: _ } => {
                return Err(LlmError::UnsupportedFeature {
                    feature: "Image in content blocks (Google adapter)".into(),
                });
            }
        }
    }
    Ok(parts)
}

/// 将 ToolResult 的 content 序列化为 Gemini functionResponse 格式。
fn serialize_google_tool_result_parts(blocks: &[ContentBlock]) -> serde_json::Value {
    let text: String = blocks
        .iter()
        .filter_map(|b| b.as_text())
        .collect::<Vec<_>>()
        .join("\n");
    serde_json::json!(text)
}

/// 将 ToolDefinition 序列化为 Gemini functionDeclarations。
fn serialize_google_tools(tools: &[lellm_core::ToolDefinition]) -> Vec<serde_json::Value> {
    tools
        .iter()
        .map(|tool| {
            let mut obj = serde_json::Map::new();
            obj.insert("name".into(), tool.name.clone().into());
            if !tool.description.is_empty() {
                obj.insert("description".into(), tool.description.clone().into());
            }
            obj.insert("parameters".into(), tool.parameters.clone());
            serde_json::Value::Object(obj)
        })
        .collect()
}

/// 将 ToolChoice 序列化为 Gemini functionCallingConfig。
fn serialize_google_tool_choice(choice: &ToolChoice) -> serde_json::Value {
    match choice {
        ToolChoice::Tool { name } => {
            serde_json::json!({"mode": "ANY", "allowedFunctionNames": [name]})
        }
        ToolChoice::Any => {
            serde_json::json!({"mode": "ANY"})
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use lellm_core::{CacheControl, TextBlock};

    #[test]
    fn test_tool_cache_control_ignored() {
        let tools = vec![lellm_core::ToolDefinition {
            name: "search".into(),
            description: "Search".into(),
            parameters: serde_json::json!({"type": "object"}),
            cache_control: Some(CacheControl::Breakpoint),
        }];
        let result = serialize_google_tools(&tools);
        assert_eq!(result.len(), 1);
        // cache_control 不应出现在 Google 输出中
        assert!(result[0].get("cache_control").is_none());
        assert_eq!(result[0]["name"], "search");
    }

    #[test]
    fn test_text_block_cache_control_ignored() {
        let blocks = vec![ContentBlock::Text(TextBlock {
            text: "hello".into(),
            cache_control: Some(CacheControl::Breakpoint),
        })];
        let text: String = blocks
            .iter()
            .filter_map(|b| b.as_text().map(|s| s.to_string()))
            .collect();
        // Google 只取文本,忽略 cache_control
        assert_eq!(text, "hello");
    }
}