|
| 1 | +package com.openai.example; |
| 2 | + |
| 3 | +import com.openai.client.OpenAIClient; |
| 4 | +import com.openai.client.okhttp.OpenAIOkHttpClient; |
| 5 | +import com.openai.models.ChatModel; |
| 6 | +import com.openai.models.chat.completions.ChatCompletionContentPart; |
| 7 | +import com.openai.models.chat.completions.ChatCompletionContentPartText; |
| 8 | +import com.openai.models.chat.completions.ChatCompletionCreateParams; |
| 9 | +import com.openai.models.files.FileCreateParams; |
| 10 | +import com.openai.models.files.FileObject; |
| 11 | +import com.openai.models.files.FilePurpose; |
| 12 | +import java.io.IOException; |
| 13 | +import java.net.URISyntaxException; |
| 14 | +import java.nio.file.Path; |
| 15 | +import java.nio.file.Paths; |
| 16 | +import java.util.List; |
| 17 | + |
| 18 | +public final class CompletionsFileExample { |
| 19 | + private CompletionsFileExample() {} |
| 20 | + |
| 21 | + public static void main(String[] args) throws URISyntaxException, InterruptedException, IOException { |
| 22 | + // Configures using one of: |
| 23 | + // - The `OPENAI_API_KEY` environment variable |
| 24 | + // - The `OPENAI_BASE_URL` and `AZURE_OPENAI_KEY` environment variables |
| 25 | + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); |
| 26 | + |
| 27 | + ClassLoader classloader = Thread.currentThread().getContextClassLoader(); |
| 28 | + Path pdfPath = Paths.get(classloader.getResource("pdflatex-image.pdf").toURI()); |
| 29 | + |
| 30 | + FileObject logoFileObject = client.files() |
| 31 | + .create(FileCreateParams.builder() |
| 32 | + .file(pdfPath) |
| 33 | + .purpose(FilePurpose.USER_DATA) |
| 34 | + .build()); |
| 35 | + |
| 36 | + ChatCompletionContentPart.File logoFile = ChatCompletionContentPart.File.builder() |
| 37 | + .file(ChatCompletionContentPart.File.FileObject.builder() |
| 38 | + .fileId(logoFileObject.id()) |
| 39 | + .build()) |
| 40 | + .build(); |
| 41 | + ChatCompletionContentPart logoContentPart = ChatCompletionContentPart.ofFile(logoFile); |
| 42 | + |
| 43 | + ChatCompletionContentPart questionContentPart = |
| 44 | + ChatCompletionContentPart.ofText(ChatCompletionContentPartText.builder() |
| 45 | + .text("Describe this image.") |
| 46 | + .build()); |
| 47 | + ChatCompletionCreateParams createParams = ChatCompletionCreateParams.builder() |
| 48 | + .model(ChatModel.GPT_4O_MINI) |
| 49 | + .maxCompletionTokens(2048) |
| 50 | + .addUserMessageOfArrayOfContentParts(List.of(questionContentPart, logoContentPart)) |
| 51 | + .build(); |
| 52 | + |
| 53 | + client.chat().completions().create(createParams).choices().stream() |
| 54 | + .flatMap(choice -> choice.message().content().stream()) |
| 55 | + .forEach(System.out::println); |
| 56 | + } |
| 57 | +} |
0 commit comments