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

Enable semantic cache with @CacheResult #659

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package io.quarkiverse.langchain4j.deployment;

import static io.quarkus.runtime.annotations.ConfigPhase.BUILD_TIME;

import io.quarkus.runtime.annotations.ConfigRoot;
import io.smallrye.config.ConfigMapping;

@ConfigRoot(phase = BUILD_TIME)
@ConfigMapping(prefix = "quarkus.langchain4j.cache")
public interface AiCacheBuildConfig {

/**
* Ai Cache embedding model related settings
*/
CacheEmbeddingModelConfig embedding();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package io.quarkiverse.langchain4j.deployment;

import io.quarkus.builder.item.SimpleBuildItem;

public final class AiCacheBuildItem extends SimpleBuildItem {

private boolean enable;
private String embeddingModelName;

public AiCacheBuildItem(boolean enable, String embeddingModelName) {
this.enable = enable;
this.embeddingModelName = embeddingModelName;
}

public boolean isEnable() {
return enable;
}

public String getEmbeddingModelName() {
return embeddingModelName;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package io.quarkiverse.langchain4j.deployment;

import jakarta.enterprise.context.ApplicationScoped;

import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.ClassType;
import org.jboss.jandex.IndexView;

import dev.langchain4j.model.embedding.EmbeddingModel;
import io.quarkiverse.langchain4j.ModelName;
import io.quarkiverse.langchain4j.runtime.AiCacheRecorder;
import io.quarkiverse.langchain4j.runtime.NamedConfigUtil;
import io.quarkiverse.langchain4j.runtime.cache.AiCacheProvider;
import io.quarkiverse.langchain4j.runtime.cache.AiCacheStore;
import io.quarkiverse.langchain4j.runtime.cache.config.AiCacheConfig;
import io.quarkus.arc.deployment.SyntheticBeanBuildItem;
import io.quarkus.arc.deployment.UnremovableBeanBuildItem;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;

public class AiCacheProcessor {

@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
void setupBeans(AiCacheBuildConfig cacheBuildConfig,
AiCacheConfig cacheConfig,
AiCacheRecorder recorder,
CombinedIndexBuildItem indexBuildItem,
BuildProducer<AiCacheBuildItem> aiCacheBuildItemProducer,
BuildProducer<UnremovableBeanBuildItem> unremovableProducer,
BuildProducer<SyntheticBeanBuildItem> syntheticBeanProducer) {

IndexView index = indexBuildItem.getIndex();
boolean enableCache = false;

for (AnnotationInstance instance : index.getAnnotations(LangChain4jDotNames.REGISTER_AI_SERVICES)) {
if (instance.target().kind() != AnnotationTarget.Kind.CLASS) {
continue;
}

ClassInfo declarativeAiServiceClassInfo = instance.target().asClass();

if (declarativeAiServiceClassInfo.hasAnnotation(LangChain4jDotNames.CACHE_RESULT)) {
enableCache = true;
break;
}
}

String embeddingModelName = NamedConfigUtil.DEFAULT_NAME;
if (cacheBuildConfig.embedding() != null)
embeddingModelName = cacheBuildConfig.embedding().name().orElse(NamedConfigUtil.DEFAULT_NAME);

aiCacheBuildItemProducer.produce(new AiCacheBuildItem(enableCache, embeddingModelName));

if (enableCache) {
SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem
.configure(AiCacheProvider.class)
.setRuntimeInit()
.addInjectionPoint(ClassType.create(AiCacheStore.class))
.scope(ApplicationScoped.class)
.createWith(recorder.messageWindow(cacheConfig, embeddingModelName))
.defaultBean();

if (NamedConfigUtil.isDefault(embeddingModelName)) {
configurator.addInjectionPoint(ClassType.create(LangChain4jDotNames.EMBEDDING_MODEL));
} else {
configurator.addInjectionPoint(ClassType.create(LangChain4jDotNames.EMBEDDING_MODEL),
AnnotationInstance.builder(ModelName.class).add("value", embeddingModelName).build());
}

syntheticBeanProducer.produce(configurator.done());
unremovableProducer.produce(UnremovableBeanBuildItem.beanTypes(AiCacheStore.class));
unremovableProducer.produce(UnremovableBeanBuildItem.beanTypes(EmbeddingModel.class));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@
import org.objectweb.asm.tree.analysis.AnalyzerException;

import dev.langchain4j.exception.IllegalConfigurationException;
import dev.langchain4j.service.Moderate;
import io.quarkiverse.langchain4j.ModelName;
import io.quarkiverse.langchain4j.ToolBox;
import io.quarkiverse.langchain4j.deployment.config.LangChain4jBuildConfig;
Expand Down Expand Up @@ -189,6 +188,7 @@ public void findDeclarativeServices(CombinedIndexBuildItem indexBuildItem,

Set<String> chatModelNames = new HashSet<>();
Set<String> moderationModelNames = new HashSet<>();

for (AnnotationInstance instance : index.getAnnotations(LangChain4jDotNames.REGISTER_AI_SERVICES)) {
if (instance.target().kind() != AnnotationTarget.Kind.CLASS) {
continue; // should never happen
Expand All @@ -210,14 +210,11 @@ public void findDeclarativeServices(CombinedIndexBuildItem indexBuildItem,
}

String chatModelName = NamedConfigUtil.DEFAULT_NAME;
String moderationModelName = NamedConfigUtil.DEFAULT_NAME;

if (chatLanguageModelSupplierClassDotName == null) {
AnnotationValue modelNameValue = instance.value("modelName");
if (modelNameValue != null) {
String modelNameValueStr = modelNameValue.asString();
if ((modelNameValueStr != null) && !modelNameValueStr.isEmpty()) {
chatModelName = modelNameValueStr;
}
}
chatModelName = getModelName(modelNameValue);
chatModelNames.add(chatModelName);
}

Expand All @@ -243,6 +240,18 @@ public void findDeclarativeServices(CombinedIndexBuildItem indexBuildItem,
}
}

// the default value depends on whether tools exists or not - if they do, then we require a AiCacheProvider bean
DotName aiCacheProviderSupplierClassDotName = LangChain4jDotNames.BEAN_AI_CACHE_PROVIDER_SUPPLIER;
AnnotationValue aiCacheProviderSupplierValue = instance.value("cacheProviderSupplier");
if (aiCacheProviderSupplierValue != null) {
aiCacheProviderSupplierClassDotName = aiCacheProviderSupplierValue.asClass().name();
if (!aiCacheProviderSupplierClassDotName
.equals(LangChain4jDotNames.BEAN_AI_CACHE_PROVIDER_SUPPLIER)) {
validateSupplierAndRegisterForReflection(aiCacheProviderSupplierClassDotName, index,
reflectiveClassProducer);
}
}

DotName retrieverClassDotName = null;
AnnotationValue retrieverValue = instance.value("retriever");
if (retrieverValue != null) {
Expand Down Expand Up @@ -296,17 +305,11 @@ public void findDeclarativeServices(CombinedIndexBuildItem indexBuildItem,
}

// determine whether the method is annotated with @Moderate
String moderationModelName = NamedConfigUtil.DEFAULT_NAME;
for (MethodInfo method : declarativeAiServiceClassInfo.methods()) {
if (method.hasAnnotation(LangChain4jDotNames.MODERATE)) {
if (moderationModelSupplierClassName.equals(LangChain4jDotNames.BEAN_IF_EXISTS_MODERATION_MODEL_SUPPLIER)) {
AnnotationValue modelNameValue = instance.value("modelName");
if (modelNameValue != null) {
String modelNameValueStr = modelNameValue.asString();
if ((modelNameValueStr != null) && !modelNameValueStr.isEmpty()) {
moderationModelName = modelNameValueStr;
}
}
moderationModelName = getModelName(modelNameValue);
moderationModelNames.add(moderationModelName);
}
break;
Expand All @@ -325,13 +328,15 @@ public void findDeclarativeServices(CombinedIndexBuildItem indexBuildItem,
chatLanguageModelSupplierClassDotName,
toolDotNames,
chatMemoryProviderSupplierClassDotName,
aiCacheProviderSupplierClassDotName,
retrieverClassDotName,
retrievalAugmentorSupplierClassName,
customRetrievalAugmentorSupplierClassIsABean,
auditServiceSupplierClassName,
moderationModelSupplierClassName,
cdiScope,
chatModelName, moderationModelName));
chatModelName,
moderationModelName));
}

for (String chatModelName : chatModelNames) {
Expand Down Expand Up @@ -365,7 +370,8 @@ public void handleDeclarativeServices(AiServicesRecorder recorder,
List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems,
List<SelectedChatModelProviderBuildItem> selectedChatModelProvider,
BuildProducer<SyntheticBeanBuildItem> syntheticBeanProducer,
BuildProducer<UnremovableBeanBuildItem> unremoveableProducer) {
BuildProducer<UnremovableBeanBuildItem> unremoveableProducer,
AiCacheBuildItem aiCacheBuildItem) {

boolean needsChatModelBean = false;
boolean needsStreamingChatModelBean = false;
Expand All @@ -374,6 +380,8 @@ public void handleDeclarativeServices(AiServicesRecorder recorder,
boolean needsRetrievalAugmentorBean = false;
boolean needsAuditServiceBean = false;
boolean needsModerationModelBean = false;
boolean needsAiCacheProvider = false;

Set<DotName> allToolNames = new HashSet<>();

for (DeclarativeAiServiceBuildItem bi : declarativeAiServiceItems) {
Expand All @@ -390,6 +398,10 @@ public void handleDeclarativeServices(AiServicesRecorder recorder,
? bi.getChatMemoryProviderSupplierClassDotName().toString()
: null;

String aiCacheProviderSupplierClassName = bi.getAiCacheProviderSupplierClassDotName() != null
? bi.getAiCacheProviderSupplierClassDotName().toString()
: null;

String retrieverClassName = bi.getRetrieverClassDotName() != null
? bi.getRetrieverClassDotName().toString()
: null;
Expand All @@ -407,7 +419,7 @@ public void handleDeclarativeServices(AiServicesRecorder recorder,
: null);

// determine whether the method returns Multi<String>
boolean injectStreamingChatModelBean = false;
boolean needsStreamingChatModel = false;
for (MethodInfo method : declarativeAiServiceClassInfo.methods()) {
if (!LangChain4jDotNames.MULTI.equals(method.returnType().name())) {
continue;
Expand All @@ -423,29 +435,41 @@ public void handleDeclarativeServices(AiServicesRecorder recorder,
throw illegalConfiguration("Only Multi<String> is supported as a Multi return type. Offending method is '"
+ method.declaringClass().name().toString() + "#" + method.name() + "'");
}
injectStreamingChatModelBean = true;
needsStreamingChatModel = true;
}

boolean injectModerationModelBean = false;
boolean needsModerationModel = false;
for (MethodInfo method : declarativeAiServiceClassInfo.methods()) {
if (method.hasAnnotation(Moderate.class)) {
injectModerationModelBean = true;
if (method.hasAnnotation(LangChain4jDotNames.MODERATE)) {
needsModerationModel = true;
break;
}
}

String chatModelName = bi.getChatModelName();
String moderationModelName = bi.getModerationModelName();
boolean enableCache = aiCacheBuildItem.isEnable();

// It is not possible to use the cache in combination with the tools.
if (!toolClassNames.isEmpty() && enableCache
&& declarativeAiServiceClassInfo.hasAnnotation(LangChain4jDotNames.CACHE_RESULT)) {
throw new RuntimeException("The cache cannot be used in combination with the tools. Affected class: %s"
.formatted(serviceClassName));
}

SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem
.configure(QuarkusAiServiceContext.class)
.forceApplicationClass()
.createWith(recorder.createDeclarativeAiService(
new DeclarativeAiServiceCreateInfo(serviceClassName, chatLanguageModelSupplierClassName,
toolClassNames, chatMemoryProviderSupplierClassName, retrieverClassName,
toolClassNames, chatMemoryProviderSupplierClassName, aiCacheProviderSupplierClassName,
retrieverClassName,
retrievalAugmentorSupplierClassName,
auditServiceClassSupplierName, moderationModelSupplierClassName, chatModelName,
moderationModelName,
injectStreamingChatModelBean, injectModerationModelBean)))
needsStreamingChatModel,
needsModerationModel,
enableCache)))
.setRuntimeInit()
.addQualifier()
.annotation(LangChain4jDotNames.QUARKUS_AI_SERVICE_CONTEXT_QUALIFIER).addValue("value", serviceClassName)
Expand All @@ -455,15 +479,15 @@ public void handleDeclarativeServices(AiServicesRecorder recorder,
if ((chatLanguageModelSupplierClassName == null) && !selectedChatModelProvider.isEmpty()) {
if (NamedConfigUtil.isDefault(chatModelName)) {
configurator.addInjectionPoint(ClassType.create(LangChain4jDotNames.CHAT_MODEL));
if (injectStreamingChatModelBean) {
if (needsStreamingChatModel) {
configurator.addInjectionPoint(ClassType.create(LangChain4jDotNames.STREAMING_CHAT_MODEL));
needsStreamingChatModelBean = true;
}
} else {
configurator.addInjectionPoint(ClassType.create(LangChain4jDotNames.CHAT_MODEL),
AnnotationInstance.builder(ModelName.class).add("value", chatModelName).build());

if (injectStreamingChatModelBean) {
if (needsStreamingChatModel) {
configurator.addInjectionPoint(ClassType.create(LangChain4jDotNames.STREAMING_CHAT_MODEL),
AnnotationInstance.builder(ModelName.class).add("value", chatModelName).build());
needsStreamingChatModelBean = true;
Expand Down Expand Up @@ -519,7 +543,7 @@ public void handleDeclarativeServices(AiServicesRecorder recorder,
}

if (LangChain4jDotNames.BEAN_IF_EXISTS_MODERATION_MODEL_SUPPLIER.toString()
.equals(moderationModelSupplierClassName) && injectModerationModelBean) {
.equals(moderationModelSupplierClassName) && needsModerationModel) {

if (NamedConfigUtil.isDefault(moderationModelName)) {
configurator.addInjectionPoint(ClassType.create(LangChain4jDotNames.MODERATION_MODEL));
Expand All @@ -531,6 +555,16 @@ public void handleDeclarativeServices(AiServicesRecorder recorder,
needsModerationModelBean = true;
}

if (enableCache) {

if (LangChain4jDotNames.BEAN_AI_CACHE_PROVIDER_SUPPLIER.toString().equals(aiCacheProviderSupplierClassName)) {
configurator.addInjectionPoint(ClassType.create(LangChain4jDotNames.AI_CACHE_PROVIDER));
} else {
configurator.addInjectionPoint(ClassType.create(LangChain4jDotNames.AI_CACHE_PROVIDER));
}
needsAiCacheProvider = true;
}

syntheticBeanProducer.produce(configurator.done());
}

Expand All @@ -555,6 +589,9 @@ public void handleDeclarativeServices(AiServicesRecorder recorder,
if (needsModerationModelBean) {
unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(LangChain4jDotNames.MODERATION_MODEL));
}
if (needsAiCacheProvider) {
unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(LangChain4jDotNames.AI_CACHE_PROVIDER));
}
if (!allToolNames.isEmpty()) {
unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(allToolNames));
}
Expand Down Expand Up @@ -877,6 +914,8 @@ private AiServiceMethodCreateInfo gatherMethodMetadata(MethodInfo method, boolea

boolean requiresModeration = method.hasAnnotation(LangChain4jDotNames.MODERATE);
Class<?> returnType = JandexUtil.load(method.returnType(), Thread.currentThread().getContextClassLoader());
boolean requiresCache = method.declaringClass().hasDeclaredAnnotation(LangChain4jDotNames.CACHE_RESULT)
|| method.hasDeclaredAnnotation(LangChain4jDotNames.CACHE_RESULT);

List<MethodParameterInfo> params = method.parameters();

Expand Down Expand Up @@ -914,7 +953,7 @@ private AiServiceMethodCreateInfo gatherMethodMetadata(MethodInfo method, boolea
List<String> methodToolClassNames = gatherMethodToolClassNames(method);

return new AiServiceMethodCreateInfo(method.declaringClass().name().toString(), method.name(), systemMessageInfo,
userMessageInfo, memoryIdParamPosition, requiresModeration,
userMessageInfo, memoryIdParamPosition, requiresModeration, requiresCache,
returnType, metricsTimedInfo, metricsCountedInfo, spanInfo, responseSchemaInfo, methodToolClassNames);
}

Expand Down Expand Up @@ -1249,6 +1288,16 @@ static Map<String, Integer> toNameToArgsPositionMap(List<TemplateParameterInfo>
}
}

private String getModelName(AnnotationValue value) {
if (value != null) {
String modelNameValueStr = value.asString();
if ((modelNameValueStr != null) && !modelNameValueStr.isEmpty()) {
return modelNameValueStr;
}
}
return NamedConfigUtil.DEFAULT_NAME;
}

public static final class AiServicesMethodBuildItem extends MultiBuildItem {

private final MethodInfo methodInfo;
Expand Down
Loading
Loading