|
| 1 | +package com.langchainbeam.example; |
| 2 | + |
| 3 | +import org.apache.beam.runners.flink.FlinkPipelineOptions; |
| 4 | +import org.apache.beam.runners.flink.FlinkRunner; |
| 5 | +import org.apache.beam.sdk.Pipeline; |
| 6 | +import org.apache.beam.sdk.io.TextIO; |
| 7 | +import org.apache.beam.sdk.options.PipelineOptionsFactory; |
| 8 | +import org.apache.beam.sdk.transforms.DoFn; |
| 9 | +import org.apache.beam.sdk.transforms.ParDo; |
| 10 | + |
| 11 | +import com.langchainbeam.LangchainBeam; |
| 12 | +import com.langchainbeam.LangchainModelHandler; |
| 13 | +import com.langchainbeam.model.LangchainBeamOutput; |
| 14 | +import com.langchainbeam.model.openai.OpenAiModelOptions; |
| 15 | + |
| 16 | +// Run sentiment analysis pipeline on Apache Flink using flink runner |
| 17 | +public class ApacheFlinkExample { |
| 18 | + |
| 19 | + public static void main(String[] args) { |
| 20 | + String prompt = "Categorize the product review as Positive or Negative."; |
| 21 | + |
| 22 | + String apiKey = System.getenv("OPENAI_API_KEY"); |
| 23 | + |
| 24 | + // Create model options with the model and its parameters |
| 25 | + OpenAiModelOptions modelOptions = OpenAiModelOptions.builder() |
| 26 | + .modelName("gpt-4o-mini") |
| 27 | + .apiKey(apiKey) |
| 28 | + .build(); |
| 29 | + |
| 30 | + // Create Apache flink pipeline options |
| 31 | + FlinkPipelineOptions options = PipelineOptionsFactory.as(FlinkPipelineOptions.class); |
| 32 | + options.setJobName("product-review-job"); |
| 33 | + options.setRunner(FlinkRunner.class); |
| 34 | + |
| 35 | + // Set Flink-specific options |
| 36 | + options.setParallelism(2); |
| 37 | + options.setMaxParallelism(16); |
| 38 | + |
| 39 | + // create beam pipeline |
| 40 | + Pipeline p = Pipeline.create(options); |
| 41 | + |
| 42 | + // create model handler |
| 43 | + LangchainModelHandler handler = new LangchainModelHandler(modelOptions, prompt); |
| 44 | + |
| 45 | + p.apply(TextIO.read().from("/home/ganesh/Downloads/product_reviews.csv"))// load data |
| 46 | + .apply(LangchainBeam.run(handler)) // apply the LangchainBeam transform. |
| 47 | + .apply(ParDo.of(new DoFn<LangchainBeamOutput, Void>() { |
| 48 | + |
| 49 | + @ProcessElement |
| 50 | + public void processElement(@Element LangchainBeamOutput out) { |
| 51 | + System.out |
| 52 | + .println("Model Output: " + out.getOutput() + "Input Element " + out.getInputElement()); |
| 53 | + } |
| 54 | + })); |
| 55 | + |
| 56 | + p.run(); |
| 57 | + } |
| 58 | +} |
0 commit comments