-
Notifications
You must be signed in to change notification settings - Fork 819
SOLR-18187: Document enrichment with LLMs #4259
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
Draft
nicolo-rinaldi
wants to merge
18
commits into
apache:main
Choose a base branch
from
SeaseLtd:llm-document-enrichment
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
b11d049
[llm-document-erichment] Add first revision of the feature
nicolo-rinaldi dfb27ab
[llm-document-enrichment] First working version
nicolo-rinaldi 827548a
[llm-document-enrichment] Add promptFile feature to DocumentEnrichmen…
nicolo-rinaldi cc94317
[llm-document-enrichment] Add multiple inputField support + tests
nicolo-rinaldi c723362
[llm-document-enrchment] Add supprot for:
nicolo-rinaldi cf0d6bb
[llm-document-enrichment] polished code, added tests and added file f…
nicolo-rinaldi 570c2aa
[llm-document-enrichment] updated supported models + added tests
nicolo-rinaldi 184f579
[llm-document-enrichment] added documentation for 'Document Enrichmen…
nicolo-rinaldi 1b7c972
[llm-document-enrichment] cleanup of DocumentEnrichmentUpdateProcesso…
nicolo-rinaldi 9cf0315
Merge branch 'main' into llm-document-enrichment
nicolo-rinaldi 36208af
Merge branch 'main' into llm-document-enrichment
nicolo-rinaldi 3d29d16
[llm-document-enrichment] Addressed comments in Anna's review
nicolo-rinaldi 55ff9ab
[llm-document-enrichment] Addressed comments in Anna's review
nicolo-rinaldi ed40008
[llm-document-enrichment] Fixed broken tests and updated documentation
nicolo-rinaldi ba27be1
[llm-document-enrichment] Added tests, Exception for multiple output …
nicolo-rinaldi b092f22
[llm-document-enrichment] Updated documentation
nicolo-rinaldi 6e9525d
Merge branch 'main' into llm-document-enrichment
nicolo-rinaldi 4f39e40
[llm-document-enrichment] Pre-check changes
nicolo-rinaldi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,4 @@ | ||
| title: Add DocumentEnrichmentUpdateProcessorFactory for LLM-based document enrichment at index time | ||
| type: added # added, changed, fixed, deprecated, removed, dependency_update, security, other | ||
| authors: | ||
| - name: Nicolò Rinaldi |
This file contains hidden or 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 hidden or 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 @@ | ||
| 905f570cd38c2ebd94fa159f2e88bca06bbf71c8 |
This file contains hidden or 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 @@ | ||
| 49973974543318de23f3f09b21c79d5e45815d8c |
This file contains hidden or 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 @@ | ||
| e3c631fa2fce6e79ad50fc86adb724656992263a |
This file contains hidden or 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 hidden or 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
211 changes: 211 additions & 0 deletions
211
...odels/src/java/org/apache/solr/languagemodels/documentenrichment/model/SolrChatModel.java
This file contains hidden or 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,211 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You 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 | ||
| * | ||
| * http://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.apache.solr.languagemodels.documentenrichment.model; | ||
|
|
||
| import dev.langchain4j.data.message.UserMessage; | ||
| import dev.langchain4j.model.chat.ChatModel; | ||
| import dev.langchain4j.model.chat.request.ChatRequest; | ||
| import dev.langchain4j.model.chat.request.ResponseFormat; | ||
| import java.lang.invoke.MethodHandles; | ||
| import java.lang.reflect.Method; | ||
| import java.time.Duration; | ||
| import java.util.ArrayList; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
| import org.apache.lucene.util.Accountable; | ||
| import org.apache.lucene.util.RamUsageEstimator; | ||
| import org.apache.solr.common.SolrException; | ||
| import org.apache.solr.common.util.Utils; | ||
| import org.apache.solr.core.SolrResourceLoader; | ||
| import org.apache.solr.languagemodels.documentenrichment.store.ChatModelException; | ||
| import org.apache.solr.languagemodels.documentenrichment.store.rest.ManagedChatModelStore; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| /** | ||
| * This object wraps a {@link dev.langchain4j.model.chat.ChatModel} to produce the content of a | ||
| * field based on the content of other fields specified as input. It's meant to be used as a managed | ||
| * resource with the {@link ManagedChatModelStore} | ||
| */ | ||
| public class SolrChatModel implements Accountable { | ||
| private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); | ||
| private static final long BASE_RAM_BYTES = | ||
| RamUsageEstimator.shallowSizeOfInstance(SolrChatModel.class); | ||
| private static final String TIMEOUT_PARAM = "timeout"; | ||
| private static final String MAX_RETRIES_PARAM = "maxRetries"; | ||
| private static final String THINKING_BUDGET_TOKENS = "thinkingBudgetTokens"; | ||
| private static final String RANDOM_SEED = "randomSeed"; | ||
|
|
||
| private final String name; | ||
| private final Map<String, Object> params; | ||
| private final ChatModel chatModel; | ||
| private final int hashCode; | ||
|
|
||
| public static SolrChatModel getInstance( | ||
| SolrResourceLoader solrResourceLoader, | ||
| String className, | ||
| String name, | ||
| Map<String, Object> params) | ||
| throws ChatModelException { | ||
| try { | ||
| /* | ||
| * The idea here is to build a {@link dev.langchain4j.model.chat.ChatModel} using inversion | ||
| * of control. | ||
| * Each model has its own list of parameters we don't know beforehand, but each {@link dev.langchain4j.model.chat.ChatModel} class | ||
| * has its own builder that uses setters with the same name of the parameter in input. | ||
| * */ | ||
| ChatModel chatModel; | ||
| Class<?> modelClass = solrResourceLoader.findClass(className, ChatModel.class); | ||
| var builder = modelClass.getMethod("builder").invoke(null); | ||
| if (params != null) { | ||
| /* | ||
| * This block of code has the responsibility of instantiate a {@link | ||
| * dev.langchain4j.model.chat.ChatModel} using the params provided. Classes have | ||
| * params of the specific implementation of {@link | ||
| * dev.langchain4j.model.chat.ChatModel}, which is not known beforehand. So we benefit of | ||
| * the design choice in langchain4j that each subclass implementing {@link | ||
| * dev.langchain4j.model.chat.ChatModel} uses setters with the same name of the | ||
| * param. | ||
| */ | ||
| for (String paramName : params.keySet()) { | ||
| /* | ||
| * When a param is not primitive, we need to instantiate the object explicitly and then call the | ||
| * setter method. | ||
| * N.B. when adding support to new models, pay attention to all the parameters they | ||
| * support, some of them may require to be handled in here as separate switch cases | ||
| */ | ||
| switch (paramName) { | ||
| case TIMEOUT_PARAM -> builder | ||
| .getClass() | ||
| .getMethod(paramName, Duration.class) | ||
| .invoke(builder, Duration.ofSeconds((Long) params.get(paramName))); | ||
|
|
||
| case MAX_RETRIES_PARAM, THINKING_BUDGET_TOKENS, RANDOM_SEED -> builder | ||
| .getClass() | ||
| .getMethod(paramName, Integer.class) | ||
| .invoke(builder, ((Long) params.get(paramName)).intValue()); | ||
|
|
||
| /* | ||
| * For primitive params if there's only one setter available, we call it. | ||
| * If there's choice we default to the string one | ||
| */ | ||
| default -> { | ||
| ArrayList<Method> paramNameMatches = new ArrayList<>(); | ||
| for (var method : builder.getClass().getMethods()) { | ||
| if (paramName.equals(method.getName()) && method.getParameterCount() == 1) { | ||
| paramNameMatches.add(method); | ||
| } | ||
| } | ||
| if (paramNameMatches.size() == 1) { | ||
| paramNameMatches.getFirst().invoke(builder, params.get(paramName)); | ||
| } else { | ||
| try { | ||
| builder | ||
| .getClass() | ||
| .getMethod(paramName, String.class) | ||
| .invoke(builder, params.get(paramName).toString()); | ||
| } catch (NoSuchMethodException e) { | ||
| log.error("Parameter {} not supported by model {}", paramName, className); | ||
| throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| chatModel = (ChatModel) builder.getClass().getMethod("build").invoke(builder); | ||
| return new SolrChatModel(name, chatModel, params); | ||
| } catch (final Exception e) { | ||
| throw new ChatModelException("Model loading failed for " + className, e); | ||
| } | ||
| } | ||
|
|
||
| public SolrChatModel(String name, ChatModel chatModel, Map<String, Object> params) { | ||
| this.name = name; | ||
| this.chatModel = chatModel; | ||
| this.params = params; | ||
| this.hashCode = calculateHashCode(); | ||
| } | ||
|
|
||
| /** | ||
| * Sends a structured chat request and returns the parsed value from the {@code {"value": ...}} | ||
| * JSON object that the model is instructed to produce via {@code responseFormat}. | ||
| * | ||
| * @return the extracted value: a {@link String}, {@link Number}, {@link Integer}, {@link | ||
| * Boolean}, or {@link java.util.List} depending on the Solr output field type | ||
| */ | ||
| public Object chat(String prompt, ResponseFormat responseFormat) { | ||
| ChatRequest chatRequest = | ||
| ChatRequest.builder() | ||
| .responseFormat(responseFormat) | ||
| .messages(UserMessage.from(prompt)) | ||
| .build(); | ||
| String rawJson = chatModel.chat(chatRequest).aiMessage().text(); | ||
| Object parsed = Utils.fromJSONString(rawJson); | ||
| if (!(parsed instanceof Map<?, ?> map) || !map.containsKey("value")) { | ||
|
nicolo-rinaldi marked this conversation as resolved.
|
||
| throw new SolrException( | ||
|
nicolo-rinaldi marked this conversation as resolved.
|
||
| SolrException.ErrorCode.SERVER_ERROR, | ||
| "LLM was not able to format the response correctly: " + rawJson); | ||
| } | ||
| return map.get("value"); | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return getClass().getSimpleName() + "(name=" + getName() + ")"; | ||
| } | ||
|
|
||
| @Override | ||
| public long ramBytesUsed() { | ||
| return BASE_RAM_BYTES | ||
| + RamUsageEstimator.sizeOfObject(name) | ||
| + RamUsageEstimator.sizeOfObject(chatModel); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return hashCode; | ||
| } | ||
|
|
||
| private int calculateHashCode() { | ||
| final int prime = 31; | ||
| int result = 1; | ||
| result = (prime * result) + Objects.hashCode(name); | ||
| result = (prime * result) + Objects.hashCode(chatModel); | ||
| return result; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean equals(Object obj) { | ||
| if (this == obj) return true; | ||
| if (!(obj instanceof SolrChatModel)) return false; | ||
| final SolrChatModel other = (SolrChatModel) obj; | ||
| return Objects.equals(chatModel, other.chatModel) && Objects.equals(name, other.name); | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public String getChatModelClassName() { | ||
| return chatModel.getClass().getName(); | ||
| } | ||
|
|
||
| public Map<String, Object> getParams() { | ||
| return params; | ||
| } | ||
| } | ||
19 changes: 19 additions & 0 deletions
19
...models/src/java/org/apache/solr/languagemodels/documentenrichment/model/package-info.java
This file contains hidden or 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,19 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You 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 | ||
| * | ||
| * http://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. | ||
| */ | ||
|
|
||
| /** APIs and classes for implementing text to vector logic. */ | ||
| package org.apache.solr.languagemodels.documentenrichment.model; |
30 changes: 30 additions & 0 deletions
30
.../src/java/org/apache/solr/languagemodels/documentenrichment/store/ChatModelException.java
This file contains hidden or 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,30 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You 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 | ||
| * | ||
| * http://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.apache.solr.languagemodels.documentenrichment.store; | ||
|
|
||
| public class ChatModelException extends RuntimeException { | ||
|
|
||
| private static final long serialVersionUID = 1L; | ||
|
|
||
| public ChatModelException(String message) { | ||
| super(message); | ||
| } | ||
|
|
||
| public ChatModelException(String message, Exception cause) { | ||
| super(message, cause); | ||
| } | ||
| } |
66 changes: 66 additions & 0 deletions
66
...dels/src/java/org/apache/solr/languagemodels/documentenrichment/store/ChatModelStore.java
This file contains hidden or 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,66 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You 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 | ||
| * | ||
| * http://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.apache.solr.languagemodels.documentenrichment.store; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.LinkedHashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import org.apache.solr.languagemodels.documentenrichment.model.SolrChatModel; | ||
|
|
||
| /** Simple store to manage CRUD operations on the {@link SolrChatModel} */ | ||
| public class ChatModelStore { | ||
|
|
||
| private final Map<String, SolrChatModel> availableModels; | ||
|
|
||
| public ChatModelStore() { | ||
| availableModels = Collections.synchronizedMap(new LinkedHashMap<>()); | ||
| } | ||
|
|
||
| public SolrChatModel getModel(String name) { | ||
| return availableModels.get(name); | ||
| } | ||
|
|
||
| public void clear() { | ||
| availableModels.clear(); | ||
| } | ||
|
|
||
| public List<SolrChatModel> getModels() { | ||
| synchronized (availableModels) { | ||
| final List<SolrChatModel> availableModelsValues = new ArrayList<>(availableModels.values()); | ||
| return Collections.unmodifiableList(availableModelsValues); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "ChatModelStore [availableModels=" + availableModels.keySet() + "]"; | ||
| } | ||
|
|
||
| public SolrChatModel delete(String modelName) { | ||
| return availableModels.remove(modelName); | ||
| } | ||
|
|
||
| public void addModel(SolrChatModel modeldata) throws ChatModelException { | ||
| final String name = modeldata.getName(); | ||
| if (availableModels.putIfAbsent(modeldata.getName(), modeldata) != null) { | ||
| throw new ChatModelException( | ||
| "model '" + name + "' already exists. Please use a different name"); | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.