|
| 1 | +package com.openai.example; |
| 2 | + |
| 3 | +import static com.openai.models.responses.ResponseFormatTextJsonSchemaConfig.Schema; |
| 4 | + |
| 5 | +import com.openai.client.OpenAIClient; |
| 6 | +import com.openai.client.okhttp.OpenAIOkHttpClient; |
| 7 | +import com.openai.core.JsonValue; |
| 8 | +import com.openai.models.ChatModel; |
| 9 | +import com.openai.models.responses.ResponseCreateParams; |
| 10 | +import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig; |
| 11 | +import com.openai.models.responses.ResponseTextConfig; |
| 12 | +import java.util.List; |
| 13 | +import java.util.Map; |
| 14 | + |
| 15 | +public final class ResponsesStructuredOutputsRawExample { |
| 16 | + private ResponsesStructuredOutputsRawExample() {} |
| 17 | + |
| 18 | + public static void main(String[] args) { |
| 19 | + // Configures using one of: |
| 20 | + // - The `OPENAI_API_KEY` environment variable |
| 21 | + // - The `OPENAI_BASE_URL` and `AZURE_OPENAI_KEY` environment variables |
| 22 | + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); |
| 23 | + |
| 24 | + Schema schema = Schema.builder() |
| 25 | + .putAdditionalProperty("type", JsonValue.from("object")) |
| 26 | + .putAdditionalProperty( |
| 27 | + "properties", |
| 28 | + JsonValue.from(Map.of("employees", Map.of("type", "array", "items", Map.of("type", "string"))))) |
| 29 | + .putAdditionalProperty("required", JsonValue.from(List.of("employees"))) |
| 30 | + .putAdditionalProperty("additionalProperties", JsonValue.from(false)) |
| 31 | + .build(); |
| 32 | + ResponseTextConfig textConfig = ResponseTextConfig.builder() |
| 33 | + .format(ResponseFormatTextJsonSchemaConfig.builder() |
| 34 | + .name("employees") |
| 35 | + .schema(schema) |
| 36 | + .strict(true) |
| 37 | + .build()) |
| 38 | + .build(); |
| 39 | + |
| 40 | + ResponseCreateParams createParams = ResponseCreateParams.builder() |
| 41 | + .input("Who works at OpenAI?") |
| 42 | + .text(textConfig) |
| 43 | + .model(ChatModel.GPT_4O) |
| 44 | + .build(); |
| 45 | + |
| 46 | + client.responses().create(createParams).output().stream() |
| 47 | + .flatMap(item -> item.message().stream()) |
| 48 | + .flatMap(message -> message.content().stream()) |
| 49 | + .flatMap(content -> content.outputText().stream()) |
| 50 | + .forEach(outputText -> System.out.println(outputText.text())); |
| 51 | + } |
| 52 | +} |
0 commit comments