From b047371941e2c005f6cda9a45946f0027e686bc2 Mon Sep 17 00:00:00 2001 From: Ken Kousen Date: Tue, 10 Jun 2025 12:32:00 -0400 Subject: [PATCH] - Bump `langchain4j` version to `1.1.0-SNAPSHOT` in `pom.xml` - Add `LambdaStreamingExamples` showcasing streaming response handling with OpenAI models --- other-examples/pom.xml | 2 +- .../main/java/LambdaStreamingExamples.java | 48 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 other-examples/src/main/java/LambdaStreamingExamples.java diff --git a/other-examples/pom.xml b/other-examples/pom.xml index b6f12c86..a4bf2337 100644 --- a/other-examples/pom.xml +++ b/other-examples/pom.xml @@ -19,7 +19,7 @@ dev.langchain4j langchain4j - 1.0.1 + 1.1.0-SNAPSHOT diff --git a/other-examples/src/main/java/LambdaStreamingExamples.java b/other-examples/src/main/java/LambdaStreamingExamples.java new file mode 100644 index 00000000..c443f85c --- /dev/null +++ b/other-examples/src/main/java/LambdaStreamingExamples.java @@ -0,0 +1,48 @@ +import static dev.langchain4j.model.LambdaStreamingResponseHandler.onPartialResponseAndErrorBlocking; +import static dev.langchain4j.model.LambdaStreamingResponseHandler.onPartialResponseBlocking; + +import dev.langchain4j.model.chat.StreamingChatModel; +import dev.langchain4j.model.openai.OpenAiChatModelName; +import dev.langchain4j.model.openai.OpenAiStreamingChatModel; + + +public class LambdaStreamingExamples { + + static class LambdaChatModelExample { + + public static void main(String[] args) throws InterruptedException { + // Note: "demo" key does not support streaming, please use your own key. + StreamingChatModel model = OpenAiStreamingChatModel.builder() + .apiKey(ApiKeys.OPENAI_API_KEY) + .modelName(OpenAiChatModelName.GPT_4_1_NANO) + .build(); + + // Example of streaming a response with partial updates + onPartialResponseBlocking(model, "Why is the sky blue?", System.out::print); + + // Example of streaming a response with error handling but no error expected + onPartialResponseAndErrorBlocking( + model, + "Explain quantum physics", + System.out::print, + error -> System.err.println("Error: " + error.getMessage())); + } + } + + static class LambdaChatModelErrorExample { + + public static void main(String[] args) throws InterruptedException { + StreamingChatModel invalidModel = OpenAiStreamingChatModel.builder() + .apiKey("demo") + .modelName(OpenAiChatModelName.GPT_4_1_NANO) + .build(); + + onPartialResponseAndErrorBlocking( + invalidModel, + "'demo' key does not support streaming", + System.out::print, + error -> System.err.println("Error caught: " + error.getMessage())); + System.out.println("\nError handling test completed!"); + } + } +}