Skip to content

fix: skip nil responses in generateContent - #630

Merged
wolo-lab merged 3 commits into
google:mainfrom
koriyoshi2041:fix/nil-pointer-base-flow
Sep 28, 2026
Merged

wolo-lab merged 3 commits into
google:mainfrom
koriyoshi2041:fix/nil-pointer-base-flow

Conversation

@koriyoshi2041

Copy link
Copy Markdown
Contributor

Summary

Adds nil checks for LLMResponse in base_flow.go to prevent nil pointer dereference panics when a model yields a nil response.

Problem: In callLLM() and generateContent(), the code accesses resp.LLMResponse and resp.Content without checking for nil. When a model returns an empty stream or yields nil, this causes a panic.

Fix:

  • Added nil guard for resp.LLMResponse in callLLM() (line ~337) — skips the iteration
  • Added nil guard for resp in generateContent() (line ~413) — skips nil responses

Related to #586.

Test plan

  • Added TestCallLLMNilResponse — verifies no panic when model yields nil
  • go test ./internal/llminternal/... passes
  • go vet ./... passes

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the robustness of the LLM interaction logic by introducing critical nil checks. It resolves a potential stability issue where the application could crash due to nil pointer dereferences if an LLM model returned an unexpected nil response. The changes ensure that the system gracefully handles such scenarios, improving overall reliability.

Highlights

  • Nil Pointer Dereference Fix: Implemented nil checks for LLMResponse within the callLLM function and for resp within the generateContent function in base_flow.go to prevent panics when a model yields a nil response or an empty stream.
  • New Test Case: Added TestCallLLMNilResponse in base_flow_test.go to specifically verify that the system does not panic when an LLM model returns a nil response, addressing a regression related to issue Nil pointer dereference in base_flow.go: runconfig.FromContext returns nil #586.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • internal/llminternal/base_flow.go
    • Added a nil guard for resp.LLMResponse in callLLM() to skip iteration if the response is nil.
    • Added a nil guard for resp in generateContent() to skip nil responses before further processing.
  • internal/llminternal/base_flow_test.go
    • Imported context, iter, and runconfig packages.
    • Added a mockModel struct to simulate LLM behavior for testing.
    • Implemented TestCallLLMNilResponse to verify that callLLM does not panic when a model yields a nil LLMResponse.
Activity
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@google-cla

google-cla Bot commented Mar 6, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses a potential nil pointer dereference in base_flow.go by adding nil checks in callLLM and generateContent. The change in generateContent correctly prevents a panic when a model yields a nil response, and a regression test has been added to verify this fix. My review suggests that the corresponding nil check added in callLLM may be redundant due to the fix in generateContent and could be removed for code clarity.

Comment thread internal/llminternal/base_flow.go Resolved
@koriyoshi2041
koriyoshi2041 force-pushed the fix/nil-pointer-base-flow branch 2 times, most recently from 920857b to edf91d3 Compare May 31, 2026 09:27
@koriyoshi2041

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main to resolve the conflict — it was a textual clash in base_flow_test.go with the newly added TestPreprocess_Toolset, plus callLLM gained an artifactDelta parameter upstream which the regression test now passes. Both tests pass and go vet/gofmt are clean.

@koriyoshi2041
koriyoshi2041 force-pushed the fix/nil-pointer-base-flow branch from edf91d3 to 622417e Compare June 8, 2026 08:13
@koriyoshi2041

Copy link
Copy Markdown
Contributor Author

Rebased this onto current main and tightened the patch based on the earlier review note: the extra callLLM nil guard is gone now, so the fix lives at the generateContent boundary and the regression test still covers the callLLM entry point.

Checked locally:

go test ./internal/llminternal
go vet ./internal/llminternal
git diff --check

@karolpiotrowicz karolpiotrowicz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apologies for the long silence here — this sat without a maintainer review far longer than it should have.

