4 if (chunk_data.empty()) {
8 std::string cleaned_chunk = chunk_data;
12 const std::string prefix =
"data: ";
13 if (cleaned_chunk.rfind(prefix, 0) == 0) {
14 cleaned_chunk.erase(0, prefix.length());
18 while (!cleaned_chunk.empty() &&
19 (cleaned_chunk.back() ==
'\n' || cleaned_chunk.back() ==
'\r')) {
20 cleaned_chunk.pop_back();
24 if (cleaned_chunk ==
"[DONE]") {
29 if (cleaned_chunk.empty()) {
34 json chunk_json = json::parse(cleaned_chunk);
37 if (chunk_json.contains(
"error")) {
38 error_ = chunk_json[
"error"];
44 if (chunk_json.contains(
"content")) {
45 std::string content = chunk_json[
"content"].get<std::string>();
46 concatenated_content_ += content;
50 if (chunk_json.contains(
"tokens")) {
51 for (
const auto& tok : chunk_json[
"tokens"]) {
52 concatenated_tokens_.push_back(tok.get<
int>());
57 last_chunk_ = chunk_json;
62 else callback_(concatenated_content_.c_str());
67 }
catch (
const json::exception& e) {
68 error_ = json{{
"message", std::string(
"JSON parse error: ") + e.what()}};