| 419 | const char *think_open = "<think>"; |
| 420 | const char *think_close = "</think>"; |
| 421 | size_t total = p->pending_len + len; |
| 422 | char *buf = malloc(total ? total : 1); |
| 423 | if (!buf) return; |
| 424 | if (p->pending_len) memcpy(buf, p->pending, p->pending_len); |
| 425 | if (len) memcpy(buf + p->pending_len, text, len); |
| 426 | p->pending_len = 0; |
| 427 | |
| 428 | size_t i = 0; |
| 429 | while (i < total) { |
| 430 | const char *cur = buf + i; |
| 431 | const size_t rem = total - i; |
| 432 | if (bytes_has_prefix(cur, rem, think_open)) { |
| 433 | p->in_think = true; |
| 434 | i += strlen(think_open); |
| 435 | continue; |
| 436 | } |
| 437 | if (bytes_has_prefix(cur, rem, think_close)) { |
| 438 | p->in_think = false; |
| 439 | token_printer_reset_color(p); |
| 440 | if (!p->last_output_newline) { |
| 441 | fputc('\n', p->fp); |
| 442 | p->last_output_newline = true; |
| 443 | } |
| 444 | i += strlen(think_close); |
| 445 | continue; |
| 446 | } |
| 447 | if (!finish && cur[0] == '<' && |
| 448 | (bytes_is_partial_prefix(cur, rem, think_open) || |
| 449 | bytes_is_partial_prefix(cur, rem, think_close))) |
| 450 | { |
| 451 | if (rem < sizeof(p->pending)) { |
| 452 | memcpy(p->pending, cur, rem); |
| 453 | p->pending_len = rem; |
| 454 | } |
| 455 | break; |
| 456 | } |
| 457 | token_printer_write_char(p, cur[0]); |
| 458 | i++; |
| 459 | } |
| 460 | |
| 461 | free(buf); |
| 462 | } |
| 463 | |
| 464 | static void token_printer_finish(token_printer *p) { |
| 465 | if (p->format_thinking) { |
| 466 | token_printer_process(p, NULL, 0, true); |
| 467 | token_printer_reset_color(p); |
| 468 | } |
| 469 | fflush(p->fp); |
| 470 | } |
| 471 | |
| 472 | static void generation_done(void *ud) { |
| 473 | token_printer *p = ud; |
| 474 | token_printer_finish(p); |
| 475 | if (!p->last_output_newline) { |
| 476 | fputc('\n', p->fp); |
| 477 | p->last_output_newline = true; |
| 478 | } |
no test coverage detected