From 7ae2ab773d7cd3cf1f04838d7674263dfcfe74aa Mon Sep 17 00:00:00 2001 From: Stefan Bratanov Date: Sun, 14 Jan 2024 14:07:20 +0200 Subject: [PATCH] Add more examples --- README.md | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 123 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f476334..2e145c1 100644 --- a/README.md +++ b/README.md @@ -36,17 +36,17 @@ OpenAI openAI = OpenAI.newBuilder(System.getenv("OPENAI_API_KEY")).build(); ChatClient chatClient = openAI.chatClient(); CreateChatCompletionRequest createChatCompletionRequest = CreateChatCompletionRequest.newBuilder() - .model("gpt-3.5-turbo") - .message(ChatMessage.userMessage("Who won the world series in 2020?")) - .build(); + .model("gpt-3.5-turbo") + .message(ChatMessage.userMessage("Who won the world series in 2020?")) + .build(); ChatCompletion chatCompletion = chatClient.createChatCompletion(createChatCompletionRequest); // ChatCompletion[id=chatcmpl-123, created=1703506594, model=gpt-3.5-turbo-0613, systemFingerprint=fp_44709d6fcb, choices=[Choice[index=0, message=Message[content=The Los Angeles Dodgers won the World Series in 2020., toolCalls=null, role=assistant], logProbs=null, finishReason=stop]], usage=Usage[promptTokens=17, completionTokens=13, totalTokens=30]] ImagesClient imagesClient = openAI.imagesClient(); CreateImageRequest createImageRequest = CreateImageRequest.newBuilder() - .model("dall-e-3") - .prompt("A cute baby sea otter") - .build(); + .model("dall-e-3") + .prompt("A cute baby sea otter") + .build(); Images images = imagesClient.createImage(createImageRequest); // Images[created=1704009569, data=[Image[b64Json=null, url=https://foo.bar/cute-baby-sea-otter.png, revisedPrompt=Generate an image of a baby sea otter, exuding cuteness. The small, furry creature should be floating blissfully on its back in clear, calm waters, its round button eyes are brimming with innocence and curiosity.]]] ``` @@ -73,4 +73,121 @@ Images images = imagesClient.createImage(createImageRequest); | [Messages](https://platform.openai.com/docs/api-reference/messages) | ✔️ | | [Runs](https://platform.openai.com/docs/api-reference/runs) | ✔️ | +## More examples +- Configure an organization +```java +OpenAI openAI = OpenAI.newBuilder(System.getenv("OPENAI_API_KEY")) + .organization("org-zweLLamVlP6c5n66zY334ivs") + .build(); +``` +- Configure a custom Java's `HttpClient` +```java +HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(20)) + .executor(Executors.newFixedThreadPool(3)) + .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80))) + .build(); +OpenAI openAI = OpenAI.newBuilder(System.getenv("OPENAI_API_KEY")) + .httpClient(httpClient) + .build(); +``` +- Create chat completion async +```java +ChatClient chatClient = openAI.chatClient(); +CreateChatCompletionRequest request = CreateChatCompletionRequest.newBuilder() + .model("gpt-3.5-turbo") + .message(ChatMessage.userMessage("Who won the world series in 2020?")) + .build(); +CompletableFuture chatCompletion = chatClient.createChatCompletionAsync(request); +chatCompletion.thenAccept(System.out::println); +``` +- Streaming +```java +ChatClient chatClient = openAI.chatClient(); +CreateChatCompletionRequest request = CreateChatCompletionRequest.newBuilder() + .message(ChatMessage.userMessage("Who won the world series in 2020?")) + .stream(true) + .build(); +// with java.util.stream.Stream +chatClient.streamChatCompletion(request).forEach(System.out::println); +// with subscriber +chatClient.streamChatCompletion(request, new StreamChatCompletionSubscriber() { + @Override + public void onChunk(ChatCompletionChunk chunk) { + System.out.println(chunk); + } + + @Override + public void onComplete() { + // ... + } +}); +``` +- Create speech +```java +AudioClient audioClient = openAI.audioClient(); +SpeechRequest request = SpeechRequest.newBuilder() + .model("ttl-1") + .input("The quick brown fox jumped over the lazy dog.") + .voice("alloy") + .build(); +Path output = Paths.get("/tmp/speech.mp3"); +audioClient.createSpeech(request, output); +``` +- List models +```java +ModelsClient modelsClient = openAI.modelsClient(); +List models = modelsClient.listModels(); +``` +- Classifiy if text violates OpenAI's Content Policy +```java +ModerationsClient moderationsClient = openAI.moderationsClient(); +ModerationRequest request = ModerationRequest.newBuilder() + .input("I want to bake a cake.") + .build(); +Moderation moderation = moderationsClient.createModeration(request); +boolean violence = moderation.results().get(0).categories().violence(); +``` +- Build AI Assistant +```java +AssistantsClient assistantsClient = openAI.assistantsClient(); +ThreadsClient threadsClient = openAI.threadsClient(); +MessagesClient messagesClient = openAI.messagesClient(); +RunsClient runsClient = openAI.runsClient(); + +// Step 1: Create an Assistant +CreateAssistantRequest createAssistantRequest = CreateAssistantRequest.newBuilder() + .name("Math Tutor") + .model("gpt-3.5-turbo-1106") + .instructions("You are a personal math tutor. Write and run code to answer math questions.") + .tool(Tool.codeInterpreterTool()) + .build(); +Assistant assistant = assistantsClient.createAssistant(createAssistantRequest); + +// Step 2: Create a Thread +CreateThreadRequest createThreadRequest = CreateThreadRequest.newBuilder().build(); +Thread thread = threadsClient.createThread(createThreadRequest); + +// Step 3: Add a Message to a Thread +CreateMessageRequest createMessageRequest = CreateMessageRequest.newBuilder() + .role("user") + .content("I need to solve the equation `3x + 11 = 14`. Can you help me?") + .build(); +ThreadMessage message = messagesClient.createMessage(thread.id(), createMessageRequest); + +// Step 4: Run the Assistant +CreateRunRequest createRunRequest = CreateRunRequest.newBuilder() + .assistantId(assistant.id()) + .instructions("Please address the user as Jane Doe. The user has a premium account.") + .build(); +ThreadRun run = runsClient.createRun(thread.id(), createRunRequest); + +// Step 5: Check the Run status +ThreadRun retrievedRun = runsClient.retrieveRun(thread.id(), run.id()); +String status = retrievedRun.status(); + +// Step 6: Display the Assistant's Response +PaginatedThreadMessages paginatedMessages = messagesClient.listMessages(thread.id(), PaginationQueryParameters.none()); +List messages = paginatedMessages.data(); +```