lmkit 0.1.0

Multi-provider AI API client (OpenAI, Anthropic, Google Gemini, Aliyun, Ollama, Zhipu; chat, embed incl. Gemini, rerank, image, audio stubs)
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
//! **Anthropic Messages API** 兼容:`POST …/messages`(非流式与 `stream: true`)。
//!
//! 请求头:`x-api-key`、`anthropic-version`(当前实现为 `2023-06-01`)。详见模块级 rustdoc(历史说明)。

use async_trait::async_trait;
use futures::future::ready;
use futures::StreamExt;
use serde::Serialize;
use serde_json::{json, Value};
use std::time::Duration;

use crate::client::HttpClient;
use crate::config::ProviderConfig;
use crate::error::{Error, Result};
use crate::sse::SseEvent;

use super::{
    ChatChunk, ChatMessage, ChatProvider, ChatRequest, ChatResponse, ChatStream, FinishReason,
    FunctionCallResult, Role, ToolCall, ToolCallDelta, ToolChoice, ToolDefinition,
};

/// Anthropic Messages 兼容实现使用的 `anthropic-version` 请求头取值。
pub(crate) const ANTHROPIC_VERSION: &str = "2023-06-01";

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
const DEFAULT_MAX_TOKENS: u32 = 4096;
const DEFAULT_TEMPERATURE: f32 = 0.2;

#[derive(Debug, Serialize)]
struct MessagesBody {
    model: String,
    max_tokens: u32,
    #[serde(skip_serializing_if = "String::is_empty")]
    system: String,
    messages: Vec<AnthropicApiMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<AnthropicTool>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_choice: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stream: Option<bool>,
}

#[derive(Debug, Serialize)]
struct AnthropicApiMessage {
    role: String,
    content: AnthropicContent,
}

#[derive(Debug, Serialize)]
#[serde(untagged)]
enum AnthropicContent {
    Text(String),
    Blocks(Vec<Value>),
}

#[derive(Debug, Serialize)]
struct AnthropicTool {
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    input_schema: Value,
}

pub(crate) struct AnthropicCompatChat {
    client: HttpClient,
    api_key: String,
    model: String,
    base_url: String,
}

impl AnthropicCompatChat {
    pub fn new(config: &ProviderConfig) -> Result<Self> {
        let timeout = config.timeout.unwrap_or(DEFAULT_TIMEOUT);
        let client = HttpClient::new(timeout)?;
        Ok(Self {
            client,
            api_key: config.api_key.clone(),
            model: config.model.clone(),
            base_url: config.base_url.clone(),
        })
    }

    fn build_body(&self, request: &ChatRequest, stream: bool) -> Result<MessagesBody> {
        let (system, messages) = build_anthropic_messages(&request.messages)?;
        let tools: Option<Vec<AnthropicTool>> = request
            .tools
            .as_ref()
            .filter(|t| !t.is_empty())
            .map(|t| t.iter().map(tool_to_anthropic).collect());
        let tool_choice = if tools.is_some() {
            request
                .tool_choice
                .as_ref()
                .and_then(anthropic_tool_choice_json)
        } else {
            None
        };
        let max_tokens = request.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS);
        let temperature = request.temperature.or(Some(DEFAULT_TEMPERATURE));
        Ok(MessagesBody {
            model: self.model.clone(),
            max_tokens,
            system,
            messages,
            tools,
            tool_choice,
            temperature,
            stream: stream.then_some(true),
        })
    }
}

fn tool_to_anthropic(t: &ToolDefinition) -> AnthropicTool {
    AnthropicTool {
        name: t.function.name.clone(),
        description: t.function.description.clone(),
        input_schema: t.function.parameters.clone(),
    }
}

/// Anthropic 仅支持 `auto` / `any` / `tool`;`ToolChoice::None` 不传 `tool_choice`(与默认行为一致)。
fn anthropic_tool_choice_json(c: &ToolChoice) -> Option<Value> {
    match c {
        ToolChoice::None => None,
        ToolChoice::Auto => Some(json!({ "type": "auto" })),
        ToolChoice::Required => Some(json!({ "type": "any" })),
        ToolChoice::Tool(name) => Some(json!({ "type": "tool", "name": name })),
    }
}

