forked from ezimuel/php-llm-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai_function.php
More file actions
84 lines (77 loc) · 2.72 KB
/
Copy pathopenai_function.php
File metadata and controls
84 lines (77 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/**
* OpenAI moderation example
*/
require dirname(__DIR__) . '/vendor/autoload.php';
$apiKey = getenv('OPENAI_API_KEY');
$client = OpenAI::client($apiKey);
/**
* Returns the current temperature in a location as sentence
*/
function get_current_weather(string $location, string $unit = 'celsius'): string
{
$temperature = 20.5; // # this should be a result of an HTTP API call
return sprintf(
"The temperature in %s is %.2f %s",
$location,
$temperature,
$unit === 'celsius' ? '°C' : '°F'
);
}
$question = 'What\'s the weather like in Turin?';
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo-0613',
'messages' => [
['role' => 'user', 'content' => $question],
],
'tools' => [
[
'type' => 'function',
'function' => [
'name' => 'get_current_weather',
'description' => 'Get the current weather in a given location',
'parameters' => [
'type' => 'object',
'properties' => [
'location' => [
'type' => 'string',
'description' => 'The city and state, e.g. San Francisco, CA',
],
'unit' => [
'type' => 'string',
'enum' => ['celsius', 'fahrenheit']
],
],
'required' => ['location'],
],
],
]
]
]);
// If toolCalls is not empty I need to execute the function
// and give back to GPT to give a final answer
foreach ($response->choices as $choice) {
foreach ($choice->message->toolCalls as $call) {
if ($call->type === 'function') {
$arguments = json_decode($call->function->arguments, true);
printf("Calling function %s(%s)\n", $call->function->name, implode('=', $arguments));
$result = call_user_func($call->function->name, ...$arguments);
if (!empty($result)) {
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo-0613',
'messages' => [
[
'role' => 'system',
'content' => sprintf(
"Knowing that %s, answer to the user question",
$result
)
],
['role' => 'user', 'content' => $question],
]
]);
}
}
}
}
printf("Answer: %s\n", $response->choices[0]->message->content);