Skip to content

Commit fbdfb2a

Browse files
committed
Merge remote-tracking branch 'origin/main' into bruno-addMicrosoftFoundryAgentSamples
2 parents 1e50d69 + 5d035eb commit fbdfb2a

File tree

3 files changed

+32
-73
lines changed

3 files changed

+32
-73
lines changed

03-CoreGenerativeAITechniques/05-ImageGenerationOpenAI.md

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,6 @@ To run the sample code, you'll need to:
3131
```bash
3232
cd samples\CoreSamples\ImageGeneration-01
3333
```
34-
If you're using Linux, macOS, Git Bash, WSL, or the VS Code terminal:
35-
```bash
36-
cd samples\CoreSamples\ImageGeneration-01
37-
```
3834

3935
If you're using Linux, macOS, Git Bash, WSL, or the VS Code terminal:
4036
```bash

samples/AgentFx/AgentFx-AIFoundryAgents-01/Program.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@
2121
// get existing agent
2222
AIAgent aiAgent = await persistentAgentClient.GetAIAgentAsync(assistantId);
2323

24-
var thread = aiAgent.GetNewThread();
25-
2624
while (true)
2725
{
2826
Console.Write("User: ");
@@ -31,6 +29,6 @@
3129
{
3230
break;
3331
}
34-
var response = await aiAgent.RunAsync(userInput, thread);
32+
var response = await aiAgent.RunAsync(userInput);
3533
Console.WriteLine($"Agent: {response.Text}");
3634
}

samples/AgentFx/AgentFx-ImageGen-02/ImageGenerator.cs

Lines changed: 31 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
using System.ComponentModel;
44
using System.Text;
55
using System.Text.Json;
6+
using OpenAI;
7+
using OpenAI.Images;
8+
using System.ClientModel;
9+
10+
#pragma warning disable OPENAI001
611

712
namespace AgentFx_ImageGen_02;
813

@@ -18,90 +23,50 @@ public static async Task<string> GenerateImageFromPrompt(
1823
.AddEnvironmentVariables()
1924
.AddUserSecrets<Program>()
2025
.Build();
21-
var deploymentName = config["deploymentName"] ?? "gpt-5-mini";
2226

2327
// You will need to set these environment variables or edit the following values.
2428
var endpoint = config["endpoint"];
2529
var deployment = config["FLUX_DEPLOYMENT_NAME"];
26-
var apiVersion = config["FLUX_OPENAI_API_VERSION"];
2730
var apiKey = config["AZURE_OPENAI_API_KEY"];
2831

29-
if (!endpoint.EndsWith('/'))
32+
// Ensure endpoint ends with /openai/v1/
33+
if (!endpoint.EndsWith("/openai/v1/"))
3034
{
31-
endpoint += '/';
35+
if (endpoint.EndsWith('/'))
36+
{
37+
endpoint += "openai/v1/";
38+
}
39+
else
40+
{
41+
endpoint += "/openai/v1/";
42+
}
3243
}
3344

34-
var basePath = $"openai/deployments/{deployment}/images";
35-
var urlParams = $"?api-version={apiVersion}";
36-
37-
using var client = new HttpClient();
45+
ImageClient client = new(
46+
credential: new ApiKeyCredential(apiKey),
47+
model: deployment,
48+
options: new OpenAIClientOptions()
49+
{
50+
Endpoint = new Uri(endpoint),
51+
}
52+
);
3853

39-
var generationUrl = $"{endpoint}{basePath}/generations{urlParams}";
40-
var generationBody = new
54+
ImageGenerationOptions options = new()
4155
{
42-
prompt = imageGenerationPrompt, // use provided prompt
43-
n =1,
44-
size = "1024x1024",
45-
quality = "standard",
46-
output_format = "png",
56+
Size = GeneratedImageSize.W1024xH1024,
4757
};
4858

49-
using (var genRequest = new HttpRequestMessage(HttpMethod.Post, generationUrl))
50-
{
51-
genRequest.Headers.Add("Api-Key", apiKey);
52-
var json = JsonSerializer.Serialize(generationBody);
53-
genRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
54-
55-
var genResponse = await client.SendAsync(genRequest);
56-
genResponse.EnsureSuccessStatusCode();
57-
var genResult = await genResponse.Content.ReadAsStringAsync();
58-
59-
// Save image(s) and return path of first image
60-
var savedPath = SaveImageFromGenerationResponse(genResult);
61-
return savedPath;
62-
}
63-
}
64-
65-
/// <summary>
66-
/// Parses the JSON image generation response, extracts the first base64 image payload and saves it as a PNG file.
67-
/// Returns the absolute path to the saved image file.
68-
/// </summary>
69-
/// <param name="generationResponseJson">JSON returned by the image generation endpoint.</param>
70-
/// <returns>Absolute file path of saved PNG image.</returns>
71-
public static string SaveImageFromGenerationResponse(string generationResponseJson)
72-
{
73-
if (string.IsNullOrWhiteSpace(generationResponseJson))
74-
throw new ArgumentException("Generation response JSON is empty", nameof(generationResponseJson));
75-
76-
using var doc = JsonDocument.Parse(generationResponseJson);
77-
var root = doc.RootElement;
78-
if (!root.TryGetProperty("data", out var dataArray) || dataArray.ValueKind != JsonValueKind.Array || dataArray.GetArrayLength() ==0)
79-
throw new InvalidOperationException("Image generation response does not contain a 'data' array with any items.");
80-
81-
var first = dataArray[0];
82-
if (!first.TryGetProperty("b64_json", out var b64Element))
83-
throw new InvalidOperationException("Image generation response item does not contain 'b64_json'.");
84-
85-
var b64 = b64Element.GetString();
86-
if (string.IsNullOrWhiteSpace(b64))
87-
throw new InvalidOperationException("'b64_json' value is empty.");
88-
89-
byte[] bytes;
90-
try
91-
{
92-
bytes = Convert.FromBase64String(b64);
93-
}
94-
catch (FormatException ex)
95-
{
96-
throw new InvalidOperationException("Failed to decode base64 image content.", ex);
97-
}
59+
GeneratedImage image = await client.GenerateImageAsync(imageGenerationPrompt, options);
60+
BinaryData bytes = image.ImageBytes;
9861

9962
var outputDir = Path.Combine(Environment.CurrentDirectory, "generated-images");
10063
Directory.CreateDirectory(outputDir);
10164

102-
var fileName = $"image_{DateTime.UtcNow:yyyyMMdd_HHmmssfff}.png";
65+
var fileName = $"image_{DateTime.UtcNow:yyyyMMdd_HHmmssfff}.jpg";
10366
var filePath = Path.Combine(outputDir, fileName);
104-
File.WriteAllBytes(filePath, bytes);
67+
File.WriteAllBytes(filePath, bytes.ToArray());
68+
10569
return filePath;
10670
}
10771
}
72+

0 commit comments

Comments
 (0)