Skip to content

#113 Replace StreamingChatLanguageModelReply.Error with throwing exception#178

Merged
kpavlov merged 1 commit intomainfrom
flow-errors
Jul 20, 2025
Merged

#113 Replace StreamingChatLanguageModelReply.Error with throwing exception#178
kpavlov merged 1 commit intomainfrom
flow-errors

Conversation

@kpavlov
Copy link
Owner

@kpavlov kpavlov commented Jul 20, 2025

Removed the Error type from StreamingChatLanguageModelReply and its usage. Currently the error was being emitted twice. Once as an exception, and once as data. We should avoid emitting an event twice, since it only occurs once. It's possible for the user to manually transform the exception into a value using catch { emit(...) }

Closes #113

Integrated changes from #117 by @nomisRev :

Removed the Error type from StreamingChatLanguageModelReply and its usage. Currently the error was being emitted twice. Once as an exception, and once as data. We should avoid emitting an event twice, since it only occurs once. It's possible for the user to manually transform the exception into a value using catch { emit(...) } as demonstrated in my other PR.

- Removed duplicated dependency from `pom.xml`.
- Simplified lambda expressions in `ChatMemoryServiceExtensions`.
- Consolidated assertion imports and improved flow testing in `ServiceWithFlowTest`.
- Enhanced formatting and readability across sample classes and tests.
- Removed unused and redundant code from `StreamingChatModelExtensions` and other files.
@codacy-production
Copy link

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
+0.02% (target: -1.00%) 0.00%
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (319c6b4) 740 578 78.11%
Head commit (1e790d1) 736 (-4) 575 (-3) 78.13% (+0.02%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#178) 2 0 0.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

@codecov
Copy link

codecov bot commented Jul 20, 2025

Codecov Report

Attention: Patch coverage is 0% with 2 lines in your changes missing coverage. Please review.

Project coverage is 68.83%. Comparing base (319c6b4) to head (1e790d1).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...tlin/service/memory/ChatMemoryServiceExtensions.kt 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #178      +/-   ##
==========================================
- Coverage   68.86%   68.83%   -0.04%     
==========================================
  Files          29       29              
  Lines         742      738       -4     
  Branches      132      132              
==========================================
- Hits          511      508       -3     
+ Misses        164      163       -1     
  Partials       67       67              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai
Copy link

coderabbitai bot commented Jul 20, 2025

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Removed duplicate test dependency to streamline project setup.
    • Updated error handling in streaming chat flows to propagate exceptions instead of emitting error replies.
  • Style

    • Improved code formatting and consistency across multiple files for better readability.
    • Reformatted function signatures and parameter lists for clarity.
  • Tests

    • Adjusted tests to expect exceptions for error scenarios in streaming chat flows.
    • Enhanced test formatting and assertions for improved reliability.

Walkthrough

This update primarily simplifies error handling in the StreamingChatModelExtensions.kt by removing the explicit error reply emission in the streaming chat flow. The corresponding test is updated to expect exceptions directly rather than error reply objects. Additional changes include dependency deduplication, code formatting improvements, and minor stylistic adjustments across several Kotlin source and sample files.

Changes

File(s) Change Summary
langchain4j-kotlin/pom.xml Removed duplicate test dependency entry for io.kotest:kotest-assertions-core-jvm.
langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/model/chat/StreamingChatModelExtensions.kt Removed StreamingChatModelReply.Error class and error emission; now errors are logged and the flow closes.
langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/service/ReflectionVariableResolver.kt Reformatted code: removed an extra blank line and split function parameters for readability.
langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/service/memory/ChatMemoryServiceExtensions.kt Simplified suspend function bodies to single-expression style; no logic changes.
langchain4j-kotlin/src/test/kotlin/me/kpavlov/langchain4j/kotlin/adapters/ServiceWithFlowTest.kt Updated test to expect exceptions instead of error reply objects in flow error scenarios.
langchain4j-kotlin/src/test/kotlin/me/kpavlov/langchain4j/kotlin/model/chat/StreamingChatModelIT.kt Removed import and usage of fail() for error replies; no other logic changes.
langchain4j-kotlin/src/test/kotlin/me/kpavlov/langchain4j/kotlin/service/ServiceWithPromptTemplatesTest.kt Reformatted test function for consistent indentation; no logic changes.
samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/AsyncAiServiceExample.kt Reformatted parameter lists and assignments for readability; no logic changes.
samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/Environment.kt Reformatted model initialization to multi-line style; no logic changes.
samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/OpenAiChatModelExample.kt Added trailing comma to constructor parameter list; no logic changes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant StreamingChatModel
    participant Flow

    Client->>StreamingChatModel: Start chatFlow()
    StreamingChatModel->>Flow: Emit PartialResponse(s)
    Note over Flow: On error, log and close flow (no error reply emitted)
    Flow-->>Client: PartialResponse(s)
    Flow--x Client: Exception thrown on error
Loading

Poem

In the warren, code flows anew,
Errors now leap, not just pass through.
Replies are clear, no Error disguise,
Just logs and exceptions—no need for surprise!
Formatting neat, dependencies light,
The code hops forward, ever bright.
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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: 0

🧹 Nitpick comments (4)
langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/service/ReflectionVariableResolver.kt (1)

113-116: Signature tightened – consider updating KDoc/nullable contract

args is now non-nullable in findMemoryIdParameter.
The caller already guards against null, so the change is safe and removes a redundant null-check inside this helper. Just make sure any internal documentation (or IntelliJ hints) still claiming the parameter is nullable is updated accordingly, otherwise readers might get confused.

langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/service/memory/ChatMemoryServiceExtensions.kt (1)

21-25: Consistent style – consider dropping explicit public

Kotlin defaults to public; you can omit the modifier for brevity here (as done in other files). Purely stylistic – feel free to ignore.

samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/Environment.kt (1)

9-14: Consider lazy-initialising the model constant

Creating the ChatModel at file-load time will execute builder logic (and potentially hit network/env access) on every import, even when the model is unused (e.g. in unit tests). A small tweak keeps sample code equally simple while deferring the cost until the first use:

-val model: ChatModel =
-    OpenAiChatModel
-        .builder()
-        .modelName("gpt-4o-nano")
-        .apiKey(testEnv["OPENAI_API_KEY"])
-        .build()
+val model: ChatModel by lazy {
+    OpenAiChatModel
+        .builder()
+        .modelName("gpt-4o-nano")
+        .apiKey(testEnv["OPENAI_API_KEY"])
+        .build()
+}

No functional change, just safer module initialisation and slightly faster test start-up.

samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/AsyncAiServiceExample.kt (1)

19-25: Optional: extract builder chain for reuse / testability

The fluent chain building assistant is perfectly valid, but if multiple samples (or production code) create identical assistants, consider wrapping the chain in a helper to improve reuse and make mocking easier:

private fun buildAsyncAssistant(model: ChatModel): AsyncAssistant =
    createAiService(
        serviceClass = AsyncAssistant::class.java,
        factory = AsyncAiServicesFactory(),
    )
        .chatModel(model)
        .systemMessageProvider { "You are a helpful software engineer" }
        .build()

Then:

val assistant = buildAsyncAssistant(model)

Purely optional – feel free to skip if this is the only call site.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 319c6b4 and 1e790d1.

📒 Files selected for processing (10)
  • langchain4j-kotlin/pom.xml (0 hunks)
  • langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/model/chat/StreamingChatModelExtensions.kt (0 hunks)
  • langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/service/ReflectionVariableResolver.kt (1 hunks)
  • langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/service/memory/ChatMemoryServiceExtensions.kt (1 hunks)
  • langchain4j-kotlin/src/test/kotlin/me/kpavlov/langchain4j/kotlin/adapters/ServiceWithFlowTest.kt (2 hunks)
  • langchain4j-kotlin/src/test/kotlin/me/kpavlov/langchain4j/kotlin/model/chat/StreamingChatModelIT.kt (1 hunks)
  • langchain4j-kotlin/src/test/kotlin/me/kpavlov/langchain4j/kotlin/service/ServiceWithPromptTemplatesTest.kt (1 hunks)
  • samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/AsyncAiServiceExample.kt (1 hunks)
  • samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/Environment.kt (1 hunks)
  • samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/OpenAiChatModelExample.kt (1 hunks)
💤 Files with no reviewable changes (2)
  • langchain4j-kotlin/pom.xml
  • langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/model/chat/StreamingChatModelExtensions.kt
🧰 Additional context used
🧬 Code Graph Analysis (1)
samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/AsyncAiServiceExample.kt (1)
langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/service/AiServicesExtensions.kt (1)
  • createAiService (10-13)
🔇 Additional comments (9)
langchain4j-kotlin/src/main/kotlin/me/kpavlov/langchain4j/kotlin/service/memory/ChatMemoryServiceExtensions.kt (1)

16-20: Nice expression-body rewrite

Converting withContext blocks to a single-line expression improves readability without altering behaviour. LGTM.

langchain4j-kotlin/src/test/kotlin/me/kpavlov/langchain4j/kotlin/service/ServiceWithPromptTemplatesTest.kt (1)

21-60: LGTM! Code formatting improvements enhance readability.

The reformatting improves code readability without changing any functional logic. The test continues to properly verify that the AiServices builder correctly processes system and user prompt templates.

langchain4j-kotlin/src/test/kotlin/me/kpavlov/langchain4j/kotlin/model/chat/StreamingChatModelIT.kt (1)

66-75: LGTM! Error handling change aligns with PR objectives.

The removal of StreamingChatModelReply.Error case handling is correct. With the new approach, errors will be thrown as exceptions rather than emitted as error replies, making the error handling more straightforward and preventing duplicate error emissions.

langchain4j-kotlin/src/test/kotlin/me/kpavlov/langchain4j/kotlin/adapters/ServiceWithFlowTest.kt (2)

13-20: LGTM! New imports support the updated error handling approach.

The added imports (shouldThrow, shouldHaveSize, shouldBe, shouldBeInstanceOf, onEach) are appropriate for the new test logic that expects exceptions instead of error replies.


153-173: LGTM! Test correctly validates the new exception-based error handling.

The test has been properly updated to align with the new error handling approach:

  1. Correct exception expectation: Uses shouldThrow<Exception> to expect the flow to throw when an error occurs
  2. Proper token collection: Collects partial responses using onEach before the error is thrown
  3. Comprehensive assertions: Verifies both the exception message and the collected tokens

This change successfully validates that errors are now propagated as exceptions rather than being emitted as StreamingChatModelReply.Error objects, which aligns perfectly with the PR objectives.

samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/OpenAiChatModelExample.kt (1)

11-11: Trailing comma 👍

Using a trailing comma after the constructor parameter improves future diffs and is supported from Kotlin 1.4+. Looks good.

samples/src/main/kotlin/me/kpavlov/langchain4j/kotlin/samples/AsyncAiServiceExample.kt (3)

10-12: Readable multi-line signature

The reformatted suspend fun askQuestion(..., ) with a trailing comma is clear and consistent with Kotlin style guidelines.


16-16: Constructor trailing comma

Same remark as above – improves diff hygiene, no issues.


28-28: Trailing comma in call

The trailing comma after the argument is fine and keeps calls consistent with the rest of the file.

@kpavlov kpavlov merged commit 42478a8 into main Jul 20, 2025
6 of 8 checks passed
@kpavlov kpavlov deleted the flow-errors branch July 20, 2025 12:05
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.

Flow extension potentially dropping messages

1 participant