From b6d8fee2a4e4d5c112a31e675531d6230eb08efe Mon Sep 17 00:00:00 2001 From: Thomas Vitale Date: Tue, 30 Jan 2024 21:53:06 +0100 Subject: [PATCH] Update PDF reader example --- .../thomasvitale/ai/spring/ChatService.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/05-document-readers/document-readers-pdf-ollama/src/main/java/com/thomasvitale/ai/spring/ChatService.java b/05-document-readers/document-readers-pdf-ollama/src/main/java/com/thomasvitale/ai/spring/ChatService.java index 42f9f69..80291bc 100644 --- a/05-document-readers/document-readers-pdf-ollama/src/main/java/com/thomasvitale/ai/spring/ChatService.java +++ b/05-document-readers/document-readers-pdf-ollama/src/main/java/com/thomasvitale/ai/spring/ChatService.java @@ -1,5 +1,7 @@ package com.thomasvitale.ai.spring; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.UserMessage; @@ -12,11 +14,16 @@ import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; +import static org.springframework.ai.reader.pdf.PagePdfDocumentReader.*; + @Service class ChatService { + private static final Logger log = LoggerFactory.getLogger(ChatService.class); + private final ChatClient chatClient; private final SimpleVectorStore vectorStore; @@ -37,6 +44,7 @@ Answer questions given the context information below (DOCUMENTS section) and no """); List similarDocuments = vectorStore.similaritySearch(SearchRequest.query(message).withTopK(2)); + logDocumentMetadata(similarDocuments); String documents = similarDocuments.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator())); Map model = Map.of("documents", documents); @@ -49,4 +57,16 @@ Answer questions given the context information below (DOCUMENTS section) and no return chatResponse.getResult().getOutput(); } + private void logDocumentMetadata(List documents) { + log.info("Similar documents retrieved to answer your question:"); + documents.forEach(document -> { + var metadata = Map.of( + "fileName", document.getMetadata().get(METADATA_FILE_NAME), + "startPageNumber", document.getMetadata().get(METADATA_START_PAGE_NUMBER), + "endPageNumber", Objects.requireNonNullElse(document.getMetadata().get(METADATA_END_PAGE_NUMBER), "-") + ); + log.info("Metadata: " + metadata); + }); + } + }