Skip to content

Commit

Permalink
Update PDF reader example
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasVitale committed Jan 30, 2024
1 parent 43b7dce commit b6d8fee
Showing 1 changed file with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;

Expand All @@ -37,6 +44,7 @@ Answer questions given the context information below (DOCUMENTS section) and no
""");

List<Document> similarDocuments = vectorStore.similaritySearch(SearchRequest.query(message).withTopK(2));
logDocumentMetadata(similarDocuments);
String documents = similarDocuments.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator()));

Map<String,Object> model = Map.of("documents", documents);
Expand All @@ -49,4 +57,16 @@ Answer questions given the context information below (DOCUMENTS section) and no
return chatResponse.getResult().getOutput();
}

private void logDocumentMetadata(List<Document> 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);
});
}

}

0 comments on commit b6d8fee

Please sign in to comment.