ChunkParser.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Helpers;
  4. use App\Enums\Status;
  5. final class ChunkParser
  6. {
  7. public string $chunk = '';
  8. private string $buffer = '';
  9. private array $results = [];
  10. public function __construct(private readonly array $tags = ['think', 'content', 'fields'], private readonly string $name = 'inference_rag_')
  11. {
  12. foreach ($this->tags as $tag) {
  13. $this->results[$tag] = null;
  14. }
  15. }
  16. public function append(string $chunk): self
  17. {
  18. $this->chunk = $chunk;
  19. $this->buffer .= $chunk;
  20. return $this;
  21. }
  22. public function parse(): self
  23. {
  24. if ($this->buffer === '') {
  25. return $this;
  26. }
  27. foreach ($this->tags as $tag) {
  28. $positions = $this->positions($this->buffer, $tag);
  29. if (count($positions) >= 1) {
  30. $length = strlen('<|' . $this->name . $tag . '|>');
  31. $content = substr($this->buffer, $positions[0] + $length, ($positions[1] ?? null) - $positions[0] - $length);
  32. $this->results[$tag] = $content;
  33. } else {
  34. $this->results[$tag] = null;
  35. }
  36. }
  37. return $this;
  38. }
  39. private function positions(string $buffer, string $tag): array
  40. {
  41. $pattern = "/<\\|" . $this->name . $tag . "\\|>/";
  42. $matches = [];
  43. preg_match_all($pattern, $buffer, $matches, PREG_OFFSET_CAPTURE);
  44. return !empty($matches[0]) ? array_column($matches[0], 1) : [];
  45. }
  46. public function all(): array
  47. {
  48. return $this->results;
  49. }
  50. public function toArray(): array
  51. {
  52. return ['think' => $this->think, 'content' => $this->content, 'fields' => $this->fields, 'status' => $this->getStatus()];
  53. }
  54. private function getStatus(): ?Status
  55. {
  56. if ($this->think && !$this->content) {
  57. return Status::Thinking;
  58. }
  59. if ($this->content) {
  60. return Status::Typing;
  61. }
  62. return null;
  63. }
  64. public function __get(string $tag)
  65. {
  66. if($tag === 'status') {
  67. return $this->getStatus();
  68. }
  69. $string = $this->results[$tag] ?? null;
  70. if ($tag === 'fields') {
  71. try {
  72. return json_decode($string, true);
  73. } catch (\Throwable) {
  74. return [];
  75. }
  76. }
  77. return $string;
  78. }
  79. }