Package org.codelibs.fess.llm
Class AbstractLlmClient
java.lang.Object
org.codelibs.fess.llm.AbstractLlmClient
- All Implemented Interfaces:
LlmClient
- Direct Known Subclasses:
GeminiLlmClient,OllamaLlmClient,OpenAiLlmClient
Abstract base class for LLM client implementations.
Provides shared infrastructure (HTTP client, availability checking) and
default implementations of RAG workflow methods with injectable prompt templates.
Subclasses implement provider-specific chat/streamChat and checkAvailabilityNow.
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected StringCustom system prompt template for answer generation.protected org.codelibs.core.timer.TimeoutTaskThe scheduled task for periodic availability checks.protected BooleanCached availability status of the LLM provider.protected StringCustom system prompt for direct answer generation (without document search).protected StringCustom system prompt for document-not-found responses.protected StringCustom prompt template for relevance evaluation.protected StringCustom system prompt template for FAQ answer generation.protected org.apache.hc.client5.http.impl.classic.CloseableHttpClientThe HTTP client used for API communication.protected StringCustom prompt template for intent detection.protected StringCustom system prompt for no-results responses.protected static final com.fasterxml.jackson.databind.ObjectMapperShared ObjectMapper instance for JSON processing.protected StringCustom system prompt template for summary generation.protected StringCustom system prompt suffix for summary generation.protected StringCustom system prompt for unclear intent responses. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddHistory(LlmChatRequest request, List<LlmMessage> history) Adds conversation history to the request.protected StringbuildContext(List<Map<String, Object>> documents, org.codelibs.fess.mylasta.direction.FessConfig fessConfig) Builds context from document content for the LLM prompt.protected StringBuilds the evaluation prompt for relevance checking.protected StringbuildIntentDetectionPrompt(String userMessage) Builds the intent detection prompt.protected LlmChatRequestbuildStreamingRequest(org.codelibs.fess.mylasta.direction.FessConfig fessConfig, String userMessage, String context, List<LlmMessage> history) Builds a streaming LLM chat request with conversation history.protected abstract booleanPerforms the actual availability check against the LLM provider.voiddestroy()Cleans up resources.detectIntent(String userMessage) Detects the intent of a user message.Evaluates search results for relevance to the user's question.extractJsonArray(String json, String key) Extracts a string array from JSON response.protected booleanextractJsonBoolean(String json, String key) Extracts a boolean value from JSON response.extractJsonIntArray(String json, String key) Extracts an integer array from JSON response.protected StringextractJsonString(String json, String key) Extracts a string value from JSON response using Jackson parser.protected StringextractJsonStringFallback(String json, String key) Fallback regex-based extraction for string values.generateAnswer(String userMessage, List<Map<String, Object>> documents, List<LlmMessage> history) Generates an answer using document content (synchronous version for non-enhanced flow).voidgenerateDirectAnswer(String userMessage, List<LlmMessage> history, LlmStreamCallback callback) Generates a direct answer without document search.voidgenerateDocumentNotFoundResponse(String userMessage, String documentUrl, List<LlmMessage> history, LlmStreamCallback callback) Generates a response when the specified document URL is not found.voidgenerateFaqAnswerResponse(String userMessage, List<Map<String, Object>> documents, List<LlmMessage> history, LlmStreamCallback callback) Generates an FAQ answer using document content (streaming).voidgenerateNoResultsResponse(String userMessage, List<LlmMessage> history, LlmStreamCallback callback) Generates a response when no relevant documents are found.voidgenerateSummaryResponse(String userMessage, List<Map<String, Object>> documents, List<LlmMessage> history, LlmStreamCallback callback) Generates a summary of the specified documents.voidgenerateUnclearIntentResponse(String userMessage, List<LlmMessage> history, LlmStreamCallback callback) Generates a response asking user for clarification when intent is unclear.protected intGets the availability check interval in seconds.protected intGets the maximum tokens for result evaluation.org.apache.hc.client5.http.impl.classic.CloseableHttpClientGets the HTTP client, initializing it if necessary.protected intGets the maximum tokens for intent detection.protected StringGets the language instruction based on the user's locale.protected StringGets the configured LLM type.protected intGets the maximum tokens for the response.protected abstract StringgetModel()Gets the model name.protected StringgetStringValue(Map<String, Object> map, String key) Gets a string value from a map.protected doubleGets the temperature parameter.protected abstract intGets the request timeout in milliseconds.protected LocaleGets the user's locale from the current request context.voidinit()Initializes the HTTP client and starts availability checking.booleanChecks if this LLM client is available and properly configured.protected booleanChecks if RAG chat feature is enabled.protected RelevanceEvaluationResultParses the evaluation response from LLM.protected IntentDetectionResultparseIntentResponse(String response) Parses the LLM response and extracts intent detection result.protected StringresolveLanguageInstruction(String prompt) Resolves the {{languageInstruction}} placeholder in a prompt.voidsetAnswerGenerationSystemPrompt(String answerGenerationSystemPrompt) Sets the custom system prompt for answer generation.voidsetDirectAnswerSystemPrompt(String directAnswerSystemPrompt) Sets the custom system prompt for direct answer generation.voidsetDocumentNotFoundSystemPrompt(String documentNotFoundSystemPrompt) Sets the custom system prompt for document-not-found responses.voidsetEvaluationPrompt(String evaluationPrompt) Sets the custom evaluation prompt for relevance checking.voidsetFaqAnswerSystemPrompt(String faqAnswerSystemPrompt) Sets the custom system prompt for FAQ answer generation.voidsetIntentDetectionPrompt(String intentDetectionPrompt) Sets the custom prompt template for intent detection.voidsetNoResultsSystemPrompt(String noResultsSystemPrompt) Sets the custom system prompt for no-results responses.voidsetSummarySystemPrompt(String summarySystemPrompt) Sets the custom system prompt for summary generation.voidsetSummarySystemPromptSuffix(String summarySystemPromptSuffix) Sets the custom system prompt suffix for summary generation.voidsetUnclearIntentSystemPrompt(String unclearIntentSystemPrompt) Sets the custom system prompt for unclear intent responses.protected voidStarts periodic availability checking if RAG chat is enabled.voidstreamGenerateAnswer(String userMessage, List<Map<String, Object>> documents, List<LlmMessage> history, LlmStreamCallback callback) Generates an answer using document content (streaming version for enhanced flow).protected StringstripCodeFences(String response) Strips code fence markers from JSON response.protected voidUpdates the cached availability state.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.codelibs.fess.llm.LlmClient
chat, getName, streamChat
-
Field Details
-
objectMapper
protected static final com.fasterxml.jackson.databind.ObjectMapper objectMapperShared ObjectMapper instance for JSON processing. -
httpClient
protected org.apache.hc.client5.http.impl.classic.CloseableHttpClient httpClientThe HTTP client used for API communication. -
cachedAvailability
Cached availability status of the LLM provider. -
availabilityCheckTask
protected org.codelibs.core.timer.TimeoutTask availabilityCheckTaskThe scheduled task for periodic availability checks. -
intentDetectionPrompt
Custom prompt template for intent detection. Use${userMessage}as placeholder. -
unclearIntentSystemPrompt
Custom system prompt for unclear intent responses. -
noResultsSystemPrompt
Custom system prompt for no-results responses. -
documentNotFoundSystemPrompt
Custom system prompt for document-not-found responses. Use${documentUrl}as placeholder. -
summarySystemPromptSuffix
Custom system prompt suffix for summary generation. -
evaluationPrompt
Custom prompt template for relevance evaluation. Uses{{maxRelevantDocs}},{{userMessage}},{{query}},{{searchResults}}placeholders. -
answerGenerationSystemPrompt
Custom system prompt template for answer generation. Uses{{systemPrompt}},{{context}}placeholders. -
summarySystemPrompt
Custom system prompt template for summary generation. Uses{{systemPrompt}},{{documentContent}}placeholders. -
faqAnswerSystemPrompt
Custom system prompt template for FAQ answer generation. Uses{{systemPrompt}},{{context}}placeholders. -
directAnswerSystemPrompt
Custom system prompt for direct answer generation (without document search).
-
-
Constructor Details
-
AbstractLlmClient
public AbstractLlmClient()Default constructor.
-
-
Method Details
-
init
public void init()Initializes the HTTP client and starts availability checking. Should be called from subclass init() methods. -
destroy
public void destroy()Cleans up resources. -
startAvailabilityCheck
protected void startAvailabilityCheck()Starts periodic availability checking if RAG chat is enabled. -
updateAvailability
protected void updateAvailability()Updates the cached availability state. -
isAvailable
public boolean isAvailable()Description copied from interface:LlmClientChecks if this LLM client is available and properly configured.- Specified by:
isAvailablein interfaceLlmClient- Returns:
- true if the client is available, false otherwise
-
getHttpClient
public org.apache.hc.client5.http.impl.classic.CloseableHttpClient getHttpClient()Gets the HTTP client, initializing it if necessary.- Returns:
- the HTTP client
-
checkAvailabilityNow
protected abstract boolean checkAvailabilityNow()Performs the actual availability check against the LLM provider.- Returns:
- true if the provider is available
-
getTimeout
protected abstract int getTimeout()Gets the request timeout in milliseconds.- Returns:
- the timeout in milliseconds
-
getModel
Gets the model name.- Returns:
- the model name
-
getAvailabilityCheckInterval
protected int getAvailabilityCheckInterval()Gets the availability check interval in seconds.- Returns:
- the interval in seconds
-
isRagChatEnabled
protected boolean isRagChatEnabled()Checks if RAG chat feature is enabled.- Returns:
- true if RAG chat is enabled
-
getLlmType
Gets the configured LLM type.- Returns:
- the LLM type from configuration
-
getTemperature
protected double getTemperature()Gets the temperature parameter.- Returns:
- the temperature
-
getMaxTokens
protected int getMaxTokens()Gets the maximum tokens for the response.- Returns:
- the maximum tokens
-
getIntentDetectionMaxTokens
protected int getIntentDetectionMaxTokens()Gets the maximum tokens for intent detection.- Returns:
- the maximum tokens for intent detection
-
getEvaluationMaxTokens
protected int getEvaluationMaxTokens()Gets the maximum tokens for result evaluation.- Returns:
- the maximum tokens for result evaluation
-
setIntentDetectionPrompt
Sets the custom prompt template for intent detection.- Parameters:
intentDetectionPrompt- the prompt template with{{userMessage}}placeholder
-
setUnclearIntentSystemPrompt
Sets the custom system prompt for unclear intent responses.- Parameters:
unclearIntentSystemPrompt- the system prompt
-
setNoResultsSystemPrompt
Sets the custom system prompt for no-results responses.- Parameters:
noResultsSystemPrompt- the system prompt
-
setDocumentNotFoundSystemPrompt
Sets the custom system prompt for document-not-found responses.- Parameters:
documentNotFoundSystemPrompt- the system prompt with{{documentUrl}}placeholder
-
setSummarySystemPromptSuffix
Sets the custom system prompt suffix for summary generation.- Parameters:
summarySystemPromptSuffix- the prompt suffix
-
setEvaluationPrompt
Sets the custom evaluation prompt for relevance checking.- Parameters:
evaluationPrompt- the evaluation prompt template
-
setAnswerGenerationSystemPrompt
Sets the custom system prompt for answer generation.- Parameters:
answerGenerationSystemPrompt- the answer generation system prompt template
-
setSummarySystemPrompt
Sets the custom system prompt for summary generation.- Parameters:
summarySystemPrompt- the summary system prompt template
-
setFaqAnswerSystemPrompt
Sets the custom system prompt for FAQ answer generation.- Parameters:
faqAnswerSystemPrompt- the FAQ answer system prompt template
-
setDirectAnswerSystemPrompt
Sets the custom system prompt for direct answer generation.- Parameters:
directAnswerSystemPrompt- the direct answer system prompt
-
getUserLocale
Gets the user's locale from the current request context.- Returns:
- the user's locale, or default locale if not in request context
-
getLanguageInstruction
Gets the language instruction based on the user's locale.- Returns:
- the language instruction string, or empty string if locale is English
-
resolveLanguageInstruction
Resolves the {{languageInstruction}} placeholder in a prompt.- Parameters:
prompt- the prompt template- Returns:
- the prompt with language instruction resolved
-
detectIntent
Description copied from interface:LlmClientDetects the intent of a user message.- Specified by:
detectIntentin interfaceLlmClient- Parameters:
userMessage- the user's message- Returns:
- the detected intent with extracted keywords
-
evaluateResults
public RelevanceEvaluationResult evaluateResults(String userMessage, String query, List<Map<String, Object>> searchResults) Description copied from interface:LlmClientEvaluates search results for relevance to the user's question.- Specified by:
evaluateResultsin interfaceLlmClient- Parameters:
userMessage- the original user messagequery- the search query usedsearchResults- the search results to evaluate- Returns:
- evaluation result with relevant document IDs
-
generateAnswer
public LlmChatResponse generateAnswer(String userMessage, List<Map<String, Object>> documents, List<LlmMessage> history) Description copied from interface:LlmClientGenerates an answer using document content (synchronous version for non-enhanced flow).- Specified by:
generateAnswerin interfaceLlmClient- Parameters:
userMessage- the user's messagedocuments- the documents with contenthistory- the conversation history- Returns:
- the chat response
-
streamGenerateAnswer
public void streamGenerateAnswer(String userMessage, List<Map<String, Object>> documents, List<LlmMessage> history, LlmStreamCallback callback) Description copied from interface:LlmClientGenerates an answer using document content (streaming version for enhanced flow).- Specified by:
streamGenerateAnswerin interfaceLlmClient- Parameters:
userMessage- the user's messagedocuments- the documents with contenthistory- the conversation historycallback- the streaming callback
-
generateUnclearIntentResponse
public void generateUnclearIntentResponse(String userMessage, List<LlmMessage> history, LlmStreamCallback callback) Description copied from interface:LlmClientGenerates a response asking user for clarification when intent is unclear.- Specified by:
generateUnclearIntentResponsein interfaceLlmClient- Parameters:
userMessage- the user's messagehistory- the conversation historycallback- the streaming callback
-
generateNoResultsResponse
public void generateNoResultsResponse(String userMessage, List<LlmMessage> history, LlmStreamCallback callback) Description copied from interface:LlmClientGenerates a response when no relevant documents are found.- Specified by:
generateNoResultsResponsein interfaceLlmClient- Parameters:
userMessage- the user's messagehistory- the conversation historycallback- the streaming callback
-
generateDocumentNotFoundResponse
public void generateDocumentNotFoundResponse(String userMessage, String documentUrl, List<LlmMessage> history, LlmStreamCallback callback) Description copied from interface:LlmClientGenerates a response when the specified document URL is not found.- Specified by:
generateDocumentNotFoundResponsein interfaceLlmClient- Parameters:
userMessage- the user's messagedocumentUrl- the URL that was not foundhistory- the conversation historycallback- the streaming callback
-
generateSummaryResponse
public void generateSummaryResponse(String userMessage, List<Map<String, Object>> documents, List<LlmMessage> history, LlmStreamCallback callback) Description copied from interface:LlmClientGenerates a summary of the specified documents.- Specified by:
generateSummaryResponsein interfaceLlmClient- Parameters:
userMessage- the user's messagedocuments- the documents to summarizehistory- the conversation historycallback- the streaming callback
-
generateFaqAnswerResponse
public void generateFaqAnswerResponse(String userMessage, List<Map<String, Object>> documents, List<LlmMessage> history, LlmStreamCallback callback) Description copied from interface:LlmClientGenerates an FAQ answer using document content (streaming). Uses a prompt optimized for direct, concise FAQ-style answers.- Specified by:
generateFaqAnswerResponsein interfaceLlmClient- Parameters:
userMessage- the user's messagedocuments- the documents with contenthistory- the conversation historycallback- the streaming callback
-
generateDirectAnswer
public void generateDirectAnswer(String userMessage, List<LlmMessage> history, LlmStreamCallback callback) Description copied from interface:LlmClientGenerates a direct answer without document search.- Specified by:
generateDirectAnswerin interfaceLlmClient- Parameters:
userMessage- the user's messagehistory- the conversation historycallback- the streaming callback
-
buildIntentDetectionPrompt
Builds the intent detection prompt.- Parameters:
userMessage- the user's message- Returns:
- the constructed prompt string
-
buildEvaluationPrompt
protected String buildEvaluationPrompt(String userMessage, String query, List<Map<String, Object>> searchResults) Builds the evaluation prompt for relevance checking.- Parameters:
userMessage- the user's messagequery- the search querysearchResults- the search results to evaluate- Returns:
- the evaluation prompt
-
buildContext
protected String buildContext(List<Map<String, Object>> documents, org.codelibs.fess.mylasta.direction.FessConfig fessConfig) Builds context from document content for the LLM prompt.- Parameters:
documents- the search result documentsfessConfig- the Fess configuration- Returns:
- the context string
-
buildStreamingRequest
protected LlmChatRequest buildStreamingRequest(org.codelibs.fess.mylasta.direction.FessConfig fessConfig, String userMessage, String context, List<LlmMessage> history) Builds a streaming LLM chat request with conversation history.- Parameters:
fessConfig- the Fess configurationuserMessage- the user's messagecontext- the context from search resultshistory- the conversation history- Returns:
- the LLM chat request
-
parseIntentResponse
Parses the LLM response and extracts intent detection result.- Parameters:
response- the JSON response from LLM- Returns:
- the parsed intent detection result
-
parseEvaluationResponse
protected RelevanceEvaluationResult parseEvaluationResponse(String response, List<Map<String, Object>> searchResults) Parses the evaluation response from LLM.- Parameters:
response- the LLM responsesearchResults- the search results- Returns:
- the parsed evaluation result
-
stripCodeFences
Strips code fence markers from JSON response.- Parameters:
response- the response that may contain code fences- Returns:
- the response with code fences removed
-
extractJsonString
Extracts a string value from JSON response using Jackson parser.- Parameters:
json- the JSON responsekey- the key to extract- Returns:
- the extracted string value
-
extractJsonStringFallback
Fallback regex-based extraction for string values.- Parameters:
json- the JSON responsekey- the key to extract- Returns:
- the extracted string value
-
extractJsonBoolean
Extracts a boolean value from JSON response.- Parameters:
json- the JSON responsekey- the key to extract- Returns:
- the extracted boolean value
-
extractJsonArray
Extracts a string array from JSON response.- Parameters:
json- the JSON responsekey- the key to extract- Returns:
- the extracted string array
-
extractJsonIntArray
Extracts an integer array from JSON response.- Parameters:
json- the JSON responsekey- the key to extract- Returns:
- the extracted integer array
-
getStringValue
Gets a string value from a map.- Parameters:
map- the map to get the value fromkey- the key to look up- Returns:
- the string value, or an empty string if not found
-
addHistory
Adds conversation history to the request.- Parameters:
request- the LLM chat requesthistory- the conversation history
-