agentix 0.22.1

Multi-provider LLM client for Rust — streaming, non-streaming, tool calls, MCP, DeepSeek, OpenAI, Anthropic, Gemini, Mimo
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
pub mod request;
pub mod response;

use eventsource_stream::Eventsource;
use futures::{StreamExt, stream::BoxStream};
use tracing::debug;

use crate::config::AgentConfig;
use crate::error::ApiError;
use crate::msg::LlmEvent;
use crate::provider::{PostConfig, post_json, post_streaming};
use crate::raw::shared::ToolDefinition;
use crate::request::{Message, ToolCall};
use crate::types::{
    CompleteResponse, FinishReason, PartialToolCall, StreamBufs, ToolCallChunk, UsageStats,
};

use response::{ContentBlockDelta, ContentBlockStart, ResponseBlock, StreamEvent};

pub(crate) async fn stream_anthropic(
    token: &str,
    http: &reqwest::Client,
    config: &AgentConfig,
    messages: &[Message],
    tools: &[ToolDefinition],
) -> Result<BoxStream<'static, LlmEvent>, ApiError> {
    stream_anthropic_with_post_config(
        token,
        http,
        config,
        messages,
        tools,
        PostConfig {
            use_query_key: false,
            auth_header: Some("x-api-key"),
            extra_headers: &[("anthropic-version", "2023-06-01")],
            max_retries: config.max_retries,
            retry_delay_ms: config.retry_delay_ms,
        },
    )
    .await
}

pub(crate) async fn stream_mimo(
    token: &str,
    http: &reqwest::Client,
    config: &AgentConfig,
    messages: &[Message],
    tools: &[ToolDefinition],
) -> Result<BoxStream<'static, LlmEvent>, ApiError> {
    stream_anthropic_with_post_config(
        token,
        http,
        config,
        messages,
        tools,
        PostConfig {
            use_query_key: false,
            auth_header: Some("api-key"),
            extra_headers: &[],
            max_retries: config.max_retries,
            retry_delay_ms: config.retry_delay_ms,
        },
    )
    .await
}

async fn stream_anthropic_with_post_config(
    token: &str,
    http: &reqwest::Client,
    config: &AgentConfig,
    messages: &[Message],
    tools: &[ToolDefinition],
    post_config: PostConfig,
) -> Result<BoxStream<'static, LlmEvent>, ApiError> {
    let req = request::build_anthropic_request(config, messages, tools, true);
    let url = format!("{}/v1/messages", config.base_url.trim_end_matches('/'));
    let resp = post_streaming(http, &url, &req, token, &post_config).await?;

    Ok(async_stream::stream! {
        let mut bufs = StreamBufs::new();
        let mut blocks: Vec<Option<BlockBuild>> = Vec::new();
        let mut sse  = resp.bytes_stream().eventsource();
        let mut saw_message_stop = false;

        while let Some(ev_res) = sse.next().await {
            match ev_res {
                Ok(ev) => {
                    #[cfg(feature = "sensitive-logs")]
                    if crate::sensitive_logs_enabled() {
                        tracing::info!(body = %ev.data, "received raw streaming response chunk");
                    }
                    if ev.data == "[DONE]" {
                        break;
                    }
                    match serde_json::from_str::<StreamEvent>(&ev.data) {
                        Ok(chunk) => {
                            if matches!(chunk, StreamEvent::MessageStop) {
                                saw_message_stop = true;
                            }
                            for lev in parse_stream_event(chunk, &mut bufs, &mut blocks) { yield lev; }
                        }
                        Err(e) => {
                            debug!(data = %ev.data, error = %e, "anthropic chunk parse failed");
                        }
                    }
                }
                Err(e) => { yield LlmEvent::Error(e.to_string()); break; }
            }
        }
        if !saw_message_stop {
            yield LlmEvent::Error("stream ended without message_stop".to_string());
        }
        for tc in finalize(&mut bufs) { yield LlmEvent::ToolCall(tc); }
        // Only emit provider_data when the turn has both thinking AND tool_use
        // blocks — that's the combination where Anthropic enforces signature
        // round-trip on the next turn.
        if let Some(state) = assistant_state_from_blocks(&blocks) {
            yield LlmEvent::AssistantState(state);
        }
        yield LlmEvent::Done;
    }
    .boxed())
}

pub(crate) async fn complete_anthropic(
    token: &str,
    http: &reqwest::Client,
    config: &AgentConfig,
    messages: &[Message],
    tools: &[ToolDefinition],
) -> Result<CompleteResponse, ApiError> {
    complete_anthropic_with_post_config(
        token,
        http,
        config,
        messages,
        tools,
        PostConfig {
            use_query_key: false,
            auth_header: Some("x-api-key"),
            extra_headers: &[("anthropic-version", "2023-06-01")],
            max_retries: config.max_retries,
            retry_delay_ms: config.retry_delay_ms,
        },
    )
    .await
}

