cetai 0.1.1

Typed prompt! expressions and #[ai] functions for natural-language tasks over DeepSeek.
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
//! DeepSeek wire types and HTTP client with the two-layer retry model
//! (PLAN §6, §7.2): each logical model request owns a full HTTP retry budget.
//! Raw I/O goes through the replaceable [`Transport`] layer; the default
//! implementation below uses reqwest + tokio.

use std::sync::Arc;
#[cfg(feature = "reqwest-transport")]
use std::sync::LazyLock;
use std::time::Duration;

#[cfg(feature = "reqwest-transport")]
use reqwest::header::{HeaderMap, CONTENT_TYPE, RETRY_AFTER};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::config::{AiConfig, Thinking};
use crate::error::{content_fingerprint, summarize, AiError, Result};
#[cfg(feature = "reqwest-transport")]
use crate::transport::{BoxFuture, TransportError};
use crate::transport::{Transport, TransportRequest, TransportResponse};
use crate::usage::UsageStats;

/// Shared HTTP client. Per-attempt timeouts are set on each request.
#[cfg(feature = "reqwest-transport")]
static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);

/// Default [`Transport`] implementation backed by a shared reqwest client and
/// tokio timers. Selected automatically when the `reqwest-transport` feature
/// is enabled.
#[cfg(feature = "reqwest-transport")]
pub(crate) struct ReqwestTransport;

#[cfg(feature = "reqwest-transport")]
impl Transport for ReqwestTransport {
    fn name(&self) -> &'static str {
        "reqwest"
    }

    fn send(
        &self,
        request: TransportRequest,
    ) -> BoxFuture<'static, std::result::Result<TransportResponse, TransportError>> {
        Box::pin(async move {
            let response = CLIENT
                .post(&request.url)
                .bearer_auth(&request.bearer_token)
                .header(CONTENT_TYPE, "application/json")
                .body(request.body)
                .timeout(request.timeout)
                .send()
                .await;

            let response = response.map_err(|err| TransportError {
                // Connection and per-attempt timeout failures are transient.
                retryable: err.is_timeout() || err.is_connect(),
                summary: summarize(&redact_transport_error(&err), 200),
            })?;

            let status = response.status().as_u16();
            let request_id = extract_request_id(response.headers());
            let retry_after = extract_retry_after(response.headers());
            // A body-read failure degrades to an empty body, as before.
            let body = response.bytes().await.unwrap_or_default().to_vec();

            Ok(TransportResponse {
                status,
                retry_after,
                request_id,
                body,
            })
        })
    }

    fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
        Box::pin(async move {
            tokio::time::sleep(duration).await;
        })
    }
}

/// One chat message.
#[derive(Serialize, Clone)]
pub(crate) struct Message {
    pub role: &'static str,
    pub content: String,
}

impl Message {
    pub(crate) fn system(content: String) -> Self {
        Message {
            role: "system",
            content,
        }
    }

    pub(crate) fn user(content: String) -> Self {
        Message {
            role: "user",
            content,
        }
    }

    pub(crate) fn assistant(content: String) -> Self {
        Message {
            role: "assistant",
            content,
        }
    }
}

#[derive(Serialize)]
pub(crate) struct ResponseFormat {
    pub r#type: &'static str,
}

#[derive(Serialize)]
pub(crate) struct ThinkingSpec {
    pub r#type: &'static str,
}

/// Non-streaming Chat Completions request body.
#[derive(Serialize)]
pub(crate) struct ChatRequest {
    pub model: String,
    pub messages: Vec<Message>,
    pub response_format: ResponseFormat,
    pub max_tokens: u32,
    pub temperature: f32,
    pub stream: bool,
    pub thinking: ThinkingSpec,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<&'static str>,
}

impl ChatRequest {
    pub(crate) fn build(
        config: &AiConfig,
        messages: Vec<Message>,
        thinking: Thinking,
        max_tokens: u32,
    ) -> Self {
        ChatRequest {
            model: config.model.clone(),
            messages,
            response_format: ResponseFormat {
                r#type: "json_object",
            },
            max_tokens,
            temperature: config.temperature,
            stream: false,
            thinking: ThinkingSpec {
                r#type: thinking.wire_type(),
            },
            reasoning_effort: thinking.reasoning_effort(),
        }
    }
}

