|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace NeuronAI\Providers\Anthropic; |
| 4 | + |
| 5 | +use GuzzleHttp\Exception\GuzzleException; |
| 6 | +use NeuronAI\Exceptions\ProviderException; |
| 7 | +use Psr\Http\Message\StreamInterface; |
| 8 | + |
| 9 | +trait HandleStream |
| 10 | +{ |
| 11 | + |
| 12 | + /** |
| 13 | + * @throws ProviderException |
| 14 | + * @throws GuzzleException |
| 15 | + */ |
| 16 | + public function stream(array|string $messages, callable $executeToolsCallback): \Generator |
| 17 | + { |
| 18 | + $mapper = new MessageMapper($messages); |
| 19 | + |
| 20 | + $json = \array_filter([ |
| 21 | + 'stream' => true, |
| 22 | + 'model' => $this->model, |
| 23 | + 'max_tokens' => $this->max_tokens, |
| 24 | + 'stop_sequences' => $this->stop_sequences, |
| 25 | + 'temperature' => $this->temperature, |
| 26 | + 'system' => $this->system ?? null, |
| 27 | + 'messages' => $mapper->map(), |
| 28 | + ]); |
| 29 | + |
| 30 | + if (!empty($this->tools)) { |
| 31 | + $json['tools'] = $this->generateToolsPayload(); |
| 32 | + } |
| 33 | + |
| 34 | + // https://docs.anthropic.com/claude/reference/messages_post |
| 35 | + $stream = $this->client->post('v1/messages', compact('json'))->getBody(); |
| 36 | + |
| 37 | + $toolCalls = []; |
| 38 | + |
| 39 | + while (! $stream->eof()) { |
| 40 | + if (!$line = $this->parseNextDataLine($stream)) { |
| 41 | + continue; |
| 42 | + } |
| 43 | + |
| 44 | + // Tool calls detection (https://docs.anthropic.com/en/api/messages-streaming#streaming-request-with-tool-use) |
| 45 | + if ( |
| 46 | + (isset($line['content_block']['type']) && $line['content_block']['type'] === 'tool_use') || |
| 47 | + (isset($line['delta']['type']) && $line['delta']['type'] === 'input_json_delta') |
| 48 | + ) { |
| 49 | + $toolCalls = $this->composeToolCalls($line, $toolCalls); |
| 50 | + continue; |
| 51 | + } |
| 52 | + |
| 53 | + // Handle tool call |
| 54 | + if ($line['type'] === 'content_block_stop' && !empty($toolCalls)) { |
| 55 | + // Restore the input field as an array |
| 56 | + $toolCalls = \array_map(function (array $call) { |
| 57 | + $call['input'] = json_decode($call['input'], true); |
| 58 | + return $call; |
| 59 | + }, $toolCalls); |
| 60 | + |
| 61 | + yield from $executeToolsCallback( |
| 62 | + $this->createToolMessage(\end($toolCalls)) |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + // Process regular content |
| 67 | + $content = $line['delta']['text']??''; |
| 68 | + |
| 69 | + yield $content; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Recreate the tool_call format of anthropic API from streaming. |
| 75 | + * |
| 76 | + * @param array<string, mixed> $line |
| 77 | + * @param array<int, array<string, mixed>> $toolCalls |
| 78 | + * @return array<int, array<string, mixed>> |
| 79 | + */ |
| 80 | + protected function composeToolCalls(array $line, array $toolCalls): array |
| 81 | + { |
| 82 | + if (!\array_key_exists($line['index'], $toolCalls)) { |
| 83 | + $toolCalls[$line['index']] = [ |
| 84 | + 'type' => 'tool_use', |
| 85 | + 'id' => $line['content_block']['id'], |
| 86 | + 'name' => $line['content_block']['name'], |
| 87 | + 'input' => '', |
| 88 | + ]; |
| 89 | + } else { |
| 90 | + if ($input = $line['delta']['partial_json']??null) { |
| 91 | + $toolCalls[$line['index']]['input'] .= $input; |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + return $toolCalls; |
| 96 | + } |
| 97 | + |
| 98 | + protected function parseNextDataLine(StreamInterface $stream): ?array |
| 99 | + { |
| 100 | + $line = $this->readLine($stream); |
| 101 | + |
| 102 | + if (! \str_starts_with($line, 'data:')) { |
| 103 | + return null; |
| 104 | + } |
| 105 | + |
| 106 | + $line = \trim(\substr($line, \strlen('data: '))); |
| 107 | + |
| 108 | + try { |
| 109 | + return \json_decode($line, true, flags: JSON_THROW_ON_ERROR); |
| 110 | + } catch (\Throwable $exception) { |
| 111 | + throw new ProviderException('Anthropic streaming error - '.$exception->getMessage()); |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + protected function readLine(StreamInterface $stream): string |
| 116 | + { |
| 117 | + $buffer = ''; |
| 118 | + |
| 119 | + while (! $stream->eof()) { |
| 120 | + $byte = $stream->read(1); |
| 121 | + |
| 122 | + if ($byte === '') { |
| 123 | + return $buffer; |
| 124 | + } |
| 125 | + |
| 126 | + $buffer .= $byte; |
| 127 | + |
| 128 | + if ($byte === "\n") { |
| 129 | + break; |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + return $buffer; |
| 134 | + } |
| 135 | +} |
0 commit comments