Hello !
Thank you for posting on Microsoft Learn.
With Semantic Kernel you get every file that the code interpreter produces as a file-reference item in the assistant reply. All you have to do is :
- Collect the file-ids (they arrive as StreamingFileReferenceContent while you stream, or FileReferenceContent when you ask for the full message).
- Use the underlying OpenAIFileClient (or the file_client you created) to download the bytes.
using Azure.AI.OpenAI;
using Microsoft.SemanticKernel.Agents.OpenAI;
using Microsoft.SemanticKernel.Contents;
using Microsoft.SemanticKernel;
using OpenAI.Files;
using System.Linq;
OpenAIFileClient fileClient = client.GetOpenAIFileClient();
List<string> fileIds = new();
await foreach (StreamingChatMessageContent chunk
in agent.InvokeStreamingAsync(userMessage, thread))
{
Console.Write(chunk.Content);
fileIds.AddRange(chunk.Items
.OfType<StreamingFileReferenceContent>()
.Select(f => f.FileId));
}
foreach (string id in fileIds)
{
OpenAIFile info = fileClient.GetFile(id);
BinaryData data = await fileClient.DownloadFileAsync(id);
string localName = Path.Combine("downloads",
Path.GetFileName(info.Filename ?? $"{id}.bin"));
await File.WriteAllBytesAsync(localName, data.ToArray());
Console.WriteLine($"saved → {localName}");
}
Another alternative you can have (non-streaming) :
ChatMessageContent reply = await agent.InvokeAsync(userMessage, thread);
foreach (var file in reply.Items.OfType<FileReferenceContent>())
{
var bytes = await fileClient.DownloadFileAsync(file.FileId);
File.WriteAllBytes($"out/{file.FileId}.png", bytes.ToArray());
}