use crate::requests::*;
use serde::{Deserialize, Serialize};
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::ReponseContentEmpty);
}
if res.content.len() > 1 {
return Err(CompletionError::ReponseContentEmpty);
}
let content = res
.content
.first()
.ok_or_else(|| CompletionError::ReponseContentEmpty)?
.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),
})
}
}
#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
pub struct AnthropicCompletionResponse {
pub id: String,
pub content: Vec<CompletionContent>,
pub model: String,
pub stop_reason: StopReason,
pub stop_sequence: Option<String>,
pub usage: CompletionUsage,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct CompletionContent {
pub text: String,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct CompletionUsage {
pub input_tokens: u32,
pub output_tokens: u32,
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
EndTurn,
MaxTokens,
StopSequence,
ToolUse,
}