fn build_anthropic_messages(msgs: &[ChatMessage]) -> Result<(String, Vec<AnthropicApiMessage>)> {
    let mut system_parts: Vec<String> = Vec::new();
    let mut out: Vec<AnthropicApiMessage> = Vec::new();
    for m in msgs {
        match m.role {
            Role::System => {
                if let Some(c) = &m.content {
                    if !c.is_empty() {
                        system_parts.push(c.clone());
                    }
                }
            }
            Role::User => {
                out.push(AnthropicApiMessage {
                    role: "user".to_string(),
                    content: user_content(m)?,
                });
            }
            Role::Assistant => {
                out.push(AnthropicApiMessage {
                    role: "assistant".to_string(),
                    content: assistant_content(m)?,
                });
            }
            Role::Tool => {
                let tool_use_id = m
                    .tool_call_id
                    .clone()
                    .ok_or(Error::MissingField("tool.tool_call_id"))?;
                let content = m.content.clone().unwrap_or_default();
                let block = json!({
                    "type": "tool_result",
                    "tool_use_id": tool_use_id,
                    "content": content,
                });
                out.push(AnthropicApiMessage {
                    role: "user".to_string(),
                    content: AnthropicContent::Blocks(vec![block]),
                });
            }
        }
    }
    Ok((system_parts.join("\n\n"), out))
}

fn user_content(m: &ChatMessage) -> Result<AnthropicContent> {
    let text = m
        .content
        .clone()
        .ok_or(Error::MissingField("user.content"))?;
    Ok(AnthropicContent::Text(text))
}

fn assistant_content(m: &ChatMessage) -> Result<AnthropicContent> {
    let has_tools = m.tool_calls.as_ref().is_some_and(|t| !t.is_empty());
    if !has_tools {
        return Ok(AnthropicContent::Text(
            m.content.clone().unwrap_or_default(),
        ));
    }
    let mut blocks: Vec<Value> = Vec::new();
    if let Some(t) = &m.content {
        if !t.is_empty() {
            blocks.push(json!({ "type": "text", "text": t }));
        }
    }
    if let Some(calls) = &m.tool_calls {
        for c in calls {
            let input: Value = serde_json::from_str(&c.function.arguments).unwrap_or(json!({}));
            blocks.push(json!({
                "type": "tool_use",
                "id": c.id,
                "name": c.function.name,
                "input": input,
            }));
        }
    }
    if blocks.is_empty() {
        Ok(AnthropicContent::Text(String::new()))
    } else {
        Ok(AnthropicContent::Blocks(blocks))
    }
}

#[async_trait]
impl ChatProvider for AnthropicCompatChat {
    async fn complete(&self, request: &ChatRequest) -> Result<ChatResponse> {
        let body = self.build_body(request, false)?;
        let url = format!("{}/messages", self.base_url.trim_end_matches('/'));
        let headers = [
            ("x-api-key", self.api_key.as_str()),
            ("anthropic-version", ANTHROPIC_VERSION),
        ];
        let v: Value = self
            .client
            .post_json_with_headers(&url, &headers, &body, |s| s)
            .await?;
        parse_anthropic_message_response(&v)
    }

    async fn complete_stream(&self, request: &ChatRequest) -> Result<ChatStream> {
        let body = self.build_body(request, true)?;
        let url = format!("{}/messages", self.base_url.trim_end_matches('/'));
        let headers = [
            ("x-api-key", self.api_key.as_str()),
            ("anthropic-version", ANTHROPIC_VERSION),
        ];
        let sse = self
            .client
            .post_json_with_headers_sse(&url, &headers, &body, |s| s)
            .await?;
        let mut finish_emitted = false;
        Ok(Box::pin(sse.filter_map(move |item| {
            ready(anthropic_stream_item_to_chunk(item, &mut finish_emitted))
        })))
    }
}

fn parse_anthropic_message_response(body: &Value) -> Result<ChatResponse> {
    let content = body
        .get("content")
        .and_then(|c| c.as_array())
        .ok_or(Error::MissingField("content"))?;
    let mut text_parts: Vec<String> = Vec::new();
    let mut tool_calls: Vec<ToolCall> = Vec::new();
    for block in content {
        match block.get("type").and_then(|t| t.as_str()) {
            Some("text") => {
                if let Some(t) = block.get("text").and_then(|x| x.as_str()) {
                    text_parts.push(t.to_string());
                }
            }
            Some("tool_use") => {
                let id = block
                    .get("id")
                    .and_then(|x| x.as_str())
                    .ok_or(Error::MissingField("tool_use.id"))?
                    .to_string();
                let name = block
                    .get("name")
                    .and_then(|x| x.as_str())
                    .ok_or(Error::MissingField("tool_use.name"))?
                    .to_string();
                let input = block.get("input").cloned().unwrap_or(json!({}));
                let arguments = serde_json::to_string(&input).unwrap_or_else(|_| "{}".to_string());
                tool_calls.push(ToolCall {
                    id,
                    function: FunctionCallResult { name, arguments },
                });
            }
            _ => {}
        }
    }
    let text = if text_parts.is_empty() {
        None
    } else {
        Some(text_parts.join(""))
    };
    let tool_calls = if tool_calls.is_empty() {
        None
    } else {
        Some(tool_calls)
    };
    let finish_reason = body
        .get("stop_reason")
        .and_then(|s| s.as_str())
        .and_then(map_anthropic_stop_reason);
    Ok(ChatResponse {
        content: text,
        tool_calls,
        finish_reason,
    })
}

/// 流式解析中间结果:`message_stop` 单独标记,便于与 `message_delta` 中的 `stop_reason` 去重。
enum AnthropicStreamParse {
    Chunk(ChatChunk),
    MessageStopOnly,
}

fn anthropic_stream_item_to_chunk(
    item: Result<SseEvent>,
    finish_emitted: &mut bool,
) -> Option<Result<ChatChunk>> {
    let ev = match item {
        Err(e) => return Some(Err(e)),
        Ok(ev) => ev,
    };
    let inner = match anthropic_parse_sse_event(ev) {
        None => return None,
        Some(Err(e)) => return Some(Err(e)),
        Some(Ok(p)) => p,
    };
    match inner {
        AnthropicStreamParse::Chunk(c) => {
            if c.finish_reason.is_some() {
                *finish_emitted = true;
            }
            Some(Ok(c))
        }
        AnthropicStreamParse::MessageStopOnly => {
            if *finish_emitted {
                None
            } else {
                *finish_emitted = true;
                Some(Ok(ChatChunk::finish(FinishReason::Stop)))
            }
        }
    }
}

fn anthropic_parse_sse_event(ev: SseEvent) -> Option<Result<AnthropicStreamParse>> {
    let data = ev.data.trim();
    if data.is_empty() {
        return None;
    }
    let v: Value = match serde_json::from_str(data) {
        Ok(v) => v,
        Err(e) => return Some(Err(Error::Parse(e.to_string()))),
    };

    if ev.event.as_deref() == Some("error")
        || v.get("type").and_then(|t| t.as_str()) == Some("error")
    {
        let msg = v
            .get("error")
            .and_then(|e| e.get("message"))
            .and_then(|m| m.as_str())
            .unwrap_or("anthropic stream error");
        // SSE error 帧通常不带 HTTP 状态码;用 500 表示「流内协议错误」,便于与 `Error::Api` 统一。
        return Some(Err(Error::Api {
            status: 500,
            message: msg.to_string(),
        }));
    }

    let ty = v.get("type").and_then(|t| t.as_str())?;

    match ty {
        "content_block_start" => {
            let block = v.get("content_block")?;
            if block.get("type").and_then(|t| t.as_str()) == Some("tool_use") {
                let index = v.get("index").and_then(|i| i.as_u64()).unwrap_or(0) as u32;
                let id = block.get("id").and_then(|x| x.as_str()).map(str::to_string);
                let name = block
                    .get("name")
                    .and_then(|x| x.as_str())
                    .map(str::to_string);
                return Some(Ok(AnthropicStreamParse::Chunk(ChatChunk {
                    delta: None,
                    tool_call_deltas: Some(vec![ToolCallDelta {
                        index,
                        id,
                        function_name: name,
                        function_arguments: None,
                    }]),
                    finish_reason: None,
                })));
            }
            None
        }
        "content_block_delta" => {
            let delta = v.get("delta")?;
            if delta.get("type").and_then(|t| t.as_str()) == Some("text_delta") {
                let text = delta.get("text").and_then(|t| t.as_str())?;
                return Some(Ok(AnthropicStreamParse::Chunk(ChatChunk::delta(text))));
            }
            if delta.get("type").and_then(|t| t.as_str()) == Some("input_json_delta") {
                let index = v.get("index").and_then(|i| i.as_u64()).unwrap_or(0) as u32;
                let partial = delta
                    .get("partial_json")
                    .and_then(|p| p.as_str())
                    .unwrap_or("")
                    .to_string();
                return Some(Ok(AnthropicStreamParse::Chunk(ChatChunk {
                    delta: None,
                    tool_call_deltas: Some(vec![ToolCallDelta {
                        index,
                        id: None,
                        function_name: None,
                        function_arguments: Some(partial),
                    }]),
                    finish_reason: None,
                })));
            }
            None
        }
        "message_delta" => {
            let stop = v
                .get("delta")
                .and_then(|d| d.get("stop_reason"))
                .and_then(|s| s.as_str());
            if let Some(r) = stop {
                if let Some(fr) = map_anthropic_stop_reason(r) {
                    return Some(Ok(AnthropicStreamParse::Chunk(ChatChunk {
                        delta: None,
                        tool_call_deltas: None,
                        finish_reason: Some(fr),
                    })));
                }
            }
            None
        }
        "message_stop" => Some(Ok(AnthropicStreamParse::MessageStopOnly)),
        _ => None,
    }
}

fn map_anthropic_stop_reason(s: &str) -> Option<FinishReason> {
    match s {
        "end_turn" | "stop_sequence" => Some(FinishReason::Stop),
        "max_tokens" => Some(FinishReason::Length),
        "tool_use" => Some(FinishReason::ToolCalls),
        _ => None,
    }
}

#[cfg(test)]
mod tests;