Skip to content

Commit

Permalink
Merge branch 'master' into feature/chat
Browse files Browse the repository at this point in the history
  • Loading branch information
OkGoDoIt authored Mar 9, 2023
2 parents 057918f + cad3ad3 commit 9b11270
Show file tree
Hide file tree
Showing 14 changed files with 818 additions and 8 deletions.
46 changes: 46 additions & 0 deletions OpenAI_API/Images/ImageGenerationEndpoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
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 ImageGenerationEndpoint : EndpointBase
{
/// <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.ImageGenerations"/>.
/// </summary>
/// <param name="api"></param>
internal ImageGenerationEndpoint(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)
{
ImageGenerationRequest req = new ImageGenerationRequest(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(ImageGenerationRequest request)
{
return await HttpPost<ImageResult>(postData: request);
}
}
}
76 changes: 76 additions & 0 deletions OpenAI_API/Images/ImageGenerationRequest.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 ImageGenerationRequest
{
/// <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; } = 1;

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

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

/// <summary>
/// The format in which the generated images are returned. Must be one of url or b64_json. Defaults to Url.
/// </summary>
[JsonProperty("response_format"), JsonConverter(typeof(ImageResponseFormat.ImageResponseJsonConverter))]
public ImageResponseFormat ResponseFormat { get; set; }

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

}

/// <summary>
/// Creates a new <see cref="ImageGenerationRequest"/> 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="size">The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024.</param>
/// <param name="user">A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.</param>
/// <param name="responseFormat">The format in which the generated images are returned. Must be one of url or b64_json.</param>
public ImageGenerationRequest(
string prompt,
int? numOfImages = 1,
ImageSize size = null,
string user = null,
ImageResponseFormat responseFormat = null)
{
this.Prompt = prompt;
this.NumOfImages = numOfImages;
this.User = user;
this.Size = size ?? ImageSize._1024;
this.ResponseFormat = responseFormat ?? ImageResponseFormat.Url;
}

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

namespace OpenAI_API.Images
{
/// <summary>
/// Represents available response formats for image generation endpoints
/// </summary>
public class ImageResponseFormat
{
private ImageResponseFormat(string value) { Value = value; }

private string Value { get; set; }

/// <summary>
/// Requests an image that is 256x256
/// </summary>
public static ImageResponseFormat Url { get { return new ImageResponseFormat("url"); } }
/// <summary>
/// Requests an image that is 512x512
/// </summary>
public static ImageResponseFormat B64_json { get { return new ImageResponseFormat("b64_json"); } }


/// <summary>
/// Gets the string value for this response format to pass to the API
/// </summary>
/// <returns>The response format as a string</returns>
public override string ToString()
{
return Value;
}

/// <summary>
/// Gets the string value for this response format to pass to the API
/// </summary>
/// <param name="value">The ImageResponseFormat to convert</param>
public static implicit operator String(ImageResponseFormat value) { return value; }

internal class ImageResponseJsonConverter : JsonConverter<ImageResponseFormat>
{
public override ImageResponseFormat ReadJson(JsonReader reader, Type objectType, ImageResponseFormat existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return new ImageResponseFormat(reader.ReadAsString());
}

public override void WriteJson(JsonWriter writer, ImageResponseFormat value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
}

}
55 changes: 55 additions & 0 deletions OpenAI_API/Images/ImageResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
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>
/// Gets the url or base64-encoded image data of the first result, or null if there are no results
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (Data?.Count > 0)
{
return Data[0].Url ?? Data[0].Base64Data;
}
else
{
return null;
}
}
}

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

public string Url { get; set; }

/// <summary>
/// The base64-encoded image data as returned by the API
/// </summary>
[JsonProperty("b64_json")]
public string Base64Data { get; set; }

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

namespace OpenAI_API.Images
{
/// <summary>
/// Represents available sizes for image generation endpoints
/// </summary>
public class ImageSize
{
private ImageSize(string value) { Value = value; }

private string Value { get; set; }

/// <summary>
/// Requests an image that is 256x256
/// </summary>
public static ImageSize _256 { get { return new ImageSize("256x256"); } }
/// <summary>
/// Requests an image that is 512x512
/// </summary>
public static ImageSize _512 { get { return new ImageSize("512x512"); } }
/// <summary>
/// Requests and image that is 1024x1024
/// </summary>
public static ImageSize _1024 { get { return new ImageSize("1024x1024"); } }

/// <summary>
/// Gets the string value for this size to pass to the API
/// </summary>
/// <returns>The size as a string</returns>
public override string ToString()
{
return Value;
}



/// <summary>
/// Gets the string value for this size to pass to the API
/// </summary>
/// <param name="value">The ImageSize to convert</param>
public static implicit operator String(ImageSize value) { return value; }

internal class ImageSizeJsonConverter : JsonConverter<ImageSize>
{
public override void WriteJson(JsonWriter writer, ImageSize value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}

public override ImageSize ReadJson(JsonReader reader, Type objectType, ImageSize existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return new ImageSize(reader.ReadAsString());
}
}
}

}
15 changes: 13 additions & 2 deletions OpenAI_API/Model/Model.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,15 +134,26 @@ public Model()
public static Model AdaTextEmbedding => new Model("text-embedding-ada-002") { OwnedBy = "openai" };

/// <summary>
///
/// Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with the latest model iteration.
/// </summary>
public static Model ChatGPTTurbo => new Model("gpt-3.5-turbo") { OwnedBy = "openai" };

/// <summary>
///
/// Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.
/// </summary>
public static Model ChatGPTTurbo0301 => new Model("gpt-3.5-turbo-0301") { OwnedBy = "openai" };

/// <summary>
/// Stable text moderation model that may provide lower accuracy compared to TextModerationLatest.
/// OpenAI states they will provide advanced notice before updating this model.
/// </summary>
public static Model TextModerationStable => new Model("text-moderation-stable") { OwnedBy = "openai" };

/// <summary>
/// The latest text moderation model. This model will be automatically upgraded over time.
/// </summary>
public static Model TextModerationLatest => new Model("text-moderation-latest") { OwnedBy = "openai" };


/// <summary>
/// Gets more details about this Model from the API, specifically properties such as <see cref="OwnedBy"/> and permissions.
Expand Down
51 changes: 51 additions & 0 deletions OpenAI_API/Moderation/ModerationEndpoint.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.Moderation
{
/// <summary>
/// This endpoint classifies text against the OpenAI Content Policy
/// </summary>
public class ModerationEndpoint : EndpointBase
{
/// <summary>
/// This allows you to send request to the recommended model without needing to specify. OpenAI recommends using the <see cref="Model.TextModerationLatest"/> model
/// </summary>
public ModerationRequest DefaultModerationRequestArgs { get; set; } = new ModerationRequest() { Model = Model.TextModerationLatest };

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

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

/// <summary>
/// Ask the API to classify the text using the default model.
/// </summary>
/// <param name="input">Text to classify</param>
/// <returns>Asynchronously returns the classification result</returns>
public async Task<ModerationResult> CallModerationAsync(string input)
{
ModerationRequest req = new ModerationRequest(DefaultModerationRequestArgs.Model, input);
return await CallModerationAsync(req);
}

/// <summary>
/// Ask the API to classify the text using a custom request.
/// </summary>
/// <param name="request">Request to send to the API</param>
/// <returns>Asynchronously returns the classification result</returns>
public async Task<ModerationResult> CallModerationAsync(ModerationRequest request)
{
return await HttpPost<ModerationResult>(postData: request);
}
}
}
Loading

0 comments on commit 9b11270

Please sign in to comment.