adk-model 3.0.0

LLM model integrations for Rust Agent Development Kit (ADK-Rust) (Gemini, OpenAI, Claude, DeepSeek, etc.)
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
//! Azure AI Inference client implementation.

use super::config::AzureAIConfig;
use super::convert;
use crate::retry::{RetryConfig, execute_with_retry, is_retryable_model_error};
use adk_core::{AdkError, ErrorComponent, Llm, LlmRequest, LlmResponse, LlmResponseStream, Part};
use async_stream::try_stream;
use async_trait::async_trait;
use futures::StreamExt;
use reqwest::Client;
use serde_json::Value;

/// Stream that ended, or whose connection failed, before a finish reason.
const INCOMPLETE_STREAM: &str = "model.azure_ai.incomplete_stream";
/// Stream chunk that is not valid JSON.
const INVALID_CHUNK: &str = "model.azure_ai.invalid_chunk";
/// Error frame the endpoint sent inside the stream.
const STREAM_ERROR: &str = "model.azure_ai.stream_error";

/// Azure AI Inference client for models hosted on Azure AI endpoints.
///
/// Supports models like Cohere, Llama, and Mistral deployed via Azure AI
/// Inference. Uses `api-key` header authentication and the Azure AI chat
/// completions REST API.
///
/// # Example
///
/// ```rust,ignore
/// use adk_model::azure_ai::{AzureAIClient, AzureAIConfig};
///
/// let config = AzureAIConfig::new(
///     "https://my-endpoint.eastus.inference.ai.azure.com",
///     "my-api-key",
///     "meta-llama-3.1-8b-instruct",
/// );
/// let client = AzureAIClient::new(config)?;
/// ```
pub struct AzureAIClient {
    client: Client,
    endpoint: String,
    api_key: String,
    model: String,
    retry_config: RetryConfig,
}

impl AzureAIClient {
    /// Create a new Azure AI Inference client from the given config.
    pub fn new(config: AzureAIConfig) -> Result<Self, AdkError> {
        let client = crate::HttpTimeouts::default()
            .apply(Client::builder())
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|e| AdkError::model(format!("Failed to create HTTP client: {e}")))?;

        Ok(Self {
            client,
            endpoint: config.endpoint,
            api_key: config.api_key,
            model: config.model,
            retry_config: RetryConfig::default(),
        })
    }

    /// Sets the connect and idle timeouts of the HTTP transport, so a stalled stream fails
    /// with a `Timeout` error instead of holding the run.
    ///
    /// See [`HttpTimeouts`](crate::HttpTimeouts) for the defaults.
    ///
    /// # Example
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use adk_model::azure_ai::{AzureAIClient, AzureAIConfig};
    /// use adk_model::HttpTimeouts;
    ///
    /// let config = AzureAIConfig::new("https://my-endpoint.inference.ai.azure.com", "key", "model");
    /// let client = AzureAIClient::new(config)?
    ///     .with_timeouts(HttpTimeouts::new(Duration::from_secs(10), Duration::from_secs(120)))?;
    /// # let _ = client;
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error when the Azure AI HTTP client cannot be built.
    pub fn with_timeouts(mut self, timeouts: crate::HttpTimeouts) -> Result<Self, AdkError> {
        self.client = timeouts
            .apply(Client::builder())
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|e| AdkError::model(format!("Failed to create HTTP client: {e}")))?;
        Ok(self)
    }

    /// Set the retry configuration, consuming and returning `self` for builder chaining.
    #[must_use]
    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
        self.retry_config = retry_config;
        self
    }

    /// Set the retry configuration by mutable reference.
    pub fn set_retry_config(&mut self, retry_config: RetryConfig) {
        self.retry_config = retry_config;
    }

    /// Return a reference to the current retry configuration.
    pub fn retry_config(&self) -> &RetryConfig {
        &self.retry_config
    }

    /// Build the chat completions URL for this endpoint.
    fn api_url(&self) -> String {
        format!(
            "{}/chat/completions?api-version=2024-05-01-preview",
            self.endpoint.trim_end_matches('/')
        )
    }
}

#[async_trait]
impl Llm for AzureAIClient {
    fn max_cost_micro_usd(&self, request: &adk_core::LlmRequest) -> Option<u64> {
        crate::pricing::PricingCatalog::standard().max_cost_micro_usd(
            Some("azure-ai"),
            self.name(),
            request,
            crate::pricing::request_output_cap(request),
        )
    }

