Skip to content

fix(go/plugins/googlegenai): runtime panic if no candidates returned #2925

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 1 commit into from
May 21, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions go/plugins/googlegenai/gemini.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,11 +451,6 @@ func generate(
}
resp.Candidates = merged
r = translateResponse(resp)
if r == nil {
// No candidates were returned. Probably rare, but it might avoid a NPE
// to return an empty instead of nil result.
r = &ai.ModelResponse{}
}
r.Request = input
if cache != nil {
r.Message.Metadata = setCacheMetadata(r.Message.Metadata, cache)
Expand Down Expand Up @@ -840,9 +835,17 @@ func translateCandidate(cand *genai.Candidate) *ai.ModelResponse {

// Translate from a genai.GenerateContentResponse to a ai.ModelResponse.
func translateResponse(resp *genai.GenerateContentResponse) *ai.ModelResponse {
r := translateCandidate(resp.Candidates[0])
var r *ai.ModelResponse
if len(resp.Candidates) > 0 {
r = translateCandidate(resp.Candidates[0])
} else {
r = &ai.ModelResponse{}
}

if r.Usage == nil {
r.Usage = &ai.GenerationUsage{}
}

r.Usage = &ai.GenerationUsage{}
if u := resp.UsageMetadata; u != nil {
r.Usage.InputTokens = int(u.PromptTokenCount)
r.Usage.OutputTokens = int(u.CandidatesTokenCount)
Expand Down
Loading