in src/WebJobs.Extensions.OpenAI/Assistants/AssistantService.cs [59:133]
public async Task CreateAssistantAsync(AssistantCreateRequest request, CancellationToken cancellationToken)
{
this.logger.LogInformation(
"[{Id}] Creating new chat session with instructions = \"{Text}\"",
request.Id,
request.Instructions ?? "(none)");
TableClient tableClient = this.GetOrCreateTableClient(request.ChatStorageConnectionSetting, request.CollectionName);
// Create the table if it doesn't exist
await tableClient.CreateIfNotExistsAsync();
// Check to see if the assistant has already been initialized
AsyncPageable<TableEntity> queryResultsFilter = tableClient.QueryAsync<TableEntity>(
filter: $"PartitionKey eq '{request.Id}'",
cancellationToken: cancellationToken);
// Create a batch of table transaction actions for deleting entities
List<TableTransactionAction> deleteBatch = new(capacity: 100);
// Local function for deleting batches of assistant state
async Task DeleteBatch()
{
if (deleteBatch.Count > 0)
{
this.logger.LogInformation(
"Deleting {Count} record(s) for assistant '{Id}'.",
deleteBatch.Count,
request.Id);
await tableClient.SubmitTransactionAsync(deleteBatch);
deleteBatch.Clear();
}
}
await foreach (TableEntity entity in queryResultsFilter)
{
// If the count is greater than or equal to 100, submit the transaction and clear the batch
if (deleteBatch.Count >= 100)
{
await DeleteBatch();
}
deleteBatch.Add(new TableTransactionAction(TableTransactionActionType.Delete, entity));
}
if (deleteBatch.Any())
{
// delete any remaining
await DeleteBatch();
}
// Create a batch of table transaction actions
List<TableTransactionAction> batch = new();
// Add first chat message entity to table
if (!string.IsNullOrWhiteSpace(request.Instructions))
{
ChatMessageTableEntity chatMessageEntity = new(
partitionKey: request.Id,
messageIndex: 1, // 1-based index
content: request.Instructions,
role: ChatMessageRole.System,
toolCalls: null);
batch.Add(new TableTransactionAction(TableTransactionActionType.Add, chatMessageEntity));
}
// Add assistant state entity to table
AssistantStateEntity assistantStateEntity = new(request.Id) { TotalMessages = batch.Count };
batch.Add(new TableTransactionAction(TableTransactionActionType.Add, assistantStateEntity));
// Add the batch of table transaction actions to the table
await tableClient.SubmitTransactionAsync(batch);
}