我正在尝试使用会话变量(asp.net 应用程序)保留 Assistant 和 AssistantClient 类的实例,并检索它以与模型进行进一步对话。 我相信这将帮助助手保留其聊天记录,以便对新问题的模型响应是适当的。
public class AIHelper
{
AzureOpenAIClient? client;
public OpenAI.Assistants.Assistant? openai_Assistant;
public OpenAI.Assistants.AssistantClient? openai_AssistantClient;
public void EstablishAISession()
{
client = new AzureOpenAIClient(apiEndPoint,azureKeyCredentials,azureOpenAIClientOptions)
openai_assistantClient = client.getAssistantClient();
openai_assistant = openai_assistantClient.CreateAssistant(modelName)
}
}
//I do serailization and deserlization using below code
if( _httpContextAccessor.HttpContext.Session.GetString("AIHelper") == null){
AIHelper aiHelper = new AIHelper();
aiHelper.EstablishAISession();
_httpContextAccessor.HttpContext.Session.SetString("AIHelper", JsonConvert.SerializeObject(aiHelper));
}
else
{
aiHelper = JsonConvert.DeserializeObject<AIHelper>(_httpContextAccessor.HttpContext.Session.GetString("AIHelper"));
}
反序列化后,我总是得到 aiHelper.openai_Assistant 和 openai_AssistantClient 值为 null。
我期望反序列化有助于使用 Assistant 和 AssistantClient 类的现有实例。
要使用会话变量保留 OpenAI
Assistant
的实例,请按照以下步骤操作:
下面的代码定义了一个用于存储聊天记录的可序列化类:
public class SerializableChatContext
{
public List<string> Messages { get; set; }
public List<DateTime> Timestamps { get; set; }
public string UserId { get; set; }
}
以下代码将上下文存储在会话中:
var chatContext = new SerializableChatContext
{
Messages = new List<string> { "Hello, how can I help you today?" },
Timestamps = new List<DateTime> { DateTime.UtcNow },
UserId = "user123"
};
Session["ChatContext"] = chatContext;
下面的代码列出了来自线程的消息。我对 Azure OpenAI 使用了这个链接:
Response<PageableList<ThreadMessage>> afterRunMessagesResponse
= await client.GetMessagesAsync(thread.Id);
IReadOnlyList<ThreadMessage> messages = afterRunMessagesResponse.Value.Data;
foreach (ThreadMessage threadMessage in messages)
{
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
foreach (MessageContent contentItem in threadMessage.ContentItems)
{
if (contentItem is MessageTextContent textItem)
{
Console.Write(textItem.Text);
}
else if (contentItem is MessageImageFileContent imageFileItem)
{
Console.Write($"<image from ID: {imageFileItem.FileId}");
}
Console.WriteLine();
}
}
输出:
有关更多详细信息,请参阅此 GitHub 存储库,了解适用于 .NET 的 OpenAI Assistants 客户端库。