|
| 1 | +package com.openai.example; |
| 2 | + |
| 3 | +import com.openai.client.OpenAIClientAsync; |
| 4 | +import com.openai.client.okhttp.OpenAIOkHttpClientAsync; |
| 5 | +import com.openai.core.JsonValue; |
| 6 | +import com.openai.models.ChatCompletionCreateParams; |
| 7 | +import com.openai.models.ChatCompletionUserMessageParam; |
| 8 | +import com.openai.models.ChatModel; |
| 9 | +import com.openai.models.ResponseFormatJsonSchema; |
| 10 | +import com.openai.models.ResponseFormatJsonSchema.JsonSchema; |
| 11 | +import java.util.Map; |
| 12 | + |
| 13 | +public final class StructuredOutputsAsyncExample { |
| 14 | + private StructuredOutputsAsyncExample() {} |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + // Configures using one of: |
| 18 | + // - The `OPENAI_API_KEY` environment variable |
| 19 | + // - The `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_KEY` environment variables |
| 20 | + OpenAIClientAsync client = OpenAIOkHttpClientAsync.fromEnv(); |
| 21 | + |
| 22 | + // TODO: Update this once we support extracting JSON schemas from Java classes |
| 23 | + JsonSchema.Schema schema = JsonSchema.Schema.builder() |
| 24 | + .putAdditionalProperty("type", JsonValue.from("object")) |
| 25 | + .putAdditionalProperty( |
| 26 | + "properties", JsonValue.from(Map.of("employees", Map.of("items", Map.of("type", "string"))))) |
| 27 | + .build(); |
| 28 | + ChatCompletionCreateParams createParams = ChatCompletionCreateParams.builder() |
| 29 | + .model(ChatModel.GPT_4O_MINI) |
| 30 | + .maxCompletionTokens(2048) |
| 31 | + .responseFormat(ResponseFormatJsonSchema.builder() |
| 32 | + .jsonSchema(JsonSchema.builder() |
| 33 | + .name("employee-list") |
| 34 | + .schema(schema) |
| 35 | + .build()) |
| 36 | + .build()) |
| 37 | + .addMessage(ChatCompletionUserMessageParam.builder() |
| 38 | + .content("Who works at OpenAI?") |
| 39 | + .build()) |
| 40 | + .build(); |
| 41 | + |
| 42 | + client.chat() |
| 43 | + .completions() |
| 44 | + .create(createParams) |
| 45 | + .thenAccept(completion -> completion.choices().stream() |
| 46 | + .flatMap(choice -> choice.message().content().stream()) |
| 47 | + .forEach(System.out::println)) |
| 48 | + .join(); |
| 49 | + } |
| 50 | +} |
0 commit comments