|
| 1 | +package com.microsoft.openai.samples.rag.chat.approaches.semantickernel; |
| 2 | + |
| 3 | +import com.azure.ai.openai.OpenAIAsyncClient; |
| 4 | +import com.microsoft.openai.samples.rag.approaches.ContentSource; |
| 5 | +import com.microsoft.openai.samples.rag.approaches.RAGApproach; |
| 6 | +import com.microsoft.openai.samples.rag.approaches.RAGOptions; |
| 7 | +import com.microsoft.openai.samples.rag.approaches.RAGResponse; |
| 8 | +import com.microsoft.openai.samples.rag.retrieval.semantickernel.CognitiveSearchPlugin; |
| 9 | +import com.microsoft.openai.samples.rag.common.ChatGPTConversation; |
| 10 | +import com.microsoft.openai.samples.rag.common.ChatGPTUtils; |
| 11 | +import com.microsoft.openai.samples.rag.proxy.CognitiveSearchProxy; |
| 12 | +import com.microsoft.openai.samples.rag.proxy.OpenAIProxy; |
| 13 | +import com.microsoft.semantickernel.Kernel; |
| 14 | +import com.microsoft.semantickernel.SKBuilders; |
| 15 | +import com.microsoft.semantickernel.orchestration.ContextVariables; |
| 16 | +import com.microsoft.semantickernel.orchestration.SKContext; |
| 17 | +import org.springframework.beans.factory.annotation.Value; |
| 18 | +import org.springframework.stereotype.Component; |
| 19 | + |
| 20 | +import java.io.OutputStream; |
| 21 | +import java.util.Arrays; |
| 22 | +import java.util.Collections; |
| 23 | +import java.util.List; |
| 24 | +import java.util.Objects; |
| 25 | +import java.util.stream.Collectors; |
| 26 | + |
| 27 | +/** |
| 28 | + * Use Java Semantic Kernel framework with semantic and native functions chaining. It uses an |
| 29 | + * imperative style for AI orchestration through semantic kernel functions chaining. |
| 30 | + * InformationFinder.SearchFromConversation native function and RAG.AnswerConversation semantic function are called |
| 31 | + * sequentially. Several cognitive search retrieval options are available: Text, Vector, Hybrid. |
| 32 | + */ |
| 33 | +@Component |
| 34 | +public class JavaSemanticKernelChainsChatApproach implements RAGApproach<ChatGPTConversation, RAGResponse> { |
| 35 | + private final CognitiveSearchProxy cognitiveSearchProxy; |
| 36 | + |
| 37 | + private final OpenAIProxy openAIProxy; |
| 38 | + |
| 39 | + private final OpenAIAsyncClient openAIAsyncClient; |
| 40 | + |
| 41 | + @Value("${openai.chatgpt.deployment}") |
| 42 | + private String gptChatDeploymentModelId; |
| 43 | + |
| 44 | + public JavaSemanticKernelChainsChatApproach(CognitiveSearchProxy cognitiveSearchProxy, OpenAIAsyncClient openAIAsyncClient, OpenAIProxy openAIProxy) { |
| 45 | + this.cognitiveSearchProxy = cognitiveSearchProxy; |
| 46 | + this.openAIAsyncClient = openAIAsyncClient; |
| 47 | + this.openAIProxy = openAIProxy; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * @param questionOrConversation |
| 52 | + * @param options |
| 53 | + * @return |
| 54 | + */ |
| 55 | + @Override |
| 56 | + public RAGResponse run(ChatGPTConversation questionOrConversation, RAGOptions options) { |
| 57 | + String question = ChatGPTUtils.getLastUserQuestion(questionOrConversation.getMessages()); |
| 58 | + String conversation = ChatGPTUtils.formatAsChatML(questionOrConversation.toOpenAIChatMessages()); |
| 59 | + |
| 60 | + Kernel semanticKernel = buildSemanticKernel(options); |
| 61 | + |
| 62 | + // STEP 1: Retrieve relevant documents using the current conversation. It reuses the |
| 63 | + // CognitiveSearchRetriever appraoch through the CognitiveSearchPlugin native function. |
| 64 | + SKContext searchContext = |
| 65 | + semanticKernel.runAsync( |
| 66 | + conversation, |
| 67 | + semanticKernel.getSkill("InformationFinder").getFunction("SearchFromConversation", null)).block(); |
| 68 | + |
| 69 | + // STEP 2: Build a SK context with the sources retrieved from the memory store and conversation |
| 70 | + ContextVariables variables = SKBuilders.variables() |
| 71 | + .withVariable("sources", searchContext.getResult()) |
| 72 | + .withVariable("conversation", conversation) |
| 73 | + .withVariable("suggestions", String.valueOf(options.isSuggestFollowupQuestions())) |
| 74 | + .withVariable("input", question) |
| 75 | + .build(); |
| 76 | + |
| 77 | + /** |
| 78 | + * STEP 3: Get a reference of the semantic function [AnswerConversation] of the [RAG] plugin |
| 79 | + * (a.k.a. skill) from the SK skills registry and provide it with the pre-built context. |
| 80 | + * Triggering Open AI to get a reply. |
| 81 | + */ |
| 82 | + SKContext reply = semanticKernel.runAsync(variables, |
| 83 | + semanticKernel.getSkill("RAG").getFunction("AnswerConversation", null)).block(); |
| 84 | + |
| 85 | + return new RAGResponse.Builder() |
| 86 | + .prompt("Prompt is managed by Semantic Kernel") |
| 87 | + .answer(reply.getResult()) |
| 88 | + .sources(formSourcesList(searchContext.getResult())) |
| 89 | + .sourcesAsText(searchContext.getResult()) |
| 90 | + .question(question) |
| 91 | + .build(); |
| 92 | + } |
| 93 | + |
| 94 | + @Override |
| 95 | + public void runStreaming( |
| 96 | + ChatGPTConversation questionOrConversation, |
| 97 | + RAGOptions options, |
| 98 | + OutputStream outputStream) { |
| 99 | + throw new IllegalStateException("Streaming not supported for this approach"); |
| 100 | + } |
| 101 | + |
| 102 | + private List<ContentSource> formSourcesList(String result) { |
| 103 | + if (result == null) { |
| 104 | + return Collections.emptyList(); |
| 105 | + } |
| 106 | + return Arrays.stream(result |
| 107 | + .split("\n")) |
| 108 | + .map(source -> { |
| 109 | + String[] split = source.split(":", 2); |
| 110 | + if (split.length >= 2) { |
| 111 | + var sourceName = split[0].trim(); |
| 112 | + var sourceContent = split[1].trim(); |
| 113 | + return new ContentSource(sourceName, sourceContent); |
| 114 | + } else { |
| 115 | + return null; |
| 116 | + } |
| 117 | + }) |
| 118 | + .filter(Objects::nonNull) |
| 119 | + .collect(Collectors.toList()); |
| 120 | + } |
| 121 | + |
| 122 | + /** |
| 123 | + * Build semantic kernel context with AnswerConversation semantic function and |
| 124 | + * InformationFinder.SearchFromConversation native function. AnswerConversation is imported from |
| 125 | + * src/main/resources/semantickernel/Plugins. InformationFinder.SearchFromConversation is implemented in a |
| 126 | + * traditional Java class method: CognitiveSearchPlugin.searchFromConversation |
| 127 | + * |
| 128 | + * @param options |
| 129 | + * @return |
| 130 | + */ |
| 131 | + private Kernel buildSemanticKernel(RAGOptions options) { |
| 132 | + Kernel kernel = SKBuilders.kernel() |
| 133 | + .withDefaultAIService(SKBuilders.chatCompletion() |
| 134 | + .withModelId(gptChatDeploymentModelId) |
| 135 | + .withOpenAIClient(this.openAIAsyncClient) |
| 136 | + .build()) |
| 137 | + .build(); |
| 138 | + |
| 139 | + kernel.importSkill( |
| 140 | + new CognitiveSearchPlugin(this.cognitiveSearchProxy, this.openAIProxy, options), |
| 141 | + "InformationFinder"); |
| 142 | + kernel.importSkillFromResources("semantickernel/Plugins", "RAG", "AnswerConversation", null); |
| 143 | + |
| 144 | + return kernel; |
| 145 | + } |
| 146 | + |
| 147 | +} |
0 commit comments