Skip to content

Commit

Permalink
Handle missing array keys
Browse files Browse the repository at this point in the history
  • Loading branch information
Erdem Köse committed Dec 1, 2024
1 parent 7da0475 commit aea0323
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/Resources/Candidate.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace GeminiAPI\Resources;

use GeminiAPI\Enums\FinishReason;
use GeminiAPI\Enums\Role;
use GeminiAPI\Traits\ArrayTypeValidator;
use UnexpectedValueException;

Expand Down Expand Up @@ -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,
Expand Down
27 changes: 27 additions & 0 deletions tests/Unit/Resources/CandidateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit aea0323

Please sign in to comment.