Ether Framework
Unified API docs for Ether modules
Loading...
Searching...
No Matches
OpenAiChatModel.java
Go to the documentation of this file.
1package dev.rafex.ether.ai.openai.chat;
2
3/*-
4 * #%L
5 * ether-ai-openai
6 * %%
7 * Copyright (C) 2025 - 2026 Raúl Eduardo González Argote
8 * %%
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 * #L%
27 */
28
29import java.io.IOException;
30import java.net.http.HttpClient;
31import java.net.http.HttpRequest;
32import java.net.http.HttpResponse;
33import java.nio.charset.StandardCharsets;
34import java.util.LinkedHashMap;
35import java.util.Map;
36import java.util.Objects;
37
38import com.fasterxml.jackson.databind.JsonNode;
39
40import dev.rafex.ether.ai.core.chat.AiChatModel;
41import dev.rafex.ether.ai.core.chat.AiChatRequest;
42import dev.rafex.ether.ai.core.chat.AiChatResponse;
43import dev.rafex.ether.ai.core.error.AiHttpException;
44import dev.rafex.ether.ai.core.message.AiMessage;
45import dev.rafex.ether.ai.core.message.AiMessageRole;
46import dev.rafex.ether.ai.core.usage.AiUsage;
47import dev.rafex.ether.ai.openai.config.OpenAiConfig;
48import dev.rafex.ether.json.JsonCodec;
49import dev.rafex.ether.json.JsonUtils;
50
51/**
52 * Implementación de {@link AiChatModel} para la API de OpenAI.
53 *
54 * <p>Envía solicitudes de chat completions a la API de OpenAI y procesa las respuestas.</p>
55 */
56public final class OpenAiChatModel implements AiChatModel {
57
58 private final OpenAiConfig config;
59 private final HttpClient httpClient;
60 private final JsonCodec jsonCodec;
61
62 /**
63 * Crea un modelo de chat OpenAI usando la configuración proporcionada.
64 *
65 * @param config La configuración de OpenAI.
66 * @throws NullPointerException si la configuración es nula.
67 */
68 public OpenAiChatModel(final OpenAiConfig config) {
69 this(config, HttpClient.newBuilder().connectTimeout(config.timeout()).build(), JsonUtils.codec());
70 }
71
72 /**
73 * Crea un modelo de chat OpenAI con configuración personalizada.
74 *
75 * @param config La configuración de OpenAI.
76 * @param httpClient El cliente HTTP a utilizar.
77 * @param jsonCodec El codificador JSON a utilizar.
78 * @throws NullPointerException si la configuración o el cliente HTTP son nulos.
79 */
80 public OpenAiChatModel(final OpenAiConfig config, final HttpClient httpClient, final JsonCodec jsonCodec) {
81 this.config = Objects.requireNonNull(config, "config");
82 this.httpClient = Objects.requireNonNull(httpClient, "httpClient");
83 this.jsonCodec = jsonCodec == null ? JsonUtils.codec() : jsonCodec;
84 }
85
86 @Override
87 public AiChatResponse generate(final AiChatRequest request) throws IOException, InterruptedException {
88 final byte[] payload = jsonCodec.toJsonBytes(toPayload(request));
89 final var builder = HttpRequest.newBuilder(config.chatCompletionsUri()).timeout(config.timeout())
90 .header("Authorization", "Bearer " + config.apiKey()).header("Content-Type", "application/json")
91 .POST(HttpRequest.BodyPublishers.ofByteArray(payload));
92
93 if (!config.organization().isBlank()) {
94 builder.header("OpenAI-Organization", config.organization());
95 }
96 if (!config.project().isBlank()) {
97 builder.header("OpenAI-Project", config.project());
98 }
99 config.defaultHeaders().forEach(builder::header);
100
101 final var response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray());
102 if (response.statusCode() < 200 || response.statusCode() >= 300) {
103 throw new AiHttpException("OpenAI request failed with HTTP " + response.statusCode(), response.statusCode(),
104 new String(response.body(), StandardCharsets.UTF_8));
105 }
106
107 final JsonNode root = jsonCodec.readTree(response.body());
108 final JsonNode choice = root.path("choices").path(0);
109 final JsonNode messageNode = choice.path("message");
110 final var message = new AiMessage(AiMessageRole.fromWireValue(text(messageNode, "role")),
111 text(messageNode, "content"));
112 return new AiChatResponse(text(root, "id"), text(root, "model"), message, text(choice, "finish_reason"),
113 usage(root.path("usage")));
114 }
115
116 private static Map<String, Object> toPayload(final AiChatRequest request) {
117 final var payload = new LinkedHashMap<String, Object>();
118 payload.put("model", request.model());
119 payload.put("messages", request.messages().stream()
120 .map(message -> Map.of("role", message.role().wireValue(), "content", message.content())).toList());
121 if (request.temperature() != null) {
122 payload.put("temperature", request.temperature());
123 }
124 if (request.maxOutputTokens() != null) {
125 payload.put("max_completion_tokens", request.maxOutputTokens());
126 }
127 return payload;
128 }
129
130 private static String text(final JsonNode node, final String fieldName) throws IOException {
131 final JsonNode field = node.path(fieldName);
132 if (field.isMissingNode() || field.isNull()) {
133 throw new IOException("Missing JSON field: " + fieldName);
134 }
135 return field.asText();
136 }
137
138 private static AiUsage usage(final JsonNode node) {
139 if (node == null || node.isMissingNode() || node.isNull()) {
140 return AiUsage.empty();
141 }
142 return new AiUsage(node.path("prompt_tokens").asInt(0), node.path("completion_tokens").asInt(0),
143 node.path("total_tokens").asInt(0));
144 }
145}
OpenAiChatModel(final OpenAiConfig config, final HttpClient httpClient, final JsonCodec jsonCodec)
Crea un modelo de chat OpenAI con configuración personalizada.
OpenAiChatModel(final OpenAiConfig config)
Crea un modelo de chat OpenAI usando la configuración proporcionada.
AiChatResponse generate(final AiChatRequest request)
static AiMessageRole fromWireValue(final String value)