Package org.codelibs.fess.chat
Class ChatClient
java.lang.Object
org.codelibs.fess.chat.ChatClient
Client class for RAG (Retrieval-Augmented Generation) chat functionality.
Orchestrates the multi-phase RAG workflow including session management,
document search, and delegation to LlmClientManager for LLM operations.
Prompt construction and LLM-specific logic is handled by LlmClient implementations.
- Author:
- FessProject
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classResult of a chat request.protected static classSearch request parameters for RAG chat context retrieval.protected static classResult of a search operation, including queryId and requestedTime. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected ChatSessionManagerThe session manager for managing chat sessions.protected LlmClientManagerThe LLM client manager for language model interactions.protected MarkdownRendererThe markdown renderer for converting markdown to safe HTML. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddSourcesToMessage(ChatMessage assistantMessage, List<Map<String, Object>> sourceList, String contextPath, String queryId, long requestedTime) Creates ChatSource objects from search results and adds them to the assistant message.protected StringbuildAssistantHistoryContent(ChatMessage msg, String mode, int assistantMaxChars, int summaryMaxChars) Builds the assistant message content for history based on the specified mode.protected StringbuildGoUrl(String contextPath, String docId, String queryId, long requestedTime, int order) Builds a go URL for the given document.protected StringbuildSmartSummaryContent(ChatMessage msg, int maxChars) Builds a smart summary of the assistant message for history.protected StringBuilds a summary string from source document titles and URLs.protected StringbuildSourceTitlesContent(ChatMessage msg, int summaryMaxChars) Builds a summary string from source document titles.protected StringbuildTruncatedContent(ChatMessage msg, int maxChars) Builds a truncated version of the assistant message content.Performs a chat request with RAG.chat(String sessionId, String userMessage, String userId, Map<String, String[]> fields, String[] extraQueries) Performs a chat request with RAG and search filters.protected StringescapeHtml(String text) Escapes HTML special characters.protected StringescapeQueryValue(String value) Escapes special characters in the value for use in Fess queries.protected List<LlmMessage> extractHistory(ChatSession session) Extracts conversation history from a chat session as LlmMessage list.fetchFullContent(List<String> docIds) Fetches full document content for the given document IDs.protected intGets the maximum number of history messages to retain.booleanChecks if RAG chat is available.protected voidpopulateUrlLink(Map<String, Object> doc) Populates the url_link field in the document map if not already present.protected StringrenderMarkdownToHtml(String markdown) Renders markdown text to sanitized HTML.protected StringResolves the context path from the current request, or empty string if unavailable.protected ChatClient.ChatSearchResultsearchByUrl(String url) Searches for documents by URL.protected ChatClient.ChatSearchResultsearchDocuments(String query) Searches for documents relevant to the user's query.protected ChatClient.ChatSearchResultSearches for documents relevant to the user's query.searchWithQuery(String query) Searches documents using a Fess query.Searches documents using a Fess query with filters.streamChatEnhanced(String sessionId, String userMessage, String userId, Map<String, String[]> fields, String[] extraQueries, ChatPhaseCallback callback) Performs an enhanced streaming chat request with multi-phase RAG flow and search filters.streamChatEnhanced(String sessionId, String userMessage, String userId, ChatPhaseCallback callback) Performs an enhanced streaming chat request with multi-phase RAG flow.
-
Field Details
-
chatSessionManager
The session manager for managing chat sessions. -
llmClientManager
The LLM client manager for language model interactions. -
markdownRenderer
The markdown renderer for converting markdown to safe HTML.
-
-
Constructor Details
-
ChatClient
public ChatClient()Default constructor.
-
-
Method Details
-
isAvailable
public boolean isAvailable()Checks if RAG chat is available.- Returns:
- true if RAG chat is available
-
chat
Performs a chat request with RAG.- Parameters:
sessionId- the session ID (can be null for new sessions)userMessage- the user's messageuserId- the user ID (can be null for anonymous users)- Returns:
- the chat response including session info and sources
-
chat
public ChatClient.ChatResult chat(String sessionId, String userMessage, String userId, Map<String, String[]> fields, String[] extraQueries) Performs a chat request with RAG and search filters.- Parameters:
sessionId- the session ID (can be null for new sessions)userMessage- the user's messageuserId- the user ID (can be null for anonymous users)fields- the field filters (e.g., label)extraQueries- the extra query filters (e.g., filetype, timestamp)- Returns:
- the chat response including session info and sources
-
streamChatEnhanced
public ChatClient.ChatResult streamChatEnhanced(String sessionId, String userMessage, String userId, ChatPhaseCallback callback) Performs an enhanced streaming chat request with multi-phase RAG flow.- Parameters:
sessionId- the session ID (can be null for new sessions)userMessage- the user's messageuserId- the user ID (can be null for anonymous users)callback- the callback to receive phase notifications and streaming chunks- Returns:
- the chat result with session info, sources, and HTML content
-
streamChatEnhanced
public ChatClient.ChatResult streamChatEnhanced(String sessionId, String userMessage, String userId, Map<String, String[]> fields, String[] extraQueries, ChatPhaseCallback callback) Performs an enhanced streaming chat request with multi-phase RAG flow and search filters. This flow includes: intent detection, keyword search, result evaluation, content retrieval, answer generation, and markdown rendering.- Parameters:
sessionId- the session ID (can be null for new sessions)userMessage- the user's messageuserId- the user ID (can be null for anonymous users)fields- the field filters (e.g., label)extraQueries- the extra query filters (e.g., filetype, timestamp)callback- the callback to receive phase notifications and streaming chunks- Returns:
- the chat result with session info, sources, and HTML content
-
extractHistory
Extracts conversation history from a chat session as LlmMessage list. The assistant message content in history is controlled by therag.chat.history.assistant.contentconfiguration property.- Parameters:
session- the chat session- Returns:
- the list of LlmMessages representing the conversation history
-
buildAssistantHistoryContent
protected String buildAssistantHistoryContent(ChatMessage msg, String mode, int assistantMaxChars, int summaryMaxChars) Builds the assistant message content for history based on the specified mode.- Parameters:
msg- the assistant chat messagemode- the content mode (full, smart_summary, source_titles, source_titles_and_urls, truncated, none)assistantMaxChars- the maximum characters for truncated modesummaryMaxChars- the maximum characters for summary modes- Returns:
- the content string for history, or null if the message should be excluded
-
buildSourceTitlesContent
Builds a summary string from source document titles.- Parameters:
msg- the assistant chat messagesummaryMaxChars- the maximum characters for the content summary- Returns:
- a string listing referenced document titles
-
buildSourceTitlesAndUrlsContent
Builds a summary string from source document titles and URLs.- Parameters:
msg- the assistant chat message- Returns:
- a string listing referenced document titles and URLs
-
buildTruncatedContent
Builds a truncated version of the assistant message content.- Parameters:
msg- the assistant chat messagemaxChars- the maximum characters for the content- Returns:
- the truncated content
-
buildSmartSummaryContent
Builds a smart summary of the assistant message for history. Preserves the beginning (direct answer) and end (conclusion) of long responses, omitting the middle section, and appends source titles.- Parameters:
msg- the assistant chat messagemaxChars- the maximum characters for the summary- Returns:
- the summarized content with source titles
-
searchWithQuery
Searches documents using a Fess query.- Parameters:
query- the Fess query string- Returns:
- the list of search result documents
-
searchWithQuery
protected List<Map<String,Object>> searchWithQuery(String query, Map<String, String[]> fields, String[] extraQueries) Searches documents using a Fess query with filters.- Parameters:
query- the Fess query stringfields- the field filters (e.g., label)extraQueries- the extra query filters (e.g., filetype, timestamp)- Returns:
- the list of search result documents
-
fetchFullContent
Fetches full document content for the given document IDs.- Parameters:
docIds- the document IDs to fetch- Returns:
- list of documents with full content
-
escapeQueryValue
Escapes special characters in the value for use in Fess queries.- Parameters:
value- the value to escape- Returns:
- the escaped value
-
renderMarkdownToHtml
Renders markdown text to sanitized HTML.- Parameters:
markdown- the markdown text- Returns:
- sanitized HTML
-
escapeHtml
Escapes HTML special characters.- Parameters:
text- the text to escape- Returns:
- the escaped text
-
getMaxHistoryMessages
protected int getMaxHistoryMessages()Gets the maximum number of history messages to retain.- Returns:
- the maximum number of history messages
-
searchDocuments
Searches for documents relevant to the user's query. Delegates to the multi-argument variant with empty filters.- Parameters:
query- the search query- Returns:
- a ChatSearchResult with documents and search metadata
-
searchByUrl
Searches for documents by URL.- Parameters:
url- the URL to search for- Returns:
- a ChatSearchResult with documents and search metadata
-
searchDocuments
protected ChatClient.ChatSearchResult searchDocuments(String query, Map<String, String[]> fields, String[] extraQueries) Searches for documents relevant to the user's query. SearchHelper applies role-based access control filtering through SearchRequestType.JSON and the role filter mechanism, ensuring users only see documents they are authorized to access.This is the primary extension point for subclasses to customize search behavior.
- Parameters:
query- the search queryfields- the field filters (e.g., label)extraQueries- the extra query filters (e.g., filetype, timestamp)- Returns:
- a ChatSearchResult with documents and search metadata
-
resolveContextPath
Resolves the context path from the current request, or empty string if unavailable.- Returns:
- the context path
-
buildGoUrl
protected String buildGoUrl(String contextPath, String docId, String queryId, long requestedTime, int order) Builds a go URL for the given document.- Parameters:
contextPath- the application context pathdocId- the document IDqueryId- the query ID from the searchrequestedTime- the requested time from the searchorder- the order index of the document- Returns:
- the go URL, or null if docId or queryId is null
-
addSourcesToMessage
protected void addSourcesToMessage(ChatMessage assistantMessage, List<Map<String, Object>> sourceList, String contextPath, String queryId, long requestedTime) Creates ChatSource objects from search results and adds them to the assistant message.- Parameters:
assistantMessage- the message to add sources tosourceList- the search result documentscontextPath- the application context pathqueryId- the query ID from the searchrequestedTime- the requested time from the search
-
populateUrlLink
Populates the url_link field in the document map if not already present.- Parameters:
doc- the document map
-