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
use crate::requests::completion::*;
use serde::{Deserialize, Serialize};
use tool::{Function, ToolCall};
impl CompletionResponse {
pub fn new_from_anthropic(
req: &CompletionRequest,
res: AnthropicCompletionResponse,
) -> Result<Self, CompletionError> {
let finish_reason = match res.stop_reason {
StopReason::EndTurn => CompletionFinishReason::Eos,
StopReason::StopSequence => {
if let Some(stopping_string) = &res.stop_sequence {
if let Some(stop_sequence) =
req.stop_sequences.parse_string_response(stopping_string)
{
CompletionFinishReason::MatchingStoppingSequence(stop_sequence)
} else {
CompletionFinishReason::NonMatchingStoppingSequence(Some(
stopping_string.clone(),
))
}
} else {
CompletionFinishReason::NonMatchingStoppingSequence(None)
}
}
StopReason::MaxTokens => CompletionFinishReason::StopLimit,
StopReason::ToolUse => {
return Err(CompletionError::StopReasonUnsupported(
"StopReason::ToolUse is not supported".to_owned(),
));
}
};
if res.content.is_empty() {
return Err(CompletionError::ResponseContentEmpty);
}
if res.content.len() > 1 {
return Err(CompletionError::ResponseContentEmpty);
}
let content = res
.content
.first()
.ok_or_else(|| CompletionError::ResponseContentEmpty)?
.text()
.to_owned();
Ok(Self {
id: res.id.to_owned(),
index: None,
content,
finish_reason,
completion_probabilities: None,
truncated: false,
generation_settings: GenerationSettings::new_from_anthropic(req, &res),
timing_usage: TimingUsage::new_from_generic(req.start_time),
token_usage: TokenUsage::new_from_anthropic(&res),
tool_calls: match res.content.as_slice() {
[
CompletionContent::ToolUse {
name,
input,
id,
r#type,
},
..,
] => Some(vec![ToolCall {
id: id.to_owned(),
r#type: r#type.to_owned(),
function: Function {
name: name.to_owned(),
arguments: serde_json::to_string(input)?,
},
}]),
_ => None,
},
})
}
}
/// Represents a chat completion response returned by model, based on the provided input.
#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
pub struct AnthropicCompletionResponse {
/// Unique object identifier.
///
/// The format and length of IDs may change over time.
pub id: String,
/// Content generated by the model.
///
/// This is an array of content blocks, each of which has a type that determines its shape. Currently, the only type in responses is "text".
pub content: Vec<CompletionContent>,
/// The model that handled the request.
pub model: String,
/// The reason that we stopped.
///
/// This may be one of the following values:
///
/// "end_turn": the model reached a natural stopping point
/// "max_tokens": we exceeded the requested max_tokens or the model's maximum
/// "stop_sequence": one of your provided custom stop_sequences was generated
pub stop_reason: StopReason,
/// Which custom stop sequence was generated, if any.
///
/// This value will be a non-null string if one of your custom stop sequences was generated.
pub stop_sequence: Option<String>,
/// Billing and rate-limit usage.
///
/// Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.
///
/// Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in usage will not match one-to-one with the exact visible content of an API request or response.
///
/// For example, output_tokens will be non-zero, even for an empty string response from Claude.
pub usage: CompletionUsage,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum CompletionContent {
/// The single text content.
String(String),
Text {
r#type: String,
text: String,
},
ToolUse {
r#type: String,
id: String,
name: String,
input: serde_json::Value,
},
}
impl CompletionContent {
pub fn text(&self) -> String {
match self {
CompletionContent::String(text) => text.to_string(),
CompletionContent::Text {
r#type: _, text, ..
} => text.to_string(),
CompletionContent::ToolUse { .. } => "".to_string(),
}
}
}
/// Usage statistics for the completion request.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct CompletionUsage {
/// The number of input tokens which were used.
pub input_tokens: u32,
/// The number of output tokens which were used.
pub output_tokens: u32,
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
/// The model reached a natural stopping point.
EndTurn,
/// We exceeded the requested max_tokens or the model's maximum.
MaxTokens,
/// One of your provided custom stop_sequences was generated.
StopSequence,
/// Claude wants to use an external tool.
ToolUse,
}