Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 17 additions & 30 deletions sdk/ai/Azure.AI.Agents.Persistent/src/Custom/ThreadMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,26 +231,7 @@ public virtual async Task<Response<PersistentThreadMessage>> CreateMessageAsync(
Argument.AssertNotNull(contentBlocks, nameof(contentBlocks));

// Convert blocks to a JSON array stored as BinaryData
var jsonElements = new List<JsonElement>();
foreach (MessageInputContentBlock block in contentBlocks)
{
// Write the content into a MemoryStream.
using var memStream = new MemoryStream();

// Write the RequestContent into the MemoryStream
block.ToRequestContent().WriteTo(memStream, default);

// Reset stream position to the beginning
memStream.Position = 0;

// Parse to a JsonDocument, then clone the root element so we can reuse it
using var tempDoc = JsonDocument.Parse(memStream);
jsonElements.Add(tempDoc.RootElement.Clone());
}

// Now serialize the array of JsonElements into a single BinaryData for the request:
var jsonString = JsonSerializer.Serialize(contentBlocks, JsonElementSerializer.Default.ListJsonElement);
BinaryData serializedBlocks = BinaryData.FromString(jsonString);
BinaryData serializedBlocks = ConvertMessageInputContentBlocksToJson(contentBlocks);

return await CreateMessageAsync(
threadId,
Expand Down Expand Up @@ -295,6 +276,21 @@ public virtual Response<PersistentThreadMessage> CreateMessage(
Argument.AssertNotNullOrEmpty(threadId, nameof(threadId));
Argument.AssertNotNull(contentBlocks, nameof(contentBlocks));

// Convert blocks to a JSON array stored as BinaryData
BinaryData serializedBlocks = ConvertMessageInputContentBlocksToJson(contentBlocks);

return CreateMessage(
threadId,
role,
serializedBlocks,
attachments,
metadata,
cancellationToken
);
}

private static BinaryData ConvertMessageInputContentBlocksToJson(IEnumerable<MessageInputContentBlock> contentBlocks)
{
// Convert blocks to a JSON array stored as BinaryData
var jsonElements = new List<JsonElement>();
foreach (MessageInputContentBlock block in contentBlocks)
Expand All @@ -315,16 +311,7 @@ public virtual Response<PersistentThreadMessage> CreateMessage(

// Now serialize the array of JsonElements into a single BinaryData for the request:
var jsonString = JsonSerializer.Serialize(jsonElements, JsonElementSerializer.Default.ListJsonElement);
BinaryData serializedBlocks = BinaryData.FromString(jsonString);

return CreateMessage(
threadId,
role,
serializedBlocks,
attachments,
metadata,
cancellationToken
);
return BinaryData.FromString(jsonString);
}

/// <summary> Gets a list of messages that exist on a thread. </summary>
Expand Down