|
| 1 | +package com.microsoft.openai.samples.rag.chat.approaches.semantickernel; |
| 2 | + |
| 3 | +import com.azure.ai.openai.OpenAIAsyncClient; |
| 4 | +import com.azure.core.credential.TokenCredential; |
| 5 | +import com.azure.search.documents.SearchAsyncClient; |
| 6 | +import com.azure.search.documents.SearchDocument; |
| 7 | +import com.microsoft.openai.samples.rag.approaches.ContentSource; |
| 8 | +import com.microsoft.openai.samples.rag.approaches.RAGApproach; |
| 9 | +import com.microsoft.openai.samples.rag.approaches.RAGOptions; |
| 10 | +import com.microsoft.openai.samples.rag.approaches.RAGResponse; |
| 11 | +import com.microsoft.openai.samples.rag.ask.approaches.semantickernel.memory.CustomAzureCognitiveSearchMemoryStore; |
| 12 | +import com.microsoft.openai.samples.rag.common.ChatGPTConversation; |
| 13 | +import com.microsoft.openai.samples.rag.common.ChatGPTUtils; |
| 14 | +import com.microsoft.semantickernel.Kernel; |
| 15 | +import com.microsoft.semantickernel.SKBuilders; |
| 16 | +import com.microsoft.semantickernel.ai.embeddings.Embedding; |
| 17 | +import com.microsoft.semantickernel.memory.MemoryQueryResult; |
| 18 | +import com.microsoft.semantickernel.memory.MemoryRecord; |
| 19 | +import com.microsoft.semantickernel.orchestration.SKContext; |
| 20 | +import org.slf4j.Logger; |
| 21 | +import org.slf4j.LoggerFactory; |
| 22 | +import org.springframework.beans.factory.annotation.Value; |
| 23 | +import org.springframework.stereotype.Component; |
| 24 | +import reactor.core.publisher.Mono; |
| 25 | + |
| 26 | +import java.io.OutputStream; |
| 27 | +import java.util.List; |
| 28 | +import java.util.function.Function; |
| 29 | +import java.util.stream.Collectors; |
| 30 | + |
| 31 | +/** |
| 32 | + * Accomplish the same task as in the PlainJavaAskApproach approach but using Semantic Kernel framework: |
| 33 | + * 1. Memory abstraction is used for vector search capability. It uses Azure Cognitive Search as memory store. |
| 34 | + * 2. Semantic function has been defined to ask question using sources from memory search results |
| 35 | + */ |
| 36 | +@Component |
| 37 | +public class JavaSemanticKernelWithMemoryChatApproach implements RAGApproach<ChatGPTConversation, RAGResponse> { |
| 38 | + private static final Logger LOGGER = LoggerFactory.getLogger(JavaSemanticKernelWithMemoryChatApproach.class); |
| 39 | + private final TokenCredential tokenCredential; |
| 40 | + private final OpenAIAsyncClient openAIAsyncClient; |
| 41 | + |
| 42 | + private final SearchAsyncClient searchAsyncClient; |
| 43 | + |
| 44 | + private final String EMBEDDING_FIELD_NAME = "embedding"; |
| 45 | + |
| 46 | + @Value("${cognitive.search.service}") |
| 47 | + String searchServiceName; |
| 48 | + @Value("${cognitive.search.index}") |
| 49 | + String indexName; |
| 50 | + @Value("${openai.chatgpt.deployment}") |
| 51 | + private String gptChatDeploymentModelId; |
| 52 | + |
| 53 | + @Value("${openai.embedding.deployment}") |
| 54 | + private String embeddingDeploymentModelId; |
| 55 | + |
| 56 | + public JavaSemanticKernelWithMemoryChatApproach(TokenCredential tokenCredential, OpenAIAsyncClient openAIAsyncClient, SearchAsyncClient searchAsyncClient) { |
| 57 | + this.tokenCredential = tokenCredential; |
| 58 | + this.openAIAsyncClient = openAIAsyncClient; |
| 59 | + this.searchAsyncClient = searchAsyncClient; |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public RAGResponse run(ChatGPTConversation questionOrConversation, RAGOptions options) { |
| 64 | + |
| 65 | + String question = ChatGPTUtils.getLastUserQuestion(questionOrConversation.getMessages()); |
| 66 | + |
| 67 | + //Build semantic kernel with Azure Cognitive Search as memory store. AnswerQuestion skill is imported from resources. |
| 68 | + Kernel semanticKernel = buildSemanticKernel(options); |
| 69 | + |
| 70 | + /** |
| 71 | + * Use semantic kernel built-in memory.searchAsync. It uses OpenAI to generate embeddings for the provided question. |
| 72 | + * Question embeddings are provided to cognitive search via search options. |
| 73 | + */ |
| 74 | + List<MemoryQueryResult> memoryResult = semanticKernel.getMemory().searchAsync( |
| 75 | + indexName, |
| 76 | + question, |
| 77 | + options.getTop(), |
| 78 | + 0.5f, |
| 79 | + false) |
| 80 | + .block(); |
| 81 | + |
| 82 | + LOGGER.info("Total {} sources found in cognitive vector store for search query[{}]", memoryResult.size(), question); |
| 83 | + |
| 84 | + String sources = buildSourcesText(memoryResult); |
| 85 | + List<ContentSource> sourcesList = buildSources(memoryResult); |
| 86 | + |
| 87 | + SKContext skcontext = SKBuilders.context().build() |
| 88 | + .setVariable("sources", sources) |
| 89 | + .setVariable("input", question); |
| 90 | + |
| 91 | + |
| 92 | + Mono<SKContext> result = semanticKernel.getFunction("RAG", "AnswerQuestion").invokeAsync(skcontext); |
| 93 | + |
| 94 | + return new RAGResponse.Builder() |
| 95 | + //.prompt(plan.toPlanString()) |
| 96 | + .prompt("placeholders for prompt") |
| 97 | + .answer(result.block().getResult()) |
| 98 | + .sources(sourcesList) |
| 99 | + .sourcesAsText(sources) |
| 100 | + .question(question) |
| 101 | + .build(); |
| 102 | + |
| 103 | + } |
| 104 | + |
| 105 | + @Override |
| 106 | + public void runStreaming(ChatGPTConversation questionOrConversation, RAGOptions options, OutputStream outputStream) { |
| 107 | + throw new IllegalStateException("Streaming not supported for this approach"); |
| 108 | + } |
| 109 | + |
| 110 | + private List<ContentSource> buildSources(List<MemoryQueryResult> memoryResult) { |
| 111 | + return memoryResult |
| 112 | + .stream() |
| 113 | + .map(result -> { |
| 114 | + return new ContentSource( |
| 115 | + result.getMetadata().getId(), |
| 116 | + result.getMetadata().getText() |
| 117 | + ); |
| 118 | + }) |
| 119 | + .collect(Collectors.toList()); |
| 120 | + } |
| 121 | + |
| 122 | + private String buildSourcesText(List<MemoryQueryResult> memoryResult) { |
| 123 | + StringBuilder sourcesContentBuffer = new StringBuilder(); |
| 124 | + memoryResult.stream().forEach(memory -> { |
| 125 | + sourcesContentBuffer.append(memory.getMetadata().getId()) |
| 126 | + .append(": ") |
| 127 | + .append(memory.getMetadata().getText().replace("\n", "")) |
| 128 | + .append("\n"); |
| 129 | + }); |
| 130 | + return sourcesContentBuffer.toString(); |
| 131 | + } |
| 132 | + |
| 133 | + private Kernel buildSemanticKernel(RAGOptions options) { |
| 134 | + var kernelWithACS = SKBuilders.kernel() |
| 135 | + .withMemoryStorage( |
| 136 | + new CustomAzureCognitiveSearchMemoryStore("https://%s.search.windows.net".formatted(searchServiceName), |
| 137 | + tokenCredential, |
| 138 | + this.searchAsyncClient, |
| 139 | + this.EMBEDDING_FIELD_NAME, |
| 140 | + buildCustomMemoryMapper())) |
| 141 | + .withDefaultAIService(SKBuilders.textEmbeddingGeneration() |
| 142 | + .withOpenAIClient(openAIAsyncClient) |
| 143 | + .withModelId(embeddingDeploymentModelId) |
| 144 | + .build()) |
| 145 | + .withDefaultAIService(SKBuilders.chatCompletion() |
| 146 | + .withModelId(gptChatDeploymentModelId) |
| 147 | + .withOpenAIClient(this.openAIAsyncClient) |
| 148 | + .build()) |
| 149 | + .build(); |
| 150 | + |
| 151 | + kernelWithACS.importSkillFromResources("semantickernel/Plugins", "RAG", "AnswerQuestion", null); |
| 152 | + return kernelWithACS; |
| 153 | + } |
| 154 | + |
| 155 | + private Function<SearchDocument, MemoryRecord> buildCustomMemoryMapper() { |
| 156 | + return searchDocument -> { |
| 157 | + return MemoryRecord.localRecord( |
| 158 | + (String) searchDocument.get("sourcepage"), |
| 159 | + (String) searchDocument.get("content"), |
| 160 | + "chunked text from original source", |
| 161 | + new Embedding((List<Float>) searchDocument.get(EMBEDDING_FIELD_NAME)), |
| 162 | + (String) searchDocument.get("category"), |
| 163 | + (String) searchDocument.get("id"), |
| 164 | + null); |
| 165 | + |
| 166 | + }; |
| 167 | + } |
| 168 | +} |
0 commit comments