pub(crate) async fn complete_mimo(
    token: &str,
    http: &reqwest::Client,
    config: &AgentConfig,
    messages: &[Message],
    tools: &[ToolDefinition],
) -> Result<CompleteResponse, ApiError> {
    complete_anthropic_with_post_config(
        token,
        http,
        config,
        messages,
        tools,
        PostConfig {
            use_query_key: false,
            auth_header: Some("api-key"),
            extra_headers: &[],
            max_retries: config.max_retries,
            retry_delay_ms: config.retry_delay_ms,
        },
    )
    .await
}

async fn complete_anthropic_with_post_config(
    token: &str,
    http: &reqwest::Client,
    config: &AgentConfig,
    messages: &[Message],
    tools: &[ToolDefinition],
    post_config: PostConfig,
) -> Result<CompleteResponse, ApiError> {
    let req = request::build_anthropic_request(config, messages, tools, false);
    let url = format!("{}/v1/messages", config.base_url.trim_end_matches('/'));
    let body = post_json(http, &url, &req, token, &post_config).await?;

    // Parse twice: once structurally for content/tool_calls/reasoning, once
    // as a raw Value to preserve the full content array for round-tripping
    // thinking blocks with signatures.
    let raw_value: serde_json::Value = serde_json::from_str(&body).map_err(ApiError::Json)?;
    let raw: response::Response = serde_json::from_str(&body).map_err(ApiError::Json)?;

    let mut content_buf = String::new();
    let mut reasoning_buf = String::new();
    let mut tool_calls = Vec::new();
    let mut has_thinking = false;

    for block in &raw.content {
        match block {
            ResponseBlock::Text { text } => content_buf.push_str(text),
            ResponseBlock::Thinking { thinking, .. } => {
                reasoning_buf.push_str(thinking);
                has_thinking = true;
            }
            ResponseBlock::RedactedThinking { .. } => {
                has_thinking = true;
            }
            ResponseBlock::ToolUse { id, name, input } => {
                tool_calls.push(ToolCall {
                    id: id.clone(),
                    name: name.clone(),
                    arguments: serde_json::to_string(input).unwrap_or_default(),
                });
            }
        }
    }

    // Only preserve provider_data when the turn has both thinking AND tool
    // calls — that's when Anthropic enforces signature round-trip. Pure
    // thinking-no-tools turns don't require it (the API strips them).
    let provider_data = if has_thinking && !tool_calls.is_empty() {
        raw_value
            .get("content")
            .cloned()
            .map(anthropic_content_to_provider_data)
    } else {
        None
    };

    Ok(CompleteResponse {
        content: if content_buf.is_empty() {
            None
        } else {
            Some(content_buf)
        },
        reasoning: if reasoning_buf.is_empty() {
            None
        } else {
            Some(reasoning_buf)
        },
        tool_calls,
        provider_data,
        usage: raw.usage.map(UsageStats::from).unwrap_or_default(),
        finish_reason: raw
            .stop_reason
            .as_deref()
            .map(FinishReason::from)
            .unwrap_or_default(),
    })
}

/// Wrap the raw content array in a tagged envelope so the request serializer
/// can identify Anthropic's format if another provider ever emits
/// provider_data of a different shape. The wrapper also isolates callers from
/// the raw Anthropic content shape (they should treat it as opaque).
fn anthropic_content_to_provider_data(content: serde_json::Value) -> serde_json::Value {
    serde_json::json!({
        "anthropic_content": content,
    })
}

