Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use RestClient in ChromaApi #717

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;

/**
Expand Down Expand Up @@ -56,7 +57,7 @@ public ChromaApi chromaApi(ChromaApiProperties apiProperties, RestTemplate restT

String chromaUrl = String.format("%s:%s", connectionDetails.getHost(), connectionDetails.getPort());

var chromaApi = new ChromaApi(chromaUrl, restTemplate, new ObjectMapper());
var chromaApi = new ChromaApi(chromaUrl, RestClient.builder(restTemplate), new ObjectMapper());

if (StringUtils.hasText(apiProperties.getKeyToken())) {
chromaApi.withKeyToken(apiProperties.getKeyToken());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand All @@ -27,41 +28,42 @@
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.ai.chroma.ChromaApi.QueryRequest.Include;
import org.springframework.http.HttpEntity;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.RestClient;

/**
* Single-class Chroma API implementation based on the (unofficial) Chroma REST API.
*
* @author Christian Tzolov
* @author Eddú Meléndez
*/
public class ChromaApi {

// Regular expression pattern that looks for a message inside the ValueError(...).
private static Pattern VALUE_ERROR_PATTERN = Pattern.compile("ValueError\\('([^']*)'\\)");

private final String baseUrl;

private final RestTemplate restTemplate;
private final RestClient restClient;

private final ObjectMapper objectMapper;

private String keyToken;

public ChromaApi(String baseUrl, RestTemplate restTemplate) {
this(baseUrl, restTemplate, new ObjectMapper());
public ChromaApi(String baseUrl, RestClient.Builder restClientBuilder) {
this(baseUrl, restClientBuilder, new ObjectMapper());
}

public ChromaApi(String baseUrl, RestTemplate restTemplate, ObjectMapper objectMapper) {
this.baseUrl = baseUrl;
this.restTemplate = restTemplate;
public ChromaApi(String baseUrl, RestClient.Builder restClientBuilder, ObjectMapper objectMapper) {
Consumer<HttpHeaders> defaultHeaders = headers -> {
headers.setContentType(MediaType.APPLICATION_JSON);
};
this.restClient = restClientBuilder.baseUrl(baseUrl).defaultHeaders(defaultHeaders).build();
this.objectMapper = objectMapper;
}

Expand All @@ -82,7 +84,7 @@ public ChromaApi withKeyToken(String keyToken) {
* @param password Credentials password.
*/
public ChromaApi withBasicAuthCredentials(String username, String password) {
this.restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(username, password));
this.restClient.mutate().requestInterceptor(new BasicAuthenticationInterceptor(username, password));
return this;
}

Expand Down Expand Up @@ -265,9 +267,12 @@ public List<Embedding> toEmbeddingResponseList(QueryResponse queryResponse) {

public Collection createCollection(CreateCollectionRequest createCollectionRequest) {

return this.restTemplate
.exchange(this.baseUrl + "/api/v1/collections", HttpMethod.POST,
this.getHttpEntityFor(createCollectionRequest), Collection.class)
return this.restClient.post()
.uri("/api/v1/collections")
.headers(this::httpHeaders)
.body(createCollectionRequest)
.retrieve()
.toEntity(Collection.class)
.getBody();
}

Expand All @@ -278,16 +283,21 @@ public Collection createCollection(CreateCollectionRequest createCollectionReque
*/
public void deleteCollection(String collectionName) {

this.restTemplate.exchange(this.baseUrl + "/api/v1/collections/{collection_name}", HttpMethod.DELETE,
new HttpEntity<>(httpHeaders()), Void.class, collectionName);
this.restClient.delete()
.uri("/api/v1/collections/{collection_name}", collectionName)
.headers(this::httpHeaders)
.retrieve()
.toBodilessEntity();
}

public Collection getCollection(String collectionName) {

try {
return this.restTemplate
.exchange(this.baseUrl + "/api/v1/collections/{collection_name}", HttpMethod.GET,
new HttpEntity<>(httpHeaders()), Collection.class, collectionName)
return this.restClient.get()
.uri("/api/v1/collections/{collection_name}", collectionName)
.headers(this::httpHeaders)
.retrieve()
.toEntity(Collection.class)
.getBody();
}
catch (HttpServerErrorException e) {
Expand All @@ -305,9 +315,11 @@ private static class CollectionList extends ArrayList<Collection> {

public List<Collection> listCollections() {

return this.restTemplate
.exchange(this.baseUrl + "/api/v1/collections", HttpMethod.GET, new HttpEntity<>(httpHeaders()),
CollectionList.class)
return this.restClient.get()
.uri("/api/v1/collections")
.headers(this::httpHeaders)
.retrieve()
.toEntity(CollectionList.class)
.getBody();
}

Expand All @@ -317,41 +329,55 @@ public List<Collection> listCollections() {

public void upsertEmbeddings(String collectionId, AddEmbeddingsRequest embedding) {

this.restTemplate
.exchange(this.baseUrl + "/api/v1/collections/{collection_id}/upsert", HttpMethod.POST,
this.getHttpEntityFor(embedding), Boolean.class, collectionId)
.getBody();
this.restClient.post()
.uri("/api/v1/collections/{collection_id}/upsert", collectionId)
.headers(this::httpHeaders)
.body(embedding)
.retrieve()
.toBodilessEntity();
}

public List<String> deleteEmbeddings(String collectionId, DeleteEmbeddingsRequest deleteRequest) {

return this.restTemplate
.exchange(this.baseUrl + "/api/v1/collections/{collection_id}/delete", HttpMethod.POST,
this.getHttpEntityFor(deleteRequest), List.class, collectionId)
return this.restClient.post()
.uri("/api/v1/collections/{collection_id}/delete", collectionId)
.headers(this::httpHeaders)
.body(deleteRequest)
.retrieve()
.toEntity(new ParameterizedTypeReference<List<String>>() {
})
.getBody();
}

public Long countEmbeddings(String collectionId) {

return this.restTemplate
.exchange(this.baseUrl + "/api/v1/collections/{collection_id}/count", HttpMethod.GET,
new HttpEntity<>(httpHeaders()), Long.class, collectionId)
return this.restClient.get()
.uri("/api/v1/collections/{collection_id}/count", collectionId)
.headers(this::httpHeaders)
.retrieve()
.toEntity(Long.class)
.getBody();
}

public QueryResponse queryCollection(String collectionId, QueryRequest queryRequest) {

return this.restTemplate
.exchange(this.baseUrl + "/api/v1/collections/{collection_id}/query", HttpMethod.POST,
this.getHttpEntityFor(queryRequest), QueryResponse.class, collectionId)
return this.restClient.post()
.uri("/api/v1/collections/{collection_id}/query", collectionId)
.headers(this::httpHeaders)
.body(queryRequest)
.retrieve()
.toEntity(QueryResponse.class)
.getBody();
}

public GetEmbeddingResponse getEmbeddings(String collectionId, GetEmbeddingsRequest getEmbeddingsRequest) {

return this.restTemplate
.exchange(this.baseUrl + "/api/v1/collections/{collection_id}/get", HttpMethod.POST,
this.getHttpEntityFor(getEmbeddingsRequest), GetEmbeddingResponse.class, collectionId)
return this.restClient.post()
.uri("/api/v1/collections/{collection_id}/get", collectionId)
.headers(this::httpHeaders)
.body(getEmbeddingsRequest)
.retrieve()
.toEntity(GetEmbeddingResponse.class)
.getBody();
}

Expand All @@ -365,17 +391,10 @@ public Map<String, Object> where(String text) {
}
}

private <T> HttpEntity<T> getHttpEntityFor(T body) {
return new HttpEntity<>(body, httpHeaders());
}

private HttpHeaders httpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
private void httpHeaders(HttpHeaders headers) {
if (StringUtils.hasText(this.keyToken)) {
headers.setBearerAuth(this.keyToken);
}
return headers;
}

private String getValueErrorMessage(String logString) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestClient;
import org.testcontainers.chromadb.ChromaDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
Expand Down Expand Up @@ -185,7 +186,7 @@ public RestTemplate restTemplate() {

@Bean
public ChromaApi chromaApi(RestTemplate restTemplate) {
return new ChromaApi(chromaContainer.getEndpoint(), restTemplate);
return new ChromaApi(chromaContainer.getEndpoint(), RestClient.builder(restTemplate));
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import org.testcontainers.chromadb.ChromaDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
Expand All @@ -32,7 +34,6 @@
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import org.testcontainers.utility.MountableFile;

import static org.assertj.core.api.Assertions.assertThat;
Expand Down Expand Up @@ -102,8 +103,8 @@ public RestTemplate restTemplate() {

@Bean
public ChromaApi chromaApi(RestTemplate restTemplate) {
return new ChromaApi(chromaContainer.getEndpoint(), restTemplate).withBasicAuthCredentials("admin",
"password");
return new ChromaApi(chromaContainer.getEndpoint(), RestClient.builder(restTemplate))
.withBasicAuthCredentials("admin", "password");
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.UUID;

import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestClient;
import org.testcontainers.chromadb.ChromaDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
Expand Down Expand Up @@ -208,7 +209,7 @@ public RestTemplate restTemplate() {

@Bean
public ChromaApi chromaApi(RestTemplate restTemplate) {
return new ChromaApi(chromaContainer.getEndpoint(), restTemplate);
return new ChromaApi(chromaContainer.getEndpoint(), RestClient.builder(restTemplate));
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import org.testcontainers.chromadb.ChromaDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
Expand All @@ -32,7 +34,6 @@
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import static org.assertj.core.api.Assertions.assertThat;

Expand Down Expand Up @@ -133,7 +134,7 @@ public RestTemplate restTemplate() {

@Bean
public ChromaApi chromaApi(RestTemplate restTemplate) {
var chromaApi = new ChromaApi(chromaContainer.getEndpoint(), restTemplate);
var chromaApi = new ChromaApi(chromaContainer.getEndpoint(), RestClient.builder(restTemplate));
chromaApi.withKeyToken(CHROMA_SERVER_AUTH_CREDENTIALS);
return chromaApi;
}
Expand Down