package com.ankurm.codesearch; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; /** * Calls any {@code POST /v1/embeddings} endpoint that speaks the OpenAI request shape: OpenAI itself, Ollama * ({@code http://localhost:11434/v1}), vLLM, LM Studio, llama.cpp's server. This is the swap-in for * {@link HashingEmbedder} when you want meaning instead of word overlap. * *

The tests run it against a stub server, which proves the request and response handling and nothing about * the quality of any real model's vectors. */ public final class OpenAiCompatibleEmbedder implements Embedder { private static final JsonMapper JSON = JsonMapper.builder().build(); private final URI endpoint; private final String model; private final String apiKey; private final int dimensions; private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); /** @param baseUrl for example {@code http://localhost:11434/v1}; {@code /embeddings} is appended. */ public OpenAiCompatibleEmbedder(String baseUrl, String model, String apiKey, int dimensions) { this.endpoint = URI.create(baseUrl.replaceAll("/+$", "") + "/embeddings"); this.model = model; this.apiKey = apiKey; this.dimensions = dimensions; } @Override public int dimensions() { return dimensions; } @Override public String name() { return "openai-compatible:" + model; } @Override public float[] embed(String text) { return embedAll(List.of(text)).get(0); } @Override public List embedAll(List texts) { List out = new ArrayList<>(); // 64 texts per request keeps every request body small and every server's batch limit happy. for (int from = 0; from < texts.size(); from += 64) { out.addAll(request(texts.subList(from, Math.min(from + 64, texts.size())))); } return out; } private List request(List batch) { try { // LinkedHashMap, not Map.of: Map.of iterates in a per-JVM random order, which makes request bytes unstable. Map payload = new java.util.LinkedHashMap<>(); payload.put("model", model); payload.put("input", batch); String body = JSON.writeValueAsString(payload); HttpRequest.Builder req = HttpRequest.newBuilder(endpoint).timeout(Duration.ofSeconds(60)) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(body)); if (apiKey != null && !apiKey.isBlank()) { req.header("Authorization", "Bearer " + apiKey); } HttpResponse res = http.send(req.build(), HttpResponse.BodyHandlers.ofString()); if (res.statusCode() != 200) { throw new IllegalStateException("embedding endpoint returned HTTP " + res.statusCode() + ": " + res.body()); } // The spec returns "data" with an "index" per item; sort by it rather than trusting the order. JsonNode data = JSON.readTree(res.body()).get("data"); float[][] vectors = new float[batch.size()][]; for (JsonNode item : data) { JsonNode e = item.get("embedding"); float[] v = new float[e.size()]; double norm = 0; for (int i = 0; i < v.length; i++) { v[i] = (float) e.get(i).asDouble(); norm += v[i] * v[i]; } norm = Math.sqrt(norm); for (int i = 0; i < v.length && norm > 0; i++) { v[i] /= (float) norm; } if (v.length != dimensions) { throw new IllegalStateException("expected " + dimensions + " dimensions but the model returned " + v.length + "; change the dimensions you passed in, or re-index"); } vectors[item.get("index").asInt()] = v; } return List.of(vectors); } catch (IOException e) { throw new IllegalStateException("could not call " + endpoint, e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("interrupted while calling " + endpoint, e); } } }