/// Token usage, including DeepSeek context-cache counters.
#[derive(Deserialize, Default)]
pub(crate) struct Usage {
    pub prompt_tokens: Option<u64>,
    pub completion_tokens: Option<u64>,
    pub prompt_cache_hit_tokens: Option<u64>,
    pub prompt_cache_miss_tokens: Option<u64>,
}

#[derive(Deserialize)]
pub(crate) struct ResponseMessage {
    pub content: Option<String>,
    pub tool_calls: Option<Value>,
}

#[derive(Deserialize)]
pub(crate) struct Choice {
    pub message: Option<ResponseMessage>,
    pub finish_reason: Option<String>,
}

#[derive(Deserialize)]
pub(crate) struct ChatResponse {
    pub choices: Option<Vec<Choice>>,
    pub usage: Option<Usage>,
}

/// A parsed, successful logical response plus per-request metadata.
pub(crate) struct LogicalResponse {
    pub content: Option<String>,
    pub finish_reason: Option<String>,
    pub tool_calls_present: bool,
    pub usage: Option<Usage>,
    pub request_id: Option<String>,
    pub http_retries_used: u32,
}

#[derive(Deserialize)]
struct ApiErrorBody {
    error: Option<ApiErrorDetail>,
}

#[derive(Deserialize)]
struct ApiErrorDetail {
    message: Option<String>,
}

enum AttemptOutcome {
    Success(LogicalResponse),
    Retryable {
        summary: String,
        status: Option<u16>,
        request_id: Option<String>,
        retry_after: Option<Duration>,
    },
    Fatal(AiError),
}

/// Sends one logical model request, consuming up to `http_retries` extra
/// physical attempts on transient failures. The serialized body bytes are
/// reused byte-identically across attempts. All I/O and backoff sleeps go
/// through the transport installed in [`AiConfig::transport`].
pub(crate) async fn send(
    config: &AiConfig,
    base_url: &str,
    request: &ChatRequest,
    http_retries: u32,
    stats: &mut UsageStats,
) -> Result<LogicalResponse> {
    let transport = config
        .transport
        .clone()
        .ok_or_else(|| AiError::InvalidConfig("no HTTP transport configured".to_string()))?;
    let body = serde_json::to_vec(request)
        .map_err(|err| AiError::InvalidConfig(format!("failed to encode request: {err}")))?;
    let url = format!("{base_url}/chat/completions");

    let mut retries_used = 0u32;
    loop {
        match attempt(&transport, config, &url, &body).await {
            AttemptOutcome::Success(mut response) => {
                response.http_retries_used = retries_used;
                stats.http_retries += retries_used;
                if let Some(usage) = &response.usage {
                    stats.add_usage(usage);
                }
                if response.request_id.is_some() {
                    stats.request_id.clone_from(&response.request_id);
                }
                return Ok(response);
            }
            AttemptOutcome::Retryable {
                summary,
                status,
                request_id,
                retry_after,
            } => {
                if retries_used >= http_retries {
                    return Err(match status {
                        Some(status) => AiError::Api {
                            status: Some(status),
                            request_id,
                            summary,
                        },
                        None => AiError::Http {
                            attempts: retries_used + 1,
                            summary,
                        },
                    });
                }
                retries_used += 1;
                transport.sleep(backoff(retries_used, retry_after)).await;
            }
            AttemptOutcome::Fatal(err) => return Err(err),
        }
    }
}

