forked from spring-projects/spring-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
spring-projectsGH-1214: Batching strategy for embedding documents
- When embedding documents, allow batching the documents using some criteria. - `BatchingStrategy` interface with a `TokenCountBatchingStrategy` implementation that uses the openai max input token size of 8191 as the default. - Add a default method in EmbeddingModel to embed document using this new batching strategy. - Change `MilvusVectorStore` to make use of this new batching API. - Adding unit tests for `TokenCountBatchingStrategy`. - Adding openai integration test to call the embed API that uses batching. Resolves spring-projects#1214
- Loading branch information
1 parent
d538e00
commit 3999067
Showing
11 changed files
with
4,429 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4,124 changes: 4,124 additions & 0 deletions
4,124
models/spring-ai-openai/src/test/resources/text_source.txt
Large diffs are not rendered by default.
Oops, something went wrong.
39 changes: 39 additions & 0 deletions
39
spring-ai-core/src/main/java/org/springframework/ai/embedding/BatchingStrategy.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
/* | ||
* Copyright 2024 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package org.springframework.ai.embedding; | ||
|
||
import java.util.List; | ||
|
||
import org.springframework.ai.document.Document; | ||
|
||
/** | ||
* Contract for batching {@link Document} objects so that the call to embed them could be | ||
* optimized. | ||
* | ||
* @author Soby Chacko | ||
* @since 1.0.0 | ||
*/ | ||
public interface BatchingStrategy { | ||
|
||
/** | ||
* {@link EmbeddingModel} implementations can call this method to optimize embedding | ||
* tokens. The incoming collection of {@link Document}s are split into su-batches. | ||
* @param documents to batch | ||
* @return a list of sub-batches that contain {@link Document}s. | ||
*/ | ||
List<List<Document>> batch(List<Document> documents); | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletions
107
...ng-ai-core/src/main/java/org/springframework/ai/embedding/TokenCountBatchingStrategy.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
/* | ||
* Copyright 2024 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package org.springframework.ai.embedding; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
|
||
import org.springframework.ai.document.ContentFormatter; | ||
import org.springframework.ai.document.Document; | ||
import org.springframework.ai.document.MetadataMode; | ||
import org.springframework.ai.tokenizer.JTokkitTokenCountEstimator; | ||
import org.springframework.ai.tokenizer.TokenCountEstimator; | ||
|
||
import com.knuddels.jtokkit.api.EncodingType; | ||
|
||
/** | ||
* Token count based strategy implementation for {@link BatchingStrategy}. Using openai | ||
* max input token as the default: | ||
* https://platform.openai.com/docs/guides/embeddings/embedding-models. | ||
* | ||
* @author Soby Chacko | ||
* @since 1.0.0 | ||
*/ | ||
public class TokenCountBatchingStrategy implements BatchingStrategy { | ||
|
||
/** | ||
* Using openai upper limit of input token count as the default. | ||
*/ | ||
private static final int MAX_INPUT_TOKEN_COUNT = 8191; | ||
|
||
private final TokenCountEstimator tokenCountEstimator; | ||
|
||
private final int maxInputTokenCount; | ||
|
||
private final ContentFormatter contentFormater; | ||
|
||
private final MetadataMode metadataMode; | ||
|
||
public TokenCountBatchingStrategy() { | ||
this(EncodingType.CL100K_BASE, MAX_INPUT_TOKEN_COUNT); | ||
} | ||
|
||
/** | ||
* @param encodingType {@link EncodingType} | ||
* @param maxInputTokenCount upper limit for input tokens | ||
*/ | ||
public TokenCountBatchingStrategy(EncodingType encodingType, int maxInputTokenCount) { | ||
this(encodingType, maxInputTokenCount, Document.DEFAULT_CONTENT_FORMATTER, MetadataMode.NONE); | ||
} | ||
|
||
/** | ||
* @param encodingType {@link EncodingType} | ||
* @param maxInputTokenCount upper limit for input tokens | ||
* @param contentFormatter {@link ContentFormatter} | ||
* @param metadataMode {@link MetadataMode} | ||
*/ | ||
public TokenCountBatchingStrategy(EncodingType encodingType, int maxInputTokenCount, | ||
ContentFormatter contentFormatter, MetadataMode metadataMode) { | ||
this.tokenCountEstimator = new JTokkitTokenCountEstimator(encodingType); | ||
this.maxInputTokenCount = (int) Math.round(maxInputTokenCount - (maxInputTokenCount * .1)); | ||
this.contentFormater = contentFormatter; | ||
this.metadataMode = metadataMode; | ||
} | ||
|
||
@Override | ||
public List<List<Document>> batch(List<Document> documents) { | ||
List<List<Document>> batches = new ArrayList<>(); | ||
int currentSize = 0; | ||
List<Document> currentBatch = new ArrayList<>(); | ||
|
||
for (Document document : documents) { | ||
int tokenCount = this.tokenCountEstimator | ||
.estimate(document.getFormattedContent(this.contentFormater, this.metadataMode)); | ||
// TODO: If there are documents that exceed the limit, we should fail fast | ||
// before getting into this loop. | ||
if (tokenCount > this.maxInputTokenCount) { | ||
throw new IllegalArgumentException( | ||
"Tokens in a single document exceeds the maximum number of allowed input tokens"); | ||
} | ||
if (currentSize + tokenCount > maxInputTokenCount) { | ||
batches.add(currentBatch); | ||
currentBatch.clear(); | ||
currentSize = 0; | ||
} | ||
currentBatch.add(document); | ||
currentSize += tokenCount; | ||
} | ||
if (!currentBatch.isEmpty()) { | ||
batches.add(currentBatch); | ||
} | ||
return batches; | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
57 changes: 57 additions & 0 deletions
57
...-core/src/test/java/org/springframework/ai/embedding/TokenCountBatchingStrategyTests.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
/* | ||
* Copyright 2024-2024 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package org.springframework.ai.embedding; | ||
|
||
import static org.assertj.core.api.Assertions.assertThat; | ||
import static org.assertj.core.api.Assertions.assertThatThrownBy; | ||
|
||
import java.io.IOException; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.List; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
import org.springframework.ai.document.Document; | ||
import org.springframework.core.io.DefaultResourceLoader; | ||
import org.springframework.core.io.Resource; | ||
|
||
/** | ||
* Basic unit test for {@link TokenCountBatchingStrategy}. | ||
* | ||
* @author Soby Chacko | ||
*/ | ||
public class TokenCountBatchingStrategyTests { | ||
|
||
@Test | ||
void batchEmbeddingHappyPath() { | ||
TokenCountBatchingStrategy tokenCountBatchingStrategy = new TokenCountBatchingStrategy(); | ||
List<List<Document>> batch = tokenCountBatchingStrategy.batch( | ||
List.of(new Document("Hello world"), new Document("Hello Spring"), new Document("Hello Spring AI!"))); | ||
assertThat(batch.size()).isEqualTo(1); | ||
assertThat(batch.get(0).size()).isEqualTo(3); | ||
} | ||
|
||
@Test | ||
void batchEmbeddingWithLargeDocumentExceedsMaxTokenSize() throws IOException { | ||
Resource resource = new DefaultResourceLoader().getResource("classpath:text_source.txt"); | ||
String contentAsString = resource.getContentAsString(StandardCharsets.UTF_8); | ||
TokenCountBatchingStrategy tokenCountBatchingStrategy = new TokenCountBatchingStrategy(); | ||
assertThatThrownBy(() -> { | ||
tokenCountBatchingStrategy.batch(List.of(new Document(contentAsString))); | ||
}).isInstanceOf(IllegalArgumentException.class); | ||
} | ||
|
||
} |
Oops, something went wrong.