Skip to content

Add Gemini streaming#340

Merged
KaQuMiQ merged 6 commits intomainfrom
feat-gemini-streaming
Jun 23, 2025
Merged

Add Gemini streaming#340
KaQuMiQ merged 6 commits intomainfrom
feat-gemini-streaming

Conversation

@wporoslo
Copy link
Collaborator

No description provided.

@wporoslo wporoslo requested a review from KaQuMiQ June 17, 2025 15:23
@coderabbitai
Copy link

coderabbitai bot commented Jun 17, 2025

Walkthrough

The changes update the optional dependencies for the "gemini" group in the configuration file by expanding the list to include "google-api-core~=2.25,<3.0" alongside existing packages. In the source code, a function in lmm.py is renamed to correct typographical errors in both its name and internal string literals. In lmm_generation.py, the lmm_completion method is refactored to delegate streaming and non-streaming logic to two new internal methods, _completion and _completion_stream, respectively. This refactor introduces full streaming support, enhanced error handling, and improved separation of concerns within the completion logic.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🔭 Outside diff range comments (2)
src/draive/gemini/lmm.py (1)

352-367: Add docstring & make the match case-insensitive

The mapping is correct, but:

  1. A short docstring would silence the lint warning and clarify intent.
  2. Consider normalising the input (resolution.casefold()) so callers can pass "Medium"/"MEDIUM" etc. without surprising None.
