-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement LLM call caching with a vector store
Use a vector store on top of the existing agent_conversations table
- Loading branch information
1 parent
988c813
commit 5615127
Showing
6 changed files
with
198 additions
and
10 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
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
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
159 changes: 159 additions & 0 deletions
159
src/main/java/com/datastax/ai/agent/llmCache/AiAgentSessionVector.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,159 @@ | ||
/* | ||
* 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. | ||
* | ||
* See the NOTICE file distributed with this work for additional information | ||
* regarding copyright ownership. | ||
*/ | ||
package com.datastax.ai.agent.llmCache; | ||
|
||
import java.util.List; | ||
import java.util.concurrent.atomic.AtomicReference; | ||
|
||
import com.datastax.ai.agent.base.AiAgent; | ||
import com.datastax.ai.agent.base.AiAgentDelegator; | ||
import com.datastax.oss.driver.api.core.CqlSession; | ||
import com.datastax.oss.driver.api.core.type.DataTypes; | ||
import com.datastax.oss.driver.shaded.guava.common.base.Preconditions; | ||
import java.time.Instant; | ||
import java.util.Map; | ||
import java.util.UUID; | ||
|
||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
import org.springframework.ai.chat.ChatResponse; | ||
import org.springframework.ai.chat.Generation; | ||
import org.springframework.ai.chat.messages.SystemMessage; | ||
import org.springframework.ai.chat.messages.UserMessage; | ||
import org.springframework.ai.chat.prompt.Prompt; | ||
import org.springframework.ai.document.Document; | ||
import org.springframework.ai.embedding.EmbeddingClient; | ||
import org.springframework.ai.vectorstore.CassandraVectorStore; | ||
import org.springframework.ai.vectorstore.CassandraVectorStoreConfig; | ||
import org.springframework.ai.vectorstore.CassandraVectorStoreConfig.DocumentIdTranslator; | ||
import org.springframework.ai.vectorstore.CassandraVectorStoreConfig.SchemaColumn; | ||
import org.springframework.ai.vectorstore.SearchRequest; | ||
|
||
import reactor.core.publisher.Flux; | ||
|
||
public class AiAgentSessionVector extends AiAgentDelegator { | ||
|
||
private static final CassandraVectorStoreConfig.PrimaryKeyTranslator PRIMARY_KEY_TRANSLATOR | ||
= (pKeyColumns) -> { | ||
if (pKeyColumns.isEmpty()) { | ||
return UUID.randomUUID().toString() + "§¶0"; | ||
} | ||
Preconditions.checkArgument(2 == pKeyColumns.size()); | ||
|
||
String sessionId = pKeyColumns.get(0) instanceof UUID | ||
? ((UUID) pKeyColumns.get(0)).toString() | ||
: (String)pKeyColumns.get(0); | ||
|
||
String exchangeTimestamp = pKeyColumns.get(1) instanceof Instant | ||
? String.valueOf(((Instant) pKeyColumns.get(1)).toEpochMilli()) | ||
: (String) pKeyColumns.get(1); | ||
|
||
return sessionId.toString() + "§¶" + exchangeTimestamp; | ||
}; | ||
|
||
private static final DocumentIdTranslator DOCUMENT_ID_TRANSLATOR | ||
= (id) -> { | ||
String[] parts = id.split("§¶"); | ||
Preconditions.checkArgument(2 == parts.length); | ||
UUID sessionId = UUID.fromString(parts[0]); | ||
Instant exchangeTimestamp = Instant.ofEpochMilli(Long.parseLong(parts[1])); | ||
return List.of(sessionId, exchangeTimestamp); | ||
}; | ||
|
||
private static final Logger logger = LoggerFactory.getLogger(AiAgentSessionVector.class); | ||
|
||
private final AiAgent agent; | ||
private final CassandraVectorStore store; | ||
|
||
public static AiAgentSessionVector create(AiAgent agent, CqlSession cqlSession, EmbeddingClient embeddingClient) { | ||
return new AiAgentSessionVector(agent, cqlSession, embeddingClient); | ||
} | ||
|
||
AiAgentSessionVector(AiAgent agent, CqlSession cqlSession, EmbeddingClient embeddingClient) { | ||
super(agent); | ||
this.agent = agent; | ||
|
||
CassandraVectorStoreConfig config = CassandraVectorStoreConfig.builder() | ||
.withCqlSession(cqlSession) | ||
.withKeyspaceName("datastax_ai_agent") | ||
.withTableName("agent_conversations") | ||
.withPartitionKeys(List.of(new SchemaColumn("session_id", DataTypes.TIMEUUID))) | ||
.withClusteringKeys(List.of(new SchemaColumn("exchange_timestamp", DataTypes.TIMESTAMP))) | ||
.withContentColumnName("prompt_request") | ||
.addMetadataColumn(new SchemaColumn("prompt_response", DataTypes.TEXT)) | ||
.withPrimaryKeyTranslator(PRIMARY_KEY_TRANSLATOR) | ||
.withDocumentIdTranslator(DOCUMENT_ID_TRANSLATOR) | ||
.build(); | ||
|
||
this.store = new CassandraVectorStore(config, embeddingClient); | ||
} | ||
|
||
@Override | ||
public Flux<ChatResponse> send(Prompt prompt) { | ||
|
||
final UserMessage userMsg = (UserMessage) prompt.getInstructions() | ||
.stream().filter(m -> m instanceof UserMessage).findFirst().get(); | ||
|
||
final SystemMessage systemMsg = (SystemMessage) prompt.getInstructions() | ||
.stream().filter(m -> m instanceof SystemMessage).findFirst().get(); | ||
|
||
// AiAgentSession is expected to have put these into the UserMessage | ||
Preconditions.checkState(userMsg.getProperties().containsKey("ChatExchange_sessionId")); | ||
Preconditions.checkState(userMsg.getProperties().containsKey("ChatExchange_exchange_timestamp")); | ||
|
||
SearchRequest request = SearchRequest | ||
.query(userMsg.getContent()) | ||
.withTopK(10) | ||
.withSimilarityThreshold(0.99); | ||
|
||
List<Document> similarPromptResponses = store.similaritySearch(request); | ||
if (!similarPromptResponses.isEmpty()) { | ||
String similarResponse = (String) similarPromptResponses.get(0).getMetadata().get("prompt_response"); | ||
return Flux.just(new ChatResponse(List.of(new Generation(similarResponse)))); | ||
} else { | ||
|
||
final AtomicReference<StringBuilder> stringBufferRef = new AtomicReference<>(); | ||
|
||
return agent.send(prompt).doOnSubscribe(subscription -> { | ||
stringBufferRef.set(new StringBuilder()); | ||
}).doOnNext(chatResponse -> { | ||
if (null != chatResponse.getResult()) { | ||
if (null != chatResponse.getResult().getOutput().getContent()) { | ||
stringBufferRef.get().append(chatResponse.getResult().getOutput().getContent()); | ||
} | ||
} | ||
}).doOnComplete(() -> { | ||
|
||
Document promptRequestResponse = new Document( | ||
PRIMARY_KEY_TRANSLATOR.apply(List.of( | ||
userMsg.getProperties().get("ChatExchange_sessionId"), | ||
userMsg.getProperties().get("ChatExchange_exchange_timestamp"))), | ||
userMsg.getContent(), | ||
Map.of("prompt_response", stringBufferRef.get().toString())); | ||
|
||
store.add(List.of(promptRequestResponse)); | ||
|
||
stringBufferRef.set(null); | ||
}).doOnError(e -> { | ||
logger.error("Aggregation Error", e); | ||
stringBufferRef.set(null); | ||
}); | ||
} | ||
} | ||
|
||
} |
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
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