Skip to content

Image interaction API

Zoltan Juhasz edited this page May 2, 2023 · 1 revision

The Images API provides three methods for interacting with images:

Creating images from scratch based on a text prompt Creating edits of an existing image based on a new text prompt Creating variations of an existing image

Example - Create an image

Learn how to generate images with DALL·E models

static async Task Main(string[] args)
{
    // This example demonstrates, how you can ask OpenAI to an image based on your instructions.
    // More information: https://platform.openai.com/docs/guides/images/image-generation-beta
    //
    // The very first step to create an account at OpenAI: https://platform.openai.com/
    // Using the loggedIn account, navigate to https://platform.openai.com/account/api-keys
    // Here you can create apiKey(s)

    using var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((builder, services) =>
    {
        services.AddForgeOpenAI(options => {
            options.AuthenticationInfo = builder.Configuration["OpenAI:ApiKey"]!;
        });
    })
    .Build();

    IOpenAIService openAi = host.Services.GetService<IOpenAIService>()!;

    ImageCreateRequest request = new ImageCreateRequest();
    request.Prompt = "A cute baby sea otter";

    HttpOperationResult<ImageCreateResponse> response = 
        await openAi.ImageService
            .CreateImageAsync(request, CancellationToken.None)
                .ConfigureAwait(false);
    
    if (response.IsSuccess)
    {
        Console.WriteLine(response.Result!);

        response.Result!.ImageData.ForEach(imageData => OpenUrl(imageData.ImageUrl));
    }
    else
    {
        Console.WriteLine(response);
    }
}