|
| 1 | +package com.microsoft.semantickernel.agents.chatcompletion; |
| 2 | + |
| 3 | +import com.microsoft.semantickernel.Kernel; |
| 4 | +import com.microsoft.semantickernel.agents.AgentInvokeOptions; |
| 5 | +import com.microsoft.semantickernel.agents.AgentResponseItem; |
| 6 | +import com.microsoft.semantickernel.agents.AgentThread; |
| 7 | +import com.microsoft.semantickernel.agents.KernelAgent; |
| 8 | +import com.microsoft.semantickernel.builders.SemanticKernelBuilder; |
| 9 | +import com.microsoft.semantickernel.contextvariables.ContextVariable; |
| 10 | +import com.microsoft.semantickernel.orchestration.InvocationContext; |
| 11 | +import com.microsoft.semantickernel.orchestration.InvocationReturnMode; |
| 12 | +import com.microsoft.semantickernel.orchestration.PromptExecutionSettings; |
| 13 | +import com.microsoft.semantickernel.orchestration.ToolCallBehavior; |
| 14 | +import com.microsoft.semantickernel.semanticfunctions.KernelArguments; |
| 15 | +import com.microsoft.semantickernel.semanticfunctions.PromptTemplate; |
| 16 | +import com.microsoft.semantickernel.semanticfunctions.PromptTemplateConfig; |
| 17 | +import com.microsoft.semantickernel.semanticfunctions.PromptTemplateFactory; |
| 18 | +import com.microsoft.semantickernel.services.ServiceNotFoundException; |
| 19 | +import com.microsoft.semantickernel.services.chatcompletion.AuthorRole; |
| 20 | +import com.microsoft.semantickernel.services.chatcompletion.ChatCompletionService; |
| 21 | +import com.microsoft.semantickernel.services.chatcompletion.ChatHistory; |
| 22 | +import com.microsoft.semantickernel.services.chatcompletion.ChatMessageContent; |
| 23 | +import reactor.core.publisher.Flux; |
| 24 | +import reactor.core.publisher.Mono; |
| 25 | + |
| 26 | +import java.util.List; |
| 27 | +import java.util.Map; |
| 28 | +import java.util.function.Function; |
| 29 | +import java.util.stream.Collectors; |
| 30 | + |
| 31 | +public class ChatCompletionAgent extends KernelAgent { |
| 32 | + |
| 33 | + ChatCompletionAgent( |
| 34 | + String id, |
| 35 | + String name, |
| 36 | + String description, |
| 37 | + Kernel kernel, |
| 38 | + KernelArguments kernelArguments, |
| 39 | + InvocationContext context, |
| 40 | + String instructions, |
| 41 | + PromptTemplate template |
| 42 | + ) { |
| 43 | + super( |
| 44 | + id, |
| 45 | + name, |
| 46 | + description, |
| 47 | + kernel, |
| 48 | + kernelArguments, |
| 49 | + context, |
| 50 | + instructions, |
| 51 | + template |
| 52 | + ); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Invoke the agent with the given chat history. |
| 57 | + * |
| 58 | + * @param messages The chat history to process |
| 59 | + * @param thread The agent thread to use |
| 60 | + * @param options The options for invoking the agent |
| 61 | + * @return A Mono containing the agent response |
| 62 | + */ |
| 63 | + @Override |
| 64 | + public Mono<List<AgentResponseItem<ChatMessageContent<?>>>> invokeAsync(List<ChatMessageContent<?>> messages, AgentThread thread, AgentInvokeOptions options) { |
| 65 | + |
| 66 | + Mono<ChatHistory> chatHistoryFromThread = this.<ChatHistoryAgentThread>ensureThreadExistsAsync(messages, thread, ChatHistoryAgentThread::new) |
| 67 | + .cast(ChatHistoryAgentThread.class) |
| 68 | + .map(ChatHistoryAgentThread::getChatHistory) |
| 69 | + .flatMap(threadChatHistory -> { |
| 70 | + return Mono.just(new ChatHistory(threadChatHistory.getMessages())); |
| 71 | + }); |
| 72 | + |
| 73 | + |
| 74 | + Mono<List<ChatMessageContent<?>>> updatedChatHistory = chatHistoryFromThread.flatMap( |
| 75 | + chatHistory -> internalInvokeAsync( |
| 76 | + this.getName(), |
| 77 | + chatHistory, |
| 78 | + options |
| 79 | + ) |
| 80 | + ); |
| 81 | + |
| 82 | + return updatedChatHistory.flatMap(chatMessageContents -> { |
| 83 | + return Flux.fromIterable(chatMessageContents) |
| 84 | + .concatMap(chatMessageContent -> this.notifyThreadOfNewMessageAsync(thread, chatMessageContent)) |
| 85 | + .then(Mono.just(chatMessageContents)); // return the original list |
| 86 | + }).flatMap(chatMessageContents -> { |
| 87 | + return Mono.just(chatMessageContents.stream() |
| 88 | + .map(chatMessageContent -> { |
| 89 | + return new AgentResponseItem<ChatMessageContent<?>>( |
| 90 | + chatMessageContent, |
| 91 | + thread); |
| 92 | + }).collect(Collectors.toList())); |
| 93 | + }); |
| 94 | + } |
| 95 | + |
| 96 | + private Mono<List<ChatMessageContent<?>>> internalInvokeAsync( |
| 97 | + String agentName, |
| 98 | + ChatHistory history, |
| 99 | + AgentInvokeOptions options |
| 100 | + ) { |
| 101 | + final Kernel kernel = options.getKernel() != null ? options.getKernel() : this.kernel; |
| 102 | + final KernelArguments arguments = mergeArguments(options.getKernelArguments()); |
| 103 | + final String additionalInstructions = options.getAdditionalInstructions(); |
| 104 | + final InvocationContext invocationContext = options.getInvocationContext() != null ? options.getInvocationContext() : this.invocationContext; |
| 105 | + |
| 106 | + try { |
| 107 | + ChatCompletionService chatCompletionService = kernel.getService(ChatCompletionService.class, arguments); |
| 108 | + |
| 109 | + PromptExecutionSettings executionSettings = invocationContext.getPromptExecutionSettings() != null |
| 110 | + ? invocationContext.getPromptExecutionSettings() |
| 111 | + : kernelArguments.getExecutionSettings().get(chatCompletionService.getServiceId()); |
| 112 | + |
| 113 | + final InvocationContext newMessagesContext = InvocationContext.builder() |
| 114 | + .withPromptExecutionSettings(executionSettings) |
| 115 | + .withToolCallBehavior(invocationContext.getToolCallBehavior()) |
| 116 | + .withTelemetry(invocationContext.getTelemetry()) |
| 117 | + .withContextVariableConverter(invocationContext.getContextVariableTypes()) |
| 118 | + .withKernelHooks(invocationContext.getKernelHooks()) |
| 119 | + .withReturnMode(InvocationReturnMode.FULL_HISTORY) |
| 120 | + .build(); |
| 121 | + |
| 122 | + return formatInstructionsAsync(kernel, arguments, newMessagesContext).flatMap( |
| 123 | + instructions -> { |
| 124 | + // Create a new chat history with the instructions |
| 125 | + ChatHistory chat = new ChatHistory( |
| 126 | + instructions |
| 127 | + ); |
| 128 | + |
| 129 | + // Add agent additional instructions |
| 130 | + if (additionalInstructions != null) { |
| 131 | + chat.addMessage(new ChatMessageContent<>( |
| 132 | + AuthorRole.SYSTEM, |
| 133 | + additionalInstructions |
| 134 | + )); |
| 135 | + } |
| 136 | + |
| 137 | + chat.addAll(history); |
| 138 | + int previousHistorySize = chat.getMessages().size(); |
| 139 | + |
| 140 | + return chatCompletionService.getChatMessageContentsAsync(chat, kernel, newMessagesContext) |
| 141 | + .map(chatMessageContents -> { |
| 142 | + return chatMessageContents.subList( |
| 143 | + previousHistorySize, |
| 144 | + chatMessageContents.size()); |
| 145 | + }); |
| 146 | + } |
| 147 | + ); |
| 148 | + |
| 149 | + |
| 150 | + } catch (ServiceNotFoundException e) { |
| 151 | + throw new RuntimeException(e); |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + /** |
| 156 | + * Builder for creating instances of ChatCompletionAgent. |
| 157 | + */ |
| 158 | + public static Builder builder() { |
| 159 | + return new Builder(); |
| 160 | + } |
| 161 | + |
| 162 | + public static class Builder implements SemanticKernelBuilder<ChatCompletionAgent> { |
| 163 | + private String id; |
| 164 | + private String name; |
| 165 | + private String description; |
| 166 | + private Kernel kernel; |
| 167 | + private KernelArguments KernelArguments; |
| 168 | + private InvocationContext invocationContext; |
| 169 | + private String instructions; |
| 170 | + private PromptTemplate template; |
| 171 | + |
| 172 | + public Builder withId(String id) { |
| 173 | + this.id = id; |
| 174 | + return this; |
| 175 | + } |
| 176 | + |
| 177 | + public Builder withName(String name) { |
| 178 | + this.name = name; |
| 179 | + return this; |
| 180 | + } |
| 181 | + |
| 182 | + public Builder withDescription(String description) { |
| 183 | + this.description = description; |
| 184 | + return this; |
| 185 | + } |
| 186 | + |
| 187 | + public Builder withKernel(Kernel kernel) { |
| 188 | + this.kernel = kernel; |
| 189 | + return this; |
| 190 | + } |
| 191 | + |
| 192 | + public Builder withKernelArguments(KernelArguments KernelArguments) { |
| 193 | + this.KernelArguments = KernelArguments; |
| 194 | + return this; |
| 195 | + } |
| 196 | + |
| 197 | + public Builder withInstructions(String instructions) { |
| 198 | + this.instructions = instructions; |
| 199 | + return this; |
| 200 | + } |
| 201 | + |
| 202 | + public Builder withInvocationContext(InvocationContext invocationContext) { |
| 203 | + this.invocationContext = invocationContext; |
| 204 | + return this; |
| 205 | + } |
| 206 | + |
| 207 | + public Builder withTemplate(PromptTemplate template) { |
| 208 | + this.template = template; |
| 209 | + return this; |
| 210 | + } |
| 211 | + |
| 212 | + public ChatCompletionAgent build() { |
| 213 | + return new ChatCompletionAgent( |
| 214 | + id, |
| 215 | + name, |
| 216 | + description, |
| 217 | + kernel, |
| 218 | + KernelArguments, |
| 219 | + invocationContext, |
| 220 | + instructions, |
| 221 | + template |
| 222 | + ); |
| 223 | + } |
| 224 | + |
| 225 | + public ChatCompletionAgent build(PromptTemplateConfig promptTemplateConfig, PromptTemplateFactory promptTemplateFactory) { |
| 226 | + return new ChatCompletionAgent( |
| 227 | + id, |
| 228 | + name, |
| 229 | + description, |
| 230 | + kernel, |
| 231 | + KernelArguments, |
| 232 | + invocationContext, |
| 233 | + promptTemplateConfig.getTemplate(), |
| 234 | + promptTemplateFactory.tryCreate(promptTemplateConfig) |
| 235 | + ); |
| 236 | + } |
| 237 | + } |
| 238 | +} |
0 commit comments