|
| 1 | +package org.testcontainers.containers; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.io.OutputStream; |
| 7 | +import java.net.HttpURLConnection; |
| 8 | +import java.net.URL; |
| 9 | +import java.nio.charset.StandardCharsets; |
| 10 | + |
| 11 | +public class DockerModelRunnerContainer extends GenericContainer { |
| 12 | + |
| 13 | + public static final String MODEL_RUNNER_ENDPOINT = "model-runner.docker.internal"; |
| 14 | + private SocatContainer socat; |
| 15 | + private String model; |
| 16 | + |
| 17 | + @Override |
| 18 | + public void start() { |
| 19 | + socat = new SocatContainer() |
| 20 | + .withTarget(80, MODEL_RUNNER_ENDPOINT, 80); |
| 21 | + socat.start(); |
| 22 | + pullModel(); |
| 23 | + } |
| 24 | + |
| 25 | + private void pullModel() { |
| 26 | + logger().info("Pulling model: {}. Please be patient, no progress bar yet!", model); |
| 27 | + try { |
| 28 | + // Construct JSON payload |
| 29 | + String json = String.format("{\"from\":\"%s\"}", model); |
| 30 | + String endpoint = "http://" + socat.getHost() + ":" + socat.getMappedPort(80) + "/models/create"; |
| 31 | + |
| 32 | + URL url = new URL(endpoint); |
| 33 | + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
| 34 | + connection.setRequestMethod("POST"); |
| 35 | + connection.setRequestProperty("Content-Type", "application/json"); |
| 36 | + connection.setDoOutput(true); |
| 37 | + |
| 38 | + try (OutputStream os = connection.getOutputStream()) { |
| 39 | + byte[] input = json.getBytes(StandardCharsets.UTF_8); |
| 40 | + os.write(input, 0, input.length); |
| 41 | + } |
| 42 | + |
| 43 | + try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { |
| 44 | + StringBuilder response = new StringBuilder(); |
| 45 | + String responseLine; |
| 46 | + while ((responseLine = br.readLine()) != null) { |
| 47 | + response.append(responseLine.trim()); |
| 48 | + } |
| 49 | + logger().info(response.toString()); |
| 50 | + } |
| 51 | + } catch (IOException e) { |
| 52 | + throw new RuntimeException(e); |
| 53 | + } |
| 54 | + logger().info("Finished pulling model: {}", model); |
| 55 | + } |
| 56 | + |
| 57 | + @Override |
| 58 | + public void stop() { |
| 59 | + socat.stop(); |
| 60 | + } |
| 61 | + |
| 62 | + public String getOpenAIEndpoint() { |
| 63 | + return "http://" + socat.getHost() + ":" + socat.getMappedPort(80) + "/engines"; |
| 64 | + } |
| 65 | + |
| 66 | + public DockerModelRunnerContainer withModel(String modelName) { |
| 67 | + this.model = modelName; |
| 68 | + return this; |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments