Skip to content

Commit

Permalink
fix: OpenAI finish response parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
Dustin Blackman committed Jan 30, 2024
1 parent 9b950a5 commit ec3b054
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
17 changes: 15 additions & 2 deletions src/infrastructure/backends/openai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,13 @@ struct CompletionRequest {

#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct CompletionDeltaResponse {
content: String,
content: Option<String>,
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct CompletionChoiceResponse {
delta: CompletionDeltaResponse,
finish_reason: Option<String>,
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
Expand Down Expand Up @@ -202,7 +203,19 @@ impl Backend for OpenAI {
let ores: CompletionResponse = serde_json::from_str(&cleaned_line).unwrap();
tracing::debug!(body = ?ores, "Completion response");

let text = ores.choices[0].delta.content.to_string();
let choice = &ores.choices[0];
if choice.finish_reason.is_some() {
break;
}
if choice.delta.content.is_none() {
continue;
}

let text = choice.delta.content.clone().unwrap().to_string();
if text.is_empty() {
continue;
}

last_message += &text;
let msg = BackendResponse {
author: Author::Model,
Expand Down
15 changes: 12 additions & 3 deletions src/infrastructure/backends/openai_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,20 +102,29 @@ async fn it_gets_completions() -> Result<()> {
let first_line = serde_json::to_string(&CompletionResponse {
choices: vec![CompletionChoiceResponse {
delta: CompletionDeltaResponse {
content: "Hello ".to_string(),
content: Some("Hello ".to_string()),
},
finish_reason: None,
}],
})?;

let second_line = serde_json::to_string(&CompletionResponse {
choices: vec![CompletionChoiceResponse {
delta: CompletionDeltaResponse {
content: "World".to_string(),
content: Some("World".to_string()),
},
finish_reason: None,
}],
})?;

let body = [first_line, second_line].join("\n");
let third_line = serde_json::to_string(&CompletionResponse {
choices: vec![CompletionChoiceResponse {
delta: CompletionDeltaResponse { content: None },
finish_reason: Some("stop".to_string()),
}],
})?;

let body = [first_line, second_line, third_line].join("\n");
let prompt = BackendPrompt {
text: "Say hi to the world".to_string(),
backend_context: serde_json::to_string(&vec![MessageRequest {
Expand Down

0 comments on commit ec3b054

Please sign in to comment.