-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathChatSession.php
More file actions
93 lines (74 loc) · 2.25 KB
/
ChatSession.php
File metadata and controls
93 lines (74 loc) · 2.25 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
85
86
87
88
89
90
91
92
93
<?php
declare(strict_types=1);
namespace GeminiAPI;
use GeminiAPI\Enums\Role;
use GeminiAPI\Resources\Content;
use GeminiAPI\Resources\Parts\PartInterface;
use GeminiAPI\Responses\GenerateContentResponse;
use GeminiAPI\Traits\ArrayTypeValidator;
use InvalidArgumentException;
use Psr\Http\Client\ClientExceptionInterface;
class ChatSession
{
use ArrayTypeValidator;
/** @var Content[] */
private array $history;
public function __construct(
private readonly GenerativeModel $model,
) {
}
/**
* @throws ClientExceptionInterface
*/
public function sendMessage(PartInterface ...$parts): GenerateContentResponse
{
$this->history[] = new Content($parts, Role::User);
$response = $this->model->generateContentWithContents($this->history);
if (!empty($response->candidates)) {
$parts = $response->candidates[0]->content->parts;
$this->history[] = new Content($parts, Role::Model);
}
return $response;
}
/**
* @param callable(GenerateContentResponse): void $callback
* @param PartInterface ...$parts
* @return void
*/
public function sendMessageStream(
callable $callback,
PartInterface ...$parts,
): void {
$this->history[] = new Content($parts, Role::User);
$parts = [];
$partsCollectorCallback = function (GenerateContentResponse $response) use ($callback, &$parts) {
if (!empty($response->candidates)) {
array_push($parts, ...$response->parts());
}
$callback($response);
};
$this->model->generateContentStreamWithContents($partsCollectorCallback, $this->history);
if (!empty($parts)) {
$this->history[] = new Content($parts, Role::Model);
}
}
/**
* @return Content[]
*/
public function history(): array
{
return $this->history;
}
/**
* @param Content[] $history
* @return $this
* @throws InvalidArgumentException
*/
public function withHistory(array $history): self
{
$this->ensureArrayOfType($history, Content::class);
$clone = clone $this;
$clone->history = $history;
return $clone;
}
}