|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using Microsoft.SemanticKernel; |
| 4 | +using Microsoft.SemanticKernel.ChatCompletion; |
| 5 | +using Resources; |
| 6 | + |
| 7 | +namespace ChatCompletion; |
| 8 | + |
| 9 | +// This example shows how to use OpenAI chat completion with PDF files. |
| 10 | +public class OpenAI_ChatCompletionWithFile(ITestOutputHelper output) : BaseTest(output) |
| 11 | +{ |
| 12 | + [Fact] |
| 13 | + public async Task LocalFileAsync() |
| 14 | + { |
| 15 | + var fileBytes = await EmbeddedResource.ReadAllAsync("employees.pdf"); |
| 16 | + |
| 17 | + var kernel = Kernel.CreateBuilder() |
| 18 | + .AddOpenAIChatCompletion(TestConfiguration.OpenAI.ChatModelId, TestConfiguration.OpenAI.ApiKey) |
| 19 | + .Build(); |
| 20 | + |
| 21 | + var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>(); |
| 22 | + |
| 23 | + var chatHistory = new ChatHistory("You are a friendly assistant."); |
| 24 | + |
| 25 | + chatHistory.AddUserMessage( |
| 26 | + [ |
| 27 | + new TextContent("What’s in this file?"), |
| 28 | + new BinaryContent(fileBytes, "application/pdf") |
| 29 | + ]); |
| 30 | + |
| 31 | + var reply = await chatCompletionService.GetChatMessageContentAsync(chatHistory); |
| 32 | + |
| 33 | + Console.WriteLine(reply.Content); |
| 34 | + } |
| 35 | + |
| 36 | + [Fact] |
| 37 | + public async Task DateUriFileAsync() |
| 38 | + { |
| 39 | + var fileBytes = await EmbeddedResource.ReadAllAsync("employees.pdf"); |
| 40 | + var fileBase64 = Convert.ToBase64String(fileBytes.ToArray()); |
| 41 | + var dataUri = $"data:application/pdf;base64,{fileBase64}"; |
| 42 | + |
| 43 | + var kernel = Kernel.CreateBuilder() |
| 44 | + .AddOpenAIChatCompletion(TestConfiguration.OpenAI.ChatModelId, TestConfiguration.OpenAI.ApiKey) |
| 45 | + .Build(); |
| 46 | + |
| 47 | + var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>(); |
| 48 | + |
| 49 | + var chatHistory = new ChatHistory("You are a friendly assistant."); |
| 50 | + |
| 51 | + chatHistory.AddUserMessage( |
| 52 | + [ |
| 53 | + new TextContent("What’s in this file?"), |
| 54 | + new BinaryContent(dataUri) |
| 55 | + ]); |
| 56 | + |
| 57 | + var reply = await chatCompletionService.GetChatMessageContentAsync(chatHistory); |
| 58 | + |
| 59 | + Console.WriteLine(reply.Content); |
| 60 | + } |
| 61 | +} |
0 commit comments