    fn context_window(&self) -> Option<u64> {
        crate::pricing::PricingCatalog::standard().context_window(Some("azure-ai"), self.name())
    }

    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
        vec![adk_core::DataDestination::of_url("azure-ai", &self.endpoint)]
    }

    fn name(&self) -> &str {
        &self.model
    }

    #[tracing::instrument(
        name = "model.generate_content",
        skip_all,
        fields(
            model.name = %self.name(),
            stream = %stream,
            request.contents_count = %request.contents.len(),
            request.tools_count = %request.tools.len()
        )
    )]
    async fn generate_content(
        &self,
        mut request: LlmRequest,
        stream: bool,
    ) -> Result<LlmResponseStream, AdkError> {
        // Native items reach this provider only from the turns its own origin marks.
        adk_core::history::retain_replayable(
            &mut request.contents,
            &adk_core::history::ProviderOrigin::new("azure-ai", &self.model),
        );
        let usage_span =
            crate::telemetry::inference_span("azure-ai", &self.model, stream, &request);
        let api_url = self.api_url();
        let api_key = self.api_key.clone();
        let model = self.model.clone();
        let endpoint = self.endpoint.clone();
        let client = self.client.clone();
        let retry_config = self.retry_config.clone();

        let body = convert::build_request_body(
            &model,
            &request.contents,
            &request.tools,
            request.config.as_ref(),
            stream,
        )?;

        let response_stream = try_stream! {
            let response = execute_with_retry(&retry_config, is_retryable_model_error, || {
                let client = client.clone();
                let api_url = api_url.clone();
                let api_key = api_key.clone();
                let body = body.clone();
                let endpoint = endpoint.clone();
                async move {
                    let resp = client
                        .post(&api_url)
                        .header("api-key", &api_key)
                        .header("Content-Type", "application/json")
                        .json(&body)
                        .send()
                        .await
                        .map_err(|e| AdkError::new(
                            ErrorComponent::Model,
                            crate::http_timeouts::transport_category(&e),
                            "model.azure_ai.request",
                            format!("Azure AI error for endpoint={endpoint}: {e}"),
                        ).with_provider("azure-ai"))?;

                    if !resp.status().is_success() {
                        let status = resp.status();
                        let status_code = status.as_u16();
                        let retry_after = resp
                            .headers()
                            .get(reqwest::header::RETRY_AFTER)
                            .and_then(|value| value.to_str().ok())
                            .and_then(crate::retry::parse_retry_after);
                        let error_text = resp.text().await.unwrap_or_default();
                        let error = AdkError::new(
                            ErrorComponent::Model,
                            crate::retry::category_for_status_code(status_code),
                            "model.azure_ai.api_error",
                            format!(
                                "Azure AI error for endpoint={endpoint}, status={status}: {}",
                                adk_core::upstream_excerpt(&error_text)
                            ),
                        ).with_upstream_status(status_code).with_provider("azure-ai");
                        let error = crate::error_metadata::classify_quota(
                            error,
                            crate::error_metadata::body_reports_exhausted_quota(&error_text),
                        );
                        return Err(crate::retry::with_retry_after(
                            crate::error_metadata::from_body(error, &error_text),
                            retry_after,
                        ));
                    }

                    Ok(resp)
                }
            })
            .await?;

            if stream {
                let mut byte_stream = response.bytes_stream();
                let mut buffer = Vec::new();
                let mut finished = false;
                let mut terminal: Option<LlmResponse> = None;

                // Accumulate tool calls across SSE chunks
                let mut tool_call_accumulators: std::collections::HashMap<u32, (String, String, String)> =
                    std::collections::HashMap::new();

                while let Some(chunk_result) = byte_stream.next().await {
                    let chunk = chunk_result.map_err(|error| {
                        crate::stream_error::interrupted("azure-ai", INCOMPLETE_STREAM, &error)
                    })?;

                    buffer.extend_from_slice(&chunk);

                    while let Some(line) = crate::sse::take_line(&mut buffer)? {

                        if line.is_empty() || line == "data: [DONE]" {
                            continue;
                        }

                        if let Some(data) = line.strip_prefix("data: ") {
                            match serde_json::from_str::<Value>(data) {
                                Ok(chunk_json) => {
                                    if let Some(error) = chunk_json.get("error").filter(|error| !error.is_null()) {
                                        Err(crate::stream_error::reported("azure-ai", STREAM_ERROR, error))?;
                                    }
                                    // Accumulate tool call deltas
                                    accumulate_tool_calls(&chunk_json, &mut tool_call_accumulators);

                                    let mut llm_resp = convert::parse_sse_chunk(&chunk_json);
                                    if finished {
                                        if let Some(usage) = llm_resp.usage_metadata
                                            && let Some(response) = &mut terminal
                                        {
                                            response.usage_metadata = Some(usage);
                                        }
                                        continue;
                                    }
                                    // Tool deltas are incomplete until the finish event.
                                    if let Some(content) = &mut llm_resp.content {
                                        content.parts.retain(|part| !matches!(part, Part::FunctionCall { .. }));
                                    }

                                    if llm_resp.turn_complete {
                                        finished = true;
                                        // Emit accumulated tool calls if any
                                        if !tool_call_accumulators.is_empty() {
                                            let mut sorted: Vec<_> =
                                                tool_call_accumulators.drain().collect();
                                            sorted.sort_by_key(|(idx, _)| *idx);

                                            let calls = sorted
                                                .into_iter()
                                                .map(|(_, (id, name, args_str))| {
                                                    let args = crate::tool_args::streamed_tool_arguments(
                                                        "azure-ai",
                                                        &name,
                                                        &args_str,
                                                    );
                                                    Part::FunctionCall {
                                                        name,
                                                        args,
                                                        id: Some(id),
                                                        thought_signature: None,
                                                    }
                                                })
                                                .collect::<Vec<Part>>();

                                            let mut parts = llm_resp.content.take().map(|content| content.parts).unwrap_or_default();
                                            parts.extend(calls);

                                            llm_resp.content = Some(adk_core::Content {
                                                role: "model".to_string(),
                                                parts,
                                            });
                                            llm_resp.turn_complete = false;
                                        }
                                        // Usage may arrive after the finish event. Do not let the
                                        // runner stop polling before accounting and stream validation.
                                        terminal = Some(llm_resp);
                                    } else if llm_resp.content.is_some() || llm_resp.usage_metadata.is_some() {
                                        yield llm_resp;
                                    }
                                }
                                Err(error) => Err(crate::stream_error::undecodable("azure-ai", INVALID_CHUNK, &error))?,
                            }
                        }
                    }
                }
                if !finished || buffer.iter().any(|byte| !byte.is_ascii_whitespace()) {
                    Err(crate::stream_error::incomplete(
                        "azure-ai",
                        INCOMPLETE_STREAM,
                        "the response finished",
                    ))?;
                }
                if let Some(response) = terminal {
                    yield response;
                }
            } else {
                let response_text = response.text().await.map_err(|e| AdkError::new(
                    ErrorComponent::Model,
                    crate::http_timeouts::transport_category(&e),
                    "model.azure_ai.request",
                    format!("Azure AI response could not be read: {e}"),
                ).with_provider("azure-ai"))?;

                let response_json: Value = serde_json::from_str(&response_text)
                    .map_err(|e| AdkError::model(format!(
                        "Azure AI response parse failed: {}",
                        adk_core::json_error_summary(&e)
                    )))?;

                yield convert::parse_response(&response_json);
            }
        };

        Ok(crate::usage_tracking::with_priced_usage_tracking(
            Box::pin(response_stream),
            usage_span,
            "azure-ai",
            &self.model,
        ))
    }
}