-def resolution_as_media_resolution(
-    resolution: Literal["low", "medium", "high"] | Missing,
+def resolution_as_media_resolution(
+    resolution: Literal["low", "medium", "high"] | Missing,
src/draive/gemini/lmm_generation.py (1)

195-254: Rate-limit handling always retries immediately

Raising RateLimitError(retry_after=0) causes upstream middleware to retry with no delay, which can hammer the API.
If the ResourceExhausted message includes a suggested wait time, parse it, otherwise fall back to an exponential back-off.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between af01229 and 3cb7111.

📒 Files selected for processing (3)
  • pyproject.toml (1 hunks)
  • src/draive/gemini/lmm.py (2 hunks)
  • src/draive/gemini/lmm_generation.py (9 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/draive/gemini/lmm.py

[convention] 352-352: Missing function or method docstring

(C0116)

src/draive/gemini/lmm_generation.py

[convention] 1-1: Missing module docstring

(C0114)


[error] 5-5: Unable to import 'google.api_core.exceptions'

(E0401)


[error] 5-5: No name 'api_core' in module 'google'

(E0611)


[error] 46-46: Cannot import 'draive.multimodal.content' due to 'expected '(' (draive.multimodal.content, line 100)'

(E0001)


[error] 46-46: No name 'content' in module 'draive.multimodal'

(E0611)


[convention] 82-82: Missing function or method docstring

(C0116)


[refactor] 82-82: Too many arguments (7/5)

(R0913)


[refactor] 82-82: Too many local variables (16/15)

(R0914)


[refactor] 133-193: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 195-195: Too many arguments (18/5)

(R0913)


[refactor] 195-195: Too many positional arguments (18/5)

(R0917)


[refactor] 195-195: Too many local variables (32/15)

(R0914)


[refactor] 195-195: Too many branches (13/12)

(R0912)


[refactor] 333-360: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)


[refactor] 362-362: Too many arguments (18/5)

(R0913)


[refactor] 362-362: Too many positional arguments (18/5)

(R0917)


[refactor] 362-362: Too many local variables (21/15)

(R0914)


[refactor] 414-414: Too many branches (16/12)

(R0912)

🪛 GitHub Actions: CI
src/draive/gemini/lmm_generation.py

[error] 5-5: Pyright: Import "google.api_core.exceptions" could not be resolved (reportMissingImports)

🔇 Additional comments (1)
pyproject.toml (1)

38-42: Verify google-api-core~=2.25 actually exists and is compatible

~= pins you to the 2.25. series; if the latest released major-minor is lower (e.g. 2.20) or higher (e.g. 2.30), the resolver will fail.
Double-check PyPI and, if needed, relax the pin to "google-api-core>=2.25,<3" or to the latest available minor.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (2)
src/draive/gemini/lmm_generation.py (2)

139-170: Request-builder logic still duplicated – extract a helper to DRY the code.
The two huge config={…} dictionaries in _completion and _completion_stream remain almost identical, keeping cyclomatic complexity high and risking drift.
Refactor into a private _build_request_config(**params) used by both paths.


420-547: Ensure the streaming iterator is closed to avoid leaked transports.
The inner async for exits via break or exception without calling completion_stream.aclose().
Wrap the loop in try / finally and close:

-            async for completion_chunk in completion_stream:
+            try:
+                async for completion_chunk in completion_stream:
+                    ...
+            finally:
+                await completion_stream.aclose()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3cb7111 and aac9b95.

📒 Files selected for processing (1)
  • src/draive/gemini/lmm_generation.py (9 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/draive/gemini/lmm_generation.py

[convention] 1-1: Missing module docstring

(C0114)


[error] 52-52: Cannot import 'draive.multimodal.content' due to 'expected '(' (draive.multimodal.content, line 100)'

(E0001)


[error] 52-52: No name 'content' in module 'draive.multimodal'

(E0611)


[convention] 88-88: Missing function or method docstring

(C0116)


[refactor] 88-88: Too many arguments (7/5)

(R0913)


[refactor] 88-88: Too many local variables (16/15)

(R0914)


[refactor] 139-199: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 201-201: Too many arguments (18/5)

(R0913)


[refactor] 201-201: Too many positional arguments (18/5)

(R0917)


[refactor] 201-201: Too many local variables (32/15)

(R0914)


[refactor] 201-201: Too many branches (13/12)

(R0912)


[warning] 261-261: Catching previously caught exception type Exception

(W0705)


[refactor] 339-366: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)


[refactor] 368-368: Too many arguments (18/5)

(R0913)


[refactor] 368-368: Too many positional arguments (18/5)

(R0917)


[refactor] 368-368: Too many local variables (21/15)

(R0914)


[refactor] 420-420: Too many branches (16/12)

(R0912)

🪛 GitHub Actions: CI
src/draive/gemini/lmm_generation.py

[error] 6-6: Import "google.api_core.exceptions" could not be resolved (reportMissingImports)

🔇 Additional comments (1)
src/draive/gemini/lmm_generation.py (1)

5-10: Import guard looks good – thanks for fixing the optional-dependency issue.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (2)
src/draive/gemini/lmm_generation.py (2)

5-13: Optional-dependency guard implemented correctly – nice!
The TYPE_CHECKING gate and runtime fallback for ResourceExhausted resolve the missing-import issue raised earlier.


175-204: Drop redundant else after early return
Since the if stream: branch already returns, the else: block is superfluous. Removing it and de-indenting the synchronous path simplifies control flow.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aac9b95 and 6ffeea9.

📒 Files selected for processing (1)
  • src/draive/gemini/lmm_generation.py (8 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/draive/gemini/lmm_generation.py

[convention] 1-1: Missing module docstring

(C0114)


[error] 57-57: Cannot import 'draive.multimodal.content' due to 'expected '(' (draive.multimodal.content, line 100)'

(E0001)


[convention] 57-57: Import "from draive.multimodal.content import MultimodalContent, MultimodalContentElement" should be placed at the top of the module

(C0413)


[error] 57-57: No name 'content' in module 'draive.multimodal'

(E0611)


[convention] 58-58: Import "from draive.utils import RateLimitError" should be placed at the top of the module

(C0413)


[convention] 93-93: Missing function or method docstring

(C0116)


[refactor] 93-93: Too many arguments (7/5)

(R0913)


[refactor] 93-93: Too many local variables (16/15)

(R0914)


[refactor] 144-204: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 206-206: Too many arguments (18/5)

(R0913)


[refactor] 206-206: Too many positional arguments (18/5)

(R0917)


[refactor] 206-206: Too many local variables (32/15)

(R0914)


[warning] 256-256: Catching previously caught exception type Exception

(W0705)


[refactor] 334-361: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)


[refactor] 206-206: Too many branches (13/12)

(R0912)


[refactor] 363-363: Too many arguments (18/5)

(R0913)


[refactor] 363-363: Too many positional arguments (18/5)

(R0917)


[refactor] 363-363: Too many local variables (21/15)

(R0914)


[warning] 408-408: Catching previously caught exception type Exception

(W0705)


[warning] 538-540: The except handler raises immediately

(W0706)


[refactor] 411-411: Too many branches (18/12)

(R0912)


[refactor] 549-549: Too many arguments (14/5)

(R0913)

@wporoslo wporoslo force-pushed the feat-gemini-streaming branch from 6ffeea9 to 9172517 Compare June 18, 2025 15:30
@wporoslo wporoslo force-pushed the feat-gemini-streaming branch from 9172517 to 9a02e4f Compare June 18, 2025 15:32
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
src/draive/gemini/lmm.py (1)

352-365: Add a short docstring

resolution_as_media_resolution() is public (exported in __all__) but still lacks even a one-liner.
Document accepted literals and the fact that Missing|None returns None so downstream can rely on it.

♻️ Duplicate comments (3)
src/draive/gemini/lmm_generation.py (3)

181-196: Drop the redundant else

The if stream: branch returns immediately, so the else: is unnecessary noise:

-    if stream:
-        return …
-    else:
-        return …
+    if stream:
+        return …
+    return …

245-256: Ensure the gRPC/HTTP stream is closed

completion_stream is never explicitly closed; breaking out of the loop leaks the underlying transport.

-        try:
-            completion_stream = …
-
-        async def stream():
-            async for chunk in self._stream_processor(…):
-                yield chunk
+        try:
+            completion_stream = …
+
+        async def stream():
+            try:
+                async for chunk in self._stream_processor(…):
+                    yield chunk
+            finally:
+                await completion_stream.aclose()

5-10: Use a semantic fallback for ResourceExhausted

Shadowing ResourceExhausted with plain Exception loses its semantic meaning (rate-limit).
Safer fallback:

-ResourceExhausted = Exception
+class ResourceExhausted(Exception):  # pragma: no cover
+    """Stub raised when google-api-core is absent."""

so downstream except ResourceExhausted keeps working.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ffeea9 and ddae7ff.

📒 Files selected for processing (3)
  • pyproject.toml (1 hunks)
  • src/draive/gemini/lmm.py (2 hunks)
  • src/draive/gemini/lmm_generation.py (8 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/draive/gemini/lmm.py

[convention] 352-352: Missing function or method docstring

(C0116)

src/draive/gemini/lmm_generation.py

[convention] 1-1: Missing module docstring

(C0114)


[error] 53-53: Cannot import 'draive.multimodal.content' due to 'expected '(' (draive.multimodal.content, line 100)'

(E0001)


[error] 53-53: No name 'content' in module 'draive.multimodal'

(E0611)


[refactor] 89-89: Too many arguments (7/5)

(R0913)


[refactor] 89-89: Too many local variables (17/15)

(R0914)


[refactor] 181-196: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 198-198: Too many arguments (6/5)

(R0913)


[refactor] 198-198: Too many positional arguments (6/5)

(R0917)


[warning] 216-216: Catching previously caught exception type Exception

(W0705)


[refactor] 236-236: Too many arguments (6/5)

(R0913)


[refactor] 236-236: Too many positional arguments (6/5)

(R0917)


[warning] 254-254: Catching previously caught exception type Exception

(W0705)


[refactor] 297-324: Unnecessary "elif" after "break", remove the leading "el" from "elif"

(R1723)


[refactor] 265-265: Too many branches (14/12)

(R0912)


[refactor] 367-370: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 407-428: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)


[warning] 404-404: Unused argument 'is_streaming'

(W0613)


[refactor] 468-468: Too many arguments (14/5)

(R0913)

🔇 Additional comments (1)
src/draive/gemini/lmm_generation.py (1)

169-173: Verify modality names sent to the API

[m.name for m in response_modalities] yields TEXT, IMAGE, … whereas Gemini expects lowercase strings ("text", "image").
If that’s the case, use m.value.lower() or a dedicated mapping to avoid 400 replies.

@wporoslo wporoslo force-pushed the feat-gemini-streaming branch from 946e8b3 to 938d67c Compare June 18, 2025 16:18
@wporoslo
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Jun 20, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
src/draive/gemini/lmm_generation.py (1)

256-262: Ensure the streaming connection is properly closed.

The stream() generator doesn't ensure that completion_stream is closed when iteration completes or is interrupted. This can lead to resource leaks.

Wrap the stream processing in a try-finally block to ensure cleanup:

-async def stream():
-    async for chunk in self._stream_processor(
-        completion_stream, model, functions, output_decoder
-    ):
-        yield chunk
+async def stream():
+    try:
+        async for chunk in self._stream_processor(
+            completion_stream, model, functions, output_decoder
+        ):
+            yield chunk
+    finally:
+        # Ensure the stream is closed even if iteration is interrupted
+        if hasattr(completion_stream, 'aclose'):
+            await completion_stream.aclose()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 938d67c and 7cc91f1.

📒 Files selected for processing (1)
  • src/draive/gemini/lmm_generation.py (8 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/draive/gemini/lmm_generation.py

[convention] 1-1: Missing module docstring

(C0114)


[error] 55-55: Cannot import 'draive.multimodal.content' due to 'expected '(' (draive.multimodal.content, line 100)'

(E0001)


[error] 55-55: No name 'content' in module 'draive.multimodal'

(E0611)


[refactor] 91-91: Too many arguments (7/5)

(R0913)


[refactor] 91-91: Too many local variables (17/15)

(R0914)


[refactor] 199-199: Too many arguments (6/5)

(R0913)


[refactor] 199-199: Too many positional arguments (6/5)

(R0917)


[refactor] 235-235: Too many arguments (6/5)

(R0913)


[refactor] 235-235: Too many positional arguments (6/5)

(R0917)


[refactor] 296-323: Unnecessary "elif" after "break", remove the leading "el" from "elif"

(R1723)


[refactor] 264-264: Too many branches (14/12)

(R0912)


[refactor] 366-369: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 405-426: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)


[refactor] 466-466: Too many arguments (14/5)

(R0913)

🔇 Additional comments (4)
src/draive/gemini/lmm_generation.py (4)

5-12: Import guard properly implemented!

The ResourceExhausted exception is now correctly handled with a try-except fallback, ensuring the code works even when the optional google-api-core dependency is not installed.


158-197: Excellent refactoring with proper delegation pattern!

The method now cleanly delegates to specialized methods for streaming and non-streaming cases, and the common request building logic is properly extracted into _build_request. This addresses the previous concerns about code duplication and complexity.


428-463: Well-implemented tool call accumulation logic!

The method correctly handles merging partial tool calls with the same identifier, which is essential for streaming scenarios. The logic properly handles both dictionary and non-dictionary arguments.


466-509: Clean consolidation of request building logic!

The _build_request function successfully extracts and consolidates all request configuration logic, addressing the previous concerns about code duplication between streaming and non-streaming paths.

@KaQuMiQ KaQuMiQ merged commit d0ee134 into main Jun 23, 2025
5 checks passed
@KaQuMiQ KaQuMiQ deleted the feat-gemini-streaming branch June 23, 2025 09:14
@coderabbitai coderabbitai bot mentioned this pull request Jun 23, 2025
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.

2 participants