Skip to main content

adk_model/openai/
azure.rs

1//! Azure deployment routing over ADK's shared Chat Completions codec and stream parser.
2use super::{AzureConfig, OpenAIReasoningEffort, OpenAiSchemaAdapter};
3use crate::{
4    openai_compatible::{ErrorCodes, OpenAICompatible, OpenAICompatibleConfig},
5    retry::RetryConfig,
6};
7use adk_core::{AdkError, Llm, LlmRequest, LlmResponseStream, SchemaAdapter};
8use async_trait::async_trait;
9use std::sync::Arc;
10
11/// The codes the dedicated Azure client reported before it shared the compatible transport.
12const ERROR_CODES: ErrorCodes = ErrorCodes {
13    request: "model.azure_openai.request",
14    api_error: "model.azure_openai.api_error",
15    parse: "model.azure_openai.parse",
16    incomplete_stream: "model.azure_openai.incomplete_stream",
17    stream_error: "model.azure_openai.stream_error",
18    status: &[
19        (401, "model.azure_openai.unauthorized"),
20        (404, "model.azure_openai.not_found"),
21        (408, "model.azure_openai.timeout"),
22        (429, "model.azure_openai.rate_limited"),
23        (500, "model.azure_openai.unavailable"),
24        (502, "model.azure_openai.unavailable"),
25        (503, "model.azure_openai.unavailable"),
26        (504, "model.azure_openai.unavailable"),
27        (529, "model.azure_openai.overloaded"),
28    ],
29    quota_exhausted: "model.azure_openai.quota_exhausted",
30};
31
32/// Azure deployment client with API-key authentication and streaming support.
33pub struct AzureOpenAIClient {
34    inner: OpenAICompatible,
35}
36
37impl AzureOpenAIClient {
38    /// Construct a client from explicit deployment routing and credentials.
39    ///
40    /// # Errors
41    ///
42    /// Returns an error when `api_base` is not an absolute URL or `api_key` cannot be
43    /// sent as an HTTP header value.
44    ///
45    /// # Example
46    ///
47    /// ```
48    /// use adk_model::openai::{AzureConfig, AzureOpenAIClient};
49    ///
50    /// let config = AzureConfig::new(
51    ///     "azure-key",
52    ///     "https://my-resource.openai.azure.com",
53    ///     "2024-12-01-preview",
54    ///     "gpt-4o",
55    /// );
56    /// let client = AzureOpenAIClient::new(config)?;
57    /// # Ok::<(), adk_core::AdkError>(())
58    /// ```
59    pub fn new(config: AzureConfig) -> Result<Self, AdkError> {
60        let mut url = reqwest::Url::parse(&config.api_base)
61            .map_err(|_| AdkError::model("invalid Azure endpoint"))?;
62        url.path_segments_mut()
63            .map_err(|_| AdkError::model("invalid Azure endpoint"))?
64            .pop_if_empty()
65            .extend(["openai", "deployments", &config.deployment_id, "chat", "completions"]);
66        url.query_pairs_mut().append_pair("api-version", &config.api_version);
67        let mut key = reqwest::header::HeaderValue::from_str(&config.api_key)
68            .map_err(|_| AdkError::model("invalid Azure API key"))?;
69        key.set_sensitive(true);
70        let inner = OpenAICompatible::new(
71            OpenAICompatibleConfig::new("", config.deployment_id)
72                .with_provider_name("azure-openai"),
73        )?
74        .with_completion_url(url.to_string())
75        .with_error_codes(ERROR_CODES)
76        .with_request_adapter(Arc::new(move |_, headers| {
77            headers.remove(reqwest::header::AUTHORIZATION);
78            headers.insert("api-key", key.clone());
79            Ok(())
80        }));
81        Ok(Self { inner })
82    }
83
84    /// Set the deployment's supported reasoning effort.
85    ///
86    /// # Example
87    ///
88    /// ```
89    /// use adk_model::openai::{AzureConfig, AzureOpenAIClient, OpenAIReasoningEffort};
90    ///
91    /// let config = AzureConfig::new(
92    ///     "azure-key",
93    ///     "https://my-resource.openai.azure.com",
94    ///     "2024-12-01-preview",
95    ///     "o4-mini",
96    /// );
97    /// let client = AzureOpenAIClient::new(config)?
98    ///     .with_reasoning_effort(Some(OpenAIReasoningEffort::Low));
99    /// # Ok::<(), adk_core::AdkError>(())
100    /// ```
101    #[must_use]
102    pub fn with_reasoning_effort(mut self, effort: Option<OpenAIReasoningEffort>) -> Self {
103        self.inner = self.inner.with_reasoning_effort(effort);
104        self
105    }
106
107    /// Set the retry policy while constructing the client.
108    #[must_use]
109    pub fn with_retry_config(mut self, config: RetryConfig) -> Self {
110        self.inner.set_retry_config(config);
111        self
112    }
113
114    /// Replace the retry policy.
115    pub fn set_retry_config(&mut self, config: RetryConfig) {
116        self.inner.set_retry_config(config);
117    }
118
119    /// Return the configured retry policy.
120    pub fn retry_config(&self) -> &RetryConfig {
121        self.inner.retry_config()
122    }
123
124    /// Sets the connect and idle timeouts of the HTTP transport, so a stalled stream fails
125    /// instead of holding the run.
126    ///
127    /// See [`HttpTimeouts`](crate::HttpTimeouts) for the defaults.
128    ///
129    /// # Example
130    ///
131    /// ```
132    /// use std::time::Duration;
133    ///
134    /// use adk_model::openai::{AzureConfig, AzureOpenAIClient};
135    /// use adk_model::HttpTimeouts;
136    ///
137    /// let config = AzureConfig::new(
138    ///     "azure-key",
139    ///     "https://my-resource.openai.azure.com",
140    ///     "2024-12-01-preview",
141    ///     "gpt-4o",
142    /// );
143    /// let client = AzureOpenAIClient::new(config)?
144    ///     .with_timeouts(HttpTimeouts::new(Duration::from_secs(10), Duration::from_secs(120)))?;
145    /// # let _ = client;
146    /// # Ok::<(), adk_core::AdkError>(())
147    /// ```
148    ///
149    /// # Errors
150    ///
151    /// Returns an `Internal` error with code `model.openai.http_client_init` when the HTTP
152    /// client cannot be built.
153    pub fn with_timeouts(mut self, timeouts: crate::HttpTimeouts) -> Result<Self, AdkError> {
154        self.inner = self.inner.with_timeouts(timeouts)?;
155        Ok(self)
156    }
157}
158
159#[async_trait]
160impl Llm for AzureOpenAIClient {
161    fn max_cost_micro_usd(&self, request: &adk_core::LlmRequest) -> Option<u64> {
162        self.inner.max_cost_micro_usd(request)
163    }
164
165    fn context_window(&self) -> Option<u64> {
166        self.inner.context_window()
167    }
168
169    fn data_locality(&self) -> adk_core::DataLocality {
170        self.inner.data_locality()
171    }
172
173    // The deployment URL on the configured resource, such as `my-resource.openai.azure.com`.
174    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
175        self.inner.data_destinations()
176    }
177
178    fn name(&self) -> &str {
179        self.inner.name()
180    }
181
182    fn schema_adapter(&self) -> &dyn SchemaAdapter {
183        static ADAPTER: OpenAiSchemaAdapter = OpenAiSchemaAdapter;
184        &ADAPTER
185    }
186
187    async fn generate_content(
188        &self,
189        request: LlmRequest,
190        stream: bool,
191    ) -> Result<LlmResponseStream, AdkError> {
192        self.inner.generate_content(request, stream).await
193    }
194}