Open History to see the last commit
1<?php
2
3/**
4 * Example usage of TanStack AI PHP library
5 */
6
7require __DIR__ . '/../vendor/autoload.php';
8
9use TanStack\AI\StreamChunkConverter;
10use TanStack\AI\MessageFormatters;
11use TanStack\AI\SSEFormatter;
12
13// Example 1: Convert messages to Anthropic format
14$messages = [
15 [
16 'role' => 'system',
17 'content' => 'You are a helpful assistant.'
18 ],
19 [
20 'role' => 'user',
21 'content' => 'Hello!'
22 ]
23];
24
25[$systemMessage, $anthropicMessages] = MessageFormatters::formatMessagesForAnthropic($messages);
26echo "System message: " . ($systemMessage ?? 'none') . "\n";
27echo "Anthropic messages: " . json_encode($anthropicMessages, JSON_PRETTY_PRINT) . "\n\n";
28
29// Example 2: Convert messages to OpenAI format
30$openaiMessages = MessageFormatters::formatMessagesForOpenAI($messages);
31echo "OpenAI messages: " . json_encode($openaiMessages, JSON_PRETTY_PRINT) . "\n\n";
32
33// Example 3: Initialize converter
34$converter = new StreamChunkConverter(
35 model: 'claude-3-haiku-20240307',
36 provider: 'anthropic'
37);
38
39// Example 4: Convert an event (simulated)
40$simulatedEvent = [
41 'type' => 'content_block_delta',
42 'delta' => [
43 'type' => 'text_delta',
44 'text' => 'Hello'
45 ]
46];
47
48$chunks = $converter->convertEvent($simulatedEvent);
49foreach ($chunks as $chunk) {
50 echo "Chunk: " . SSEFormatter::formatChunk($chunk);
51}
52
53// Example 5: Format completion
54echo SSEFormatter::formatDone();
55
56// Example 6: Handle errors
57try {
58 throw new Exception('Something went wrong');
59} catch (Exception $e) {
60 $errorChunk = $converter->convertError($e);
61 echo SSEFormatter::formatChunk($errorChunk);
62}
63