diff --git a/src/Resources/Candidate.php b/src/Resources/Candidate.php index fee3c2f..2b26e76 100644 --- a/src/Resources/Candidate.php +++ b/src/Resources/Candidate.php @@ -5,6 +5,7 @@ namespace GeminiAPI\Resources; use GeminiAPI\Enums\FinishReason; +use GeminiAPI\Enums\Role; use GeminiAPI\Traits\ArrayTypeValidator; use UnexpectedValueException; @@ -61,9 +62,17 @@ public static function fromArray(array $candidate): self $candidate['safetyRatings'] ?? [], ); + $content = isset($candidate['content']) + ? Content::fromArray($candidate['content']) + : Content::text('', Role::Model); + + $finishReason = isset($candidate['finishReason']) + ? FinishReason::from($candidate['finishReason']) + : FinishReason::OTHER; + return new self( - Content::fromArray($candidate['content']), - FinishReason::from($candidate['finishReason']), + $content, + $finishReason, $citationMetadata, $safetyRatings, $candidate['tokenCount'] ?? 0, diff --git a/tests/Unit/Resources/CandidateTest.php b/tests/Unit/Resources/CandidateTest.php index 4748820..bec86cc 100644 --- a/tests/Unit/Resources/CandidateTest.php +++ b/tests/Unit/Resources/CandidateTest.php @@ -93,4 +93,31 @@ public function testFromArray() self::assertInstanceOf(Candidate::class, $candidate); } + + public function testFromArrayWithoutContent() + { + $candidate = Candidate::fromArray([ + 'safetyRatings' => [], + 'citationMetadata' => [], + 'index' => 1, + 'tokenCount' => 1, + 'finishReason' => 'OTHER', + ]); + + self::assertInstanceOf(Candidate::class, $candidate); + } + + public function testFromArrayWithoutFinishReason() + { + $candidate = Candidate::fromArray([ + 'content' => ['parts' => [], 'role' => 'user'], + 'safetyRatings' => [], + 'citationMetadata' => [], + 'index' => 1, + 'tokenCount' => 1, + ]); + + self::assertInstanceOf(Candidate::class, $candidate); + self::assertEquals(FinishReason::OTHER, $candidate->finishReason); + } }