|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +require __DIR__.'/../vendor/autoload.php'; |
| 4 | + |
| 5 | +use JDecool\OllamaClient\ClientBuilder; |
| 6 | +use JDecool\OllamaClient\Client\Message; |
| 7 | +use JDecool\OllamaClient\Client\Tool; |
| 8 | +use JDecool\OllamaClient\Client\ToolFunction; |
| 9 | +use JDecool\OllamaClient\Client\Request\ChatRequest; |
| 10 | + |
| 11 | +$builder = new ClientBuilder(); |
| 12 | +$client = $builder->create(); |
| 13 | + |
| 14 | +$request = new ChatRequest( |
| 15 | + model: 'llama3.1', |
| 16 | + messages: $messages = [ |
| 17 | + new Message('user', 'What is the weather in San Francisco?'), |
| 18 | + ], |
| 19 | + tools: [ |
| 20 | + new Tool( |
| 21 | + type: Tool::TYPE_FUNCTION, |
| 22 | + function: new ToolFunction( |
| 23 | + name: 'get_current_weather', |
| 24 | + description: 'Get the current weather for a location', |
| 25 | + parameters: [ |
| 26 | + 'type' => 'object', |
| 27 | + 'properties' => [ |
| 28 | + 'location' => [ |
| 29 | + 'type' => 'string', |
| 30 | + 'description' => 'The city and state, e.g., San Francisco, CA', |
| 31 | + ], |
| 32 | + 'unit' => [ |
| 33 | + 'type' => 'string', |
| 34 | + 'enum' => ['celsius', 'fahrenheit'], |
| 35 | + 'description' => 'The unit of temperature', |
| 36 | + ], |
| 37 | + ], |
| 38 | + 'required' => ['location'], |
| 39 | + ], |
| 40 | + ), |
| 41 | + ), |
| 42 | + ], |
| 43 | +); |
| 44 | + |
| 45 | +$response = $client->chat($request); |
| 46 | +var_dump($response); |
| 47 | + |
| 48 | +// Check if the model wants to use a tool |
| 49 | +if ($response->message->toolCalls !== null) { |
| 50 | + foreach ($response->message->toolCalls as $toolCall) { |
| 51 | + echo "Function: {$toolCall->function->name}\n"; |
| 52 | + echo "Arguments: " . json_encode($toolCall->function->arguments, JSON_PRETTY_PRINT) . "\n"; |
| 53 | + |
| 54 | + // Simulate executing the function |
| 55 | + $functionResult = match($toolCall->function->name) { |
| 56 | + 'get_current_weather' => json_encode([ |
| 57 | + 'temperature' => 72, |
| 58 | + 'unit' => $toolCall->function->arguments['unit'] ?? 'fahrenheit', |
| 59 | + 'condition' => 'sunny', |
| 60 | + ]), |
| 61 | + default => json_encode(['error' => 'Unknown function']), |
| 62 | + }; |
| 63 | + |
| 64 | + // Add assistant message with tool calls |
| 65 | + $messages[] = $response->message; |
| 66 | + |
| 67 | + // Add tool response message |
| 68 | + $messages[] = new Message( |
| 69 | + role: 'tool', |
| 70 | + content: (string) $functionResult, |
| 71 | + ); |
| 72 | + } |
| 73 | + |
| 74 | + // Send the conversation back with tool results |
| 75 | + $finalRequest = new ChatRequest( |
| 76 | + model: 'llama3.1', |
| 77 | + messages: $messages, |
| 78 | + ); |
| 79 | + |
| 80 | + var_dump($client->chat($finalRequest)); |
| 81 | +} |
0 commit comments