|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | +package com.microsoft.semantickernel.samples.syntaxexamples.java; |
| 3 | + |
| 4 | +import com.azure.ai.openai.OpenAIAsyncClient; |
| 5 | +import com.azure.ai.openai.OpenAIClientBuilder; |
| 6 | +import com.azure.core.credential.AzureKeyCredential; |
| 7 | +import com.azure.core.credential.KeyCredential; |
| 8 | +import com.microsoft.semantickernel.Kernel; |
| 9 | +import com.microsoft.semantickernel.aiservices.openai.chatcompletion.OpenAIChatCompletion; |
| 10 | +import com.microsoft.semantickernel.exceptions.ConfigurationException; |
| 11 | +import com.microsoft.semantickernel.implementation.telemetry.SemanticKernelTelemetry; |
| 12 | +import com.microsoft.semantickernel.orchestration.InvocationContext; |
| 13 | +import com.microsoft.semantickernel.orchestration.InvocationReturnMode; |
| 14 | +import com.microsoft.semantickernel.orchestration.ToolCallBehavior; |
| 15 | +import com.microsoft.semantickernel.plugin.KernelPluginFactory; |
| 16 | +import com.microsoft.semantickernel.samples.syntaxexamples.functions.Example59_OpenAIFunctionCalling.PetPlugin; |
| 17 | +import com.microsoft.semantickernel.semanticfunctions.KernelFunctionArguments; |
| 18 | +import com.microsoft.semantickernel.semanticfunctions.annotations.DefineKernelFunction; |
| 19 | +import com.microsoft.semantickernel.semanticfunctions.annotations.KernelFunctionParameter; |
| 20 | +import com.microsoft.semantickernel.services.ServiceNotFoundException; |
| 21 | +import com.microsoft.semantickernel.services.chatcompletion.ChatCompletionService; |
| 22 | +import com.microsoft.semantickernel.services.chatcompletion.ChatHistory; |
| 23 | +import io.opentelemetry.api.GlobalOpenTelemetry; |
| 24 | +import io.opentelemetry.api.trace.Span; |
| 25 | +import io.opentelemetry.api.trace.SpanKind; |
| 26 | +import io.opentelemetry.api.trace.StatusCode; |
| 27 | +import io.opentelemetry.context.Scope; |
| 28 | +import java.io.IOException; |
| 29 | +import java.math.BigInteger; |
| 30 | +import java.nio.charset.StandardCharsets; |
| 31 | +import java.security.MessageDigest; |
| 32 | +import java.security.NoSuchAlgorithmException; |
| 33 | +import java.util.Locale; |
| 34 | +import reactor.core.publisher.Mono; |
| 35 | + |
| 36 | +public class FunctionTelemetry_Example { |
| 37 | + /* |
| 38 | + * // Get the Application Insights agent from |
| 39 | + * https://github.com/microsoft/ApplicationInsights-Java, e.g: |
| 40 | + * ``` |
| 41 | + * wget -O "/tmp/applicationinsights-agent-3.6.1.jar" |
| 42 | + * "https://github.com/microsoft/ApplicationInsights-Java/releases/download/3.6.1/applicationinsights-agent-3.6.1.jar" |
| 43 | + * ``` |
| 44 | + * |
| 45 | + * // Get your application insights connection string from the Azure portal |
| 46 | + * ``` |
| 47 | + * CLIENT_ENDPOINT="<ENDPOINT>" \ |
| 48 | + * AZURE_CLIENT_KEY="<KEY>" \ |
| 49 | + * APPLICATIONINSIGHTS_CONNECTION_STRING="<CONNECTION STRING>" \ |
| 50 | + * MAVEN_OPTS="-javaagent:/tmp/applicationinsights-agent-3.6.1.jar" \ |
| 51 | + * ../../../mvnw package exec:java -Dsample="java.FunctionTelemetry_Example" |
| 52 | + * ``` |
| 53 | + * |
| 54 | + * If you open the Application Insights "Live metrics" view while running this example, you |
| 55 | + * should see the telemetry in real-time. |
| 56 | + * Otherwise within a few minutes, you should see the telemetry in the Application Insights -> |
| 57 | + * Investigate -> Transaction search ui in the Azure portal. |
| 58 | + */ |
| 59 | + |
| 60 | + private static final String CLIENT_KEY = System.getenv("CLIENT_KEY"); |
| 61 | + private static final String AZURE_CLIENT_KEY = System.getenv("AZURE_CLIENT_KEY"); |
| 62 | + |
| 63 | + // Only required if AZURE_CLIENT_KEY is set |
| 64 | + private static final String CLIENT_ENDPOINT = System.getenv("CLIENT_ENDPOINT"); |
| 65 | + private static final String MODEL_ID = "gpt-4o"; |
| 66 | + |
| 67 | + public static void main(String[] args) |
| 68 | + throws ConfigurationException, IOException, NoSuchMethodException, InterruptedException { |
| 69 | + requestsWithSpanContext(); |
| 70 | + testNestedCalls(); |
| 71 | + requestsWithScope(); |
| 72 | + |
| 73 | + Thread.sleep(1000); |
| 74 | + } |
| 75 | + |
| 76 | + private static void requestsWithSpanContext() throws IOException { |
| 77 | + Span fakeRequest = GlobalOpenTelemetry.getTracer("Custom") |
| 78 | + .spanBuilder("GET /requestsWithSpanContext") |
| 79 | + .setSpanKind(SpanKind.SERVER) |
| 80 | + .setAttribute("http.request.method", "GET") |
| 81 | + .setAttribute("url.path", "/requestsWithSpanContext") |
| 82 | + .setAttribute("url.scheme", "http") |
| 83 | + .startSpan(); |
| 84 | + |
| 85 | + // Pass span context to the telemetry object to correlate telemetry with the request |
| 86 | + SemanticKernelTelemetry telemetry = new SemanticKernelTelemetry( |
| 87 | + GlobalOpenTelemetry.getTracer("Custom"), |
| 88 | + fakeRequest.getSpanContext()); |
| 89 | + |
| 90 | + sequentialFunctionCalls(telemetry); |
| 91 | + |
| 92 | + fakeRequest.setStatus(StatusCode.OK); |
| 93 | + fakeRequest.end(); |
| 94 | + } |
| 95 | + |
| 96 | + private static void requestsWithScope() throws IOException { |
| 97 | + Span fakeRequest = GlobalOpenTelemetry.getTracer("Custom") |
| 98 | + .spanBuilder("GET /requestsWithScope") |
| 99 | + .setSpanKind(SpanKind.SERVER) |
| 100 | + .setAttribute("http.request.method", "GET") |
| 101 | + .setAttribute("url.path", "/requestsWithScope") |
| 102 | + .setAttribute("url.scheme", "http") |
| 103 | + .startSpan(); |
| 104 | + |
| 105 | + // Pass span context to the telemetry object to correlate telemetry with the request |
| 106 | + SemanticKernelTelemetry telemetry = new SemanticKernelTelemetry(); |
| 107 | + |
| 108 | + try (Scope scope = fakeRequest.makeCurrent()) { |
| 109 | + sequentialFunctionCalls(telemetry); |
| 110 | + } |
| 111 | + |
| 112 | + fakeRequest.setStatus(StatusCode.OK); |
| 113 | + fakeRequest.end(); |
| 114 | + } |
| 115 | + |
| 116 | + public static void sequentialFunctionCalls(SemanticKernelTelemetry telemetry) { |
| 117 | + |
| 118 | + OpenAIAsyncClient client; |
| 119 | + |
| 120 | + if (AZURE_CLIENT_KEY != null) { |
| 121 | + client = new OpenAIClientBuilder() |
| 122 | + .credential(new AzureKeyCredential(AZURE_CLIENT_KEY)) |
| 123 | + .endpoint(CLIENT_ENDPOINT) |
| 124 | + .buildAsyncClient(); |
| 125 | + |
| 126 | + } else { |
| 127 | + client = new OpenAIClientBuilder() |
| 128 | + .credential(new KeyCredential(CLIENT_KEY)) |
| 129 | + .buildAsyncClient(); |
| 130 | + } |
| 131 | + |
| 132 | + ChatCompletionService chat = OpenAIChatCompletion.builder() |
| 133 | + .withModelId(MODEL_ID) |
| 134 | + .withOpenAIAsyncClient(client) |
| 135 | + .build(); |
| 136 | + |
| 137 | + var plugin = KernelPluginFactory.createFromObject(new PetPlugin(), "PetPlugin"); |
| 138 | + |
| 139 | + var kernel = Kernel.builder() |
| 140 | + .withAIService(ChatCompletionService.class, chat) |
| 141 | + .withPlugin(plugin) |
| 142 | + .build(); |
| 143 | + |
| 144 | + var chatHistory = new ChatHistory(); |
| 145 | + chatHistory.addUserMessage( |
| 146 | + "What is the name and type of the pet with id ca2fc6bc-1307-4da6-a009-d7bf88dec37b?"); |
| 147 | + |
| 148 | + var messages = chat.getChatMessageContentsAsync( |
| 149 | + chatHistory, |
| 150 | + kernel, |
| 151 | + InvocationContext.builder() |
| 152 | + .withToolCallBehavior(ToolCallBehavior.allowAllKernelFunctions(true)) |
| 153 | + .withReturnMode(InvocationReturnMode.FULL_HISTORY) |
| 154 | + .withTelemetry(telemetry) |
| 155 | + .build()) |
| 156 | + .block(); |
| 157 | + |
| 158 | + chatHistory = new ChatHistory(messages); |
| 159 | + |
| 160 | + System.out.println( |
| 161 | + "THE NAME AND TYPE IS: " + chatHistory.getLastMessage().get().getContent()); |
| 162 | + } |
| 163 | + |
| 164 | + public static void testNestedCalls() { |
| 165 | + |
| 166 | + OpenAIAsyncClient client; |
| 167 | + |
| 168 | + if (AZURE_CLIENT_KEY != null) { |
| 169 | + client = new OpenAIClientBuilder() |
| 170 | + .credential(new AzureKeyCredential(AZURE_CLIENT_KEY)) |
| 171 | + .endpoint(CLIENT_ENDPOINT) |
| 172 | + .buildAsyncClient(); |
| 173 | + |
| 174 | + } else { |
| 175 | + client = new OpenAIClientBuilder() |
| 176 | + .credential(new KeyCredential(CLIENT_KEY)) |
| 177 | + .buildAsyncClient(); |
| 178 | + } |
| 179 | + |
| 180 | + ChatCompletionService chat = OpenAIChatCompletion.builder() |
| 181 | + .withModelId(MODEL_ID) |
| 182 | + .withOpenAIAsyncClient(client) |
| 183 | + .build(); |
| 184 | + |
| 185 | + var plugin = KernelPluginFactory.createFromObject(new TextAnalysisPlugin(), |
| 186 | + "TextAnalysisPlugin"); |
| 187 | + |
| 188 | + var kernel = Kernel.builder() |
| 189 | + .withAIService(ChatCompletionService.class, chat) |
| 190 | + .withPlugin(plugin) |
| 191 | + .build(); |
| 192 | + |
| 193 | + SemanticKernelTelemetry telemetry = new SemanticKernelTelemetry(); |
| 194 | + |
| 195 | + Span span = GlobalOpenTelemetry.getTracer("Test") |
| 196 | + .spanBuilder("testNestedCalls span") |
| 197 | + .setSpanKind(SpanKind.SERVER) |
| 198 | + .startSpan(); |
| 199 | + |
| 200 | + try (Scope scope = span.makeCurrent()) { |
| 201 | + String analysed = kernel |
| 202 | + .invokePromptAsync( |
| 203 | + """ |
| 204 | + Analyse the following text: |
| 205 | + Hello There |
| 206 | + """, |
| 207 | + KernelFunctionArguments.builder().build(), |
| 208 | + InvocationContext.builder() |
| 209 | + .withToolCallBehavior(ToolCallBehavior.allowAllKernelFunctions(true)) |
| 210 | + .withReturnMode(InvocationReturnMode.NEW_MESSAGES_ONLY) |
| 211 | + .withTelemetry(telemetry) |
| 212 | + .build()) |
| 213 | + .withResultType(String.class) |
| 214 | + .map(result -> { |
| 215 | + return result.getResult(); |
| 216 | + }) |
| 217 | + .block(); |
| 218 | + System.out.println(analysed); |
| 219 | + } finally { |
| 220 | + span.end(); |
| 221 | + } |
| 222 | + |
| 223 | + } |
| 224 | + |
| 225 | + public static class TextAnalysisPlugin { |
| 226 | + |
| 227 | + @DefineKernelFunction(description = "Change all string chars to uppercase.", name = "Uppercase") |
| 228 | + public String uppercase( |
| 229 | + @KernelFunctionParameter(description = "Text to uppercase", name = "input") String text) { |
| 230 | + return text.toUpperCase(Locale.ROOT); |
| 231 | + } |
| 232 | + |
| 233 | + @DefineKernelFunction(name = "sha256sum", description = "Calculates a sha256 of the input", returnType = "string") |
| 234 | + public Mono<String> sha256sum( |
| 235 | + @KernelFunctionParameter(name = "input", description = "The input to checksum", type = String.class) String input, |
| 236 | + Kernel kernel, |
| 237 | + SemanticKernelTelemetry telemetry) throws NoSuchAlgorithmException { |
| 238 | + MessageDigest digest = MessageDigest.getInstance("SHA-256"); |
| 239 | + byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8)); |
| 240 | + String hashStr = new BigInteger(1, hash).toString(16); |
| 241 | + |
| 242 | + return kernel |
| 243 | + .invokePromptAsync( |
| 244 | + """ |
| 245 | + Uppercase the following text: |
| 246 | + === BEGIN TEXT === |
| 247 | + %s |
| 248 | + === END TEXT === |
| 249 | + """.formatted(hashStr) |
| 250 | + .stripIndent(), |
| 251 | + null, |
| 252 | + InvocationContext.builder() |
| 253 | + .withToolCallBehavior(ToolCallBehavior.allowAllKernelFunctions(true)) |
| 254 | + .withReturnMode(InvocationReturnMode.NEW_MESSAGES_ONLY) |
| 255 | + .withTelemetry(telemetry) |
| 256 | + .build()) |
| 257 | + .withResultType(String.class) |
| 258 | + .map(result -> { |
| 259 | + return result.getResult(); |
| 260 | + }); |
| 261 | + } |
| 262 | + |
| 263 | + @DefineKernelFunction(name = "formatAnswer", description = "Formats an answer", returnType = "string") |
| 264 | + public Mono<String> formatAnswer( |
| 265 | + @KernelFunctionParameter(name = "input", description = "The input to format", type = String.class) String input, |
| 266 | + Kernel kernel, |
| 267 | + SemanticKernelTelemetry telemetry) throws ServiceNotFoundException { |
| 268 | + |
| 269 | + return kernel |
| 270 | + .invokePromptAsync( |
| 271 | + """ |
| 272 | + Translate the following text into Italian: |
| 273 | + === BEGIN TEXT === |
| 274 | + %s |
| 275 | + === END TEXT === |
| 276 | + """.formatted(input) |
| 277 | + .stripIndent()) |
| 278 | + .withResultType(String.class) |
| 279 | + .map(result -> { |
| 280 | + return result.getResult(); |
| 281 | + }); |
| 282 | + } |
| 283 | + |
| 284 | + @DefineKernelFunction(name = "analyseInput", description = "Gives a text analysis of the input", returnType = "string") |
| 285 | + public Mono<String> analyseInput( |
| 286 | + @KernelFunctionParameter(name = "input", description = "The input to analyse", type = String.class) String input, |
| 287 | + Kernel kernel, |
| 288 | + SemanticKernelTelemetry telemetry) throws ServiceNotFoundException { |
| 289 | + |
| 290 | + return kernel |
| 291 | + .invokePromptAsync( |
| 292 | + """ |
| 293 | + Calculating sha256sum of the following text: |
| 294 | + === BEGIN TEXT === |
| 295 | + %s |
| 296 | + === END TEXT === |
| 297 | + """.formatted(input) |
| 298 | + .stripIndent(), |
| 299 | + null, |
| 300 | + InvocationContext.builder() |
| 301 | + .withToolCallBehavior(ToolCallBehavior.allowAllKernelFunctions(true)) |
| 302 | + .withReturnMode(InvocationReturnMode.NEW_MESSAGES_ONLY) |
| 303 | + .withTelemetry(telemetry) |
| 304 | + .build()) |
| 305 | + .withResultType(String.class) |
| 306 | + .map(result -> { |
| 307 | + return result.getResult(); |
| 308 | + }) |
| 309 | + .flatMap(answer -> { |
| 310 | + return kernel |
| 311 | + .invokePromptAsync( |
| 312 | + """ |
| 313 | + Format the following text: |
| 314 | + === BEGIN TEXT === |
| 315 | + %s |
| 316 | + === END TEXT === |
| 317 | + """.formatted(answer) |
| 318 | + .stripIndent()) |
| 319 | + .withInvocationContext( |
| 320 | + InvocationContext.builder() |
| 321 | + .withToolCallBehavior( |
| 322 | + ToolCallBehavior.allowAllKernelFunctions(true)) |
| 323 | + .withReturnMode(InvocationReturnMode.NEW_MESSAGES_ONLY) |
| 324 | + .withTelemetry(telemetry) |
| 325 | + .build()) |
| 326 | + .withArguments(null) |
| 327 | + .withTelemetry(telemetry) |
| 328 | + .withResultType(String.class); |
| 329 | + }) |
| 330 | + .map(it -> { |
| 331 | + return it.getResult(); |
| 332 | + }); |
| 333 | + } |
| 334 | + |
| 335 | + } |
| 336 | + |
| 337 | +} |
0 commit comments