fn parse_stream_event(
    ev: StreamEvent,
    bufs: &mut StreamBufs,
    blocks: &mut Vec<Option<BlockBuild>>,
) -> Vec<LlmEvent> {
    match ev {
        StreamEvent::MessageStart { message } => {
            if let Some(u) = message.usage {
                return vec![LlmEvent::Usage(UsageStats::from(u))];
            }
            vec![]
        }
        StreamEvent::MessageDelta { usage, .. } => {
            if let Some(u) = usage {
                return vec![LlmEvent::Usage(UsageStats::from(u))];
            }
            vec![]
        }
        StreamEvent::ContentBlockStart {
            index,
            content_block,
        } => {
            let idx = index as usize;
            if bufs.tool_call_bufs.len() <= idx {
                bufs.tool_call_bufs.resize_with(idx + 1, || None);
            }
            if blocks.len() <= idx {
                blocks.resize_with(idx + 1, || None);
            }
            match content_block {
                ContentBlockStart::ToolUse { id, name } => {
                    bufs.tool_call_bufs[idx] = Some(PartialToolCall {
                        id: id.clone(),
                        name: name.clone(),
                        arguments: String::new(),
                    });
                    blocks[idx] = Some(BlockBuild::ToolUse {
                        id: id.clone(),
                        name: name.clone(),
                        input_json: String::new(),
                    });
                    vec![LlmEvent::ToolCallChunk(ToolCallChunk {
                        id,
                        name,
                        delta: String::new(),
                        index,
                    })]
                }
                ContentBlockStart::Text { text } => {
                    blocks[idx] = Some(BlockBuild::Text { text: text.clone() });
                    if text.is_empty() {
                        vec![]
                    } else {
                        bufs.content_buf.push_str(&text);
                        vec![LlmEvent::Token(text)]
                    }
                }
                ContentBlockStart::Thinking { thinking } => {
                    blocks[idx] = Some(BlockBuild::Thinking {
                        text: thinking.clone(),
                        signature: None,
                    });
                    if thinking.is_empty() {
                        vec![]
                    } else {
                        bufs.reasoning_buf.push_str(&thinking);
                        vec![LlmEvent::Reasoning(thinking)]
                    }
                }
                ContentBlockStart::RedactedThinking { data } => {
                    blocks[idx] = Some(BlockBuild::RedactedThinking { data });
                    vec![]
                }
            }
        }
        StreamEvent::ContentBlockDelta { index, delta } => {
            let idx = index as usize;
            match delta {
                ContentBlockDelta::TextDelta { text } if !text.is_empty() => {
                    if let Some(Some(BlockBuild::Text { text: t })) = blocks.get_mut(idx) {
                        t.push_str(&text);
                    }
                    bufs.content_buf.push_str(&text);
                    vec![LlmEvent::Token(text)]
                }
                ContentBlockDelta::ThinkingDelta { thinking } if !thinking.is_empty() => {
                    if let Some(Some(BlockBuild::Thinking { text, .. })) = blocks.get_mut(idx) {
                        text.push_str(&thinking);
                    }
                    bufs.reasoning_buf.push_str(&thinking);
                    vec![LlmEvent::Reasoning(thinking)]
                }
                ContentBlockDelta::SignatureDelta { signature } => {
                    if let Some(Some(BlockBuild::Thinking { signature: sig, .. })) =
                        blocks.get_mut(idx)
                    {
                        match sig {
                            Some(existing) => existing.push_str(&signature),
                            None => *sig = Some(signature),
                        }
                    }
                    vec![]
                }
                ContentBlockDelta::InputJsonDelta { partial_json } if !partial_json.is_empty() => {
                    if let Some(Some(BlockBuild::ToolUse { input_json, .. })) = blocks.get_mut(idx)
                    {
                        input_json.push_str(&partial_json);
                    }
                    if let Some(Some(partial)) = bufs.tool_call_bufs.get_mut(idx) {
                        partial.arguments.push_str(&partial_json);
                        vec![LlmEvent::ToolCallChunk(ToolCallChunk {
                            id: partial.id.clone(),
                            name: partial.name.clone(),
                            delta: partial_json,
                            index,
                        })]
                    } else {
                        vec![]
                    }
                }
                _ => vec![],
            }
        }
        _ => vec![],
    }
}

#[derive(Debug)]
enum BlockBuild {
    Text {
        text: String,
    },
    Thinking {
        text: String,
        signature: Option<String>,
    },
    RedactedThinking {
        data: String,
    },
    ToolUse {
        id: String,
        name: String,
        input_json: String,
    },
}

impl BlockBuild {
    fn to_value(&self) -> serde_json::Value {
        match self {
            BlockBuild::Text { text } => {
                serde_json::json!({ "type": "text", "text": text })
            }
            BlockBuild::Thinking { text, signature } => {
                let mut obj = serde_json::json!({ "type": "thinking", "thinking": text });
                if let Some(sig) = signature {
                    obj.as_object_mut()
                        .unwrap()
                        .insert("signature".into(), serde_json::Value::String(sig.clone()));
                }
                obj
            }
            BlockBuild::RedactedThinking { data } => {
                serde_json::json!({ "type": "redacted_thinking", "data": data })
            }
            BlockBuild::ToolUse {
                id,
                name,
                input_json,
            } => {
                let input: serde_json::Value = serde_json::from_str(input_json)
                    .unwrap_or_else(|_| serde_json::Value::Object(Default::default()));
                serde_json::json!({
                    "type": "tool_use",
                    "id": id,
                    "name": name,
                    "input": input,
                })
            }
        }
    }
}

fn assistant_state_from_blocks(blocks: &[Option<BlockBuild>]) -> Option<serde_json::Value> {
    let has_thinking = blocks.iter().flatten().any(|b| {
        matches!(
            b,
            BlockBuild::Thinking { .. } | BlockBuild::RedactedThinking { .. }
        )
    });
    let has_tool_use = blocks
        .iter()
        .flatten()
        .any(|b| matches!(b, BlockBuild::ToolUse { .. }));
    if !(has_thinking && has_tool_use) {
        return None;
    }
    let arr: Vec<serde_json::Value> = blocks.iter().flatten().map(|b| b.to_value()).collect();
    Some(serde_json::json!({ "anthropic_content": serde_json::Value::Array(arr) }))
}

fn finalize(bufs: &mut StreamBufs) -> Vec<ToolCall> {
    bufs.tool_call_bufs
        .drain(..)
        .flatten()
        .map(|p| ToolCall {
            id: p.id,
            name: p.name,
            arguments: p.arguments,
        })
        .collect()
}