Adding your own data as context to OpenAIs ChatGPT in .NET

My last post on OpenAI ChatGPT showed how to use ChatGPT in a .NET application using the Azure.AI.OpenAI library. This package went meanwhile to beta version 1.11.0-beta.1 and thus the usage of the ChatCompletionOptions has changed a little bit, you guess you will note it in your applications and tests.

For todays example I use OkGoDoIt OpenAI-API library, as I want to show you how to connect to OpenAI without using Azure services and also I find it easier to use for simple applications.

In order to connect to OpenAI ChatGPT without Azure services you need to generate a secret key for your application in the OpenAI web UI. If you are using an enterprise account, you also need to add your organization identifier as second parameter for the initial connection (not shown in the example). Immediately thereafter you can instantiate your conversation object using the specified model.

using OpenAI_API;
using OpenAI_API.Models;

OpenAIAPI openAiApi = new OpenAIAPI(new APIAuthentication("your-secret-key"));

var chat = openAiApi.Chat.CreateConversation();
chat.Model = Model.ChatGPTTurbo;

In this example, I want to create an Italian chef using a receipe collection provided by me as context.

Therefore the systems message context states, that the model shall act as Italian chef.

For making this Italian chef using your own kitchen receipes in its repertoire, you have can add them as JSON file using prompt/completion pairs. Each prompt/completion pair has to be in a single line in this file. I guess it’s easy to see how to use this mechanism for adding your proprietary data to a context.

// system context set-up
chat.AppendSystemMessage("You are an expert for for italian kitchen. You answer every question with Italian dialect from Puglia.");

// data for context as prompt/completion pairs
var fileResponse = await openAiApi.Files.UploadFileAsync("data\\SpaghettiPuttanesca.txt");

/*
file example, single line: { "prompt": "Spaghetti Puttanesca ingredients", "completion": "ingredients are: tomato, olives, capers, garlic, anchovy, red wine, spaghetti" }
*/

// the ID of the uploaded file for context
Console.WriteLine($"File ID: {fileResponse.Id}");

Now we can just add the user prompt in the context. I am using an async request in this example, as you always should to avoid blocking your application.

// user prompt
chat.AppendUserInput("What is the main ingredients for Spaghetti Puttanesca?");
await foreach (var completionResponse in chat.StreamResponseEnumerableFromChatbotAsync())
{
    Console.Write(completionResponse);
}

Hope you enjoy OpenAIs ChatGPT! As you can see, it’s very easy to integrate your own data context in the ChatGPT model using external JSON files. Happy coding πŸš€!