Skip to content

Commit

Permalink
Merge pull request #50 from stonelv/master
Browse files Browse the repository at this point in the history
Add Image Generation API (DALL-E), thanks @stonelv
  • Loading branch information
OkGoDoIt committed Mar 8, 2023
2 parents e949bd4 + 1066e7d commit a3e3d14
Show file tree
Hide file tree
Showing 6 changed files with 224 additions and 1 deletion.
51 changes: 51 additions & 0 deletions OpenAI_API/Images/ImageEndpoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using OpenAI_API.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace OpenAI_API.Images
{
/// <summary>
/// Given a prompt and/or an input image, the model will generate a new image.
/// </summary>
public class ImageEndpoint : EndpointBase
{
/// <summary>
/// This allows you to send request to the recommended model without needing to specify.
/// </summary>
public ImageRequest DefaultImageRequestArgs { get; set; } = new ImageRequest() {};

/// <summary>
/// The name of the endpoint, which is the final path segment in the API URL. For example, "image".
/// </summary>
protected override string Endpoint { get { return "images/generations"; } }

/// <summary>
/// Constructor of the api endpoint. Rather than instantiating this yourself, access it through an instance of <see cref="OpenAIAPI"/> as <see cref="OpenAIAPI.Images"/>.
/// </summary>
/// <param name="api"></param>
internal ImageEndpoint(OpenAIAPI api) : base(api) { }

/// <summary>
/// Ask the API to Creates an image given a prompt.
/// </summary>
/// <param name="input">A text description of the desired image(s)</param>
/// <returns>Asynchronously returns the image result. Look in its <see cref="Data.Url"/> </returns>
public async Task<ImageResult> CreateImageAsync(string input)
{
ImageRequest req = new ImageRequest(prompt: input);
return await CreateImageAsync(req);
}

/// <summary>
/// Ask the API to Creates an image given a prompt.
/// </summary>
/// <param name="request">Request to be send</param>
/// <returns>Asynchronously returns the image result. Look in its <see cref="Data.Url"/> </returns>
public async Task<ImageResult> CreateImageAsync(ImageRequest request)
{
return await HttpPost<ImageResult>(postData: request);
}
}
}
76 changes: 76 additions & 0 deletions OpenAI_API/Images/ImageRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using Newtonsoft.Json;
using OpenAI_API.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpenAI_API.Images
{
/// <summary>
/// Represents a request to the Images API. Mostly matches the parameters in <see href="https://platform.openai.com/docs/api-reference/images/create">the OpenAI docs</see>, although some have been renames or expanded into single/multiple properties for ease of use.
/// </summary>
public class ImageRequest
{
/// <summary>
/// A text description of the desired image(s). The maximum length is 1000 characters.
/// </summary>
[JsonProperty("prompt")]
public string Prompt { get; set; }

/// <summary>
/// How many different choices to request for each prompt. Defaults to 1.
/// </summary>
[JsonProperty("n")]
public int? NumOfImages { get; set; }

/// <summary>
/// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.
/// </summary>
[JsonProperty("user")]
public string User { get; set; }

/// <summary>
/// The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024.
/// </summary>
[JsonProperty("size")]
public string Size { get; set; }

/// <summary>
/// The format in which the generated images are returned. Must be one of url or b64_json.
/// </summary>
[JsonProperty("response_format")]
public string ResponseFormat { get; set; }

/// <summary>
/// Cretes a new, empty <see cref="ImageRequest"/>
/// </summary>
public ImageRequest()
{

}

/// <summary>
/// Creates a new <see cref="ImageRequest"/> with the specified parameters
/// </summary>
/// <param name="prompt">A text description of the desired image(s). The maximum length is 1000 characters.</param>
/// <param name="numOfImages">How many different choices to request for each prompt. Defaults to 1.</param>
/// <param name="user">A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.</param>
/// <param name="size">The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024.</param>
/// <param name="responseFormat">The format in which the generated images are returned. Must be one of url or b64_json.</param>
public ImageRequest(
string prompt,
int? numOfImages = null,
string user = null,
string size = null,
string responseFormat = null)
{
this.Prompt = prompt;
this.NumOfImages = numOfImages;
this.User = user;
this.Size = size;
this.ResponseFormat = responseFormat;
}

}
}
33 changes: 33 additions & 0 deletions OpenAI_API/Images/ImageResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace OpenAI_API.Images
{
/// <summary>
/// Represents an image result returned by the Image API.
/// </summary>
public class ImageResult : ApiResultBase
{
/// <summary>
/// List of results of the embedding
/// </summary>
[JsonProperty("data")]
public List<Data> Data { get; set; }
}

/// <summary>
/// Data returned from the Image API.
/// </summary>
public class Data
{
/// <summary>
/// The url of the image.
/// </summary>
[JsonProperty("url")]

public string Url { get; set; }

}
}
7 changes: 6 additions & 1 deletion OpenAI_API/OpenAIAPI.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using OpenAI_API.Completions;
using OpenAI_API.Embedding;
using OpenAI_API.Files;
using OpenAI_API.Images;
using OpenAI_API.Models;
using System.Xml.Linq;

