-
Notifications
You must be signed in to change notification settings - Fork 17
refactor: centralize json schema generation #212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace PhpLlm\LlmChain\Chain\JsonSchema; | ||
|
||
final readonly class DescriptionParser | ||
{ | ||
public function getDescription(\ReflectionProperty|\ReflectionParameter $reflector): string | ||
{ | ||
if ($reflector instanceof \ReflectionProperty) { | ||
return $this->fromProperty($reflector); | ||
} | ||
|
||
return $this->fromParameter($reflector); | ||
} | ||
|
||
private function fromProperty(\ReflectionProperty $property): string | ||
{ | ||
$comment = $property->getDocComment(); | ||
|
||
if (is_string($comment) && preg_match('/@var\s+[a-zA-Z\\\\]+\s+((.*)(?=\*)|.*)/', $comment, $matches)) { | ||
return trim($matches[1]); | ||
} | ||
|
||
$class = $property->getDeclaringClass(); | ||
if ($class->hasMethod('__construct')) { | ||
return $this->fromParameter( | ||
new \ReflectionParameter([$class->getName(), '__construct'], $property->getName()) | ||
); | ||
} | ||
|
||
return ''; | ||
} | ||
|
||
private function fromParameter(\ReflectionParameter $parameter): string | ||
{ | ||
$comment = $parameter->getDeclaringFunction()->getDocComment(); | ||
if (!$comment) { | ||
return ''; | ||
} | ||
|
||
if (preg_match('/@param\s+\S+\s+\$'.preg_quote($parameter->getName(), '/').'\s+((.*)(?=\*)|.*)/', $comment, $matches)) { | ||
return trim($matches[1]); | ||
} | ||
|
||
return ''; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace PhpLlm\LlmChain\Chain\JsonSchema; | ||
|
||
use PhpLlm\LlmChain\Chain\JsonSchema\Attribute\With; | ||
use Symfony\Component\TypeInfo\Type; | ||
use Symfony\Component\TypeInfo\Type\BuiltinType; | ||
use Symfony\Component\TypeInfo\Type\CollectionType; | ||
use Symfony\Component\TypeInfo\Type\ObjectType; | ||
use Symfony\Component\TypeInfo\TypeIdentifier; | ||
use Symfony\Component\TypeInfo\TypeResolver\TypeResolver; | ||
|
||
/** | ||
* @phpstan-type JsonSchema array{ | ||
* type: 'object', | ||
* properties: array<string, array{ | ||
* type: string, | ||
* description: string, | ||
* enum?: list<string>, | ||
* const?: string|int|list<string>, | ||
* pattern?: string, | ||
* minLength?: int, | ||
* maxLength?: int, | ||
* minimum?: int, | ||
* maximum?: int, | ||
* multipleOf?: int, | ||
* exclusiveMinimum?: int, | ||
* exclusiveMaximum?: int, | ||
* minItems?: int, | ||
* maxItems?: int, | ||
* uniqueItems?: bool, | ||
* minContains?: int, | ||
* maxContains?: int, | ||
* required?: bool, | ||
* minProperties?: int, | ||
* maxProperties?: int, | ||
* dependentRequired?: bool, | ||
* }>, | ||
* required: list<string>, | ||
* additionalProperties: false, | ||
* } | ||
*/ | ||
final readonly class Factory | ||
{ | ||
private TypeResolver $typeResolver; | ||
|
||
public function __construct( | ||
private DescriptionParser $descriptionParser = new DescriptionParser(), | ||
?TypeResolver $typeResolver = null, | ||
) { | ||
$this->typeResolver = $typeResolver ?? TypeResolver::create(); | ||
} | ||
|
||
/** | ||
* @return JsonSchema|null | ||
*/ | ||
public function buildParameters(string $className, string $methodName): ?array | ||
{ | ||
$reflection = new \ReflectionMethod($className, $methodName); | ||
|
||
return $this->convertTypes($reflection->getParameters()); | ||
} | ||
|
||
/** | ||
* @return JsonSchema|null | ||
*/ | ||
public function buildProperties(string $className): ?array | ||
{ | ||
$reflection = new \ReflectionClass($className); | ||
|
||
return $this->convertTypes($reflection->getProperties()); | ||
} | ||
|
||
/** | ||
* @param list<\ReflectionProperty|\ReflectionParameter> $elements | ||
* | ||
* @return JsonSchema|null | ||
*/ | ||
private function convertTypes(array $elements): ?array | ||
{ | ||
if (0 === count($elements)) { | ||
return null; | ||
} | ||
|
||
$result = [ | ||
'type' => 'object', | ||
'properties' => [], | ||
'required' => [], | ||
'additionalProperties' => false, | ||
]; | ||
|
||
foreach ($elements as $element) { | ||
$name = $element->getName(); | ||
$type = $this->typeResolver->resolve($element); | ||
$schema = $this->getTypeSchema($type); | ||
|
||
if ($type->isNullable()) { | ||
$schema['type'] = [$schema['type'], 'null']; | ||
} else { | ||
$result['required'][] = $name; | ||
} | ||
|
||
$description = $this->descriptionParser->getDescription($element); | ||
if ('' !== $description) { | ||
$schema['description'] = $description; | ||
} | ||
|
||
// Check for ToolParameter attributes | ||
$attributes = $element->getAttributes(With::class); | ||
if (count($attributes) > 0) { | ||
$attributeState = array_filter((array) $attributes[0]->newInstance(), fn ($value) => null !== $value); | ||
$schema = array_merge($schema, $attributeState); | ||
} | ||
|
||
$result['properties'][$name] = $schema; | ||
} | ||
|
||
return $result; | ||
} | ||
|
||
/** | ||
* @return array<string, mixed> | ||
*/ | ||
private function getTypeSchema(Type $type): array | ||
{ | ||
switch (true) { | ||
case $type->isIdentifiedBy(TypeIdentifier::INT): | ||
return ['type' => 'integer']; | ||
|
||
case $type->isIdentifiedBy(TypeIdentifier::FLOAT): | ||
return ['type' => 'number']; | ||
|
||
case $type->isIdentifiedBy(TypeIdentifier::BOOL): | ||
return ['type' => 'boolean']; | ||
|
||
case $type->isIdentifiedBy(TypeIdentifier::ARRAY): | ||
assert($type instanceof CollectionType); | ||
$collectionValueType = $type->getCollectionValueType(); | ||
|
||
if ($collectionValueType->isIdentifiedBy(TypeIdentifier::OBJECT)) { | ||
assert($collectionValueType instanceof ObjectType); | ||
|
||
return [ | ||
'type' => 'array', | ||
'items' => $this->buildProperties($collectionValueType->getClassName()), | ||
]; | ||
} | ||
|
||
return [ | ||
'type' => 'array', | ||
'items' => $this->getTypeSchema($collectionValueType), | ||
]; | ||
|
||
case $type->isIdentifiedBy(TypeIdentifier::OBJECT): | ||
if ($type instanceof BuiltinType) { | ||
throw new \InvalidArgumentException('Cannot build schema from plain object type.'); | ||
} | ||
assert($type instanceof ObjectType); | ||
if (in_array($type->getClassName(), ['DateTime', 'DateTimeImmutable', 'DateTimeInterface'], true)) { | ||
return ['type' => 'string', 'format' => 'date-time']; | ||
} else { | ||
// Recursively build the schema for an object type | ||
return $this->buildProperties($type->getClassName()); | ||
} | ||
|
||
// no break | ||
case $type->isIdentifiedBy(TypeIdentifier::STRING): | ||
default: | ||
// Fallback to string for any unhandled types | ||
return ['type' => 'string']; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.