async fn attempt(
    transport: &Arc<dyn Transport>,
    config: &AiConfig,
    url: &str,
    body: &[u8],
) -> AttemptOutcome {
    use secrecy::ExposeSecret;

    let result = transport
        .send(TransportRequest {
            url: url.to_string(),
            bearer_token: config.api_key.expose_secret().to_string(),
            body: body.to_vec(),
            timeout: Duration::from_secs(config.timeout_secs),
        })
        .await;

    let response = match result {
        Ok(response) => response,
        Err(err) if err.retryable => {
            return AttemptOutcome::Retryable {
                summary: err.summary,
                status: None,
                request_id: None,
                retry_after: None,
            };
        }
        Err(err) => {
            return AttemptOutcome::Fatal(AiError::Http {
                attempts: 1,
                summary: err.summary,
            });
        }
    };

    let TransportResponse {
        status,
        retry_after,
        request_id,
        body,
    } = response;
    let body_text = String::from_utf8_lossy(&body);

    if !(200..300).contains(&status) {
        let detail = serde_json::from_str::<ApiErrorBody>(&body_text)
            .ok()
            .and_then(|parsed| parsed.error)
            .and_then(|error| error.message)
            .map(|message| summarize(&message, 200));
        let summary = match detail {
            Some(detail) => format!("HTTP {status}: {detail}"),
            None => format!("HTTP {status}"),
        };
        return match status {
            429 | 500 | 503 => AttemptOutcome::Retryable {
                summary,
                status: Some(status),
                request_id,
                retry_after,
            },
            // 400, 401, 402, 422 and everything else: not retried.
            _ => AttemptOutcome::Fatal(AiError::Api {
                status: Some(status),
                request_id,
                summary,
            }),
        };
    }

    let parsed = match serde_json::from_str::<ChatResponse>(&body_text) {
        Ok(parsed) => parsed,
        Err(err) => {
            return AttemptOutcome::Fatal(AiError::Api {
                status: Some(status),
                request_id,
                summary: format!(
                    "malformed success response ({} bytes, hash {:#x}): {}",
                    body_text.len(),
                    content_fingerprint(&body_text),
                    summarize(&err.to_string(), 200)
                ),
            });
        }
    };

    let Some(choice) = parsed.choices.and_then(|mut choices| {
        if choices.is_empty() {
            None
        } else {
            Some(choices.remove(0))
        }
    }) else {
        return AttemptOutcome::Fatal(AiError::Api {
            status: Some(status),
            request_id,
            summary: "response contains no choices".to_string(),
        });
    };

    // `insufficient_system_resource` joins the HTTP-class retry budget, not
    // the model-repair budget (PLAN §7.2).
    if choice.finish_reason.as_deref() == Some("insufficient_system_resource") {
        return AttemptOutcome::Retryable {
            summary: "finish_reason: insufficient_system_resource".to_string(),
            status: Some(status),
            request_id,
            retry_after: None,
        };
    }

    let message = choice.message.unwrap_or(ResponseMessage {
        content: None,
        tool_calls: None,
    });
    let tool_calls_present = message
        .tool_calls
        .as_ref()
        .is_some_and(|calls| !calls.is_null());

    AttemptOutcome::Success(LogicalResponse {
        content: message.content,
        finish_reason: choice.finish_reason,
        tool_calls_present,
        usage: parsed.usage,
        request_id,
        http_retries_used: 0,
    })
}

#[cfg(feature = "reqwest-transport")]
fn extract_request_id(headers: &HeaderMap) -> Option<String> {
    headers
        .get("x-request-id")
        .and_then(|value| value.to_str().ok())
        .map(str::to_string)
}

#[cfg(feature = "reqwest-transport")]
fn extract_retry_after(headers: &HeaderMap) -> Option<Duration> {
    let value = headers.get(RETRY_AFTER)?.to_str().ok()?.trim().to_string();
    // Only the numeric-seconds form is honored; HTTP-date parsing is out of
    // scope for the MVP.
    value.parse::<u64>().ok().map(Duration::from_secs)
}

/// Exponential backoff with jitter: 500ms * 2^(n-1), capped at 30s, scaled by
/// a random factor in [0.5, 1.0). A valid `Retry-After` wins for 429.
fn backoff(retry_number: u32, retry_after: Option<Duration>) -> Duration {
    if let Some(retry_after) = retry_after {
        return retry_after;
    }
    let base_ms = 500u64.saturating_mul(1u64 << retry_number.saturating_sub(1).min(6));
    let capped = base_ms.min(30_000);
    let jitter = 0.5 + fastrand::f64() * 0.5;
    Duration::from_millis((capped as f64 * jitter) as u64)
}

#[cfg(feature = "reqwest-transport")]
fn redact_transport_error(err: &reqwest::Error) -> String {
    // reqwest errors may embed URLs; strip the text after the first " for "
    // separator so summaries stay short and free of request details.
    let text = err.to_string();
    text.split(" for ").next().unwrap_or(&text).to_string()
}