Skip to content

[Fix] stream for llm completion #345

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

Conversation

Daggx
Copy link
Contributor

@Daggx Daggx commented Mar 27, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced response handling now supports live streaming of outputs, delivering content progressively for a more dynamic experience.
    • Introduced a new StreamChat class to facilitate streaming responses.
  • Refactor
    • Updated processing logic to seamlessly manage both streaming and non-streaming response modes.

Copy link

coderabbitai bot commented Mar 27, 2025

Walkthrough

The pull request modifies the completion method in the LLMEngine class to handle responses based on the stream parameter. If stream is True, it returns a StreamChatCompletion object initialized with the response. If stream is False, it validates the response using ResponseModel.model_validate(response) and returns the validated output. Additionally, a new StreamChat class is introduced in chat_dataclass.py, which includes a stream attribute defined as a generator yielding ModelResponseStream objects.

Changes

File Change Summary
edenai_apis/.../llm_engine.py Modified completion method to conditionally handle responses: returns StreamChatCompletion when stream is True, otherwise validates and returns a full response.
edenai_apis/.../chat/chat_dataclass.py Added new class StreamChat with a stream attribute defined as a Generator[ModelResponseStream, None, None].

Sequence Diagram(s)

Loading
sequenceDiagram
    participant C as Client
    participant L as LLMEngine
    participant R as Response
    participant V as Validator

    C->>L: call completion(request, stream)
    alt stream is True
       L->>R: Receive streaming response
       R->>L: Send response part
       L-->>C: Yield content part via generator
    else stream is False
       L->>R: Receive complete response
       L->>V: Validate response
       V-->>L: Validated response
       L-->>C: Return validated response
    end

Poem

I'm a coding rabbit on a joyful spree,
Hopping through changes with glee and esprit.
Streaming carrots flow in a rhythmic beat,
While validations make the full response complete.
With whiskers twitching in digital delight,
I celebrate these changes from morning till night! 🥕🐇


🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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: 0

🧹 Nitpick comments (2)
edenai_apis/llmengine/llm_engine.py (2)

11-11: Remove unused import

The stream_chunk_builder from litellm is imported but not used in the code.

-from litellm import stream_chunk_builder
🧰 Tools
🪛 Ruff (0.8.2)

11-11: litellm.stream_chunk_builder imported but unused

Remove unused import: litellm.stream_chunk_builder

(F401)


847-854: Consider consistent return types across stream handling methods

While this implementation works, it's worth noting that other streaming methods in this class (like chat and multimodal_chat) wrap their stream responses in a ResponseType object, while this method returns the raw generator. Consider standardizing this pattern for consistency.

-            if stream:
-                streaming_response = (
-                    part.choices[0].delta.content or "" for part in response
-                )
-                return streaming_response
-            else:
-                response = ResponseModel.model_validate(response)
-                return response
+            if stream:
+                streaming_response = (
+                    part.choices[0].delta.content or "" for part in response
+                )
+                return ResponseType[str](
+                    original_response=None,
+                    standardized_response=streaming_response,
+                )
+            else:
+                response = ResponseModel.model_validate(response)
+                return response
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 398dd74 and 3eb7ab7.

📒 Files selected for processing (1)
  • edenai_apis/llmengine/llm_engine.py (2 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
edenai_apis/llmengine/llm_engine.py (1)
edenai_apis/llmengine/types/response_types.py (1)
  • ResponseModel (56-119)
🪛 Ruff (0.8.2)
edenai_apis/llmengine/llm_engine.py

11-11: litellm.stream_chunk_builder imported but unused

Remove unused import: litellm.stream_chunk_builder

(F401)

🔇 Additional comments (1)
edenai_apis/llmengine/llm_engine.py (1)

847-854: Looks good - streaming implementation works correctly

The implementation correctly handles streaming by returning a generator that yields content from each part of the response when stream=True, and returning the validated response otherwise.

@Daggx Daggx marked this pull request as draft March 28, 2025 08:49
@Daggx Daggx marked this pull request as ready for review March 31, 2025 14:22
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: 0

🧹 Nitpick comments (1)
edenai_apis/features/llm/chat/chat_dataclass.py (1)

217-218: LGTM! Consider adding documentation

The new StreamChat class is well-structured and correctly implements the generator pattern for streaming responses. The proper type annotation Generator[ModelResponseStream, None, None] ensures type safety.

For better maintainability, consider adding a class docstring explaining its purpose and relationship to the streaming functionality in the LLMEngine.

 class StreamChat(BaseModel):
+    """
+    A model for streaming chat completions.
+    
+    Attributes:
+        stream: Generator yielding ModelResponseStream objects for incremental responses.
+    """
     stream: Generator[ModelResponseStream, None, None]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 3eb7ab7 and febdea3.

📒 Files selected for processing (2)
  • edenai_apis/features/llm/chat/chat_dataclass.py (2 hunks)
  • edenai_apis/llmengine/llm_engine.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • edenai_apis/llmengine/llm_engine.py
🔇 Additional comments (1)
edenai_apis/features/llm/chat/chat_dataclass.py (1)

1-1: LGTM! Necessary imports added for stream functionality

The added imports of Generator from typing and ModelResponseStream from litellm directly support the new streaming functionality being introduced.

Also applies to: 4-4

@juandavidcruzgomez juandavidcruzgomez merged commit f9be9a6 into master Mar 31, 2025
3 of 4 checks passed
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.

None yet

2 participants