Expand Down Expand Up @@ -39,6 +40,7 @@ public OpenAIAPI(APIAuthentication apiKeys = null)
Models = new ModelsEndpoint(this);
Files = new FilesEndpoint(this);
Embeddings = new EmbeddingEndpoint(this);
Images = new ImageEndpoint(this);
}

/// <summary>
Expand Down Expand Up @@ -76,7 +78,10 @@ public static OpenAIAPI ForAzure(string YourResourceName, string deploymentId, A
/// </summary>
public FilesEndpoint Files { get; }


/// <summary>
/// The API lets you do operations with images. You can Given a prompt and/or an input image, the model will generate a new image.
/// </summary>
public ImageEndpoint Images { get; }

}
}
44 changes: 44 additions & 0 deletions OpenAI_Tests/ImageEndpointTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using NUnit.Framework;
using OpenAI_API.Images;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpenAI_Tests
{
public class ImageEndpointTests
{
[SetUp]
public void Setup()
{
OpenAI_API.APIAuthentication.Default = new OpenAI_API.APIAuthentication(Environment.GetEnvironmentVariable("TEST_OPENAI_SECRET_KEY"));
}

[Test]
public void CreateBasicImage()
{
var api = new OpenAI_API.OpenAIAPI();

Assert.IsNotNull(api.Images);

var results = api.Images.CreateImageAsync(new ImageRequest("A cyberpunk monkey hacker dreaming of a beautiful bunch of bananas, digital art")).Result;
Assert.IsNotNull(results);
if (results.CreatedUnixTime.HasValue)
{
Assert.NotZero(results.CreatedUnixTime.Value);
Assert.NotNull(results.Created);
Assert.Greater(results.Created.Value, new DateTime(2018, 1, 1));
Assert.Less(results.Created.Value, DateTime.Now.AddDays(1));
}
else
{
Assert.Null(results.Created);
}
//Assert.NotNull(results.Object);
Assert.NotZero(results.Data.Count);
Assert.That(results.Data.First().Url.Length > 0);
}

}
}
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,20 @@ There are also methods to get file contents, delete a file, etc.

The fine-tuning endpoint itself has not yet been implemented, but will be added soon.

### Images
The Images API is accessed via `OpenAIAPI.Images`:

```csharp
async Task<EmbeddingResult> CreateEmbeddingAsync(ImageRequest request);

// for example
var result = await api.Images.CreateImageAsync(new ImageRequest("A test text for images"));
// or
var result = await api.Images.CreateImageAsync("A test text for images");
```

The image result contains a URL for a online image.

### Azure

For using the Azure OpenAI Service, you need to specify the name of your Azure OpenAI resource as well as your model deployment id. Additionally you may specify the Api version which defaults to `2022-12-01`.
Expand Down

0 comments on commit a3e3d14

Please sign in to comment.