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
use std::fmt;
use std::time::Duration;
/// EN: Case-insensitive HTTP headers retained for diagnostics and request construction.
/// 中文:用于诊断和构造请求的大小写不敏感 HTTP 头集合。
#[derive(Clone, Default, PartialEq, Eq)]
pub struct HeaderMap {
entries: Vec<(String, String)>,
}
impl HeaderMap {
/// EN: Creates an empty header map.
/// 中文:创建空的请求头集合。
pub fn new() -> Self {
Self {
entries: Vec::new(),
}
}
/// EN: Creates headers from name/value pairs.
/// 中文:通过名称和值的键值对创建请求头集合。
pub fn from_pairs<I, P>(pairs: I) -> Self
where
I: IntoIterator<Item = P>,
P: IntoHeaderPair,
{
let mut headers = Self::new();
for pair in pairs {
let (name, value) = pair.into_header_pair();
headers.insert(name, value);
}
headers
}
/// EN: Inserts or replaces a header value using ASCII case-insensitive header names.
/// 中文:使用 ASCII 大小写不敏感的头名称插入或替换请求头。
pub fn insert(&mut self, name: impl Into<String>, value: impl Into<String>) {
let name = name.into();
let value = value.into();
if let Some((_, existing)) = self
.entries
.iter_mut()
.find(|(existing, _)| existing.eq_ignore_ascii_case(&name))
{
*existing = value;
return;
}
self.entries.push((name, value));
}
/// EN: Returns a header value by ASCII case-insensitive name.
/// 中文:按 ASCII 大小写不敏感名称返回请求头值。
pub fn get(&self, name: &str) -> Option<&str> {
self.entries
.iter()
.find(|(existing, _)| existing.eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_str())
}
/// EN: Iterates over header names and values.
/// 中文:遍历请求头名称和值。
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.entries
.iter()
.map(|(name, value)| (name.as_str(), value.as_str()))
}
}
/// EN: Converts owned or borrowed header pairs into SDK header storage.
/// 中文:将拥有或借用的请求头键值对转换为 SDK 头存储。
pub trait IntoHeaderPair {
/// EN: Converts the pair into owned strings.
/// 中文:将键值对转换为拥有所有权的字符串。
fn into_header_pair(self) -> (String, String);
}
impl<K, V> IntoHeaderPair for (K, V)
where
K: ToString,
V: ToString,
{
fn into_header_pair(self) -> (String, String) {
(self.0.to_string(), self.1.to_string())
}
}
impl<K, V> IntoHeaderPair for &(K, V)
where
K: ToString,
V: ToString,
{
fn into_header_pair(self) -> (String, String) {
(self.0.to_string(), self.1.to_string())
}
}
impl<const N: usize> From<[(&str, &str); N]> for HeaderMap {
fn from(value: [(&str, &str); N]) -> Self {
Self::from_pairs(value)
}
}
impl fmt::Debug for HeaderMap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let redacted: Vec<(&str, &str)> = self
.entries
.iter()
.map(|(name, value)| {
let value = if is_sensitive_header(name) {
"<redacted>"
} else {
value.as_str()
};
(name.as_str(), value)
})
.collect();
f.debug_list().entries(redacted).finish()
}
}
fn is_sensitive_header(name: &str) -> bool {
name.eq_ignore_ascii_case("authorization")
|| name.eq_ignore_ascii_case("openai-organization")
|| name.eq_ignore_ascii_case("openai-project")
|| name.eq_ignore_ascii_case("openai-webhook-secret")
}
/// EN: OpenAI request id returned by response headers.
/// 中文:响应头返回的 OpenAI 请求 ID。
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct RequestId(String);
impl RequestId {
/// EN: Creates a request id wrapper.
/// 中文:创建请求 ID 包装类型。
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
/// EN: Returns the request id as a string slice.
/// 中文:以字符串切片返回请求 ID。
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for RequestId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("RequestId").field(&self.0).finish()
}
}
impl fmt::Display for RequestId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
/// EN: Structured OpenAI error body fields.
/// 中文:结构化的 OpenAI 错误响应体字段。
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ApiErrorBody {
/// EN: Human-readable OpenAI error message.
/// 中文:OpenAI 返回的可读错误消息。
pub message: String,
/// EN: OpenAI error type, when present.
/// 中文:OpenAI 错误类型,如响应中存在。
#[serde(default)]
pub r#type: Option<String>,
/// EN: OpenAI error code, when present.
/// 中文:OpenAI 错误代码,如响应中存在。
#[serde(default)]
pub code: Option<String>,
/// EN: Request parameter associated with the error, when present.
/// 中文:与错误关联的请求参数,如响应中存在。
#[serde(default)]
pub param: Option<String>,
}
/// EN: Alias for the structured OpenAI API error body.
/// 中文:结构化 OpenAI API 错误响应体的别名。
pub type OpenAiError = ApiErrorBody;
/// EN: Error returned by OpenAI with HTTP and diagnostic context.
/// 中文:包含 HTTP 与诊断上下文的 OpenAI 错误。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ApiError {
/// EN: HTTP response status.
/// 中文:HTTP 响应状态码。
pub status: u16,
/// EN: OpenAI request id, when returned.
/// 中文:OpenAI 请求 ID,如响应中存在。
pub request_id: Option<RequestId>,
/// EN: Redacted diagnostic response headers.
/// 中文:已脱敏的诊断响应头。
pub headers: HeaderMap,
/// EN: Structured OpenAI error fields.
/// 中文:结构化 OpenAI 错误字段。
pub error: ApiErrorBody,
/// EN: Safe raw body copy, when retained.
/// 中文:在安全时保留的原始响应体副本。
pub raw_body: Option<String>,
}
/// EN: Retry exhaustion details.
/// 中文:重试耗尽时的详细信息。
#[derive(Debug)]
#[non_exhaustive]
pub struct RetryExhausted {
/// EN: Number of attempts made.
/// 中文:已经执行的尝试次数。
pub attempts: usize,
/// EN: Last failure observed by the retry loop.
/// 中文:重试循环观察到的最后一次失败。
pub last_error: Box<LingerError>,
}
/// EN: Top-level SDK error categories.
/// 中文:SDK 顶层错误类别。
#[derive(Debug)]
#[non_exhaustive]
pub enum ErrorKind {
/// EN: HTTP transport failed before a complete response was available.
/// 中文:在完整响应可用前 HTTP 传输失败。
Transport { message: String },
/// EN: A configured timeout elapsed.
/// 中文:配置的超时时间已耗尽。
Timeout { message: String },
/// EN: Request serialization or response deserialization failed.
/// 中文:请求序列化或响应反序列化失败。
Serialization { message: String },
/// EN: Incremental stream parsing failed.
/// 中文:增量流解析失败。
Streaming { message: String },
/// EN: Retry policy exhausted all configured attempts.
/// 中文:重试策略耗尽了所有配置的尝试次数。
RetryExhausted(RetryExhausted),
/// EN: OpenAI returned a non-successful API response.
/// 中文:OpenAI 返回了非成功的 API 响应。
Api(ApiError),
/// EN: SDK configuration or builder input is invalid.
/// 中文:SDK 配置或构建器输入无效。
InvalidConfig { message: String },
}
/// EN: Structured error returned by SDK operations.
/// 中文:SDK 操作返回的结构化错误。
pub struct LingerError {
kind: Box<ErrorKind>,
}
impl LingerError {
/// EN: Creates a transport error.
/// 中文:创建传输错误。
pub fn transport(message: impl Into<String>) -> Self {
Self {
kind: Box::new(ErrorKind::Transport {
message: message.into(),
}),
}
}
/// EN: Creates a timeout error.
/// 中文:创建超时错误。
pub fn timeout(message: impl Into<String>) -> Self {
Self {
kind: Box::new(ErrorKind::Timeout {
message: message.into(),
}),
}
}
/// EN: Creates a serialization or deserialization error.
/// 中文:创建序列化或反序列化错误。
pub fn serialization(message: impl Into<String>) -> Self {
Self {
kind: Box::new(ErrorKind::Serialization {
message: message.into(),
}),
}
}
/// EN: Creates a streaming error.
/// 中文:创建流式解析错误。
pub fn streaming(message: impl Into<String>) -> Self {
Self {
kind: Box::new(ErrorKind::Streaming {
message: message.into(),
}),
}
}
/// EN: Creates an invalid configuration error.
/// 中文:创建无效配置错误。
pub fn invalid_config(message: impl Into<String>) -> Self {
Self {
kind: Box::new(ErrorKind::InvalidConfig {
message: message.into(),
}),
}
}
/// EN: Creates an API error from response parts.
/// 中文:通过响应组成部分创建 API 错误。
pub fn api(
status: u16,
headers: HeaderMap,
request_id: Option<RequestId>,
error: ApiErrorBody,
) -> Self {
Self {
kind: Box::new(ErrorKind::Api(ApiError {
status,
request_id,
headers,
error,
raw_body: None,
})),
}
}
/// EN: Creates a retry exhaustion error.
/// 中文:创建重试耗尽错误。
pub fn retry_exhausted(attempts: usize, last_error: LingerError) -> Self {
Self {
kind: Box::new(ErrorKind::RetryExhausted(RetryExhausted {
attempts,
last_error: Box::new(last_error),
})),
}
}
/// EN: Returns the structured error kind.
/// 中文:返回结构化错误类别。
pub fn kind(&self) -> &ErrorKind {
self.kind.as_ref()
}
}
impl fmt::Debug for LingerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LingerError")
.field("kind", &self.kind)
.finish()
}
}
impl fmt::Display for LingerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind.as_ref() {
ErrorKind::Transport { message } => write!(f, "transport error: {message}"),
ErrorKind::Timeout { message } => write!(f, "timeout error: {message}"),
ErrorKind::Serialization { message } => write!(f, "serialization error: {message}"),
ErrorKind::Streaming { message } => write!(f, "streaming error: {message}"),
ErrorKind::RetryExhausted(details) => {
write!(f, "retry exhausted after {} attempts", details.attempts)
}
ErrorKind::Api(error) => write!(
f,
"OpenAI API error {}: {}",
error.status, error.error.message
),
ErrorKind::InvalidConfig { message } => {
write!(f, "invalid SDK configuration: {message}")
}
}
}
}
impl std::error::Error for LingerError {}
impl From<serde_json::Error> for LingerError {
fn from(value: serde_json::Error) -> Self {
Self::serialization(value.to_string())
}
}
pub(crate) fn request_id_from_headers(headers: &HeaderMap) -> Option<RequestId> {
headers
.get("x-request-id")
.or_else(|| headers.get("openai-request-id"))
.map(RequestId::new)
}
pub(crate) fn parse_retry_after_seconds(value: &str) -> Option<Duration> {
let seconds = value.trim().parse::<u64>().ok()?;
Some(Duration::from_secs(seconds))
}
pub(crate) fn parse_api_error(status: u16, headers: HeaderMap, body: &[u8]) -> LingerError {
#[derive(serde::Deserialize)]
struct Wire {
error: ApiErrorBody,
}
let request_id = request_id_from_headers(&headers);
match serde_json::from_slice::<Wire>(body) {
Ok(parsed) => LingerError::api(status, headers, request_id, parsed.error),
Err(_) => LingerError::api(
status,
headers,
request_id,
ApiErrorBody {
message: format!(
"OpenAI API returned HTTP status {status} with an unparseable error body"
),
r#type: None,
code: None,
param: None,
},
),
}
}