How to Add Chat History in OpenAI Assistant in a C# Bot Framework?

Hi everyone,

I’m working on a bot using OpenAI’s Assistant API within the Bot Framework SDK. I’ve integrated it to handle conversations, but I’m struggling with adding chat history. I’m using Cosmos DB to store previous conversations. When a user re-engages, I want to load the previous chat into the assistant thread.

Here’s a simplified part of my code:

// Fetch previous messages
var recentMessages = await _cosmosDbService.GetFormattedRecentMessagesAsync(conversationData.ThreadID);
var messages = new List<ThreadInitializationMessage>();

foreach (var msg in recentMessages)
{
    if (msg.who == "User")
    {
        messages.Add(new ThreadInitializationMessage(msg.Message, MessageRole.User));
    }
    else
    {
        messages.Add(new ThreadInitializationMessage(msg.Message, MessageRole.Assistant));
    }
}

// Initialize thread with messages
var threadOptions = new ThreadCreationOptions(messages);
var run = await client.CreateThreadAndRunAsync(assistantId, threadOptions);

However, I’m running into issues with message types and correctly loading chat history. Any suggestions on improving this?

Thanks!

Why are you storing chat history of assistant? The threads stores it for you. The only reason could be you trying to access thread after its retention period has passed.

If that’s the case, you can store the whole conversation in JSON format and add it to a new thread when User comes back.

If that’s not the case, simple fetch the thread ID and all the messages will come with it.