The change still applies. generateContent on main at 058933d still reaches base_flow.go:944 — } else if !resp.Partial { — with no nil check, and nothing fixed it in the meantime. Driving a third-party model.LLM that yields (nil, nil) through the public runner: on main the invocation ends with node "a" panicked: runtime error: invalid memory address or nil pointer dereference, and with your patch it does not. A mixed [nil, final] stream still delivers the final response, so the continue does what it should. The guard is at the right layer.

Three things before it can go in.

Rebase. base_flow.go merges cleanly, but base_flow_test.go conflicts — main has grown a lot of tests since your base and the module moved to google.golang.org/adk/v2. It is a plain end-of-file collision, so it should be quick.

A trailing nil after a partial response wipes the span. base_flow.go:939 does lastResponse = *response before your guard runs, so a skipped nil overwrites the last good response and the deferred span-end records nothing. On a [partial(prompt=10, candidates=20), nil] stream the generate_content span comes out with empty input and output token attributes, where the same stream without the trailing nil records 10 and 20. [final, nil] is unaffected — a non-partial response has already closed the span — so this is specifically the streaming-then-nil shape.

The fix is to move the check above line 939, but please use the conjunct form:

if resp == nil && err == nil {
    continue
}

The && err == nil matters more than it looks. Every model in the tree reports failure as yield(nil, err), so a bare if resp == nil { continue } hoisted above line 939 skips the error branch entirely — I ran it, and a model returning an error produced zero yields with no error reaching the caller. Your current placement does not have that problem. It is only the hoist that needs the guard on err.

The test never runs its assertion. Once the fix works callLLM yields nothing, so the loop body — and the only t.Fatalf — is dead. It would pass equally if continue were return, which would drop every response after a nil. It is a real regression test for the panic, so it earns its place, but asserting the yielded count and adding the [nil, final] case would pin the skip-and-keep-consuming behaviour.

Two smaller ones. The comment cites #586, but that was the runconfig.FromContext nil, fixed separately and already referenced in this same file at base_flow.go:842 — better to describe the real trigger, since no in-tree model can produce a nil response and what this defends against is a third-party model.LLM. And the new mockModel duplicates mockModelForTest in the same package, so you can drop it.

One thing I checked and it is fine: the skipped nil produces a run with no events and a nil error, which looks like it hides the failure. main already behaves that way for a non-nil content-less response — base_flow.go:652 skips those deliberately, mirroring adk-python's base_llm_flow.py:1484. Your change routes one more input into an outcome the framework already treats as normal. A log line on the skip would be a nice touch, not a blocker.

Not yours to fix, but worth knowing: the same "a continue bypasses the consumer's only stop signal" shape already exists at base_flow.go:652, and a model emitting content-less responses without bound will spin there on main today. I will raise that separately.

Finally, the title still says callLLM — since your June revision the fix lives entirely in generateContent.

@koriyoshi2041
koriyoshi2041 force-pushed the fix/nil-pointer-base-flow branch from 622417e to 8613b7c Compare September 3, 2026 07:23
@koriyoshi2041 koriyoshi2041 changed the title fix: guard against nil LLMResponse in base_flow callLLM fix: skip nil responses in generateContent Sep 3, 2026
@koriyoshi2041

Copy link
Copy Markdown
Contributor Author

Addressed all requested changes and rebased onto current main:

  • moved the nil guard ahead of response wrapping and telemetry state updates, using resp == nil && err == nil so model errors still propagate;
  • reused mockModelForTest and asserted both zero yields for [nil] and continued consumption for [nil, final];
  • added telemetry coverage for [partial, nil], preserving the partial response's token attributes when the deferred span closes;
  • updated the PR title to reflect the generateContent boundary.

Verified locally with go test ./internal/llminternal, go vet ./internal/llminternal, and git diff --check.

@karolpiotrowicz karolpiotrowicz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The revision does everything I asked, and the conjunct form is exactly right.

I re-ran the checks against the rebased head (8613b7c) on top of current main (ffddb2a). The span keeps the partial's token attributes now — a [partial(prompt=10, candidates=20), nil] stream records 10 and 20 where it previously recorded nothing — model errors still reach the caller, and [nil, final] still delivers the final response.

The part worth calling out is the test work, which is stronger than what I asked for. I mutated the guard three ways in a scratch copy and re-ran your committed suite against each:

guard deleted            -> TestCallLLMSkipsNilResponseAndContinues/nil_only panics
guard back in the old spot -> TestGenerateContentTracingNoFinalResponse: expected input tokens 10, got
guard reduced to bare resp == nil -> TestGenerateContentTracingError: expected span status "Error", got "Unset"

All three regressions are now caught by tests in the repo. In particular that last one means someone can no longer quietly simplify the condition back to resp == nil and swallow every model error — that was the gap I was most worried about leaving open, and appending the trailing yield(nil, nil) to the existing telemetry test closes it neatly.

Three small things, none of them blocking, all optional.

The new table has no error column, so the (nil, err) case cannot be written in it. That case is covered, but only indirectly, by the span-status assertion in TestGenerateContentTracingError. A wantErr field and a third row asserting that callLLM yields exactly one item carrying the error would make the guarantee direct rather than inferred from telemetry.

The nil then final row asserts a count of one but not that the surviving response is the one carrying "done". It happens not to matter today, since the obvious wrong implementation would panic rather than yield the wrong item, but capturing the response and comparing its text would make the test say what its name claims.

The comment reads "may yield an empty response" while the guard tests nil-ness. A non-nil &model.LLMResponse{} trailing a partial still blanks the span — I checked, and it does that on main too, so it is not something this PR introduced and not yours to fix here. Saying "a nil response" would just keep the comment matched to the code.

One thing I want to be explicit about, since I raised it last time and it is still true: continue skips the yield, so a model emitting nils without bound still cannot be stopped by the consumer. I said it was not yours to fix and I stand by that — the identical shape already exists at base_flow.go:652 and is reachable on main today with a more ordinary producer. I will file that separately rather than hold this up for it.

CI is green across the board, including apidiff. From my side this is ready.

@wolo-lab
wolo-lab merged commit 8b0de7b into google:main Sep 28, 2026
14 checks passed
kdroste-google pushed a commit to kdroste-google/adk-go that referenced this pull request Sep 29, 2026
wolo-lab added a commit that referenced this pull request Oct 2, 2026
…1630, #630) (#1692)

* fix(internal/utils): skip nil Parts in the Parts accessors (#1556)

(cherry picked from commit f4666ec)

* fix(llminternal): build arrays when assembling streamed function call arguments (#1630)

(cherry picked from commit d6bdb0d)

* fix: skip empty model responses in generateContent (#630)

(cherry picked from commit 8b0de7b)
tongxury pushed a commit to tongxury/adk-go that referenced this pull request Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants