llm-connector 1.2.1

Next-generation Rust library for LLM protocol abstraction with native multi-modal support. Supports 12+ providers (OpenAI, Anthropic, Google, Aliyun, Zhipu, Ollama, Tencent, Volcengine, LongCat, Moonshot, DeepSeek, Xiaomi) with clean Protocol/Provider separation, type-safe interface, and universal 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
use crate::error::LlmConnectorError;
use crate::types::{ChatRequest, ChatResponse, Message, Role, Tool, ToolChoice};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[cfg(feature = "streaming")]
use futures_util::Stream;
#[cfg(feature = "streaming")]
use std::pin::Pin;

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResponsesRequest {
    pub model: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_output_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub previous_response_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,

    #[serde(skip_serializing)]
    pub api_key: Option<String>,
    #[serde(skip_serializing)]
    pub base_url: Option<String>,
    #[serde(skip_serializing)]
    pub extra_headers: Option<HashMap<String, String>>,

    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResponsesUsage {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_tokens: Option<u32>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResponsesOutputContent {
    #[serde(rename = "type")]
    pub content_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResponsesOutputItem {
    #[serde(rename = "type")]
    pub item_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<Vec<ResponsesOutputContent>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResponsesResponse {
    pub id: String,
    pub object: String,
    #[serde(default)]
    pub created_at: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<Vec<ResponsesOutputItem>>,
    #[serde(default)]
    pub output_text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<ResponsesUsage>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

impl ResponsesResponse {
    pub fn populate_output_text(&mut self) {
        if !self.output_text.is_empty() {
            return;
        }

        let mut merged = Vec::new();
        if let Some(output) = &self.output {
            for item in output {
                if let Some(content) = &item.content {
                    for block in content {
                        if let Some(text) = &block.text
                            && !text.is_empty()
                        {
                            merged.push(text.clone());
                        }
                    }
                }
            }
        }

        if !merged.is_empty() {
            self.output_text = merged.join("");
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResponsesStreamEvent {
    #[serde(rename = "type")]
    pub event_type: String,
    #[serde(flatten)]
    pub data: HashMap<String, serde_json::Value>,
}

impl ResponsesStreamEvent {
    pub fn response_created(response_id: impl Into<String>, model: Option<String>) -> Self {
        let mut data = HashMap::new();
        data.insert(
            "response".to_string(),
            serde_json::json!({
                "id": response_id.into(),
                "object": "response",
                "model": model,
                "status": "in_progress",
            }),
        );
        Self {
            event_type: "response.created".to_string(),
            data,
        }
    }

    pub fn output_text_delta(response_id: impl Into<String>, delta: impl Into<String>) -> Self {
        let mut data = HashMap::new();
        data.insert(
            "response_id".to_string(),
            serde_json::json!(response_id.into()),
        );
        data.insert("delta".to_string(), serde_json::json!(delta.into()));
        Self {
            event_type: "response.output_text.delta".to_string(),
            data,
        }
    }

    pub fn response_completed(
        response_id: impl Into<String>,
        usage: Option<ResponsesUsage>,
        model: Option<String>,
    ) -> Self {
        let mut data = HashMap::new();
        data.insert(
            "response".to_string(),
            serde_json::json!({
                "id": response_id.into(),
                "object": "response",
                "model": model,
                "status": "completed",
                "usage": usage,
            }),
        );
        Self {
            event_type: "response.completed".to_string(),
            data,
        }
    }
}

#[cfg(feature = "streaming")]
pub type ResponsesStream = Pin<
    Box<dyn Stream<Item = Result<ResponsesStreamEvent, crate::error::LlmConnectorError>> + Send>,
>;

pub fn responses_request_to_chat_request(
    request: &ResponsesRequest,
) -> Result<ChatRequest, LlmConnectorError> {
    let mut messages = Vec::new();

    if let Some(instructions) = &request.instructions
        && !instructions.trim().is_empty()
    {
        messages.push(Message::system(instructions.clone()));
    }

    if let Some(input) = &request.input {
        append_input_messages(&mut messages, input)?;
    }

    let tools = if let Some(raw_tools) = request.tools.as_ref() {
        Some(
            serde_json::from_value::<Vec<Tool>>(raw_tools.clone()).map_err(|e| {
                LlmConnectorError::InvalidRequest(format!("Failed to map responses.tools: {}", e))
            })?,
        )
    } else {
        None
    };

    let tool_choice = if let Some(raw_choice) = request.tool_choice.as_ref() {
        Some(
            serde_json::from_value::<ToolChoice>(raw_choice.clone()).map_err(|e| {
                LlmConnectorError::InvalidRequest(format!(
                    "Failed to map responses.tool_choice: {}",
                    e
                ))
            })?,
        )
    } else {
        None
    };

    Ok(ChatRequest {
        model: request.model.clone(),
        messages,
        temperature: request.temperature,
        top_p: request.top_p,
        max_tokens: request.max_output_tokens,
        stream: request.stream,
        tools,
        tool_choice,
        api_key: request.api_key.clone(),
        base_url: request.base_url.clone(),
        extra_headers: request.extra_headers.clone(),
        ..Default::default()
    })
}

pub fn chat_response_to_responses_response(chat: &ChatResponse) -> ResponsesResponse {
    let text = if !chat.content.is_empty() {
        chat.content.clone()
    } else {
        chat.choices
            .first()
            .map(|choice| choice.message.content_as_text())
            .unwrap_or_default()
    };

    let usage = chat.usage.as_ref().map(|u| ResponsesUsage {
        input_tokens: Some(u.prompt_tokens),
        output_tokens: Some(u.completion_tokens),
        total_tokens: Some(u.total_tokens),
        extra: HashMap::new(),
    });

    ResponsesResponse {
        id: chat.id.clone(),
        object: "response".to_string(),
        created_at: chat.created,
        model: Some(chat.model.clone()),
        status: Some("completed".to_string()),
        output: Some(vec![ResponsesOutputItem {
            item_type: "message".to_string(),
            id: Some(format!("msg_{}", chat.id)),
            role: Some("assistant".to_string()),
            content: Some(vec![ResponsesOutputContent {
                content_type: "output_text".to_string(),
                text: Some(text.clone()),
                extra: HashMap::new(),
            }]),
            name: None,
            arguments: None,
            extra: HashMap::new(),
        }]),
        output_text: text,
        usage,
        extra: HashMap::new(),
    }
}

fn append_input_messages(
    messages: &mut Vec<Message>,
    input: &serde_json::Value,
) -> Result<(), LlmConnectorError> {
    match input {
        serde_json::Value::Null => {}
        serde_json::Value::String(text) => {
            if !text.is_empty() {
                messages.push(Message::user(text.clone()));
            }
        }
        serde_json::Value::Array(items) => {
            if let Ok(parsed) = serde_json::from_value::<Vec<Message>>(input.clone()) {
                messages.extend(parsed);
                return Ok(());
            }

            for item in items {
                if let Some(msg) = map_input_item_to_message(item) {
                    messages.push(msg);
                }
            }
        }
        serde_json::Value::Object(_) => {
            if let Ok(parsed) = serde_json::from_value::<Message>(input.clone()) {
                messages.push(parsed);
                return Ok(());
            }

            if let Some(msg) = map_input_item_to_message(input) {
                messages.push(msg);
            }
        }
        _ => {
            return Err(LlmConnectorError::InvalidRequest(
                "responses.input must be string/object/array".to_string(),
            ));
        }
    }

    Ok(())
}

fn map_input_item_to_message(value: &serde_json::Value) -> Option<Message> {
    let obj = value.as_object()?;

    if let Some(content) = obj.get("content")
        && content.is_string()
    {
        let role = parse_role(obj.get("role"));
        return Some(Message::text(role, content.as_str().unwrap_or_default()));
    }

    if let Some(text) = obj.get("text").and_then(|v| v.as_str()) {
        let role = parse_role(obj.get("role"));
        return Some(Message::text(role, text));
    }

    if obj.get("type").and_then(|v| v.as_str()) == Some("input_text")
        && let Some(text) = obj.get("text").and_then(|v| v.as_str())
    {
        return Some(Message::user(text));
    }

    if let Some(content) = obj.get("content").and_then(|v| v.as_array()) {
        let mut joined = Vec::new();
        for part in content {
            if part.get("type").and_then(|v| v.as_str()) == Some("input_text")
                && let Some(text) = part.get("text").and_then(|v| v.as_str())
            {
                joined.push(text.to_string());
            }
        }

        if !joined.is_empty() {
            let role = parse_role(obj.get("role"));
            return Some(Message::text(role, joined.join("\n")));
        }
    }

    None
}

fn parse_role(raw: Option<&serde_json::Value>) -> Role {
    match raw.and_then(|v| v.as_str()).unwrap_or("user") {
        "system" => Role::System,
        "assistant" => Role::Assistant,
        "tool" => Role::Tool,
        _ => Role::User,
    }
}

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

    #[test]
    fn test_map_string_input_to_chat_message() {
        let req = ResponsesRequest {
            model: "gpt-4.1".to_string(),
            input: Some(serde_json::json!("hello")),
            ..Default::default()
        };

        let chat = responses_request_to_chat_request(&req).expect("map should succeed");
        assert_eq!(chat.messages.len(), 1);
        assert_eq!(chat.messages[0].role, Role::User);
        assert_eq!(chat.messages[0].content_as_text(), "hello");
    }

    #[test]
    fn test_map_instructions_to_system_message() {
        let req = ResponsesRequest {
            model: "gpt-4.1".to_string(),
            instructions: Some("be concise".to_string()),
            input: Some(serde_json::json!("hello")),
            ..Default::default()
        };

        let chat = responses_request_to_chat_request(&req).expect("map should succeed");
        assert_eq!(chat.messages.len(), 2);
        assert_eq!(chat.messages[0].role, Role::System);
        assert_eq!(chat.messages[0].content_as_text(), "be concise");
    }

    #[test]
    fn test_chat_response_to_responses_response() {
        let chat = ChatResponse {
            id: "chatcmpl_1".to_string(),
            object: "chat.completion".to_string(),
            created: 1,
            model: "gpt-4.1".to_string(),
            content: "ok".to_string(),
            ..Default::default()
        };

        let resp = chat_response_to_responses_response(&chat);
        assert_eq!(resp.object, "response");
        assert_eq!(resp.output_text, "ok");
        assert_eq!(resp.model.as_deref(), Some("gpt-4.1"));
    }
}