Class ChatClient

java.lang.Object
org.codelibs.fess.chat.ChatClient

public class ChatClient extends Object
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
  • Field Details

    • chatSessionManager

      protected ChatSessionManager chatSessionManager
      The session manager for managing chat sessions.
    • llmClientManager

      protected LlmClientManager llmClientManager
      The LLM client manager for language model interactions.
    • markdownRenderer

      protected MarkdownRenderer 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

      public ChatClient.ChatResult chat(String sessionId, String userMessage, String userId)
      Performs a chat request with RAG.
      Parameters:
      sessionId - the session ID (can be null for new sessions)
      userMessage - the user's message
      userId - 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 message
      userId - 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 message
      userId - 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 message
      userId - 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
    • extractHistoryForIntent

      protected List<LlmMessage> extractHistoryForIntent(ChatSession session)
      Extracts conversation history shaped for the Intent Detection prompt. For smart_summary mode each assistant turn is rendered as a single searched: "..." -> found: [...] line. For other modes, this delegates to the per-message buildAssistantHistoryContent(org.codelibs.fess.entity.ChatMessage, java.lang.String, int, int) logic.
      Parameters:
      session - the chat session
      Returns:
      the list of LlmMessages for Intent Detection
    • extractHistoryForAnswer

      protected List<LlmMessage> extractHistoryForAnswer(ChatSession session)
      Extracts conversation history shaped for the Answer Generation prompt. For smart_summary mode each (user, assistant) turn is rendered as a single Q: "..." (searched: "...", refs: [...]) line. For other modes, this delegates to the per-message buildAssistantHistoryContent(org.codelibs.fess.entity.ChatMessage, java.lang.String, int, int) logic.
      Parameters:
      session - the chat session
      Returns:
      the list of LlmMessages for Answer Generation
    • 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 message
      mode - the content mode (full, smart_summary, source_titles, source_titles_and_urls, truncated, none)
      assistantMaxChars - the maximum characters for truncated mode
      summaryMaxChars - the maximum characters for summary modes
      Returns:
      the content string for history, or null if the message should be excluded
    • buildSourceTitlesContent

      protected String buildSourceTitlesContent(ChatMessage msg, int summaryMaxChars)
      Builds a summary string from source document titles.
      Parameters:
      msg - the assistant chat message
      summaryMaxChars - the maximum characters for the content summary
      Returns:
      a string listing referenced document titles
    • buildSourceTitlesAndUrlsContent

      protected String buildSourceTitlesAndUrlsContent(ChatMessage msg)
      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

      protected String buildTruncatedContent(ChatMessage msg, int maxChars)
      Builds a truncated version of the assistant message content.
      Parameters:
      msg - the assistant chat message
      maxChars - the maximum characters for the content
      Returns:
      the truncated content
    • renderIntentHistoryTurn

      protected String renderIntentHistoryTurn(ChatMessage assistantMsg, int titlesMaxCount)
      Renders a single assistant turn for the Intent Detection prompt history. Format: searched: "<query>" -> found: [Title1, Title2, ... (+N more)]. Returns null when there is neither a search query nor any titles.
      Parameters:
      assistantMsg - the assistant message
      titlesMaxCount - the maximum number of titles to include
      Returns:
      the rendered line or null
    • renderAnswerHistoryTurn

      protected String renderAnswerHistoryTurn(String userQuery, ChatMessage assistantMsg, int titlesMaxCount)
      Renders a single (user, assistant) turn for the Answer Generation prompt history. Format: Q: "<userQuery>" (searched: "<query>", refs: [Title1, Title2]).
      Parameters:
      userQuery - the user's question for that turn
      assistantMsg - the assistant message
      titlesMaxCount - the maximum number of titles to include
      Returns:
      the rendered line, or null if userQuery is blank
    • searchWithQuery

      protected List<Map<String,Object>> searchWithQuery(String query)
      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 string
      fields - the field filters (e.g., label)
      extraQueries - the extra query filters (e.g., filetype, timestamp)
      Returns:
      the list of search result documents
    • fetchFullContent

      protected List<Map<String,Object>> fetchFullContent(List<String> docIds)
      Fetches full document content for the given doc ids.

      Delegates to ChatContentFetcher. With a blank query the fetcher resolves every document to its full content, preserving the original behavior of this method.

      Parameters:
      docIds - the document IDs to fetch
      Returns:
      list of documents with full content, in docIds order
    • escapeQueryValue

      protected String escapeQueryValue(String value)
      Escapes special characters in the value for use in Fess queries.
      Parameters:
      value - the value to escape
      Returns:
      the escaped value
    • renderMarkdownToHtml

      protected String renderMarkdownToHtml(String markdown)
      Renders markdown text to sanitized HTML.
      Parameters:
      markdown - the markdown text
      Returns:
      sanitized HTML
    • escapeHtml

      protected String escapeHtml(String text)
      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

      protected ChatClient.ChatSearchResult searchDocuments(String query)
      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

      protected ChatClient.ChatSearchResult searchByUrl(String url)
      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 query
      fields - the field filters (e.g., label)
      extraQueries - the extra query filters (e.g., filetype, timestamp)
      Returns:
      a ChatSearchResult with documents and search metadata
    • resolveContextPath

      protected String 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 path
      docId - the document ID
      queryId - the query ID from the search
      requestedTime - the requested time from the search
      order - 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 to
      sourceList - the search result documents
      contextPath - the application context path
      queryId - the query ID from the search
      requestedTime - the requested time from the search
    • populateUrlLink

      protected void populateUrlLink(Map<String,Object> doc)
      Populates the url_link field in the document map if not already present.
      Parameters:
      doc - the document map