/// Accumulate tool call argument deltas from an SSE chunk into the accumulator map.
///
/// Each tool call is identified by its index in the `tool_calls` array. The
/// accumulator stores `(id, name, arguments_string)` per index, appending
/// argument fragments as they arrive across multiple chunks.
fn accumulate_tool_calls(
    chunk: &Value,
    accumulators: &mut std::collections::HashMap<u32, (String, String, String)>,
) {
    let Some(tool_calls) = chunk
        .get("choices")
        .and_then(|c| c.get(0))
        .and_then(|choice| choice.get("delta"))
        .and_then(|delta| delta.get("tool_calls"))
        .and_then(|tc| tc.as_array())
    else {
        return;
    };

    for tc in tool_calls {
        let index = tc.get("index").and_then(|i| i.as_u64()).unwrap_or(0) as u32;
        let entry = accumulators.entry(index).or_insert_with(|| {
            let id = tc.get("id").and_then(|i| i.as_str()).unwrap_or("").to_string();
            (id, String::new(), String::new())
        });

        if let Some(id) = tc.get("id").and_then(|i| i.as_str())
            && !id.is_empty()
        {
            entry.0 = id.to_string();
        }

        if let Some(func) = tc.get("function") {
            if let Some(name) = func.get("name").and_then(|n| n.as_str())
                && !name.is_empty()
            {
                entry.1 = name.to_string();
            }
            if let Some(args) = func.get("arguments").and_then(|a| a.as_str()) {
                entry.2.push_str(args);
            }
        }
    }
}