-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnumOutputParser.php
More file actions
75 lines (60 loc) · 2.41 KB
/
EnumOutputParser.php
File metadata and controls
75 lines (60 loc) · 2.41 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
<?php
declare(strict_types=1);
namespace Cortex\OutputParsers;
use BackedEnum;
use Cortex\LLM\Data\ChatGeneration;
use Cortex\LLM\Data\ChatGenerationChunk;
use Cortex\Exceptions\OutputParserException;
class EnumOutputParser extends AbstractOutputParser
{
/**
* @param class-string<\BackedEnum> $enum
*/
public function __construct(
protected string $enum,
) {}
public function parse(ChatGeneration|ChatGenerationChunk|string $output): BackedEnum
{
if (! enum_exists($this->enum) || ! is_subclass_of($this->enum, BackedEnum::class)) {
throw OutputParserException::failed(sprintf('Invalid enum: %s', $this->enum));
}
$enumName = class_basename($this->enum);
// If the output has a tool call with the enum name, then assume we are using the schema tool.
if (! is_string($output) && $output->message->hasToolCall($enumName)) {
$schemaTool = $output->message->getToolCall($enumName);
$parsed = (new JsonOutputToolsParser(key: $schemaTool->function->name, singleToolCall: true))
->parse($output);
if (array_key_exists($enumName, $parsed)) {
$enum = $this->enum::tryFrom($parsed[$enumName]);
if ($enum !== null) {
return $enum;
}
}
}
$textOutput = match (true) {
$output instanceof ChatGenerationChunk => $output->contentSoFar,
$output instanceof ChatGeneration => $output->message->text() ?? '',
default => $output,
};
// First try to get the enum from the string output
$enum = $this->enum::tryFrom($textOutput);
// Then use the json output parser to get the enum from the json output
if ($enum === null) {
try {
$data = (new JsonOutputParser())->parse($output);
} catch (OutputParserException $e) {
throw OutputParserException::failed(
sprintf('Enum %s not found in output', $this->enum),
previous: $e,
);
}
if (array_key_exists($enumName, $data)) {
$enum = $this->enum::from($data[$enumName]);
}
}
if ($enum === null) {
throw OutputParserException::failed(sprintf('Enum %s not found in output', $this->enum));
}
return $enum;
}
}