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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
use std::fmt;
use serde::{Deserialize, Serialize, Serializer};
use super::request::{FinishReason, ToolCall};
#[derive(Debug, Deserialize, Clone, Default, PartialEq, Serialize)]
pub struct ErrResponse {
pub error: Err,
}
#[derive(Debug, Deserialize, Clone, Default, PartialEq, Serialize)]
pub struct Err {
pub message: String,
pub r#type: String,
pub param: String,
pub code: String,
}
#[derive(Debug, Deserialize, Clone, Default, PartialEq, Serialize)]
pub struct Response {
/// A unique identifier for the chat completion.
pub id: String,
/// A list of chat completion choices. Can be more than one if n is greater than 1.
pub choices: Vec<Choice>,
/// The Unix timestamp (in seconds) of when the chat completion was created.
pub created: u64,
/// The model used for the chat completion.
pub model: String,
/// The service tier used for processing the request.
/// This field is only included if the service_tier parameter is specified in the request.
#[serde(skip_serializing_if = "Option::is_none")]
pub service_tier: Option<ServiceTier>,
/// This fingerprint represents the backend configuration that the model runs with.
/// Can be used in conjunction with the seed request parameter to understand when backend changes have been
/// made that might impact determinism.
pub system_fingerprint: Option<String>,
/// The object type, which is always chat.completion
pub object: String,
/// Usage statistics for the completion request.
pub usage: Usage,
}
#[derive(Debug, Clone)]
pub struct ResponseBuilder {
inner: Response,
}
impl Default for ResponseBuilder {
fn default() -> Self {
Self::new()
}
}
impl ResponseBuilder {
pub fn new() -> Self {
Self {
inner: Response {
object: "chat.completion".to_string(),
..Default::default()
},
}
}
pub fn build(self) -> Response {
self.inner
}
pub fn push_assistant_message(mut self, message: impl Into<String>) -> Self {
self.inner.choices.push(Choice {
index: self.inner.choices.len(),
message: Message {
role: Role::Assistant,
content: Some(message.into()),
..Default::default()
},
finish_reason: None,
logprobs: None,
});
self
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.inner.id = id.into();
self
}
pub fn model(mut self, model: impl Into<String>) -> Self {
self.inner.model = model.into();
self
}
}
/// Service tier used for processing the request.
///
/// - `auto`: The system will utilize scale tier credits until they are exhausted (if Project is Scale tier enabled), otherwise uses default tier.
/// - `default`: The request will be processed using the default service tier with a lower uptime SLA and no latency guarantee.
/// - `flex`: The request will be processed with the Flex Processing service tier.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ServiceTier {
Auto,
Default,
Flex,
}
/// Usage statistics for the completion request.
#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq)]
pub struct Usage {
/// Number of tokens in the generated completion.
pub completion_tokens: u32,
/// Number of tokens in the prompt.
pub prompt_tokens: u32,
/// Total number of tokens used in the request (prompt + completion).
pub total_tokens: u32,
/// Breakdown of tokens used in a completion.
#[serde(skip_serializing_if = "Option::is_none")]
pub completion_tokens_details: Option<CompletionTokensDetails>,
/// Breakdown of tokens used in the prompt.
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_tokens_details: Option<PromptTokensDetails>,
}
/// Breakdown of tokens used in a completion.
#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq)]
pub struct CompletionTokensDetails {
/// When using Predicted Outputs, the number of tokens in the prediction that appeared in the completion.
#[serde(skip_serializing_if = "Option::is_none")]
pub accepted_prediction_tokens: Option<u32>,
/// Audio input tokens generated by the model.
#[serde(skip_serializing_if = "Option::is_none")]
pub audio_tokens: Option<u32>,
/// Tokens generated by the model for reasoning.
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning_tokens: Option<u32>,
/// When using Predicted Outputs, the number of tokens in the prediction that did not appear in the completion.
/// However, like reasoning tokens, these tokens are still counted in the total completion tokens for purposes
/// of billing, output, and context window limits.
#[serde(skip_serializing_if = "Option::is_none")]
pub rejected_prediction_tokens: Option<u32>,
}
/// Breakdown of tokens used in the prompt.
#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq)]
pub struct PromptTokensDetails {
/// Audio input tokens present in the prompt.
#[serde(skip_serializing_if = "Option::is_none")]
pub audio_tokens: Option<u32>,
/// Cached tokens present in the prompt.
#[serde(skip_serializing_if = "Option::is_none")]
pub cached_tokens: Option<u32>,
}
#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq)]
pub struct Message {
/// The contents of the message.
pub content: Option<String>,
/// OpenRouter-style gateways may send this alongside `content`; official OpenAI Chat Completions
/// message objects do not document this field.
#[serde(
default,
skip_serializing_if = "Option::is_none",
alias = "reasoning_content",
alias = "thinking"
)]
pub reasoning: Option<String>,
/// The tool calls generated by the model, such as function calls.
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_calls: Option<Vec<ToolCall>>,
/// The role of the author of this message.
pub role: Role,
/// The refusal message generated by the model.
#[serde(skip_serializing_if = "Option::is_none")]
pub refusal: Option<String>,
/// Annotations for the message, when applicable, as when using the web search tool.
#[serde(skip_serializing_if = "Option::is_none")]
pub annotations: Option<Vec<Annotation>>,
/// If the audio output modality is requested, this object contains data about the audio response from the model.
#[serde(skip_serializing_if = "Option::is_none")]
pub audio: Option<ChatCompletionAudio>,
}
/// The role of the author of a message.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Role {
/// Developer-provided instructions (replaces system in some contexts).
Developer,
/// System instructions.
System,
#[default]
/// User input.
User,
/// Assistant response.
Assistant,
/// Tool result.
Tool,
/// Deprecated: Function result.
#[deprecated(note = "Use Tool instead")]
Function,
}
impl fmt::Display for Role {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Role::Developer => write!(f, "developer"),
Role::System => write!(f, "system"),
Role::User => write!(f, "user"),
Role::Assistant => write!(f, "assistant"),
Role::Tool => write!(f, "tool"),
#[allow(deprecated)]
Role::Function => write!(f, "function"),
}
}
}
impl Role {
pub fn as_str(&self) -> &'static str {
match *self {
Role::Developer => "developer",
Role::System => "system",
Role::User => "user",
Role::Assistant => "assistant",
Role::Tool => "tool",
#[allow(deprecated)]
Role::Function => "function",
}
}
}
#[derive(Debug, Deserialize, Default, Serialize, Clone, PartialEq)]
pub struct Choice {
pub index: usize,
pub message: Message,
/// The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,
/// `length` if the maximum number of tokens specified in the request was reached,
/// `content_filter` if content was omitted due to a flag from our content filters,
/// `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.
pub finish_reason: Option<FinishReason>,
/// Log probability information for the choice.
pub logprobs: Option<Logprobs>,
}
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
pub struct Logprobs {
/// A list of message content tokens with log probability information.
#[serde(skip_serializing_if = "Option::is_none")]
pub content: Option<Vec<LogprobContent>>,
/// A list of message refusal tokens with log probability information.
#[serde(skip_serializing_if = "Option::is_none")]
pub refusal: Option<Vec<LogprobContent>>,
}
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
pub struct LogprobContent {
/// The token.
pub token: String,
/// The log probability of this token, if it is within the top 20 most likely tokens.
/// Otherwise, the value -9999.0 is used to signify that the token is very unlikely.
pub logprob: f64,
/// A list of integers representing the UTF-8 bytes representation of the token.
/// Useful in instances where characters are represented by multiple tokens and their
/// byte representations must be combined to generate the correct text representation.
/// Can be null if there is no bytes representation for the token.
#[serde(skip_serializing_if = "Option::is_none")]
pub bytes: Option<Vec<u8>>,
/// List of the most likely tokens and their log probability, at this token position.
/// In rare cases, there may be fewer than the number of requested top_logprobs returned.
#[serde(skip_serializing_if = "Option::is_none")]
pub top_logprobs: Option<Vec<TopLogprobs>>,
}
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
pub struct TopLogprobs {
/// The token.
pub token: String,
/// The log probability of this token, if it is within the top 20 most likely tokens.
/// Otherwise, the value -9999.0 is used to signify that the token is very unlikely.
pub logprob: f64,
/// A list of integers representing the UTF-8 bytes representation of the token.
/// Useful in instances where characters are represented by multiple tokens and their
/// byte representations must be combined to generate the correct text representation.
/// Can be null if there is no bytes representation for the token.
#[serde(skip_serializing_if = "Option::is_none")]
pub bytes: Option<Vec<u8>>,
}
/// Annotation for a message, such as a URL citation when using web search.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct Annotation {
/// The type of the annotation. Currently, only 'url_citation' is supported.
#[serde(rename = "type")]
pub annotation_type: String,
/// A URL citation when using web search.
#[serde(skip_serializing_if = "Option::is_none")]
pub url_citation: Option<AnnotationURLCitation>,
}
/// A URL citation when using web search.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct AnnotationURLCitation {
/// The index of the last character of the URL citation in the message.
pub end_index: usize,
/// The index of the first character of the URL citation in the message.
pub start_index: usize,
/// The title of the web resource.
pub title: String,
/// The URL of the web resource.
pub url: String,
}
/// Audio response from the model when audio output modality is requested.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct ChatCompletionAudio {
/// Unique identifier for this audio response.
pub id: String,
/// Base64 encoded audio bytes generated by the model, in the format specified in the request.
pub data: String,
/// The Unix timestamp (in seconds) for when this audio response will no longer be accessible on the server for use in multi-turn conversations.
pub expires_at: u64,
/// Transcript of the audio generated by the model.
pub transcript: String,
}
impl Response {
pub fn first_assistant_message(&self) -> Option<&Message> {
self.choices
.iter()
.find(|choice| choice.message.role == Role::Assistant)
.map(|choice| &choice.message)
}
pub fn first_assistant_message_text(&self) -> Option<String> {
self.first_assistant_message()
.and_then(|message| message.content.to_owned())
}
pub fn first_assistant_message_reasoning_text(&self) -> Option<String> {
self.first_assistant_message()
.and_then(|message| message.reasoning.to_owned())
}
/// Serialize this response with a custom JSON key for `reasoning_content` values nested under
/// `choices[].message`. See [`WithReasoningContentField`].
///
/// # Examples
///
/// ```ignore
/// serde_json::to_string(&response)?;
/// serde_json::to_string(&response.with_reasoning_content_field("reasoning_content"))?;
/// serde_json::to_string(&response.with_reasoning_content_field("thinking"))?;
/// serde_json::to_string(&response.with_reasoning_content_field(""))?; // same as default: key "reasoning"
/// ```
pub fn with_reasoning_content_field<'a>(
&'a self,
field: &'a str,
) -> WithReasoningContentField<'a, Self> {
WithReasoningContentField::new(self, field)
}
}
fn rewrite_response_reasoning_content_keys(value: &mut serde_json::Value, new_key: &str) {
let Some(choices) = value
.get_mut("choices")
.and_then(serde_json::Value::as_array_mut)
else {
return;
};
for choice in choices {
let Some(choice) = choice.as_object_mut() else {
continue;
};
for field in ["message", "delta"] {
let Some(message) = choice
.get_mut(field)
.and_then(serde_json::Value::as_object_mut)
else {
continue;
};
if let Some(reasoning_val) = message.remove("reasoning") {
message.insert(new_key.to_string(), reasoning_val);
}
}
}
}
/// Serialize adapter: the underlying typed value is unchanged; only JSON output renames
/// `choices[].message.reasoning` or `choices[].delta.reasoning` to
/// `field` (`"reasoning_content"`, `"thinking"`, …). Use with
/// [`Response::with_reasoning_content_field`] and
/// [`crate::completions::chunk::ChunkResponse::with_reasoning_content_field`].
///
/// [`Message`], [`crate::completions::chunk::DeltaMessage`], and chunk types are not modified;
/// renaming happens only during `Serialize` by rewriting the intermediate JSON value.
///
/// # Examples
///
/// ```ignore
/// serde_json::to_string(&response)?;
/// serde_json::to_string(&response.with_reasoning_content_field("reasoning_content"))?;
/// serde_json::to_string(&response.with_reasoning_content_field("thinking"))?;
/// serde_json::to_string(&response.with_reasoning_content_field(""))?; // same as omitting wrapper: "reasoning"
/// ```
#[derive(Debug, Clone, Copy)]
pub struct WithReasoningContentField<'a, T: ?Sized> {
pub inner: &'a T,
pub field: &'a str,
}
impl<'a, T: ?Sized> WithReasoningContentField<'a, T> {
pub fn new(inner: &'a T, field: &'a str) -> Self {
Self { inner, field }
}
}
impl<'a, T: Serialize + ?Sized> Serialize for WithReasoningContentField<'a, T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if self.field.is_empty() || self.field == "reasoning" {
return self.inner.serialize(serializer);
}
let mut v = serde_json::to_value(&self.inner).map_err(serde::ser::Error::custom)?;
rewrite_response_reasoning_content_keys(&mut v, self.field);
v.serialize(serializer)
}
}
#[cfg(test)]
mod tests {
use crate::completions::request::{ToolCallFunction, ToolCallFunctionObj};
use super::*;
#[test]
fn serde() {
let tests = vec![
(
"default",
r#"{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"model": "gpt-3.5-turbo-0613",
"system_fingerprint": "fp_44709d6fcb",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "\n\nHello there, how may I assist you today?"
},
"logprobs": null,
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}"#,
Response {
id: "chatcmpl-123".to_string(),
object: "chat.completion".to_string(),
created: 1677652288,
model: "gpt-3.5-turbo-0613".to_string(),
system_fingerprint: Some("fp_44709d6fcb".to_string()),
choices: vec![Choice {
index: 0,
message: Message {
role: Role::Assistant,
content: Some(
"\n\nHello there, how may I assist you today?".to_string(),
),
reasoning: None,
tool_calls: None,
refusal: None,
annotations: None,
audio: None,
},
logprobs: None,
finish_reason: Some(FinishReason::Stop),
}],
usage: Usage {
prompt_tokens: 9,
completion_tokens: 12,
total_tokens: 21,
..Default::default()
},
service_tier: None,
},
),
(
"function",
r#"{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1699896916,
"model": "gpt-3.5-turbo-0613",
"system_fingerprint": "fp_6b68a8204b",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_current_weather",
"arguments": "{\n\"location\": \"Boston, MA\"\n}"
}
}
]
},
"logprobs": null,
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": 82,
"completion_tokens": 17,
"total_tokens": 99
}
}"#,
Response {
id: "chatcmpl-abc123".to_string(),
object: "chat.completion".to_string(),
created: 1699896916,
model: "gpt-3.5-turbo-0613".to_string(),
system_fingerprint: Some("fp_6b68a8204b".to_string()),
choices: vec![Choice {
index: 0,
message: Message {
role: Role::Assistant,
content: None,
tool_calls: Some(vec![ToolCall::Function(ToolCallFunction {
id: "call_abc123".to_string(),
function: ToolCallFunctionObj {
name: "get_current_weather".to_string(),
arguments: "{\n\"location\": \"Boston, MA\"\n}".to_string(),
},
})]),
refusal: None,
reasoning: None,
annotations: None,
audio: None,
},
logprobs: None,
finish_reason: Some(FinishReason::ToolCalls),
}],
usage: Usage {
prompt_tokens: 82,
completion_tokens: 17,
total_tokens: 99,
..Default::default()
},
service_tier: None,
},
),
(
"logprobs",
r#"{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1702685778,
"model": "gpt-3.5-turbo-0613",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I assist you today?"
},
"logprobs": {
"content": [
{
"token": "Hello",
"logprob": -0.31725305,
"bytes": [72, 101, 108, 108, 111],
"top_logprobs": [
{
"token": "Hello",
"logprob": -0.31725305,
"bytes": [72, 101, 108, 108, 111]
},
{
"token": "Hi",
"logprob": -1.3190403,
"bytes": [72, 105]
}
]
},
{
"token": "!",
"logprob": -0.02380986,
"bytes": [33],
"top_logprobs": [
{
"token": "!",
"logprob": -0.02380986,
"bytes": [33]
},
{
"token": " there",
"logprob": -3.787621,
"bytes": [32, 116, 104, 101, 114, 101]
}
]
},
{
"token": " How",
"logprob": -0.000054669687,
"bytes": [32, 72, 111, 119],
"top_logprobs": [
{
"token": " How",
"logprob": -0.000054669687,
"bytes": [32, 72, 111, 119]
},
{
"token": "<|end|>",
"logprob": -10.953937,
"bytes": null
}
]
}
]
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 9,
"total_tokens": 18
},
"system_fingerprint": "fp_44709d6fcb"
}"#,
Response {
id: "chatcmpl-123".to_string(),
object: "chat.completion".to_string(),
created: 1702685778,
model: "gpt-3.5-turbo-0613".to_string(),
system_fingerprint: Some("fp_44709d6fcb".to_string()),
choices: vec![Choice {
index: 0,
message: Message {
role: Role::Assistant,
content: Some("Hello! How can I assist you today?".to_string()),
reasoning: None,
tool_calls: None,
refusal: None,
annotations: None,
audio: None,
},
logprobs: Some(Logprobs {
content: Some(vec![
LogprobContent {
token: "Hello".to_string(),
logprob: -0.31725305,
bytes: Some(vec![72, 101, 108, 108, 111]),
top_logprobs: Some(vec![
TopLogprobs {
token: "Hello".to_string(),
logprob: -0.31725305,
bytes: Some(vec![72, 101, 108, 108, 111]),
},
TopLogprobs {
token: "Hi".to_string(),
logprob: -1.3190403,
bytes: Some(vec![72, 105]),
},
]),
},
LogprobContent {
token: "!".to_string(),
logprob: -0.02380986,
bytes: Some(vec![33]),
top_logprobs: Some(vec![
TopLogprobs {
token: "!".to_string(),
logprob: -0.02380986,
bytes: Some(vec![33]),
},
TopLogprobs {
token: " there".to_string(),
logprob: -3.787621,
bytes: Some(vec![32, 116, 104, 101, 114, 101]),
},
]),
},
LogprobContent {
token: " How".to_string(),
logprob: -0.000054669687,
bytes: Some(vec![32, 72, 111, 119]),
top_logprobs: Some(vec![
TopLogprobs {
token: " How".to_string(),
logprob: -0.000054669687,
bytes: Some(vec![32, 72, 111, 119]),
},
TopLogprobs {
token: "<|end|>".to_string(),
logprob: -10.953937,
bytes: None,
},
]),
},
]),
refusal: None,
}),
finish_reason: Some(FinishReason::Stop),
}],
usage: Usage {
prompt_tokens: 9,
completion_tokens: 9,
total_tokens: 18,
completion_tokens_details: None,
prompt_tokens_details: None,
},
service_tier: None,
},
),
(
"refusal",
r#"{
"id": "chatcmpl-123456",
"object": "chat.completion",
"created": 1728933352,
"model": "gpt-4o-2024-08-06",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hi there! How can I assist you today?"
},
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 19,
"completion_tokens": 10,
"total_tokens": 29,
"prompt_tokens_details": {
"cached_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0,
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0
}
},
"system_fingerprint": "fp_6b68a8204b"
}"#,
Response {
id: "chatcmpl-123456".to_string(),
object: "chat.completion".to_string(),
created: 1728933352,
model: "gpt-4o-2024-08-06".to_string(),
system_fingerprint: Some("fp_6b68a8204b".to_string()),
choices: vec![Choice {
index: 0,
message: Message {
role: Role::Assistant,
content: Some("Hi there! How can I assist you today?".to_string()),
reasoning: None,
tool_calls: None,
refusal: None,
annotations: None,
audio: None,
},
logprobs: None,
finish_reason: Some(FinishReason::Stop),
}],
usage: Usage {
prompt_tokens: 19,
completion_tokens: 10,
total_tokens: 29,
prompt_tokens_details: Some(PromptTokensDetails {
audio_tokens: None,
cached_tokens: Some(0),
}),
completion_tokens_details: Some(CompletionTokensDetails {
reasoning_tokens: Some(0),
accepted_prediction_tokens: Some(0),
rejected_prediction_tokens: Some(0),
audio_tokens: None,
}),
},
service_tier: None,
},
),
];
for (name, json, expected) in tests {
//test deserialize
let actual: Response = serde_json::from_str(json).unwrap();
assert_eq!(actual, expected, "deserialize test failed: {}", name);
//test serialize
let serialized = serde_json::to_string(&expected).unwrap();
let actual: Response = serde_json::from_str(&serialized).unwrap();
assert_eq!(actual, expected, "serialize test failed: {}", name);
}
}
#[test]
fn with_reasoning_content_field_response_uses_reasoning_content_in_json() {
let response = Response {
id: "id".to_string(),
object: "chat.completion".to_string(),
created: 0,
model: "m".to_string(),
system_fingerprint: None,
choices: vec![Choice {
index: 0,
message: Message {
role: Role::Assistant,
content: None,
reasoning: Some("internal".to_string()),
tool_calls: None,
refusal: None,
annotations: None,
audio: None,
},
finish_reason: None,
logprobs: None,
}],
usage: Usage {
prompt_tokens: 1,
completion_tokens: 1,
total_tokens: 2,
..Default::default()
},
service_tier: None,
};
let s = serde_json::to_string(&response.with_reasoning_content_field("reasoning_content"))
.unwrap();
let v: serde_json::Value = serde_json::from_str(&s).unwrap();
assert_eq!(v["choices"][0]["message"]["reasoning_content"], "internal");
assert!(v["choices"][0]["message"].get("reasoning").is_none());
let default_v = serde_json::to_value(&response).unwrap();
let empty_alias_v =
serde_json::to_value(response.with_reasoning_content_field("")).unwrap();
assert_eq!(default_v, empty_alias_v);
let thinking_s =
serde_json::to_string(&response.with_reasoning_content_field("thinking")).unwrap();
let vt: serde_json::Value = serde_json::from_str(&thinking_s).unwrap();
assert_eq!(vt["choices"][0]["message"]["thinking"], "internal");
}
#[test]
fn reasoning_content_field_rewrite_is_limited_to_choice_messages_and_deltas() {
let mut value = serde_json::json!({
"reasoning": "top-level config-like value",
"choices": [
{
"message": {
"role": "assistant",
"content": null,
"reasoning": "message trace",
"tool_calls": [
{
"type": "function",
"function": {
"name": "example",
"arguments": "{}",
"reasoning": "nested value"
}
}
]
}
},
{
"delta": {
"reasoning": "delta trace",
"nested": {
"reasoning": "nested delta value"
}
}
}
],
"usage": {
"reasoning": "usage value"
}
});
rewrite_response_reasoning_content_keys(&mut value, "thinking");
assert_eq!(value["choices"][0]["message"]["thinking"], "message trace");
assert!(value["choices"][0]["message"].get("reasoning").is_none());
assert_eq!(value["choices"][1]["delta"]["thinking"], "delta trace");
assert!(value["choices"][1]["delta"].get("reasoning").is_none());
assert_eq!(value["reasoning"], "top-level config-like value");
assert_eq!(
value["choices"][0]["message"]["tool_calls"][0]["function"]["reasoning"],
"nested value"
);
assert_eq!(
value["choices"][1]["delta"]["nested"]["reasoning"],
"nested delta value"
);
assert_eq!(value["usage"]["reasoning"], "usage value");
}
}