Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion sdks/java/ml/inference/openai/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,17 @@
*/
plugins {
id 'org.apache.beam.module'
id 'java'
}

applyJavaNature(
automaticModuleName: 'org.apache.beam.sdk.ml.inference.openai',
requireJavaVersion: JavaVersion.VERSION_11
)
provideIntegrationTestingDependencies()
enableJavaPerformanceTesting()

description = "Apache Beam :: SDKs :: Java :: ML :: Inference :: OpenAI"
ext.summary = "OpenAI model handler for remote inference"

dependencies {
implementation project(":sdks:java:ml:inference:remote")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
Expand All @@ -26,20 +26,20 @@
import com.openai.core.JsonSchemaLocalValidation;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.StructuredResponseCreateParams;
import org.apache.beam.sdk.ml.inference.remote.BaseModelHandler;
import org.apache.beam.sdk.ml.inference.remote.PredictionResult;

import java.util.List;
import java.util.stream.Collectors;
import org.apache.beam.sdk.ml.inference.remote.BaseModelHandler;
import org.apache.beam.sdk.ml.inference.remote.PredictionResult;

/**
* Model handler for OpenAI API inference requests.
*
* <p>This handler manages communication with OpenAI's API, including client initialization,
* request formatting, and response parsing. It uses OpenAI's structured output feature to
* ensure reliable input-output pairing.
* <p>This handler manages communication with OpenAI's API, including client initialization, request
* formatting, and response parsing. It uses OpenAI's structured output feature to ensure reliable
* input-output pairing.
*
* <h3>Usage</h3>
*
* <pre>{@code
* OpenAIModelParameters params = OpenAIModelParameters.builder()
* .apiKey("sk-...")
Expand All @@ -55,10 +55,10 @@
* .withParameters(params)
* );
* }</pre>
*
*/
@SuppressWarnings("nullness")
public class OpenAIModelHandler
implements BaseModelHandler<OpenAIModelParameters, OpenAIModelInput, OpenAIModelResponse> {
implements BaseModelHandler<OpenAIModelParameters, OpenAIModelInput, OpenAIModelResponse> {

private transient OpenAIClient client;
private OpenAIModelParameters modelParameters;
Expand All @@ -67,69 +67,67 @@ public class OpenAIModelHandler
/**
* Initializes the OpenAI client with the provided parameters.
*
* <p>This method is called once during setup. It creates an authenticated
* OpenAI client using the API key from the parameters.
* <p>This method is called once during setup. It creates an authenticated OpenAI client using the
* API key from the parameters.
*
* @param parameters the configuration parameters including API key and model name
*/
@Override
public void createClient(OpenAIModelParameters parameters) {
this.modelParameters = parameters;
this.client = OpenAIOkHttpClient.builder()
.apiKey(this.modelParameters.getApiKey())
.build();
this.client = OpenAIOkHttpClient.builder().apiKey(this.modelParameters.getApiKey()).build();
this.objectMapper = new ObjectMapper();
}

/**
* Performs inference on a batch of inputs using the OpenAI Client.
*
* <p>This method serializes the input batch to JSON string, sends it to OpenAI with structured
* output requirements, and parses the response into {@link PredictionResult} objects
* that pair each input with its corresponding output.
* output requirements, and parses the response into {@link PredictionResult} objects that pair
* each input with its corresponding output.
*
* @param input the list of inputs to process
* @return an iterable of model results and input pairs
*/
@Override
public Iterable<PredictionResult<OpenAIModelInput, OpenAIModelResponse>> request(List<OpenAIModelInput> input) {
public Iterable<PredictionResult<OpenAIModelInput, OpenAIModelResponse>> request(
List<OpenAIModelInput> input) {

try {
// Convert input list to JSON string
String inputBatch =
objectMapper.writeValueAsString(
input.stream()
.map(OpenAIModelInput::getModelInput)
.collect(Collectors.toList()));
objectMapper.writeValueAsString(
input.stream().map(OpenAIModelInput::getModelInput).collect(Collectors.toList()));
// Build structured response parameters
StructuredResponseCreateParams<StructuredInputOutput> clientParams = ResponseCreateParams.builder()
.model(modelParameters.getModelName())
.input(inputBatch)
.text(StructuredInputOutput.class, JsonSchemaLocalValidation.NO)
.instructions(modelParameters.getInstructionPrompt())
.build();
StructuredResponseCreateParams<StructuredInputOutput> clientParams =
ResponseCreateParams.builder()
.model(modelParameters.getModelName())
.input(inputBatch)
.text(StructuredInputOutput.class, JsonSchemaLocalValidation.NO)
.instructions(modelParameters.getInstructionPrompt())
.build();

// Get structured output from the model
StructuredInputOutput structuredOutput = client.responses()
.create(clientParams)
.output()
.stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.findFirst()
.orElse(null);
StructuredInputOutput structuredOutput =
client.responses().create(clientParams).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.findFirst()
.orElse(null);

if (structuredOutput == null || structuredOutput.responses == null) {
throw new RuntimeException("Model returned no structured responses");
}

// return PredictionResults
return structuredOutput.responses.stream()
.map(response -> PredictionResult.create(
OpenAIModelInput.create(response.input),
OpenAIModelResponse.create(response.output)))
.collect(Collectors.toList());
.map(
response ->
PredictionResult.create(
OpenAIModelInput.create(response.input),
OpenAIModelResponse.create(response.output)))
.collect(Collectors.toList());

} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize input batch", e);
Expand All @@ -154,13 +152,12 @@ public static class Response {
/**
* Schema class for structured output containing multiple responses.
*
* <p>This class defines the expected JSON structure for OpenAI's structured output,
* ensuring reliable parsing of batched inference results.
* <p>This class defines the expected JSON structure for OpenAI's structured output, ensuring
* reliable parsing of batched inference results.
*/
public static class StructuredInputOutput {
@JsonProperty(required = true)
@JsonPropertyDescription("Array of input-output pairs")
public List<Response> responses;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,28 @@
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.ml.inference.openai;

import org.apache.beam.sdk.ml.inference.remote.BaseInput;

/**
* Input for OpenAI model inference requests.
*
* <p>This class encapsulates text input to be sent to OpenAI models.
*
* <h3>Example Usage</h3>
*
* <pre>{@code
* OpenAIModelInput input = OpenAIModelInput.create("Translate to French: Hello");
* String text = input.getModelInput(); // "Translate to French: Hello"
Expand Down Expand Up @@ -59,5 +61,4 @@ public String getModelInput() {
public static OpenAIModelInput create(String input) {
return new OpenAIModelInput(input);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
Expand All @@ -22,10 +22,11 @@
/**
* Configuration parameters required for OpenAI model inference.
*
* <p>This class encapsulates all configuration needed to initialize and communicate with
* OpenAI's API, including authentication credentials, model selection, and inference instructions.
* <p>This class encapsulates all configuration needed to initialize and communicate with OpenAI's
* API, including authentication credentials, model selection, and inference instructions.
*
* <h3>Example Usage</h3>
*
* <pre>{@code
* OpenAIModelParameters params = OpenAIModelParameters.builder()
* .apiKey("sk-...")
Expand All @@ -36,6 +37,7 @@
*
* @see OpenAIModelHandler
*/
@SuppressWarnings("nullness")
public class OpenAIModelParameters implements BaseModelParameters {

private final String apiKey;
Expand Down Expand Up @@ -64,14 +66,12 @@ public static Builder builder() {
return new Builder();
}


public static class Builder {
private String apiKey;
private String modelName;
private String instructionPrompt;

private Builder() {
}
private Builder() {}

/**
* Sets the OpenAI API key for authentication.
Expand All @@ -93,9 +93,8 @@ public Builder modelName(String modelName) {
return this;
}
/**
* Sets the instruction prompt for the model.
* This prompt provides context or instructions to the model about how to process
* the input text.
* Sets the instruction prompt for the model. This prompt provides context or instructions to
* the model about how to process the input text.
*
* @param prompt the instruction text (required)
*/
Expand All @@ -104,9 +103,7 @@ public Builder instructionPrompt(String prompt) {
return this;
}

/**
* Builds the {@link OpenAIModelParameters} instance.
*/
/** Builds the {@link OpenAIModelParameters} instance. */
public OpenAIModelParameters build() {
return new OpenAIModelParameters(this);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
Expand All @@ -21,9 +21,11 @@

/**
* Response from OpenAI model inference results.
*
* <p>This class encapsulates the text output returned from OpenAI models..
*
* <h3>Example Usage</h3>
*
* <pre>{@code
* OpenAIModelResponse response = OpenAIModelResponse.create("Bonjour");
* String output = response.getModelResponse(); // "Bonjour"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/** OpenAI model handler for remote inference. */
package org.apache.beam.sdk.ml.inference.openai;
Loading
Loading